nx-value 0.11.0

The value a host passes to and reads from compiled NX: a JSON-like tree with JSON and MessagePack encodings.
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! NX value model for JSON-like object hierarchies.
//!
//! `NxValue` is intended to be a stable, serde-compatible data IR that can be used as input/output
//! across the NX API surface.

use std::collections::BTreeMap;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;

use serde::de::Error as _;
use serde::de::{MapAccess, SeqAccess, Visitor};
use serde::ser::{SerializeMap, SerializeSeq};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// A JSON-like tree value used as the stable NX API value type.
///
/// It is the Rust form of a canonical value, which `docs/nx-ir-format.md` (*Host values*) defines:
/// a host builds one and passes it as it is, whether it read the value from JSON or computed it,
/// and JSON and MessagePack are encodings of it for a wire or a store. It can hold nothing that is
/// not a canonical value, so a runtime given one has nothing to refuse for its kind.
///
/// Constant union cases are represented as [`NxValue::String`] carrying the bare authored case
/// name. The declaring union is recovered from the target schema (declared NX type, typed DTO
/// property, or other type annotation) at the point where the value is consumed; the IR itself
/// carries no in-payload union type wrapper.
///
/// NX has no null: its absent value is the empty sequence, [`NxValue::empty`]. [`NxValue::Null`]
/// is the host's spelling of absence, which NX reads as the empty value. NX writes it in two
/// places: an entry call's result whose type is a standalone `T?` and holds nothing, and a
/// present empty field of an update record — a cleared field — which is how key presence carries
/// "cleared" through JSON. An absent optional record field is an omitted key.
#[derive(Debug, Clone, PartialEq)]
pub enum NxValue {
    Bool(bool),
    Int32(i32),
    Int(i64),
    Float32(f32),
    Float(f64),
    /// String value.
    ///
    /// A string value may represent either a plain string or a constant union case. The two are
    /// distinguishable only against the target schema — a schema-less consumer cannot tell
    /// them apart from the payload alone.
    String(String),
    /// The host's `null`: JSON `null`, MessagePack `nil`. NX reads it as the empty value.
    Null,
    Array(Vec<NxValue>),
    /// Record value (ordered properties).
    ///
    /// When serialized to JSON, `type_name` is encoded as a `"$type"` string property if present.
    Record {
        type_name: Option<String>,
        properties: BTreeMap<String, NxValue>,
    },
}

impl NxValue {
    /// The empty value: the empty sequence, which is also the absent value.
    pub fn empty() -> Self {
        NxValue::Array(Vec::new())
    }

    /// True for the empty value, or for a host `null`, which NX reads as the empty value.
    pub fn is_empty_value(&self) -> bool {
        match self {
            NxValue::Null => true,
            NxValue::Array(elements) => elements.is_empty(),
            _ => false,
        }
    }

    /// Deserialize a value from a JSON string.
    pub fn from_json_str(source: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(source)
    }

    /// Deserialize a value from a JSON reader.
    pub fn from_json_reader<R: Read>(reader: R) -> Result<Self, serde_json::Error> {
        serde_json::from_reader(reader)
    }

    /// Deserialize a value from a JSON file.
    pub fn from_json_file(path: impl AsRef<Path>) -> Result<Self, NxValueIoError> {
        let file = File::open(path.as_ref())?;
        Ok(Self::from_json_reader(file)?)
    }

