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#[derive(Debug, Clone, PartialEq)]
10pub enum Value {
11    Null,
12    Bool(bool),
13    Int(i64),
14    Uint(u64),
15    /// 128-bit signed — only from the table `i128` type (never `auto`,
16    /// which stops at `i64`/`u64`/`f64`).
17    Int128(i128),
18    /// 128-bit unsigned — only from the table `u128` type.
19    Uint128(u128),
20    Float(f64),
21    String(String),
22    /// An RFC 3339-style date or datetime, kept as its text. Produced by
23    /// toml datetime literals, the table `dt` type and the `auto` guess —
24    /// all gated by the `datetime` feature. Serializes as the string itself (so
25    /// a serialize→deserialize round trip through a format without a
26    /// datetime type yields a `String`).
27    DateTime(String),
28    /// `YYYY-MM-DD`, kept as its text (table `date` type, `date` feature).
29    Date(String),
30    /// `hh:mm:ss[.fraction]`, kept as its text (table `time` type, `time`
31    /// feature).
32    Time(String),
33    /// Table `ipv4` type (`ipv4` feature); serializes canonically. The
34    /// `inet` type (`inet` feature) also produces this or [`Value::Ipv6`],
35    /// whichever family parses.
36    Ipv4(std::net::Ipv4Addr),
37    /// Table `ipv6` type (`ipv6` feature); serializes canonically.
38    Ipv6(std::net::Ipv6Addr),
39    /// A host address **with a netmask** (`10.0.0.1/24`), kept as its
40    /// validated text — PostgreSQL `inet` semantics, host bits below the
41    /// mask may be set (table `inet` type, `inet` feature; a bare `inet`
42    /// address maps onto [`Value::Ipv4`]/[`Value::Ipv6`] instead).
43    Inet(String),
44    /// A network — optional netmask defaulting to the full address
45    /// length, host bits below the mask must be zero — kept as its
46    /// validated text; PostgreSQL `cidr` semantics (table `cidr` type,
47    /// `cidr` feature).
48    Cidr(String),
49    /// 6-byte MAC address, kept as its validated text (table `macaddr`
50    /// type, `macaddr` feature).
51    MacAddr(String),
52    /// 8-byte MAC address, kept as its validated text (table `macaddr8`
53    /// type, `macaddr8` feature).
54    MacAddr8(String),
55    /// Hyphenated `8-4-4-4-12` UUID, kept as its validated text (table
56    /// `uuid` type, `uuid` feature).
57    Uuid(String),
58    Array(Vec<Value>),
59    Object(BTreeMap<String, Value>),
60}
61
62static NULL: Value = Value::Null;
63
64impl Value {
65    /// Object member by key; `None` when this is not an object or the key
66    /// is absent.
67    pub fn get(&self, key: &str) -> Option<&Value> {
68        match self {
69            Value::Object(map) => map.get(key),
70            _ => None,
71        }
72    }
73
74    /// Array element by index; `None` when this is not an array or the
75    /// index is out of bounds.
76    pub fn get_index(&self, index: usize) -> Option<&Value> {
77        match self {
78            Value::Array(items) => items.get(index),
79            _ => None,
80        }
81    }
82
83    pub fn is_null(&self) -> bool {
84        matches!(self, Value::Null)
85    }
86
87    pub fn as_bool(&self) -> Option<bool> {
88        match self {
89            Value::Bool(b) => Some(*b),
90            _ => None,
91        }
92    }
93
94    pub fn as_i64(&self) -> Option<i64> {
95        match self {
96            Value::Int(i) => Some(*i),
97            Value::Uint(u) => i64::try_from(*u).ok(),
98            Value::Int128(i) => i64::try_from(*i).ok(),
99            Value::Uint128(u) => i64::try_from(*u).ok(),
100            _ => None,
101        }
102    }
103
104    pub fn as_u64(&self) -> Option<u64> {
105        match self {
106            Value::Uint(u) => Some(*u),
107            Value::Int(i) => u64::try_from(*i).ok(),
108            Value::Int128(i) => u64::try_from(*i).ok(),
109            Value::Uint128(u) => u64::try_from(*u).ok(),
110            _ => None,
111        }
112    }
113
114    /// Any integer value as an `i128`.
115    pub fn as_i128(&self) -> Option<i128> {
116        match self {
117            Value::Int(i) => Some(i128::from(*i)),
118            Value::Uint(u) => Some(i128::from(*u)),
119            Value::Int128(i) => Some(*i),
120            Value::Uint128(u) => i128::try_from(*u).ok(),
121            _ => None,
122        }
123    }
124
125    /// Any integer value as a `u128`.
126    pub fn as_u128(&self) -> Option<u128> {
127        match self {
128            Value::Uint(u) => Some(u128::from(*u)),
129            Value::Int(i) => u128::try_from(*i).ok(),
130            Value::Int128(i) => u128::try_from(*i).ok(),
131            Value::Uint128(u) => Some(*u),
132            _ => None,
133        }
134    }
135
136    /// Any numeric value as a float.
137    pub fn as_f64(&self) -> Option<f64> {
138        match self {
139            Value::Float(f) => Some(*f),
140            Value::Int(i) => Some(*i as f64),
141            Value::Uint(u) => Some(*u as f64),
142            Value::Int128(i) => Some(*i as f64),
143            Value::Uint128(u) => Some(*u as f64),
144            _ => None,
145        }
146    }
147
148    /// The text of a string — or of a datetime/date/time value, which
149    /// keep their text form.
150    pub fn as_str(&self) -> Option<&str> {
151        match self {
152            Value::String(s)
153            | Value::DateTime(s)
154            | Value::Date(s)
155            | Value::Time(s)
156            | Value::Inet(s)
157            | Value::Cidr(s)
158            | Value::MacAddr(s)
159            | Value::MacAddr8(s)
160            | Value::Uuid(s) => Some(s),
161            _ => None,
162        }
163    }
164
165    /// The format id of this value — which parser produced it: `null`,
166    /// `bool`, `i64`, `u64`, `i128`, `u128`, `f64`, `str`, the typed ids (`dt`, `date`,
167    /// `time`, `ipv4`, `ipv6`, `cidr`, `macaddr`, `macaddr8`, `uuid`),
168    /// `arr:<t>` for homogeneous scalar arrays, `arr` for other arrays,
169    /// `object` for objects. Integer widths normalize to the stored type
170    /// (an `i8` cell stores an `i64`, so it reports `i64`), and `inet`
171    /// reports as the family it parsed into. Shown by `trace()` as the
172    /// `format` field of every serialized leaf.
173    pub fn format_id(&self) -> std::borrow::Cow<'static, str> {
174        use std::borrow::Cow;
175        Cow::Borrowed(match self {
176            Value::Null => "null",
177            Value::Bool(_) => "bool",
178            Value::Int(_) => "i64",
179            Value::Uint(_) => "u64",
180            Value::Int128(_) => "i128",
181            Value::Uint128(_) => "u128",
182            Value::Float(_) => "f64",
183            Value::String(_) => "str",
184            Value::DateTime(_) => "dt",
185            Value::Date(_) => "date",
186            Value::Time(_) => "time",
187            Value::Ipv4(_) => "ipv4",
188            Value::Ipv6(_) => "ipv6",
189            Value::Inet(_) => "inet",
190            Value::Cidr(_) => "cidr",
191            Value::MacAddr(_) => "macaddr",
192            Value::MacAddr8(_) => "macaddr8",
193            Value::Uuid(_) => "uuid",
194            Value::Object(_) => "object",
195            Value::Array(items) => {
196                let mut ids = items.iter().map(Value::format_id);
197                return match ids.next() {
198                    Some(first)
199                        if first != "object"
200                            && !first.starts_with("arr")
201                            && ids.all(|id| id == first) =>
202                    {
203                        Cow::Owned(format!("arr:{first}"))
204                    }
205                    _ => Cow::Borrowed("arr"),
206                };
207            }
208        })
209    }
210
211    pub fn as_array(&self) -> Option<&Vec<Value>> {
212        match self {
213            Value::Array(items) => Some(items),
214            _ => None,
215        }
216    }
217
218    pub fn as_object(&self) -> Option<&BTreeMap<String, Value>> {
219        match self {
220            Value::Object(map) => Some(map),
221            _ => None,
222        }
223    }
224}
225
226/// `value["key"]` — yields `Value::Null` for missing keys or non-objects,
227/// so lookups chain without panicking: `value["db"]["port"].as_u64()`.
228impl std::ops::Index<&str> for Value {
229    type Output = Value;
230
231    fn index(&self, key: &str) -> &Value {
232        self.get(key).unwrap_or(&NULL)
233    }
234}
235
236/// `value[0]` — yields `Value::Null` out of bounds or on non-arrays.
237impl std::ops::Index<usize> for Value {
238    type Output = Value;
239
240    fn index(&self, index: usize) -> &Value {
241        self.get_index(index).unwrap_or(&NULL)
242    }
243}
244
245impl<'de> serde::Deserialize<'de> for Value {
246    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
247    where
248        D: serde::Deserializer<'de>,
249    {
250        struct ValueVisitor;
251
252        impl<'de> serde::de::Visitor<'de> for ValueVisitor {
253            type Value = Value;
254
255            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256                f.write_str("any config value")
257            }
258
259            fn visit_bool<E>(self, v: bool) -> std::result::Result<Value, E> {
260                Ok(Value::Bool(v))
261            }
262
263            fn visit_i64<E>(self, v: i64) -> std::result::Result<Value, E> {
264                Ok(Value::Int(v))
265            }
266
267            fn visit_u64<E>(self, v: u64) -> std::result::Result<Value, E> {
268                Ok(Value::Uint(v))
269            }
270
271            fn visit_i128<E>(self, v: i128) -> std::result::Result<Value, E> {
272                // narrow back to the smaller variants when it fits, so a
273                // round trip through i64/u64-only formats stays stable
274                Ok(match i64::try_from(v) {
275                    Ok(i) => Value::Int(i),
276                    Err(_) => match u64::try_from(v) {
277                        Ok(u) => Value::Uint(u),
278                        Err(_) => Value::Int128(v),
279                    },
280                })
281            }
282
283            fn visit_u128<E>(self, v: u128) -> std::result::Result<Value, E> {
284                Ok(match u64::try_from(v) {
285                    Ok(u) => Value::Uint(u),
286                    Err(_) => Value::Uint128(v),
287                })
288            }
289
290            fn visit_f64<E>(self, v: f64) -> std::result::Result<Value, E> {
291                Ok(Value::Float(v))
292            }
293
294            fn visit_str<E>(self, v: &str) -> std::result::Result<Value, E> {
295                Ok(Value::String(v.to_owned()))
296            }
297
298            fn visit_string<E>(self, v: String) -> std::result::Result<Value, E> {
299                Ok(Value::String(v))
300            }
301
302            fn visit_unit<E>(self) -> std::result::Result<Value, E> {
303                Ok(Value::Null)
304            }
305
306            fn visit_none<E>(self) -> std::result::Result<Value, E> {
307                Ok(Value::Null)
308            }
309
310            fn visit_some<D>(self, deserializer: D) -> std::result::Result<Value, D::Error>
311            where
312                D: serde::Deserializer<'de>,
313            {
314                serde::Deserialize::deserialize(deserializer)
315            }
316
317            fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Value, A::Error>
318            where
319                A: serde::de::SeqAccess<'de>,
320            {
321                let mut items = Vec::new();
322                while let Some(item) = seq.next_element()? {
323                    items.push(item);
324                }
325                Ok(Value::Array(items))
326            }
327
328            fn visit_map<A>(self, mut map: A) -> std::result::Result<Value, A::Error>
329            where
330                A: serde::de::MapAccess<'de>,
331            {
332                let mut object = BTreeMap::new();
333                while let Some((key, value)) = map.next_entry::<String, Value>()? {
334                    object.insert(key, value);
335                }
336                Ok(Value::Object(object))
337            }
338        }
339
340        deserializer.deserialize_any(ValueVisitor)
341    }
342}
343
344impl serde::Serialize for Value {
345    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
346    where
347        S: serde::Serializer,
348    {
349        match self {
350            Value::Null => serializer.serialize_unit(),
351            Value::Bool(b) => serializer.serialize_bool(*b),
352            Value::Int(i) => serializer.serialize_i64(*i),
353            Value::Uint(u) => serializer.serialize_u64(*u),
354            // 128-bit narrows to the smaller numeric variants when it fits;
355            // a value past u64 has no JSON number form, so it serializes as
356            // its decimal string (a lossy round trip, like textual variants)
357            Value::Int128(i) => match i64::try_from(*i) {
358                Ok(v) => serializer.serialize_i64(v),
359                Err(_) => match u64::try_from(*i) {
360                    Ok(v) => serializer.serialize_u64(v),
361                    Err(_) => serializer.collect_str(i),
362                },
363            },
364            Value::Uint128(u) => match u64::try_from(*u) {
365                Ok(v) => serializer.serialize_u64(v),
366                Err(_) => serializer.collect_str(u),
367            },
368            Value::Float(f) => serializer.serialize_f64(*f),
369            Value::String(s) => serializer.serialize_str(s),
370            Value::DateTime(s)
371            | Value::Date(s)
372            | Value::Time(s)
373            | Value::Inet(s)
374            | Value::Cidr(s)
375            | Value::MacAddr(s)
376            | Value::MacAddr8(s)
377            | Value::Uuid(s) => serializer.serialize_str(s),
378            Value::Ipv4(ip) => serializer.collect_str(ip),
379            Value::Ipv6(ip) => serializer.collect_str(ip),
380            Value::Array(items) => serializer.collect_seq(items),
381            Value::Object(map) => serializer.collect_map(map),
382        }
383    }
384}