Merge branch 'print_preallocated'

This commit is contained in:
Max Bruckner
2016-11-28 23:08:25 +07:00
4 changed files with 120 additions and 32 deletions

30
cJSON.c
View File

@@ -244,6 +244,7 @@ typedef struct
char *buffer;
int length;
int offset;
cjbool noalloc;
} printbuffer;
/* realloc printbuffer if necessary to have at least "needed" bytes more */
@@ -261,6 +262,10 @@ static char* ensure(printbuffer *p, int needed)
return p->buffer + p->offset;
}
if (p->noalloc) {
return NULL;
}
newsize = pow2gt(needed);
newbuffer = (char*)cJSON_malloc(newsize);
if (!newbuffer)
@@ -883,10 +888,20 @@ char *cJSON_PrintBuffered(const cJSON *item, int prebuffer, cjbool fmt)
}
p.length = prebuffer;
p.offset = 0;
p.noalloc = false;
return print_value(item, 0, fmt, &p);
}
int cJSON_PrintPreallocated(cJSON *item,char *buf, const int len, const cjbool fmt)
{
printbuffer p;
p.buffer = buf;
p.length = len;
p.offset = 0;
p.noalloc = true;
return print_value(item,0,fmt,&p) != NULL;
}
/* Parser core - when encountering text, process appropriately. */
static const char *parse_value(cJSON *item, const char *value, const char **ep)
@@ -1138,7 +1153,10 @@ static char *print_array(const cJSON *item, int depth, cjbool fmt, printbuffer *
child = item->child;
while (child && !fail)
{
print_value(child, depth + 1, fmt, p);
if (!print_value(child, depth + 1, fmt, p))
{
return NULL;
}
p->offset = update(p);
if (child->next)
{
@@ -1435,7 +1453,10 @@ static char *print_object(const cJSON *item, int depth, cjbool fmt, printbuffer
}
/* print key */
print_string_ptr(child->string, p);
if (!print_string_ptr(child->string, p))
{
return NULL;
}
p->offset = update(p);
len = fmt ? 2 : 1;
@@ -1452,7 +1473,10 @@ static char *print_object(const cJSON *item, int depth, cjbool fmt, printbuffer
p->offset+=len;
/* print value */
print_value(child, depth, fmt, p);
if (!print_value(child, depth, fmt, p))
{
return NULL;
};
p->offset = update(p);
/* print comma if not last */