ddn.var.toJSON, ddn.data.json5.toJSON5JSON/JSON5 String Escaping Utilities
This module provides efficient, allocation-aware routines for escaping strings according to JSON and JSON5 specifications. It is used internally by ddn.var and ddn.data.json5 to produce correctly escaped string literals during serialization.
Features:
\b, \f, \n, \r, \t.\uXXXX) for control characters and, optionally, all non-ASCII code points.asciiOnly is enabled.@safe implementations suitable for use in memory-safe D code.Example:
import ddn.util.json_escape;
import std.array : appender;
// Escape a string (without surrounding quotes)
assert(escapeJSONString("hello\nworld") == "hello\\nworld");
// Write a quoted JSON string directly to an output buffer
auto buf = appender!string();
writeJSONString("say \"hi\"", buf);
assert(buf.data == `"say \"hi\""`);ddn.var.toJSON, ddn.data.json5.toJSON5void writeUnicodeEscape(Sink)(ref Sink sink, ushort v) if (is(typeof(sink.put("test"))) || is(typeof(sink.put('c')))) @safeWrite a `\uXXXX` escape sequence for a 16-bit value.void writeCodePointEscaped(Sink)(ref Sink sink, dchar dc) if (is(typeof(sink.put("test"))) || is(typeof(sink.put('c')))) @safeWrite a Unicode code point as escaped JSON.void escapeToSink(Sink)(scope const(char)[] s, ref Sink sink, const char quote, const bool asciiOnly) if (is(typeof(sink.put("test"))) || is(typeof(sink.put('c')))) @safeEscape the contents of a UTF-8 string and write to a sink.dchar tryDecodeUTF8(scope const(char)[] s, size_t pos, out size_t bytesConsumed) @safeAttempt to decode a UTF-8 code point from the string at position `pos`.string escapeJSONString(const string s, const char quote = '"', const bool asciiOnly = false) @safeEscape a UTF-8 string for inclusion in a JSON/JSON5 string literal.void writeJSONString(Sink)(scope const(char)[] s, ref Sink sink, const bool asciiOnly = false, const char quote = '"') if (is(typeof(sink.put("test"))) || is(typeof(sink.put('c')))) @safeWrite a JSON/JSON5 string literal (including surrounding quotes) to `sink`.HEX = "0123456789ABCDEF"Hex digits for escape sequence encoding.