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
14use crate::JsonValue;
15use core::fmt::{Debug, Display, Formatter};
16use core::slice::{Iter, IterMut};
17
18/// Object type, implemented using Vec.
19///
20/// # Situation
21/// 1. When the average number of entries x under Object is about 15 <= x <= 100.
22///
23/// 2. When the average number of Object entries x is about 101 <= x <= 1024, and the creation to
24/// query ratio (the average number of queries created once) < 600.
25///
26/// 3. When the average number of objects x is about 1025 <= x <= 10000, and the creation to
27/// query ratio (the average number of queries created once) < 500.
28///
29/// # Attention
30/// * Only opening the 'vec_object' feature, this Object type can be used , and it conflicts with other Objects.
31///
32/// * This Object ** does not provide the ** de-duplicate function.
33/// * Users are required to ensure that there are no duplicate entries.
34///
35/// * The output order of this Object is the same as the insertion order.
36/// # Examples
37/// ```
38/// use ylong_json::Object;
39///
40/// let object = Object::new();
41/// assert_eq!(object.is_empty(), true);
42/// ```
43#[derive(Default, Clone)]
44pub struct Object {
45    inner: Vec<(String, JsonValue)>,
46}
47
48impl Object {
49    /// Creates an empty Object.
50    ///
51    /// # Examples
52    /// ```
53    /// use ylong_json::Object;
54    ///
55    /// let object = Object::new();
56    /// assert_eq!(object.is_empty(), true);
57    /// ```
58    pub fn new() -> Self {
59        Self { inner: Vec::new() }
60    }
61
62    /// Gets the length of Object.
63    ///
64    /// # Examples
65    /// ```
66    /// use ylong_json::{JsonValue, Object};
67    ///
68    /// let mut object = Object::new();
69    /// assert_eq!(object.len(), 0);
70    /// object.insert(String::from("null"), JsonValue::Null);
71    /// assert_eq!(object.len(), 1);
72    /// ```
73    pub fn len(&self) -> usize {
74        self.inner.len()
75    }
76
77    /// Determines whether the Object is empty.
78    ///
79    /// # Examples
80    /// ```
81    /// use ylong_json::{JsonValue, Object};
82    ///
83    /// let mut object = Object::new();
84    /// assert_eq!(object.is_empty(), true);
85    /// object.insert(String::from("null"), JsonValue::Null);
86    /// assert_eq!(object.is_empty(), false);
87    /// ```
88    pub fn is_empty(&self) -> bool {
89        self.inner.is_empty()
90    }
91
92    /// Checks whether the specified key exists in the Object.
93    ///
94    /// # Examples
95    /// ```
96    /// use ylong_json::{JsonValue, Object, Number};
97    ///
98    /// let mut object = Object::new();
99    /// object.insert(String::from("null"), JsonValue::Null);
100    ///
101    /// assert_eq!(object.contains_key("null"), true);
102    /// assert_eq!(object.contains_key("no_such_key"), false);
103    /// ```
104    pub fn contains_key(&self, key: &str) -> bool {
105        self.inner.iter().any(|(k, _)| k == key)
106    }
107
108    /// Inserts the specified key and value into an Object, appending them to the end without deduplication.
109    ///
110    /// # Examples
111    /// ```
112    /// use ylong_json::{JsonValue, Object};
113    ///
114    /// let mut object = Object::new();
115    /// assert_eq!(object.len(), 0);
116    /// object.insert(String::from("null"), JsonValue::Null);
117    /// assert_eq!(object.len(), 1);
118    /// ```
119    pub fn insert(&mut self, key: String, value: JsonValue) {
120        self.inner.push((key, value))
121    }
122
123    /// Removes the element under the specified key from the Object.If there is an element with
124    /// the same name in the Object, deletes the one with the smallest subscript.
125    ///
126    /// # Examples
127    /// ```
128    /// use ylong_json::{JsonValue, Object, Number};
129    ///
130    /// let mut object = Object::new();
131    /// object.insert(String::from("null"), JsonValue::Null);
132    /// assert_eq!(object.len(), 1);
133    /// assert_eq!(object.remove("null"), Some(JsonValue::Null));
134    /// assert_eq!(object.len(), 0);
135    /// ```
136    pub fn remove(&mut self, key: &str) -> Option<JsonValue> {
137        let pos = self.inner.iter().position(|(k, _)| k == key)?;
138        Some(self.inner.remove(pos).1)
139    }
140
141    /// Gets a common iterator of Object.
142    ///
143    /// # Examples
144    /// ```
145    /// use ylong_json::Object;
146    ///
147    /// let object = Object::new();
148    /// let iter = object.iter();
149    /// ```
150    pub fn iter(&self) -> Iter<'_, (String, JsonValue)> {
151        self.inner.iter()
152    }
153
154    /// Gets a mutable iterator of Object.
155    ///
156    /// # Examples
157    /// ```
158    /// use ylong_json::Object;
159    ///
160    /// let mut object = Object::new();
161    /// let iter_mut = object.iter_mut();
162    /// ```
163    pub fn iter_mut(&mut self) -> IterMut<'_, (String, JsonValue)> {
164        self.inner.iter_mut()
165    }
166
167    /// Gets a common reference to the element in Object with the specified key.
168    /// If there is an element with the same name, returns the one with the smallest subscript.
169    ///
170    /// # Examples
171    /// ```
172    /// use ylong_json::{JsonValue, Object, Number};
173    ///
174    /// let mut object = Object::new();
175    /// object.insert(String::from("test"), JsonValue::Number(Number::from(123)));
176    ///
177    /// assert_eq!(object.get("test"), Some(&JsonValue::Number(Number::from(123))));
178    /// assert_eq!(object.get("no_such_key"), None);
179    /// ```
180    pub fn get(&self, key: &str) -> Option<&JsonValue> {
181        self.inner.iter().find(|(k, _)| k == key).map(|(_, v)| v)
182    }
183
184    /// Gets a mutable reference to the element in Object with the specified key.
185    /// If there is an element with the same name, returns the one with the smallest subscript.
186    ///
187    /// # Examples
188    /// ```
189    /// use ylong_json::{JsonValue, Object};
190    ///
191    /// let mut object = Object::new();
192    /// object.insert(String::from("null"), JsonValue::Null);
193    ///
194    /// assert_eq!(object.get_mut("null"), Some(&mut JsonValue::Null));
195    /// assert_eq!(object.get_mut("no_such_key"), None);
196    /// ```
197    pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue> {
198        self.inner
199            .iter_mut()
200            .find(|(k, _)| k == key)
201            .map(|(_, v)| v)
202    }
203
204    /// Gets a mutable reference to the last element.
205    pub(crate) fn last_mut(&mut self) -> Option<&mut JsonValue> {
206        self.inner.last_mut().map(|(_, v)| v)
207    }
208
209    pub(crate) fn get_mut_by_position(&mut self, index: usize) -> Option<&mut JsonValue> {
210        self.inner.get_mut(index).map(|(_, v)| v)
211    }
212}
213
214impl PartialEq for Object {
215    /// Determines whether two objects are equal.
216    ///
217    /// The condition for two objects to be equal is that the two objects are of equal length
218    /// and the key-value pair can be one-to-one and exactly equal.
219    ///
220    /// # Examples
221    /// ```
222    /// use ylong_json::{Object, JsonValue};
223    ///
224    /// let object1 = Object::new();
225    /// let object2 = Object::new();
226    /// let mut object3 = Object::new();
227    /// object3.insert("test".to_string(), JsonValue::Null);
228    ///
229    /// assert_eq!(object1, object2);
230    /// assert_ne!(object1, object3);
231    /// ```
232    fn eq(&self, other: &Self) -> bool {
233        if self.len() != other.len() {
234            return false;
235        }
236        for (k, v) in self.iter() {
237            if other.get(k) != Some(v) {
238                return false;
239            }
240        }
241        true
242    }
243}
244
245impl Display for Object {
246    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
247        write!(f, "{{")?;
248        for (n, (key, value)) in self.inner.iter().enumerate() {
249            if n != 0 {
250                write!(f, ",")?;
251            }
252            write!(f, "\"{key}\":{value}")?;
253        }
254        write!(f, "}}")
255    }
256}
257
258impl Debug for Object {
259    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
260        Display::fmt(self, f)
261    }
262}
263
264#[cfg(test)]
265mod ut_vec {
266    use crate::{JsonValue, Object};
267
268    /// UT test for `Object::contains_key`.
269    ///
270    /// # Title
271    /// ut_object_contains_key
272    ///
273    /// # Brief
274    /// 1. Creates a `Object`.
275    /// 2. Calls `Object::contains_key` on it.
276    /// 3. Checks if the test results are correct.
277    #[test]
278    fn ut_object_contains_key() {
279        let object = object!("key1" => "value1");
280        assert!(object.contains_key("key1"));
281        assert!(!object.contains_key("key2"));
282    }
283
284    /// UT test for `Object::iter_mut`.
285    ///
286    /// # Title
287    /// ut_object_iter_mut
288    ///
289    /// # Brief
290    /// 1. Creates a `Object`.
291    /// 2. Calls `Object::iter_mut` on it.
292    /// 3. Checks if the test results are correct.
293    #[test]
294    fn ut_object_iter_mut() {
295        let mut object = object!("key1" => "value1");
296        let mut iter_mut = object.iter_mut();
297        assert_eq!(
298            iter_mut.next(),
299            Some(&mut (String::from("key1"), JsonValue::new_string("value1")))
300        );
301        assert_eq!(iter_mut.next(), None);
302    }
303
304    /// UT test for `Object::get_mut`.
305    ///
306    /// # Title
307    /// ut_object_get_mut
308    ///
309    /// # Brief
310    /// 1. Creates a `Object`.
311    /// 2. Calls `Object::get_mut` on it.
312    /// 3. Checks if the test results are correct.
313    #[test]
314    fn ut_object_get_mut() {
315        let mut object = object!("key1" => "value1");
316        assert_eq!(
317            object.get_mut("key1"),
318            Some(&mut JsonValue::new_string("value1"))
319        );
320        assert_eq!(object.get_mut("key2"), None);
321    }
322
323    /// UT test for `Object::fmt`.
324    ///
325    /// # Title
326    /// ut_object_fmt
327    ///
328    /// # Brief
329    /// 1. Creates a `Object`.
330    /// 2. Calls `Object::fmt` on it.
331    /// 3. Checks if the test results are correct.
332    #[test]
333    fn ut_object_fmt() {
334        let object = object!("key1" => "value1"; "key2" => "value2");
335        assert_eq!(
336            format!("{object}"),
337            "{\"key1\":\"value1\",\"key2\":\"value2\"}"
338        );
339        assert_eq!(
340            format!("{object:?}"),
341            "{\"key1\":\"value1\",\"key2\":\"value2\"}"
342        );
343    }
344
345    /// UT test for `Object::eq`.
346    ///
347    /// # Title
348    /// ut_object_fmt
349    ///
350    /// # Brief
351    /// 1. Creates a `Object`.
352    /// 2. Calls `Object::eq` on it.
353    /// 3. Checks if the test results are correct.
354    #[test]
355    fn ut_object_eq() {
356        let object1 = object!("key1" => "value1");
357        let object2 = object!("key1" => "value1"; "key2" => "value2");
358        let object3 = object!("key1" => "value1"; "key3" => "value3");
359
360        assert_eq!(object1, object1);
361        assert_ne!(object1, object2);
362        assert_ne!(object2, object3);
363    }
364}
365