Merge branch '1.0'
[jansson.git] / src / load.c
index 975d7e9..1e2ad2a 100644 (file)
@@ -1,3 +1,10 @@
+/*
+ * Copyright (c) 2009 Petri Lehtinen <petri@digip.org>
+ *
+ * Jansson is free software; you can redistribute it and/or modify
+ * it under the terms of the MIT license. See LICENSE for details.
+ */
+
 #define _GNU_SOURCE
 #include <ctype.h>
 #include <errno.h>
@@ -537,6 +544,17 @@ out:
     return lex->token;
 }
 
+static char *lex_steal_string(lex_t *lex)
+{
+    char *result = NULL;
+    if(lex->token == TOKEN_STRING)
+    {
+        result = lex->value.string;
+        lex->value.string = NULL;
+    }
+    return result;
+}
+
 static int lex_init(lex_t *lex, get_func get, eof_func eof, void *data)
 {
     stream_init(&lex->stream, get, eof, data);
@@ -580,7 +598,7 @@ static json_t *parse_object(lex_t *lex, json_error_t *error)
             goto error;
         }
 
-        key = strdup(lex->value.string);
+        key = lex_steal_string(lex);
         if(!key)
             return NULL;
 
@@ -734,25 +752,6 @@ json_t *parse_json(lex_t *lex, json_error_t *error)
     return parse_value(lex, error);
 }
 
-json_t *json_load(const char *path, json_error_t *error)
-{
-    json_t *result;
-    FILE *fp;
-
-    fp = fopen(path, "r");
-    if(!fp)
-    {
-        error_set(error, NULL, "unable to open %s: %s",
-                  path, strerror(errno));
-        return NULL;
-    }
-
-    result = json_loadf(fp, error);
-
-    fclose(fp);
-    return result;
-}
-
 typedef struct
 {
     const char *data;
@@ -817,7 +816,36 @@ json_t *json_loadf(FILE *input, json_error_t *error)
         return NULL;
 
     result = parse_json(&lex, error);
+    if(!result)
+        goto out;
+
+    lex_scan(&lex, error);
+    if(lex.token != TOKEN_EOF) {
+        error_set(error, &lex, "end of file expected");
+        json_decref(result);
+        result = NULL;
+    }
 
+out:
     lex_close(&lex);
     return result;
 }
+
+json_t *json_load_file(const char *path, json_error_t *error)
+{
+    json_t *result;
+    FILE *fp;
+
+    fp = fopen(path, "r");
+    if(!fp)
+    {
+        error_set(error, NULL, "unable to open %s: %s",
+                  path, strerror(errno));
+        return NULL;
+    }
+
+    result = json_loadf(fp, error);
+
+    fclose(fp);
+    return result;
+}