palim 0.3.1

Reversible JSON diff and patch for Rust, with array moves, text deltas, JSON Patch and Merge Patch
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
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
use crate::{Delta, Error, delta, patch};
use json_patch::{
    AddOperation, MoveOperation, Patch, PatchOperation, RemoveOperation, ReplaceOperation,
    jsonptr::{PointerBuf, Token},
};
use serde_json::{Value, json};
use std::collections::HashSet;

// Generate objects directly; only arrays and unsorted Map backends construct
// a local native delta. Projection filters use the whole native path instead.
pub(crate) fn direct_patch(
    left: &Value,
    right: &Value,
    matching: &crate::DiffOptions,
    options: &crate::JsonPatchOptions,
    input_depth: usize,
) -> Result<Patch, Error> {
    let mut direct = Direct {
        matching,
        replace_disjoint: !options.factorize && !options.tests,
        positional_reorders: !options.factorize
            && !options.rationalize
            && !options.tests
            && matching.detect_moves
            && matching.array_item_matcher.is_none()
            && matching.node_filter.is_none()
            && matching.property_filter.is_none(),
        // A native leaf tuple adds at most one container to the input depth.
        bounded_delta: input_depth < delta::MAX_DELTA_DEPTH,
        operations: Vec::new(),
    };
    let depth_error = direct.walk(left, right, &mut PointerBuf::new(), 0)?;
    if let Some(error) = depth_error {
        return Err(error);
    }
    Ok(Patch(direct.operations))
}

// Reuse the existing Map structure instead of serde_json::to_value's generic
// serializer and per-entry insertion, then keep its numeric normalization.
#[inline(never)]
pub(crate) fn copy_addition(value: &Value) -> Value {
    let mut copied = value.clone();
    normalize_addition(&mut copied);
    copied
}

fn normalize_addition(value: &mut Value) {
    match value {
        Value::Array(values) => values.iter_mut().for_each(normalize_addition),
        Value::Object(values) => values.values_mut().for_each(normalize_addition),
        // Use the same parser and unwrap behavior as json!(value), including
        // malformed Numbers constructed through from_string_unchecked.
        Value::Number(number) if !normalized_number(&crate::numbers::number_text(number)) => {
            #[cfg(feature = "exact-numbers")]
            {
                *number = number.as_str().parse().unwrap();
            }
            #[cfg(not(feature = "exact-numbers"))]
            {
                *value = json!(&*number);
            }
        }
        _ => {}
    }
}

// Under arbitrary_precision, serde_json keeps decimal digits but lowercases E,
// adds an exponent sign, and converts the integer -0 to 0. Only skip its parser
// for strings it would leave byte-for-byte unchanged; everything else still
// uses that parser, including invalid from_string_unchecked payloads.
fn normalized_number(raw: &str) -> bool {
    let mut bytes = raw.as_bytes();
    if let Some(rest) = bytes.strip_prefix(b"-") {
        bytes = rest;
    }
    match bytes.first() {
        Some(b'0') => bytes = &bytes[1..],
        Some(b'1'..=b'9') => {
            bytes = &bytes[1..];
            while bytes.first().is_some_and(u8::is_ascii_digit) {
                bytes = &bytes[1..];
            }
        }
        _ => return false,
    }
    if let Some(rest) = bytes.strip_prefix(b".") {
        bytes = rest;
        if !bytes.first().is_some_and(u8::is_ascii_digit) {
            return false;
        }
        while bytes.first().is_some_and(u8::is_ascii_digit) {
            bytes = &bytes[1..];
        }
    }
    if let Some(rest) = bytes.strip_prefix(b"e") {
        bytes = rest;
        match bytes.first() {
            Some(b'+' | b'-') => bytes = &bytes[1..],
            _ => return false,
        }
        if !bytes.first().is_some_and(u8::is_ascii_digit) {
            return false;
        }
        while bytes.first().is_some_and(u8::is_ascii_digit) {
            bytes = &bytes[1..];
        }
    }
    bytes.is_empty() && raw != "-0"
}

struct Direct<'a> {
    matching: &'a crate::DiffOptions,
    replace_disjoint: bool,
    positional_reorders: bool,
    bounded_delta: bool,
    operations: Vec<PatchOperation>,
}

fn check_leaf_depth(depth: usize, values: &[&Value]) -> Result<(), Error> {
    if depth >= delta::MAX_DELTA_DEPTH {
        return Err(Error::new("", "JSON nesting exceeds max_depth"));
    }
    for value in values {
        if value.is_array() || value.is_object() {
            delta::check_depth(value, delta::MAX_DELTA_DEPTH - depth - 1)?;
        }
    }
    Ok(())
}

