Skip to main content

coip_format/
value.rs

1use alloc::collections::BTreeMap;
2use alloc::string::String;
3use alloc::vec::Vec;
4use core::cmp::Ordering;
5use core::hash::{Hash, Hasher};
6
7use crate::varint::{write_string, write_uvarint};
8use crate::{Cursor, FormatError};
9
10/// Lossless, self-describing dynamic value supporting all COI / MMDB types.
11#[derive(Debug, Clone)]
12pub enum Value {
13    Null,
14    Bool(bool),
15    U8(u8),
16    U16(u16),
17    U32(u32),
18    U64(u64),
19    U128(u128),
20    I32(i32),
21    I64(i64),
22    F32(f32),
23    F64(f64),
24    Utf8(String),
25    Bytes(Vec<u8>),
26    Array(Vec<Value>),
27    Map(BTreeMap<String, Value>),
28}
29
30impl Value {
31    /// Strict bit-exact equality (preserves exact numeric type and IEEE-754 float bits).
32    pub fn bit_eq(&self, other: &Self) -> bool {
33        match (self, other) {
34            (Self::Null, Self::Null) => true,
35            (Self::Bool(a), Self::Bool(b)) => a == b,
36            (Self::U8(a), Self::U8(b)) => a == b,
37            (Self::U16(a), Self::U16(b)) => a == b,
38            (Self::U32(a), Self::U32(b)) => a == b,
39            (Self::U64(a), Self::U64(b)) => a == b,
40            (Self::U128(a), Self::U128(b)) => a == b,
41            (Self::I32(a), Self::I32(b)) => a == b,
42            (Self::I64(a), Self::I64(b)) => a == b,
43            (Self::F32(a), Self::F32(b)) => a.to_bits() == b.to_bits(),
44            (Self::F64(a), Self::F64(b)) => a.to_bits() == b.to_bits(),
45            (Self::Utf8(a), Self::Utf8(b)) => a == b,
46            (Self::Bytes(a), Self::Bytes(b)) => a == b,
47            (Self::Array(a), Self::Array(b)) => {
48                a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.bit_eq(y))
49            }
50            (Self::Map(a), Self::Map(b)) => {
51                a.len() == b.len()
52                    && a.iter()
53                        .zip(b)
54                        .all(|((ka, va), (kb, vb))| ka == kb && va.bit_eq(vb))
55            }
56            _ => false,
57        }
58    }
59
60    pub fn as_map(&self) -> Option<&BTreeMap<String, Value>> {
61        match self {
62            Self::Map(m) => Some(m),
63            _ => None,
64        }
65    }
66
67    pub fn as_array(&self) -> Option<&[Value]> {
68        match self {
69            Self::Array(a) => Some(a),
70            _ => None,
71        }
72    }
73
74    pub fn as_str(&self) -> Option<&str> {
75        match self {
76            Self::Utf8(s) => Some(s),
77            _ => None,
78        }
79    }
80
81    fn tag_order(&self) -> u8 {
82        match self {
83            Self::Null => 0,
84            Self::Bool(_) => 1,
85            Self::U8(_) => 2,
86            Self::U16(_) => 3,
87            Self::U32(_) => 4,
88            Self::U64(_) => 5,
89            Self::U128(_) => 6,
90            Self::I32(_) => 7,
91            Self::I64(_) => 8,
92            Self::F32(_) => 9,
93            Self::F64(_) => 10,
94            Self::Utf8(_) => 11,
95            Self::Bytes(_) => 12,
96            Self::Array(_) => 13,
97            Self::Map(_) => 14,
98        }
99    }
100
101    /// Deterministic total ordering over canonical `Value`s (using IEEE-754 bit patterns for floats).
102    pub fn bit_cmp(&self, other: &Self) -> Ordering {
103        match (self, other) {
104            (Self::Null, Self::Null) => Ordering::Equal,
105            (Self::Bool(a), Self::Bool(b)) => a.cmp(b),
106            (Self::U8(a), Self::U8(b)) => a.cmp(b),
107            (Self::U16(a), Self::U16(b)) => a.cmp(b),
108            (Self::U32(a), Self::U32(b)) => a.cmp(b),
109            (Self::U64(a), Self::U64(b)) => a.cmp(b),
110            (Self::U128(a), Self::U128(b)) => a.cmp(b),
111            (Self::I32(a), Self::I32(b)) => a.cmp(b),
112            (Self::I64(a), Self::I64(b)) => a.cmp(b),
113            (Self::F32(a), Self::F32(b)) => a.to_bits().cmp(&b.to_bits()),
114            (Self::F64(a), Self::F64(b)) => a.to_bits().cmp(&b.to_bits()),
115            (Self::Utf8(a), Self::Utf8(b)) => a.cmp(b),
116            (Self::Bytes(a), Self::Bytes(b)) => a.cmp(b),
117            (Self::Array(a), Self::Array(b)) => {
118                for (x, y) in a.iter().zip(b.iter()) {
119                    let c = x.bit_cmp(y);
120                    if c != Ordering::Equal {
121                        return c;
122                    }
123                }
124                a.len().cmp(&b.len())
125            }
126            (Self::Map(a), Self::Map(b)) => {
127                for ((ka, va), (kb, vb)) in a.iter().zip(b.iter()) {
128                    let c = ka.cmp(kb);
129                    if c != Ordering::Equal {
130                        return c;
131                    }
132                    let c = va.bit_cmp(vb);
133                    if c != Ordering::Equal {
134                        return c;
135                    }
136                }
137                a.len().cmp(&b.len())
138            }
139            _ => self.tag_order().cmp(&other.tag_order()),
140        }
141    }
142
143    pub fn bit_hash<H: Hasher>(&self, state: &mut H) {
144        self.tag_order().hash(state);
145        match self {
146            Self::Null => {}
147            Self::Bool(v) => v.hash(state),
148            Self::U8(v) => v.hash(state),
149            Self::U16(v) => v.hash(state),
150            Self::U32(v) => v.hash(state),
151            Self::U64(v) => v.hash(state),
152            Self::U128(v) => v.hash(state),
153            Self::I32(v) => v.hash(state),
154            Self::I64(v) => v.hash(state),
155            Self::F32(v) => v.to_bits().hash(state),
156            Self::F64(v) => v.to_bits().hash(state),
157            Self::Utf8(v) => v.hash(state),
158            Self::Bytes(v) => v.hash(state),
159            Self::Array(v) => {
160                v.len().hash(state);
161                for x in v {
162                    x.bit_hash(state);
163                }
164            }
165            Self::Map(m) => {
166                m.len().hash(state);
167                for (k, v) in m {
168                    k.hash(state);
169                    v.bit_hash(state);
170                }
171            }
172        }
173    }
174
175    /// Encode this `Value` into canonical COI Dynamic wire bytes.
176    pub fn encode(&self, out: &mut Vec<u8>) {
177        match self {
178            Self::Null => out.push(0),
179            Self::Bool(false) => out.push(1),
180            Self::Bool(true) => out.push(2),
181            Self::U8(v) => {
182                out.push(3);
183                out.push(*v);
184            }
185            Self::U16(v) => {
186                out.push(4);
187                out.extend_from_slice(&v.to_le_bytes());
188            }
189            Self::U32(v) => {
190                out.push(5);
191                out.extend_from_slice(&v.to_le_bytes());
192            }
193            Self::U64(v) => {
194                out.push(6);
195                out.extend_from_slice(&v.to_le_bytes());
196            }
197            Self::U128(v) => {
198                out.push(7);
199                out.extend_from_slice(&v.to_le_bytes());
200            }
201            Self::I32(v) => {
202                out.push(8);
203                out.extend_from_slice(&v.to_le_bytes());
204            }
205            Self::I64(v) => {
206                out.push(9);
207                out.extend_from_slice(&v.to_le_bytes());
208            }
209            Self::F32(v) => {
210                out.push(10);
211                out.extend_from_slice(&v.to_bits().to_le_bytes());
212            }
213            Self::F64(v) => {
214                out.push(11);
215                out.extend_from_slice(&v.to_bits().to_le_bytes());
216            }
217            Self::Utf8(s) => {
218                out.push(12);
219                write_string(out, s);
220            }
221            Self::Bytes(b) => {
222                out.push(13);
223                write_uvarint(out, b.len() as u64);
224                out.extend_from_slice(b);
225            }
226            Self::Array(arr) => {
227                out.push(14);
228                write_uvarint(out, arr.len() as u64);
229                for item in arr {
230                    item.encode(out);
231                }
232            }
233            Self::Map(map) => {
234                out.push(15);
235                write_uvarint(out, map.len() as u64);
236                for (k, v) in map {
237                    write_string(out, k);
238                    v.encode(out);
239                }
240            }
241        }
242    }
243
244    /// Decode a canonical COI Dynamic `Value` from a cursor.
245    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
246        let tag = c.read_u8()?;
247        match tag {
248            0 => Ok(Self::Null),
249            1 => Ok(Self::Bool(false)),
250            2 => Ok(Self::Bool(true)),
251            3 => Ok(Self::U8(c.read_u8()?)),
252            4 => Ok(Self::U16(c.read_u16()?)),
253            5 => Ok(Self::U32(c.read_u32()?)),
254            6 => Ok(Self::U64(c.read_u64()?)),
255            7 => Ok(Self::U128(c.read_u128()?)),
256            8 => Ok(Self::I32(c.read_i32()?)),
257            9 => Ok(Self::I64(c.read_i64()?)),
258            10 => Ok(Self::F32(c.read_f32()?)),
259            11 => Ok(Self::F64(c.read_f64()?)),
260            12 => Ok(Self::Utf8(c.read_string()?)),
261            13 => {
262                let len =
263                    usize::try_from(c.read_uvarint()?).map_err(|_| FormatError::UnexpectedEof)?;
264                Ok(Self::Bytes(c.read_bytes(len)?.to_vec()))
265            }
266            14 => {
267                let count =
268                    usize::try_from(c.read_uvarint()?).map_err(|_| FormatError::UnexpectedEof)?;
269                let mut arr = Vec::with_capacity(count);
270                for _ in 0..count {
271                    arr.push(Self::decode(c)?);
272                }
273                Ok(Self::Array(arr))
274            }
275            15 => {
276                let count =
277                    usize::try_from(c.read_uvarint()?).map_err(|_| FormatError::UnexpectedEof)?;
278                let mut map = BTreeMap::new();
279                for _ in 0..count {
280                    let k = c.read_string()?;
281                    let v = Self::decode(c)?;
282                    map.insert(k, v);
283                }
284                Ok(Self::Map(map))
285            }
286            _ => Err(FormatError::InvalidValueTag(tag)),
287        }
288    }
289
290    pub fn decode_exact(buf: &[u8]) -> Result<Self, FormatError> {
291        let mut c = Cursor::new(buf);
292        Self::decode(&mut c)
293    }
294}
295
296impl PartialEq for Value {
297    fn eq(&self, other: &Self) -> bool {
298        self.bit_eq(other)
299    }
300}
301
302impl Eq for Value {}
303
304impl Hash for Value {
305    fn hash<H: Hasher>(&self, state: &mut H) {
306        self.bit_hash(state);
307    }
308}
309
310impl PartialOrd for Value {
311    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
312        Some(self.cmp(other))
313    }
314}
315
316impl Ord for Value {
317    fn cmp(&self, other: &Self) -> Ordering {
318        self.bit_cmp(other)
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    #[test]
327    fn test_value_roundtrip_and_bit_eq() {
328        let mut m = BTreeMap::new();
329        m.insert(String::from("neg_zero"), Value::F64(-0.0));
330        m.insert(String::from("lat"), Value::F64(37.7510123));
331        m.insert(String::from("flag"), Value::Bool(false));
332        m.insert(String::from("big"), Value::U128(u128::MAX));
333        m.insert(
334            String::from("arr"),
335            Value::Array(alloc::vec![Value::U16(1), Value::Utf8(String::from("ok"))]),
336        );
337        let val = Value::Map(m);
338        let mut buf = Vec::new();
339        val.encode(&mut buf);
340        let decoded = Value::decode_exact(&buf).unwrap();
341        assert_eq!(val, decoded);
342        assert_ne!(Value::F64(-0.0), Value::F64(0.0));
343    }
344}