Skip to main content

miniserde_miku/json/
array.rs

1use crate::json::{drop, Value};
2use alloc::vec::Vec;
3use core::iter::FromIterator;
4use core::mem::ManuallyDrop;
5use core::ops::{Deref, DerefMut};
6use core::ptr;
7
8/// A `Vec<Value>` with a non-recursive drop impl.
9#[derive(Clone, Debug, Default)]
10pub struct Array {
11    inner: Vec<Value>,
12}
13
14impl Drop for Array {
15    fn drop(&mut self) {
16        self.inner.drain(..).for_each(drop::safely);
17    }
18}
19
20fn take(array: Array) -> Vec<Value> {
21    let array = ManuallyDrop::new(array);
22    unsafe { ptr::read(&array.inner) }
23}
24
25impl Array {
26    pub fn new() -> Self {
27        Array { inner: Vec::new() }
28    }
29}
30
31impl Deref for Array {
32    type Target = Vec<Value>;
33
34    fn deref(&self) -> &Self::Target {
35        &self.inner
36    }
37}
38
39impl DerefMut for Array {
40    fn deref_mut(&mut self) -> &mut Self::Target {
41        &mut self.inner
42    }
43}
44
45impl IntoIterator for Array {
46    type Item = Value;
47    type IntoIter = <Vec<Value> as IntoIterator>::IntoIter;
48
49    fn into_iter(self) -> Self::IntoIter {
50        take(self).into_iter()
51    }
52}
53
54impl<'a> IntoIterator for &'a Array {
55    type Item = &'a Value;
56    type IntoIter = <&'a Vec<Value> as IntoIterator>::IntoIter;
57
58    fn into_iter(self) -> Self::IntoIter {
59        self.iter()
60    }
61}
62
63impl<'a> IntoIterator for &'a mut Array {
64    type Item = &'a mut Value;
65    type IntoIter = <&'a mut Vec<Value> as IntoIterator>::IntoIter;
66
67    fn into_iter(self) -> Self::IntoIter {
68        self.iter_mut()
69    }
70}
71
72impl FromIterator<Value> for Array {
73    fn from_iter<I>(iter: I) -> Self
74    where
75        I: IntoIterator<Item = Value>,
76    {
77        Array {
78            inner: Vec::from_iter(iter),
79        }
80    }
81}