jsonx 0.1.0

A serde-enabled implementation of the JSONX extended-JSON format: typed value constructors, unquoted keys, and trailing commas.
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
//! A dynamically-typed JSONX value tree.

use std::borrow::Cow;
#[cfg(not(feature = "preserve_order"))]
use std::collections::BTreeMap;
use std::fmt;
use std::net::{IpAddr, SocketAddr};

#[cfg(feature = "preserve_order")]
use indexmap::IndexMap;
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::datetime::DateTime;
use crate::tokens::{
    strip_ctor, TOKEN_CTOR, TOKEN_DATETIME, TOKEN_INT, TOKEN_IP, TOKEN_IPPORT, TOKEN_UINT,
};

/// A JSONX object.
///
/// By default this is a sorted [`std::collections::BTreeMap`], giving
/// deterministic, input-order-independent output. Enable the `preserve_order`
/// feature to back it with `indexmap::IndexMap` instead, which keeps keys in
/// insertion order (matching common JSON/YAML/TOML encoders).
#[cfg(not(feature = "preserve_order"))]
pub type Map = BTreeMap<String, Value>;

/// A JSONX object, backed by [`indexmap::IndexMap`] so keys keep their insertion
/// order (the `preserve_order` feature is enabled).
#[cfg(feature = "preserve_order")]
pub type Map = IndexMap<String, Value>;

/// A dynamically-typed JSONX value.
///
/// Plain JSON numbers always decode to [`Value::Number`] (an `f64`), matching
/// the JSONX reference implementation. The remaining variants correspond to
/// JSONX's extended `type(value)` constructors.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    /// `null`
    Null,
    /// `true` / `false`
    Bool(bool),
    /// A plain JSON number (always an `f64`).
    Number(f64),
    /// A string.
    String(String),
    /// An array.
    Array(Vec<Value>),
    /// An object (keys are kept sorted).
    Object(Map),

    /// `int(...)` — a machine-width signed integer.
    Int(i64),
    /// `uint(...)` — a machine-width unsigned integer.
    Uint(u64),
    /// `int8(...)`
    Int8(i8),
    /// `int16(...)`
    Int16(i16),
    /// `int32(...)`
    Int32(i32),
    /// `int64(...)`
    Int64(i64),
    /// `uint8(...)`
    Uint8(u8),
    /// `uint16(...)`
    Uint16(u16),
    /// `uint32(...)`
    Uint32(u32),
    /// `uint64(...)`
    Uint64(u64),

    /// `datetime("...")`
    DateTime(DateTime),
    /// `ip("...")`
    Ip(IpAddr),
    /// `ipport("...")`
    IpPort(SocketAddr),
    /// `bytes("...")` — raw bytes (the Base64 is decoded on parse).
    Bytes(Vec<u8>),

    /// A constructor not built into JSONX, e.g. `duration("5s")` or
    /// `ipnet("10.0.0.0/8")`.
    ///
    /// JSONX is open — `name(value)` is just a function call — so the dynamic
    /// `Value` path captures any unrecognized constructor here instead of
    /// failing. This lets generic consumers pass through, inspect, and re-emit
    /// custom constructors losslessly. (Typed targets still drive the built-in
    /// and derived constructors directly; this variant is only produced by the
    /// dynamic path.)
    Constructor {
        /// The constructor name (a JSONX identifier), e.g. `"duration"`.
        name: String,
        /// The constructor argument, parsed as a nested value.
        arg: Box<Value>,
    },
}

impl Value {
    /// Returns `true` if the value is `null`.
    pub fn is_null(&self) -> bool {
        matches!(self, Value::Null)
    }

