xelf 0.5.3

A versatile Rust toolkit for self-use.
Documentation
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use crate::collections::Contains;
use ::serde::{de::DeserializeOwned, ser::Serialize};
use ::serde_json::{json, map::Map, value::Index, Number, Value as Json};
use ::std::{borrow::Borrow, hash::Hash, str::FromStr};
#[cfg(feature = "num")]
use num_traits::{AsPrimitive, Float, FromPrimitive, PrimInt};

////////////////////////////////////////////////////////////////////////////////

/// Trait for JSON object, arrary, associated with an index.
pub trait JsonIndexed<I> {
    fn get_member(&self, index: I) -> Option<&Json>;
}

impl<I: Index> JsonIndexed<I> for Json {
    #[inline(always)]
    fn get_member(&self, index: I) -> Option<&Json> {
        self.get(index)
    }
}

impl<I: AsRef<str>> JsonIndexed<I> for Map<String, Json> {
    #[inline(always)]
    fn get_member(&self, index: I) -> Option<&Json> {
        self.get(index.as_ref())
    }
}

impl<I: PrimInt + AsPrimitive<usize> + Index> JsonIndexed<I> for Vec<Json> {
    #[inline(always)]
    fn get_member(&self, index: I) -> Option<&Json> {
        self.get(index.as_())
    }
}

////////////////////////////////////////////////////////////////////////////////

/// Trait to get a field value with a default value.
pub trait JsonGetOr<'a, I, T, _T> {
    /// Get a field value, returns the default value if failed.
    ///
    /// # Arguments
    ///
    /// * `index` - A string (slice) for a child value, or an integer value of an array item.
    ///
    /// * `default` - The default value returned on error.
    ///
    /// # Returns
    ///
    /// If there is an item which matches the index and the default value's type, return its value.
    ///
    /// Otherwize, returns the default value.
    ///
    /// # Examples
    ///
    /// ```
    /// use serde_json::json;
    /// use xelf::json::*;
    ///
    /// let jsn = json!({"name": "Tom", "value": 100});
    ///
    /// assert_eq!(jsn.get_or("name", "John"), "Tom");
    /// // type dese not match
    /// assert_eq!(jsn.get_or("name", 1), 1);
    /// // index dese not match
    /// assert_eq!(jsn.get_or("Name", "Json"), "Json");
    ///
    /// assert_eq!(jsn.get_or("value", 1), 100);
    /// // type dese not match
    /// assert_eq!(jsn.get_or("value", "1"), "1");
    /// ```
    fn get_or(&'a self, index: I, default: T) -> T;

    /// Get a field value, returns the default value if failed.
    ///
    /// # Arguments
    ///
    /// * `index` - A string (slice) for a child value, or an integer value of an array item.
    ///
    /// * `f` - A function to return the default value.
    ///
    /// # Returns
    ///
    /// If there is an item which matches the index and the default value's type, return its value.
    ///
    /// Otherwize, call the function and returns it's result.
    fn get_or_else<F: FnOnce() -> T>(&'a self, index: I, f: F) -> T;
}

#[cfg(feature = "num")]
impl<I, T, V> JsonGetOr<'_, I, T, i64> for V
where
    I: Index,
    T: PrimInt + FromPrimitive,
    V: JsonIndexed<I>,
{
    #[inline]
    fn get_or(&self, index: I, default: T) -> T {
        self.get_member(index)
            .and_then(|x| x.as_i64())
            .and_then(|x| T::from_i64(x))
            .unwrap_or(default)
    }

    #[inline]
    fn get_or_else<F: FnOnce() -> T>(&self, index: I, f: F) -> T {
        self.get_member(index)
            .and_then(|x| x.as_i64())
            .and_then(|x| T::from_i64(x))
            .unwrap_or_else(f)
    }
}

#[cfg(feature = "num")]
impl<I, T, V> JsonGetOr<'_, I, T, f64> for V
where
    I: Index,
    T: Float + FromPrimitive,
    V: JsonIndexed<I>,
{
    #[inline]
    fn get_or(&self, index: I, default: T) -> T {
        self.get_member(index)
            .and_then(|x| x.as_f64())
            .and_then(|x| T::from_f64(x))
            .unwrap_or(default)
    }

    #[inline]
    fn get_or_else<F: FnOnce() -> T>(&self, index: I, f: F) -> T {
        self.get_member(index)
            .and_then(|x| x.as_f64())
            .and_then(|x| T::from_f64(x))
            .unwrap_or_else(f)
    }
}

impl<'a, I: Index, V: JsonIndexed<I>> JsonGetOr<'a, I, &'a str, char> for V {
    #[inline]
    fn get_or(&'a self, index: I, default: &'a str) -> &'a str {
        self.get_member(index)
            .and_then(|x| x.as_str())
            .unwrap_or(default)
    }

    #[inline]
    fn get_or_else<F: FnOnce() -> &'a str>(&'a self, index: I, f: F) -> &'a str {
        self.get_member(index)
            .and_then(|x| x.as_str())
            .unwrap_or_else(f)
    }
}

