Skip to main content

deser_value/
seq.rs

1use std::fmt;
2use std::hash::{Hash, Hasher};
3use std::ops::{Deref, DerefMut};
4
5use deser_core::Order;
6
7use crate::tree;
8use crate::value::{Kind, Value};
9
10/// A sequence of values.
11///
12/// A sequence dereferences to a [`Vec`] of its values.  Additionally it
13/// holds the [`Order`] of the values, which is passed on when the sequence
14/// is serialized, if it holds the values of a repeated key of a multimap
15/// (see [`Map::is_multimap`](crate::Map::is_multimap)) and if an empty
16/// sequence could also be an empty map (see
17/// [`is_ambiguous_empty`](Self::is_ambiguous_empty)).  They are not
18/// considered when sequences are compared.
19///
20/// ```
21/// use deser::Order;
22/// use deser_value::{Seq, Value};
23///
24/// let mut seq = Seq::new();
25/// seq.set_order(Order::Sorted);
26/// seq.push(Value::from(1));
27/// seq.push(Value::from(2));
28/// assert_eq!(seq.len(), 2);
29/// assert_eq!(seq.order(), Order::Sorted);
30/// ```
31#[derive(Default)]
32pub struct Seq {
33    pub(crate) items: Vec<Value>,
34    pub(crate) order: Order,
35    pub(crate) repeated: bool,
36    pub(crate) ambiguous_empty: bool,
37}
38
39impl Seq {
40    /// Creates an empty sequence.
41    pub const fn new() -> Seq {
42        Seq {
43            items: Vec::new(),
44            order: Order::Natural,
45            repeated: false,
46            ambiguous_empty: false,
47        }
48    }
49
50    /// Creates an empty sequence with a capacity.
51    pub fn with_capacity(capacity: usize) -> Seq {
52        Seq {
53            items: Vec::with_capacity(capacity),
54            order: Order::Natural,
55            repeated: false,
56            ambiguous_empty: false,
57        }
58    }
59
60    /// Returns the order of the values.
61    pub fn order(&self) -> Order {
62        self.order
63    }
64
65    /// Sets the order of the values.
66    pub fn set_order(&mut self, order: Order) {
67        self.order = order;
68    }
69
70    /// Returns `true` if the sequence holds the values of a repeated key.
71    ///
72    /// Within a multimap (see [`Map::is_multimap`](crate::Map::is_multimap))
73    /// the values are passed on as the values of a key that is given more
74    /// than once.  Elsewhere this has no effect.
75    pub fn is_repeated(&self) -> bool {
76        self.repeated
77    }
78
79    /// Sets if the sequence holds the values of a repeated key.
80    pub fn set_repeated(&mut self, yes: bool) {
81        self.repeated = yes;
82    }
83
84    /// Returns `true` if the sequence is empty and could also be an empty
85    /// map.
86    ///
87    /// Sequences that are deserialized from empty containers that formats
88    /// cannot tell apart from empty maps (like the empty arrays of PHP, see
89    /// [`ContainerShape::set_ambiguous_empty`](deser_core::ContainerShape::set_ambiguous_empty))
90    /// are marked like this.  When the sequence is deserialized into
91    /// another type, types that expect a map receive an empty map, and an
92    /// update of a map with it leaves the map as it is.  The flag has no
93    /// effect once the sequence has values.
94    ///
95    /// ```
96    /// use std::collections::BTreeMap;
97    /// use deser_value::{Seq, Value};
98    ///
99    /// let mut seq = Seq::new();
100    /// seq.set_ambiguous_empty(true);
101    /// let map: BTreeMap<String, u32> = deser_value::from_value(&Value::from(seq)).unwrap();
102    /// assert!(map.is_empty());
103    /// ```
104    pub fn is_ambiguous_empty(&self) -> bool {
105        self.ambiguous_empty && self.items.is_empty()
106    }
107
108    /// Sets if the sequence could also be an empty map when it's empty.
109    pub fn set_ambiguous_empty(&mut self, yes: bool) {
110        self.ambiguous_empty = yes;
111    }
112
113    /// Creates an empty sequence with the order and the flags of this one.
114    pub(crate) fn empty_like(&self, capacity: usize) -> Seq {
115        let mut seq = Seq::with_capacity(capacity);
116        seq.set_order(self.order);
117        seq.set_repeated(self.repeated);
118        seq.set_ambiguous_empty(self.ambiguous_empty);
119        seq
120    }
121
122    /// Converts the sequence into a vector.
123    pub fn into_vec(mut self) -> Vec<Value> {
124        std::mem::take(&mut self.items)
125    }
126}
127
128impl Deref for Seq {
129    type Target = Vec<Value>;
130
131    fn deref(&self) -> &Vec<Value> {
132        &self.items
133    }
134}
135
136impl DerefMut for Seq {
137    fn deref_mut(&mut self) -> &mut Vec<Value> {
138        &mut self.items
139    }
140}
141
142impl Drop for Seq {
143    fn drop(&mut self) {
144        if self.items.iter().any(|item| item.has_children()) {
145            tree::drop_values(std::mem::take(&mut self.items));
146        }
147    }
148}
149
150impl Clone for Seq {
151    fn clone(&self) -> Seq {
152        match tree::clone_seq(self) {
153            Kind::Seq(seq) => seq,
154            _ => unreachable!(),
155        }
156    }
157}
158
159impl PartialEq for Seq {
160    fn eq(&self, other: &Seq) -> bool {
161        tree::eq_seq(self, other)
162    }
163}
164
165impl Eq for Seq {}
166
167impl Hash for Seq {
168    fn hash<H: Hasher>(&self, state: &mut H) {
169        tree::hash_seq(self, state);
170    }
171}
172
173impl fmt::Debug for Seq {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        tree::fmt_seq(self, f)
176    }
177}
178
179impl From<Vec<Value>> for Seq {
180    fn from(items: Vec<Value>) -> Seq {
181        Seq {
182            items,
183            order: Order::Natural,
184            repeated: false,
185            ambiguous_empty: false,
186        }
187    }
188}
189
190impl From<Seq> for Vec<Value> {
191    fn from(seq: Seq) -> Vec<Value> {
192        seq.into_vec()
193    }
194}
195
196impl<T: Into<Value>> FromIterator<T> for Seq {
197    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Seq {
198        Seq::from(iter.into_iter().map(Into::into).collect::<Vec<_>>())
199    }
200}
201
202impl<T: Into<Value>> Extend<T> for Seq {
203    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
204        self.items.extend(iter.into_iter().map(Into::into));
205    }
206}
207
208impl IntoIterator for Seq {
209    type Item = Value;
210    type IntoIter = std::vec::IntoIter<Value>;
211
212    fn into_iter(self) -> Self::IntoIter {
213        self.into_vec().into_iter()
214    }
215}
216
217impl<'a> IntoIterator for &'a Seq {
218    type Item = &'a Value;
219    type IntoIter = std::slice::Iter<'a, Value>;
220
221    fn into_iter(self) -> Self::IntoIter {
222        self.items.iter()
223    }
224}
225
226impl<'a> IntoIterator for &'a mut Seq {
227    type Item = &'a mut Value;
228    type IntoIter = std::slice::IterMut<'a, Value>;
229
230    fn into_iter(self) -> Self::IntoIter {
231        self.items.iter_mut()
232    }
233}