    /// Returns the string contents if this is a [`Value::String`].
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Value::String(s) => Some(s),
            _ => None,
        }
    }

    /// Returns the boolean if this is a [`Value::Bool`].
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Returns the value as an `f64` if it is any numeric variant.
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Value::Number(n) => Some(*n),
            Value::Int(n) | Value::Int64(n) => Some(*n as f64),
            Value::Uint(n) | Value::Uint64(n) => Some(*n as f64),
            Value::Int8(n) => Some(*n as f64),
            Value::Int16(n) => Some(*n as f64),
            Value::Int32(n) => Some(*n as f64),
            Value::Uint8(n) => Some(*n as f64),
            Value::Uint16(n) => Some(*n as f64),
            Value::Uint32(n) => Some(*n as f64),
            _ => None,
        }
    }

    /// Returns the value as an `i64` if it is an integer variant that fits.
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Value::Int(n) | Value::Int64(n) => Some(*n),
            Value::Int8(n) => Some(*n as i64),
            Value::Int16(n) => Some(*n as i64),
            Value::Int32(n) => Some(*n as i64),
            Value::Uint8(n) => Some(*n as i64),
            Value::Uint16(n) => Some(*n as i64),
            Value::Uint32(n) => Some(*n as i64),
            Value::Uint(n) | Value::Uint64(n) => i64::try_from(*n).ok(),
            _ => None,
        }
    }

    /// Returns the array elements if this is a [`Value::Array`].
    pub fn as_array(&self) -> Option<&[Value]> {
        match self {
            Value::Array(a) => Some(a),
            _ => None,
        }
    }

    /// Returns the object map if this is a [`Value::Object`].
    pub fn as_object(&self) -> Option<&Map> {
        match self {
            Value::Object(m) => Some(m),
            _ => None,
        }
    }

    /// Looks up a value by key (objects) or by index expressed as a string is
    /// not supported here; use [`Value::get_index`] for arrays.
    pub fn get(&self, key: &str) -> Option<&Value> {
        match self {
            Value::Object(m) => m.get(key),
            _ => None,
        }
    }

    /// Looks up an array element by index.
    pub fn get_index(&self, index: usize) -> Option<&Value> {
        match self {
            Value::Array(a) => a.get(index),
            _ => None,
        }
    }

    /// Builds a [`Value::Constructor`] for a custom `name(value)` constructor.
    ///
    /// `name` must be a valid JSONX identifier — a leading ASCII letter or `_`,
    /// then ASCII alphanumerics or `_`. A name that isn't (e.g. `"bad name"`,
    /// `"3lead"`, `"with-dash"`) has no round-trippable JSONX form, so
    /// serializing it returns an error; in debug builds this constructor also
    /// asserts the name eagerly so the mistake surfaces at the call site.
    ///
    /// ```
    /// use jsonx::Value;
    /// let v = Value::constructor("duration", "5s");
    /// assert_eq!(jsonx::to_string(&v).unwrap(), r#"duration("5s")"#);
    /// ```
    pub fn constructor(name: impl Into<String>, arg: impl Into<Value>) -> Value {
        let name = name.into();
        debug_assert!(
            crate::tokens::is_ident(&name),
            "constructor name {name:?} is not a valid JSONX identifier; \
             it cannot be serialized to round-trippable JSONX"
        );
        Value::Constructor {
            name,
            arg: Box::new(arg.into()),
        }
    }

    /// Builds an `int(...)` value — the machine-width signed integer.
    ///
    /// Note that `From<i64>` produces [`Value::Int64`] (the explicitly-sized
    /// variant) instead; use this for the machine-width `int` form.
    pub fn int(n: i64) -> Value {
        Value::Int(n)
    }

    /// Builds a `uint(...)` value — the machine-width unsigned integer.
    ///
    /// Note that `From<u64>` produces [`Value::Uint64`] instead; use this for
    /// the machine-width `uint` form.
    pub fn uint(n: u64) -> Value {
        Value::Uint(n)
    }

    /// Builds a `bytes("...")` value from a byte buffer.
    ///
    /// There is intentionally no `From<Vec<u8>>` for [`Value`]: a byte vector is
    /// ambiguous between a `bytes(...)` blob and an array of integers, so the
    /// choice is made explicit here.
    pub fn bytes(b: impl Into<Vec<u8>>) -> Value {
        Value::Bytes(b.into())
    }

    /// Builds a string value.
    pub fn string(s: impl Into<String>) -> Value {
        Value::String(s.into())
    }

    /// Returns the canonical text that appears inside the parentheses of this
    /// value's JSONX constructor form, or `None` for values that don't render as
    /// a constructor (`null`, booleans, bare numbers, strings, arrays, objects).
    ///
    /// This yields the exact argument `jsonx` would emit — the RFC 3339 string
    /// for [`Value::DateTime`], the Base64 for [`Value::Bytes`], the decimal for
    /// the integer variants, the address for [`Value::Ip`] / [`Value::IpPort`] —
    /// without rendering and re-parsing the whole `name(...)` wrapper. For a
    /// custom [`Value::Constructor`] it returns a string argument directly, or
    /// the JSONX rendering of a non-string argument.
    ///
    /// ```
    /// use jsonx::Value;
    /// let v: Value = jsonx::from_str(r#"datetime("2017-12-25T15:00:00Z")"#).unwrap();
    /// assert_eq!(v.to_jsonx_arg().as_deref(), Some("2017-12-25T15:00:00Z"));
    /// assert_eq!(Value::Null.to_jsonx_arg(), None);
    /// ```
    pub fn to_jsonx_arg(&self) -> Option<String> {
        Some(match self {
            Value::Int(n) | Value::Int64(n) => n.to_string(),
            Value::Uint(n) | Value::Uint64(n) => n.to_string(),
            Value::Int8(n) => n.to_string(),
            Value::Int16(n) => n.to_string(),
            Value::Int32(n) => n.to_string(),
            Value::Uint8(n) => n.to_string(),
            Value::Uint16(n) => n.to_string(),
            Value::Uint32(n) => n.to_string(),
            Value::DateTime(dt) => crate::datetime::to_jsonx_string(dt),
            Value::Ip(ip) => ip.to_string(),
            Value::IpPort(sa) => sa.to_string(),
            Value::Bytes(b) => crate::base64::encode(b),
            Value::Constructor { arg, .. } => match arg.as_str() {
                Some(s) => s.to_owned(),
                None => crate::ser::to_string(arg).ok()?,
            },
            _ => return None,
        })
    }
}

