1use std::collections::BTreeMap;
7
8#[derive(Debug, Clone, PartialEq)]
13#[non_exhaustive]
14pub enum Value {
15 Null,
16 Bool(bool),
17 Int(i64),
18 Uint(u64),
19 Int128(i128),
25 Uint128(u128),
29 Float(f64),
30 String(String),
31 DateTime(String),
37 Date(String),
39 Time(String),
42 Ipv4(String),
48 Ipv6(String),
51 Inet(String),
56 Cidr(String),
61 MacAddr(String),
64 MacAddr8(String),
67 Uuid(String),
70 Array(Vec<Value>),
71 Object(BTreeMap<String, Value>),
72}
73
74static NULL: Value = Value::Null;
75
76impl Value {
77 pub fn get(&self, key: &str) -> Option<&Value> {
80 match self {
81 Value::Object(map) => map.get(key),
82 _ => None,
83 }
84 }
85
86 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 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 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 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 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 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 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 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
279macro_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 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
326macro_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
357impl 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
420impl 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 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 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
543pub(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 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}