Skip to main content

immutable_json/
array.rs

1use crate::api::Number::{Decimal, Integer};
2use crate::api::{Number, Value};
3use crate::error::JsonIndexError;
4use crate::object::Object;
5use crate::util::{insert, push_back};
6use imbl::shared_ptr::DefaultSharedPtr;
7use imbl::vector::Iter;
8use imbl::Vector;
9use std::cmp::PartialEq;
10use std::fmt::{Display, Formatter};
11use std::hash::Hash;
12
13/// Represents a JSON array.
14#[derive(Clone, Debug, Eq, PartialEq, Hash)]
15pub struct Array {
16    vec: Vector<Value>,
17}
18
19impl Default for Array {
20    fn default() -> Self {
21        Self::new()
22    }
23}
24
25impl Display for Array {
26    /// Converts a JSON array to a string.
27    /// ```rust
28    /// # use immutable_json::api::Value;
29    /// # use immutable_json::error::Error;
30    /// # use std::str::FromStr;
31    /// # fn main() -> Result<(), Error>{
32    ///let data = r#"
33    ///    [
34    ///        "string",
35    ///        1,
36    ///        3.0,
37    ///        false,
38    ///        {"test": "test"},
39    ///        [1]
40    ///    ]"#;
41    ///
42    ///let v: serde_json::Value = serde_json::from_str(data)?;
43    ///
44    ///assert_eq!(Some(v), serde_json::from_str(&Value::from_str(data)?.to_string()).ok());
45    /// #   Ok(())
46    /// # }
47    /// ```
48    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
49        Display::fmt(&Value::Array(self.clone()), f)
50    }
51}
52
53impl FromIterator<Value> for Array {
54    /// Creates a JSON array from a stream of JSON values.
55    fn from_iter<T: IntoIterator<Item = Value>>(iter: T) -> Self {
56        iter.into_iter().fold(Self::new(), |a, v| a.add(&v))
57    }
58}
59
60impl<'a> IntoIterator for &'a Array {
61    type Item = Value;
62    type IntoIter = ArrayIter<'a>;
63
64    /// Iterates over the values in a JSON array,
65    fn into_iter(self) -> ArrayIter<'a> {
66        self.iter()
67    }
68}
69
70impl Array {
71    /// Adds a JSON value to an array.
72    /// ```rust
73    /// # use immutable_json::array::Array;
74    /// # use immutable_json::api::Value;
75    /// # fn main() {
76    ///assert_eq!(Some(true), Array::new().add(&Value::Bool(true)).get_bool(0).ok().flatten());
77    /// # }
78    /// ```
79    pub fn add(&self, value: &Value) -> Self {
80        Self {
81            vec: push_back(&self.vec, value.clone()),
82        }
83    }
84
85    /// Adds an array to an array.
86    /// ```rust
87    /// # use immutable_json::array::Array;
88    /// # fn main() {
89    ///assert_eq!(
90    ///     Some(0),
91    ///     Array::new()
92    ///         .add_array(&Array::new().add_integer(0))
93    ///         .get_array(0).ok().flatten().and_then(|a| a.get_integer(0).ok().flatten()));
94    /// # }
95    /// ```
96    pub fn add_array(&self, value: &Array) -> Self {
97        self.add(&Value::Array(value.clone()))
98    }
99
100    /// Adds a bool to an array.
101    /// ```rust
102    /// # use immutable_json::array::Array;
103    /// # fn main() {
104    ///assert_eq!(Some(true), Array::new().add_bool(true).get_bool(0).ok().flatten());
105    /// # }
106    /// ```
107    pub fn add_bool(&self, value: bool) -> Self {
108        self.add(&Value::Bool(value))
109    }
110
111    /// Adds a decimal to an array.
112    /// ```rust
113    /// # use immutable_json::array::Array;
114    /// # fn main() {
115    ///assert_eq!(Some(2.0), Array::new().add_decimal(2.0).get_decimal(0).ok().flatten());
116    /// # }
117    /// ```
118    pub fn add_decimal(&self, value: f64) -> Self {
119        self.add(&Value::Number(Decimal(value)))
120    }
121
122    /// Adds an integer to an array.
123    /// ```rust
124    /// # use immutable_json::array::Array;
125    /// # fn main() {
126    ///assert_eq!(Some(0), Array::new().add_integer(0).get_integer(0).ok().flatten());
127    /// # }
128    /// ```
129    pub fn add_integer(&self, value: i128) -> Self {
130        self.add(&Value::Number(Integer(value)))
131    }
132
133    /// Adds a number to an array.
134    /// ```rust
135    /// # use immutable_json::array::Array;
136    /// # use immutable_json::api::Number::Integer;
137    /// # fn main() {
138    ///assert_eq!(
139    ///    Some(Integer(0)),
140    ///    Array::new().add_number(Integer(0)).get_number(0).ok().flatten());
141    /// # }
142    /// ```
143    pub fn add_number(&self, value: Number) -> Self {
144        self.add(&Value::Number(value))
145    }
146
147    /// Adds an object to an array.
148    /// ```rust
149    /// # use immutable_json::array::Array;
150    /// # use immutable_json::object::Object;
151    /// # fn main() {
152    ///assert_eq!(
153    ///    Some(0),
154    ///    Array::new()
155    ///        .add_object(&Object::new().add_integer("test", 0))
156    ///        .get_object(0).ok().flatten().and_then(|o| o.get_integer("test")));
157    /// # }
158    /// ```
159    pub fn add_object(&self, value: &Object) -> Self {
160        self.add(&Value::Object(value.clone()))
161    }
162
163    /// Adds a string to an array.
164    /// ```rust
165    /// # use immutable_json::array::Array;
166    /// # fn main() {
167    ///assert_eq!(
168    ///    Some("test".to_string()),
169    ///    Array::new().add_string("test").get_string(0).ok().flatten());
170    /// # }
171    /// ```
172    pub fn add_string(&self, value: &str) -> Self {
173        self.add(&Value::String(value.to_string()))
174    }
175
176    /// Gets a JSON value from an array at a given index, which is positive and less than the length
177    /// of the array.
178    pub fn get(&self, index: usize) -> Result<Value, JsonIndexError> {
179        self.vec.get(index).cloned().ok_or_else(|| JsonIndexError {
180            index,
181            len: self.len(),
182        })
183    }
184
185    /// Gets an array from an array at a given index, which is positive and less than the length
186    /// of the array. If the value at the position is not an array, `None` is returned.
187    /// ```rust
188    /// # use immutable_json::array::Array;
189    /// # use immutable_json::api::Number::Integer;
190    /// # use immutable_json::error::JsonIndexError;
191    /// # fn main() {
192    ///let array = Array::new().add_number(Integer(0));
193    ///
194    ///assert_eq!(Some(Integer(0)), array.get_number(0).ok().flatten());
195    ///assert_eq!(None, array.get_string(0).ok().flatten());
196    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.get_number(1).err());
197    /// # }
198    /// ```
199    pub fn get_array(&self, index: usize) -> Result<Option<Array>, JsonIndexError> {
200        self.get(index).map(|v| v.as_array())
201    }
202
203    /// Gets a bool from an array at a given index, which is positive and less than the length
204    /// of the array. If the value at the position is not a Boolean, `None` is returned.
205    /// ```rust
206    /// # use immutable_json::array::Array;
207    /// # use immutable_json::error::JsonIndexError;
208    /// # fn main() {
209    ///let array = Array::new().add_bool(true);
210    ///
211    ///assert_eq!(Some(true), array.get_bool(0).ok().flatten());
212    ///assert_eq!(None, array.get_string(0).ok().flatten());
213    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.get_bool(1).err());
214    /// # }
215    /// ```
216    pub fn get_bool(&self, index: usize) -> Result<Option<bool>, JsonIndexError> {
217        self.get(index).map(|v| v.as_bool())
218    }
219
220    /// Gets a decimal from an array at a given index, which is positive and less than the length
221    /// of the array. If the value at the position is not a decimal, `None` is returned.
222    /// ```rust
223    /// # use immutable_json::array::Array;
224    /// # use immutable_json::error::JsonIndexError;
225    /// # fn main() {
226    ///let array = Array::new().add_decimal(2.0);
227    ///
228    ///assert_eq!(Some(2.0), array.get_decimal(0).ok().flatten());
229    ///assert_eq!(None, array.get_string(0).ok().flatten());
230    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.get_decimal(1).err());
231    /// # }
232    /// ```
233    pub fn get_decimal(&self, index: usize) -> Result<Option<f64>, JsonIndexError> {
234        self.get(index).map(|v| v.as_decimal())
235    }
236
237    /// Gets an integer from an array at a given index, which is positive and less than the length
238    /// of the array. If the value at the position is not an integer, `None` is returned.
239    /// ```rust
240    /// # use immutable_json::array::Array;
241    /// # use immutable_json::error::JsonIndexError;
242    /// # fn main() {
243    ///let array = Array::new().add_integer(0);
244    ///
245    ///assert_eq!(Some(0), array.get_integer(0).ok().flatten());
246    ///assert_eq!(None, array.get_string(0).ok().flatten());
247    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.get_integer(1).err());
248    /// # }
249    /// ```
250    pub fn get_integer(&self, index: usize) -> Result<Option<i128>, JsonIndexError> {
251        self.get(index).map(|v| v.as_integer())
252    }
253
254    /// Gets a number from an array at a given index, which is positive and less than the length
255    /// of the array. If the value at the position is not a number, `None` is returned.
256    /// ```rust
257    /// # use immutable_json::array::Array;
258    /// # use immutable_json::api::Number::Integer;
259    /// # use immutable_json::error::JsonIndexError;
260    /// # fn main() {
261    ///let array = Array::new().add_number(Integer(0));
262    ///
263    ///assert_eq!(Some(Integer(0)), array.get_number(0).ok().flatten());
264    ///assert_eq!(None, array.get_string(0).ok().flatten());
265    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.get_number(1).err());
266    /// # }
267    /// ```
268    pub fn get_number(&self, index: usize) -> Result<Option<Number>, JsonIndexError> {
269        self.get(index).map(|v| v.as_number())
270    }
271
272    /// Gets an object from an array at a given index, which is positive and less than the length
273    /// of the array. If the value at the position is not a JSON object, `None` is returned.
274    /// ```rust
275    /// # use immutable_json::array::Array;
276    /// # use immutable_json::object::Object;
277    /// # use immutable_json::error::JsonIndexError;
278    /// # fn main() {
279    ///let array = Array::new().add_object(&Object::new().add_integer("test", 0));
280    ///
281    ///assert_eq!(Some(0),
282    ///    array.get_object(0).ok().flatten().and_then(|o| o.get_integer("test")));
283    ///assert_eq!(None, array.get_string(0).ok().flatten());
284    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.get_object(1).err());
285    /// # }
286    /// ```
287    pub fn get_object(&self, index: usize) -> Result<Option<Object>, JsonIndexError> {
288        self.get(index).map(|v| v.as_object())
289    }
290
291    /// Gets a string from an array at a given index, which is positive and less than the length
292    /// of the array. If the value at the position is not a string, `None` is returned.
293    /// ```rust
294    /// # use immutable_json::array::Array;
295    /// # use immutable_json::error::JsonIndexError;
296    /// # fn main() {
297    ///let array = Array::new().add_string("test");
298    ///
299    ///assert_eq!(Some("test".to_string()), array.get_string(0).ok().flatten());
300    ///assert_eq!(None, array.get_integer(0).ok().flatten());
301    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.get_string(1).err());
302    /// # }
303    /// ```
304    pub fn get_string(&self, index: usize) -> Result<Option<String>, JsonIndexError> {
305        self.get(index).map(|v| v.as_string())
306    }
307
308    /// Inserts a JSON value to an array at a given index. If the index is equal to the length of
309    /// the array, the value is added at the end of it.
310    /// ```rust
311    /// # use immutable_json::array::Array;
312    /// # use immutable_json::api::Value;
313    /// # use immutable_json::error::Error;
314    /// # fn main() -> Result<(), Error>{
315    ///assert_eq!(Some(true), Array::new().insert(0, &Value::Bool(true))?.get_bool(0).ok().flatten());
316    /// # Ok(())
317    /// # }
318    /// ```
319    pub fn insert(&self, index: usize, value: &Value) -> Result<Self, JsonIndexError> {
320        if index > self.len() {
321            Err(JsonIndexError {
322                index,
323                len: self.len(),
324            })
325        } else {
326            Ok(Self {
327                vec: insert(&self.vec, index, value.clone()),
328            })
329        }
330    }
331
332    /// Inserts an array to an array at a given index. If the index is equal to the length of
333    /// the array, the value is added at the end of it.
334    /// ```rust
335    /// # use immutable_json::array::Array;
336    /// # use immutable_json::error::Error;
337    /// # fn main() -> Result<(), Error>{
338    ///assert_eq!(
339    ///    Some(0),
340    ///    Array::new()
341    ///        .insert_array(0, &Array::new().insert_integer(0, 0)?)?
342    ///        .get_array(0).ok().flatten().and_then(|a| a.get_integer(0).ok().flatten()));
343    /// # Ok(())
344    /// # }
345    /// ```
346    pub fn insert_array(&self, index: usize, value: &Array) -> Result<Self, JsonIndexError> {
347        self.insert(index, &Value::Array(value.clone()))
348    }
349
350    /// Inserts a bool to an array at a given index. If the index is equal to the length of
351    /// the array, the value is added at the end of it.
352    /// ```rust
353    /// # use immutable_json::array::Array;
354    /// # use immutable_json::error::Error;
355    /// # fn main() -> Result<(), Error>{
356    ///assert_eq!(Some(true), Array::new().insert_bool(0, true)?.get_bool(0).ok().flatten());
357    /// # Ok(())
358    /// # }
359    /// ```
360    pub fn insert_bool(&self, index: usize, value: bool) -> Result<Self, JsonIndexError> {
361        self.insert(index, &Value::Bool(value))
362    }
363
364    /// Inserts a decimal to an array at a given index. If the index is equal to the length of
365    /// the array, the value is added at the end of it.
366    /// ```rust
367    /// # use immutable_json::array::Array;
368    /// # use immutable_json::error::Error;
369    /// # fn main() -> Result<(), Error>{
370    ///assert_eq!(Some(2.0), Array::new().insert_decimal(0, 2.0)?.get_decimal(0).ok().flatten());
371    /// # Ok(())
372    /// # }
373    /// ```
374    pub fn insert_decimal(&self, index: usize, value: f64) -> Result<Self, JsonIndexError> {
375        self.insert(index, &Value::Number(Decimal(value)))
376    }
377
378    /// Inserts an integer to an array at a given index. If the index is equal to the length of
379    /// the array, the value is added at the end of it.
380    /// ```rust
381    /// # use immutable_json::array::Array;
382    /// # use immutable_json::error::Error;
383    /// # fn main() -> Result<(), Error>{
384    ///assert_eq!(Some(0), Array::new().insert_integer(0, 0)?.get_integer(0).ok().flatten());
385    /// # Ok(())
386    /// # }
387    /// ```
388    pub fn insert_integer(&self, index: usize, value: i128) -> Result<Self, JsonIndexError> {
389        self.insert(index, &Value::Number(Integer(value)))
390    }
391
392    /// Inserts a number to an array at a given index. If the index is equal to the length of
393    /// the array, the value is added at the end of it.
394    /// ```rust
395    /// # use immutable_json::array::Array;
396    /// # use immutable_json::api::Number::Integer;
397    /// # use immutable_json::error::Error;
398    /// # fn main() -> Result<(), Error>{
399    ///assert_eq!(
400    ///    Some(Integer(0)),
401    ///    Array::new().insert_number(0, Integer(0))?.get_number(0).ok().flatten());
402    /// # Ok(())
403    /// # }
404    /// ```
405    pub fn insert_number(&self, index: usize, value: Number) -> Result<Self, JsonIndexError> {
406        self.insert(index, &Value::Number(value))
407    }
408
409    /// Inserts an object to an array at a given index. If the index is equal to the length of
410    /// the array, the value is added at the end of it.
411    /// ```rust
412    /// # use immutable_json::array::Array;
413    /// # use immutable_json::object::Object;
414    /// # use immutable_json::error::Error;
415    /// # fn main() -> Result<(), Error>{
416    ///assert_eq!(
417    ///    Some(0),
418    ///    Array::new()
419    ///        .insert_object(0, &Object::new().add_integer("test", 0))?
420    ///        .get_object(0).ok().flatten().and_then(|o| o.get_integer("test")));
421    /// # Ok(())
422    /// # }
423    /// ```
424    pub fn insert_object(&self, index: usize, value: &Object) -> Result<Self, JsonIndexError> {
425        self.insert(index, &Value::Object(value.clone()))
426    }
427
428    /// Inserts a string to an array at a given index. If the index is equal to the length of
429    /// the array, the value is added at the end of it.
430    /// ```rust
431    /// # use immutable_json::array::Array;
432    /// # use immutable_json::error::Error;
433    /// # fn main() -> Result<(), Error>{
434    ///assert_eq!(
435    ///    Some("test".to_string()),
436    ///    Array::new().insert_string(0, "test")?.get_string(0).ok().flatten());
437    /// # Ok(())
438    /// # }
439    /// ```
440    pub fn insert_string(&self, index: usize, value: &str) -> Result<Self, JsonIndexError> {
441        self.insert(index, &Value::String(value.to_string()))
442    }
443
444    /// Indicates if the array is empty or not.
445    /// ```rust
446    /// # use immutable_json::array::Array;
447    /// # fn main() {
448    ///assert_eq!(true, Array::new().is_empty());
449    ///assert_eq!(false, Array::new().add_integer(0).is_empty());
450    /// # }
451    /// ```
452    pub fn is_empty(&self) -> bool {
453        self.vec.is_empty()
454    }
455
456    /// Returns an iterator over the values of the array.
457    /// ```rust
458    /// # use immutable_json::array::Array;
459    /// # fn main() {
460    ///let array = Array::new().add_string("test").add_integer(1);
461    ///
462    ///assert_eq!(array, Array::from_iter(array.iter()));
463    /// # }
464    /// ```
465    pub fn iter(&'_ self) -> ArrayIter<'_> {
466        ArrayIter {
467            iter: self.vec.iter(),
468        }
469    }
470
471    /// Returns the length of an array.
472    /// ```rust
473    /// # use immutable_json::array::Array;
474    /// # fn main() {
475    ///assert_eq!(0, Array::new().len());
476    ///assert_eq!(1, Array::new().add_integer(0).len());
477    /// # }
478    /// ```
479    pub fn len(&self) -> usize {
480        self.vec.len()
481    }
482
483    /// Creates an empty JSON array.
484    pub fn new() -> Self {
485        Self { vec: Vector::new() }
486    }
487
488    /// Removes a JSON value from an array at a given index, which is positive and less than the
489    /// length of the array.
490    /// ```rust
491    /// # use immutable_json::array::Array;
492    /// # use immutable_json::error::JsonIndexError;
493    /// # fn main() {
494    ///assert_eq!(Some(0), Array::new().add_integer(0).remove(0).ok().map(|a| a.len()));
495    ///assert_eq!(Some(JsonIndexError { index: 1, len: 0, }), Array::new().remove(1).err());
496    /// # }
497    /// ```
498    pub fn remove(&self, index: usize) -> Result<Self, JsonIndexError> {
499        if index >= self.len() {
500            Err(JsonIndexError {
501                index,
502                len: self.len(),
503            })
504        } else {
505            let mut new_vec = self.vec.clone();
506
507            new_vec.remove(index);
508            Ok(Self { vec: new_vec })
509        }
510    }
511
512    /// Sets a JSON value in an array at a given index, which is positive and less than the length
513    /// of the array.
514    pub fn set(&self, index: usize, value: &Value) -> Result<Self, JsonIndexError> {
515        if index >= self.len() {
516            Err(JsonIndexError {
517                index,
518                len: self.len(),
519            })
520        } else {
521            let mut new_vec = self.vec.clone();
522
523            new_vec.set(index, value.clone());
524            Ok(Self { vec: new_vec })
525        }
526    }
527
528    /// Sets an array in an array at a given index, which is positive and less than the length
529    /// of the array.
530    /// ```rust
531    /// # use immutable_json::array::Array;
532    /// # use immutable_json::error::JsonIndexError;
533    /// # fn main() {
534    ///let array = Array::new().add_bool(true);
535    ///
536    ///assert_eq!(
537    ///    Some(0),
538    ///    array
539    ///        .set_array(0, &Array::new().add_integer(0))
540    ///        .ok()
541    ///        .and_then(|a| {
542    ///            a.get_array(0).ok().flatten().and_then(|a| a.get_integer(0).ok().flatten())
543    ///        }));
544    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.set_bool(1, false).err());
545    /// # }
546    /// ```
547    pub fn set_array(&self, index: usize, value: &Array) -> Result<Self, JsonIndexError> {
548        self.set(index, &Value::Array(value.clone()))
549    }
550
551    /// Sets a bool in an array at a given index, which is positive and less than the length
552    /// of the array.
553    /// ```rust
554    /// # use immutable_json::array::Array;
555    /// # use immutable_json::error::JsonIndexError;
556    /// # fn main() {
557    ///let array = Array::new().add_bool(true);
558    ///
559    ///assert_eq!(
560    ///    Some(false),
561    ///    array
562    ///        .set_bool(0, false)
563    ///        .ok()
564    ///        .and_then(|a| a.get_bool(0).ok().flatten()));
565    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.set_bool(1, false).err());
566    /// # }
567    /// ```
568    pub fn set_bool(&self, index: usize, value: bool) -> Result<Self, JsonIndexError> {
569        self.set(index, &Value::Bool(value))
570    }
571
572    /// Sets a decimal in an array at a given index, which is positive and less than the length
573    /// of the array.
574    /// ```rust
575    /// # use immutable_json::array::Array;
576    /// # use immutable_json::error::JsonIndexError;
577    /// # fn main() {
578    ///let array = Array::new().add_bool(true);
579    ///
580    ///assert_eq!(
581    ///    Some(3.0),
582    ///    array
583    ///        .set_decimal(0, 3.0)
584    ///        .ok()
585    ///        .and_then(|a| a.get_decimal(0).ok().flatten()));
586    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.set_decimal(1, 1.0).err());
587    /// # }
588    /// ```
589    pub fn set_decimal(&self, index: usize, value: f64) -> Result<Self, JsonIndexError> {
590        self.set(index, &Value::Number(Decimal(value)))
591    }
592
593    /// Sets an integer in an array at a given index, which is positive and less than the length
594    /// of the array.
595    /// ```rust
596    /// # use immutable_json::array::Array;
597    /// # use immutable_json::error::JsonIndexError;
598    /// # fn main() {
599    ///let array = Array::new().add_bool(true);
600    ///
601    ///assert_eq!(
602    ///    Some(3),
603    ///    array
604    ///        .set_integer(0, 3)
605    ///        .ok()
606    ///        .and_then(|a| a.get_integer(0).ok().flatten()));
607    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.set_integer(1, 1).err());
608    /// # }
609    /// ```
610    pub fn set_integer(&self, index: usize, value: i128) -> Result<Self, JsonIndexError> {
611        self.set(index, &Value::Number(Integer(value)))
612    }
613
614    /// Sets a number in an array at a given index, which is positive and less than the length
615    /// of the array.
616    /// ```rust
617    /// # use immutable_json::array::Array;
618    /// # use immutable_json::api::Number::Decimal;
619    /// # use immutable_json::error::JsonIndexError;
620    /// # fn main() {
621    ///let array = Array::new().add_bool(true);
622    ///
623    ///assert_eq!(
624    ///    Some(Decimal(3.0)),
625    ///    array
626    ///        .set_number(0, Decimal(3.0))
627    ///        .ok()
628    ///        .and_then(|a| a.get_number(0).ok().flatten()));
629    ///assert_eq!(
630    ///    Some(JsonIndexError { index: 1, len: 1, }),
631    ///    array.set_number(1, Decimal(1.0)).err());
632    /// # }
633    /// ```
634    pub fn set_number(&self, index: usize, value: Number) -> Result<Self, JsonIndexError> {
635        self.set(index, &Value::Number(value))
636    }
637
638    /// Sets an object in an array at a given index, which is positive and less than the length
639    /// of the array.
640    /// ```rust
641    /// # use immutable_json::array::Array;
642    /// # use immutable_json::object::Object;
643    /// # use immutable_json::error::JsonIndexError;
644    /// # fn main() {
645    ///let array = Array::new().add_bool(true);
646    ///
647    ///assert_eq!(
648    ///    Some("test".to_string()),
649    ///    array
650    ///        .set_object(0, &Object::new().add_string("test", "test"))
651    ///        .ok()
652    ///        .and_then(|a| a.get_object(0).ok().flatten().and_then(|o| o.get_string("test"))));
653    ///assert_eq!(
654    ///    Some(JsonIndexError { index: 1, len: 1, }),
655    ///    array.set_object(1, &Object::new()).err());
656    /// # }
657    /// ```
658    pub fn set_object(&self, index: usize, value: &Object) -> Result<Self, JsonIndexError> {
659        self.set(index, &Value::Object(value.clone()))
660    }
661
662    /// Sets a string in an array at a given index, which is positive and less than the length
663    /// of the array.
664    /// ```rust
665    /// # use immutable_json::array::Array;
666    /// # use immutable_json::error::JsonIndexError;
667    /// # fn main() {
668    ///let array = Array::new().add_bool(true);
669    ///
670    ///assert_eq!(
671    ///    Some("test".to_string()),
672    ///    array
673    ///        .set_string(0, "test")
674    ///        .ok()
675    ///        .and_then(|a| a.get_string(0).ok().flatten()));
676    ///assert_eq!(Some(JsonIndexError { index: 1, len: 1, }), array.set_string(1, "test").err());
677    /// # }
678    /// ```
679    pub fn set_string(&self, index: usize, value: &str) -> Result<Self, JsonIndexError> {
680        self.set(index, &Value::String(value.to_string()))
681    }
682}
683
684#[derive(Clone)]
685pub struct ArrayIter<'a> {
686    iter: Iter<'a, Value, DefaultSharedPtr>,
687}
688
689impl<'a> Iterator for ArrayIter<'a> {
690    type Item = Value;
691
692    fn next(&mut self) -> Option<Self::Item> {
693        self.iter.next().cloned()
694    }
695}