aboutsummaryrefslogtreecommitdiff
path: root/src/common/jsonapi.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/common/jsonapi.c')
-rw-r--r--src/common/jsonapi.c46
1 files changed, 41 insertions, 5 deletions
diff --git a/src/common/jsonapi.c b/src/common/jsonapi.c
index 2e86589cfd8..18cd78b86f6 100644
--- a/src/common/jsonapi.c
+++ b/src/common/jsonapi.c
@@ -135,27 +135,63 @@ IsValidJsonNumber(const char *str, int len)
/*
* makeJsonLexContextCstringLen
+ * Initialize the given JsonLexContext object, or create one
*
- * lex constructor, with or without StringInfo object for de-escaped lexemes.
+ * If a valid 'lex' pointer is given, it is initialized. This can
+ * be used for stack-allocated structs, saving overhead. If NULL is
+ * given, a new struct is allocated.
*
- * Without is better as it makes the processing faster, so only make one
- * if really required.
+ * If need_escapes is true, ->strval stores the unescaped lexemes.
+ * Unescaping is expensive, so only request it when necessary.
+ *
+ * If need_escapes is true or lex was given as NULL, then caller is
+ * responsible for freeing the returned struct, either by calling
+ * freeJsonLexContext() or (in backend environment) via memory context
+ * cleanup.
*/
JsonLexContext *
-makeJsonLexContextCstringLen(char *json, int len, int encoding, bool need_escapes)
+makeJsonLexContextCstringLen(JsonLexContext *lex, char *json,
+ int len, int encoding, bool need_escapes)
{
- JsonLexContext *lex = palloc0(sizeof(JsonLexContext));
+ if (lex == NULL)
+ {
+ lex = palloc0(sizeof(JsonLexContext));
+ lex->flags |= JSONLEX_FREE_STRUCT;
+ }
+ else
+ memset(lex, 0, sizeof(JsonLexContext));
lex->input = lex->token_terminator = lex->line_start = json;
lex->line_number = 1;
lex->input_length = len;
lex->input_encoding = encoding;
if (need_escapes)
+ {
lex->strval = makeStringInfo();
+ lex->flags |= JSONLEX_FREE_STRVAL;
+ }
+
return lex;
}
/*
+ * Free memory in a JsonLexContext. There's no need for this if a *lex
+ * pointer was given when the object was made and need_escapes was false,
+ * or (in backend environment) a memory context delete/reset is imminent.
+ */
+void
+freeJsonLexContext(JsonLexContext *lex)
+{
+ if (lex->flags & JSONLEX_FREE_STRVAL)
+ {
+ pfree(lex->strval->data);
+ pfree(lex->strval);
+ }
+ if (lex->flags & JSONLEX_FREE_STRUCT)
+ pfree(lex);
+}
+
+/*
* pg_parse_json
*
* Publicly visible entry point for the JSON parser.