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
//! The dynamic config value: the [`Value`] enum, its accessors and its
//! serde bridges. `Value::format_id` names the parser a value came from
//! (shown by traces); typed variants beyond JSON's set (datetime, IPs,
//! MACs, …) are produced by the feature-gated table value parsers.
use std::collections::BTreeMap;
/// Dynamic config value.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Null,
Bool(bool),
Int(i64),
Uint(u64),
/// 128-bit signed — only from the table `i128` type (never `auto`,
/// which stops at `i64`/`u64`/`f64`).
Int128(i128),
/// 128-bit unsigned — only from the table `u128` type.
Uint128(u128),
Float(f64),
String(String),
/// An RFC 3339-style date or datetime, kept as its text. Produced by
/// toml datetime literals, the table `dt` type and the `auto` guess —
/// all gated by the `datetime` feature. Serializes as the string itself (so
/// a serialize→deserialize round trip through a format without a
/// datetime type yields a `String`).
DateTime(String),
/// `YYYY-MM-DD`, kept as its text (table `date` type, `date` feature).
Date(String),
/// `hh:mm:ss[.fraction]`, kept as its text (table `time` type, `time`
/// feature).
Time(String),
/// Table `ipv4` type (`ipv4` feature); serializes canonically. The
/// `inet` type (`inet` feature) also produces this or [`Value::Ipv6`],
/// whichever family parses.
Ipv4(std::net::Ipv4Addr),
/// Table `ipv6` type (`ipv6` feature); serializes canonically.
Ipv6(std::net::Ipv6Addr),
/// A host address **with a netmask** (`10.0.0.1/24`), kept as its
/// validated text — PostgreSQL `inet` semantics, host bits below the
/// mask may be set (table `inet` type, `inet` feature; a bare `inet`
/// address maps onto [`Value::Ipv4`]/[`Value::Ipv6`] instead).
Inet(String),
/// A network — optional netmask defaulting to the full address
/// length, host bits below the mask must be zero — kept as its
/// validated text; PostgreSQL `cidr` semantics (table `cidr` type,
/// `cidr` feature).
Cidr(String),
/// 6-byte MAC address, kept as its validated text (table `macaddr`
/// type, `macaddr` feature).
MacAddr(String),
/// 8-byte MAC address, kept as its validated text (table `macaddr8`
/// type, `macaddr8` feature).
MacAddr8(String),
/// Hyphenated `8-4-4-4-12` UUID, kept as its validated text (table
/// `uuid` type, `uuid` feature).
Uuid(String),
Array(Vec<Value>),
Object(BTreeMap<String, Value>),
}
static NULL: Value = Value::Null;
impl Value {
/// Object member by key; `None` when this is not an object or the key
/// is absent.
pub fn get(&self, key: &str) -> Option<&Value> {
match self {
Value::Object(map) => map.get(key),
_ => None,
}
}
/// Array element by index; `None` when this is not an array or the
/// index is out of bounds.
pub fn get_index(&self, index: usize) -> Option<&Value> {
match self {
Value::Array(items) => items.get(index),
_ => None,
}
}
pub fn is_null(&self) -> bool {
matches!(self, Value::Null)
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Value::Bool(b) => Some(*b),
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match self {
Value::Int(i) => Some(*i),
Value::Uint(u) => i64::try_from(*u).ok(),
Value::Int128(i) => i64::try_from(*i).ok(),
Value::Uint128(u) => i64::try_from(*u).ok(),
_ => None,
}
}
pub fn as_u64(&self) -> Option<u64> {
match self {
Value::Uint(u) => Some(*u),
Value::Int(i) => u64::try_from(*i).ok(),
Value::Int128(i) => u64::try_from(*i).ok(),
Value::Uint128(u) => u64::try_from(*u).ok(),
_ => None,
}
}
/// Any integer value as an `i128`.
pub fn as_i128(&self) -> Option<i128> {
match self {
Value::Int(i) => Some(i128::from(*i)),
Value::Uint(u) => Some(i128::from(*u)),
Value::Int128(i) => Some(*i),
Value::Uint128(u) => i128::try_from(*u).ok(),
_ => None,
}
}
/// Any integer value as a `u128`.
pub fn as_u128(&self) -> Option<u128> {
match self {
Value::Uint(u) => Some(u128::from(*u)),
Value::Int(i) => u128::try_from(*i).ok(),
Value::Int128(i) => u128::try_from(*i).ok(),
Value::Uint128(u) => Some(*u),
_ => None,
}
}
/// Any numeric value as a float.
pub fn as_f64(&self) -> Option<f64> {
match self {
Value::Float(f) => Some(*f),
Value::Int(i) => Some(*i as f64),
Value::Uint(u) => Some(*u as f64),
Value::Int128(i) => Some(*i as f64),
Value::Uint128(u) => Some(*u as f64),
_ => None,
}
}
/// The text of a string — or of a datetime/date/time value, which
/// keep their text form.
pub fn as_str(&self) -> Option<&str> {
match self {
Value::String(s)
| Value::DateTime(s)
| Value::Date(s)
| Value::Time(s)
| Value::Inet(s)
| Value::Cidr(s)
| Value::MacAddr(s)
| Value::MacAddr8(s)
| Value::Uuid(s) => Some(s),
_ => None,
}
}
/// The format id of this value — which parser produced it: `null`,
/// `bool`, `i64`, `u64`, `i128`, `u128`, `f64`, `str`, the typed ids (`dt`, `date`,
/// `time`, `ipv4`, `ipv6`, `cidr`, `macaddr`, `macaddr8`, `uuid`),
/// `arr:<t>` for homogeneous scalar arrays, `arr` for other arrays,
/// `object` for objects. Integer widths normalize to the stored type
/// (an `i8` cell stores an `i64`, so it reports `i64`), and `inet`
/// reports as the family it parsed into. Shown by `trace()` as the
/// `format` field of every serialized leaf.
pub fn format_id(&self) -> std::borrow::Cow<'static, str> {
use std::borrow::Cow;
Cow::Borrowed(match self {
Value::Null => "null",
Value::Bool(_) => "bool",
Value::Int(_) => "i64",
Value::Uint(_) => "u64",
Value::Int128(_) => "i128",
Value::Uint128(_) => "u128",
Value::Float(_) => "f64",
Value::String(_) => "str",
Value::DateTime(_) => "dt",
Value::Date(_) => "date",
Value::Time(_) => "time",
Value::Ipv4(_) => "ipv4",
Value::Ipv6(_) => "ipv6",
Value::Inet(_) => "inet",
Value::Cidr(_) => "cidr",
Value::MacAddr(_) => "macaddr",
Value::MacAddr8(_) => "macaddr8",
Value::Uuid(_) => "uuid",
Value::Object(_) => "object",
Value::Array(items) => {
let mut ids = items.iter().map(Value::format_id);
return match ids.next() {
Some(first)
if first != "object"
&& !first.starts_with("arr")
&& ids.all(|id| id == first) =>
{
Cow::Owned(format!("arr:{first}"))
}
_ => Cow::Borrowed("arr"),
};
}
})
}
pub fn as_array(&self) -> Option<&Vec<Value>> {
match self {
Value::Array(items) => Some(items),
_ => None,
}
}
pub fn as_object(&self) -> Option<&BTreeMap<String, Value>> {
match self {
Value::Object(map) => Some(map),
_ => None,
}
}
}
/// `value["key"]` — yields `Value::Null` for missing keys or non-objects,
/// so lookups chain without panicking: `value["db"]["port"].as_u64()`.
impl std::ops::Index<&str> for Value {
type Output = Value;
fn index(&self, key: &str) -> &Value {
self.get(key).unwrap_or(&NULL)
}
}
/// `value[0]` — yields `Value::Null` out of bounds or on non-arrays.
impl std::ops::Index<usize> for Value {
type Output = Value;
fn index(&self, index: usize) -> &Value {
self.get_index(index).unwrap_or(&NULL)
}
}
impl<'de> serde::Deserialize<'de> for Value {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ValueVisitor;
impl<'de> serde::de::Visitor<'de> for ValueVisitor {
type Value = Value;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("any config value")
}
fn visit_bool<E>(self, v: bool) -> std::result::Result<Value, E> {
Ok(Value::Bool(v))
}
fn visit_i64<E>(self, v: i64) -> std::result::Result<Value, E> {
Ok(Value::Int(v))
}
fn visit_u64<E>(self, v: u64) -> std::result::Result<Value, E> {
Ok(Value::Uint(v))
}
fn visit_i128<E>(self, v: i128) -> std::result::Result<Value, E> {
// narrow back to the smaller variants when it fits, so a
// round trip through i64/u64-only formats stays stable
Ok(match i64::try_from(v) {
Ok(i) => Value::Int(i),
Err(_) => match u64::try_from(v) {
Ok(u) => Value::Uint(u),
Err(_) => Value::Int128(v),
},
})
}
fn visit_u128<E>(self, v: u128) -> std::result::Result<Value, E> {
Ok(match u64::try_from(v) {
Ok(u) => Value::Uint(u),
Err(_) => Value::Uint128(v),
})
}
fn visit_f64<E>(self, v: f64) -> std::result::Result<Value, E> {
Ok(Value::Float(v))
}
fn visit_str<E>(self, v: &str) -> std::result::Result<Value, E> {
Ok(Value::String(v.to_owned()))
}
fn visit_string<E>(self, v: String) -> std::result::Result<Value, E> {
Ok(Value::String(v))
}
fn visit_unit<E>(self) -> std::result::Result<Value, E> {
Ok(Value::Null)
}
fn visit_none<E>(self) -> std::result::Result<Value, E> {
Ok(Value::Null)
}
fn visit_some<D>(self, deserializer: D) -> std::result::Result<Value, D::Error>
where
D: serde::Deserializer<'de>,
{
serde::Deserialize::deserialize(deserializer)
}
fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut items = Vec::new();
while let Some(item) = seq.next_element()? {
items.push(item);
}
Ok(Value::Array(items))
}
fn visit_map<A>(self, mut map: A) -> std::result::Result<Value, A::Error>
where
A: serde::de::MapAccess<'de>,
{
let mut object = BTreeMap::new();
while let Some((key, value)) = map.next_entry::<String, Value>()? {
object.insert(key, value);
}
Ok(Value::Object(object))
}
}
deserializer.deserialize_any(ValueVisitor)
}
}
impl serde::Serialize for Value {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Value::Null => serializer.serialize_unit(),
Value::Bool(b) => serializer.serialize_bool(*b),
Value::Int(i) => serializer.serialize_i64(*i),
Value::Uint(u) => serializer.serialize_u64(*u),
// 128-bit narrows to the smaller numeric variants when it fits;
// a value past u64 has no JSON number form, so it serializes as
// its decimal string (a lossy round trip, like textual variants)
Value::Int128(i) => match i64::try_from(*i) {
Ok(v) => serializer.serialize_i64(v),
Err(_) => match u64::try_from(*i) {
Ok(v) => serializer.serialize_u64(v),
Err(_) => serializer.collect_str(i),
},
},
Value::Uint128(u) => match u64::try_from(*u) {
Ok(v) => serializer.serialize_u64(v),
Err(_) => serializer.collect_str(u),
},
Value::Float(f) => serializer.serialize_f64(*f),
Value::String(s) => serializer.serialize_str(s),
Value::DateTime(s)
| Value::Date(s)
| Value::Time(s)
| Value::Inet(s)
| Value::Cidr(s)
| Value::MacAddr(s)
| Value::MacAddr8(s)
| Value::Uuid(s) => serializer.serialize_str(s),
Value::Ipv4(ip) => serializer.collect_str(ip),
Value::Ipv6(ip) => serializer.collect_str(ip),
Value::Array(items) => serializer.collect_seq(items),
Value::Object(map) => serializer.collect_map(map),
}
}
}