Skip to main content

c4/
value.rs

1//! The dynamic config value: the [`Value`] enum, its accessors and its
2//! serde bridges. `Value::format_id` names the parser a value came from
3//! (shown by traces); typed variants beyond JSON's set (datetime, IPs,
4//! MACs, …) are produced by the feature-gated table value parsers.
5
6use std::collections::BTreeMap;
7
8/// Dynamic config value.
9///
10/// Non-exhaustive: new variants may come without a breaking release, so
11/// a `match` needs a `_` arm.
12#[derive(Debug, Clone, PartialEq)]
13#[non_exhaustive]
14pub enum Value {
15    Null,
16    Bool(bool),
17    Int(i64),
18    Uint(u64),
19    /// 128-bit signed — only from the table `i128` type (never `auto`,
20    /// which stops at `i64`/`u64`/`f64`). Serializes as a plain number
21    /// when it fits `i64` or `u64`, otherwise as its decimal **string**
22    /// (JSON has no wider integer); [`format_id`](Value::format_id) still reports
23    /// `i128`.
24    Int128(i128),
25    /// 128-bit unsigned — only from the table `u128` type. Serializes as
26    /// a plain number when it fits `u64`, otherwise as its decimal
27    /// **string**; [`format_id`](Value::format_id) still reports `u128`.
28    Uint128(u128),
29    Float(f64),
30    String(String),
31    /// An RFC 3339-style date or datetime, kept as its text. Produced by
32    /// toml datetime literals, the table `dt` type and the `auto` guess —
33    /// all gated by the `datetime` feature. Serializes as the string itself (so
34    /// a serialize→deserialize round trip through a format without a
35    /// datetime type yields a `String`).
36    DateTime(String),
37    /// `YYYY-MM-DD`, kept as its text (table `date` type, `date` feature).
38    Date(String),
39    /// `hh:mm:ss[.fraction]`, kept as its text (table `time` type, `time`
40    /// feature).
41    Time(String),
42    /// An IPv4 address, kept as its validated **canonical** text (table
43    /// `ipv4` type, `ipv4` feature) — text like every typed value, so
44    /// [`as_str`](Value::as_str) works; [`as_ip`](Value::as_ip) gives the
45    /// address. The `inet` type (`inet` feature) also produces this or
46    /// [`Value::Ipv6`], whichever family parses.
47    Ipv4(String),
48    /// An IPv6 address, kept as its validated canonical text
49    /// (`2001:0DB8::1` → `2001:db8::1`; table `ipv6` type, `ipv6` feature).
50    Ipv6(String),
51    /// A host address **with a netmask** (`10.0.0.1/24`), kept as its
52    /// validated text — PostgreSQL `inet` semantics, host bits below the
53    /// mask may be set (table `inet` type, `inet` feature; a bare `inet`
54    /// address maps onto [`Value::Ipv4`]/[`Value::Ipv6`] instead).
55    Inet(String),
56    /// A network — optional netmask defaulting to the full address
57    /// length, host bits below the mask must be zero — kept as its
58    /// validated text; PostgreSQL `cidr` semantics (table `cidr` type,
59    /// `cidr` feature).
60    Cidr(String),
61    /// 6-byte MAC address, kept as its validated text (table `macaddr`
62    /// type, `macaddr` feature).
63    MacAddr(String),
64    /// 8-byte MAC address, kept as its validated text (table `macaddr8`
65    /// type, `macaddr8` feature).
66    MacAddr8(String),
67    /// Hyphenated `8-4-4-4-12` UUID, kept as its validated text (table
68    /// `uuid` type, `uuid` feature).
69    Uuid(String),
70    Array(Vec<Value>),
71    Object(BTreeMap<String, Value>),
72}
73
74static NULL: Value = Value::Null;
75
76impl Value {
77    /// Object member by key; `None` when this is not an object or the key
78    /// is absent.
79    pub fn get(&self, key: &str) -> Option<&Value> {
80        match self {
81            Value::Object(map) => map.get(key),
82            _ => None,
83        }
84    }
85
86    /// Array element by index; `None` when this is not an array or the
87    /// index is out of bounds.
88    pub fn get_index(&self, index: usize) -> Option<&Value> {
89        match self {
90            Value::Array(items) => items.get(index),
91            _ => None,
92        }
93    }
94
95    pub fn is_null(&self) -> bool {
96        matches!(self, Value::Null)
97    }
98
99    pub fn as_bool(&self) -> Option<bool> {
100        match self {
101            Value::Bool(b) => Some(*b),
102            _ => None,
103        }
104    }
105
106    pub fn as_i64(&self) -> Option<i64> {
107        match self {
108            Value::Int(i) => Some(*i),
109            Value::Uint(u) => i64::try_from(*u).ok(),
110            Value::Int128(i) => i64::try_from(*i).ok(),
111            Value::Uint128(u) => i64::try_from(*u).ok(),
112            _ => None,
113        }
114    }
115
116    pub fn as_u64(&self) -> Option<u64> {
117        match self {
118            Value::Uint(u) => Some(*u),
119            Value::Int(i) => u64::try_from(*i).ok(),
120            Value::Int128(i) => u64::try_from(*i).ok(),
121            Value::Uint128(u) => u64::try_from(*u).ok(),
122            _ => None,
123        }
124    }
125
126    /// Any integer value as an `i128`.
127    pub fn as_i128(&self) -> Option<i128> {
128        match self {
129            Value::Int(i) => Some(i128::from(*i)),
130            Value::Uint(u) => Some(i128::from(*u)),
131            Value::Int128(i) => Some(*i),
132            Value::Uint128(u) => i128::try_from(*u).ok(),
133            _ => None,
134        }
135    }
136
137    /// Any integer value as a `u128`.
138    pub fn as_u128(&self) -> Option<u128> {
139        match self {
140            Value::Uint(u) => Some(u128::from(*u)),
141            Value::Int(i) => u128::try_from(*i).ok(),
142            Value::Int128(i) => u128::try_from(*i).ok(),
143            Value::Uint128(u) => Some(*u),
144            _ => None,
145        }
146    }
147
148    /// Any numeric value as a float.
149    pub fn as_f64(&self) -> Option<f64> {
150        match self {
151            Value::Float(f) => Some(*f),
152            Value::Int(i) => Some(*i as f64),
153            Value::Uint(u) => Some(*u as f64),
154            Value::Int128(i) => Some(*i as f64),
155            Value::Uint128(u) => Some(*u as f64),
156            _ => None,
157        }
158    }
159
160    /// The text of a string — or of any typed value (datetime, IP, MAC,
161    /// uuid, …), which all keep their text form.
162    pub fn as_str(&self) -> Option<&str> {
163        match self {
164            Value::String(s)
165            | Value::DateTime(s)
166            | Value::Date(s)
167            | Value::Time(s)
168            | Value::Ipv4(s)
169            | Value::Ipv6(s)
170            | Value::Inet(s)
171            | Value::Cidr(s)
172            | Value::MacAddr(s)
173            | Value::MacAddr8(s)
174            | Value::Uuid(s) => Some(s),
175            _ => None,
176        }
177    }
178
179    /// Convert this value into any serde type, with the same rules as
180    /// [`Loader::load`](crate::Loader::load): strings coerce into numbers
181    /// and bools (and back), and an error names the key path. It consumes
182    /// the value; take one section of a loaded config with `.clone()`:
183    ///
184    /// ```
185    /// #[derive(serde::Deserialize)]
186    /// struct Db {
187    ///     port: u16,
188    /// }
189    ///
190    /// # fn main() -> Result<(), c4::Error> {
191    /// let config = c4::Value::from(std::collections::BTreeMap::from([(
192    ///     "db".to_owned(),
193    ///     c4::Value::from(std::collections::BTreeMap::from([(
194    ///         "port".to_owned(),
195    ///         c4::Value::from("5432"),
196    ///     )])),
197    /// )]));
198    /// let db: Db = config["db"].clone().into_typed()?;
199    /// assert_eq!(db.port, 5432);
200    /// # Ok(())
201    /// # }
202    /// ```
203    pub fn into_typed<T: serde::de::DeserializeOwned>(self) -> crate::Result<T> {
204        T::deserialize(crate::de::ValueDeserializer::new(self))
205            .map_err(|e| crate::Error::Deserialize(e.to_string()))
206    }
207
208    /// The address of an [`Ipv4`](Value::Ipv4) or [`Ipv6`](Value::Ipv6)
209    /// value; `None` for anything else, a string that looks like one
210    /// included.
211    pub fn as_ip(&self) -> Option<std::net::IpAddr> {
212        match self {
213            Value::Ipv4(s) | Value::Ipv6(s) => s.parse().ok(),
214            _ => None,
215        }
216    }
217
218    /// The format id of this value — which parser produced it: `null`,
219    /// `bool`, `i64`, `u64`, `i128`, `u128`, `f64`, `str`, the typed ids (`dt`, `date`,
220    /// `time`, `ipv4`, `ipv6`, `cidr`, `macaddr`, `macaddr8`, `uuid`),
221    /// `arr:<t>` for homogeneous scalar arrays, `arr` for other arrays,
222    /// `object` for objects. Integer widths normalize to the stored type
223    /// (an `i8` cell stores an `i64`, so it reports `i64`), and `inet`
224    /// reports as the family it parsed into. Shown by `trace()` as the
225    /// `format` field of every serialized leaf.
226    pub fn format_id(&self) -> std::borrow::Cow<'static, str> {
227        use std::borrow::Cow;
228        Cow::Borrowed(match self {
229            Value::Null => "null",
230            Value::Bool(_) => "bool",
231            Value::Int(_) => "i64",
232            Value::Uint(_) => "u64",
233            Value::Int128(_) => "i128",
234            Value::Uint128(_) => "u128",
235            Value::Float(_) => "f64",
236            Value::String(_) => "str",
237            Value::DateTime(_) => "dt",
238            Value::Date(_) => "date",
239            Value::Time(_) => "time",
240            Value::Ipv4(_) => "ipv4",
241            Value::Ipv6(_) => "ipv6",
242            Value::Inet(_) => "inet",
243            Value::Cidr(_) => "cidr",
244            Value::MacAddr(_) => "macaddr",
245            Value::MacAddr8(_) => "macaddr8",
246            Value::Uuid(_) => "uuid",
247            Value::Object(_) => "object",
248            Value::Array(items) => {
249                let mut ids = items.iter().map(Value::format_id);
250                return match ids.next() {
251                    Some(first)
252                        if first != "object"
253                            && !first.starts_with("arr")
254                            && ids.all(|id| id == first) =>
255                    {
256                        Cow::Owned(format!("arr:{first}"))
257                    }
258                    _ => Cow::Borrowed("arr"),
259                };
260            }
261        })
262    }
263
264    pub fn as_array(&self) -> Option<&Vec<Value>> {
265        match self {
266            Value::Array(items) => Some(items),
267            _ => None,
268        }
269    }
270
271    pub fn as_object(&self) -> Option<&BTreeMap<String, Value>> {
272        match self {
273            Value::Object(map) => Some(map),
274            _ => None,
275        }
276    }
277}
278
279/// `value["key"]` — yields `Value::Null` for missing keys or non-objects,
280/// so lookups chain without panicking: `value["db"]["port"].as_u64()`.
281// Conversions into a `Value`, for custom formats, tests and overrides.
282macro_rules! from_scalar {
283    ($($ty:ty => $variant:ident via $conv:ty),* $(,)?) => {$(
284        impl From<$ty> for Value {
285            fn from(v: $ty) -> Value {
286                Value::$variant(<$conv>::from(v))
287            }
288        }
289    )*};
290}
291
292from_scalar! {
293    bool => Bool via bool,
294    i8 => Int via i64, i16 => Int via i64, i32 => Int via i64, i64 => Int via i64,
295    u8 => Uint via u64, u16 => Uint via u64, u32 => Uint via u64, u64 => Uint via u64,
296    i128 => Int128 via i128, u128 => Uint128 via u128,
297    f32 => Float via f64, f64 => Float via f64,
298    String => String via String,
299}
300
301impl From<&str> for Value {
302    fn from(v: &str) -> Value {
303        Value::String(v.to_owned())
304    }
305}
306
307impl<T: Into<Value>> From<Option<T>> for Value {
308    /// `None` is [`Value::Null`].
309    fn from(v: Option<T>) -> Value {
310        v.map_or(Value::Null, Into::into)
311    }
312}
313
314impl<T: Into<Value>> From<Vec<T>> for Value {
315    fn from(v: Vec<T>) -> Value {
316        Value::Array(v.into_iter().map(Into::into).collect())
317    }
318}
319
320impl From<BTreeMap<String, Value>> for Value {
321    fn from(v: BTreeMap<String, Value>) -> Value {
322        Value::Object(v)
323    }
324}
325
326// Comparisons with plain values, both ways, through the `as_*` accessors:
327// text matches any typed text, integers match across widths, and a float
328// matches any number.
329macro_rules! eq_via {
330    ($($ty:ty => |$v:ident, $o:ident| $cmp:expr),* $(,)?) => {$(
331        impl PartialEq<$ty> for Value {
332            fn eq(&self, other: &$ty) -> bool {
333                let ($v, $o) = (self, other);
334                $cmp
335            }
336        }
337        impl PartialEq<Value> for $ty {
338            fn eq(&self, other: &Value) -> bool {
339                other == self
340            }
341        }
342    )*};
343}
344
345eq_via! {
346    str => |v, o| v.as_str() == Some(o),
347    &str => |v, o| v.as_str() == Some(*o),
348    String => |v, o| v.as_str() == Some(o.as_str()),
349    bool => |v, o| v.as_bool() == Some(*o),
350    i32 => |v, o| v.as_i128() == Some(i128::from(*o)),
351    i64 => |v, o| v.as_i128() == Some(i128::from(*o)),
352    u32 => |v, o| v.as_i128() == Some(i128::from(*o)),
353    u64 => |v, o| v.as_i128() == Some(i128::from(*o)),
354    f64 => |v, o| v.as_f64() == Some(*o),
355}
356
357/// Compact JSON: typed values print as their text, non-finite floats as
358/// `null` (like any JSON serializer). Use [`Value::as_str`] for a string's
359/// raw text.
360impl std::fmt::Display for Value {
361    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
362        fn text(f: &mut std::fmt::Formatter<'_>, s: &str) -> std::fmt::Result {
363            f.write_str("\"")?;
364            for c in s.chars() {
365                match c {
366                    '"' => f.write_str("\\\"")?,
367                    '\\' => f.write_str("\\\\")?,
368                    '\n' => f.write_str("\\n")?,
369                    '\r' => f.write_str("\\r")?,
370                    '\t' => f.write_str("\\t")?,
371                    c if c < ' ' => write!(f, "\\u{:04x}", c as u32)?,
372                    c => write!(f, "{c}")?,
373                }
374            }
375            f.write_str("\"")
376        }
377        match self {
378            Value::Null => f.write_str("null"),
379            Value::Bool(b) => write!(f, "{b}"),
380            Value::Int(i) => write!(f, "{i}"),
381            Value::Uint(u) => write!(f, "{u}"),
382            Value::Int128(i) => write!(f, "{i}"),
383            Value::Uint128(u) => write!(f, "{u}"),
384            Value::Float(x) if x.is_finite() => write!(f, "{x:?}"),
385            Value::Float(_) => f.write_str("null"),
386            Value::Array(items) => {
387                f.write_str("[")?;
388                for (i, item) in items.iter().enumerate() {
389                    if i > 0 {
390                        f.write_str(",")?;
391                    }
392                    write!(f, "{item}")?;
393                }
394                f.write_str("]")
395            }
396            Value::Object(map) => {
397                f.write_str("{")?;
398                for (i, (key, value)) in map.iter().enumerate() {
399                    if i > 0 {
400                        f.write_str(",")?;
401                    }
402                    text(f, key)?;
403                    write!(f, ":{value}")?;
404                }
405                f.write_str("}")
406            }
407            other => text(f, other.as_str().unwrap_or_default()),
408        }
409    }
410}
411
412impl std::ops::Index<&str> for Value {
413    type Output = Value;
414
415    fn index(&self, key: &str) -> &Value {
416        self.get(key).unwrap_or(&NULL)
417    }
418}
419
420/// `value[0]` — yields `Value::Null` out of bounds or on non-arrays.
421impl std::ops::Index<usize> for Value {
422    type Output = Value;
423
424    fn index(&self, index: usize) -> &Value {
425        self.get_index(index).unwrap_or(&NULL)
426    }
427}
428
429impl<'de> serde::Deserialize<'de> for Value {
430    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
431    where
432        D: serde::Deserializer<'de>,
433    {
434        struct ValueVisitor;
435
436        impl<'de> serde::de::Visitor<'de> for ValueVisitor {
437            type Value = Value;
438
439            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
440                f.write_str("any config value")
441            }
442
443            fn visit_bool<E>(self, v: bool) -> std::result::Result<Value, E> {
444                Ok(Value::Bool(v))
445            }
446
447            fn visit_i64<E>(self, v: i64) -> std::result::Result<Value, E> {
448                Ok(Value::Int(v))
449            }
450
451            fn visit_u64<E>(self, v: u64) -> std::result::Result<Value, E> {
452                Ok(Value::Uint(v))
453            }
454
455            fn visit_i128<E>(self, v: i128) -> std::result::Result<Value, E> {
456                // narrow back to the smaller variants when it fits, so a
457                // round trip through i64/u64-only formats stays stable
458                Ok(match i64::try_from(v) {
459                    Ok(i) => Value::Int(i),
460                    Err(_) => match u64::try_from(v) {
461                        Ok(u) => Value::Uint(u),
462                        Err(_) => Value::Int128(v),
463                    },
464                })
465            }
466
467            fn visit_u128<E>(self, v: u128) -> std::result::Result<Value, E> {
468                Ok(match u64::try_from(v) {
469                    Ok(u) => Value::Uint(u),
470                    Err(_) => Value::Uint128(v),
471                })
472            }
473
474            fn visit_f64<E>(self, v: f64) -> std::result::Result<Value, E> {
475                Ok(Value::Float(v))
476            }
477
478            fn visit_str<E>(self, v: &str) -> std::result::Result<Value, E> {
479                Ok(Value::String(v.to_owned()))
480            }
481
482            fn visit_string<E>(self, v: String) -> std::result::Result<Value, E> {
483                Ok(Value::String(v))
484            }
485
486            fn visit_newtype_struct<D>(
487                self,
488                deserializer: D,
489            ) -> std::result::Result<Value, D::Error>
490            where
491                D: serde::Deserializer<'de>,
492            {
493                // c4's own deserializer parked the value here (see
494                // `PASS_THROUGH`); any other one is an ordinary newtype
495                match PASS_THROUGH.with(|slot| slot.take()) {
496                    Some(value) => Ok(value),
497                    None => deserializer.deserialize_any(ValueVisitor),
498                }
499            }
500
501            fn visit_unit<E>(self) -> std::result::Result<Value, E> {
502                Ok(Value::Null)
503            }
504
505            fn visit_none<E>(self) -> std::result::Result<Value, E> {
506                Ok(Value::Null)
507            }
508
509            fn visit_some<D>(self, deserializer: D) -> std::result::Result<Value, D::Error>
510            where
511                D: serde::Deserializer<'de>,
512            {
513                serde::Deserialize::deserialize(deserializer)
514            }
515
516            fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Value, A::Error>
517            where
518                A: serde::de::SeqAccess<'de>,
519            {
520                let mut items = Vec::new();
521                while let Some(item) = seq.next_element()? {
522                    items.push(item);
523                }
524                Ok(Value::Array(items))
525            }
526
527            fn visit_map<A>(self, mut map: A) -> std::result::Result<Value, A::Error>
528            where
529                A: serde::de::MapAccess<'de>,
530            {
531                let mut object = BTreeMap::new();
532                while let Some((key, value)) = map.next_entry::<String, Value>()? {
533                    object.insert(key, value);
534                }
535                Ok(Value::Object(object))
536            }
537        }
538
539        deserializer.deserialize_newtype_struct(PASS_THROUGH_NAME, ValueVisitor)
540    }
541}
542
543/// The newtype name `Value::deserialize` asks for. c4's `ValueDeserializer`
544/// answers it by parking its owned value in [`PASS_THROUGH`] — no serde
545/// round trip, which would flatten typed variants into strings.
546pub(crate) const PASS_THROUGH_NAME: &str = "$c4::private::Value";
547
548thread_local! {
549    pub(crate) static PASS_THROUGH: std::cell::Cell<Option<Value>> =
550        const { std::cell::Cell::new(None) };
551}
552
553impl serde::Serialize for Value {
554    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
555    where
556        S: serde::Serializer,
557    {
558        match self {
559            Value::Null => serializer.serialize_unit(),
560            Value::Bool(b) => serializer.serialize_bool(*b),
561            Value::Int(i) => serializer.serialize_i64(*i),
562            Value::Uint(u) => serializer.serialize_u64(*u),
563            // 128-bit narrows to the smaller numeric variants when it fits;
564            // a value past u64 has no JSON number form, so it serializes as
565            // its decimal string (a lossy round trip, like textual variants)
566            Value::Int128(i) => match i64::try_from(*i) {
567                Ok(v) => serializer.serialize_i64(v),
568                Err(_) => match u64::try_from(*i) {
569                    Ok(v) => serializer.serialize_u64(v),
570                    Err(_) => serializer.collect_str(i),
571                },
572            },
573            Value::Uint128(u) => match u64::try_from(*u) {
574                Ok(v) => serializer.serialize_u64(v),
575                Err(_) => serializer.collect_str(u),
576            },
577            Value::Float(f) => serializer.serialize_f64(*f),
578            Value::String(s) => serializer.serialize_str(s),
579            Value::DateTime(s)
580            | Value::Date(s)
581            | Value::Time(s)
582            | Value::Inet(s)
583            | Value::Cidr(s)
584            | Value::MacAddr(s)
585            | Value::MacAddr8(s)
586            | Value::Uuid(s) => serializer.serialize_str(s),
587            Value::Ipv4(ip) | Value::Ipv6(ip) => serializer.serialize_str(ip),
588            Value::Array(items) => serializer.collect_seq(items),
589            Value::Object(map) => serializer.collect_map(map),
590        }
591    }
592}