lloyd / yajl

A fast streaming JSON parsing library in C.
http://lloyd.github.com/yajl
ISC License
2.15k stars 435 forks source link

changing callback routines mid-parse #156

Open mewalig opened 9 years ago

mewalig commented 9 years ago

It would be useful to me to be able to change callback routines mid-parse. To do that I made the following code changes which seem to work properly. I thought I'd share in case it looks useful to others or as a library improvement. Below is the git diff output:

diff --git a/src/api/yajl_parse.h b/src/api/yajl_parse.h
index 1c25a60..1c6802f 100644
--- a/src/api/yajl_parse.h
+++ b/src/api/yajl_parse.h
@@ -108,2 +108,2 @@ extern "C" {
                                     yajl_alloc_funcs * afs,
                                     void * ctx);

+    /** swap parser callback routines. returns the old callback structure
+     *  \param hand - a handle to the json parser allocated with yajl_alloc
+     *  \param callbacks  a yajl callbacks structure specifying the
+     *                    functions to call when different JSON entities
+     *                    are encountered in the input text.
+     */
+    YAJL_API const yajl_callbacks * yajl_swap_callbacks(yajl_handle handle,
+                                                        const yajl_callbacks * callbacks);
+
+

     /** configuration parameters for the parser, these may be passed to
      *  yajl_config() along with option specific argument(s).  In general,
diff --git a/src/yajl.c b/src/yajl.c
index d477893..72fdc2b 100644
--- a/src/yajl.c
+++ b/src/yajl.c
@@ -42,2 +42,2 @@ yajl_status_to_string(yajl_status stat)
     return statStr;
 }

+
 yajl_handle
 yajl_alloc(const yajl_callbacks * callbacks,
            yajl_alloc_funcs * afs,
@@ -78,2 +79,2 @@ yajl_alloc(const yajl_callbacks * callbacks,
     return hand;
 }

+const yajl_callbacks *
+yajl_swap_callbacks(yajl_handle h, const yajl_callbacks * callbacks) {
+  const yajl_callbacks *old_callbacks = h->callbacks;
+  h->callbacks = callbacks;
+  return old_callbacks;
+}
+
 int
 yajl_config(yajl_handle h, yajl_option opt, ...)
 {