add some comments and quote (' + \) to dump_str
authorTero Marttila <terom@fixme.fi>
Fri, 13 Mar 2009 15:09:53 +0200
changeset 51 cc61eaa841ef
parent 50 46c3983638d3
child 52 97604efda1ce
add some comments and quote (' + \) to dump_str
src/test.c
--- a/src/test.c	Fri Mar 13 14:59:38 2009 +0200
+++ b/src/test.c	Fri Mar 13 15:09:53 2009 +0200
@@ -31,6 +31,8 @@
  * If len is given as >= 0, only the given number of chars will be dumped from str
  *
  * The buffer cycles a bit, so you pointers remain valid across DUMP_STR_COUNT calls.
+ *
+ * The resulting strings are truncated to (DUMP_STR_BUF - DUMP_STR_TAIL) bytes, not including the ending "...'\0"
  */
 const char *dump_strn (const char *str, ssize_t len)
 {
@@ -57,14 +59,31 @@
     *buf++ = '\'';
     
     // dump each char
-    for (; *str && (size_t) (buf - buf_ptr) < DUMP_STR_BUF - DUMP_STR_TAIL && (len < 0 || (size_t) (str - str_ptr) < (size_t) len); str++) {
+    for (; (
+            // ...stop on NUL
+                *str 
+
+            // ...leave DUMP_STR_TAIL bytes room at the end of buf
+            &&  (size_t) (buf - buf_ptr) < DUMP_STR_BUF - DUMP_STR_TAIL 
+            
+            // ...don't consume more than len bytes of str, unless len < 0
+            &&  (len < 0 || (size_t) (str - str_ptr) < (size_t) len)
+        ); str++
+    ) {
         if (*str == '\'') {
-            buf = dump_str_append(buf, "\\'"); break;
+            // escape quotes
+            buf = dump_str_append(buf, "\\'");
+
+        } else if (*str == '\\') {
+            // escape escapes
+            buf = dump_str_append(buf, "\\\\");
 
         } else if (isprint(*str)) {
+            // normal char
             *buf++ = *str;
 
         } else {
+            // something more special
             switch (*str) {
                 case '\r':
                     buf = dump_str_append(buf, "\\r"); break;
@@ -73,13 +92,14 @@
                     buf = dump_str_append(buf, "\\n"); break;
 
                 default:
+                    // format as "\xFF"
                     buf += snprintf(buf, (DUMP_STR_BUF - (buf - buf_ptr)), "\\x%02x", *str);
                     break;
             }
         }
     }
 
-    // quote
+    // end quote
     *buf++ = '\'';
 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