nson/
array.rs

1//! Array
2
3use core::fmt;
4use core::iter::FromIterator;
5use core::ops::{Deref, DerefMut};
6
7use alloc::string::String;
8use alloc::vec::Vec;
9
10#[cfg(feature = "std")]
11use std::io::{Read, Write};
12
13#[cfg(not(feature = "std"))]
14use crate::io::{Read, Write};
15
16use crate::decode::{DecodeResult, decode_array};
17use crate::encode::{EncodeResult, encode_array};
18
19use super::id::Id;
20use super::map::Map;
21use super::value::Value;
22
23#[derive(Clone, PartialEq, Default, Eq)]
24pub struct Array {
25    inner: Vec<Value>,
26}
27
28impl Array {
29    pub fn new() -> Array {
30        Array { inner: Vec::new() }
31    }
32
33    pub fn with_capacity(capacity: usize) -> Array {
34        Array {
35            inner: Vec::with_capacity(capacity),
36        }
37    }
38
39    pub fn from_vec(vec: Vec<Value>) -> Array {
40        Array { inner: vec }
41    }
42
43    pub fn len(&self) -> usize {
44        self.inner.len()
45    }
46
47    pub fn is_empty(&self) -> bool {
48        self.inner.is_empty()
49    }
50
51    pub fn push(&mut self, value: impl Into<Value>) {
52        self.inner.push(value.into());
53    }
54
55    pub fn push_value(&mut self, value: Value) {
56        self.inner.push(value);
57    }
58
59    pub fn inner(&self) -> &Vec<Value> {
60        &self.inner
61    }
62
63    pub fn as_mut_inner(&mut self) -> &mut Vec<Value> {
64        &mut self.inner
65    }
66
67    pub fn into_inner(self) -> Vec<Value> {
68        self.inner
69    }
70
71    pub fn iter(&self) -> core::slice::Iter<'_, Value> {
72        self.into_iter()
73    }
74
75    pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, Value> {
76        self.into_iter()
77    }
78
79    pub fn bytes_size(&self) -> usize {
80        4 + self.iter().map(|v| v.bytes_size() + 1).sum::<usize>() + 1
81    }
82
83    pub fn encode(&self, writer: &mut impl Write) -> EncodeResult<()> {
84        encode_array(writer, self)
85    }
86
87    pub fn decode(reader: &mut impl Read) -> DecodeResult<Array> {
88        decode_array(reader)
89    }
90}
91
92impl fmt::Debug for Array {
93    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94        write!(f, "{:?}", self.inner)
95    }
96}
97
98impl Deref for Array {
99    type Target = Vec<Value>;
100    fn deref(&self) -> &Vec<Value> {
101        &self.inner
102    }
103}
104
105impl DerefMut for Array {
106    fn deref_mut(&mut self) -> &mut Vec<Value> {
107        &mut self.inner
108    }
109}
110
111impl AsRef<Vec<Value>> for Array {
112    fn as_ref(&self) -> &Vec<Value> {
113        &self.inner
114    }
115}
116
117macro_rules! array_from_impls {
118    ($($T:ty)+) => {
119        $(
120            impl From<Vec<$T>> for Array {
121                fn from(vec: Vec<$T>) -> Array {
122                    vec.into_iter().map(Into::into).collect()
123                }
124            }
125        )+
126    }
127}
128
129array_from_impls! {
130    f32 f64 i32 i64 u32 u64 i8 u8 i16 u16 &str String &String Array
131    Map bool Vec<u8> Id
132}
133
134impl IntoIterator for Array {
135    type Item = Value;
136    type IntoIter = alloc::vec::IntoIter<Value>;
137
138    fn into_iter(self) -> Self::IntoIter {
139        self.inner.into_iter()
140    }
141}
142
143impl<'a> IntoIterator for &'a Array {
144    type Item = &'a Value;
145    type IntoIter = core::slice::Iter<'a, Value>;
146
147    fn into_iter(self) -> Self::IntoIter {
148        self.inner.iter()
149    }
150}
151
152impl<'a> IntoIterator for &'a mut Array {
153    type Item = &'a mut Value;
154    type IntoIter = core::slice::IterMut<'a, Value>;
155
156    fn into_iter(self) -> Self::IntoIter {
157        self.inner.iter_mut()
158    }
159}
160
161impl FromIterator<Value> for Array {
162    fn from_iter<I: IntoIterator<Item = Value>>(iter: I) -> Self {
163        let mut array = Array::new();
164
165        for i in iter {
166            array.push(i);
167        }
168
169        array
170    }
171}
172
173#[cfg(test)]
174mod test {
175    use crate::Array;
176
177    #[test]
178    fn to_vec() {
179        let mut array = Array::new();
180
181        array.push(123);
182        array.push("haha");
183
184        let vec = array.to_bytes().unwrap();
185
186        let array2 = Array::from_bytes(&vec).unwrap();
187
188        assert_eq!(array, array2);
189    }
190}