impl Direct<'_> {
    fn native(
        &mut self,
        left: &Value,
        right: &Value,
        path: &PointerBuf,
        depth: usize,
    ) -> Result<Option<Error>, Error> {
        let change = match (left, right) {
            (Value::Array(source), Value::Array(target))
                if self.positional_reorders && self.bounded_delta =>
            {
                crate::diff::array_for_patch(
                    source,
                    target,
                    self.matching,
                    path,
                    &mut self.operations,
                )?
            }
            _ => crate::diff::node(left, right, self.matching, path.as_str())?,
        };
        let Some(change) = change else {
            return Ok(None);
        };
        let depth_error = if self.bounded_delta {
            None
        } else {
            delta::check_depth(&change, delta::MAX_DELTA_DEPTH.saturating_sub(depth)).err()
        };
        walk(
            left,
            right,
            &change,
            path,
            &mut self.operations,
            self.replace_disjoint,
        )?;
        Ok(depth_error)
    }

    fn walk(
        &mut self,
        left: &Value,
        right: &Value,
        path: &mut PointerBuf,
        depth: usize,
    ) -> Result<Option<Error>, Error> {
        if left == right {
            return Ok(None);
        }
        match (left, right) {
            (Value::Array(_), Value::Array(_)) => self.native(left, right, path, depth),
            (Value::Object(source), Value::Object(target)) => {
                // serde_json's downstream preserve_order feature can substitute
                // an insertion-ordered Map. Retain native ordering for that case.
                if !source.keys().is_sorted() || !target.keys().is_sorted() {
                    return self.native(left, right, path, depth);
                }
                let mut source = source.iter().peekable();
                let mut target = target.iter().peekable();
                let mut depth_error = None;
                loop {
                    let order = match (source.peek(), target.peek()) {
                        (Some((old, _)), Some((new, _))) => old.cmp(new),
                        (Some(_), None) => std::cmp::Ordering::Less,
                        (None, Some(_)) => std::cmp::Ordering::Greater,
                        (None, None) => break,
                    };
                    let (key, old, new) = match order {
                        std::cmp::Ordering::Less => {
                            let (key, old) = source.next().unwrap();
                            (key, Some(old), None)
                        }
                        std::cmp::Ordering::Greater => {
                            let (key, new) = target.next().unwrap();
                            (key, None, Some(new))
                        }
                        std::cmp::Ordering::Equal => {
                            let (key, old) = source.next().unwrap();
                            let (_, new) = target.next().unwrap();
                            (key, Some(old), Some(new))
                        }
                    };
                    path.push_back(key.as_str());
                    // Delay wire-depth failures until all matching callbacks have
                    // run, as in the full native diff followed by depth checking.
                    let child_error = match (old, new) {
                        (Some(old), Some(new)) => self.walk(old, new, path, depth + 1)?,
                        (Some(old), None) => {
                            let error = if self.bounded_delta {
                                None
                            } else {
                                check_leaf_depth(depth + 1, &[old]).err()
                            };
                            self.operations
                                .push(PatchOperation::Remove(RemoveOperation {
                                    path: path.clone(),
                                }));
                            error
                        }
                        (None, Some(new)) => {
                            let error = if self.bounded_delta {
                                None
                            } else {
                                check_leaf_depth(depth + 1, &[new]).err()
                            };
                            self.operations.push(PatchOperation::Add(AddOperation {
                                path: path.clone(),
                                value: copy_addition(new),
                            }));
                            error
                        }
                        (None, None) => unreachable!("key came from one of the objects"),
                    };
                    depth_error = depth_error.or(child_error);
                    path.pop_back();
                }
                Ok(depth_error)
            }
            _ => {
                let error = if self.bounded_delta {
                    None
                } else {
                    check_leaf_depth(depth, &[left, right]).err()
                };
                self.operations
                    .push(PatchOperation::Replace(ReplaceOperation {
                        path: path.clone(),
                        value: right.clone(),
                    }));
                Ok(error)
            }
        }
    }
}

