1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use crate::Value;

/// Represents a JSON key/value type.
///
/// For performance reasons we use a Vec instead of a Hashmap.
/// This comes with a tradeoff of slower key accesses as we need to iterate and compare.
///
/// The ObjectAsVec struct is a wrapper around a Vec of (&str, Value) pairs.
/// It provides methods to make it easy to migrate from serde_json::Value::Object or
/// serde_json::Map.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ObjectAsVec<'ctx>(pub Vec<(&'ctx str, Value<'ctx>)>);

impl<'ctx> From<Vec<(&'ctx str, Value<'ctx>)>> for ObjectAsVec<'ctx> {
    fn from(vec: Vec<(&'ctx str, Value<'ctx>)>) -> Self {
        Self(vec)
    }
}

impl<'ctx> ObjectAsVec<'ctx> {
    /// Access to the underlying Vec
    #[inline]
    pub fn as_vec(&self) -> &Vec<(&str, Value)> {
        &self.0
    }

    /// Access to the underlying Vec
    #[inline]
    pub fn into_vec(self) -> Vec<(&'ctx str, Value<'ctx>)> {
        self.0
    }

    /// Returns a reference to the value corresponding to the key.
    ///
    /// ## Performance
    /// As this is backed by a Vec, this searches linearly through the Vec as may be much more
    /// expensive than a `Hashmap` for larger Objects.
    #[inline]
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.0
            .iter()
            .find_map(|(k, v)| if *k == key { Some(v) } else { None })
    }

    /// Returns a mutable reference to the value corresponding to the key, if it exists.
    ///
    /// ## Performance
    /// As this is backed by a Vec, this searches linearly through the Vec as may be much more
    /// expensive than a `Hashmap` for larger Objects.
    #[inline]
    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value<'ctx>> {
        self.0
            .iter_mut()
            .find_map(|(k, v)| if *k == key { Some(v) } else { None })
    }

    /// Returns the key-value pair corresponding to the supplied key.
    ///
    /// ## Performance
    /// As this is backed by a Vec, this searches linearly through the Vec as may be much more
    /// expensive than a `Hashmap` for larger Objects.
    #[inline]
    pub fn get_key_value(&self, key: &str) -> Option<(&str, &Value)> {
        self.0
            .iter()
            .find_map(|(k, v)| if *k == key { Some((*k, v)) } else { None })
    }

    /// An iterator visiting all key-value pairs
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
        self.0.iter().map(|(k, v)| (*k, v))
    }

    /// Returns the number of elements in the object
    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns true if the object contains no elements
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// An iterator visiting all keys
    #[inline]
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.0.iter().map(|(k, _)| *k)
    }

    /// An iterator visiting all values
    #[inline]
    pub fn values(&self) -> impl Iterator<Item = &Value> {
        self.0.iter().map(|(_, v)| v)
    }

    /// Returns true if the object contains a value for the specified key.
    ///
    /// ## Performance
    /// As this is backed by a Vec, this searches linearly through the Vec as may be much more
    /// expensive than a `Hashmap` for larger Objects.
    #[inline]
    pub fn contains_key(&self, key: &str) -> bool {
        self.0.iter().any(|(k, _)| *k == key)
    }

    /// Inserts a key-value pair into the object.
    /// If the object did not have this key present, `None` is returned.
    /// If the object did have this key present, the value is updated, and the old value is
    /// returned.
    ///
    /// ## Performance
    /// This operation is linear in the size of the Vec because it potentially requires iterating
    /// through all elements to find a matching key.
    #[inline]
    pub fn insert(&mut self, key: &'ctx str, value: Value<'ctx>) -> Option<Value<'ctx>> {
        for (k, v) in &mut self.0 {
            if *k == key {
                return Some(std::mem::replace(v, value));
            }
        }
        // If the key is not found, push the new key-value pair to the end of the Vec
        self.0.push((key, value));
        None
    }

    /// Inserts a key-value pair into the object if the key does not yet exist, otherwise returns a
    /// mutable reference to the existing value.
    ///
    /// ## Performance
    /// This operation might be linear in the size of the Vec because it requires iterating through
    /// all elements to find a matching key, and might add to the end if not found.
    #[inline]
    pub fn insert_or_get_mut(&mut self, key: &'ctx str, value: Value<'ctx>) -> &mut Value<'ctx> {
        // get position to circumvent lifetime issue
        if let Some(pos) = self.0.iter_mut().position(|(k, _)| *k == key) {
            &mut self.0[pos].1
        } else {
            self.0.push((key, value));
            &mut self.0.last_mut().unwrap().1
        }
    }

    /// Inserts a key-value pair into the object and returns the mutable reference of the inserted
    /// value.
    ///
    /// ## Note
    /// The key must not exist in the object. If the key already exists, the object will contain
    /// multiple keys afterwards.
    ///
    /// ## Performance
    /// This operation is linear in the size of the Vec because it potentially requires iterating
    /// through all elements to find a matching key.
    #[inline]
    pub fn insert_unchecked_and_get_mut(
        &mut self,
        key: &'ctx str,
        value: Value<'ctx>,
    ) -> &mut Value<'ctx> {
        self.0.push((key, value));
        let idx = self.0.len() - 1;
        &mut self.0[idx].1
    }
}

