-
Notifications
You must be signed in to change notification settings - Fork 4
/
assign.rs
918 lines (873 loc) · 35.7 KB
/
assign.rs
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
//! # Assign values based on JSON [`Pointer`]s
//!
//! This module provides the [`Assign`] trait which allows for the assignment of
//! values based on a JSON Pointer.
//!
//! This module is enabled by default with the `"assign"` feature flag.
//!
//! # Expansion
//! The path will automatically be expanded if the [`Pointer`] is not fully
//! exhausted before reaching a non-existent key in the case of objects, index
//! in the case of arrays, or a scalar value (including `null`) based upon a
//! best-guess effort on the meaning of each [`Token`](crate::Token):
//! - If the [`Token`](crate::Token) is equal to `"0"` or `"-"`, the token will
//! be considered an index of an array.
//! - All tokens not equal to `"0"` or `"-"` will be considered keys of an
//! object.
//!
//! ## Usage
//! [`Assign`] can be used directly or through the [`assign`](Pointer::assign)
//! method of [`Pointer`].
//!
//! ```rust
//! use jsonptr::Pointer;
//! use serde_json::json;
//! let mut data = json!({"foo": "bar"});
//! let ptr = Pointer::from_static("/foo");
//! let replaced = ptr.assign(&mut data, "baz").unwrap();
//! assert_eq!(replaced, Some(json!("bar")));
//! assert_eq!(data, json!({"foo": "baz"}));
//! ```
//! ## Provided implementations
//!
//! | Lang | value type | feature flag | Default |
//! | ----- |: ----------------- :|: ---------- :| ------- |
//! | JSON | `serde_json::Value` | `"json"` | ✓ |
//! | TOML | `toml::Value` | `"toml"` | |
//!
use crate::{
index::{OutOfBoundsError, ParseIndexError},
Pointer,
};
use core::fmt::{self, Debug};
/*
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
╔══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ Assign ║
║ ¯¯¯¯¯¯¯¯ ║
╚══════════════════════════════════════════════════════════════════════════════╝
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
/// Implemented by types which can internally assign a
/// ([`Value`](`Assign::Value`)) at a path represented by a JSON [`Pointer`].
///
/// ## Expansion
/// For provided implementations (`"json"`, and `"toml"`) path will
/// automatically be expanded the if the [`Pointer`] is not fully exhausted
/// before reaching a non-existent key in the case of objects, index in the case
/// of arrays, or a scalar value (including `null`) based upon a best-guess
/// effort on the meaning of each [`Token`](crate::Token):
///
/// - If the [`Token`](crate::Token) is equal to `"0"` or `"-"`, the token will
/// be considered an index of an array.
/// - All tokens not equal to `"0"` or `"-"` will be considered keys of an
/// object.
///
/// ## Examples
///
/// ### Successful assignment with replacement
/// This example demonstrates a successful assignment with replacement.
/// ```rust
/// use jsonptr::{Pointer, assign::Assign};
/// use serde_json::{json, Value};
///
/// let mut data = json!({"foo": "bar"});
/// let ptr = Pointer::from_static("/foo");
///
/// let replaced = data.assign(&ptr, "baz").unwrap();
/// assert_eq!(replaced, Some(json!("bar")));
/// assert_eq!(data, json!({"foo": "baz"}));
/// ```
///
/// ### Successful assignment with path expansion
/// This example demonstrates path expansion, including an array index (`"0"`)
/// ```rust
/// # use jsonptr::{Pointer, assign::Assign};
/// # use serde_json::{json, Value};
/// let ptr = Pointer::from_static("/foo/bar/0/baz");
/// let mut data = serde_json::json!({"foo": "bar"});
///
/// let replaced = data.assign(ptr, json!("qux")).unwrap();
///
/// assert_eq!(&data, &json!({"foo": {"bar": [{"baz": "qux"}]}}));
/// assert_eq!(replaced, Some(json!("bar")));
/// ```
///
/// ### Successful assignment with `"-"` token
///
/// This example performs path expansion using the special `"-"` token (per RFC
/// 6901) to represent the next element in an array.
///
/// ```rust
/// # use jsonptr::{Pointer, assign::Assign};
/// # use serde_json::{json, Value};
/// let ptr = Pointer::from_static("/foo/bar/-/baz");
/// let mut data = json!({"foo": "bar"});
///
/// let replaced = data.assign(ptr, json!("qux")).unwrap();
/// assert_eq!(&data, &json!({"foo": {"bar": [{"baz": "qux"}]}}));
/// assert_eq!(replaced, Some(json!("bar")));
/// ```
pub trait Assign {
/// The type of value that this implementation can operate on.
type Value;
/// Error associated with `Assign`
type Error;
/// Assigns a value of based on the path provided by a JSON Pointer,
/// returning the replaced value, if any.
///
/// # Errors
/// Returns [`Self::Error`] if the assignment fails.
fn assign<V>(&mut self, ptr: &Pointer, value: V) -> Result<Option<Self::Value>, Self::Error>
where
V: Into<Self::Value>;
}
/*
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
╔══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ AssignError ║
║ ¯¯¯¯¯¯¯¯¯¯¯¯¯ ║
╚══════════════════════════════════════════════════════════════════════════════╝
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
/// Possible error returned from [`Assign`] implementations for
/// [`serde_json::Value`] and
/// [`toml::Value`](https://docs.rs/toml/0.8.14/toml/index.html).
#[derive(Debug, PartialEq, Eq)]
pub enum AssignError {
/// A `Token` within the `Pointer` failed to be parsed as an array index.
FailedToParseIndex {
/// Offset of the partial pointer starting with the invalid index.
offset: usize,
/// The source [`ParseIndexError`]
source: ParseIndexError,
},
/// target array.
OutOfBounds {
/// Offset of the partial pointer starting with the invalid index.
offset: usize,
/// The source [`OutOfBoundsError`]
source: OutOfBoundsError,
},
}
impl fmt::Display for AssignError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FailedToParseIndex { offset, .. } => {
write!(
f,
"assignment failed due to an invalid index at offset {offset}"
)
}
Self::OutOfBounds { offset, .. } => {
write!(
f,
"assignment failed due to index at offset {offset} being out of bounds"
)
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for AssignError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::FailedToParseIndex { source, .. } => Some(source),
Self::OutOfBounds { source, .. } => Some(source),
}
}
}
enum Assigned<'v, V> {
Done(Option<V>),
Continue { next_dest: &'v mut V, same_value: V },
}
/*
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
╔══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ json impl ║
║ ¯¯¯¯¯¯¯¯¯¯¯ ║
╚══════════════════════════════════════════════════════════════════════════════╝
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
#[cfg(feature = "json")]
mod json {
use super::{Assign, AssignError, Assigned};
use crate::{Pointer, Token};
use alloc::{
string::{String, ToString},
vec::Vec,
};
use core::mem;
use serde_json::{map::Entry, Map, Value};
fn expand(mut remaining: &Pointer, mut value: Value) -> Value {
while let Some((ptr, tok)) = remaining.split_back() {
remaining = ptr;
match tok.encoded() {
"0" | "-" => {
value = Value::Array(vec![value]);
}
_ => {
let mut obj = Map::new();
obj.insert(tok.to_string(), value);
value = Value::Object(obj);
}
}
}
value
}
impl Assign for Value {
type Value = Value;
type Error = AssignError;
fn assign<V>(&mut self, ptr: &Pointer, value: V) -> Result<Option<Self::Value>, Self::Error>
where
V: Into<Self::Value>,
{
assign_value(ptr, self, value.into())
}
}
pub(crate) fn assign_value(
mut ptr: &Pointer,
mut dest: &mut Value,
mut value: Value,
) -> Result<Option<Value>, AssignError> {
let mut offset = 0;
while let Some((token, tail)) = ptr.split_front() {
let tok_len = token.encoded().len();
let assigned = match dest {
Value::Array(array) => assign_array(token, tail, array, value, offset)?,
Value::Object(obj) => assign_object(token, tail, obj, value),
_ => assign_scalar(ptr, dest, value),
};
match assigned {
Assigned::Done(assignment) => {
return Ok(assignment);
}
Assigned::Continue {
next_dest: next_value,
same_value: same_src,
} => {
value = same_src;
dest = next_value;
ptr = tail;
}
}
offset += 1 + tok_len;
}
// Pointer is root, we can replace `dest` directly
let replaced = Some(core::mem::replace(dest, value));
Ok(replaced)
}
#[allow(clippy::needless_pass_by_value)]
fn assign_array<'v>(
token: Token<'_>,
remaining: &Pointer,
array: &'v mut Vec<Value>,
src: Value,
offset: usize,
) -> Result<Assigned<'v, Value>, AssignError> {
// parsing the index
let idx = token
.to_index()
.map_err(|source| AssignError::FailedToParseIndex { offset, source })?
.for_len_incl(array.len())
.map_err(|source| AssignError::OutOfBounds { offset, source })?;
debug_assert!(idx <= array.len());
if idx < array.len() {
// element exists in the array, we either need to replace it or continue
// depending on whether this is the last token or not
if remaining.is_root() {
// last token, we replace the value and call it a day
Ok(Assigned::Done(Some(mem::replace(&mut array[idx], src))))
} else {
// not the last token, we continue with a mut ref to the element as
// the next value
Ok(Assigned::Continue {
next_dest: &mut array[idx],
same_value: src,
})
}
} else {
// element does not exist in the array.
// we create the path and assign the value
let src = expand(remaining, src);
array.push(src);
Ok(Assigned::Done(None))
}
}
#[allow(clippy::needless_pass_by_value)]
fn assign_object<'v>(
token: Token<'_>,
remaining: &Pointer,
obj: &'v mut Map<String, Value>,
src: Value,
) -> Assigned<'v, Value> {
// grabbing the entry of the token
let entry = obj.entry(token.to_string());
// adding token to the pointer buf
match entry {
Entry::Occupied(entry) => {
// if the entry exists, we either replace it or continue
let entry = entry.into_mut();
if remaining.is_root() {
// if this is the last token, we are done
// grab the old value and replace it with the new one
Assigned::Done(Some(mem::replace(entry, src)))
} else {
// if this is not the last token, we continue with a mutable
// reference to the entry as the next value
Assigned::Continue {
same_value: src,
next_dest: entry,
}
}
}
Entry::Vacant(entry) => {
// if the entry does not exist, we create a value based on the
// remaining path with the src value as a leaf and assign it to the
// entry
entry.insert(expand(remaining, src));
Assigned::Done(None)
}
}
}
fn assign_scalar<'v>(
remaining: &Pointer,
scalar: &'v mut Value,
value: Value,
) -> Assigned<'v, Value> {
// scalar values are always replaced at the current buf (with its token)
// build the new src and we replace the value with it.
let replaced = Some(mem::replace(scalar, expand(remaining, value)));
Assigned::Done(replaced)
}
}
/*
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
╔══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ toml impl ║
║ ¯¯¯¯¯¯¯¯¯¯¯ ║
╚══════════════════════════════════════════════════════════════════════════════╝
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
#[cfg(feature = "toml")]
mod toml {
use super::{Assign, AssignError, Assigned};
use crate::{Pointer, Token};
use alloc::{string::String, vec, vec::Vec};
use core::mem;
use toml::{map::Entry, map::Map, Value};
fn expand(mut remaining: &Pointer, mut value: Value) -> Value {
while let Some((ptr, tok)) = remaining.split_back() {
remaining = ptr;
match tok.encoded() {
"0" | "-" => {
value = Value::Array(vec![value]);
}
_ => {
let mut obj = Map::new();
obj.insert(tok.to_string(), value);
value = Value::Table(obj);
}
}
}
value
}
impl Assign for Value {
type Value = Value;
type Error = AssignError;
fn assign<V>(&mut self, ptr: &Pointer, value: V) -> Result<Option<Self::Value>, Self::Error>
where
V: Into<Self::Value>,
{
assign_value(ptr, self, value.into())
}
}
pub(crate) fn assign_value(
mut ptr: &Pointer,
mut dest: &mut Value,
mut value: Value,
) -> Result<Option<Value>, AssignError> {
let mut offset = 0;
while let Some((token, tail)) = ptr.split_front() {
let tok_len = token.encoded().len();
let assigned = match dest {
Value::Array(array) => assign_array(token, tail, array, value, offset)?,
Value::Table(tbl) => assign_object(token, tail, tbl, value),
_ => assign_scalar(ptr, dest, value),
};
match assigned {
Assigned::Done(assignment) => {
return Ok(assignment);
}
Assigned::Continue {
next_dest: next_value,
same_value: same_src,
} => {
value = same_src;
dest = next_value;
ptr = tail;
}
}
offset += 1 + tok_len;
}
// Pointer is root, we can replace `dest` directly
let replaced = Some(mem::replace(dest, value));
Ok(replaced)
}
#[allow(clippy::needless_pass_by_value)]
fn assign_array<'v>(
token: Token<'_>,
remaining: &Pointer,
array: &'v mut Vec<Value>,
src: Value,
offset: usize,
) -> Result<Assigned<'v, Value>, AssignError> {
// parsing the index
let idx = token
.to_index()
.map_err(|source| AssignError::FailedToParseIndex { offset, source })?
.for_len_incl(array.len())
.map_err(|source| AssignError::OutOfBounds { offset, source })?;
debug_assert!(idx <= array.len());
if idx < array.len() {
// element exists in the array, we either need to replace it or continue
// depending on whether this is the last token or not
if remaining.is_root() {
// last token, we replace the value and call it a day
Ok(Assigned::Done(Some(mem::replace(&mut array[idx], src))))
} else {
// not the last token, we continue with a mut ref to the element as
// the next value
Ok(Assigned::Continue {
next_dest: &mut array[idx],
same_value: src,
})
}
} else {
// element does not exist in the array.
// we create the path and assign the value
let src = expand(remaining, src);
array.push(src);
Ok(Assigned::Done(None))
}
}
#[allow(clippy::needless_pass_by_value)]
fn assign_object<'v>(
token: Token<'_>,
remaining: &Pointer,
obj: &'v mut Map<String, Value>,
src: Value,
) -> Assigned<'v, Value> {
// grabbing the entry of the token
match obj.entry(token.to_string()) {
Entry::Occupied(entry) => {
// if the entry exists, we either replace it or continue
let entry = entry.into_mut();
if remaining.is_root() {
// if this is the last token, we are done
// grab the old value and replace it with the new one
Assigned::Done(Some(mem::replace(entry, src)))
} else {
// if this is not the last token, we continue with a mutable
// reference to the entry as the next value
Assigned::Continue {
same_value: src,
next_dest: entry,
}
}
}
Entry::Vacant(entry) => {
// if the entry does not exist, we create a value based on the
// remaining path with the src value as a leaf and assign it to the
// entry
entry.insert(expand(remaining, src));
Assigned::Done(None)
}
}
}
fn assign_scalar<'v>(
remaining: &Pointer,
scalar: &'v mut Value,
value: Value,
) -> Assigned<'v, Value> {
// scalar values are always replaced at the current buf (with its token)
// build the new src and we replace the value with it.
Assigned::Done(Some(mem::replace(scalar, expand(remaining, value))))
}
}
/*
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
╔══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ Tests ║
║ ¯¯¯¯¯¯¯ ║
╚══════════════════════════════════════════════════════════════════════════════╝
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*/
#[cfg(test)]
#[allow(clippy::too_many_lines)]
mod tests {
use super::{Assign, AssignError};
use crate::{
index::{OutOfBoundsError, ParseIndexError},
Pointer,
};
use alloc::str::FromStr;
use core::fmt::{Debug, Display};
#[derive(Debug)]
struct Test<V: Assign> {
data: V,
ptr: &'static str,
assign: V,
expected_data: V,
expected: Result<Option<V>, V::Error>,
}
impl<V> Test<V>
where
V: Assign + Clone + PartialEq + Display + Debug,
V::Value: Debug + PartialEq + From<V>,
V::Error: Debug + PartialEq,
Result<Option<V>, V::Error>: PartialEq<Result<Option<V::Value>, V::Error>>,
{
fn all(tests: impl IntoIterator<Item = Test<V>>) {
tests.into_iter().enumerate().for_each(|(i, t)| t.run(i));
}
fn run(self, i: usize) {
let Test {
ptr,
mut data,
assign,
expected_data,
expected,
..
} = self;
let ptr = Pointer::from_static(ptr);
let replaced = ptr.assign(&mut data, assign.clone());
assert_eq!(
&expected_data, &data,
"test #{i}:\n\ndata: \n{data:#?}\n\nexpected_data\n{expected_data:#?}"
);
assert_eq!(&expected, &replaced);
}
}
/*
╔═══════════════════════════════════════════════════╗
║ json ║
╚═══════════════════════════════════════════════════╝
*/
#[test]
#[cfg(feature = "json")]
fn assign_json() {
use alloc::vec;
use serde_json::json;
Test::all([
Test {
ptr: "/foo",
data: json!({}),
assign: json!("bar"),
expected_data: json!({"foo": "bar"}),
expected: Ok(None),
},
Test {
ptr: "",
data: json!({"foo": "bar"}),
assign: json!("baz"),
expected_data: json!("baz"),
expected: Ok(Some(json!({"foo": "bar"}))),
},
Test {
ptr: "/foo",
data: json!({"foo": "bar"}),
assign: json!("baz"),
expected_data: json!({"foo": "baz"}),
expected: Ok(Some(json!("bar"))),
},
Test {
ptr: "/foo/bar",
data: json!({"foo": "bar"}),
assign: json!("baz"),
expected_data: json!({"foo": {"bar": "baz"}}),
expected: Ok(Some(json!("bar"))),
},
Test {
ptr: "/foo/bar",
data: json!({}),
assign: json!("baz"),
expected_data: json!({"foo": {"bar": "baz"}}),
expected: Ok(None),
},
Test {
ptr: "/",
data: json!({}),
assign: json!("foo"),
expected_data: json!({"": "foo"}),
expected: Ok(None),
},
Test {
ptr: "/-",
data: json!({}),
assign: json!("foo"),
expected_data: json!({"-": "foo"}),
expected: Ok(None),
},
Test {
ptr: "/-",
data: json!(null),
assign: json!(34),
expected_data: json!([34]),
expected: Ok(Some(json!(null))),
},
Test {
ptr: "/foo/-",
data: json!({"foo": "bar"}),
assign: json!("baz"),
expected_data: json!({"foo": ["baz"]}),
expected: Ok(Some(json!("bar"))),
},
Test {
ptr: "/foo/-/bar",
assign: "baz".into(),
data: json!({}),
expected: Ok(None),
expected_data: json!({"foo":[{"bar": "baz"}]}),
},
Test {
ptr: "/foo/-/bar",
assign: "qux".into(),
data: json!({"foo":[{"bar":"baz" }]}),
expected: Ok(None),
expected_data: json!({"foo":[{"bar":"baz"},{"bar":"qux"}]}),
},
Test {
ptr: "/foo/-/bar",
data: json!({"foo":[{"bar":"baz"},{"bar":"qux"}]}),
assign: "quux".into(),
expected: Ok(None),
expected_data: json!({"foo":[{"bar":"baz"},{"bar":"qux"},{"bar":"quux"}]}),
},
Test {
ptr: "/foo/0/bar",
data: json!({"foo":[{"bar":"baz"},{"bar":"qux"},{"bar":"quux"}]}),
assign: "grault".into(),
expected: Ok(Some("baz".into())),
expected_data: json!({"foo":[{"bar":"grault"},{"bar":"qux"},{"bar":"quux"}]}),
},
Test {
ptr: "/0",
data: json!({}),
assign: json!("foo"),
expected_data: json!({"0": "foo"}),
expected: Ok(None),
},
Test {
ptr: "/1",
data: json!(null),
assign: json!("foo"),
expected_data: json!({"1": "foo"}),
expected: Ok(Some(json!(null))),
},
Test {
ptr: "/0",
data: json!([]),
expected_data: json!(["foo"]),
assign: json!("foo"),
expected: Ok(None),
},
Test {
ptr: "///bar",
data: json!({"":{"":{"bar": 42}}}),
assign: json!(34),
expected_data: json!({"":{"":{"bar":34}}}),
expected: Ok(Some(json!(42))),
},
Test {
ptr: "/1",
data: json!([]),
assign: json!("foo"),
expected: Err(AssignError::OutOfBounds {
offset: 0,
source: OutOfBoundsError {
index: 1,
length: 0,
},
}),
expected_data: json!([]),
},
Test {
ptr: "/0",
data: json!(["foo"]),
assign: json!("bar"),
expected: Ok(Some(json!("foo"))),
expected_data: json!(["bar"]),
},
Test {
ptr: "/a",
data: json!([]),
assign: json!("foo"),
expected: Err(AssignError::FailedToParseIndex {
offset: 0,
source: ParseIndexError {
source: usize::from_str("foo").unwrap_err(),
},
}),
expected_data: json!([]),
},
]);
}
/*
╔══════════════════════════════════════════════════╗
║ toml ║
╚══════════════════════════════════════════════════╝
*/
#[test]
#[cfg(feature = "toml")]
fn assign_toml() {
use alloc::vec;
use toml::{toml, Table, Value};
Test::all([
Test {
data: Value::Table(toml::Table::new()),
ptr: "/foo",
assign: "bar".into(),
expected_data: toml! { "foo" = "bar" }.into(),
expected: Ok(None),
},
Test {
data: toml! {foo = "bar"}.into(),
ptr: "",
assign: "baz".into(),
expected_data: "baz".into(),
expected: Ok(Some(toml! {foo = "bar"}.into())),
},
Test {
data: toml! { foo = "bar"}.into(),
ptr: "/foo",
assign: "baz".into(),
expected_data: toml! {foo = "baz"}.into(),
expected: Ok(Some("bar".into())),
},
Test {
data: toml! { foo = "bar"}.into(),
ptr: "/foo/bar",
assign: "baz".into(),
expected_data: toml! {foo = { bar = "baz"}}.into(),
expected: Ok(Some("bar".into())),
},
Test {
data: Table::new().into(),
ptr: "/",
assign: "foo".into(),
expected_data: toml! {"" = "foo"}.into(),
expected: Ok(None),
},
Test {
data: Table::new().into(),
ptr: "/-",
assign: "foo".into(),
expected_data: toml! {"-" = "foo"}.into(),
expected: Ok(None),
},
Test {
data: "data".into(),
ptr: "/-",
assign: 34.into(),
expected_data: Value::Array(vec![34.into()]),
expected: Ok(Some("data".into())),
},
Test {
data: toml! {foo = "bar"}.into(),
ptr: "/foo/-",
assign: "baz".into(),
expected_data: toml! {foo = ["baz"]}.into(),
expected: Ok(Some("bar".into())),
},
Test {
data: Table::new().into(),
ptr: "/0",
assign: "foo".into(),
expected_data: toml! {"0" = "foo"}.into(),
expected: Ok(None),
},
Test {
data: 21.into(),
ptr: "/1",
assign: "foo".into(),
expected_data: toml! {"1" = "foo"}.into(),
expected: Ok(Some(21.into())),
},
Test {
data: Value::Array(vec![]),
ptr: "/0",
expected_data: vec![Value::from("foo")].into(),
assign: "foo".into(),
expected: Ok(None),
},
Test {
ptr: "/foo/-/bar",
assign: "baz".into(),
data: Table::new().into(),
expected: Ok(None),
expected_data: toml! { "foo" = [{"bar" = "baz"}] }.into(),
},
Test {
ptr: "/foo/-/bar",
assign: "qux".into(),
data: toml! {"foo" = [{"bar" = "baz"}] }.into(),
expected: Ok(None),
expected_data: toml! {"foo" = [{"bar" = "baz"}, {"bar" = "qux"}]}.into(),
},
Test {
ptr: "/foo/-/bar",
data: toml! {"foo" = [{"bar" = "baz"}, {"bar" = "qux"}]}.into(),
assign: "quux".into(),
expected: Ok(None),
expected_data: toml! {"foo" = [{"bar" = "baz"}, {"bar" = "qux"}, {"bar" = "quux"}]}
.into(),
},
Test {
ptr: "/foo/0/bar",
data: toml! {"foo" = [{"bar" = "baz"}, {"bar" = "qux"}, {"bar" = "quux"}]}.into(),
assign: "grault".into(),
expected: Ok(Some("baz".into())),
expected_data:
toml! {"foo" = [{"bar" = "grault"}, {"bar" = "qux"}, {"bar" = "quux"}]}.into(),
},
Test {
data: Value::Array(vec![]),
ptr: "/-",
assign: "foo".into(),
expected: Ok(None),
expected_data: vec!["foo"].into(),
},
Test {
data: Value::Array(vec![]),
ptr: "/1",
assign: "foo".into(),
expected: Err(AssignError::OutOfBounds {
offset: 0,
source: OutOfBoundsError {
index: 1,
length: 0,
},
}),
expected_data: Value::Array(vec![]),
},
Test {
data: Value::Array(vec![]),
ptr: "/a",
assign: "foo".into(),
expected: Err(AssignError::FailedToParseIndex {
offset: 0,
source: ParseIndexError {
source: usize::from_str("foo").unwrap_err(),
},
}),
expected_data: Value::Array(vec![]),
},
]);
}
}