// Standard generation need not construct reversible tuples when no
// primitive item can survive. Containers and caller-defined pairing stay on
// the native matching path. Check the first target before allocating a set so
// that common reorders usually return immediately.
pub(crate) fn disjoint_array_patch(
    left: &Value,
    right: &Value,
    positional: bool,
) -> Result<Option<Patch>, Error> {
    let (Some(source), Some(target)) = (left.as_array(), right.as_array()) else {
        return Ok(None);
    };
    if let Some(first) = target.first() {
        if first.is_array() || first.is_object() || source.contains(first) {
            return Ok(None);
        }
    }
    if let Some(first) = source.first() {
        if first.is_array() || first.is_object() || target.contains(first) {
            return Ok(None);
        }
    }
    if source
        .iter()
        .chain(target)
        .any(|value| value.is_array() || value.is_object())
    {
        return Ok(None);
    }
    crate::diff::check_array_capacity(source, target, "")?;
    let originals: HashSet<_> = source.iter().collect();
    if target.iter().any(|value| originals.contains(value)) {
        return Ok(None);
    }
    let mut output = Vec::new();
    if positional {
        replace_disjoint(source, target, &PointerBuf::new(), &mut output);
    } else {
        output.reserve(source.len() + target.len());
        for index in (0..source.len()).rev() {
            output.push(PatchOperation::Remove(RemoveOperation {
                path: child(&PointerBuf::new(), index),
            }));
        }
        for (index, value) in target.iter().enumerate() {
            output.push(PatchOperation::Add(AddOperation {
                path: child(&PointerBuf::new(), index),
                value: value.clone(),
            }));
        }
    }
    Ok(Some(Patch(output)))
}

fn replace_disjoint(
    source: &[Value],
    target: &[Value],
    path: &PointerBuf,
    out: &mut Vec<PatchOperation>,
) {
    let overlap = source.len().min(target.len());
    out.reserve(source.len().max(target.len()));
    for (index, value) in target.iter().take(overlap).enumerate() {
        out.push(PatchOperation::Replace(ReplaceOperation {
            path: child(path, index),
            value: value.clone(),
        }));
    }
    for index in (overlap..source.len()).rev() {
        out.push(PatchOperation::Remove(RemoveOperation {
            path: child(path, index),
        }));
    }
    for (index, value) in target.iter().enumerate().skip(overlap) {
        out.push(PatchOperation::Add(AddOperation {
            path: child(path, index),
            value: value.clone(),
        }));
    }
}

// Accept at most 10% overhead against estimated move bytes. The widest index
// is a cheap estimate; replacement bytes use exact scalar serialization and
// escaped parent-path lengths. Stop as soon as the budget is exceeded, so a
// one-move rotate examines only a few values and retains its native script.
pub(crate) fn positional_reorder(
    source: &[Value],
    target: &[Value],
    path: &PointerBuf,
    moves: usize,
    out: &mut Vec<PatchOperation>,
) -> Result<bool, Error> {
    if moves == 0 {
        return Ok(false);
    }
    let parent_bytes = crate::rfc::bytes(path.as_str())? as u128;
    let digits = (source.len() - 1).checked_ilog10().map_or(1, |v| v + 1) as u128;
    // A move has 29 bytes besides its two serialized pointer strings.
    // Include one comma per operation on both sides of the comparison.
    let budget = moves as u128 * (30 + 2 * (parent_bytes + 1 + digits)) * 11 / 10;
    let supported = |value: &Value| match value {
        Value::Array(_) | Value::Object(_) => false,
        // Preserve normalization and malformed unchecked-number behavior on
        // the native path; only already-normalized numbers enter this shortcut.
        Value::Number(number) => normalized_number(&crate::numbers::number_text(number)),
        _ => true,
    };
    let mut cost = 0u128;
    for (index, (old, new)) in source.iter().zip(target).enumerate() {
        // Matching proved that the unique token sets are identical. Checking
        // the target once therefore also establishes scalar/canonical source
        // values; identity/position keys cannot equal primitive value keys.
        if !supported(new) {
            return Ok(false);
        }
        if old != new {
            let digits = index.checked_ilog10().map_or(1, |v| v + 1) as u128;
            let value_bytes = match new {
                // arbitrary_precision serializes a normalized Number verbatim.
                Value::Number(number) => crate::numbers::number_text(number).len(),
                _ => crate::rfc::bytes(new)?,
            };
            // Replace has 33 bytes besides its serialized path and value.
            cost += 34 + parent_bytes + 1 + digits + value_bytes as u128;
            if cost > budget {
                return Ok(false);
            }
        }
    }
    out.reserve(source.len());
    for (index, (old, new)) in source.iter().zip(target).enumerate() {
        if old != new {
            out.push(PatchOperation::Replace(ReplaceOperation {
                path: child(path, index),
                value: new.clone(),
            }));
        }
    }
    Ok(true)
}

pub(crate) fn export(left: &Value, change: &Delta) -> Result<Patch, Error> {
    let right = patch::apply(left, &change.0, true)?;
    export_known(left, &right, change, true)
}

// The diff pipeline already knows the target (or its filtered projection).
// Public Delta::to_json_patch still validates its baseline through export above.
pub(crate) fn export_known(
    left: &Value,
    right: &Value,
    change: &Delta,
    replace_disjoint_arrays: bool,
) -> Result<Patch, Error> {
    let mut output = Vec::new();
    walk(
        left,
        right,
        &change.0,
        &PointerBuf::new(),
        &mut output,
        replace_disjoint_arrays,
    )?;
    Ok(Patch(output))
}

