use crate::emit::{self, EscapeMode};
#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct WriteOptions {
pub indent: Vec<u8>,
pub space: Vec<u8>,
pub space_before: Vec<u8>,
pub object_nl: Vec<u8>,
pub array_nl: Vec<u8>,
pub escape: EscapeMode,
pub float: FloatFormat,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FloatFormat {
#[default]
Fpconv,
#[cfg(feature = "shortest-floats")]
#[cfg_attr(docsrs, doc(cfg(feature = "shortest-floats")))]
Shortest,
}
impl WriteOptions {
pub const COMPACT: WriteOptions = WriteOptions {
indent: Vec::new(),
space: Vec::new(),
space_before: Vec::new(),
object_nl: Vec::new(),
array_nl: Vec::new(),
escape: EscapeMode::Standard,
float: FloatFormat::Fpconv,
};
#[must_use]
pub fn pretty() -> WriteOptions {
WriteOptions {
indent: b" ".to_vec(),
space: b" ".to_vec(),
space_before: Vec::new(),
object_nl: b"\n".to_vec(),
array_nl: b"\n".to_vec(),
escape: EscapeMode::Standard,
float: FloatFormat::Fpconv,
}
}
fn is_compact_layout(&self) -> bool {
self.indent.is_empty()
&& self.space.is_empty()
&& self.space_before.is_empty()
&& self.object_nl.is_empty()
&& self.array_nl.is_empty()
}
}
#[doc(alias = "serialize")]
#[doc(alias = "stringify")]
#[doc(alias = "generate")]
pub struct Writer<'a> {
out: &'a mut Vec<u8>,
cfg: &'a WriteOptions,
compact: bool,
depth: usize,
first: bool,
after_key: bool,
}
impl std::fmt::Debug for Writer<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Writer")
.field("depth", &self.depth)
.field("first", &self.first)
.field("after_key", &self.after_key)
.field("compact", &self.compact)
.field("written", &self.out.len())
.finish_non_exhaustive()
}
}
static COMPACT: WriteOptions = WriteOptions::COMPACT;
impl<'a> Writer<'a> {
#[must_use]
pub fn new(out: &'a mut Vec<u8>, cfg: &'a WriteOptions) -> Writer<'a> {
Writer {
compact: cfg.is_compact_layout(),
out,
cfg,
depth: 0,
first: true,
after_key: false,
}
}
#[must_use]
pub fn compact(out: &'a mut Vec<u8>) -> Writer<'a> {
Writer::new(out, &COMPACT)
}
#[must_use]
pub fn depth(&self) -> usize {
self.depth
}
#[must_use]
pub fn buffer(&mut self) -> &mut Vec<u8> {
self.out
}
#[inline(always)]
fn push_indent(&mut self) {
for _ in 0..self.depth {
self.out.extend_from_slice(&self.cfg.indent);
}
}
#[inline(always)]
fn value_prefix(&mut self) {
if self.after_key {
self.after_key = false;
return;
}
if self.depth > 0 {
if !self.first {
self.out.push(b',');
}
if !self.compact {
self.out.extend_from_slice(&self.cfg.array_nl);
self.push_indent();
}
}
self.first = false;
}
#[inline]
pub fn null(&mut self) {
self.value_prefix();
self.out.extend_from_slice(b"null");
}
#[inline]
pub fn boolean(&mut self, value: bool) {
self.value_prefix();
self.out
.extend_from_slice(if value { b"true" } else { b"false" });
}
#[inline]
pub fn int(&mut self, value: i64) {
self.value_prefix();
emit::write_i64(self.out, value);
}
#[inline]
pub fn float(&mut self, value: f64) {
assert!(
value.is_finite(),
"Writer::float requires a finite value; encode a non-finite \
policy via Writer::value_raw"
);
self.value_prefix();
match self.cfg.float {
FloatFormat::Fpconv => emit::write_f64(self.out, value),
#[cfg(feature = "shortest-floats")]
FloatFormat::Shortest => {
let mut buf = zmij::Buffer::new();
self.out
.extend_from_slice(buf.format_finite(value).as_bytes());
}
}
}
#[inline]
pub fn str(&mut self, value: &str) {
self.value_prefix();
self.write_quoted(value.as_bytes());
}
#[inline]
pub unsafe fn str_utf8_unchecked(&mut self, value: &[u8]) {
self.value_prefix();
self.write_quoted(value);
}
#[inline]
pub fn value_raw(&mut self, bytes: &[u8]) {
self.value_prefix();
self.out.extend_from_slice(bytes);
}
#[inline]
pub fn key(&mut self, key: &str) {
self.key_prefix();
self.write_quoted(key.as_bytes());
self.key_suffix();
}
#[inline]
pub unsafe fn key_utf8_unchecked(&mut self, key: &[u8]) {
self.key_prefix();
self.write_quoted(key);
self.key_suffix();
}
#[inline(always)]
fn key_prefix(&mut self) {
if !self.first {
self.out.push(b',');
}
if !self.compact {
self.out.extend_from_slice(&self.cfg.object_nl);
self.push_indent();
}
self.first = false;
}
#[inline(always)]
fn key_suffix(&mut self) {
if !self.compact {
self.out.extend_from_slice(&self.cfg.space_before);
}
self.out.push(b':');
if !self.compact {
self.out.extend_from_slice(&self.cfg.space);
}
self.after_key = true;
}
#[inline]
pub fn begin_array(&mut self) {
self.value_prefix();
self.out.push(b'[');
self.depth += 1;
self.first = true;
}
#[inline]
pub fn end_array(&mut self) {
self.end_container(b']');
}
#[inline]
pub fn begin_object(&mut self) {
self.value_prefix();
self.out.push(b'{');
self.depth += 1;
self.first = true;
}
#[inline]
pub fn end_object(&mut self) {
self.end_container(b'}');
}
#[inline(always)]
fn end_container(&mut self, closer: u8) {
self.depth = self.depth.saturating_sub(1);
let nl = if closer == b']' {
&self.cfg.array_nl
} else {
&self.cfg.object_nl
};
if !self.first && !self.compact && !nl.is_empty() {
self.out.extend_from_slice(nl);
self.push_indent();
}
self.out.push(closer);
self.first = false;
}
#[inline(always)]
fn write_quoted(&mut self, bytes: &[u8]) {
self.out.reserve(bytes.len() + 2);
self.out.push(b'"');
emit::escape_into(self.out, bytes, self.cfg.escape);
self.out.push(b'"');
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escape_modes_flow_through_write_options() {
let bs = char::from(0x5C);
let html = format!("{bs}u003cp{bs}u003e A {bs}u0026 B");
let sep = format!("{bs}u2028");
let cases = [
(EscapeMode::HtmlSafe, format!("[\"{html} {sep}\"]")),
(EscapeMode::HtmlEntities, format!("[\"{html} \u{2028}\"]")),
(EscapeMode::JsSeparators, format!("[\"<p> A & B {sep}\"]")),
(EscapeMode::Standard, "[\"<p> A & B \u{2028}\"]".to_string()),
];
for (mode, expected) in cases {
let cfg = WriteOptions {
escape: mode,
..Default::default()
};
let mut out = Vec::new();
let mut w = Writer::new(&mut out, &cfg);
w.begin_array();
w.str("<p> A & B \u{2028}");
w.end_array();
assert_eq!(std::str::from_utf8(&out).unwrap(), expected, "{mode:?}");
}
}
#[test]
#[should_panic(expected = "finite")]
fn float_rejects_nan() {
let mut out = Vec::new();
Writer::compact(&mut out).float(f64::NAN);
}
#[test]
#[should_panic(expected = "finite")]
fn float_rejects_infinity() {
let mut out = Vec::new();
Writer::compact(&mut out).float(f64::INFINITY);
}
#[test]
#[should_panic(expected = "finite")]
fn float_rejects_neg_infinity() {
let mut out = Vec::new();
Writer::compact(&mut out).float(f64::NEG_INFINITY);
}
#[test]
fn root_closers_saturate() {
let mut out = Vec::new();
{
let mut w = Writer::compact(&mut out);
w.end_array();
w.end_object();
w.int(1);
}
assert_eq!(out, b"]}1");
let mut out = Vec::new();
{
let pretty = WriteOptions::pretty();
let mut w = Writer::new(&mut out, &pretty);
w.end_object();
w.begin_array();
w.int(1);
w.end_array();
}
assert_eq!(String::from_utf8(out).unwrap(), "}[\n 1\n]");
}
fn doc(cfg: &WriteOptions, f: impl FnOnce(&mut Writer)) -> String {
let mut out = Vec::new();
let mut w = Writer::new(&mut out, cfg);
f(&mut w);
assert_eq!(w.depth(), 0, "unbalanced containers in test doc");
String::from_utf8(out).unwrap()
}
fn sample(w: &mut Writer) {
w.begin_object();
w.key("a");
w.begin_array();
w.int(1);
w.begin_object();
w.key("x");
w.int(2);
w.end_object();
w.str("s");
w.end_array();
w.key("e");
w.begin_object();
w.end_object();
w.key("ea");
w.begin_array();
w.end_array();
w.key("n");
w.null();
w.end_object();
}
#[test]
fn compact() {
assert_eq!(
doc(&WriteOptions::COMPACT, sample),
r#"{"a":[1,{"x":2},"s"],"e":{},"ea":[],"n":null}"#
);
}
#[test]
fn pretty() {
let expected = "{\n \"a\": [\n 1,\n {\n \"x\": 2\n },\n \"s\"\n ],\n \"e\": {},\n \"ea\": [],\n \"n\": null\n}";
assert_eq!(doc(&WriteOptions::pretty(), sample), expected);
}
#[test]
fn custom_layout_partial_newlines() {
let cfg = WriteOptions {
indent: b"..".to_vec(),
object_nl: b"|".to_vec(),
..WriteOptions::default()
};
assert_eq!(
doc(&cfg, sample),
"{|..\"a\":[....1,....{|......\"x\":2|....},....\"s\"],|..\"e\":{},|..\"ea\":[],|..\"n\":null|}"
);
}
#[test]
fn root_scalars_and_raw() {
assert_eq!(doc(&WriteOptions::COMPACT, |w| w.str("top")), "\"top\"");
#[allow(clippy::redundant_closure_for_method_calls)]
let null = |w: &mut Writer| w.null();
assert_eq!(doc(&WriteOptions::COMPACT, null), "null");
assert_eq!(doc(&WriteOptions::COMPACT, |w| w.float(1.5)), "1.5");
assert_eq!(
doc(&WriteOptions::COMPACT, |w| {
w.begin_array();
w.value_raw(b"1208925819614629174706176");
w.value_raw(b"NaN");
w.end_array();
}),
"[1208925819614629174706176,NaN]"
);
}
#[test]
fn escape_modes() {
let script_safe = WriteOptions {
escape: EscapeMode::ScriptSafe,
..WriteOptions::default()
};
assert_eq!(
doc(&script_safe, |w| w.str("a/b\u{2028}")),
"\"a\\/b\\u2028\""
);
let ascii = WriteOptions {
escape: EscapeMode::AsciiOnly,
..WriteOptions::default()
};
assert_eq!(doc(&ascii, |w| w.str("héllo")), "\"h\\u00e9llo\"");
}
#[test]
fn pretty_root_scalar_has_no_layout() {
assert_eq!(doc(&WriteOptions::pretty(), |w| w.int(42)), "42");
}
#[test]
fn appends_after_existing_content() {
let mut out = b"data: ".to_vec();
let cfg = WriteOptions::COMPACT;
let mut w = Writer::new(&mut out, &cfg);
w.begin_array();
w.int(1);
w.end_array();
assert_eq!(out, b"data: [1]");
}
}