aboutsummaryrefslogtreecommitdiff
path: root/sprinter-json.c
diff options
context:
space:
mode:
authorAustin Clements <amdragon@MIT.EDU>2012-08-02 21:14:49 -0400
committerDavid Bremner <bremner@debian.org>2012-08-03 20:21:29 -0300
commit14883b07003b9ed4223cd8f2c03b301fddae07bd (patch)
tree216ab7263c82a84aff4a03aa1ce759148cc07080 /sprinter-json.c
parent624d1897ce70fde8a41f2ea245db2a5e27f16ce1 (diff)
sprinter: Add a string_len method
This method allows callers to output strings with specific lengths. It's useful both for strings with embedded NULs (which JSON can represent, though parser support is apparently spotty), and non-terminated strings.
Diffstat (limited to 'sprinter-json.c')
-rw-r--r--sprinter-json.c16
1 files changed, 14 insertions, 2 deletions
diff --git a/sprinter-json.c b/sprinter-json.c
index 4649655..c9b6835 100644
--- a/sprinter-json.c
+++ b/sprinter-json.c
@@ -88,8 +88,13 @@ json_end (struct sprinter *sp)
fputc ('\n', spj->stream);
}
+/* This implementation supports embedded NULs as allowed by the JSON
+ * specification and Unicode. Support for *parsing* embedded NULs
+ * varies, but is generally not a problem outside of C-based parsers
+ * (Python's json module and Emacs' json.el take embedded NULs in
+ * stride). */
static void
-json_string (struct sprinter *sp, const char *val)
+json_string_len (struct sprinter *sp, const char *val, size_t len)
{
static const char *const escapes[] = {
['\"'] = "\\\"", ['\\'] = "\\\\", ['\b'] = "\\b",
@@ -98,7 +103,7 @@ json_string (struct sprinter *sp, const char *val)
struct sprinter_json *spj = json_begin_value (sp);
fputc ('"', spj->stream);
- for (; *val; ++val) {
+ for (; len; ++val, --len) {
unsigned char ch = *val;
if (ch < ARRAY_SIZE (escapes) && escapes[ch])
fputs (escapes[ch], spj->stream);
@@ -111,6 +116,12 @@ json_string (struct sprinter *sp, const char *val)
}
static void
+json_string (struct sprinter *sp, const char *val)
+{
+ json_string_len (sp, val, strlen (val));
+}
+
+static void
json_integer (struct sprinter *sp, int val)
{
struct sprinter_json *spj = json_begin_value (sp);
@@ -166,6 +177,7 @@ sprinter_json_create (const void *ctx, FILE *stream)
.begin_list = json_begin_list,
.end = json_end,
.string = json_string,
+ .string_len = json_string_len,
.integer = json_integer,
.boolean = json_boolean,
.null = json_null,