Skip to main content

jsonx_lib/
array.rs

1//! JSON arrays.
2
3use alloc::vec::{self, Vec};
4use core::{
5    fmt,
6    ops::{Deref, DerefMut},
7    slice,
8};
9
10use crate::{Value, tree};
11
12/// A JSON array: a list of values in document order.
13///
14/// `Array` dereferences to `Vec<Value>`, so every slice and vector method
15/// works on it directly (`len`, `iter`, `push`, indexing, sorting). It exists
16/// as its own type rather than a bare `Vec` so that dropping, cloning, and
17/// comparing an arbitrarily deep value uses bounded stack.
18///
19/// # Examples
20///
21/// ```
22/// use jsonx_lib::{json, parse, Array, Value};
23///
24/// let doc = parse("[1, [2, 3]]")?;
25/// let items: &Array = doc.as_array().unwrap();
26/// assert_eq!(items.len(), 2);
27/// assert_eq!(items[1][0], 2);
28///
29/// let mut built = Array::new();
30/// built.push(Value::from("a"));
31/// built.push(json!(null));
32/// assert_eq!(Value::Array(built).to_string(), r#"["a",null]"#);
33/// # Ok::<(), jsonx_lib::Error>(())
34/// ```
35#[derive(Default)]
36pub struct Array<'a> {
37    items: Vec<Value<'a>>,
38}
39
40impl<'a> Array<'a> {
41    /// An empty array. Does not allocate.
42    ///
43    /// # Examples
44    ///
45    /// ```
46    /// assert!(jsonx_lib::Array::new().is_empty());
47    /// ```
48    #[inline]
49    #[must_use]
50    pub const fn new() -> Self {
51        Self { items: Vec::new() }
52    }
53
54    /// An empty array with room for `capacity` items.
55    ///
56    /// # Examples
57    ///
58    /// ```
59    /// let a = jsonx_lib::Array::with_capacity(8);
60    /// assert!(a.capacity() >= 8);
61    /// ```
62    #[inline]
63    #[must_use]
64    pub fn with_capacity(capacity: usize) -> Self {
65        Self {
66            items: Vec::with_capacity(capacity),
67        }
68    }
69
70    /// Takes the items out as a `Vec`.
71    ///
72    /// # Examples
73    ///
74    /// ```
75    /// let doc = jsonx_lib::parse("[true, false]")?;
76    /// let items = doc.as_array().cloned().unwrap_or_default().into_vec();
77    /// assert_eq!(items, [true, false]);
78    /// # Ok::<(), jsonx_lib::Error>(())
79    /// ```
80    #[inline]
81    #[must_use]
82    pub fn into_vec(mut self) -> Vec<Value<'a>> {
83        core::mem::take(&mut self.items)
84    }
85
86    /// Copies every borrowed string so the array no longer borrows from the
87    /// input. Iterative at any depth.
88    ///
89    /// # Examples
90    ///
91    /// ```
92    /// use jsonx_lib::{parse, Array};
93    ///
94    /// let owned: Array<'static> = {
95    ///     let text = String::from(r#"["x"]"#);
96    ///     parse(&text)?.as_array().cloned().unwrap_or_default().into_owned()
97    /// };
98    /// assert_eq!(owned[0], "x");
99    /// # Ok::<(), jsonx_lib::Error>(())
100    /// ```
101    #[must_use]
102    pub fn into_owned(self) -> Array<'static> {
103        match tree::into_owned(Value::Array(self)) {
104            Value::Array(a) => a,
105            _ => Array::new(),
106        }
107    }
108
109    #[inline]
110    pub(crate) fn items_mut(&mut self) -> &mut Vec<Value<'a>> {
111        &mut self.items
112    }
113}
114
115impl<'a> Deref for Array<'a> {
116    type Target = Vec<Value<'a>>;
117
118    #[inline]
119    fn deref(&self) -> &Self::Target {
120        &self.items
121    }
122}
123
124impl DerefMut for Array<'_> {
125    #[inline]
126    fn deref_mut(&mut self) -> &mut Self::Target {
127        &mut self.items
128    }
129}
130
131impl Drop for Array<'_> {
132    fn drop(&mut self) {
133        // Recursion is capped at a fixed depth; deeper parts are flattened
134        // onto an explicit stack, so a deep value never exhausts the stack.
135        tree::drop_items(&mut self.items);
136    }
137}
138
139impl Clone for Array<'_> {
140    fn clone(&self) -> Self {
141        Self {
142            items: tree::clone_items(&self.items),
143        }
144    }
145}
146
147impl PartialEq for Array<'_> {
148    fn eq(&self, other: &Self) -> bool {
149        self.items.len() == other.items.len()
150            && self
151                .items
152                .iter()
153                .zip(&other.items)
154                .all(|(a, b)| tree::eq(a, b))
155    }
156}
157
158impl Eq for Array<'_> {}
159
160impl fmt::Debug for Array<'_> {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        f.debug_list().entries(self.items.iter()).finish()
163    }
164}
165
166impl<'a> From<Vec<Value<'a>>> for Array<'a> {
167    #[inline]
168    fn from(items: Vec<Value<'a>>) -> Self {
169        Self { items }
170    }
171}
172
173impl<'a, T: Into<Value<'a>>> FromIterator<T> for Array<'a> {
174    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
175        Self {
176            items: iter.into_iter().map(Into::into).collect(),
177        }
178    }
179}
180
181impl<'a, T: Into<Value<'a>>> Extend<T> for Array<'a> {
182    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
183        self.items.extend(iter.into_iter().map(Into::into));
184    }
185}
186
187impl<'a> IntoIterator for Array<'a> {
188    type Item = Value<'a>;
189    type IntoIter = vec::IntoIter<Value<'a>>;
190
191    #[inline]
192    fn into_iter(self) -> Self::IntoIter {
193        self.into_vec().into_iter()
194    }
195}
196
197impl<'r, 'a> IntoIterator for &'r Array<'a> {
198    type Item = &'r Value<'a>;
199    type IntoIter = slice::Iter<'r, Value<'a>>;
200
201    #[inline]
202    fn into_iter(self) -> Self::IntoIter {
203        self.items.iter()
204    }
205}
206
207impl<'r, 'a> IntoIterator for &'r mut Array<'a> {
208    type Item = &'r mut Value<'a>;
209    type IntoIter = slice::IterMut<'r, Value<'a>>;
210
211    #[inline]
212    fn into_iter(self) -> Self::IntoIter {
213        self.items.iter_mut()
214    }
215}