Skip to main content

cddl_cat/
value.rs

1//! This module declares a generic Value enum for use with validation.
2
3use std::collections::BTreeMap;
4use std::fmt;
5
6use float_ord::FloatOrd;
7
8/// `Value` represents all the types of data we can validate.
9///
10/// To validate a new type of data, write implementations of the `From`
11/// trait for that type.  See the [`cbor`] module for an example.
12///
13/// [`cbor`]: crate::cbor
14///
15#[derive(Clone, Eq, Ord, PartialEq, PartialOrd)]
16#[allow(missing_docs)]
17pub enum Value {
18    Null,
19    Bool(bool),
20    Integer(i128),
21    Float(FloatOrd<f64>),
22    Bytes(Vec<u8>),
23    Text(String),
24    Array(Vec<Value>),
25    Map(BTreeMap<Value, Value>),
26}
27
28// FloatOrd doesn't implement Debug, so we have to do all the work by hand.
29impl fmt::Debug for Value {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            Value::Null => write!(f, "Null"),
33            Value::Bool(x) => x.fmt(f),
34            Value::Integer(x) => x.fmt(f),
35            Value::Float(x) => x.0.fmt(f),
36            Value::Bytes(x) => x.fmt(f),
37            Value::Text(x) => x.fmt(f),
38            Value::Array(x) => x.fmt(f),
39            Value::Map(x) => x.fmt(f),
40        }
41    }
42}
43
44// Only exists so implementers don't need to use/see float_ord::FloatOrd
45impl Value {
46    pub(crate) fn from_float<F: Into<f64>>(f: F) -> Value {
47        Value::Float(FloatOrd(f.into()))
48    }
49}