fn child<'a>(path: &PointerBuf, token: impl Into<Token<'a>>) -> PointerBuf {
    let mut result = path.clone();
    result.push_back(token);
    result
}

// Occupied original/final slots have frequency one. Prefix sums give the
// current sequential rank while point updates move an item between its slots.
// This is the binary indexed tree from Fenwick (1994), DOI 10.1002/spe.4380240306.
struct Ranks(Vec<usize>);

impl Ranks {
    fn new(mut frequencies: Vec<usize>) -> Self {
        for index in 0..frequencies.len() {
            let parent = index | (index + 1);
            if parent < frequencies.len() {
                frequencies[parent] += frequencies[index];
            }
        }
        Self(frequencies)
    }

    fn before(&self, mut end: usize) -> usize {
        let mut rank = 0;
        while end > 0 {
            rank += self.0[end - 1];
            end &= end - 1;
        }
        rank
    }

    fn occupy(&mut self, mut index: usize, occupied: bool) {
        while index < self.0.len() {
            if occupied {
                self.0[index] += 1;
            } else {
                self.0[index] -= 1;
            }
            index |= index + 1;
        }
    }
}

fn walk(
    left: &Value,
    right: &Value,
    change: &Value,
    path: &PointerBuf,
    out: &mut Vec<PatchOperation>,
    replace_disjoint_arrays: bool,
) -> Result<(), Error> {
    match change {
        Value::Array(a) => match a.len() {
            1 => out.push(PatchOperation::Add(AddOperation {
                path: path.clone(),
                value: a[0].clone(),
            })),
            2 => out.push(PatchOperation::Replace(ReplaceOperation {
                path: path.clone(),
                value: a[1].clone(),
            })),
            3 if a[2] == json!(0) => out.push(PatchOperation::Remove(RemoveOperation {
                path: path.clone(),
            })),
            3 if a[2] == json!(2) => out.push(PatchOperation::Replace(ReplaceOperation {
                path: path.clone(),
                value: right.clone(),
            })),
            _ => {
                return Err(Error::new(
                    path.as_str(),
                    "invalid delta in JSON Patch export",
                ));
            }
        },
        Value::Object(map) if delta::is_array(map) => {
            let source = left
                .as_array()
                .ok_or_else(|| Error::new(path.as_str(), "array delta requires an array"))?;
            let target = right
                .as_array()
                .ok_or_else(|| Error::new(path.as_str(), "array target is missing"))?;
            let parts = delta::parts(map, path.as_str())?;
            // Without survivors, positional replacements need half as many
            // operations. Factorization retains remove/add so that later adds
            // can become copies; guarded generation retains its container tests.
            if replace_disjoint_arrays
                && parts.moves.is_empty()
                && parts.changes.is_empty()
                && parts.removals.len() == source.len()
                && parts.additions.len() == target.len()
            {
                replace_disjoint(source, target, path, out);
                return Ok(());
            }
            let mut moved = vec![false; source.len()];
            let mut removed = vec![false; source.len()];
            for &old in parts.removals.keys() {
                removed[old] = true;
            }
            for &old in parts.moves.values() {
                moved[old] = true;
            }
            for (&old, change) in parts.removals.iter().rev() {
                if change[2] == json!(0) {
                    out.push(PatchOperation::Remove(RemoveOperation {
                        path: child(path, old),
                    }));
                }
            }
            let mut remaining = (0..source.len()).filter(|&old| !removed[old]);
            let mut desired = Vec::new();
            let mut old_at_target = vec![None; target.len()];
            for (&new, &old) in &parts.moves {
                old_at_target[new] = Some(old);
            }
            let mut additions = parts.additions.keys().copied().peekable();
            for (new, old_slot) in old_at_target.iter_mut().enumerate() {
                if additions.peek() == Some(&new) {
                    additions.next();
                    continue;
                }
                let old = old_slot
                    .as_ref()
                    .copied()
                    .or_else(|| remaining.next())
                    .ok_or_else(|| Error::new(path.as_str(), "invalid array mapping"))?;
                *old_slot = Some(old);
                desired.push(old);
            }
            if !parts.moves.is_empty() {
                // Reserve a final slot for every moved item immediately before its
                // next survivor, or after all originals if no survivor follows.
                // Survivors are already in original order. Thus the final occupied
                // slots spell `desired` without a mutable Vec or an order-stat tree.
                let mut originals = vec![0; source.len()];
                let mut finals = vec![0; source.len()];
                let mut frequencies = Vec::with_capacity(desired.len() + parts.moves.len());
                let mut cursor = 0;
                for old in 0..source.len() {
                    if removed[old] && !moved[old] {
                        continue;
                    }
                    if !moved[old] {
                        while desired.get(cursor) != Some(&old) {
                            let pending = desired
                                .get(cursor)
                                .copied()
                                .filter(|&i| moved[i])
                                .ok_or_else(|| {
                                    Error::new(path.as_str(), "inconsistent survivor order")
                                })?;
                            finals[pending] = frequencies.len();
                            frequencies.push(0);
                            cursor += 1;
                        }
                        cursor += 1;
                    }
                    originals[old] = frequencies.len();
                    frequencies.push(1);
                }
                for &old in &desired[cursor..] {
                    if !moved[old] {
                        return Err(Error::new(path.as_str(), "inconsistent survivor order"));
                    }
                    finals[old] = frequencies.len();
                    frequencies.push(0);
                }
                let mut ranks = Ranks::new(frequencies);
                for &old in desired.iter().rev().filter(|&&old| moved[old]) {
                    let from = ranks.before(originals[old]);
                    ranks.occupy(originals[old], false);
                    let to = ranks.before(finals[old]);
                    ranks.occupy(finals[old], true);
                    if from != to {
                        out.push(PatchOperation::Move(MoveOperation {
                            from: child(path, from),
                            path: child(path, to),
                        }));
                    }
                }
            }
            for (&new, value) in &parts.additions {
                out.push(PatchOperation::Add(AddOperation {
                    path: child(path, new),
                    value: (*value).clone(),
                }));
            }
            for (&new, change) in &parts.changes {
                let old = old_at_target[new]
                    .ok_or_else(|| Error::new(path.as_str(), "cannot modify an added item"))?;
                walk(
                    &source[old],
                    &target[new],
                    change,
                    &child(path, new),
                    out,
                    replace_disjoint_arrays,
                )?;
            }
        }
        Value::Object(map) => {
            for (key, change) in map {
                walk(
                    left.get(key).unwrap_or(&Value::Null),
                    right.get(key).unwrap_or(&Value::Null),
                    change,
                    &child(path, key.as_str()),
                    out,
                    replace_disjoint_arrays,
                )?;
            }
        }
        _ => {
            return Err(Error::new(
                path.as_str(),
                "invalid delta in JSON Patch export",
            ));
        }
    }
    Ok(())
}

