Added a test that adds a string with a backslash in it

This commit is contained in:
Benoît Blanchon
2014-06-25 13:55:18 +02:00
parent 45dfdbd5e4
commit 6b61617133
2 changed files with 31 additions and 6 deletions

View File

@ -37,6 +37,13 @@ namespace JsonGeneratorTests
AssertJsonIs("[\"\\\"\"]");
}
TEST_METHOD(AddOneStringContainingBackslash)
{
arr.add("\\");
AssertJsonIs("[\"\\\\\"]");
}
TEST_METHOD(AddTwoStrings)
{
arr.add("hello");

View File

@ -5,7 +5,7 @@ void StringBuilder::append(const char* s)
{
char* tail = buffer + length;
strcpy(tail, s);
strncpy(tail, s, capacity - length);
length += strlen(tail);
}
@ -16,17 +16,35 @@ void StringBuilder::appendEscaped(const char* s)
buffer[length++] = '"';
while (*s && length<capacity-2)
{
if (*s == '"')
buffer[length++] = '\\';
// keep one slot for the end quote
capacity--;
while (*s && length<capacity)
{
switch (*s)
{
case '"':
append("\\\"");
break;
case '\\':
append("\\\\");
break;
default:
buffer[length++] = *s;
break;
}
s++;
}
buffer[length++] = '"';
buffer[length] = 0;
// restore the original capacity
capacity++;
}
void StringBuilder::appendFormatted(const char* format, ...)