Growing string instead of static buffer

This commit is contained in:
Eric Fischer
2014-02-05 16:39:50 -08:00
parent 2a7fa98a3a
commit b0103ea458
+38 -13
View File
@@ -68,6 +68,33 @@ int peek(FILE *f) {
return c; return c;
} }
struct string {
char *buf;
int n;
int nalloc;
};
static void string_init(struct string *s) {
s->nalloc = 500;
s->buf = malloc(s->nalloc);
s->n = 0;
s->buf[0] = '\0';
}
static void string_append(struct string *s, char c) {
if (s->n + 2 >= s->nalloc) {
s->nalloc += 500;
s->buf = realloc(s->buf, s->nalloc);
}
s->buf[s->n++] = c;
s->buf[s->n] = '\0';
}
static void string_free(struct string *s) {
free(s->buf);
}
json_object *parse(FILE *f, json_object *current) { json_object *parse(FILE *f, json_object *current) {
int c = getc(f); int c = getc(f);
if (c == EOF) { if (c == EOF) {
@@ -147,51 +174,49 @@ json_object *parse(FILE *f, json_object *current) {
} }
if (c == '-' || (c >= '0' && c <= '9')) { if (c == '-' || (c >= '0' && c <= '9')) {
#define MAX 500 struct string val;
char val[MAX]; string_init(&val);
int off = 0;
val[off++] = c; string_append(&val, c);
if (c >= '1' && c <= '9') { if (c >= '1' && c <= '9') {
c = peek(f); c = peek(f);
while (c >= '0' && c <= '9') { while (c >= '0' && c <= '9') {
val[off++] = getc(f); string_append(&val, getc(f));
c = peek(f); c = peek(f);
} }
} }
if (peek(f) == '.') { if (peek(f) == '.') {
val[off++] = getc(f); string_append(&val, getc(f));
c = peek(f); c = peek(f);
while (c >= '0' && c <= '9') { while (c >= '0' && c <= '9') {
val[off++] = getc(f); string_append(&val, getc(f));
c = peek(f); c = peek(f);
} }
} }
c = peek(f); c = peek(f);
if (c == 'e' || c == 'E') { if (c == 'e' || c == 'E') {
val[off++] = getc(f); string_append(&val, getc(f));
c = peek(f); c = peek(f);
if (c == '+' || c == '-') { if (c == '+' || c == '-') {
val[off++] = getc(f); string_append(&val, getc(f));
} }
c = peek(f); c = peek(f);
while (c >= '0' && c <= '9') { while (c >= '0' && c <= '9') {
val[off++] = getc(f); string_append(&val, getc(f));
c = peek(f); c = peek(f);
} }
} }
val[off++] = '\0';
json_object *n = add_object(JSON_NUMBER, current); json_object *n = add_object(JSON_NUMBER, current);
n->number = atof(val); n->number = atof(val.buf);
string_free(&val);
return n; return n;
} }