/* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* json.c: Encoding and decoding JSON.
*
* Follows this standard: https://tools.ietf.org/html/rfc7159.html
*/
#define USING_FLOAT_STUFF
#include "vim.h"
#if defined(FEAT_EVAL) || defined(PROTO)
static int json_encode_item(garray_T *gap, typval_T *val, int copyID, int options);
/*
* Encode "val" into a JSON format string.
* The result is added to "gap"
* Returns FAIL on failure and makes gap->ga_data empty.
*/
static int
json_encode_gap(garray_T *gap, typval_T *val, int options)
{
if (json_encode_item(gap, val, get_copyID(), options) == FAIL)
{
ga_clear(gap);
gap->ga_data = vim_strsave((char_u *)"");
return FAIL;
}
return OK;
}
/*
* Encode "val" into a JSON format string.
* The result is in allocated memory.
* The result is empty when encoding fails.
* "options" can contain JSON_JS, JSON_NO_NONE and JSON_NL.
*/
char_u *
json_encode(typval_T *val, int options)
{
garray_T ga;
// Store bytes in the growarray.
ga_init2(&ga, 1, 4000);
json_encode_gap(&ga, val, options);
ga_append(&ga, NUL);
return ga.ga_data;
}
#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
/*
* Encode ["nr", "val"] into a JSON format string in allocated memory.
* "options" can contain JSON_JS, JSON_NO_NONE and JSON_NL.
* Returns NULL when out of memory.
*/
char_u *
json_encode_nr_expr(int nr, typval_T *val, int options)
{
typval_T listtv;
typval_T nrtv;
garray_T ga;
nrtv.v_type = VAR_NUMBER;
nrtv.vval.v_number = nr;
if (rettv_list_alloc(&listtv) == FAIL)
return NULL;
if (list_append_tv(listtv.vval.v_list, &nrtv) == FAIL
|| list_append_tv(listtv.vval.v_list, val) == FAIL)
{
list_unref(listtv.vval.v_list);
return NULL;
}
ga_init2(&ga, 1, 4000);
if (json_encode_gap(&ga, &listtv, options) == OK && (options & JSON_NL))
ga_append(&ga, '\n');
list_unref(listtv.vval.v_list);
ga_append(&ga, NUL);
return ga.ga_data;
}
/*
* Encode "val" into a JSON format string prefixed by the LSP HTTP header.
* Returns NULL when out of memory.
*/
char_u *
json_encode_lsp_msg(typval_T *val)
{
garray_T ga;
garray_T lspga;
ga_init2(&ga, 1,