Skip to main content

tabnas_support/
value.rs

1// Copyright (c) 2026 tabnas, MIT License
2
3// The value a fixture's expected column describes, and the value a parser
4// under test hands the runner.
5//
6// It is the JSON data model plus the two things a parity harness has to
7// be able to say that JSON cannot: `Undefined` (an empty expected cell,
8// or a parse that yielded no value at all, which TypeScript tells apart
9// from `null` and Go cannot) and a number that is infinite or not a
10// number (`1e400` in a fixture reads as Infinity, as `JSON.parse` reads
11// it; a JSON5 grammar produces `NaN`).
12//
13// The reader and writer are written out here rather than borrowed from a
14// JSON crate, because this crate is a dev-dependency of every tabnas
15// Rust crate and takes no dependencies of its own. They handle exactly
16// RFC 8259 JSON, with two deliberate readings recorded in
17// `doc/reference.md`: an out-of-range number widens to an infinity
18// instead of failing to load, and an unpaired `\uXXXX` surrogate decodes
19// to U+FFFD, which is what a UTF-8 string can hold (the runner refuses
20// such a cell before it is ever compared, so this is a courtesy for a
21// suite reading one deliberately).
22
23use std::fmt;
24
25/// A parsed value in the fixture data model. See the module notes.
26#[derive(Debug, Clone)]
27pub enum Value {
28    /// No value at all: an empty expected cell, or a parse that produced
29    /// nothing. Distinct from [`Value::Null`], as in TypeScript.
30    Undefined,
31    Null,
32    Bool(bool),
33    /// Every number is an `f64`, as in the canonical runtime. An integer
34    /// beyond 2^53 is therefore inexact here exactly as it is in
35    /// `JSON.parse`, and a fixture must not pin one.
36    Number(f64),
37    String(String),
38    Array(Vec<Value>),
39    /// Entries in document order. Order never takes part in equality
40    /// (ADR-15 keeps key order out of the value contract); it is kept so
41    /// a failure message renders the value the way the fixture wrote it.
42    Object(Vec<(String, Value)>),
43}
44
45impl Value {
46    /// Read a JSON text. The error is a short reason without the text
47    /// itself, so [`crate::parse_expect`] can quote the cell once.
48    pub fn parse_json(text: &str) -> Result<Value, String> {
49        let mut reader = Reader {
50            bytes: text.as_bytes(),
51            at: 0,
52        };
53        reader.skip_space();
54        let value = reader.value()?;
55        reader.skip_space();
56        if reader.at < reader.bytes.len() {
57            return Err(format!("unexpected trailing content at byte {}", reader.at));
58        }
59        Ok(value)
60    }
61
62    /// The entry at `key` of an object, or `None` for anything else.
63    pub fn get(&self, key: &str) -> Option<&Value> {
64        match self {
65            Value::Object(entries) => entries
66                .iter()
67                .find(|(name, _)| name == key)
68                .map(|(_, value)| value),
69            _ => None,
70        }
71    }
72
73    /// Insert or replace an object entry, keeping the position of an
74    /// existing key, which is what a JavaScript object does.
75    pub fn insert(&mut self, key: impl Into<String>, value: Value) {
76        let key = key.into();
77        if let Value::Object(entries) = self {
78            if let Some(entry) = entries.iter_mut().find(|(name, _)| *name == key) {
79                entry.1 = value;
80            } else {
81                entries.push((key, value));
82            }
83        }
84    }
85
86    /// Whether this is [`Value::Undefined`].
87    pub fn is_undefined(&self) -> bool {
88        matches!(self, Value::Undefined)
89    }
90
91    /// Whether this is [`Value::Null`].
92    pub fn is_null(&self) -> bool {
93        matches!(self, Value::Null)
94    }
95
96    /// The number, when this is one.
97    pub fn as_f64(&self) -> Option<f64> {
98        match self {
99            Value::Number(n) => Some(*n),
100            _ => None,
101        }
102    }
103
104    /// The string, when this is one.
105    pub fn as_str(&self) -> Option<&str> {
106        match self {
107            Value::String(s) => Some(s),
108            _ => None,
109        }
110    }
111
112    /// The boolean, when this is one.
113    pub fn as_bool(&self) -> Option<bool> {
114        match self {
115            Value::Bool(b) => Some(*b),
116            _ => None,
117        }
118    }
119
120    /// The elements, when this is an array.
121    pub fn as_array(&self) -> Option<&[Value]> {
122        match self {
123            Value::Array(items) => Some(items),
124            _ => None,
125        }
126    }
127
128    /// The entries, when this is an object.
129    pub fn as_object(&self) -> Option<&[(String, Value)]> {
130        match self {
131            Value::Object(entries) => Some(entries),
132            _ => None,
133        }
134    }
135}
136
137// Equality with JSON semantics: structural, key-order independent, an
138// integer equal to the float of the same magnitude (there is only one
139// number type here, so that is automatic), NaN equal to itself, and -0
140// NOT equal to 0. The last two are the two halves of ADR-15 and go
141// opposite ways on purpose: a parser that reports 0 for the input -0 has
142// lost information the source carried, while NaN is what a fixture cannot
143// spell but an in-language case can.
144impl PartialEq for Value {
145    fn eq(&self, other: &Value) -> bool {
146        match (self, other) {
147            (Value::Undefined, Value::Undefined) => true,
148            (Value::Null, Value::Null) => true,
149            (Value::Bool(a), Value::Bool(b)) => a == b,
150            (Value::Number(a), Value::Number(b)) => same_number(*a, *b),
151            (Value::String(a), Value::String(b)) => a == b,
152            (Value::Array(a), Value::Array(b)) => {
153                a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x == y)
154            }
155            (Value::Object(a), Value::Object(b)) => {
156                a.len() == b.len()
157                    && a.iter().all(|(key, value)| {
158                        b.iter()
159                            .find(|(other_key, _)| other_key == key)
160                            .is_some_and(|(_, other)| other == value)
161                    })
162            }
163            _ => false,
164        }
165    }
166}
167
168/// `to_bits` rather than `==`, so -0.0 and 0.0 stay distinct: the two
169/// comparisons differ only on signed zero and NaN, and NaN is handled
170/// first so its payload does not matter.
171fn same_number(a: f64, b: f64) -> bool {
172    if a.is_nan() && b.is_nan() {
173        return true;
174    }
175    a.to_bits() == b.to_bits()
176}
177
178// Renders JSON where possible, so the text lines up with how the fixture
179// wrote it. `-0` is spelt `-0` (JSON.stringify would say `0`, and a
180// signed-zero mismatch would then read "got 0, expected 0"), and the
181// values JSON cannot spell are written the way JavaScript names them:
182// `undefined`, `NaN`, `Infinity`, `-Infinity`.
183impl fmt::Display for Value {
184    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
185        match self {
186            Value::Undefined => formatter.write_str("undefined"),
187            Value::Null => formatter.write_str("null"),
188            Value::Bool(b) => write!(formatter, "{b}"),
189            Value::Number(n) => formatter.write_str(&format_number(*n)),
190            Value::String(s) => write_json_string(formatter, s),
191            Value::Array(items) => {
192                formatter.write_str("[")?;
193                for (index, item) in items.iter().enumerate() {
194                    if index > 0 {
195                        formatter.write_str(",")?;
196                    }
197                    write!(formatter, "{item}")?;
198                }
199                formatter.write_str("]")
200            }
201            Value::Object(entries) => {
202                formatter.write_str("{")?;
203                for (index, (key, value)) in entries.iter().enumerate() {
204                    if index > 0 {
205                        formatter.write_str(",")?;
206                    }
207                    write_json_string(formatter, key)?;
208                    write!(formatter, ":{value}")?;
209                }
210                formatter.write_str("}")
211            }
212        }
213    }
214}
215
216fn format_number(n: f64) -> String {
217    if n.is_nan() {
218        return "NaN".to_string();
219    }
220    if n.is_infinite() {
221        return if n > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
222    }
223    if n == 0.0 {
224        return if n.is_sign_negative() { "-0" } else { "0" }.to_string();
225    }
226    let magnitude = n.abs();
227    if !(1e-6..1e21).contains(&magnitude) {
228        // JavaScript writes the exponent with an explicit sign (`1e+21`);
229        // Rust's `{:e}` leaves a positive one bare.
230        let exp = format!("{n:e}");
231        return match exp.find('e') {
232            Some(at) if !exp[at + 1..].starts_with('-') => {
233                format!("{}e+{}", &exp[..at], &exp[at + 1..])
234            }
235            _ => exp,
236        };
237    }
238    // `Display` already writes an integral f64 without a fraction, at every
239    // magnitude below 1e21. A cast through i64 would saturate above 2^63.
240    format!("{n}")
241}
242
243fn write_json_string(formatter: &mut fmt::Formatter<'_>, text: &str) -> fmt::Result {
244    formatter.write_str("\"")?;
245    for c in text.chars() {
246        match c {
247            '"' => formatter.write_str("\\\"")?,
248            '\\' => formatter.write_str("\\\\")?,
249            '\n' => formatter.write_str("\\n")?,
250            '\r' => formatter.write_str("\\r")?,
251            '\t' => formatter.write_str("\\t")?,
252            '\u{8}' => formatter.write_str("\\b")?,
253            '\u{c}' => formatter.write_str("\\f")?,
254            c if (c as u32) < 0x20 => write!(formatter, "\\u{:04x}", c as u32)?,
255            c => write!(formatter, "{c}")?,
256        }
257    }
258    formatter.write_str("\"")
259}
260
261// A small, strict JSON reader over the bytes of a cell.
262struct Reader<'a> {
263    bytes: &'a [u8],
264    at: usize,
265}
266
267impl Reader<'_> {
268    fn skip_space(&mut self) {
269        while self.at < self.bytes.len()
270            && matches!(self.bytes[self.at], b' ' | b'\t' | b'\n' | b'\r')
271        {
272            self.at += 1;
273        }
274    }
275
276    fn peek(&self) -> Option<u8> {
277        self.bytes.get(self.at).copied()
278    }
279
280    fn value(&mut self) -> Result<Value, String> {
281        match self.peek() {
282            None => Err("unexpected end of text".to_string()),
283            Some(b'{') => self.object(),
284            Some(b'[') => self.array(),
285            Some(b'"') => self.string().map(Value::String),
286            Some(b't') => self.literal("true", Value::Bool(true)),
287            Some(b'f') => self.literal("false", Value::Bool(false)),
288            Some(b'n') => self.literal("null", Value::Null),
289            Some(b'-' | b'0'..=b'9') => self.number(),
290            Some(other) => Err(format!(
291                "unexpected character {:?} at byte {}",
292                other as char, self.at
293            )),
294        }
295    }
296
297    fn literal(&mut self, word: &str, value: Value) -> Result<Value, String> {
298        if self.bytes[self.at..].starts_with(word.as_bytes()) {
299            self.at += word.len();
300            Ok(value)
301        } else {
302            Err(format!("unexpected token at byte {}", self.at))
303        }
304    }
305
306    fn number(&mut self) -> Result<Value, String> {
307        let start = self.at;
308        if self.peek() == Some(b'-') {
309            self.at += 1;
310        }
311        match self.peek() {
312            Some(b'0') => self.at += 1,
313            Some(b'1'..=b'9') => self.digits(),
314            _ => return Err(format!("invalid number at byte {start}")),
315        }
316        if self.peek() == Some(b'.') {
317            self.at += 1;
318            if !matches!(self.peek(), Some(b'0'..=b'9')) {
319                return Err(format!("invalid number at byte {start}"));
320            }
321            self.digits();
322        }
323        if matches!(self.peek(), Some(b'e' | b'E')) {
324            self.at += 1;
325            if matches!(self.peek(), Some(b'+' | b'-')) {
326                self.at += 1;
327            }
328            if !matches!(self.peek(), Some(b'0'..=b'9')) {
329                return Err(format!("invalid number at byte {start}"));
330            }
331            self.digits();
332        }
333        let text = std::str::from_utf8(&self.bytes[start..self.at]).expect("ASCII digits");
334        // `str::parse::<f64>` answers an infinity for an out-of-range
335        // literal rather than failing, which is what JSON.parse does and
336        // what keeps a row that loads in TypeScript loading here.
337        text.parse::<f64>()
338            .map(Value::Number)
339            .map_err(|error| format!("invalid number {text:?}: {error}"))
340    }
341
342    fn digits(&mut self) {
343        while matches!(self.peek(), Some(b'0'..=b'9')) {
344            self.at += 1;
345        }
346    }
347
348    fn string(&mut self) -> Result<String, String> {
349        self.at += 1; // the opening quote
350        let mut out = String::new();
351        loop {
352            let Some(byte) = self.peek() else {
353                return Err("unterminated string".to_string());
354            };
355            match byte {
356                b'"' => {
357                    self.at += 1;
358                    return Ok(out);
359                }
360                b'\\' => {
361                    self.at += 1;
362                    let Some(escaped) = self.peek() else {
363                        return Err("unterminated string escape".to_string());
364                    };
365                    self.at += 1;
366                    match escaped {
367                        b'"' => out.push('"'),
368                        b'\\' => out.push('\\'),
369                        b'/' => out.push('/'),
370                        b'b' => out.push('\u{8}'),
371                        b'f' => out.push('\u{c}'),
372                        b'n' => out.push('\n'),
373                        b'r' => out.push('\r'),
374                        b't' => out.push('\t'),
375                        b'u' => {
376                            let unit = self.hex4()?;
377                            if (0xD800..=0xDBFF).contains(&unit) {
378                                // A high surrogate pairs with an immediately
379                                // following low one; anything else is a lone
380                                // surrogate, which a UTF-8 string spells as
381                                // U+FFFD, as Go's encoding/json does.
382                                let low = if self.bytes[self.at..].starts_with(b"\\u") {
383                                    let mark = self.at;
384                                    self.at += 2;
385                                    match self.hex4() {
386                                        Ok(low) if (0xDC00..=0xDFFF).contains(&low) => Some(low),
387                                        _ => {
388                                            self.at = mark;
389                                            None
390                                        }
391                                    }
392                                } else {
393                                    None
394                                };
395                                match low {
396                                    Some(low) => {
397                                        let scalar =
398                                            0x10000 + ((unit - 0xD800) << 10) + (low - 0xDC00);
399                                        out.push(char::from_u32(scalar).unwrap_or('\u{FFFD}'));
400                                    }
401                                    None => out.push('\u{FFFD}'),
402                                }
403                            } else {
404                                out.push(char::from_u32(unit).unwrap_or('\u{FFFD}'));
405                            }
406                        }
407                        other => {
408                            return Err(format!("invalid escape \\{}", other as char));
409                        }
410                    }
411                }
412                byte if byte < 0x20 => {
413                    return Err("control character in string".to_string());
414                }
415                _ => {
416                    // Copy one whole UTF-8 sequence. The input is a `&str`,
417                    // so the bytes are valid UTF-8 and the sequence length
418                    // follows from its first byte.
419                    let width = match byte {
420                        0x00..=0x7F => 1,
421                        0xC0..=0xDF => 2,
422                        0xE0..=0xEF => 3,
423                        _ => 4,
424                    };
425                    let end = (self.at + width).min(self.bytes.len());
426                    out.push_str(
427                        std::str::from_utf8(&self.bytes[self.at..end]).unwrap_or("\u{FFFD}"),
428                    );
429                    self.at = end;
430                }
431            }
432        }
433    }
434
435    fn hex4(&mut self) -> Result<u32, String> {
436        if self.at + 4 > self.bytes.len() {
437            return Err("truncated \\u escape".to_string());
438        }
439        let text = std::str::from_utf8(&self.bytes[self.at..self.at + 4])
440            .map_err(|_| "invalid \\u escape".to_string())?;
441        let unit = u32::from_str_radix(text, 16).map_err(|_| "invalid \\u escape".to_string())?;
442        self.at += 4;
443        Ok(unit)
444    }
445
446    fn array(&mut self) -> Result<Value, String> {
447        self.at += 1; // [
448        let mut items = Vec::new();
449        self.skip_space();
450        if self.peek() == Some(b']') {
451            self.at += 1;
452            return Ok(Value::Array(items));
453        }
454        loop {
455            self.skip_space();
456            items.push(self.value()?);
457            self.skip_space();
458            match self.peek() {
459                Some(b',') => self.at += 1,
460                Some(b']') => {
461                    self.at += 1;
462                    return Ok(Value::Array(items));
463                }
464                _ => return Err(format!("expected , or ] at byte {}", self.at)),
465            }
466        }
467    }
468
469    fn object(&mut self) -> Result<Value, String> {
470        self.at += 1; // {
471        let mut object = Value::Object(Vec::new());
472        self.skip_space();
473        if self.peek() == Some(b'}') {
474            self.at += 1;
475            return Ok(object);
476        }
477        loop {
478            self.skip_space();
479            if self.peek() != Some(b'"') {
480                return Err(format!("expected a string key at byte {}", self.at));
481            }
482            let key = self.string()?;
483            self.skip_space();
484            if self.peek() != Some(b':') {
485                return Err(format!("expected : at byte {}", self.at));
486            }
487            self.at += 1;
488            self.skip_space();
489            let value = self.value()?;
490            object.insert(key, value);
491            self.skip_space();
492            match self.peek() {
493                Some(b',') => self.at += 1,
494                Some(b'}') => {
495                    self.at += 1;
496                    return Ok(object);
497                }
498                _ => return Err(format!("expected , or }} at byte {}", self.at)),
499            }
500        }
501    }
502}
503
504#[cfg(feature = "serde_json")]
505impl From<&serde_json::Value> for Value {
506    /// A serde_json value as a fixture value. Numbers widen to `f64`, as
507    /// every number here is one.
508    fn from(value: &serde_json::Value) -> Self {
509        match value {
510            serde_json::Value::Null => Value::Null,
511            serde_json::Value::Bool(b) => Value::Bool(*b),
512            serde_json::Value::Number(n) => Value::Number(n.as_f64().unwrap_or(f64::NAN)),
513            serde_json::Value::String(s) => Value::String(s.clone()),
514            serde_json::Value::Array(items) => {
515                Value::Array(items.iter().map(Value::from).collect())
516            }
517            serde_json::Value::Object(entries) => Value::Object(
518                entries
519                    .iter()
520                    .map(|(key, value)| (key.clone(), Value::from(value)))
521                    .collect(),
522            ),
523        }
524    }
525}
526
527#[cfg(feature = "serde_json")]
528impl From<serde_json::Value> for Value {
529    fn from(value: serde_json::Value) -> Self {
530        Value::from(&value)
531    }
532}
533
534#[cfg(feature = "serde_json")]
535impl From<&Value> for serde_json::Value {
536    /// A fixture value as a serde_json one. `Undefined` becomes `null`,
537    /// and a number serde_json cannot hold (an infinity, NaN) becomes
538    /// `null` too, since that type has nowhere to put them.
539    fn from(value: &Value) -> Self {
540        match value {
541            Value::Undefined | Value::Null => serde_json::Value::Null,
542            Value::Bool(b) => serde_json::Value::Bool(*b),
543            Value::Number(n) => serde_json::Number::from_f64(*n)
544                .map(serde_json::Value::Number)
545                .unwrap_or(serde_json::Value::Null),
546            Value::String(s) => serde_json::Value::String(s.clone()),
547            Value::Array(items) => {
548                serde_json::Value::Array(items.iter().map(serde_json::Value::from).collect())
549            }
550            Value::Object(entries) => serde_json::Value::Object(
551                entries
552                    .iter()
553                    .map(|(key, value)| (key.clone(), serde_json::Value::from(value)))
554                    .collect(),
555            ),
556        }
557    }
558}