nextjson 0.1.4

A dependency-free, no_std data-contract engine: schema-first, multi-format, reuse-first JSON/CBOR and 16 wire formats.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Shared relay between parsed [`Value`] trees and the unified token stream.
//!
//! Document-oriented formats (CBOR, envy, pickle, TOML, YAML) parse their
//! input into a [`Value`] tree first, then replay that tree through the
//! crate's token stream so the generic `NsonDeserialize` machinery can drive
//! it. The tree→token conversion and the delegating [`FormatDecoder`] wrapper
//! are identical for every such codec, so they live here once instead of
//! being duplicated per format.

use alloc::borrow::Cow;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use crate::de::{Decoder, FormatDecoder, Mark, Token};
use crate::error::{Error, Result};
use crate::map::Map;
use crate::number::Number;
use crate::ser::FormatEncoder;
use crate::value::Value;

/// Format an `f64` as a decimal string, appending `.0` for integral values so
/// float-ness survives round-trips (matches the main JSON encoder).
///
/// Non-finite values are rejected: the JSON data model has no NaN or
/// infinity, and silently emitting `NaN` / `inf` text would corrupt the wire.
pub(crate) fn float_string(v: f64) -> Result<String> {
    if !v.is_finite() {
        return Err(Error::custom("non-finite float cannot be represented"));
    }
    let s = v.to_string();
    if s.contains(['.', 'e', 'E']) {
        Ok(s)
    } else {
        Ok(alloc::format!("{s}.0"))
    }
}

/// Format a [`Number`] as a plain decimal string (the shared scalar
/// representation used by the text-emitting codecs).
///
/// Integral floats are written as `77.0` rather than `77` so float-ness
/// survives round-trips, matching the main JSON encoder's `write_float_into`.
pub(crate) fn number_string(n: &Number) -> Result<String> {
    match n {
        Number::I64(v) => Ok(v.to_string()),
        Number::U64(v) => Ok(v.to_string()),
        Number::I128(v) => Ok(v.to_string()),
        Number::U128(v) => Ok(v.to_string()),
        Number::F64(v) => float_string(*v),
    }
}

/// Parse a decimal `f64`, returning `None` for non-finite results.
///
/// `str::parse::<f64>()` accepts `1e999` (overflowing to infinity) and
/// `NaN`; the JSON data model rejects those, so callers use this instead of
/// a bare parse when the result must stay within the data model.
pub(crate) fn parse_float(s: &str) -> Option<f64> {
    let v: f64 = s.parse().ok()?;
    if v.is_finite() {
        Some(v)
    } else {
        None
    }
}

enum Builder {
    Array(Vec<Value>),
    Object {
        map: Map,
        pending_key: Option<String>,
    },
    Root,
}

/// Streaming encoder that buffers the event stream into a [`Value`] tree.
///
/// Document-shaped formats (TOML, YAML) must emit scalars before their
/// subtables, so they collect the whole event stream into a tree and
/// serialize it when the root closes. The collection itself is
/// format-neutral and lives here once; each format keeps only its emitter.
///
/// `null` is collected like any other value; codecs without a null type
/// (TOML) reject it when emitting.
pub(crate) struct CollectEncoder {
    stack: Vec<Builder>,
    root: Option<Value>,
}

impl CollectEncoder {
    /// Create an empty event collector.
    pub(crate) fn new() -> Self {
        CollectEncoder {
            stack: vec![Builder::Root],
            root: None,
        }
    }

    /// Take the collected root tree (called by the format's `encode`).
    pub(crate) fn take_root(&mut self) -> Result<Value> {
        if self.stack.len() != 1 || !matches!(self.stack.last(), Some(Builder::Root)) {
            return Err(Error::custom("collector: unfinished container"));
        }
        self.root
            .take()
            .ok_or_else(|| Error::custom("collector: no root value"))
    }

    fn attach(&mut self, value: Value) -> Result<()> {
        match self.stack.last_mut() {
            Some(Builder::Array(items)) => items.push(value),
            Some(Builder::Object { map, pending_key }) => {
                let key = pending_key
                    .take()
                    .ok_or_else(|| Error::custom("collector: object value has no key"))?;
                if map.insert(key, value).is_some() {
                    return Err(Error::custom("collector: duplicate object key"));
                }
            }
            Some(Builder::Root) if self.root.is_none() => self.root = Some(value),
            Some(Builder::Root) => return Err(Error::custom("collector: multiple root values")),
            None => return Err(Error::custom("collector: value outside root")),
        }
        Ok(())
    }
}

impl FormatEncoder for CollectEncoder {
    type Error = crate::error::Error;

    fn begin_array(&mut self) -> Result<(), Self::Error> {
        self.stack.push(Builder::Array(Vec::new()));
        Ok(())
    }

    fn separator(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }

    fn end_array(&mut self) -> Result<(), Self::Error> {
        match self.stack.pop() {
            Some(Builder::Array(items)) => self.attach(Value::Array(items)),
            _ => Err(Error::custom("collector: array end without start")),
        }
    }

