static int compareStringsASCII(const char** in1, const char** in2) { const char* str1 = *in1, *str2 = *in2; int s; while(true) { char c1 = *++str1; char c2 = *++str2; /* If one string ends, the other is greater; if both end, they're equal */ if (c1 == '"') { if (c2 == '"') break; else return -1; } else if (c2 == '"') return 1; /* Handle escape sequences: */ if (c1 == '\\') c1 = ConvertJSONEscape(&str1); if (c2 == '\\') c2 = ConvertJSONEscape(&str2); /* Compare the next characters: */ s = cmp(c1, c2); if (s) return s; } /* Strings are equal, so update the positions: */ *in1 = str1 + 1; *in2 = str2 + 1; return 0; }
static const char* createStringFromJSON(const char** in, size_t *length, bool *freeWhenDone) { char* buf; char* dst; char c; /* Scan the JSON string to find its length and whether it contains escapes: */ const char* start = ++*in; unsigned escapes = 0; const char* str; for (str = start; *str != '"'; ++str) { if (*str == '\\') { ++str; if (*str == 'u') { escapes += 5; /* \uxxxx adds 5 bytes */ str += 4; } else escapes += 1; } } *in = str + 1; *length = str - start; *freeWhenDone = false; if (escapes > 0) { *length -= escapes; buf = malloc(*length); dst = buf; for (str = start; (c = *str) != '"'; ++str) { if (c == '\\') c = ConvertJSONEscape(&str); *dst++ = c; } cb_assert(dst - buf == (int)*length); start = buf; *freeWhenDone = true; } return start; }
static void testEscape(const char* source, char decoded) { const char* pos = source; assert_eq(ConvertJSONEscape(&pos), decoded); assert_eq((size_t)pos, (size_t)(source + strlen(source) - 1)); }