ax_core 0.3.2

Core library implementing the functions of ax
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
428
429
430
431
432
433
434
435
436
437
use crate::settings::scope::Scope;
use serde_json::json;

#[derive(thiserror::Error, Debug, PartialEq, Eq)]
pub enum Error {
    #[error("Value {value} at path {path} is not of type object or array.")]
    NotAnObjectOrArray { path: Scope, value: serde_json::Value },
    #[error("Index {index} invalid at path {path}.")]
    InvalidArrayIndex { path: Scope, index: usize },
}

type Result<T> = std::result::Result<T, Error>;

pub trait JsonValue {
    /// Given two JSON objects, will return a set of changed scopes.
    #[cfg(test)]
    fn diff(&self, right: &Self) -> std::collections::BTreeSet<Scope>;

    /// Removes the value at `scope`.
    fn remove_at(&self, scope: &Scope) -> serde_json::Value;

    /// Updates the value at `scope` and creates empty objects or arrays at intermediate levels.
    /// Path elements of type number are used to index into arrays which are created if they do not
    /// already exist and the index is zero.
    /// Will fail with `NotAnObjectOrArray` if `value` already contains a simple JSON value at any
    /// parent level of `scope`.
    fn update_at(&self, scope: &Scope, value: serde_json::Value) -> Result<serde_json::Value>;

    /// Updates the value at `scope` and creates empty objects or arrays at intermediate levels.
    /// Path elements of type number are used to index into arrays which are created if they do not
    /// already exist and the index is zero.
    /// Intermediate simple values will be silently replaced by objects or arrays.
    fn update_at_force(&self, scope: &Scope, value: serde_json::Value) -> serde_json::Value;
}

/// Makes sure `scope` exists within this value by creating empty objects or arrays at every
/// level and a `null` value at the leaf if no value already exists.
/// Path elements of type number are used to index into arrays which are created if they do not
/// already exist and the index is zero.
/// If `force` is set to `true` pre-existing simple non-leaf values are silently replaced by
/// objects or arrays. Otherwise `Error::NotAnObjectOrArray` is returned.
fn mk_path(value: Option<&serde_json::Value>, scope: &Scope, prefix: Scope, force: bool) -> Result<serde_json::Value> {
    match scope.split_first() {
        None => Ok(value.cloned().unwrap_or(serde_json::Value::Null)),
        Some((head, tail)) => {
            let next_prefix = prefix.append(&head);
            let key = head.to_string();
            let idx: Option<usize> = key.as_str().parse().ok();
            match (value, idx, force) {
                (Some(serde_json::Value::Array(arr)), Some(idx), _) => {
                    if idx < arr.len() {
                        // replace
                        let mut arr = arr.clone();
                        arr[idx] = mk_path(arr.get(idx), &tail, next_prefix, force)?;
                        Ok(serde_json::Value::Array(arr))
                    } else if idx == arr.len() || force {
                        // append
                        let mut arr = arr.clone();
                        arr.push(mk_path(None, &tail, next_prefix, force)?);
                        Ok(serde_json::Value::Array(arr))
                    } else {
                        Err(Error::InvalidArrayIndex {
                            index: idx,
                            path: prefix,
                        })
                    }
                }
                (Some(serde_json::Value::Object(obj)), _, _) => {
                    let mut obj = obj.clone();
                    obj.insert(key.clone(), mk_path(obj.get(&key), &tail, next_prefix, force)?);
                    Ok(serde_json::Value::Object(obj))
                }
                (None, Some(idx), _) | (Some(_), Some(idx), true) => {
                    if idx == 0 || force {
                        // create array if missing or force overwrite
                        let arr = vec![mk_path(None, &tail, next_prefix, force)?];
                        Ok(serde_json::Value::Array(arr))
                    } else {
                        Err(Error::InvalidArrayIndex {
                            index: idx,
                            path: prefix,
                        })
                    }
                }
                (None, None, _) | (Some(_), None, true) => {
                    // create object if missing or force overwrite
                    let mut obj = serde_json::Map::new();
                    obj.insert(key.clone(), mk_path(obj.get(&key), &tail, next_prefix, true)?);
                    Ok(serde_json::Value::Object(obj))
                }
                (Some(value), _, _) => Err(Error::NotAnObjectOrArray {
                    path: prefix,
                    value: value.clone(),
                }),
            }
        }
    }
}

fn update_at(obj: &mut serde_json::Value, scope: &Scope, value: serde_json::Value) {
    if let Some(v) = obj.pointer_mut(scope.as_json_ptr().as_str()) {
        // errors are ignored so we return the unmodified object
        *v = value
    };
}

impl JsonValue for serde_json::Value {
    #[cfg(test)]
    fn diff(&self, right: &Self) -> std::collections::BTreeSet<Scope> {
        let mut differ = crate::settings::json_differ::JsonDiffer::new();
        treediff::diff(self, right, &mut differ);
        differ.changed_scopes
    }