    fn begin_object(&mut self) -> Result<(), Self::Error> {
        self.stack.push(Builder::Object {
            map: Map::new(),
            pending_key: None,
        });
        Ok(())
    }

    fn key(&mut self, key: &str) -> Result<(), Self::Error> {
        match self.stack.last_mut() {
            Some(Builder::Object { map, pending_key }) => {
                if pending_key.is_some() {
                    return Err(Error::custom("collector: previous key has no value"));
                }
                if map.contains_key(key) {
                    return Err(Error::custom("collector: duplicate object key"));
                }
                *pending_key = Some(key.to_string());
                Ok(())
            }
            _ => Err(Error::custom("collector: key outside object")),
        }
    }

    fn end_object(&mut self) -> Result<(), Self::Error> {
        match self.stack.pop() {
            Some(Builder::Object { map, pending_key }) if pending_key.is_none() => {
                self.attach(Value::Object(map))
            }
            Some(Builder::Object { .. }) => {
                Err(Error::custom("collector: object key has no value"))
            }
            _ => Err(Error::custom("collector: object end without start")),
        }
    }

    fn write_null(&mut self) -> Result<(), Self::Error> {
        self.attach(Value::Null)
    }

    fn write_bool(&mut self, value: bool) -> Result<(), Self::Error> {
        self.attach(Value::from(value))
    }

    fn write_str(&mut self, value: &str) -> Result<(), Self::Error> {
        self.attach(Value::from(value))
    }

    fn write_char(&mut self, value: char) -> Result<(), Self::Error> {
        self.attach(Value::from(value))
    }

    fn write_number(&mut self, value: &Number) -> Result<(), Self::Error> {
        self.attach(Value::from(*value))
    }

    fn write_i64(&mut self, value: i64) -> Result<(), Self::Error> {
        self.attach(Value::from(value))
    }

    fn write_u64(&mut self, value: u64) -> Result<(), Self::Error> {
        self.attach(Value::from(value))
    }

    fn write_i128(&mut self, value: i128) -> Result<(), Self::Error> {
        self.attach(Value::from(value))
    }

    fn write_u128(&mut self, value: u128) -> Result<(), Self::Error> {
        self.attach(Value::from(value))
    }

    fn write_f64(&mut self, value: f64) -> Result<(), Self::Error> {
        self.attach(Value::from(value))
    }

    fn write_f32(&mut self, value: f32) -> Result<(), Self::Error> {
        self.attach(Value::from(value))
    }
}

macro_rules! impl_collecting_format_encoder {
    ($encoder:ident) => {
        impl<W: $crate::write::Write> $crate::ser::FormatEncoder for $encoder<W> {
            type Error = $crate::error::Error;

            fn begin_array(&mut self) -> $crate::Result<(), Self::Error> {
                self.collector.begin_array()
            }
            fn separator(&mut self) -> $crate::Result<(), Self::Error> {
                self.collector.separator()
            }
            fn end_array(&mut self) -> $crate::Result<(), Self::Error> {
                self.collector.end_array()
            }
            fn begin_object(&mut self) -> $crate::Result<(), Self::Error> {
                self.collector.begin_object()
            }
            fn key(&mut self, key: &str) -> $crate::Result<(), Self::Error> {
                self.collector.key(key)
            }
            fn end_object(&mut self) -> $crate::Result<(), Self::Error> {
                self.collector.end_object()
            }
            fn write_null(&mut self) -> $crate::Result<(), Self::Error> {
                self.collector.write_null()
            }
            fn write_bool(&mut self, value: bool) -> $crate::Result<(), Self::Error> {
                self.collector.write_bool(value)
            }
            fn write_str(&mut self, value: &str) -> $crate::Result<(), Self::Error> {
                self.collector.write_str(value)
            }
            fn write_char(&mut self, value: char) -> $crate::Result<(), Self::Error> {
                self.collector.write_char(value)
            }
            fn write_number(&mut self, value: &$crate::Number) -> $crate::Result<(), Self::Error> {
                self.collector.write_number(value)
            }
            fn write_i64(&mut self, value: i64) -> $crate::Result<(), Self::Error> {
                self.collector.write_i64(value)
            }
            fn write_u64(&mut self, value: u64) -> $crate::Result<(), Self::Error> {
                self.collector.write_u64(value)
            }
            fn write_i128(&mut self, value: i128) -> $crate::Result<(), Self::Error> {
                self.collector.write_i128(value)
            }
            fn write_u128(&mut self, value: u128) -> $crate::Result<(), Self::Error> {
                self.collector.write_u128(value)
            }
            fn write_f64(&mut self, value: f64) -> $crate::Result<(), Self::Error> {
                self.collector.write_f64(value)
            }
            fn write_f32(&mut self, value: f32) -> $crate::Result<(), Self::Error> {
                self.collector.write_f32(value)
            }
        }
    };
}

pub(crate) use impl_collecting_format_encoder;