macro_rules! impl_from {
    ($($ty:ty => $variant:ident),* $(,)?) => {
        $(impl From<$ty> for Value {
            fn from(v: $ty) -> Value { Value::$variant(v) }
        })*
    };
}

impl_from! {
    bool => Bool,
    f64 => Number,
    String => String,
    Vec<Value> => Array,
    Map => Object,
    i8 => Int8,
    i16 => Int16,
    i32 => Int32,
    u8 => Uint8,
    u16 => Uint16,
    u32 => Uint32,
    DateTime => DateTime,
    IpAddr => Ip,
    SocketAddr => IpPort,
}

impl From<&str> for Value {
    fn from(v: &str) -> Value {
        Value::String(v.to_owned())
    }
}

// `From<i64>`/`From<u64>` map to the explicitly-sized 64-bit variants. For the
// machine-width `int`/`uint` constructors use [`Value::int`] / [`Value::uint`].
impl From<i64> for Value {
    fn from(v: i64) -> Value {
        Value::Int64(v)
    }
}

impl From<u64> for Value {
    fn from(v: u64) -> Value {
        Value::Uint64(v)
    }
}

impl<T: Into<Value>> From<Option<T>> for Value {
    fn from(v: Option<T>) -> Value {
        match v {
            Some(v) => v.into(),
            None => Value::Null,
        }
    }
}

impl fmt::Display for Value {
    /// Renders the value as compact JSONX. Falls back to `null` if the value
    /// cannot be encoded (e.g. it contains a non-finite float).
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match crate::ser::to_string(self) {
            Ok(s) => f.write_str(&s),
            Err(_) => f.write_str("null"),
        }
    }
}

impl Serialize for Value {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Value::Null => serializer.serialize_unit(),
            Value::Bool(b) => serializer.serialize_bool(*b),
            Value::Number(n) => serializer.serialize_f64(*n),
            Value::String(s) => serializer.serialize_str(s),
            Value::Array(a) => a.serialize(serializer),
            Value::Object(m) => {
                let mut map = serializer.serialize_map(Some(m.len()))?;
                for (k, v) in m {
                    map.serialize_entry(k, v)?;
                }
                map.end()
            }
            Value::Int(n) => serializer.serialize_newtype_struct(TOKEN_INT, n),
            Value::Uint(n) => serializer.serialize_newtype_struct(TOKEN_UINT, n),
            Value::Int8(n) => serializer.serialize_i8(*n),
            Value::Int16(n) => serializer.serialize_i16(*n),
            Value::Int32(n) => serializer.serialize_i32(*n),
            Value::Int64(n) => serializer.serialize_i64(*n),
            Value::Uint8(n) => serializer.serialize_u8(*n),
            Value::Uint16(n) => serializer.serialize_u16(*n),
            Value::Uint32(n) => serializer.serialize_u32(*n),
            Value::Uint64(n) => serializer.serialize_u64(*n),
            Value::DateTime(dt) => serializer
                .serialize_newtype_struct(TOKEN_DATETIME, &crate::datetime::to_jsonx_string(dt)),
            Value::Ip(ip) => serializer.serialize_newtype_struct(TOKEN_IP, &ip.to_string()),
            Value::IpPort(sa) => serializer.serialize_newtype_struct(TOKEN_IPPORT, &sa.to_string()),
            Value::Bytes(b) => serializer.serialize_bytes(b),
            Value::Constructor { name, arg } => {
                serializer.serialize_newtype_struct(TOKEN_CTOR, &GenericCtor { name, arg })
            }
        }
    }
}

/// Serialization shim for [`Value::Constructor`]. The constructor name is
/// dynamic, so it cannot ride serde's `&'static` newtype-struct name like the
/// built-in tokens do. Instead it travels as a single-entry map `{name: arg}`:
/// our serializer recognizes the [`TOKEN_CTOR`] wrapper and emits `name(arg)`,
/// while every other serde format degrades gracefully to the map form.
struct GenericCtor<'a> {
    name: &'a str,
    arg: &'a Value,
}

impl Serialize for GenericCtor<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(1))?;
        map.serialize_entry(self.name, self.arg)?;
        map.end()
    }
}

impl<'de> Deserialize<'de> for Value {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Value, D::Error> {
        deserializer.deserialize_any(ValueVisitor)
    }
}

