1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 use crate::JsonValue;
15 use core::fmt::{Debug, Display, Formatter};
16 use core::slice::{Iter, IterMut};
17 
18 /// Array type, implemented using Vec.
19 ///
20 /// # Situation
21 /// * When the average number of Array entries exceeds 15 (estimated value), and query operation exists.
22 ///
23 /// # Attention
24 /// * 只有开启 `vec_array` feature 时才可以使用,且与其他的 array 相关 feature 冲突。(默认开启)
25 /// Only open `vec_array` feature can be used, and conflicts with other array-related features. (Enabled by default)
26 ///
27 /// # Examples
28 /// ```
29 /// use ylong_json::Array;
30 ///
31 /// let array = Array::new();
32 /// assert_eq!(array.is_empty(), true);
33 /// ```
34 #[derive(Default, Clone)]
35 pub struct Array {
36     inner: Vec<JsonValue>,
37 }
38 
39 impl Array {
40     /// Creates an empty Array instance.
41     ///
42     /// # Examples
43     /// ```
44     /// use ylong_json::Array;
45     ///
46     /// let array = Array::new();
47     /// ```
new() -> Self48     pub fn new() -> Self {
49         Self { inner: Vec::new() }
50     }
51 
52     /// Gets length of Array.
53     ///
54     /// # Examples
55     /// ```
56     /// use ylong_json::{Array, JsonValue};
57     ///
58     /// let mut array = Array::new();
59     /// assert_eq!(array.len(), 0);
60     ///
61     /// array.push(JsonValue::Null);
62     /// assert_eq!(array.len(), 1);
63     /// ```
len(&self) -> usize64     pub fn len(&self) -> usize {
65         self.inner.len()
66     }
67 
68     /// Determines whether Array is empty.
69     ///
70     /// # Examples
71     /// ```
72     /// use ylong_json::{Array, JsonValue};
73     ///
74     /// let mut array = Array::new();
75     /// assert_eq!(array.is_empty(), true);
76     ///
77     /// array.push(JsonValue::Null);
78     /// assert_eq!(array.is_empty(), false);
79     /// ```
is_empty(&self) -> bool80     pub fn is_empty(&self) -> bool {
81         self.inner.len() == 0
82     }
83 
84     /// Insert a new JsonValue at the end of Array.
85     ///
86     /// # Examples
87     /// ```
88     /// use ylong_json::{Array, JsonValue};
89     ///
90     /// let mut array = Array::new();
91     /// assert_eq!(array.len(), 0);
92     ///
93     /// array.push(JsonValue::Null);
94     /// assert_eq!(array.len(), 1);
95     /// ```
push(&mut self, value: JsonValue)96     pub fn push(&mut self, value: JsonValue) {
97         self.inner.push(value)
98     }
99 
100     /// Pops the element at the end of Array.
101     ///
102     /// # Examples
103     /// ```
104     /// use ylong_json::{Array, JsonValue};
105     ///
106     /// let mut array = Array::new();
107     /// assert_eq!(array.pop(), None);
108     ///
109     /// array.push(JsonValue::Null);
110     /// assert_eq!(array.pop(), Some(JsonValue::Null));
111     /// ```
pop(&mut self) -> Option<JsonValue>112     pub fn pop(&mut self) -> Option<JsonValue> {
113         self.inner.pop()
114     }
115 
116     /// Gets a common iterator of Array.
117     ///
118     /// # Examples
119     /// ```
120     /// use ylong_json::Array;
121     ///
122     /// let array = Array::new();
123     /// let iter = array.iter();
124     /// ```
iter(&self) -> Iter<'_, JsonValue>125     pub fn iter(&self) -> Iter<'_, JsonValue> {
126         self.inner.iter()
127     }
128 
129     /// Gets a mutable iterator of Array.
130     ///
131     /// # Examples
132     /// ```
133     /// use ylong_json::Array;
134     ///
135     /// let mut array = Array::new();
136     /// let iter_mut = array.iter_mut();
137     /// ```
iter_mut(&mut self) -> IterMut<'_, JsonValue>138     pub fn iter_mut(&mut self) -> IterMut<'_, JsonValue> {
139         self.inner.iter_mut()
140     }
141 
142     /// Returns a common reference to the specified index ** member ** in Array.
143     ///
144     /// # Examples
145     /// ```
146     /// use ylong_json::{Array, JsonValue};
147     ///
148     /// let mut array = Array::new();
149     /// array.push(JsonValue::Null);
150     /// assert_eq!(array.get(0), Some(&JsonValue::Null));
151     /// assert_eq!(array.get(1), None);
152     /// ```
get(&self, index: usize) -> Option<&JsonValue>153     pub fn get(&self, index: usize) -> Option<&JsonValue> {
154         self.inner.get(index)
155     }
156 
157     /// Returns a mutable reference to the specified index ** member ** in Array.
158     ///
159     /// # Examples
160     /// ```
161     /// use ylong_json::{Array, JsonValue};
162     ///
163     /// let mut array = Array::new();
164     /// array.push(JsonValue::Null);
165     /// assert_eq!(array.get_mut(0), Some(&mut JsonValue::Null));
166     /// assert_eq!(array.get_mut(1), None);
167     /// ```
get_mut(&mut self, index: usize) -> Option<&mut JsonValue>168     pub fn get_mut(&mut self, index: usize) -> Option<&mut JsonValue> {
169         self.inner.get_mut(index)
170     }
171 
172     /// Returns a common reference to the trailing ** member ** in Array.。
173     ///
174     /// # Examples
175     /// ```
176     /// use ylong_json::{Array, JsonValue};
177     ///
178     /// let mut array = Array::new();
179     /// assert_eq!(array.last(), None);
180     /// array.push(JsonValue::Null);
181     /// assert_eq!(array.last(), Some(&JsonValue::Null));
182     /// ```
last(&self) -> Option<&JsonValue>183     pub fn last(&self) -> Option<&JsonValue> {
184         self.inner.last()
185     }
186 
187     /// Returns a mutable reference to the trailing ** member ** in Array.
188     ///
189     /// # Examples
190     /// ```
191     /// use ylong_json::{Array, JsonValue};
192     ///
193     /// let mut array = Array::new();
194     /// assert_eq!(array.last_mut(), None);
195     /// array.push(JsonValue::Null);
196     /// assert_eq!(array.last_mut(), Some(&mut JsonValue::Null));
197     /// ```
last_mut(&mut self) -> Option<&mut JsonValue>198     pub fn last_mut(&mut self) -> Option<&mut JsonValue> {
199         self.inner.last_mut()
200     }
201 
202     /// Removes the node in Array with the specified index.
203     ///
204     /// # Examples
205     /// ```
206     /// use ylong_json::{Array, JsonValue};
207     ///
208     /// let mut array = Array::new();
209     /// array.push(JsonValue::Null);
210     /// array.push(JsonValue::Boolean(true));
211     /// array.push(JsonValue::Null);
212     ///
213     /// assert_eq!(array.len(), 3);
214     /// let second = array.remove(1);
215     /// assert_eq!(second, Some(JsonValue::Boolean(true)));
216     /// assert_eq!(array.len(), 2);
217     /// ```
remove(&mut self, index: usize) -> Option<JsonValue>218     pub fn remove(&mut self, index: usize) -> Option<JsonValue> {
219         if index >= self.inner.len() {
220             return None;
221         }
222         Some(self.inner.remove(index))
223     }
224 }
225 
226 impl PartialEq for Array {
227     /// Determines whether two arrays are equal.
228     ///
229     /// Two Arrays are equal: They have the same length and the elements in each position are equal.
230     ///
231     /// # Examples
232     /// ```
233     /// use ylong_json::{Array, JsonValue};
234     ///
235     /// let array1 = Array::new();
236     /// let array2 = Array::new();
237     /// let mut array3 = Array::new();
238     /// array3.push(JsonValue::Null);
239     ///
240     /// assert_eq!(array1, array2);
241     /// assert_ne!(array1, array3);
242     /// ```
eq(&self, other: &Self) -> bool243     fn eq(&self, other: &Self) -> bool {
244         if self.len() != other.len() {
245             return false;
246         }
247         for (a, b) in self.iter().zip(other.iter()) {
248             if a != b {
249                 return false;
250             }
251         }
252         true
253     }
254 }
255 
256 impl Display for Array {
fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result257     fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
258         write!(f, "[")?;
259         for (n, item) in self.inner.iter().enumerate() {
260             if n != 0 {
261                 write!(f, ",")?;
262             }
263             write!(f, "{item}")?;
264         }
265         write!(f, "]")
266     }
267 }
268 
269 impl Debug for Array {
fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result270     fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
271         Display::fmt(self, f)
272     }
273 }
274 
275 #[cfg(test)]
276 mod ut_vec {
277     use crate::{Array, JsonValue};
278 
279     /// UT test for `Array::is_empty`.
280     ///
281     /// # Title
282     /// ut_array_is_empty
283     ///
284     /// # Brief
285     /// 1. Creates some `Array`s.
286     /// 2. Calls `Array::is_empty`.
287     /// 3. Checks if the test results are correct.
288     #[test]
ut_array_is_empty()289     fn ut_array_is_empty() {
290         assert!(Array::new().is_empty());
291         assert!(!array!(1).is_empty());
292     }
293 
294     /// UT test for `Array::pop`.
295     ///
296     /// # Title
297     /// ut_array_pop
298     ///
299     /// # Brief
300     /// 1. Creates some `Array`s.
301     /// 2. Calls `Array::pop`.
302     /// 3. Checks if the test results are correct.
303     #[test]
ut_array_pop()304     fn ut_array_pop() {
305         let mut array = array!(1);
306         assert_eq!(array.pop(), Some(JsonValue::new_number(1.into())));
307         assert_eq!(array.pop(), None);
308     }
309 
310     /// UT test for `Array::iter_mut`.
311     ///
312     /// # Title
313     /// ut_array_iter_mut
314     ///
315     /// # Brief
316     /// 1. Creates some `Array`s.
317     /// 2. Calls `Array::iter_mut`.
318     /// 3. Checks if the test results are correct.
319     #[test]
ut_array_iter_mut()320     fn ut_array_iter_mut() {
321         let mut array = array!(1);
322         let mut iter = array.iter_mut();
323         assert_eq!(iter.next(), Some(&mut JsonValue::new_number(1.into())));
324         assert_eq!(iter.next(), None);
325     }
326 
327     /// UT test for `Array::last`.
328     ///
329     /// # Title
330     /// ut_array_last
331     ///
332     /// # Brief
333     /// 1. Creates some `Array`s.
334     /// 2. Calls `Array::last`.
335     /// 3. Checks if the test results are correct.
336     #[test]
ut_array_last()337     fn ut_array_last() {
338         let array = array!(1);
339         assert_eq!(array.last(), Some(&JsonValue::new_number(1.into())));
340 
341         let array = Array::new();
342         assert_eq!(array.last(), None);
343     }
344 
345     /// UT test for `Array::remove`.
346     ///
347     /// # Title
348     /// ut_array_remove
349     ///
350     /// # Brief
351     /// 1. Creates some `Array`s.
352     /// 2. Calls `Array::remove`.
353     /// 3. Checks if the test results are correct.
354     #[test]
ut_array_remove()355     fn ut_array_remove() {
356         let mut array = array!(1);
357         assert_eq!(array.remove(3), None);
358         assert_eq!(array.remove(0), Some(JsonValue::new_number(1.into())));
359     }
360 
361     /// UT test for `Array::eq`.
362     ///
363     /// # Title
364     /// ut_array_eq
365     ///
366     /// # Brief
367     /// 1. Creates some `Array`s.
368     /// 2. Calls `Array::eq`.
369     /// 3. Checks if the test results are correct.
370     #[test]
ut_array_eq()371     fn ut_array_eq() {
372         let array1 = array!(1);
373         let array2 = array!(1, 2);
374         let array3 = array!(1, 3);
375 
376         assert_eq!(array1, array1);
377         assert_ne!(array1, array2);
378         assert_ne!(array2, array3);
379     }
380 
381     /// UT test for `Array::fmt`.
382     ///
383     /// # Title
384     /// ut_array_fmt
385     ///
386     /// # Brief
387     /// 1. Creates some `Array`s.
388     /// 2. Calls `Array::fmt`.
389     /// 3. Checks if the test results are correct.
390     #[test]
ut_array_fmt()391     fn ut_array_fmt() {
392         let array = array!(1, 2);
393         assert_eq!(format!("{array}"), "[1,2]");
394         assert_eq!(format!("{array:?}"), "[1,2]");
395     }
396 }
397