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