Files
ArduinoJson/JsonGeneratorTests/StringBuilder.cpp

100 lines
1.6 KiB
C++
Raw Normal View History

2014-06-26 12:50:48 +02:00
/*
* Arduino JSON library
* Benoit Blanchon 2014 - MIT License
*/
#include <cstdio>
#include <cstring>
2014-06-25 13:02:39 +02:00
#include "StringBuilder.h"
void StringBuilder::append(double value)
{
char* tail = buffer + length;
_snprintf(tail, capacity - length, "%lg", value);
length += strlen(tail);
}
2014-06-25 13:02:39 +02:00
2014-06-25 13:50:28 +02:00
void StringBuilder::append(const char* s)
2014-06-25 13:02:39 +02:00
{
2014-06-26 13:14:09 +02:00
if (!s)
{
return append("null");
}
2014-06-25 13:02:39 +02:00
char* tail = buffer + length;
while (*s && length<capacity)
{
buffer[length++] = *s++;
}
2014-06-25 13:02:39 +02:00
buffer[length] = 0;
}
void StringBuilder::appendEscaped(const char* s)
{
2014-06-26 13:16:22 +02:00
if (!s)
{
return append("null");
}
2014-06-26 13:14:09 +02:00
if (length > capacity - 2)
{
// not enough from for quotes
return;
}
buffer[length++] = '"';
// keep one slot for the end quote
capacity--;
while (*s && length < capacity)
{
switch (*s)
{
case '"':
append("\\\"");
break;
case '\\':
append("\\\\");
break;
2014-06-26 13:10:52 +02:00
case '\b':
append("\\b");
break;
case '\f':
append("\\f");
break;
case '\n':
append("\\n");
break;
case '\r':
append("\\r");
break;
case '\t':
append("\\t");
break;
2014-06-26 12:50:48 +02:00
default:
buffer[length++] = *s;
break;
}
s++;
}
buffer[length++] = '"';
buffer[length] = 0;
// restore the original capacity
capacity++;
2014-06-25 13:02:39 +02:00
}