The major difference between this function and the internal cjson json_encode function is that we don't use the config object created by cjson. Instead we initialize and create a default config here to avoid passing the config as a user data object. Also, we return the generated string, and let the caller delete it
| 973 | // a user data object. |
| 974 | // Also, we return the generated string, and let the caller delete it |
| 975 | int lua_cjson_encode(lua_State *l, int index, int options_index, |
| 976 | char** json_str, size_t* json_length) |
| 977 | { |
| 978 | json_config_t cfg; |
| 979 | strbuf_t local_encode_buf; |
| 980 | strbuf_t *encode_buf; |
| 981 | |
| 982 | json_initialize_config(l, options_index, &cfg, DEFAULT_ENCODE_KEEP_BUFFER, 1, 0, 0); |
| 983 | if (!cfg.encode_keep_buffer) { |
| 984 | /* Use private buffer */ |
| 985 | encode_buf = &local_encode_buf; |
| 986 | strbuf_init(encode_buf, 0); |
| 987 | } else { |
| 988 | /* Reuse existing buffer */ |
| 989 | encode_buf = &cfg.encode_buf; |
| 990 | strbuf_reset(encode_buf); |
| 991 | } |
| 992 | |
| 993 | lua_pushvalue(l, index); // make sure the value to encode is on top of the stack |
| 994 | json_append_data(l, &cfg, 0, encode_buf); |
| 995 | lua_pop(l, 1); // pop it again |
| 996 | |
| 997 | // DEFOLD: We store away the values |
| 998 | int len; |
| 999 | *json_str = strbuf_string(encode_buf, &len); |
| 1000 | *json_length = (size_t)len; |
| 1001 | |
| 1002 | strbuf_ensure_null(encode_buf); |
| 1003 | |
| 1004 | // DEFOLD: The caller will have to free this buffer |
| 1005 | encode_buf->buf = 0; |
| 1006 | |
| 1007 | if (!cfg.encode_keep_buffer) |
| 1008 | strbuf_free(encode_buf); |
| 1009 | |
| 1010 | return 1; |
| 1011 | } |
| 1012 | |
| 1013 | // END DEFOLD |
| 1014 |
no test coverage detected