    fn remove_at(&self, scope: &Scope) -> Self {
        if let Some((init, last)) = scope.split_last() {
            let mut obj = self.clone();
            if let Some(parent) = obj.pointer_mut(init.as_json_ptr().as_str()) {
                // errors are ignored so we return the unmodified object
                match parent {
                    serde_json::Value::Object(obj) => {
                        obj.remove(&last.to_string());
                    }
                    serde_json::Value::Array(arr) => {
                        if let Ok(idx) = last.to_string().as_str().parse::<usize>() {
                            if idx < arr.len() {
                                arr.remove(idx);
                            }
                        }
                    }
                    _ => {}
                }
            }
            obj
        } else {
            json!({})
        }
    }

    fn update_at(&self, scope: &Scope, value: Self) -> Result<Self> {
        mk_path(Some(self), scope, Scope::root(), false).map(|mut obj| {
            update_at(&mut obj, scope, value);
            obj
        })
    }

    fn update_at_force(&self, scope: &Scope, value: serde_json::Value) -> Self {
        let mut obj = mk_path(Some(self), scope, Scope::root(), true).unwrap();
        update_at(&mut obj, scope, value);
        obj
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::settings::scope::Scope;
    use serde_json::{json, Value};

    fn mp(value: serde_json::Value, scope: &'static str, force: bool) -> Result<serde_json::Value> {
        super::mk_path(Some(&value), &scope.try_into().unwrap(), Scope::root(), force)
    }

    #[test]
    fn mk_path() {
        assert_eq!(mp(json!({}), "key", false).unwrap(), json!({ "key": null }));
        assert_eq!(
            mp(json!({}), "key/sub", false).unwrap(),
            json!({ "key": { "sub": null } }),
        );

        assert_eq!(
            mp(json!({ "key": {} }), "key/sub", false).unwrap(),
            json!({ "key": { "sub": null } }),
        );

        assert_eq!(
            mp(json!({ "key": "value" }), "key", false).unwrap(),
            json!({ "key": "value" }),
        );

        assert_eq!(
            mp(json!({ "key": { "sub": {} } }), "key", false).unwrap(),
            json!({ "key": { "sub": {} } }),
        );

        assert_eq!(
            mp(json!({ "key": { "sub": {} } }), "key/sub2/0", false).unwrap(),
            json!({ "key": { "sub": {}, "sub2": [null] } }),
        );

        assert_eq!(
            mp(json!({ "key": { "sub": {} } }), "key/sub/0", false).unwrap(),
            json!({ "key": { "sub": { "0": null } } }),
        );

        assert_eq!(
            format!(
                "{}",
                mp(json!({ "key": { "sub": {} } }), "key/sub2/1", false).unwrap_err()
            ),
            "Index 1 invalid at path key/sub2.",
        );
    }

    #[test]
    fn mk_path_preexisting_simple_values() {
        assert_eq!(
            mp(json!({ "key": "value" }), "key", false).unwrap(),
            json!({ "key": "value" })
        );
    }

    #[test]
    fn mk_path_over_preexisting_simple_value() {
        assert_eq!(
            format!(
                "{}",
                mp(json!({ "key": { "sub": "value" } }), "key/sub/sub", false).unwrap_err()
            ),
            "Value \"value\" at path key/sub is not of type object or array.",
        );
        assert_eq!(
            format!(
                "{}",
                mp(json!({ "key": { "sub": "value" } }), "key/sub/0", false).unwrap_err()
            ),
            "Value \"value\" at path key/sub is not of type object or array.",
        );
    }

    #[test]
    fn mk_path_force_over_preexisting_simple_value() {
        assert_eq!(
            mp(json!({ "key": { "sub": "value" } }), "key/sub/sub", true).unwrap(),
            json!({ "key": { "sub": { "sub": null } } }),
        );
        assert_eq!(
            mp(json!({ "key": { "sub": "value" } }), "key/sub/0", true).unwrap(),
            json!({ "key": { "sub": [null] } }),
        );
    }

    #[test]
    fn mk_path_force_over_nonzero_idx() {
        assert_eq!(
            mp(json!({ "key": { "sub": "value" } }), "key/sub/2", true).unwrap(),
            json!({ "key": { "sub": [null] } }),
        );
    }

    #[test]
    pub fn diff_null() {
        let right = json!({"title": "Hello!"});
        let p = Value::Null.diff(&right);
        assert_eq!(p, maplit::btreeset![Scope::root()]);
    }

    #[test]
    pub fn diff_with_null() {
        let left = json!({"title": "Hello!"});
        let p = left.diff(&Value::Null);
        assert_eq!(p, maplit::btreeset![Scope::root()])
    }

    #[test]
    pub fn diff_array() {
        let left = json!(["hello", "bye"]);
        let right = json!([]);
        let p = left.diff(&right);
        assert_eq!(p, maplit::btreeset![Scope::root()]);

        let left = json!(["hello", "bye", "hi"]);
        let right = json!(["hello"]);
        let p = left.diff(&right);
        assert_eq!(p, maplit::btreeset![Scope::root()]);
    }

    #[test]
    pub fn diff_array_object() {
        let left = json!(["hello", "bye"]);
        let right = json!({"hello": "bye"});
        let p = left.diff(&right);
        assert_eq!(p, maplit::btreeset!["hello".try_into().unwrap(), Scope::root()]);
    }

    #[test]
    pub fn diff_nested() {
        let left = json!({
            "root": {
                "sub1":{
                    "prop": "unchanged",
                    "someArray": [],
                    "someOtherArray": []
                },
                "sub2": { "something": { "changed": "here" }}
            }
        });
        let right = json!({
            "root": {
                "sub1":{
                    "prop": "changed",
                    "someArray": ["insert"]
                },
                "sub2": { "something": { "changed": "for real" }}
            }
        });
        let diff = left.diff(&right);
        assert_eq!(
            diff,
            maplit::btreeset![
                "root/sub1/prop".try_into().unwrap(),
                "root/sub1/someArray".try_into().unwrap(),
                "root/sub1/someOtherArray".try_into().unwrap(),
                "root/sub2/something/changed".try_into().unwrap(),
            ]
        );
    }

    #[test]
    pub fn remove_at_empty() {
        assert_eq!(json!({}).remove_at(&Scope::root()), json!({}));
        assert_eq!(json!({}).remove_at(&"a/b".try_into().unwrap()), json!({}));
        assert_eq!(json!({}).remove_at(&"a/0".try_into().unwrap()), json!({}));
    }

    #[test]
    pub fn remove_at() {
        assert_eq!(json!({ "foo": "bar" }).remove_at(&"foo".try_into().unwrap()), json!({}));
        assert_eq!(
            json!({ "foo": { "bar": "baz" } }).remove_at(&"foo/bar".try_into().unwrap()),
            json!({ "foo": {} }),
        );
        assert_eq!(
            json!({ "foo": { "bar": "baz", "bar2": "baz2" } }).remove_at(&"foo/bar".try_into().unwrap()),
            json!({ "foo": { "bar2": "baz2"} }),
        );
        assert_eq!(
            json!({ "foo": ["bar", "baz"] }).remove_at(&"foo/1".try_into().unwrap()),
            json!({ "foo": ["bar"] }),
        );
    }

    #[test]
    pub fn remove_at_ignore_nonexisting() {
        assert_eq!(
            json!({ "foo": { "bar": "baz" } }).remove_at(&"foo/0".try_into().unwrap()),
            json!({ "foo": { "bar": "baz" } }),
        );
        assert_eq!(
            json!({ "foo": ["bar", "baz"] }).remove_at(&"foo/2".try_into().unwrap()),
            json!({ "foo": ["bar", "baz"] }),
        );
        assert_eq!(
            json!({ "foo": ["bar", "baz"] }).remove_at(&"foo/bar".try_into().unwrap()),
            json!({ "foo": ["bar", "baz"] }),
        );
    }

    #[test]
    pub fn update_at_create() {
        assert_eq!(
            json!({}).update_at(&"a/b".try_into().unwrap(), json!("value")).unwrap(),
            json!({"a": { "b": "value" } }),
        );
        assert_eq!(
            json!({})
                .update_at(&"a/b/0".try_into().unwrap(), json!("value"))
                .unwrap(),
            json!({"a": { "b": ["value"] } }),
        );
        assert_eq!(
            json!({"a": { "b": ["value"] } })
                .update_at(&"a/b/1".try_into().unwrap(), json!("value2"))
                .unwrap(),
            json!({"a": { "b": ["value", "value2"] } }),
        );
    }

    #[test]
    pub fn update_at_replace() {
        assert_eq!(
            json!({"a": { "b": "value" } })
                .update_at(&"a/b".try_into().unwrap(), json!("updated"))
                .unwrap(),
            json!({"a": { "b": "updated" } }),
        );
        assert_eq!(
            json!({"a": { "b": "value" } })
                .update_at(&"a/b".try_into().unwrap(), json!({ "c": "x" }))
                .unwrap(),
            json!({"a": { "b": { "c": "x" } } }),
        );
        assert_eq!(
            json!({"a": { "b": { "c": "x" } } })
                .update_at(&"a/b".try_into().unwrap(), json!("value"))
                .unwrap(),
            json!({"a": { "b": "value" } }),
        );
        assert_eq!(
            json!({"a": [{ "b": { "c": "x" } }] })
                .update_at(&"a/0/b".try_into().unwrap(), json!("value"))
                .unwrap(),
            json!({"a": [{ "b": "value" }] }),
        );
    }

    #[test]
    pub fn update_at_fail() {
        assert_eq!(
            format!(
                "{}",
                json!({"a": { "b": "x" } })
                    .update_at(&"a/b/c".try_into().unwrap(), json!("value"))
                    .unwrap_err()
            ),
            "Value \"x\" at path a/b is not of type object or array.",
        );
        assert_eq!(
            format!(
                "{}",
                json!({"a": [{ "b": "x" }] })
                    .update_at(&"a/2".try_into().unwrap(), json!("value"))
                    .unwrap_err()
            ),
            "Index 2 invalid at path a.",
        );
    }

    #[test]
    pub fn update_at_force() {
        assert_eq!(
            json!({"a": { "b": "x" } }).update_at_force(&"a/b/c".try_into().unwrap(), json!("value")),
            json!({"a": { "b": { "c": "value" } } }),
        );
    }
}