Skip to main content

simd_json/value/tape/
array.rs

1use super::Value;
2use crate::Node;
3
4#[derive(Clone, Copy)]
5/// Wrapper around the tape that allows interacting with it via a `Array`-like API.
6pub struct Array<'tape, 'input>(pub(super) &'tape [Node<'input>]);
7
8/// Iterator over the elements of a tape `Array`
9pub struct Iter<'tape, 'input>(&'tape [Node<'input>]);
10
11impl<'tape, 'input> Iterator for Iter<'tape, 'input> {
12    type Item = Value<'tape, 'input>;
13
14    fn next(&mut self) -> Option<Self::Item> {
15        let (head, tail) = self.0.split_at(self.0.first()?.count());
16        self.0 = tail;
17        Some(Value(head))
18    }
19}
20
21// value_trait::Array for
22impl<'tape, 'input> Array<'tape, 'input>
23where
24    'input: 'tape,
25{
26    /// Gets a ref to a value based on n index, returns `None` if the
27    /// current Value isn't an Array or doesn't contain the index
28    /// it was asked for.
29    #[must_use]
30    pub fn get(&self, mut idx: usize) -> Option<Value<'tape, 'input>> {
31        let mut offset = 1;
32        while idx > 0 {
33            offset += self.0.get(offset)?.count();
34            idx -= 1;
35        }
36        let count = self.0.get(offset)?.count();
37        Some(Value(&self.0[offset..offset + count]))
38    }
39
40    /// Iterates over the values paris
41    #[must_use]
42    pub fn iter<'i>(&'i self) -> Iter<'tape, 'input> {
43        Iter(&self.0[1..])
44    }
45
46    /// Number of key/value pairs
47    /// # Panics
48    /// if the tape is not an array
49    #[must_use]
50    pub fn len(&self) -> usize {
51        if let Some(Node::Array { len, .. }) = self.0.first() {
52            *len
53        } else {
54            panic!("invalid tape array")
55        }
56    }
57    /// Returns if the array is empty
58    #[must_use]
59    pub fn is_empty(&self) -> bool {
60        self.len() == 0
61    }
62}
63
64impl<'tape, 'input> IntoIterator for &Array<'tape, 'input> {
65    type IntoIter = Iter<'tape, 'input>;
66    type Item = Value<'tape, 'input>;
67    fn into_iter(self) -> Self::IntoIter {
68        self.iter()
69    }
70}
71
72#[cfg(test)]
73mod test {
74    use crate::to_tape;
75    use value_trait::base::ValueAsScalar;
76
77    #[test]
78    fn get_ints() -> crate::Result<()> {
79        let mut input = b"[1,2,3,4]".to_vec();
80        let t = to_tape(input.as_mut_slice())?;
81        let v = t.as_value();
82        let a = v.as_array().expect("is an array");
83        assert_eq!(a.get(0).and_then(|v| v.as_u64()), Some(1));
84        assert_eq!(a.get(1).and_then(|v| v.as_u64()), Some(2));
85        assert_eq!(a.get(2).and_then(|v| v.as_u64()), Some(3));
86        assert_eq!(a.get(3).and_then(|v| v.as_u64()), Some(4));
87        assert_eq!(a.get(4), None);
88        Ok(())
89    }
90
91    #[test]
92    fn get_nested() -> crate::Result<()> {
93        let mut input = b"[1,[2,3],4]".to_vec();
94        let t = to_tape(input.as_mut_slice())?;
95        let v = t.as_value();
96        let a = v.as_array().expect("is an array");
97        assert_eq!(a.get(0).and_then(|v| v.as_u64()), Some(1));
98        let a1 = a.get(1).expect("has first element");
99        let a2 = a1.as_array().expect("is an array");
100        assert_eq!(a2.get(0).and_then(|v| v.as_u64()), Some(2));
101        assert_eq!(a2.get(1).and_then(|v| v.as_u64()), Some(3));
102        assert_eq!(a.get(2).and_then(|v| v.as_u64()), Some(4));
103        assert_eq!(a.get(3), None);
104        Ok(())
105    }
106
107    #[test]
108    fn iter() -> crate::Result<()> {
109        let mut input = b"[1,2,3,4]".to_vec();
110        let t = to_tape(input.as_mut_slice())?;
111        let v = t.as_value();
112        let a = v.as_array().expect("is an array");
113        let v = a
114            .iter()
115            .map(|v| v.as_u8().expect("integer"))
116            .collect::<Vec<_>>();
117
118        assert_eq!(v, vec![1, 2, 3, 4]);
119
120        Ok(())
121    }
122    #[test]
123    fn iter_container() -> crate::Result<()> {
124        let mut input = b"[1,[2,3],4]".to_vec();
125        let t = to_tape(input.as_mut_slice())?;
126        let v = t.as_value();
127        let a = v.as_array().expect("is an array");
128        let v = a.iter().map(|v| v.as_u8()).collect::<Vec<_>>();
129
130        assert_eq!(v, vec![Some(1), None, Some(4)]);
131
132        Ok(())
133    }
134}