impl<I: Index, V: JsonIndexed<I>> JsonGetOr<'_, I, bool, bool> for V {
    #[inline]
    fn get_or(&self, index: I, default: bool) -> bool {
        self.get_member(index)
            .and_then(|x| x.as_bool())
            .unwrap_or(default)
    }

    #[inline]
    fn get_or_else<F: FnOnce() -> bool>(&self, index: I, f: F) -> bool {
        self.get_member(index)
            .and_then(|x| x.as_bool())
            .unwrap_or_else(f)
    }
}

////////////////////////////////////////////////////////////////////////////////

/// Extension for serde_json::Value.
pub trait JsonObjectXlf {
    /// Insert a key-value pair into a JSON object by specifying the key name
    /// and the value to be assigned to it.
    ///
    /// # Arguments
    ///
    /// * `k` `v`: can be primitive data type, such as string references or integers.
    ///
    /// # Examples
    ///
    /// ```
    /// use serde_json::json;
    /// use xelf::json::*;
    ///
    /// let mut jsn = json!({});
    ///
    /// jsn.insert_s("name", "tom");
    /// jsn.insert_s("age", 16);
    ///
    /// assert_eq!(jsn.get_or("name", ""), "tom");
    /// assert_eq!(jsn.get_or("age", 16), 16);
    /// ```
    fn insert_s<T: Serialize>(&mut self, k: &str, v: T) -> Option<Json>;

    /// Collect all fields that have the specified prefix and insert them into
    /// a new object, removing the prefix from the field names before insertion.
    ///
    fn take_with_prefix(&mut self, prefix: &str) -> Self;

    /// Merge this JSON object to a serializable object, skip the fields in `skip`.
    fn merge_to<T, S, K>(&self, dst: &mut T, skip: &S) -> serde_json::Result<()>
    where
        T: Serialize + DeserializeOwned,
        S: ?Sized + Contains<K, str>,
        K: Hash + Ord + Eq + Borrow<str>;

    /// Recursively update all fields of this JSON object with another JSON object.
    ///
    /// # Arguments
    ///
    /// * `source`: the source JSON object.
    /// * `allow_null`: If set to `true`, the function allows updating target fields
    ///   with null values from the source object.
    ///   If set to `false`, it ignores null values from the source object.
    ///
    fn deep_update_with(&mut self, source: Json, allow_null: bool);
}

impl JsonObjectXlf for Json {
    #[inline]
    fn insert_s<T: Serialize>(&mut self, k: &str, v: T) -> Option<Json> {
        self.as_object_mut().unwrap().insert(k.to_owned(), json!(v))
    }

    fn take_with_prefix(&mut self, prefix: &str) -> Self {
        Json::from(if let Some(src) = self.as_object_mut() {
            src.take_with_prefix(prefix)
        } else {
            Map::<String, Json>::new()
        })
    }

    fn merge_to<T, S, K>(&self, dst: &mut T, skip: &S) -> serde_json::Result<()>
    where
        T: Serialize + DeserializeOwned,
        S: ?Sized + Contains<K, str>,
        K: Hash + Ord + Eq + Borrow<str>,
    {
        if let Some(map) = self.as_object() {
            map.merge_to(dst, skip)
        } else {
            Ok(())
        }
    }

    fn deep_update_with(&mut self, source: Json, allow_null: bool) {
        match self {
            Json::Null => *self = source,
            Json::Bool(_) => match source {
                Json::Bool(x) => *self = Json::Bool(x),
                Json::Number(x) => {
                    if let Some(n) = x.as_i64() {
                        *self = Json::Bool(n != 0);
                    }
                }
                Json::String(x) => {
                    if let Ok(x) = x.parse::<bool>() {
                        *self = Json::Bool(x);
                    }
                }
                Json::Null if allow_null => *self = source,
                _ => (),
            },
            Json::Number(_) => match source {
                Json::Bool(x) => *self = Json::Number((x as i64).into()),
                Json::Number(x) => *self = Json::Number(x),
                Json::String(x) => {
                    if let Ok(x) = Number::from_str(&x) {
                        *self = Json::Number(x);
                    }
                }
                Json::Null if allow_null => *self = source,
                _ => (),
            },
            Json::String(_) => match source {
                Json::Bool(x) => *self = Json::String(x.to_string()),
                Json::Number(x) => *self = Json::String(x.to_string()),
                Json::String(x) => *self = Json::String(x),
                Json::Null if allow_null => *self = source,
                _ => (),
            },
            Json::Array(array) => match source {
                Json::Array(x) => *array = x,
                Json::String(x) => {
                    if let Ok(x) = serde_json::from_str(&x) {
                        *array = x;
                    }
                }
                _ => (),
            },
            Json::Object(map) => {
                map.deep_update_with(source, allow_null);
            }
        }
    }
}

