use crate::args::{Arg, Args, Count, MAX_SCALAR_LEN};
use crate::error::Error;
use crate::hash::FastMap;
use crate::json::{Event, Reader, number_to_js_string};
use crate::key::{Key, PathMap, PathMapExt, Probe};
use crate::plural::{Plural, Shape};
use std::sync::Arc;
pub(crate) trait Params {
fn put(&self, name: &str, out: &mut String) -> bool;
fn len_of(&self, name: &str) -> Option<usize>;
fn max_len(&self) -> usize;
}
impl Params for Args<'_> {
fn put(&self, name: &str, out: &mut String) -> bool {
match self.find(name) {
Some(v) => {
v.with(|v| v.write(out));
true
}
None => false,
}
}
fn len_of(&self, name: &str) -> Option<usize> {
self.find(name).map(|v| v.with(Arg::len))
}
fn max_len(&self) -> usize {
self.max_value_len()
}
}
pub(crate) struct WithCount<'x, 'a> {
pub(crate) args: Option<&'x Args<'a>>,
pub(crate) count: Count,
}
impl Params for WithCount<'_, '_> {
fn put(&self, name: &str, out: &mut String) -> bool {
if name == "count" {
self.count.write(out);
return true;
}
match self.args.and_then(|a| a.spread(name)) {
Some(v) => {
v.with(|v| v.write(out));
true
}
None => false,
}
}
fn len_of(&self, name: &str) -> Option<usize> {
if name == "count" {
return Some(self.count.len());
}
self.args
.and_then(|a| a.spread(name))
.map(|v| v.with(Arg::len))
}
fn max_len(&self) -> usize {
self.args.map_or(0, Args::max_value_len).max(MAX_SCALAR_LEN)
}
}
#[derive(Debug, Clone)]
pub(crate) struct Template {
pub(crate) raw: &'static str,
holes: Box<[(u32, u32)]>,
}
#[derive(Debug, Clone)]
pub(crate) enum Msg {
Text(Template),
Plural(Box<PluralMsg>),
}
impl Msg {
pub(crate) fn new(s: &str) -> Msg {
if s.contains('|') {
Msg::Plural(Box::new(PluralMsg::new(s)))
} else {
Msg::Text(Template::new(s))
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct PluralMsg {
pub(crate) text: Template,
marked: bool,
forms: Box<[Form]>,
holes: Box<[(u32, u32)]>,
shape: Shape,
}
#[derive(Debug, Clone, Copy)]
struct Form {
start: u32,
end: u32,
holes_end: u32,
}
pub(crate) type FormRange<'a> = (usize, usize, &'a [(u32, u32)]);
const ZERO_MARKER: &str = "=0 ";
impl PluralMsg {
fn new(raw: &str) -> PluralMsg {
let marked = raw.starts_with(ZERO_MARKER);
let skip = if marked { ZERO_MARKER.len() } else { 0 };
let body = raw.get(skip..).unwrap_or("");
let mut forms = Vec::with_capacity(body.matches('|').count() + 1);
let mut holes = Vec::new();
let mut at = skip;
for f in body.split('|') {
let t = f.trim_matches(is_js_space);
let start = at + (t.as_ptr() as usize - f.as_ptr() as usize);
holes.extend(Holes::new(t).map(|(s, e)| ((start + s) as u32, (start + e) as u32)));
forms.push(Form {
start: start as u32,
end: (start + t.len()) as u32,
holes_end: holes.len() as u32,
});
at += f.len() + 1;
}
PluralMsg {
text: Template::new(raw),
marked,
forms: forms.into_boxed_slice(),
holes: holes.into_boxed_slice(),
shape: Shape::new(body.split('|')),
}
}
pub(crate) fn pick(
&self,
count: Count,
plural: Option<&Plural>,
params: &impl Params,
) -> String {
let Some((start, end, holes)) = self.form(count, plural) else {
return String::new();
};
render(
self.text.raw,
start,
end,
holes.iter().map(|&(s, e)| (s as usize, e as usize)),
holes.len(),
params,
)
}
#[inline]
pub(crate) fn form(&self, count: Count, plural: Option<&Plural>) -> Option<FormRange<'_>> {
let at = self.shape.index(self.marked, count.whole(), plural);
let f = self.forms.get(at)?;
let first = at
.checked_sub(1)
.and_then(|j| self.forms.get(j))
.map_or(0, |p| p.holes_end as usize);
let holes = self.holes.get(first..f.holes_end as usize).unwrap_or(&[]);
Some((f.start as usize, f.end as usize, holes))
}
}
#[derive(Debug, Clone)]
pub(crate) enum Entry {
Msg(Msg),
Value(&'static str),
Node,
}
impl Entry {
pub(crate) fn text(&self) -> Option<&'static str> {
match self {
Entry::Msg(Msg::Text(t)) => Some(t.raw),
Entry::Msg(Msg::Plural(p)) => Some(p.text.raw),
Entry::Value(v) => Some(v),
Entry::Node => None,
}
}
}
pub(crate) fn is_js_space(c: char) -> bool {
matches!(
c,
'\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'
..='\u{200a}'
| '\u{2028}'
| '\u{2029}'
| '\u{202f}'
| '\u{205f}'
| '\u{3000}'
| '\u{feff}'
)
}
#[derive(Clone)]
struct Holes<'a> {
chars: std::str::CharIndices<'a>,
open: Option<usize>,
}
impl<'a> Holes<'a> {
fn new(raw: &'a str) -> Self {
Holes {
chars: raw.char_indices(),
open: None,
}
}
}
impl Iterator for Holes<'_> {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
for (i, c) in self.chars.by_ref() {
match c {
'{' => self.open = Some(i + 1),
'}' => {
if let Some(start) = self.open.take()
&& i > start
{
return Some((start, i));
}
}
c if is_js_space(c) => self.open = None,
_ => {}
}
}
None
}
}
impl Template {
pub(crate) fn new(raw: &str) -> Self {
Template {
raw: crate::intern::intern(raw),
holes: Holes::new(raw).map(|(s, e)| (s as u32, e as u32)).collect(),
}
}
pub(crate) fn interpolate(&self, args: &impl Params) -> String {
let raw = self.raw;
if self.holes.is_empty() {
return String::from(raw);
}
render(raw, 0, raw.len(), self.holes(), self.holes.len(), args)
}
fn holes(&self) -> impl Iterator<Item = (usize, usize)> + Clone + '_ {
self.holes.iter().map(|&(s, e)| (s as usize, e as usize))
}
pub(crate) fn single_form(&self, args: &impl Params) -> String {
let (start, end) = self.single_range();
let holes = self.holes().filter(|&(s, e)| s > start && e < end);
render(self.raw, start, end, holes, self.holes.len(), args)
}
pub(crate) fn single_range(&self) -> (usize, usize) {
let raw = self.raw;
let body = raw.strip_prefix(ZERO_MARKER).unwrap_or(raw);
let trimmed = body.trim_matches(is_js_space);
let start = trimmed.as_ptr() as usize - raw.as_ptr() as usize;
(start, start + trimmed.len())
}
pub(crate) fn hole_slice(&self) -> &[(u32, u32)] {
&self.holes
}
}
const CHEAP: usize = 256;
fn render(
raw: &str,
from: usize,
end: usize,
holes: impl Iterator<Item = (usize, usize)> + Clone,
max_holes: usize,
args: &impl Params,
) -> String {
if max_holes == 0 {
return String::from(raw.get(from..end).unwrap_or(""));
}
let text = end.saturating_sub(from);
let growth = max_holes.saturating_mul(args.max_len());
let capacity = if growth <= CHEAP {
text + growth
} else {
let (mut removed, mut added) = (0usize, 0usize);
for (s, e) in holes.clone() {
if let Some(n) = raw.get(s..e).and_then(|name| args.len_of(name)) {
removed += e - s + 2;
added = added.saturating_add(n);
}
}
text.saturating_sub(removed).saturating_add(added)
};
let mut out = String::with_capacity(capacity);
let mut at = from;
for (s, e) in holes {
let Some(name) = raw.get(s..e) else {
continue;
};
let mark = out.len();
out.push_str(raw.get(at..s - 1).unwrap_or(""));
if args.put(name, &mut out) {
at = e + 1;
} else {
out.truncate(mark);
}
}
out.push_str(raw.get(at..end).unwrap_or(""));
out
}
pub(crate) fn interpolate_once(raw: &str, args: &impl Params) -> String {
let max_holes = raw.bytes().filter(|&b| b == b'{').count();
render(raw, 0, raw.len(), Holes::new(raw), max_holes, args)
}
#[derive(Debug, Clone)]
pub(crate) enum Node {
Obj {
kids: bool,
},
Arr {
kids: bool,
},
Null,
Leaf(Entry),
Linked(Entry),
}
const MAX_PATH: usize = 4096;
const PATH_RATIO: usize = 64;
const PATH_SLACK: usize = 1 << 20;
const SAMPLE: usize = 64;
fn reserve(walk: &mut PathMap<Node>, r: &Reader<'_>, start: usize) {
let used = (r.offset() - start).max(1);
walk.reserve(r.rest().saturating_mul(SAMPLE) / used);
}
pub(crate) fn path_budget(len: usize) -> usize {
len.saturating_mul(PATH_RATIO).saturating_add(PATH_SLACK)
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Tree {
walk: PathMap<Node>,
own: PathMap<Node>,
#[cfg(feature = "payload")]
json: std::sync::OnceLock<(Arc<str>, u64)>,
}
pub(crate) type Chunk = Tree;
static NODE: Entry = Entry::Node;
enum Target<'k> {
Walk,
Own(&'k str),
Dead,
}
fn parent(path: &str) -> Option<&str> {
path.rfind('.').and_then(|i| path.get(..i))
}
#[derive(Default)]
struct Kids(Option<Lists>);
type Lists = (PathMap<Key>, PathMap<Key>);
fn link(walk: &PathMap<Node>, (first, next): &mut Lists, child: &Key) {
if let Some(p) = parent(child).and_then(|p| walk.key_at(p))
&& let Some(was) = first.insert(p.clone(), child.clone())
{
next.insert(child.clone(), was);
}
}
impl Kids {
fn add(&mut self, walk: &PathMap<Node>, path: &str) {
if let Some(lists) = &mut self.0
&& let Some(k) = walk.key_at(path)
{
link(walk, lists, k);
}
}
fn drop_under(&mut self, walk: &mut PathMap<Node>, path: &str) {
let (first, next) = self.0.get_or_insert_with(|| {
let mut lists = (PathMap::default(), PathMap::default());
for k in walk.keys() {
link(walk, &mut lists, k);
}
lists
});
let mut todo: Vec<Key> = first.take(path).into_iter().collect();
while let Some(k) = todo.pop() {
walk.remove(&k);
todo.extend(next.remove(&k));
todo.extend(first.remove(&k));
}
}
}
struct Frame {
len: usize,
array: bool,
next_index: usize,
live: bool,
kids: bool,
}
impl Tree {
#[inline]
fn changed(&mut self) {
#[cfg(feature = "payload")]
self.json.take();
}
fn is_empty(&self) -> bool {
self.walk.is_empty() && self.own.is_empty()
}
pub(crate) fn get(&self, key: &str) -> Option<&Entry> {
self.find(&Probe::new(key))
}
#[inline]
pub(crate) fn find(&self, key: &Probe<'_>) -> Option<&Entry> {
fn read<'a>(map: &'a PathMap<Node>, key: &Probe<'_>) -> Option<&'a Entry> {
match map.at(key)? {
Node::Null => None,
Node::Obj { .. } | Node::Arr { .. } => Some(&NODE),
Node::Leaf(e) | Node::Linked(e) => Some(e),
}
}
if key.text().is_empty() {
return None;
}
if !self.own.is_empty()
&& let Some(e) = read(&self.own, key)
{
return Some(e);
}
read(&self.walk, key)
}
pub(crate) fn parse(bytes: &[u8], path: &str) -> Result<Tree, Error> {
let error = |offset: usize, kind: &'static str| Error::Json {
path: path.to_owned(),
offset,
kind,
};
let json_err = |e: crate::json::JsonError| error(e.offset, e.kind.as_str());
let mut r = Reader::new(bytes);
match r.next().map_err(json_err)? {
Some(Event::ObjectStart) => {}
_ => {
while r.next().map_err(json_err)?.is_some() {}
return Err(Error::NotObject {
path: path.to_owned(),
});
}
}
let mut budget = path_budget(bytes.len());
let tree = Tree::read_object(&mut r, path, &mut budget)?;
r.next().map_err(json_err)?;
Ok(tree)
}
pub(crate) fn read_object(
r: &mut Reader<'_>,
path: &str,
budget: &mut usize,
) -> Result<Tree, Error> {
let error = |offset: usize, kind: &'static str| Error::Json {
path: path.to_owned(),
offset,
kind,
};
let json_err = |e: crate::json::JsonError| error(e.offset, e.kind.as_str());
let mut tree = Tree::default();
let start = r.offset();
let mut buf = String::new();
let mut stack = vec![Frame {
len: 0,
array: false,
next_index: 0,
live: true,
kids: false,
}];
let mut key = None;
let mut kids = Kids::default();
while let Some(event) = r.next().map_err(json_err)? {
let (container, node) = match event {
Event::Key(k) => {
key = Some(k);
continue;
}
Event::ObjectEnd | Event::ArrayEnd => {
if let Some(f) = stack.pop()
&& f.live
&& !f.kids
&& !stack.is_empty()
&& let Some(Node::Obj { kids } | Node::Arr { kids }) =
buf.get(..f.len).and_then(|p| tree.walk.at_mut(p))
{
*kids = false;
}
if stack.is_empty() {
if tree.walk.capacity() > 4 * tree.walk.len() + 16 {
tree.walk.shrink_to_fit();
}
return Ok(tree);
}
continue;
}
Event::ObjectStart => (Some(false), Node::Obj { kids: true }),
Event::ArrayStart => (Some(true), Node::Arr { kids: true }),
Event::Str(s) => (None, Node::Leaf(Entry::Msg(Msg::new(&s)))),
Event::Num(n) => (
None,
Node::Leaf(Entry::Value(crate::intern::intern(&number_to_js_string(n)))),
),
Event::Bool(b) => (
None,
Node::Leaf(Entry::Value(if b { "true" } else { "false" })),
),
Event::Null => (None, Node::Null),
};
let depth = stack.len();
let Some(parent) = stack.last_mut() else {
break;
};
buf.truncate(parent.len);
let k = key.take();
let target = if !parent.live {
Target::Dead
} else if parent.array {
if depth > 1 {
buf.push('.');
}
crate::json::push_u64(&mut buf, parent.next_index as u64);
parent.next_index += 1;
Target::Walk
} else {
let k = k.as_deref().unwrap_or("");
if k == "__proto__" || (k.contains('.') && depth > 1) {
Target::Dead
} else if k.contains('.') {
Target::Own(k)
} else {
if depth > 1 {
buf.push('.');
}
buf.push_str(k);
Target::Walk
}
};
let live = match target {
Target::Walk => {
parent.kids = true;
if buf.len() > MAX_PATH {
return Err(error(r.offset(), "key path longer than 4096 bytes"));
}
*budget = match budget.checked_sub(buf.len()) {
Some(left) => left,
None => {
return Err(error(
r.offset(),
"key paths too long for the document size",
));
}
};
if tree.walk.len() == SAMPLE {
reserve(&mut tree.walk, r, start);
}
match tree.walk.insert(Key::from(buf.as_str()), node) {
Some(Node::Obj { kids: true } | Node::Arr { kids: true }) => {
kids.drop_under(&mut tree.walk, &buf);
}
Some(_) => {}
None => kids.add(&tree.walk, &buf),
}
true
}
Target::Own(k) => {
tree.own.insert(Key::from(k), node);
false
}
Target::Dead => false,
};
if let Some(array) = container {
stack.push(Frame {
len: buf.len(),
array,
next_index: 0,
live,
kids: false,
});
}
}
Err(error(r.offset(), "unexpected end"))
}
pub(crate) fn merge(&mut self, incoming: Tree) {
self.changed();
if self.is_empty() {
*self = incoming;
return;
}
let mut incoming = incoming;
let mut gone: PathMap<Node> = FastMap::default();
for (k, node) in &mut incoming.walk {
match (node, self.walk.get(k)) {
(Node::Obj { kids }, Some(Node::Obj { kids: had })) => *kids |= *had,
(_, Some(Node::Obj { kids: true } | Node::Arr { kids: true })) => {
gone.insert(k.clone(), Node::Null);
}
_ => {}
}
}
if !gone.is_empty() {
self.walk.retain(|k, _| {
!k.bytes()
.enumerate()
.any(|(i, b)| b == b'.' && k.get(..i).is_some_and(|p| gone.at_str(p).is_some()))
});
}
self.walk.extend(incoming.walk);
for (k, node) in incoming.own {
let both_obj = matches!(node, Node::Obj { .. })
&& matches!(self.own.get(&k), Some(Node::Obj { .. }));
if !both_obj {
self.own.insert(k, node);
}
}
}
}
pub(crate) fn hole_ranges(raw: &str) -> impl Iterator<Item = (usize, usize)> + '_ {
Holes::new(raw)
}
pub(crate) struct AtString {
pub(crate) key: Arc<str>,
pub(crate) own: bool,
pub(crate) hidden: bool,
pub(crate) raw: Arc<str>,
}
impl PluralMsg {
pub(crate) fn layout(&self) -> (usize, bool, &Shape) {
(self.forms.len(), self.marked, &self.shape)
}
}
impl Tree {
fn covered(&self, key: &str) -> bool {
matches!(self.own.at_str(key), Some(n) if !matches!(n, Node::Null))
}
pub(crate) fn link_target(&self, key: &str) -> Option<&Entry> {
if key.is_empty() {
return match self.walk.at_str(key)? {
Node::Null => None,
Node::Obj { .. } | Node::Arr { .. } => Some(&NODE),
Node::Leaf(e) | Node::Linked(e) => Some(e),
};
}
self.get(key)
}
pub(crate) fn strings_with_at(&self) -> Vec<AtString> {
let out: Vec<AtString> = [(&self.own, true), (&self.walk, false)]
.into_iter()
.flat_map(|(map, own)| {
map.iter().filter_map(move |(k, n)| match n {
Node::Leaf(e @ Entry::Msg(_)) => e
.text()
.filter(|t| t.contains('@'))
.map(|t| (k.text().clone(), own, t)),
_ => None,
})
})
.map(|(key, own, raw)| AtString {
hidden: !own && self.covered(&key),
key,
own,
raw: Arc::from(raw),
})
.collect();
out
}
pub(crate) fn set_message(&mut self, key: &str, own: bool, text: &str) {
self.changed();
let map = if own { &mut self.own } else { &mut self.walk };
if let Some(node) = map.at_mut(key) {
*node = Node::Leaf(Entry::Msg(Msg::new(text)));
}
}
pub(crate) fn insert_linked(&mut self, key: &str, entry: Entry) {
self.changed();
self.walk.insert(Key::from(key), Node::Linked(entry));
}
pub(crate) fn has(&self, key: &str) -> bool {
if key.is_empty() {
return false;
}
let read = |map: &PathMap<Node>| match map.at_str(key) {
None | Some(Node::Null) => None,
Some(Node::Linked(_)) => Some(false),
Some(_) => Some(true),
};
match read(&self.own) {
Some(true) => true,
_ => read(&self.walk) == Some(true),
}
}
pub(crate) fn only_linked(&self) -> bool {
!self.walk.is_empty()
&& self.own.is_empty()
&& self.walk.values().all(|n| matches!(n, Node::Linked(_)))
}
pub(crate) fn leaves(&self) -> impl Iterator<Item = (&str, &Entry)> {
let own = self.own.iter().filter_map(|(k, n)| match n {
Node::Leaf(e) => Some((&**k, e)),
_ => None,
});
let walk = self.walk.iter().filter_map(|(k, n)| match n {
Node::Leaf(e) if !k.is_empty() && !self.covered(k) => Some((&**k, e)),
_ => None,
});
own.chain(walk)
}
}
#[cfg(feature = "payload")]
impl Tree {
pub(crate) fn payload(&self) -> &(Arc<str>, u64) {
self.json.get_or_init(|| {
let mut json = String::from("{\"data\":");
self.write_json_uncached(&mut json);
self.write_linked(&mut json);
json.push('}');
let tag = content_tag(json.as_bytes());
(Arc::from(json), tag)
})
}
pub(crate) fn write_json(&self, out: &mut String) {
self.write_json_uncached(out);
}
fn write_linked(&self, out: &mut String) {
let mut linked: Vec<(&str, &Entry)> = self
.walk
.iter()
.filter_map(|(k, n)| match n {
Node::Linked(e) => Some((&**k, e)),
_ => None,
})
.collect();
if linked.is_empty() {
return;
}
linked.sort_unstable_by(|a, b| a.0.cmp(b.0));
out.push_str(",\"linked\":{");
for (i, (key, e)) in linked.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
crate::json::write_str(out, key);
out.push(':');
match e {
Entry::Msg(_) => crate::json::write_str(out, e.text().map_or("", |t| t)),
Entry::Value(v) => push_value(out, v),
Entry::Node => out.push_str("{}"),
}
}
out.push('}');
}
pub(crate) fn add_linked(&mut self, linked: Vec<(Arc<str>, Entry)>) {
self.changed();
for (k, e) in linked {
self.walk.insert(Key::from(k), Node::Linked(e));
}
}
fn write_json_uncached(&self, out: &mut String) {
let mut kids: FastMap<Option<&str>, Vec<(&str, &str, &Node)>> = FastMap::default();
for (path, node) in &self.walk {
if matches!(node, Node::Linked(_)) {
continue;
}
let (parent, key) = match path.rfind('.') {
Some(i) => (path.get(..i), path.get(i + 1..).unwrap_or("")),
None => (None, &**path),
};
kids.entry(parent).or_default().push((key, path, node));
}
let mut top: Vec<(&str, Option<&str>, &Node)> = kids
.remove(&None)
.unwrap_or_default()
.into_iter()
.map(|(k, p, n)| (k, Some(p), n))
.collect();
top.extend(
self.own
.iter()
.filter_map(|(k, n)| (!matches!(n, Node::Linked(_))).then_some((&**k, None, n))),
);
top.sort_unstable_by(|a, b| a.0.cmp(b.0));
out.push('{');
for (i, (key, path, node)) in top.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
crate::json::write_str(out, key);
out.push(':');
write_node(out, &mut kids, path, node);
}
out.push('}');
}
pub(crate) fn merge_replacing(&mut self, incoming: Tree, depth: usize) {
let at: Vec<Key> = incoming
.walk
.keys()
.filter(|k| k.bytes().filter(|&b| b == b'.').count() + 1 == depth)
.cloned()
.collect();
if !at.is_empty() {
self.walk.retain(|k, _| {
!at.iter().any(|p| {
k.strip_prefix(&**p)
.is_some_and(|rest| rest.is_empty() || rest.starts_with('.'))
})
});
}
self.merge(incoming);
}
}
#[cfg(feature = "payload")]
fn push_value(out: &mut String, v: &str) {
if v.ends_with("Infinity") || v == "NaN" {
out.push_str("null");
} else {
out.push_str(v);
}
}
#[cfg(feature = "payload")]
pub(crate) fn content_tag(bytes: &[u8]) -> u64 {
use std::hash::Hasher;
let mut h = crate::hash::FastHasher::default();
h.write(bytes);
h.finish()
}
#[cfg(feature = "payload")]
fn write_node<'t>(
out: &mut String,
kids: &mut FastMap<Option<&'t str>, Vec<(&'t str, &'t str, &'t Node)>>,
path: Option<&'t str>,
node: &'t Node,
) {
let (open, close, array) = match node {
Node::Leaf(Entry::Msg(m)) => {
let raw = match m {
Msg::Text(t) => &t.raw,
Msg::Plural(p) => &p.text.raw,
};
return crate::json::write_str(out, raw);
}
Node::Leaf(Entry::Value(v)) => return push_value(out, v),
Node::Null | Node::Leaf(Entry::Node) | Node::Linked(_) => return out.push_str("null"),
Node::Obj { .. } => ('{', '}', false),
Node::Arr { .. } => ('[', ']', true),
};
let mut list = path.and_then(|p| kids.remove(&Some(p))).unwrap_or_default();
if array {
list.sort_unstable_by_key(|k| k.0.parse::<usize>().unwrap_or(usize::MAX));
} else {
list.sort_unstable_by(|a, b| a.0.cmp(b.0));
}
out.push(open);
for (i, (key, child, n)) in list.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
if !array {
crate::json::write_str(out, key);
out.push(':');
}
write_node(out, kids, Some(child), n);
}
out.push(close);
}