    /// Serialize a value to a compact JSON string.
    pub fn to_json_string(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// Serialize a value to a pretty JSON string.
    pub fn to_json_string_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Serialize a value to JSON using the provided writer.
    pub fn to_json_writer<W: Write>(&self, writer: W) -> Result<(), serde_json::Error> {
        serde_json::to_writer(writer, self)
    }

    /// Serialize a value to a JSON file (compact form).
    pub fn to_json_file(&self, path: impl AsRef<Path>) -> Result<(), NxValueIoError> {
        let mut file = File::create(path.as_ref())?;
        self.to_json_writer(&mut file)?;
        file.flush()?;
        Ok(())
    }

    /// Serialize a value to a JSON file (pretty form).
    pub fn to_json_file_pretty(&self, path: impl AsRef<Path>) -> Result<(), NxValueIoError> {
        let mut file = File::create(path.as_ref())?;
        let json = self.to_json_string_pretty()?;
        file.write_all(json.as_bytes())?;
        file.flush()?;
        Ok(())
    }

    /// Serialize a value to MessagePack bytes.
    pub fn to_msgpack_vec(&self) -> Result<Vec<u8>, rmp_serde::encode::Error> {
        rmp_serde::to_vec(self)
    }

    /// Deserialize a value from MessagePack bytes.
    pub fn from_msgpack_slice(bytes: &[u8]) -> Result<Self, rmp_serde::decode::Error> {
        rmp_serde::from_slice(bytes)
    }
}

impl Serialize for NxValue {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            NxValue::Bool(value) => serializer.serialize_bool(*value),
            NxValue::Int32(value) => serializer.serialize_i32(*value),
            NxValue::Int(value) => serializer.serialize_i64(*value),
            NxValue::Float32(value) => serializer.serialize_f32(*value),
            NxValue::Float(value) => serializer.serialize_f64(*value),
            NxValue::String(value) => serializer.serialize_str(value),
            NxValue::Null => serializer.serialize_unit(),
            NxValue::Array(elements) => {
                let mut seq = serializer.serialize_seq(Some(elements.len()))?;
                for element in elements {
                    seq.serialize_element(element)?;
                }
                seq.end()
            }
            NxValue::Record {
                type_name,
                properties,
            } => {
                let len = properties.len() + usize::from(type_name.is_some());
                let mut map = serializer.serialize_map(Some(len))?;

                if let Some(type_name) = type_name {
                    map.serialize_entry("$type", type_name)?;
                }

                for (key, value) in properties {
                    map.serialize_entry(key, value)?;
                }

                map.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for NxValue {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct NxValueVisitor;

        impl<'de> Visitor<'de> for NxValueVisitor {
            type Value = NxValue;

            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("a JSON-like value")
            }

            fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
                Ok(NxValue::Null)
            }

            fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> {
                Ok(NxValue::Null)
            }

            fn visit_bool<E: serde::de::Error>(self, v: bool) -> Result<Self::Value, E> {
                Ok(NxValue::Bool(v))
            }

            fn visit_i32<E: serde::de::Error>(self, v: i32) -> Result<Self::Value, E> {
                Ok(NxValue::Int32(v))
            }

            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Self::Value, E> {
                Ok(NxValue::Int(v))
            }

            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Self::Value, E> {
                if v <= i64::MAX as u64 {
                    Ok(NxValue::Int(v as i64))
                } else {
                    Ok(NxValue::Float(v as f64))
                }
            }

            fn visit_f32<E: serde::de::Error>(self, v: f32) -> Result<Self::Value, E> {
                Ok(NxValue::Float32(v))
            }

            fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<Self::Value, E> {
                Ok(NxValue::Float(v))
            }

            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
                Ok(NxValue::String(v.to_owned()))
            }

            fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value, E> {
                Ok(NxValue::String(v))
            }

            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
                let mut values = Vec::new();
                while let Some(value) = seq.next_element::<NxValue>()? {
                    values.push(value);
                }
                Ok(NxValue::Array(values))
            }

            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
                let mut type_name = None;
                let mut properties = BTreeMap::new();
                while let Some((key, value)) = map.next_entry::<String, NxValue>()? {
                    if key == "$type" {
                        match value {
                            NxValue::String(name) => {
                                type_name = Some(name);
                            }
                            other => {
                                return Err(A::Error::custom(format!(
                                    "expected \"$type\" to be a string, got {:?}",
                                    other
                                )));
                            }
                        }
                        continue;
                    }

                    properties.insert(key, value);
                }

                Ok(NxValue::Record {
                    type_name,
                    properties,
                })
            }
        }

        deserializer.deserialize_any(NxValueVisitor)
    }
}

