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