sonic_rs/value/array.rs
1//! Represents a parsed JSON array. Its APIs are likes `Vec<Value>`.
2use std::{
3 fmt::Debug,
4 iter::FusedIterator,
5 ops::{Deref, DerefMut, RangeBounds},
6};
7
8use ref_cast::RefCast;
9
10use super::node::ValueMut;
11use crate::{
12 serde::tri,
13 value::{
14 node::{Value, ValueRefInner},
15 value_trait::JsonValueTrait,
16 },
17};
18
19/// Array represents a JSON array. Its APIs are likes `Array<Value>`.
20///
21/// # Example
22/// ```
23/// use sonic_rs::{array, Array, JsonContainerTrait};
24///
25/// let mut arr: Array = sonic_rs::from_str("[1, 2, 3]").unwrap();
26/// assert_eq!(arr[0], 1);
27///
28/// let mut arr = array![1, 2, 3];
29/// assert_eq!(arr[0], 1);
30///
31/// let j = sonic_rs::json!([1, 2, 3]);
32/// assert_eq!(j.as_array().unwrap()[0], 1);
33/// ```
34#[derive(Debug, Eq, PartialEq, Clone, RefCast)]
35#[repr(transparent)]
36pub struct Array(pub(crate) Value);
37
38impl Array {
39 /// Returns the inner [`Value`].
40 #[inline]
41 pub fn into_value(self) -> Value {
42 self.0
43 }
44
45 /// Constructs a new, empty `Array`.
46 ///
47 /// The array will not allocate until elements are pushed onto it.
48 ///
49 /// # Example
50 /// ```
51 /// use sonic_rs::{array, from_str, json, prelude::*, Array};
52 ///
53 /// let mut arr: Array = from_str("[]").unwrap();
54 /// dbg!(&arr);
55 /// arr.push(array![]);
56 /// arr.push(1);
57 /// arr[0] = "hello".into();
58 /// arr[1] = array![].into();
59 /// assert_eq!(arr[0], "hello");
60 /// assert_eq!(arr[1], array![]);
61 /// ```
62 #[inline]
63 pub const fn new() -> Self {
64 Array(Value::new_array())
65 }
66
67 /// Constructs a new, empty `Array` with at least the specified capacity.
68 ///
69 /// The array will be able to hold at least `capacity` elements without
70 /// reallocating. This method is allowed to allocate for more elements than
71 /// `capacity`. If `capacity` is 0, the array will not allocate.
72 ///
73 /// # Panics
74 ///
75 /// Panics if the new capacity exceeds `isize::MAX` bytes.
76 #[inline]
77 pub fn with_capacity(capacity: usize) -> Self {
78 let mut array = Self::new();
79 array.reserve(capacity);
80 array
81 }
82
83 /// Reserves capacity for at least `additional` more elements to be inserted
84 /// in the given `Array`. The collection may reserve more space to
85 /// speculatively avoid frequent reallocations. After calling `reserve`,
86 /// capacity will be greater than or equal to `self.len() + additional`.
87 /// Does nothing if capacity is already sufficient.
88 ///
89 /// # Panics
90 ///
91 /// Panics if the new capacity exceeds `isize::MAX` bytes.
92 ///
93 /// # Examples
94 /// ```
95 /// use sonic_rs::array;
96 /// let mut arr = array![1, 2, 3];
97 /// arr.reserve(10);
98 /// assert!(arr.capacity() >= 13);
99 /// ```
100 #[inline]
101 pub fn reserve(&mut self, additional: usize) {
102 self.0.reserve::<Value>(additional);
103 }
104
105 /// Resizes the `Array` in-place so that `len` is equal to `new_len`.
106 ///
107 /// If `new_len` is greater than `len`, the `Array` is extended by the
108 /// difference, with each additional slot filled with the `Value` converted from `value`.
109 /// If `new_len` is less than `len`, the `Array` is simply truncated.
110 ///
111 /// If you need more flexibility, use [`Array::resize_with`].
112 /// If you only need to resize to a smaller size, use [`Array::truncate`].
113 ///
114 /// # Examples
115 ///
116 /// ```
117 /// use sonic_rs::{array, json};
118 ///
119 /// let mut arr = array!["hello"];
120 /// arr.resize(3, "world");
121 /// assert_eq!(arr, ["hello", "world", "world"]);
122 ///
123 /// arr.resize(2, 0);
124 /// assert_eq!(arr, ["hello", "world"]);
125 ///
126 /// arr.resize(4, json!("repeat"));
127 /// assert_eq!(arr, array!["hello", "world", "repeat", "repeat"]);
128 /// ```
129 #[inline]
130 pub fn resize<T: Clone + Into<Value>>(&mut self, new_len: usize, value: T) {
131 if new_len > self.len() {
132 self.reserve(new_len - self.len());
133 for _ in self.len()..new_len {
134 self.push(value.clone().into());
135 }
136 } else {
137 self.truncate(new_len);
138 }
139 }
140
141 /// Resizes the `Array` in-place so that `len` is equal to `new_len`.
142 ///
143 /// If `new_len` is greater than `len`, the `Array` is extended by the
144 /// difference, with each additional slot filled with the result of
145 /// calling the closure `f`. The return values from `f` will end up
146 /// in the `Array` in the order they have been generated.
147 ///
148 /// If `new_len` is less than `len`, the `Array` is simply truncated.
149 ///
150 ///
151 /// # Examples
152 ///
153 /// ```
154 /// use sonic_rs::array;
155 /// let mut arr = array![1, 2, 3];
156 /// arr.resize_with(5, Default::default);
157 /// assert_eq!(arr, array![1, 2, 3, null, null]);
158 ///
159 /// let mut arr = array![];
160 /// let mut p = 1;
161 /// arr.resize_with(4, || {
162 /// p *= 2;
163 /// p.into()
164 /// });
165 /// assert_eq!(arr, [2, 4, 8, 16]);
166 /// ```
167 #[inline]
168 pub fn resize_with<F>(&mut self, new_len: usize, mut f: F)
169 where
170 F: FnMut() -> Value,
171 {
172 if new_len > self.len() {
173 self.reserve(new_len - self.len());
174 for _ in self.len()..new_len {
175 self.push(f());
176 }
177 } else {
178 self.truncate(new_len);
179 }
180 }
181
182 /// Retains only the elements specified by the predicate.
183 ///
184 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
185 /// This method operates in place, visiting each element exactly once in the
186 /// original order, and preserves the order of the retained elements.
187 ///
188 /// Because the elements are visited exactly once in the original order,
189 /// external state may be used to decide which elements to keep.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// use sonic_rs::array;
195 /// let mut arr = array![1, 2, 3, 4, 5];
196 /// let keep = [false, true, true, false, true];
197 /// let mut iter = keep.iter();
198 /// arr.retain(|_| *iter.next().unwrap());
199 /// assert_eq!(arr, array![2, 3, 5]);
200 /// ```
201 #[inline]
202 pub fn retain<F>(&mut self, mut f: F)
203 where
204 F: FnMut(&Value) -> bool,
205 {
206 self.retain_mut(|elem| f(elem));
207 }
208
209 /// Splits the collection into two at the given index.
210 ///
211 /// Returns a newly allocated array containing the elements in the range
212 /// `[at, len)`. After the call, the original array will be left containing
213 /// the elements `[0, at)` with its previous capacity unchanged.
214 ///
215 /// # Panics
216 ///
217 /// Panics if `at > len`.
218 ///
219 /// # Examples
220 ///
221 /// ```
222 /// use sonic_rs::array;
223 /// let mut arr = array![1, 2, 3];
224 /// let arr2 = arr.split_off(1);
225 /// assert_eq!(arr, [1]);
226 /// assert_eq!(arr2, [2, 3]);
227 /// assert_eq!(arr.split_off(1), array![]);
228 /// ```
229 #[inline]
230 pub fn split_off(&mut self, at: usize) -> Self {
231 if let ValueMut::Array(array) = self.0.as_mut() {
232 array.split_off(at).into()
233 } else {
234 panic!("Array::split_off: not an array");
235 }
236 }
237
238 /// Removes an element from the array and returns it.
239 ///
240 /// The removed element is replaced by the last element of the array.
241 ///
242 /// This does not preserve ordering, but is *O*(1).
243 /// If you need to preserve the element order, use [`remove`] instead.
244 ///
245 /// [`remove`]: Array::remove
246 ///
247 /// # Panics
248 ///
249 /// Panics if `index` is out of bounds.
250 ///
251 /// # Examples
252 ///
253 /// ```
254 /// use sonic_rs::array;
255 /// let mut v = array!["foo", "bar", "baz", "qux"];
256 ///
257 /// assert_eq!(v.swap_remove(1), "bar");
258 /// assert_eq!(v, ["foo", "qux", "baz"]);
259 ///
260 /// assert_eq!(v.swap_remove(0), "foo");
261 /// assert_eq!(v, ["baz", "qux"]);
262 /// ```
263 #[inline]
264 pub fn swap_remove(&mut self, index: usize) -> Value {
265 let len = self.len();
266 assert!(index < len, "index {index} out of bounds(len: {len})");
267 if index != self.len() - 1 {
268 self.swap(index, len - 1);
269 }
270 self.pop().unwrap()
271 }
272
273 /// Retains only the elements specified by the predicate, passing a mutable reference to it.
274 ///
275 /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
276 /// This method operates in place, visiting each element exactly once in the
277 /// original order, and preserves the order of the retained elements.
278 ///
279 /// # Examples
280 ///
281 /// ```
282 /// use sonic_rs::{array, JsonValueTrait};
283 ///
284 /// let mut arr = array![1, 2, 3, 4];
285 /// arr.retain_mut(|x| {
286 /// let v = (x.as_i64().unwrap());
287 /// if v <= 3 {
288 /// *x = (v + 1).into();
289 /// true
290 /// } else {
291 /// false
292 /// }
293 /// });
294 /// assert_eq!(arr, [2, 3, 4]);
295 /// ```
296 #[inline]
297 pub fn retain_mut<F>(&mut self, f: F)
298 where
299 F: FnMut(&mut Value) -> bool,
300 {
301 if let ValueMut::Array(array) = self.0.as_mut() {
302 array.retain_mut(f);
303 } else {
304 panic!("Array::retain_mut: not an array");
305 }
306 }
307
308 /// Shortens the array, keeping the first `len` elements and dropping
309 /// the rest.
310 ///
311 /// If `len` is greater or equal to the array's current length, this has
312 /// no effect.
313 ///
314 /// The [`drain`] method can emulate `truncate`, but causes the excess
315 /// elements to be returned instead of dropped.
316 ///
317 /// Note that this method has no effect on the allocated capacity
318 /// of the array.
319 ///
320 /// # Examples
321 ///
322 /// Truncating a five element array to two elements:
323 ///
324 /// ```
325 /// use sonic_rs::array;
326 /// let mut arr = array![1, 2, 3, true, "hi"];
327 /// arr.truncate(2);
328 /// assert_eq!(arr, [1, 2]);
329 /// ```
330 ///
331 /// No truncation occurs when `len` is greater than the array's current
332 /// length:
333 ///
334 /// ```
335 /// use sonic_rs::array;
336 /// let mut arr = array![1, 2, 3];
337 /// arr.truncate(8);
338 /// assert_eq!(arr, [1, 2, 3]);
339 /// ```
340 ///
341 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
342 /// method.
343 ///
344 /// ```
345 /// use sonic_rs::array;
346 /// let mut arr = array![1, 2, 3];
347 /// arr.truncate(0);
348 /// assert!(arr.is_empty());
349 /// ```
350 ///
351 /// [`clear`]: Array::clear
352 /// [`drain`]: Array::drain
353 #[inline]
354 pub fn truncate(&mut self, len: usize) {
355 if let ValueMut::Array(array) = self.0.as_mut() {
356 array.truncate(len);
357 } else {
358 panic!("Array::truncate: not an array");
359 }
360 }
361
362 /// Appends an element `val` to the back of a collection.
363 /// The `val` will be converted into `Value`.
364 ///
365 /// # Panics
366 ///
367 /// Panics if the new capacity exceeds `isize::MAX` bytes.
368 ///
369 /// # Examples
370 ///
371 /// ```
372 /// use sonic_rs::array;
373 /// let mut arr = array![1, 2];
374 /// arr.push(3);
375 /// arr.push("hi");
376 /// assert_eq!(arr, array![1, 2, 3, "hi"]);
377 /// ```
378 #[inline]
379 pub fn push<T: Into<Value>>(&mut self, val: T) {
380 if let ValueMut::Array(array) = self.0.as_mut() {
381 array.push(val.into());
382 } else {
383 panic!("Array::push: not an array");
384 }
385 }
386
387 /// Removes the last element from a array and returns it, or [`None`] if it is empty.
388 #[inline]
389 pub fn pop(&mut self) -> Option<Value> {
390 debug_assert!(self.0.is_array());
391 self.0.pop()
392 }
393
394 /// Returns the number of elements in the array.
395 #[inline]
396 pub fn len(&self) -> usize {
397 self.0
398 .as_value_slice()
399 .expect("call len in non-array type")
400 .len()
401 }
402
403 /// Returns `true` if the array contains no elements.
404 #[inline]
405 pub fn is_empty(&self) -> bool {
406 self.len() == 0
407 }
408
409 /// Extracts a mutable slice of the entire array. Equivalent to &mut s[..].
410 #[inline]
411 pub fn as_mut_slice(&mut self) -> &mut [Value] {
412 self.deref_mut()
413 }
414
415 /// Extracts a slice containing the entire array. Equivalent to &s[..].
416 #[inline]
417 pub fn as_slice(&self) -> &[Value] {
418 self.deref()
419 }
420
421 /// Returns the total number of elements the array can hold without reallocating.
422 #[inline]
423 pub fn capacity(&self) -> usize {
424 self.0.capacity()
425 }
426
427 /// Clears the array, removing all values.
428 ///
429 /// Note that this method has no effect on the allocated capacity of the array.
430 #[inline]
431 pub fn clear(&mut self) {
432 self.0.clear();
433 }
434
435 /// Removes and returns the element at position `index` within the array,
436 ///
437 /// # Panics
438 ///
439 /// Panics if `index` is out of bounds.
440 ///
441 /// # Examples
442 ///
443 /// ```
444 /// use sonic_rs::array;
445 ///
446 /// let mut arr = array![0, 1, 2];
447 /// arr.remove(1);
448 /// assert_eq!(arr, [0, 2]);
449 /// ```
450 #[inline]
451 pub fn remove(&mut self, index: usize) {
452 self.0.remove_index(index);
453 }
454
455 /// Moves all the elements of other into self, leaving other empty.
456 ///
457 /// # Examples
458 /// ```
459 /// use sonic_rs::{array, Value};
460 ///
461 /// let mut arr1 = array![1];
462 /// arr1.push(Value::from("arr1"));
463 ///
464 /// let mut arr2 = array![2];
465 /// arr2.push(Value::from("arr2"));
466 /// arr2.append(&mut arr1);
467 ///
468 /// assert_eq!(arr2, array![2, "arr2", 1, "arr1"]);
469 /// assert!(arr1.is_empty());
470 /// ```
471 #[inline]
472 pub fn append(&mut self, other: &mut Self) {
473 if let ValueMut::Array(array) = self.0.as_mut() {
474 if let ValueMut::Array(other_array) = other.0.as_mut() {
475 array.append(other_array);
476 } else {
477 panic!("Array::append: other is not an array");
478 }
479 } else {
480 panic!("Array::append: not an array");
481 }
482 }
483
484 /// Removes the specified range from the array in bulk, returning all
485 /// removed elements as an iterator. If the iterator is dropped before
486 /// being fully consumed, it drops the remaining removed elements.
487 ///
488 /// The returned iterator keeps a mutable borrow on the array to optimize
489 /// its implementation.
490 ///
491 /// # Panics
492 ///
493 /// Panics if the starting point is greater than the end point or if
494 /// the end point is greater than the length of the array.
495 ///
496 /// # Leaking
497 ///
498 /// If the returned iterator goes out of scope without being dropped (due to
499 /// [`std::mem::forget`], for example), the array may have lost and leaked
500 /// elements arbitrarily, including elements outside the range.
501 ///
502 /// # Examples
503 ///
504 /// ```
505 /// use sonic_rs::{array, Value};
506 /// let mut v = array![1, 2, 3];
507 /// let u: Vec<Value> = v.drain(1..).collect();
508 /// assert_eq!(v, &[1]);
509 /// assert_eq!(u, &[2, 3]);
510 ///
511 /// // A full range clears the array, like `clear()` does
512 /// v.drain(..);
513 /// assert!(v.is_empty());
514 /// ```
515 #[inline]
516 pub fn drain<R>(&mut self, r: R) -> Drain<'_>
517 where
518 R: RangeBounds<usize>,
519 {
520 if let ValueMut::Array(array) = self.0.as_mut() {
521 array.drain(r)
522 } else {
523 panic!("Array::drain: not an array");
524 }
525 }
526
527 /// Copies elements from `src` range to the end of the array.
528 ///
529 /// # Panics
530 ///
531 /// Panics if the starting point is greater than the end point or if
532 /// the end point is greater than the length of the array.
533 ///
534 /// # Examples
535 ///
536 /// ```
537 /// use sonic_rs::Array;
538 /// let mut arr: Array = sonic_rs::from_str("[0, 1, 2, 3, 4]").unwrap();
539 ///
540 /// arr.extend_from_within(2..);
541 /// assert_eq!(arr, [0, 1, 2, 3, 4, 2, 3, 4]);
542 ///
543 /// arr.extend_from_within(..2);
544 /// assert_eq!(arr, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
545 ///
546 /// arr.extend_from_within(4..8);
547 /// assert_eq!(arr, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
548 /// ```
549 pub fn extend_from_within<R>(&mut self, src: R)
550 where
551 R: RangeBounds<usize>,
552 {
553 if let ValueMut::Array(array) = self.0.as_mut() {
554 array.extend_from_within(src);
555 } else {
556 panic!("Array::extend_from_within: not an array");
557 }
558 }
559
560 /// Inserts an element at position `index` within the array, shifting all
561 /// elements after it to the right.
562 /// The `element` will be converted into `Value`.
563 ///
564 /// # Panics
565 ///
566 /// Panics if `index > len`.
567 ///
568 /// # Examples
569 ///
570 /// ```
571 /// use sonic_rs::{array, json};
572 ///
573 /// let mut arr = array![1, 2, 3];
574 /// arr.insert(1, "inserted1");
575 /// assert_eq!(arr, array![1, "inserted1", 2, 3]);
576 ///
577 /// arr.insert(4, "inserted2");
578 /// assert_eq!(arr, array![1, "inserted1", 2, 3, "inserted2"]);
579 ///
580 /// arr.insert(5, json!({"a": 123})); // insert at the end
581 /// assert_eq!(arr, array![1, "inserted1", 2, 3, "inserted2", {"a": 123}]);
582 /// ```
583 #[inline]
584 pub fn insert<T: Into<Value>>(&mut self, index: usize, element: T) {
585 if let ValueMut::Array(array) = self.0.as_mut() {
586 array.insert(index, element.into());
587 } else {
588 panic!("Array::insert: not an array");
589 }
590 }
591}
592
593impl Default for Array {
594 fn default() -> Self {
595 Self::new()
596 }
597}
598
599impl Deref for Array {
600 type Target = [Value];
601
602 fn deref(&self) -> &Self::Target {
603 self.0.as_value_slice().expect("Array::deref: not an array")
604 }
605}
606
607impl DerefMut for Array {
608 fn deref_mut(&mut self) -> &mut Self::Target {
609 if let ValueMut::Array(array) = self.0.as_mut() {
610 array
611 } else {
612 panic!("Array::deref_mut: not an array");
613 }
614 }
615}
616
617/// A draining iterator for `Array<T>`.
618///
619/// This `struct` is created by [`Array::drain`].
620/// See its documentation for more.
621pub type Drain<'a> = std::vec::Drain<'a, Value>;
622
623use std::{
624 ops::{Index, IndexMut},
625 slice::SliceIndex,
626};
627
628impl<I: SliceIndex<[Value]>> Index<I> for Array {
629 type Output = I::Output;
630
631 #[inline]
632 fn index(&self, index: I) -> &Self::Output {
633 Index::index(&**self, index)
634 }
635}
636
637impl<I: SliceIndex<[Value]>> IndexMut<I> for Array {
638 fn index_mut(&mut self, index: I) -> &mut Self::Output {
639 IndexMut::index_mut(&mut **self, index)
640 }
641}
642
643//////////////////////////////////////////////////////////////////////////////
644
645#[derive(Debug, Default, Clone)]
646pub struct IntoIter {
647 array: Array,
648 index: usize,
649 len: usize,
650}
651
652impl IntoIter {
653 pub fn as_mut_slice(&mut self) -> &mut [Value] {
654 if let ValueMut::Array(array) = self.array.0.as_mut() {
655 array.as_mut_slice()
656 } else {
657 panic!("Array::as_mut_slice: not an array");
658 }
659 }
660
661 pub fn as_slice(&self) -> &[Value] {
662 if let ValueRefInner::Array(array) = self.array.0.as_ref2() {
663 array
664 } else {
665 panic!("Array::as_slice: not an array");
666 }
667 }
668}
669
670impl AsRef<[Value]> for IntoIter {
671 fn as_ref(&self) -> &[Value] {
672 self.as_slice()
673 }
674}
675
676impl AsMut<[Value]> for IntoIter {
677 fn as_mut(&mut self) -> &mut [Value] {
678 self.as_mut_slice()
679 }
680}
681
682impl DoubleEndedIterator for IntoIter {
683 #[inline]
684 fn next_back(&mut self) -> Option<Self::Item> {
685 if self.index < self.len {
686 self.len -= 1;
687 let value = self.array.0.get_index_mut(self.len).unwrap();
688 Some(value.take())
689 } else {
690 None
691 }
692 }
693}
694
695impl ExactSizeIterator for IntoIter {
696 #[inline]
697 fn len(&self) -> usize {
698 self.len - self.index
699 }
700}
701
702impl FusedIterator for IntoIter {}
703
704impl Iterator for IntoIter {
705 type Item = Value;
706
707 #[inline]
708 fn next(&mut self) -> Option<Self::Item> {
709 if self.index < self.len {
710 let value = self.array.0.get_index_mut(self.index).unwrap();
711 self.index += 1;
712 Some(value.take())
713 } else {
714 None
715 }
716 }
717
718 #[inline]
719 fn size_hint(&self) -> (usize, Option<usize>) {
720 let len = self.len - self.index;
721 (len, Some(len))
722 }
723}
724
725impl IntoIterator for Array {
726 type Item = Value;
727 type IntoIter = IntoIter;
728
729 #[inline]
730 fn into_iter(self) -> Self::IntoIter {
731 let len = self.len();
732 IntoIter {
733 array: self,
734 index: 0,
735 len,
736 }
737 }
738}
739
740impl<'a> IntoIterator for &'a Array {
741 type Item = &'a Value;
742 type IntoIter = std::slice::Iter<'a, Value>;
743
744 #[inline]
745 fn into_iter(self) -> Self::IntoIter {
746 self.iter()
747 }
748}
749
750impl<'a> IntoIterator for &'a mut Array {
751 type Item = &'a mut Value;
752 type IntoIter = std::slice::IterMut<'a, Value>;
753
754 #[inline]
755 fn into_iter(self) -> Self::IntoIter {
756 self.iter_mut()
757 }
758}
759
760//////////////////////////////////////////////////////////////////////////////
761
762impl serde::ser::Serialize for Array {
763 #[inline]
764 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
765 where
766 S: serde::ser::Serializer,
767 {
768 use serde::ser::SerializeSeq;
769 let mut seq = tri!(serializer.serialize_seq(Some(self.len())));
770 for v in self {
771 tri!(seq.serialize_element(v));
772 }
773 seq.end()
774 }
775}
776
777impl<'de> serde::de::Deserialize<'de> for Array {
778 #[inline]
779 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
780 where
781 D: serde::de::Deserializer<'de>,
782 {
783 // deserialize to value at first
784 let value: Value =
785 deserializer.deserialize_newtype_struct(super::de::TOKEN, super::de::ValueVisitor)?;
786 if value.is_array() {
787 Ok(Array(value))
788 } else {
789 Err(serde::de::Error::invalid_type(
790 serde::de::Unexpected::Other("not a array"),
791 &"array",
792 ))
793 }
794 }
795}
796
797#[cfg(test)]
798mod test {
799 use super::Array;
800 use crate::value::{node::Value, value_trait::JsonValueMutTrait};
801
802 #[test]
803 fn test_value_array() {
804 let mut val = crate::from_str::<Value>(r#"[1,2,3]"#).unwrap();
805 let array = val.as_array_mut().unwrap();
806 assert_eq!(array.len(), 3);
807
808 for i in 0..3 {
809 // push static node
810 let old_len = array.len();
811 let new_node = Value::new_u64(i);
812 array.push(new_node);
813 assert_eq!(array.len(), old_len + 1);
814
815 // push node with new allocator
816 let old_len = array.len();
817 let mut new_node = Array::default();
818 new_node.push(Value::new_u64(i));
819 array.push(new_node.0);
820 assert_eq!(array.len(), old_len + 1);
821
822 // push node with self allocator
823 let old_len = array.len();
824 let mut new_node = Array::new();
825 new_node.push(Value::new_u64(i));
826 array.push(new_node.0);
827 assert_eq!(array.len(), old_len + 1);
828 }
829
830 for (i, v) in array.iter_mut().enumerate() {
831 *v = Value::new_u64(i as u64);
832 }
833
834 while !array.is_empty() {
835 dbg!(array.pop());
836 }
837 }
838}