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::{Cursor, CursorMut, Iter, IterMut, JsonValue, LinkedList, Node};
15 use core::fmt::{Debug, Display, Formatter};
16 
17 /// Array type, implemented using LinkedList.
18 ///
19 /// # Situation
20 /// * When the average number of Array entries does not exceed 15 (estimated value).
21 ///
22 /// * When the average number of Array entries exceeds 15 (estimated value), but do not or rarely made query operation.
23 ///
24 /// # Attention
25 /// * Only open `list_array` feature can be used, and conflicts with other array-related features.
26 ///
27 /// # Examples
28 /// ```
29 /// use ylong_json::Array;
30 ///
31 /// let array = Array::new();
32 /// ```
33 #[derive(Default, Clone, PartialEq)]
34 pub struct Array {
35     inner: LinkedList<JsonValue>,
36 }
37 
38 impl Array {
39     /// Creates an empty Array instance.
40     ///
41     /// # Examples
42     /// ```
43     /// use ylong_json::Array;
44     ///
45     /// let array = Array::new();
46     /// ```
new() -> Self47     pub fn new() -> Self {
48         Self {
49             inner: LinkedList::new(),
50         }
51     }
52 
53     /// Gets length of Array.
54     ///
55     /// # Examples
56     /// ```
57     /// use ylong_json::{Array, JsonValue};
58     ///
59     /// let mut array = Array::new();
60     /// assert_eq!(array.len(), 0);
61     ///
62     /// array.push(JsonValue::Null);
63     /// assert_eq!(array.len(), 1);
64     /// ```
len(&self) -> usize65     pub fn len(&self) -> usize {
66         self.inner.len()
67     }
68 
69     /// Determines whether Array is empty.
70     ///
71     /// # Examples
72     /// ```
73     /// use ylong_json::{Array, JsonValue};
74     ///
75     /// let mut array = Array::new();
76     /// assert_eq!(array.is_empty(), true);
77     ///
78     /// array.push(JsonValue::Null);
79     /// assert_eq!(array.is_empty(), false);
80     /// ```
is_empty(&self) -> bool81     pub fn is_empty(&self) -> bool {
82         self.inner.is_empty()
83     }
84 
85     /// Insert a new JsonValue at the end of Array.
86     ///
87     /// # Examples
88     /// ```
89     /// use ylong_json::{Array, JsonValue};
90     ///
91     /// let mut array = Array::new();
92     /// assert_eq!(array.len(), 0);
93     ///
94     /// array.push(JsonValue::Null);
95     /// assert_eq!(array.len(), 1);
96     /// ```
push(&mut self, value: JsonValue)97     pub fn push(&mut self, value: JsonValue) {
98         self.inner.push_back(value);
99     }
100 
101     /// Pops the element at the end of Array.
102     ///
103     /// # Examples
104     /// ```
105     /// use ylong_json::{Array, JsonValue};
106     ///
107     /// let mut array = Array::new();
108     /// assert_eq!(array.pop(), None);
109     ///
110     /// array.push(JsonValue::Null);
111     /// assert_eq!(array.pop(), Some(JsonValue::Null));
112     /// ```
pop(&mut self) -> Option<JsonValue>113     pub fn pop(&mut self) -> Option<JsonValue> {
114         self.inner.pop_back()
115     }
116 
117     /// Gets a common iterator of Array.
118     ///
119     /// # Examples
120     /// ```
121     /// use ylong_json::Array;
122     ///
123     /// let array = Array::new();
124     /// let iter = array.iter();
125     /// ```
iter(&self) -> Iter<'_, JsonValue>126     pub fn iter(&self) -> Iter<'_, JsonValue> {
127         self.inner.iter()
128     }
129 
130     /// Gets a mutable iterator of Array.
131     ///
132     /// # Examples
133     /// ```
134     /// use ylong_json::Array;
135     ///
136     /// let mut array = Array::new();
137     /// let iter_mut = array.iter_mut();
138     /// ```
iter_mut(&mut self) -> IterMut<'_, JsonValue>139     pub fn iter_mut(&mut self) -> IterMut<'_, JsonValue> {
140         self.inner.iter_mut()
141     }
142 
143     /// Returns a common reference to the specified index ** member ** in Array.
144     ///
145     /// # Examples
146     /// ```
147     /// use ylong_json::{Array, JsonValue};
148     ///
149     /// let mut array = Array::new();
150     /// array.push(JsonValue::Null);
151     /// assert_eq!(array.get(0), Some(&JsonValue::Null));
152     /// assert_eq!(array.get(1), None);
153     /// ```
get(&self, index: usize) -> Option<&JsonValue>154     pub fn get(&self, index: usize) -> Option<&JsonValue> {
155         self.get_cursor(index)?.current()
156     }
157 
158     /// Returns a mutable reference to the specified index ** member ** in Array.
159     ///
160     /// # Examples
161     /// ```
162     /// use ylong_json::{Array, JsonValue};
163     ///
164     /// let mut array = Array::new();
165     /// array.push(JsonValue::Null);
166     /// assert_eq!(array.get_mut(0), Some(&mut JsonValue::Null));
167     /// assert_eq!(array.get_mut(1), None);
168     /// ```
get_mut(&mut self, index: usize) -> Option<&mut JsonValue>169     pub fn get_mut(&mut self, index: usize) -> Option<&mut JsonValue> {
170         // Using 'get_cursor_mut' causes a problem referencing temporary variables.
171         self.get_node_mut(index).map(|n| n.get_element_mut())
172     }
173 
174     /// Returns a common reference to the trailing ** member ** in Array.
175     ///
176     /// # Examples
177     /// ```
178     /// use ylong_json::{Array, JsonValue};
179     ///
180     /// let mut array = Array::new();
181     /// assert_eq!(array.last(), None);
182     /// array.push(JsonValue::Null);
183     /// assert_eq!(array.last(), Some(&JsonValue::Null));
184     /// ```
last(&self) -> Option<&JsonValue>185     pub fn last(&self) -> Option<&JsonValue> {
186         self.inner.back()
187     }
188 
189     /// Returns a mutable reference to the trailing ** member ** in Array.
190     ///
191     /// # Examples
192     /// ```
193     /// use ylong_json::{Array, JsonValue};
194     ///
195     /// let mut array = Array::new();
196     /// assert_eq!(array.last_mut(), None);
197     /// array.push(JsonValue::Null);
198     /// assert_eq!(array.last_mut(), Some(&mut JsonValue::Null));
199     /// ```
last_mut(&mut self) -> Option<&mut JsonValue>200     pub fn last_mut(&mut self) -> Option<&mut JsonValue> {
201         self.inner.back_mut()
202     }
203 
204     /// Removes the node in Array with the specified index.
205     ///
206     /// # Examples
207     /// ```
208     /// use ylong_json::{Array, JsonValue};
209     ///
210     /// let mut array = Array::new();
211     /// array.push(JsonValue::Null);
212     /// array.push(JsonValue::Boolean(true));
213     /// array.push(JsonValue::Null);
214     ///
215     /// assert_eq!(array.len(), 3);
216     /// let second = array.remove(1);
217     /// assert_eq!(second, Some(JsonValue::Boolean(true)));
218     /// assert_eq!(array.len(), 2);
219     /// ```
remove(&mut self, index: usize) -> Option<JsonValue>220     pub fn remove(&mut self, index: usize) -> Option<JsonValue> {
221         self.get_cursor_mut(index)?.remove_current()
222     }
223 
224     /// Returns a common reference to the specified index ** node ** in Array.
225     ///
226     /// After getting a common reference to a node, the corresponding node cannot be released.
227     /// Otherwise undefined behavior will occur.
228     ///
229     /// # Examples
230     /// ```
231     /// use ylong_json::{Array, JsonValue};
232     ///
233     /// let mut array = Array::new();
234     /// array.push(JsonValue::Null);
235     /// assert_eq!(array.get_node(0).is_some(), true);
236     /// assert_eq!(array.get_node(1).is_none(), true);
237     /// ```
get_node(&self, index: usize) -> Option<&Node<JsonValue>>238     pub fn get_node(&self, index: usize) -> Option<&Node<JsonValue>> {
239         self.get_cursor(index)?.current_node()
240     }
241 
242     /// Returns a mutable reference to the specified index ** node ** in Array.
243     ///
244     /// After getting a mutable reference to a node, the corresponding node cannot be released.
245     /// Otherwise undefined behavior will occur.
246     ///
247     /// # Examples
248     /// ```
249     /// use ylong_json::{Array, JsonValue};
250     ///
251     /// let mut array = Array::new();
252     /// let value = JsonValue::Null;
253     /// array.push(value);
254     /// assert_eq!(array.get_node_mut(0).is_some(), true);
255     /// assert_eq!(array.get_node_mut(1).is_none(), true);
256     /// ```
get_node_mut(&mut self, index: usize) -> Option<&mut Node<JsonValue>>257     pub fn get_node_mut(&mut self, index: usize) -> Option<&mut Node<JsonValue>> {
258         self.get_cursor_mut(index)?.current_node()
259     }
260 
261     /// Returns a common reference to the trailing ** node ** in Array.
262     ///
263     /// # Examples
264     /// ```
265     /// use ylong_json::{Array, JsonValue};
266     ///
267     /// let mut array = Array::new();
268     /// assert_eq!(array.last_node().is_none(), true);
269     /// array.push(JsonValue::Null);
270     /// assert_eq!(array.last_node().is_some(), true);
271     /// ```
last_node(&self) -> Option<&Node<JsonValue>>272     pub fn last_node(&self) -> Option<&Node<JsonValue>> {
273         self.inner.back_node()
274     }
275 
276     /// Returns a mutable reference to the trailing ** node ** in Array.
277     ///
278     /// # Examples
279     /// ```
280     /// use ylong_json::{Array, JsonValue};
281     ///
282     /// let mut array = Array::new();
283     /// assert_eq!(array.last_node_mut().is_none(), true);
284     /// array.push(JsonValue::Null);
285     /// assert_eq!(array.last_node_mut().is_some(), true);
286     /// ```
last_node_mut(&mut self) -> Option<&mut Node<JsonValue>>287     pub fn last_node_mut(&mut self) -> Option<&mut Node<JsonValue>> {
288         self.inner.back_node_mut()
289     }
290 
291     /// Gets the common cursor of the specified index node.
get_cursor(&self, index: usize) -> Option<Cursor<'_, JsonValue>>292     fn get_cursor(&self, index: usize) -> Option<Cursor<'_, JsonValue>> {
293         let len = self.len();
294         // If index is greater than the array length, returns.
295         // If index is less than half the array length, searches from front to back;
296         // If index is greater than half the array length, searches from the back to the front.
297         return if index >= len {
298             None
299         } else if index >= (len - 1) / 2 {
300             let mut steps = len - 1 - index;
301             let mut cursor = self.inner.cursor_back();
302             while steps != 0 {
303                 let _ = cursor.index()?;
304                 cursor.move_prev();
305                 steps -= 1;
306             }
307             Some(cursor)
308         } else {
309             let mut steps = index;
310             let mut cursor = self.inner.cursor_front();
311             while steps != 0 {
312                 let _ = cursor.index()?;
313                 cursor.move_next();
314                 steps -= 1;
315             }
316             Some(cursor)
317         };
318     }
319 
320     /// Gets the mutable cursor of the specified index node.
get_cursor_mut(&mut self, index: usize) -> Option<CursorMut<'_, JsonValue>>321     fn get_cursor_mut(&mut self, index: usize) -> Option<CursorMut<'_, JsonValue>> {
322         let len = self.len();
323         // If index is greater than the array length, returns.
324         // If index is less than half the array length, searches from front to back;
325         // If index is greater than half the array length, searches from the back to the front.
326         return if index >= len {
327             None
328         } else if index >= (len - 1) / 2 {
329             let mut steps = len - 1 - index;
330             let mut cursor = self.inner.cursor_back_mut();
331             while steps != 0 {
332                 let _ = cursor.index()?;
333                 cursor.move_prev();
334                 steps -= 1;
335             }
336             Some(cursor)
337         } else {
338             let mut steps = index;
339             let mut cursor = self.inner.cursor_front_mut();
340             while steps != 0 {
341                 let _ = cursor.index()?;
342                 cursor.move_next();
343                 steps -= 1;
344             }
345             Some(cursor)
346         };
347     }
348 }
349 
350 impl Display for Array {
fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result351     fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
352         write!(f, "[")?;
353         for (n, item) in self.inner.iter().enumerate() {
354             if n != 0 {
355                 write!(f, ",")?;
356             }
357             write!(f, "{item}")?;
358         }
359         write!(f, "]")
360     }
361 }
362 
363 impl Debug for Array {
fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result364     fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
365         Display::fmt(self, f)
366     }
367 }
368 
369 #[cfg(test)]
370 mod ut_linked_list {
371     use crate::{Array, JsonValue};
372 
373     /// UT test for `Array::is_empty`.
374     ///
375     /// # Title
376     /// ut_array_is_empty
377     ///
378     /// # Brief
379     /// 1. Creates some `Array`s.
380     /// 2. Calls `Array::is_empty`.
381     /// 3. Checks if the test results are correct.
382     #[test]
ut_array_is_empty()383     fn ut_array_is_empty() {
384         assert!(Array::new().is_empty());
385         assert!(!array!(1).is_empty());
386     }
387 
388     /// UT test for `Array::pop`.
389     ///
390     /// # Title
391     /// ut_array_pop
392     ///
393     /// # Brief
394     /// 1. Creates some `Array`s.
395     /// 2. Calls `Array::pop`.
396     /// 3. Checks if the test results are correct.
397     #[test]
ut_array_pop()398     fn ut_array_pop() {
399         let mut array = array!(1);
400         assert_eq!(array.pop(), Some(JsonValue::new_number(1.into())));
401         assert_eq!(array.pop(), None);
402     }
403 
404     /// UT test for `Array::iter_mut`.
405     ///
406     /// # Title
407     /// ut_array_iter_mut
408     ///
409     /// # Brief
410     /// 1. Creates some `Array`s.
411     /// 2. Calls `Array::iter_mut`.
412     /// 3. Checks if the test results are correct.
413     #[test]
ut_array_iter_mut()414     fn ut_array_iter_mut() {
415         let mut array = array!(1);
416         let mut iter = array.iter_mut();
417         assert_eq!(iter.next(), Some(&mut JsonValue::new_number(1.into())));
418         assert_eq!(iter.next(), None);
419     }
420 
421     /// UT test for `Array::last`.
422     ///
423     /// # Title
424     /// ut_array_last
425     ///
426     /// # Brief
427     /// 1. Creates some `Array`s.
428     /// 2. Calls `Array::last`.
429     /// 3. Checks if the test results are correct.
430     #[test]
ut_array_last()431     fn ut_array_last() {
432         let array = array!(1);
433         assert_eq!(array.last(), Some(&JsonValue::new_number(1.into())));
434 
435         let array = Array::new();
436         assert_eq!(array.last(), None);
437     }
438 
439     /// UT test for `Array::get_node`.
440     ///
441     /// # Title
442     /// ut_array_get_node
443     ///
444     /// # Brief
445     /// 1. Creates some `Array`s.
446     /// 2. Calls `Array::get_node`.
447     /// 3. Checks if the test results are correct.
448     #[test]
ut_array_get_node()449     fn ut_array_get_node() {
450         let array = array!(1, 2, 3, 4, 5, 6);
451         assert!(array.get_node(0).is_some());
452         assert!(array.get_node(1).is_some());
453         assert!(array.get_node(2).is_some());
454         assert!(array.get_node(3).is_some());
455         assert!(array.get_node(4).is_some());
456         assert!(array.get_node(5).is_some());
457         assert!(array.get_node(6).is_none());
458     }
459 
460     /// UT test for `Array::get_node_mut`.
461     ///
462     /// # Title
463     /// ut_array_get_node_mut
464     ///
465     /// # Brief
466     /// 1. Creates some `Array`s.
467     /// 2. Calls `Array::get_node_mut`.
468     /// 3. Checks if the test results are correct.
469     #[test]
ut_array_get_node_mut()470     fn ut_array_get_node_mut() {
471         let mut array = array!(1, 2, 3, 4, 5, 6);
472         assert!(array.get_node_mut(0).is_some());
473         assert!(array.get_node_mut(1).is_some());
474         assert!(array.get_node_mut(2).is_some());
475         assert!(array.get_node_mut(3).is_some());
476         assert!(array.get_node_mut(4).is_some());
477         assert!(array.get_node_mut(5).is_some());
478         assert!(array.get_node_mut(6).is_none());
479     }
480 
481     /// UT test for `Array::last_node`.
482     ///
483     /// # Title
484     /// ut_array_last_node
485     ///
486     /// # Brief
487     /// 1. Creates some `Array`s.
488     /// 2. Calls `Array::last_node`.
489     /// 3. Checks if the test results are correct.
490     #[test]
ut_array_last_node()491     fn ut_array_last_node() {
492         let array = array!(1);
493         assert!(array.last_node().is_some());
494 
495         let array = Array::new();
496         assert!(array.last_node().is_none());
497     }
498 
499     /// UT test for `Array::last_node_mut`.
500     ///
501     /// # Title
502     /// ut_array_last_node_mut
503     ///
504     /// # Brief
505     /// 1. Creates some `Array`s.
506     /// 2. Calls `Array::last_node_mut`.
507     /// 3. Checks if the test results are correct.
508     #[test]
ut_array_last_node_mut()509     fn ut_array_last_node_mut() {
510         let mut array = array!(1);
511         assert!(array.last_node_mut().is_some());
512 
513         let mut array = Array::new();
514         assert!(array.last_node_mut().is_none());
515     }
516 
517     /// UT test for `Array::fmt`.
518     ///
519     /// # Title
520     /// ut_array_fmt
521     ///
522     /// # Brief
523     /// 1. Creates some `Array`s.
524     /// 2. Calls `Array::fmt`.
525     /// 3. Checks if the test results are correct.
526     #[test]
ut_array_fmt()527     fn ut_array_fmt() {
528         let array = array!(1, 2);
529         assert_eq!(format!("{array}"), "[1,2]");
530         assert_eq!(format!("{array:?}"), "[1,2]");
531     }
532 }
533