impl<'ctx> IntoIterator for ObjectAsVec<'ctx> {
    type Item = (&'ctx str, Value<'ctx>);

    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'ctx> From<ObjectAsVec<'ctx>> for serde_json::Map<String, serde_json::Value> {
    fn from(val: ObjectAsVec<'ctx>) -> Self {
        val.into_iter()
            .map(|(key, val)| (key.to_owned(), val.into()))
            .collect()
    }
}
impl<'ctx> From<&ObjectAsVec<'ctx>> for serde_json::Map<String, serde_json::Value> {
    fn from(val: &ObjectAsVec<'ctx>) -> Self {
        val.iter()
            .map(|(key, val)| (key.to_owned(), val.into()))
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use super::*;

    #[test]
    fn test_empty_initialization() {
        let obj: ObjectAsVec = ObjectAsVec(Vec::new());
        assert!(obj.is_empty());
        assert_eq!(obj.len(), 0);
    }

    #[test]
    fn test_non_empty_initialization() {
        let obj = ObjectAsVec(vec![("key", Value::Null)]);
        assert!(!obj.is_empty());
        assert_eq!(obj.len(), 1);
    }

    #[test]
    fn test_get_existing_key() {
        let obj = ObjectAsVec(vec![("key", Value::Bool(true))]);
        assert_eq!(obj.get("key"), Some(&Value::Bool(true)));
    }

    #[test]
    fn test_get_non_existing_key() {
        let obj = ObjectAsVec(vec![("key", Value::Bool(true))]);
        assert_eq!(obj.get("not_a_key"), None);
    }

    #[test]
    fn test_get_key_value() {
        let obj = ObjectAsVec(vec![("key", Value::Bool(true))]);
        assert_eq!(obj.get_key_value("key"), Some(("key", &Value::Bool(true))));
    }

    #[test]
    fn test_keys_iterator() {
        let obj = ObjectAsVec(vec![("key1", Value::Null), ("key2", Value::Bool(false))]);
        let keys: Vec<_> = obj.keys().collect();
        assert_eq!(keys, vec!["key1", "key2"]);
    }

    #[test]
    fn test_values_iterator() {
        let obj = ObjectAsVec(vec![("key1", Value::Null), ("key2", Value::Bool(true))]);
        let values: Vec<_> = obj.values().collect();
        assert_eq!(values, vec![&Value::Null, &Value::Bool(true)]);
    }

    #[test]
    fn test_iter() {
        let obj = ObjectAsVec(vec![("key1", Value::Null), ("key2", Value::Bool(true))]);
        let pairs: Vec<_> = obj.iter().collect();
        assert_eq!(
            pairs,
            vec![("key1", &Value::Null), ("key2", &Value::Bool(true))]
        );
    }

    #[test]
    fn test_into_vec() {
        let obj = ObjectAsVec(vec![("key", Value::Null)]);
        let vec = obj.into_vec();
        assert_eq!(vec, vec![("key", Value::Null)]);
    }

    #[test]
    fn test_contains_key() {
        let obj = ObjectAsVec(vec![("key", Value::Bool(false))]);
        assert!(obj.contains_key("key"));
        assert!(!obj.contains_key("no_key"));
    }

    #[test]
    fn test_insert_new() {
        let mut obj = ObjectAsVec::default();
        assert_eq!(
            obj.insert("key1", Value::Str(Cow::Borrowed("value1"))),
            None
        );
        assert_eq!(obj.len(), 1);
        assert_eq!(obj.get("key1"), Some(&Value::Str(Cow::Borrowed("value1"))));
    }

    #[test]
    fn test_insert_update() {
        let mut obj = ObjectAsVec(vec![("key1", Value::Str(Cow::Borrowed("old_value1")))]);
        assert_eq!(
            obj.insert("key1", Value::Str(Cow::Borrowed("new_value1"))),
            Some(Value::Str(Cow::Borrowed("old_value1")))
        );
        assert_eq!(obj.len(), 1);
        assert_eq!(
            obj.get("key1"),
            Some(&Value::Str(Cow::Borrowed("new_value1")))
        );
    }

    #[test]
    fn test_insert_multiple_types() {
        let mut obj = ObjectAsVec::default();
        obj.insert("boolean", Value::Bool(true));
        obj.insert("number", Value::Number(3.14.into()));
        obj.insert("string", Value::Str(Cow::Borrowed("Hello")));
        obj.insert("null", Value::Null);

        assert_eq!(
            obj.insert(
                "array",
                Value::Array(vec![Value::Number(1_u64.into()), Value::Null])
            ),
            None
        );
        assert_eq!(obj.len(), 5);
        assert_eq!(obj.get("boolean"), Some(&Value::Bool(true)));
        assert_eq!(obj.get("number"), Some(&Value::Number(3.14.into())));
        assert_eq!(obj.get("string"), Some(&Value::Str(Cow::Borrowed("Hello"))));
        assert_eq!(obj.get("null"), Some(&Value::Null));
        assert_eq!(
            obj.get("array"),
            Some(&Value::Array(vec![
                Value::Number(1_u64.into()),
                Value::Null
            ]))
        );
    }
}