#[cfg(test)]
mod direct_tests {
    use super::*;
    use crate::{DiffOptions, DiffPatcher, JsonPatchOptions};
    use proptest::prelude::*;
    use std::sync::{Arc, Mutex};

    #[test]
    #[cfg(feature = "exact-numbers")]
    fn normalized_number_matches_serde_parser() {
        for raw in [
            "0",
            "-0",
            "-0.0",
            "1.0",
            "1E5",
            "1e5",
            "1e+5",
            "1e-005",
            "1.00e+000",
            "0e-0",
            "1.5e+999",
            "18446744073709551616",
            "-9223372036854775809",
            "",
            "01",
            "-01",
            "+1",
            ".1",
            "1.",
            "1e",
            "1e+",
            "1e-",
            "1e+2.0",
            "1e+2x",
            "1e++2",
            "NaN",
            "1 ",
            " 1",
            "1\n",
            "Ù¡",
            "null",
        ] {
            let parsed = raw.parse::<serde_json::Number>();
            let unchanged = parsed.as_ref().is_ok_and(|number| number.as_str() == raw);
            assert_eq!(normalized_number(raw), unchanged, "{raw:?}");
        }
    }

    proptest! {
        #![proptest_config(ProptestConfig { cases:4096, rng_seed:proptest::test_runner::RngSeed::Fixed(20261006), ..ProptestConfig::default() })]
        #[test]
        fn number_fast_path_only_skips_unchanged_parser_results(
            raw in "[0-9.eE+\\-a-z \\n]{0,64}",
            float in any::<f64>(),
        ) {
            #[cfg(feature = "exact-numbers")]
            if normalized_number(&raw) {
                let parsed = raw.parse::<serde_json::Number>().unwrap();
                prop_assert_eq!(parsed.as_str(), raw.as_str());
            }
            if let Some(number) = serde_json::Number::from_f64(float) {
                let value = Value::Number(number);
                prop_assert_eq!(copy_addition(&value), json!(&value));
            }
            if let Ok(number) = raw.parse::<serde_json::Number>() {
                let value = Value::Number(number);
                prop_assert_eq!(copy_addition(&value), json!(&value));
            }
        }
    }