/// Errors for JSON file IO helpers.
#[derive(Debug)]
pub enum NxValueIoError {
    Io(std::io::Error),
    Json(serde_json::Error),
}

impl std::fmt::Display for NxValueIoError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NxValueIoError::Io(e) => write!(f, "io error: {}", e),
            NxValueIoError::Json(e) => write!(f, "json error: {}", e),
        }
    }
}

impl std::error::Error for NxValueIoError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            NxValueIoError::Io(e) => Some(e),
            NxValueIoError::Json(e) => Some(e),
        }
    }
}

impl From<std::io::Error> for NxValueIoError {
    fn from(value: std::io::Error) -> Self {
        NxValueIoError::Io(value)
    }
}

impl From<serde_json::Error> for NxValueIoError {
    fn from(value: serde_json::Error) -> Self {
        NxValueIoError::Json(value)
    }
}

/// The README's example, compiled as a doc test.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;

pub mod color;
pub mod math;

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn json_round_trip_in_memory() {
        let mut obj = BTreeMap::new();
        obj.insert("a".to_string(), NxValue::Int(1));
        obj.insert("b".to_string(), NxValue::Bool(true));
        obj.insert(
            "c".to_string(),
            NxValue::Array(vec![NxValue::Int(2), NxValue::String("x".to_string())]),
        );

        let value = NxValue::Record {
            type_name: None,
            properties: obj,
        };
        let json = value.to_json_string().unwrap();
        let decoded = NxValue::from_json_str(&json).unwrap();
        assert_eq!(decoded, value);
    }

    #[test]
    fn json_round_trip_primitives() {
        let cases = [
            ("true", NxValue::Bool(true)),
            ("false", NxValue::Bool(false)),
            ("0", NxValue::Int(0)),
            ("-1", NxValue::Int(-1)),
            ("2.75", NxValue::Float(2.75)),
            ("\"hello\"", NxValue::String("hello".to_string())),
            ("[]", NxValue::Array(vec![])),
            (
                "{}",
                NxValue::Record {
                    type_name: None,
                    properties: BTreeMap::new(),
                },
            ),
        ];

        for (json, expected) in cases {
            let decoded = NxValue::from_json_str(json).unwrap();
            assert_eq!(decoded, expected);
            let encoded = decoded.to_json_string().unwrap();
            let decoded_again = NxValue::from_json_str(&encoded).unwrap();
            assert_eq!(decoded_again, expected);
        }
    }

    #[test]
    fn json_round_trip_nested_structures() {
        let value = NxValue::Record {
            type_name: None,
            properties: BTreeMap::from([
                (
                    "a".to_string(),
                    NxValue::Array(vec![NxValue::Int(1), NxValue::Int(2)]),
                ),
                (
                    "b".to_string(),
                    NxValue::Record {
                        type_name: None,
                        properties: BTreeMap::from([
                            ("x".to_string(), NxValue::Bool(false)),
                            ("y".to_string(), NxValue::empty()),
                        ]),
                    },
                ),
            ]),
        };

        let json = value.to_json_string().unwrap();
        let decoded = NxValue::from_json_str(&json).unwrap();
        assert_eq!(decoded, value);
    }

    /// The canonical encoding of an occurrence-typed value, row by row: `+` and `*` are arrays, a
    /// present `?` is its item, a host `null` decodes to [`NxValue::Null`], which NX reads as the
    /// empty value, and `Null` is written as `null`.
    #[test]
    fn json_encoding_of_occurrence_typed_values() {
        // `+` and `*` encode as arrays, the empty `*` as the empty array.
        assert_eq!(
            NxValue::Array(vec![NxValue::Int(1), NxValue::Int(2)])
                .to_json_string()
                .unwrap(),
            "[1,2]"
        );
        assert_eq!(NxValue::empty().to_json_string().unwrap(), "[]");
        // A present `?` is its item; an absent standalone `?` is `null`.
        assert_eq!(NxValue::Int(1).to_json_string().unwrap(), "1");
        assert_eq!(NxValue::Null.to_json_string().unwrap(), "null");
        // Host `null` and `[]` are both read as the empty value.
        assert_eq!(NxValue::from_json_str("null").unwrap(), NxValue::Null);
        assert_eq!(NxValue::from_json_str("[]").unwrap(), NxValue::empty());
        assert!(NxValue::from_json_str("null").unwrap().is_empty_value());
        // A missing key stays missing: an absent optional field is an omitted key.
        let book = NxValue::from_json_str(r#"{"$type":"Book","title":"A"}"#).unwrap();
        let NxValue::Record { properties, .. } = &book else {
            panic!("a record");
        };
        assert!(!properties.contains_key("author"));
        assert_eq!(
            book.to_json_string().unwrap(),
            r#"{"$type":"Book","title":"A"}"#
        );
        // A cleared update-record field is `Null`, and round-trips as `null`.
        let cleared = NxValue::Record {
            type_name: Some("Book.Update".to_string()),
            properties: BTreeMap::from([("author".to_string(), NxValue::Null)]),
        };
        assert_eq!(
            cleared.to_json_string().unwrap(),
            r#"{"$type":"Book.Update","author":null}"#
        );
        assert_eq!(
            NxValue::from_json_str(r#"{"$type":"Book.Update","author":null}"#).unwrap(),
            cleared
        );
        // The encoding is structural: an empty field encodes as it is stored.
        let plain = NxValue::Record {
            type_name: Some("Box".to_string()),
            properties: BTreeMap::from([("items".to_string(), NxValue::empty())]),
        };
        assert_eq!(
            plain.to_json_string().unwrap(),
            r#"{"$type":"Box","items":[]}"#
        );
    }

    #[test]
    fn msgpack_writes_null_as_nil() {
        let bytes = NxValue::Null.to_msgpack_vec().unwrap();
        assert_eq!(bytes, vec![0xc0]);
        assert_eq!(NxValue::from_msgpack_slice(&bytes).unwrap(), NxValue::Null);
    }

    #[test]
    fn json_round_trip_constant_case_as_bare_string() {
        let value = NxValue::String("active".to_string());

        let json = value.to_json_string().unwrap();
        assert_eq!(json, "\"active\"");
        let decoded = NxValue::from_json_str(&json).unwrap();
        assert_eq!(decoded, value);
    }

    #[test]
    fn json_parses_large_u64_as_float() {
        let value = NxValue::from_json_str("18446744073709551615").unwrap();
        assert!(matches!(value, NxValue::Float(_)));
    }

    #[test]
    fn json_number_boundaries() {
        let max_i64 = NxValue::from_json_str("9223372036854775807").unwrap();
        assert_eq!(max_i64, NxValue::Int(i64::MAX));

        let min_i64 = NxValue::from_json_str("-9223372036854775808").unwrap();
        assert_eq!(min_i64, NxValue::Int(i64::MIN));

        let just_over_max_i64 = NxValue::from_json_str("9223372036854775808").unwrap();
        assert!(matches!(just_over_max_i64, NxValue::Float(_)));
    }

    #[test]
    fn json_supports_exponent_notation() {
        let value = NxValue::from_json_str("1e3").unwrap();
        assert_eq!(value, NxValue::Float(1000.0));
    }

    #[test]
    fn json_preserves_negative_zero_sign() {
        let value = NxValue::from_json_str("-0.0").unwrap();
        match value {
            NxValue::Float(f) => {
                assert_eq!(f.to_bits(), (-0.0f64).to_bits());
            }
            _ => panic!("Expected float"),
        }
    }

    #[test]
    fn json_object_serialization_is_deterministic() {
        let mut obj = BTreeMap::new();
        obj.insert("b".to_string(), NxValue::Int(2));
        obj.insert("a".to_string(), NxValue::Int(1));

        let value = NxValue::Record {
            type_name: None,
            properties: obj,
        };
        let json = value.to_json_string().unwrap();
        assert_eq!(json, "{\"a\":1,\"b\":2}");
    }

    #[test]
    fn json_reader_writer_round_trip() {
        let value = NxValue::Array(vec![
            NxValue::String("x".to_string()),
            NxValue::Int(1),
            NxValue::Bool(false),
        ]);

        let mut buffer = Vec::new();
        value.to_json_writer(&mut buffer).unwrap();

        let decoded = NxValue::from_json_reader(Cursor::new(buffer)).unwrap();
        assert_eq!(decoded, value);
    }

    #[test]
    fn json_pretty_string_round_trip() {
        let value = NxValue::Record {
            type_name: None,
            properties: BTreeMap::from([(
                "a".to_string(),
                NxValue::Array(vec![NxValue::Int(1), NxValue::Int(2)]),
            )]),
        };

        let json = value.to_json_string_pretty().unwrap();
        let decoded = NxValue::from_json_str(&json).unwrap();
        assert_eq!(decoded, value);
    }

    #[test]
    fn json_invalid_input_errors() {
        assert!(NxValue::from_json_str("{]").is_err());
        assert!(NxValue::from_json_str("[1,]").is_err());
    }

    #[test]
    fn json_missing_file_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let missing = tmp.path().join("missing.json");

        let err = NxValue::from_json_file(&missing).unwrap_err();
        assert!(matches!(err, NxValueIoError::Io(_)));
    }

    #[test]
    fn json_file_helpers_round_trip() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("value.json");

        let mut obj = BTreeMap::new();
        obj.insert("name".to_string(), NxValue::String("Ada".to_string()));
        obj.insert("age".to_string(), NxValue::Int(42));
        let value = NxValue::Record {
            type_name: None,
            properties: obj,
        };

        value.to_json_file_pretty(&path).unwrap();
        let decoded = NxValue::from_json_file(&path).unwrap();
        assert_eq!(decoded, value);
    }

    #[test]
    fn msgpack_round_trip_in_memory() {
        let mut obj = BTreeMap::new();
        obj.insert("name".to_string(), NxValue::String("Ada".to_string()));
        obj.insert("age".to_string(), NxValue::Int(42));

        let value = NxValue::Record {
            type_name: Some("User".to_string()),
            properties: obj,
        };

        let bytes = value.to_msgpack_vec().unwrap();
        let decoded = NxValue::from_msgpack_slice(&bytes).unwrap();
        assert_eq!(decoded, value);
    }

    #[test]
    fn msgpack_round_trip_constant_case_as_bare_string() {
        let value = NxValue::String("active".to_string());

        let bytes = value.to_msgpack_vec().unwrap();
        let decoded = NxValue::from_msgpack_slice(&bytes).unwrap();
        assert_eq!(decoded, value);
    }

    #[test]
    fn int32_round_trip_msgpack() {
        let value = NxValue::Int32(42);
        let bytes = value.to_msgpack_vec().unwrap();
        let decoded = NxValue::from_msgpack_slice(&bytes).unwrap();
        // MessagePack may widen small integers; the value should be numerically equal
        match decoded {
            NxValue::Int32(n) => assert_eq!(n, 42),
            NxValue::Int(n) => assert_eq!(n, 42),
            other => panic!("Expected integer, got {:?}", other),
        }
    }

    #[test]
    fn float32_serializes_to_json() {
        let value = NxValue::Float32(2.75);
        let json = value.to_json_string().unwrap();
        // JSON serializes f32 as a number
        let decoded = NxValue::from_json_str(&json).unwrap();
        // JSON always deserializes as f64, so we get Float back
        assert!(matches!(decoded, NxValue::Float(_)));
    }

    #[test]
    fn int32_serializes_to_json() {
        let value = NxValue::Int32(42);
        let json = value.to_json_string().unwrap();
        assert_eq!(json, "42");
        // JSON always deserializes integers via visit_i64/visit_u64
        let decoded = NxValue::from_json_str(&json).unwrap();
        assert_eq!(decoded, NxValue::Int(42));
    }
}

#[cfg(test)]
mod color_corpus_tests;