1use std::collections::BTreeMap;
7
8#[derive(Debug, Clone, PartialEq)]
10pub enum Value {
11 Null,
12 Bool(bool),
13 Int(i64),
14 Uint(u64),
15 Int128(i128),
18 Uint128(u128),
20 Float(f64),
21 String(String),
22 DateTime(String),
28 Date(String),
30 Time(String),
33 Ipv4(std::net::Ipv4Addr),
37 Ipv6(std::net::Ipv6Addr),
39 Inet(String),
44 Cidr(String),
49 MacAddr(String),
52 MacAddr8(String),
55 Uuid(String),
58 Array(Vec<Value>),
59 Object(BTreeMap<String, Value>),
60}
61
62static NULL: Value = Value::Null;
63
64impl Value {
65 pub fn get(&self, key: &str) -> Option<&Value> {
68 match self {
69 Value::Object(map) => map.get(key),
70 _ => None,
71 }
72 }
73
74 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 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 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 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 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 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
226impl 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
236impl 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 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 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}