thrift_codec/data/
map.rs

1use crate::data::{DataKind, DataRef, Elements};
2use crate::{ErrorKind, Result};
3
4/// Map.
5///
6/// Internally this is represented by the data structure called "associative array".
7/// No duplicate keys are removed.
8#[derive(Debug, Clone, PartialEq)]
9#[cfg_attr(feature = "serde", derive(Serialize))]
10pub struct Map(Option<Inner>);
11impl Map {
12    /// Makes an empty `Map` instance.
13    ///
14    /// Note that the returning value could not be encoded by the binary protocol encoding.
15    pub fn empty() -> Self {
16        Map(None)
17    }
18
19    /// Makes a new `Map` instance.
20    pub fn new<I, K, V>(pairs: I) -> Self
21    where
22        I: Iterator<Item = (K, V)>,
23        Vec<K>: Into<Elements>,
24        Vec<V>: Into<Elements>,
25    {
26        let mut keys = Vec::new();
27        let mut values = Vec::new();
28        for (k, v) in pairs {
29            keys.push(k);
30            values.push(v);
31        }
32        Map(Some(Inner {
33            keys: keys.into(),
34            values: values.into(),
35        }))
36    }
37
38    /// Makes a new `Map` instance from the separate `keys` and `values`.
39    ///
40    /// # Errors
41    ///
42    /// If the lengths of `keys` and `values` are differed,
43    /// this function will return an error which kind is `ErrorKind::InvalidInput`.
44    pub fn from_keys_and_values(keys: Elements, values: Elements) -> Result<Self> {
45        track_assert_eq!(keys.len(), values.len(), ErrorKind::InvalidInput);
46        Ok(Map(Some(Inner { keys, values })))
47    }
48
49    /// Returns the entry placed at the specified index.
50    pub fn get(&self, index: usize) -> Option<(DataRef, DataRef)> {
51        self.0.as_ref().and_then(|inner| inner.get(index))
52    }
53
54    /// Returns an iterator over this map.
55    pub fn iter(&self) -> MapIter {
56        MapIter {
57            map: self,
58            index: 0,
59        }
60    }
61
62    /// Returns the kind of the keys in this map.
63    pub fn key_kind(&self) -> Option<DataKind> {
64        self.0.as_ref().map(|inner| inner.keys.kind())
65    }
66
67    /// Returns the kind of the values in this map.
68    pub fn value_kind(&self) -> Option<DataKind> {
69        self.0.as_ref().map(|inner| inner.values.kind())
70    }
71
72    /// Returns the number of the entries in this map.
73    pub fn len(&self) -> usize {
74        self.0.as_ref().map_or(0, |inner| inner.len())
75    }
76
77    /// Returns `true` if this map has no entries.
78    pub fn is_empty(&self) -> bool {
79        self.len() == 0
80    }
81}
82
83#[derive(Debug, Clone, PartialEq)]
84#[cfg_attr(feature = "serde", derive(Serialize))]
85struct Inner {
86    keys: Elements,
87    values: Elements,
88}
89impl Inner {
90    pub fn get(&self, index: usize) -> Option<(DataRef, DataRef)> {
91        self.keys
92            .get(index)
93            .map(|k| (k, self.values.get(index).expect("Never fails")))
94    }
95    pub fn len(&self) -> usize {
96        self.keys.len()
97    }
98}
99
100/// An iterator which traverse the entries of a `Map`.
101#[derive(Debug)]
102pub struct MapIter<'a> {
103    map: &'a Map,
104    index: usize,
105}
106impl<'a> Iterator for MapIter<'a> {
107    type Item = (DataRef<'a>, DataRef<'a>);
108    fn next(&mut self) -> Option<Self::Item> {
109        self.index += 1;
110        self.map.get(self.index - 1)
111    }
112}