/// Maximum container nesting accepted when replaying a [`Value`] tree into
/// the token stream. Every decoder that builds a tree bounds its own parse
/// at 128; this is the shared backstop for programmatically constructed
/// trees (and any parser that forgets its own bound), so the recursion can
/// never overflow the stack.
pub(crate) const MAX_VALUE_DEPTH: u32 = 128;

/// Convert a [`Value`] into an owned token stream (the unified replay path).
///
/// Rejects trees nested deeper than [`MAX_VALUE_DEPTH`] instead of recursing
/// without bound.
pub(crate) fn value_to_tokens(v: &Value) -> Result<Vec<Token<'static>>> {
    let mut out = Vec::new();
    value_to_tokens_inner(v, &mut out, 0)?;
    Ok(out)
}

fn value_to_tokens_inner(v: &Value, out: &mut Vec<Token<'static>>, depth: u32) -> Result<()> {
    if depth > MAX_VALUE_DEPTH {
        return Err(Error::custom(
            "value nesting exceeds the maximum depth (128)",
        ));
    }
    match v {
        Value::Null => out.push(Token::Null),
        Value::Bool(b) => out.push(Token::Bool(*b)),
        Value::Number(n) => out.push(Token::Number(*n)),
        Value::String(s) => out.push(Token::Str(Cow::Owned(s.clone()))),
        Value::Array(a) => {
            out.push(Token::BeginArray);
            for x in a {
                value_to_tokens_inner(x, out, depth + 1)?;
            }
            out.push(Token::EndArray);
        }
        Value::Object(m) => {
            out.push(Token::BeginObject);
            for (k, val) in m.iter() {
                out.push(Token::Str(Cow::Owned(k.to_string())));
                value_to_tokens_inner(val, out, depth + 1)?;
            }
            out.push(Token::EndObject);
        }
    }
    Ok(())
}

/// A [`FormatDecoder`] that replays an owned token stream produced from a
/// [`Value`] tree.
///
/// Formats that parse their input into a [`Value`] first wrap that stream in
/// this type instead of re-implementing the full [`FormatDecoder`] contract.
/// The inner decoder borrows the owned stream for the lifetime of the
/// wrapper; `object_key` / `string` are re-lifetimed to the caller's `'de`.
pub struct TreeDecoder<'de> {
    inner: Decoder<'static>,
    _marker: core::marker::PhantomData<&'de ()>,
}

impl<'de> TreeDecoder<'de> {
    /// Wrap an owned token stream produced by `value_to_tokens`.
    pub fn new(tokens: Vec<Token<'static>>) -> Self {
        TreeDecoder {
            inner: Decoder::from_tokens(tokens),
            _marker: core::marker::PhantomData,
        }
    }

    /// Validate that the whole token stream was consumed.
    pub fn end(&mut self) -> Result<()> {
        self.inner.end()
    }
}

impl<'de> FormatDecoder<'de> for TreeDecoder<'de> {
    type Error = crate::error::Error;

    fn begin_object(&mut self) -> Result<(), Self::Error> {
        self.inner.begin_object()
    }
    fn end_object(&mut self) -> Result<(), Self::Error> {
        self.inner.end_object()
    }
    fn object_key(&mut self) -> Result<Option<Cow<'de, str>>, Self::Error> {
        Ok(self.inner.object_key()?.map(|k| match k {
            Cow::Borrowed(s) => Cow::Borrowed(s),
            Cow::Owned(s) => Cow::Owned(s),
        }))
    }
    fn object_entry_sep(&mut self) -> Result<bool, Self::Error> {
        self.inner.object_entry_sep()
    }
    fn begin_array(&mut self) -> Result<(), Self::Error> {
        self.inner.begin_array()
    }
    fn end_array(&mut self) -> Result<(), Self::Error> {
        self.inner.end_array()
    }
    fn array_has_more(&mut self) -> Result<bool, Self::Error> {
        self.inner.array_has_more()
    }
    fn array_entry_sep(&mut self) -> Result<bool, Self::Error> {
        self.inner.array_entry_sep()
    }
    fn unit(&mut self) -> Result<(), Self::Error> {
        self.inner.unit()
    }
    fn bool(&mut self) -> Result<bool, Self::Error> {
        self.inner.bool()
    }
    fn number(&mut self) -> Result<Number, Self::Error> {
        self.inner.number()
    }
    fn string(&mut self) -> Result<Cow<'de, str>, Self::Error> {
        Ok(match self.inner.string()? {
            Cow::Borrowed(s) => Cow::Borrowed(s),
            Cow::Owned(s) => Cow::Owned(s),
        })
    }
    fn char(&mut self) -> Result<char, Self::Error> {
        self.inner.char()
    }
    fn skip_value(&mut self) -> Result<(), Self::Error> {
        self.inner.skip_value()
    }
    fn peek_token(&mut self) -> Result<Token<'de>, Self::Error> {
        self.inner.peek_token()
    }
    fn next_token(&mut self) -> Result<Token<'de>, Self::Error> {
        self.inner.next_token()
    }
    fn save(&self) -> Mark {
        self.inner.save()
    }
    fn restore(&mut self, mark: Mark) {
        self.inner.restore(mark)
    }
}