Skip to main content

cbor_core/
map.rs

1use std::collections::{BTreeMap, HashMap};
2
3use crate::Value;
4
5/// Helper for flexible map construction.
6///
7/// Wraps `BTreeMap<Value, Value>` and implements `From` for `BTreeMap`,
8/// `HashMap`, slices of key-value pairs, and `()` (empty map), so that
9/// [`Value::map`] can accept all of these through a single `Into<Map>`
10/// bound. Rarely used directly.
11#[derive(Debug, Default, Clone, PartialEq, Eq)]
12pub struct Map(pub(crate) BTreeMap<Value, Value>);
13
14impl Map {
15    /// Create an empty map.
16    #[must_use]
17    pub const fn new() -> Self {
18        Self(BTreeMap::new())
19    }
20
21    /// Borrow the inner `BTreeMap`.
22    #[must_use]
23    pub const fn get_ref(&self) -> &BTreeMap<Value, Value> {
24        &self.0
25    }
26
27    /// Mutably borrow the inner `BTreeMap`.
28    pub fn get_mut(&mut self) -> &mut BTreeMap<Value, Value> {
29        &mut self.0
30    }
31
32    /// Unwrap into the inner `BTreeMap`.
33    #[must_use]
34    pub fn into_inner(self) -> BTreeMap<Value, Value> {
35        self.0
36    }
37}
38
39impl From<BTreeMap<Value, Value>> for Map {
40    fn from(map: BTreeMap<Value, Value>) -> Self {
41        Map(map)
42    }
43}
44
45impl<K: Into<Value> + Copy, V: Into<Value> + Copy> From<&BTreeMap<K, V>> for Map {
46    fn from(map: &BTreeMap<K, V>) -> Self {
47        Map(map.iter().map(|(&k, &v)| (k.into(), v.into())).collect())
48    }
49}
50
51impl<K: Into<Value> + Copy, V: Into<Value> + Copy> From<&HashMap<K, V>> for Map {
52    fn from(map: &HashMap<K, V>) -> Self {
53        Map(map.iter().map(|(&k, &v)| (k.into(), v.into())).collect())
54    }
55}
56
57impl<K: Into<Value> + Copy, V: Into<Value> + Copy> From<&[(K, V)]> for Map {
58    fn from(slice: &[(K, V)]) -> Self {
59        Self(slice.iter().map(|&(k, v)| (k.into(), v.into())).collect())
60    }
61}
62
63impl<const N: usize, K: Into<Value>, V: Into<Value>> From<[(K, V); N]> for Map {
64    fn from(array: [(K, V); N]) -> Self {
65        Self(array.into_iter().map(|(k, v)| (k.into(), v.into())).collect())
66    }
67}
68
69impl<K: Into<Value>, V: Into<Value>> From<Vec<(K, V)>> for Map {
70    fn from(vec: Vec<(K, V)>) -> Self {
71        Self(vec.into_iter().map(|(k, v)| (k.into(), v.into())).collect())
72    }
73}
74
75impl<K: Into<Value>, V: Into<Value>> From<Box<[(K, V)]>> for Map {
76    fn from(boxed: Box<[(K, V)]>) -> Self {
77        Self(
78            Vec::from(boxed)
79                .into_iter()
80                .map(|(k, v)| (k.into(), v.into()))
81                .collect(),
82        )
83    }
84}
85
86impl From<()> for Map {
87    fn from(_: ()) -> Self {
88        Self(BTreeMap::new())
89    }
90}