    #[test]
    #[cfg(feature = "exact-numbers")]
    fn addition_copy_keeps_nested_number_normalization_and_patch_bytes() {
        for raw in [
            "0",
            "-0",
            "-0.0",
            "1.0",
            "1E+0003",
            "1.00e00",
            "1e9999",
            "18446744073709551616",
            "-9223372036854775809",
            "0.000000001234567890123456789",
            "123456789012345678901234567890",
        ] {
            let number = Value::Number(serde_json::Number::from_string_unchecked(raw.into()));
            let mut value = json!({"nested":[null,{"a/~🦀":null}],"empty":{},
                "empty_array":[],"nil":null,"bool":true,"text":"Unicode 🦀"});
            value["nested"][0] = number.clone();
            value["nested"][1]["a/~🦀"] = number;
            let original = value.clone();
            let actual = copy_addition(&value);
            let expected = json!(&value);
            assert_eq!(actual, expected, "{raw}");
            assert_eq!(
                serde_json::to_vec(&actual).unwrap(),
                serde_json::to_vec(&expected).unwrap()
            );
            let left = json!({"kept":0});
            let mut right = left.clone();
            right["added/~"] = value.clone();
            let actual = direct_standard(&left, &right).unwrap();
            let expected = native_standard(&left, &right).unwrap();
            assert_eq!(
                serde_json::to_vec(&actual).unwrap(),
                serde_json::to_vec(&expected).unwrap()
            );
            assert_eq!(value, original);
        }
    }

    #[test]
    #[cfg(feature = "exact-numbers")]
    fn addition_copy_keeps_malformed_unchecked_number_failure() {
        let message = |result: std::thread::Result<Value>| {
            let error = result.expect_err("malformed unchecked Number must fail");
            error.downcast::<String>().unwrap()
        };
        for raw in ["", "01", "+1", "NaN", "1e", "1 ", "null"] {
            let value = Value::Array(vec![Value::Number(
                serde_json::Number::from_string_unchecked(raw.into()),
            )]);
            assert_eq!(
                message(std::panic::catch_unwind(|| copy_addition(&value))),
                message(std::panic::catch_unwind(|| json!(&value))),
                "{raw}"
            );
        }
    }

    fn native_optimized(
        matching: &DiffOptions,
        left: &Value,
        right: &Value,
        options: &JsonPatchOptions,
    ) -> Result<Patch, Error> {
        let patcher = DiffPatcher::new(matching.clone());
        let Some(change) = patcher.diff(left, right)? else {
            return Ok(Patch::default());
        };
        let standard = export_known(left, right, &change, !options.factorize && !options.tests)?;
        crate::rfc::optimize(left, right, standard, options)
    }

    fn mixed_json() -> impl Strategy<Value = Value> {
        prop_oneof![
            Just(Value::Null),
            any::<bool>().prop_map(Value::Bool),
            any::<i64>().prop_map(|value| json!(value)),
            proptest::collection::vec(any::<char>(), 0..8)
                .prop_map(|value| json!(value.into_iter().collect::<String>())),
        ]
        .prop_recursive(4, 64, 6, |inner| {
            prop_oneof![
                proptest::collection::vec(inner.clone(), 0..5).prop_map(Value::Array),
                proptest::collection::btree_map("[a-z~/]{0,4}", inner, 0..5)
                    .prop_map(|values| Value::Object(values.into_iter().collect())),
            ]
        })
    }

    proptest! {
        #![proptest_config(ProptestConfig { cases:128, rng_seed:proptest::test_runner::RngSeed::Fixed(20261005), ..ProptestConfig::default() })]
        #[test]
        fn hybrid_matches_native_on_arbitrary_mixed_json(left in mixed_json(), right in mixed_json()) {
            let matching = DiffOptions { text_diff_min_length:None, ..Default::default() };
            let patcher = DiffPatcher::new(matching.clone());
            for factorize in [false,true] {
                for rationalize in [false,true] {
                    for tests in [false,true] {
                        let options = JsonPatchOptions { factorize,rationalize,tests };
                        let expected = native_optimized(&matching,&left,&right,&options).unwrap();
                        let actual = patcher.diff_json_patch(&left,&right,&options).unwrap();
                        // Plain guarded root arrays can now use positional
                        // edits behind one complete baseline array test.
                        if !(tests && !factorize && !rationalize && left.is_array() && right.is_array()) {
                            prop_assert_eq!(&actual,&expected);
                        }
                        let mut applied = left.clone();
                        json_patch::patch(&mut applied,&actual).unwrap();
                        prop_assert_eq!(&applied,&right);
                        let inverse = crate::invert_json_patch(&left,&actual).unwrap();
                        json_patch::patch(&mut applied,&inverse).unwrap();
                        prop_assert_eq!(&applied,&left);
                    }
                }
            }
        }
    }