impl JsonObjectXlf for Map<String, Json> {
    #[inline]
    fn insert_s<T: Serialize>(&mut self, k: &str, v: T) -> Option<Json> {
        self.insert(k.to_owned(), json!(v))
    }

    fn take_with_prefix(&mut self, prefix: &str) -> Self {
        let mut map = Map::new();
        for (k, v) in self {
            if let Some(stripped) = k.strip_prefix(prefix) {
                map.insert(stripped.to_owned(), v.take());
            }
        }
        map
    }

    fn merge_to<T, S, K>(&self, dst: &mut T, skip: &S) -> serde_json::Result<()>
    where
        T: Serialize + DeserializeOwned,
        S: ?Sized + Contains<K, str>,
        K: Hash + Ord + Eq + Borrow<str>,
    {
        let mut value = serde_json::to_value(&dst)?;
        if let Some(map) = value.as_object_mut() {
            for (k, v) in map {
                if !skip.contains_ref(k.as_str()) {
                    if let Some(o) = self.get(k) {
                        *v = o.clone();
                    }
                }
            }
        }
        T::deserialize_in_place(value, dst)?;
        Ok(())
    }

    fn deep_update_with(&mut self, source: Json, allow_null: bool) {
        let mut source = match source {
            Json::Object(x) => x,
            Json::String(x) => match serde_json::from_str(&x) {
                Ok(x) => x,
                _ => return,
            },
            _ => return,
        };
        for (k, v) in self.iter_mut() {
            if let Some(x) = source.remove(k) {
                v.deep_update_with(x, allow_null);
            }
        }
    }
}

// ////////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_json_get_or() {
        let jsn = json!({"name": "Tom", "value": 100, "weight": 50.});

        assert_eq!(jsn.get_or("name", "John"), "Tom");
        // type dese not match
        assert_eq!(jsn.get_or("name", 1), 1);
        // index dese not match
        assert_eq!(jsn.get_or("Name", "Json"), "Json");

        assert_eq!(jsn.get_or("value", 1), 100);
        // type dese not match
        assert_eq!(jsn.get_or("value", "1"), "1");

        assert_eq!(jsn.get_or("weight", 1.), 50.);
        // type dese not match
        assert_eq!(jsn.get_or("weight", "1"), "1");

        let jsn = jsn.as_object().unwrap();

        assert_eq!(jsn.get_or("name", "John"), "Tom");
        // type dese not match
        assert_eq!(jsn.get_or("name", 1), 1);
        // index dese not match
        assert_eq!(jsn.get_or("Name", "Json"), "Json");

        assert_eq!(jsn.get_or("value", 1), 100);
        assert_eq!(jsn.get_or_else("value", || 1), 100);
        // type dese not match
        assert_eq!(jsn.get_or("value", "1"), "1");

        assert_eq!(jsn.get_or("weight", 1.), 50.);
        // type dese not match
        assert_ne!(jsn.get_or("weight", 1), 50);
        // type dese not match
        assert_eq!(jsn.get_or("weight", "1"), "1");
        assert_eq!(jsn.get_or_else("weight", || "1"), "1");

        let jsn = json!([1, 2., "3"]);
        let jsn = jsn.as_array().unwrap();
        assert_eq!(jsn.get_or(0, 2), 1);
        // type dese not match
        assert_eq!(jsn.get_or(1, 3), 3);
        assert_eq!(jsn.get_or(1, 2.), 2.);
        assert_eq!(jsn.get_or(3, "3"), "3");
    }

    #[test]
    fn test_json_insert() {
        let mut jsn = json!({});

        jsn.insert_s("name", "tom");
        jsn.insert_s("age", 16);

        assert_eq!(jsn.get_or("name", ""), "tom");
        assert_eq!(jsn.get_or("age", 16), 16);
    }

    #[test]
    fn test_json_merge() {
        let jsn1 = json!({"1": 11, "2": 22, "3": 33});
        let mut jsn2 = json!({"1": 1, "2": 2});
        assert!(jsn1.merge_to(&mut jsn2, &["2"]).is_ok());

        assert_eq!(jsn2.get_or("1", 0i32), 11);
        assert_eq!(jsn2.get_or("2", 0i32), 2);
        assert_eq!(jsn2.get_or("3", 0i32), 0);
    }
}