struct ValueVisitor;

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

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("any valid JSONX value")
    }

    fn visit_bool<E>(self, v: bool) -> Result<Value, E> {
        Ok(Value::Bool(v))
    }

    fn visit_i8<E>(self, v: i8) -> Result<Value, E> {
        Ok(Value::Int8(v))
    }
    fn visit_i16<E>(self, v: i16) -> Result<Value, E> {
        Ok(Value::Int16(v))
    }
    fn visit_i32<E>(self, v: i32) -> Result<Value, E> {
        Ok(Value::Int32(v))
    }
    fn visit_i64<E>(self, v: i64) -> Result<Value, E> {
        Ok(Value::Int64(v))
    }
    fn visit_i128<E>(self, v: i128) -> Result<Value, E> {
        Ok(i64::try_from(v).map_or(Value::Number(v as f64), Value::Int64))
    }

    fn visit_u8<E>(self, v: u8) -> Result<Value, E> {
        Ok(Value::Uint8(v))
    }
    fn visit_u16<E>(self, v: u16) -> Result<Value, E> {
        Ok(Value::Uint16(v))
    }
    fn visit_u32<E>(self, v: u32) -> Result<Value, E> {
        Ok(Value::Uint32(v))
    }
    fn visit_u64<E>(self, v: u64) -> Result<Value, E> {
        Ok(Value::Uint64(v))
    }
    fn visit_u128<E>(self, v: u128) -> Result<Value, E> {
        Ok(u64::try_from(v).map_or(Value::Number(v as f64), Value::Uint64))
    }

    fn visit_f32<E>(self, v: f32) -> Result<Value, E> {
        Ok(Value::Number(v as f64))
    }
    fn visit_f64<E>(self, v: f64) -> Result<Value, E> {
        Ok(Value::Number(v))
    }

    fn visit_str<E>(self, v: &str) -> Result<Value, E> {
        Ok(Value::String(v.to_owned()))
    }
    fn visit_string<E>(self, v: String) -> Result<Value, E> {
        Ok(Value::String(v))
    }
    fn visit_char<E>(self, v: char) -> Result<Value, E> {
        Ok(Value::String(v.to_string()))
    }

    fn visit_bytes<E>(self, v: &[u8]) -> Result<Value, E> {
        Ok(Value::Bytes(v.to_vec()))
    }
    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Value, E> {
        Ok(Value::Bytes(v))
    }

    fn visit_none<E>(self) -> Result<Value, E> {
        Ok(Value::Null)
    }
    fn visit_unit<E>(self) -> Result<Value, E> {
        Ok(Value::Null)
    }
    fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
        Value::deserialize(deserializer)
    }
    fn visit_newtype_struct<D: Deserializer<'de>>(
        self,
        deserializer: D,
    ) -> Result<Value, D::Error> {
        Value::deserialize(deserializer)
    }

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

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Value, A::Error> {
        // The first key may be one of our private tokens, in which case the map
        // is actually a smuggled extended type (see `crate::tokens`). Read it as
        // a `Cow` so the (borrowed) sentinel costs no allocation; a real object
        // key is only copied into the map below, exactly as before.
        let Some(first_key) = map.next_key::<Cow<str>>()? else {
            return Ok(Value::Object(Map::new()));
        };

        match first_key.as_ref() {
            TOKEN_INT => return Ok(Value::Int(map.next_value()?)),
            TOKEN_UINT => return Ok(Value::Uint(map.next_value()?)),
            TOKEN_DATETIME => {
                let s: String = map.next_value()?;
                let dt = crate::datetime::parse(&s).map_err(de::Error::custom)?;
                return Ok(Value::DateTime(dt));
            }
            TOKEN_IP => {
                let s: String = map.next_value()?;
                let ip = s.parse::<IpAddr>().map_err(de::Error::custom)?;
                return Ok(Value::Ip(ip));
            }
            TOKEN_IPPORT => {
                let s: String = map.next_value()?;
                let sa = s.parse::<SocketAddr>().map_err(de::Error::custom)?;
                return Ok(Value::IpPort(sa));
            }
            // A dynamic-named constructor smuggled out of `deserialize_any`
            // (the built-in tokens above were checked first, so this only
            // catches user constructors).
            sentinel => {
                if let Some(name) = strip_ctor(sentinel) {
                    let arg: Value = map.next_value()?;
                    return Ok(Value::Constructor {
                        name: name.to_owned(),
                        arg: Box::new(arg),
                    });
                }
            }
        }

        let mut object = Map::new();
        let first_value: Value = map.next_value()?;
        object.insert(first_key.into_owned(), first_value);
        while let Some((k, v)) = map.next_entry()? {
            object.insert(k, v);
        }
        Ok(Value::Object(object))
    }
}