    #[test]
    fn hybrid_generation_keeps_native_operations_and_matching_callbacks() {
        let left = json!({"a/~":[{"id":1,"body":"old".repeat(40)},{"id":2,"body":"unchanged"}],
            "fields":{"a":1,"b":false},"z":{"array":[[1,2],[3,4]],"removed":[0]},"gone":true});
        let right = json!({"a/~":[{"id":2,"body":"unchanged"},{"id":1,"body":"new".repeat(40)}],
            "fields":{"a":2,"b":true},"z":{"array":[[3,4],[1,5]],"added":[1]},"added":null});
        for mode in 0..3 {
            for detect_moves in [false, true] {
                let calls = Arc::new(Mutex::new(Vec::new()));
                let mut matching = DiffOptions {
                    detect_moves,
                    include_value_on_move: true,
                    text_diff_min_length: None,
                    ..Default::default()
                };
                if mode == 1 {
                    let calls = calls.clone();
                    matching.object_hash = Some(Arc::new(move |value, index| {
                        calls.lock().unwrap().push(format!("hash:{index}:{value}"));
                        value.get("id").map(Value::to_string)
                    }));
                } else if mode == 2 {
                    let calls = calls.clone();
                    matching.array_item_matcher = Some(Arc::new(move |path, left, right| {
                        calls
                            .lock()
                            .unwrap()
                            .push(format!("match:{path}:{left}:{right}"));
                        match (left.get("id"), right.get("id")) {
                            (Some(a), Some(b)) => a == b,
                            _ => left == right,
                        }
                    }));
                }
                for factorize in [false, true] {
                    for rationalize in [false, true] {
                        for tests in [false, true] {
                            let options = JsonPatchOptions {
                                factorize,
                                rationalize,
                                tests,
                            };
                            calls.lock().unwrap().clear();
                            let expected =
                                native_optimized(&matching, &left, &right, &options).unwrap();
                            let expected_calls = calls.lock().unwrap().clone();
                            calls.lock().unwrap().clear();
                            let actual = DiffPatcher::new(matching.clone())
                                .diff_json_patch(&left, &right, &options)
                                .unwrap();
                            assert_eq!(calls.lock().unwrap().as_slice(), expected_calls);
                            assert_eq!(actual, expected);
                            let mut applied = left.clone();
                            json_patch::patch(&mut applied, &actual).unwrap();
                            assert_eq!(applied, right);
                            let inverse = crate::invert_json_patch(&left, &actual).unwrap();
                            json_patch::patch(&mut applied, &inverse).unwrap();
                            assert_eq!(applied, left);
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn hybrid_deep_errors_keep_later_matching_callbacks_and_inputs() {
        for depth in [0, 123, 124, 125, 126] {
            let wrap = |value| (0..depth).fold(value, |value, _| json!({"a":value}));
            let left = json!({"deep":wrap(json!([{"id":1,"n":1}])),"later":[{"id":2,"n":1}]});
            let right = json!({"deep":wrap(json!([{"id":1,"n":2}])),"later":[{"id":2,"n":2}]});
            let original = left.clone();
            let calls = Arc::new(Mutex::new(Vec::new()));
            let recorded = calls.clone();
            let matching = DiffOptions {
                object_hash: Some(Arc::new(move |value, index| {
                    recorded.lock().unwrap().push((value.clone(), index));
                    value.get("id").map(Value::to_string)
                })),
                text_diff_min_length: None,
                ..Default::default()
            };
            let options = JsonPatchOptions {
                factorize: false,
                rationalize: false,
                tests: false,
            };
            let expected = native_optimized(&matching, &left, &right, &options);
            let expected_calls = calls.lock().unwrap().clone();
            calls.lock().unwrap().clear();
            let actual = DiffPatcher::new(matching).diff_json_patch(&left, &right, &options);
            assert_eq!(actual, expected, "depth {depth}");
            assert_eq!(*calls.lock().unwrap(), expected_calls, "depth {depth}");
            assert_eq!(left, original);
        }
    }

    fn native_standard(left: &Value, right: &Value) -> Result<Patch, Error> {
        let patcher = DiffPatcher::new(DiffOptions {
            text_diff_min_length: None,
            ..Default::default()
        });
        match patcher.diff(left, right)? {
            Some(change) => export_known(left, right, &change, true),
            None => Ok(Patch::default()),
        }
    }

    fn direct_standard(left: &Value, right: &Value) -> Result<Patch, Error> {
        let options = DiffOptions {
            text_diff_min_length: None,
            ..Default::default()
        };
        let depth = delta::measure_depth(left, options.max_depth)?
            .max(delta::measure_depth(right, options.max_depth)?);
        direct_patch(
            left,
            right,
            &options,
            &JsonPatchOptions {
                factorize: false,
                rationalize: false,
                tests: false,
            },
            depth,
        )
    }

    #[test]
    fn direct_objects_keep_native_wire_order_and_payloads() {
        #[cfg(feature = "exact-numbers")]
        for raw in ["-0", "1E+0003", "1.00e00", "1.0", "1e9999"] {
            let number = Value::Number(serde_json::Number::from_string_unchecked(raw.into()));
            let mut right = json!({"":{"a/~🦀":2},"add":null,"z":true});
            right["add"] = number.clone();
            let left = json!({"":{"a/~🦀":1},"removed":[{"nested":true}],"z":false});
            for (left, right) in [
                (left.clone(), right.clone()),
                (right, left),
                (json!(null), number.clone()),
                (number, json!({"whole":[1,2]})),
            ] {
                let expected = native_standard(&left, &right).unwrap();
                let actual = direct_standard(&left, &right).unwrap();
                assert_eq!(actual, expected);
                assert_eq!(
                    serde_json::to_vec(&actual).unwrap(),
                    serde_json::to_vec(&expected).unwrap()
                );
            }
        }
        let left = json!({"array":[1,2],"nested":{"a":1}});
        let right = json!({"array":[1,2],"nested":{"a":2}});
        assert_eq!(
            direct_standard(&left, &right).unwrap(),
            native_standard(&left, &right).unwrap()
        );
        let right = json!({"array":[2,1]});
        assert_eq!(
            direct_standard(&left, &right).unwrap(),
            native_standard(&left, &right).unwrap()
        );
    }

    #[test]
    fn direct_generation_keeps_native_delta_depth_errors() {
        let options = JsonPatchOptions {
            factorize: false,
            rationalize: false,
            tests: false,
        };
        for depth in 124..=129 {
            let wrap = |value: Value| (0..depth).fold(value, |value, _| json!({"a":value}));
            let deep = wrap(json!(1));
            for (left, right) in [
                (deep.clone(), wrap(json!(2))),
                (json!({}), json!({"added":deep})),
                (wrap(json!(1)), json!(null)),
                (wrap(json!(1)), wrap(json!(1))),
            ] {
                assert_eq!(
                    DiffPatcher::default().diff_json_patch(&left, &right, &options),
                    native_standard(&left, &right)
                );
            }
        }
    }

    #[test]
    fn positional_reorders_keep_native_delta_depth_errors() {
        let options = JsonPatchOptions {
            factorize: false,
            rationalize: false,
            tests: false,
        };
        for depth in 124..=129 {
            let wrap = |value: Value| (0..depth).fold(value, |value, _| json!({"a":value}));
            let left = wrap(json!((0..16).collect::<Vec<_>>()));
            let right = wrap(json!((0..16).rev().collect::<Vec<_>>()));
            let expected = native_standard(&left, &right);
            let actual = DiffPatcher::default().diff_json_patch(&left, &right, &options);
            assert_eq!(
                actual.as_ref().err(),
                expected.as_ref().err(),
                "depth {depth}"
            );
            if let Ok(patch) = actual {
                let mut applied = left.clone();
                json_patch::patch(&mut applied, &patch).unwrap();
                assert_eq!(applied, right);
            }
        }
    }

    #[test]
    #[cfg(feature = "exact-numbers")]
    fn positional_reorders_keep_unchecked_number_behavior() {
        for raw in ["-0", "1E5", "01", "not-a-number"] {
            let mut source: Vec<Value> = (0..16).map(|i| json!(i)).collect();
            source[15] = Value::Number(serde_json::Number::from_string_unchecked(raw.into()));
            let target: Vec<_> = source.iter().rev().cloned().collect();
            let left = Value::Array(source);
            let right = Value::Array(target);
            for include_value_on_move in [false, true] {
                let matching = DiffOptions {
                    text_diff_min_length: None,
                    include_value_on_move,
                    ..Default::default()
                };
                let options = JsonPatchOptions {
                    factorize: false,
                    rationalize: false,
                    tests: false,
                };
                let expected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    native_optimized(&matching, &left, &right, &options)
                }));
                let actual = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    DiffPatcher::new(matching).diff_json_patch(&left, &right, &options)
                }));
                match (expected, actual) {
                    (Ok(expected), Ok(actual)) => assert_eq!(actual, expected, "{raw}"),
                    (Err(_), Err(_)) => {}
                    _ => panic!("unchecked Number behavior changed: {raw}"),
                }
            }
        }
    }
}