1
//! JSON parsing module for C API
2
//!
3
//! Re-exports the data types and serde_json implementations from `azul_core::json`.
4
//! Adds RefAny serialization support on top, including C API wrapper functions
5
//! (`refany_serialize_to_json`, `json_deserialize_to_refany`) and function pointer
6
//! types (`RefAnySerializeFnType`, `RefAnyDeserializeFnType`).
7

            
8
// Re-export all data types and methods from core
9
use alloc::string::String;
10

            
11
pub use azul_core::json::*;
12
use azul_css::AzString;
13

            
14
// ============================================================================
15
// Public API Functions
16
// ============================================================================
17

            
18
/// Parse a JSON string
19
#[cfg(feature = "json")]
20
#[must_use]
21
pub fn json_parse(s: &str) -> Result<Json, JsonParseError> {
22
    Json::parse(s)
23
}
24

            
25
/// Serialize JSON to string
26
#[cfg(feature = "json")]
27
#[must_use] 
28
pub fn json_stringify(json: &Json) -> AzString {
29
    json.to_json_string()
30
}
31

            
32
// ============================================================================
33
// RefAny JSON Serialization Support
34
// ============================================================================
35

            
36
use azul_core::refany::RefAny;
37

            
38
/// Result type for `RefAny` deserialization
39
#[derive(Debug, Clone)]
40
#[repr(C, u8)]
41
pub enum ResultRefAnyString {
42
    /// Successfully deserialized `RefAny`
43
    Ok(RefAny),
44
    /// Error message describing the failure
45
    Err(AzString),
46
}
47

            
48
impl ResultRefAnyString {
49
    /// Returns `true` if this is the `Ok` variant.
50
    #[must_use] 
51
    pub const fn is_ok(&self) -> bool {
52
        matches!(self, Self::Ok(_))
53
    }
54

            
55
    /// Returns `true` if this is the `Err` variant.
56
    #[must_use] 
57
    pub const fn is_err(&self) -> bool {
58
        matches!(self, Self::Err(_))
59
    }
60

            
61
    /// Converts into `Option<RefAny>`, discarding any error.
62
    #[must_use] 
63
    pub fn ok(self) -> Option<RefAny> {
64
        match self {
65
            Self::Ok(r) => Some(r),
66
            Self::Err(_) => None,
67
        }
68
    }
69

            
70
    /// Converts into `Option<AzString>`, discarding any success value.
71
    #[must_use] 
72
    pub fn err(self) -> Option<AzString> {
73
        match self {
74
            Self::Ok(_) => None,
75
            Self::Err(e) => Some(e),
76
        }
77
    }
78
}
79

            
80
/// C-compatible function type for serializing a `RefAny`'s contents to JSON.
81
pub type RefAnySerializeFnType = extern "C" fn(RefAny) -> Json;
82

            
83
/// C-compatible function type for deserializing JSON into a new `RefAny`.
84
pub type RefAnyDeserializeFnType = extern "C" fn(Json) -> ResultRefAnyString;
85

            
86
/// Serialize a `RefAny` to JSON using its registered serialize function.
87
#[cfg(feature = "json")]
88
#[must_use]
89
pub fn serialize_refany_to_json(refany: &RefAny) -> Option<Json> {
90
    let serialize_fn = refany.get_serialize_fn();
91
    if serialize_fn == 0 {
92
        return None;
93
    }
94

            
95
    // Safety: `serialize_fn` is a valid `extern "C" fn(RefAny) -> Json` pointer,
96
    // set via `RefAny::set_serialize_fn`. The `!= 0` check above guards against null.
97
    let func: RefAnySerializeFnType = unsafe { core::mem::transmute(serialize_fn) };
98
    let json = func(refany.clone());
99

            
100
    if json.is_null() {
101
        None
102
    } else {
103
        Some(json)
104
    }
105
}
106

            
107
/// Deserialize JSON into a `RefAny` using the provided deserialize function.
108
#[cfg(feature = "json")]
109
#[must_use]
110
pub fn deserialize_refany_from_json(json: Json, deserialize_fn: usize) -> Result<RefAny, String> {
111
    if deserialize_fn == 0 {
112
        return Err("Type does not support JSON deserialization".to_string());
113
    }
114

            
115
    // Safety: `deserialize_fn` is a valid `extern "C" fn(Json) -> ResultRefAnyString` pointer,
116
    // set via `RefAny::set_deserialize_fn`. The `== 0` check above guards against null.
117
    let func: RefAnyDeserializeFnType = unsafe { core::mem::transmute(deserialize_fn) };
118

            
119
    match func(json) {
120
        ResultRefAnyString::Ok(refany) => Ok(refany),
121
        ResultRefAnyString::Err(msg) => Err(msg.as_str().to_string()),
122
    }
123
}
124

            
125
impl From<Result<RefAny, String>> for ResultRefAnyString {
126
    fn from(result: Result<RefAny, String>) -> Self {
127
        match result {
128
            Ok(refany) => Self::Ok(refany),
129
            Err(msg) => Self::Err(AzString::from(msg)),
130
        }
131
    }
132
}
133

            
134
/// Serialize a `RefAny` to JSON, returns `OptionJson::None` if not supported or fails.
135
#[cfg(feature = "json")]
136
#[must_use] 
137
pub fn refany_serialize_to_json(refany: &RefAny) -> OptionJson {
138
    match serialize_refany_to_json(refany) {
139
        Some(json) => OptionJson::Some(json),
140
        None => OptionJson::None,
141
    }
142
}
143

            
144
/// Deserialize JSON into a `RefAny` using the provided deserialize function.
145
#[cfg(feature = "json")]
146
#[must_use] 
147
pub fn json_deserialize_to_refany(json: Json, deserialize_fn: usize) -> ResultRefAnyString {
148
    deserialize_refany_from_json(json, deserialize_fn).into()
149
}
150

            
151
/// Restores `state`'s contents in-place from `json`, using its registered
152
/// deserialize fn, and **preserves the live serialize/deserialize/update hooks**
153
/// across the swap (`replace_contents` copies them from the freshly-deserialized
154
/// value, which a non-`AZ_REFLECT`-upcast deserialize would leave unset). Returns
155
/// `Err` with a reason if `state` has no deserialize fn, the JSON can't be
156
/// deserialized, or the swap fails (active borrows).
157
///
158
/// Shared by [`RefAnyUndoManager`] and the `AZ_DEBUG` server's `set_app_state` /
159
/// `restore_snapshot` so both round-trip identically.
160
#[cfg(feature = "json")]
161
pub fn restore_refany_from_json(state: &mut RefAny, json: Json) -> Result<(), String> {
162
    let deser_fn = state.get_deserialize_fn();
163
    if deser_fn == 0 {
164
        return Err("state has no deserialize fn (AZ_REFLECT_JSON not registered)".to_string());
165
    }
166
    let restored = deserialize_refany_from_json(json, deser_fn)?;
167
    let ser_fn = state.get_serialize_fn();
168
    let upd_fn = state.get_update_fn();
169
    let ok = state.replace_contents(restored);
170
    state.set_serialize_fn(ser_fn);
171
    state.set_deserialize_fn(deser_fn);
172
    state.set_update_fn(upd_fn);
173
    if ok {
174
        Ok(())
175
    } else {
176
        Err("replace_contents failed (active borrows exist)".to_string())
177
    }
178
}
179

            
180
// ============================================================================
181
// Generic application-state undo/redo ("mini-git" with reversible JSON diffs)
182
// ============================================================================
183

            
184
/// Reversible JSON diffing for the undo history. A diff is a flat list of leaf
185
/// changes keyed by RFC-6901 JSON Pointer: objects diff per-key (recursively),
186
/// while scalars / arrays / type-changes are whole-value leaf replacements.
187
/// Each change records both `old` and `new`, so a diff applies forwards (redo)
188
/// or backwards (undo).
189
#[cfg(feature = "json")]
190
mod jsondiff {
191
    use alloc::{format, string::String, vec::Vec};
192

            
193
    use serde_json::Value;
194

            
195
    /// One reversible change at a JSON Pointer path. `old`/`new` are `None` when
196
    /// the key is absent on that side (key added / removed).
197
    #[derive(Debug, Clone)]
198
    pub(super) struct Change {
199
        pub path: String,
200
        pub old: Option<Value>,
201
        pub new: Option<Value>,
202
    }
203

            
204
    /// Computes a reversible diff `old → new`.
205
    pub(super) fn diff(old: &Value, new: &Value) -> Vec<Change> {
206
        let mut out = Vec::new();
207
        diff_rec(old, new, String::new(), &mut out);
208
        out
209
    }
210

            
211
    fn diff_rec(old: &Value, new: &Value, path: String, out: &mut Vec<Change>) {
212
        if old == new {
213
            return;
214
        }
215
        if let (Value::Object(o), Value::Object(n)) = (old, new) {
216
            for (k, ov) in o {
217
                let child = format!("{}/{}", path, esc(k));
218
                match n.get(k) {
219
                    Some(nv) => diff_rec(ov, nv, child, out),
220
                    None => out.push(Change {
221
                        path: child,
222
                        old: Some(ov.clone()),
223
                        new: None,
224
                    }),
225
                }
226
            }
227
            for (k, nv) in n {
228
                if !o.contains_key(k) {
229
                    out.push(Change {
230
                        path: format!("{}/{}", path, esc(k)),
231
                        old: None,
232
                        new: Some(nv.clone()),
233
                    });
234
                }
235
            }
236
        } else {
237
            out.push(Change {
238
                path,
239
                old: Some(old.clone()),
240
                new: Some(new.clone()),
241
            });
242
        }
243
    }
244

            
245
    /// Applies a diff to `base`. `forward = true` moves `old → new` (redo);
246
    /// `forward = false` moves `new → old` (undo).
247
    pub(super) fn apply(base: &Value, diff: &[Change], forward: bool) -> Value {
248
        let mut v = base.clone();
249
        for ch in diff {
250
            let target = if forward { &ch.new } else { &ch.old };
251
            set_at(&mut v, &ch.path, target.as_ref());
252
        }
253
        v
254
    }
255

            
256
    fn set_at(root: &mut Value, path: &str, val: Option<&Value>) {
257
        if path.is_empty() {
258
            if let Some(v) = val {
259
                *root = v.clone();
260
            }
261
            return;
262
        }
263
        let split = path.rfind('/').unwrap_or(0);
264
        let parent_ptr = &path[..split];
265
        let last = unesc(&path[split + 1..]);
266
        let parent = if parent_ptr.is_empty() {
267
            root
268
        } else {
269
            match root.pointer_mut(parent_ptr) {
270
                Some(p) => p,
271
                None => return,
272
            }
273
        };
274
        if let Some(obj) = parent.as_object_mut() {
275
            match val {
276
                Some(v) => {
277
                    obj.insert(last, v.clone());
278
                }
279
                None => {
280
                    obj.remove(&last);
281
                }
282
            }
283
        }
284
    }
285

            
286
    fn esc(k: &str) -> String {
287
        k.replace('~', "~0").replace('/', "~1")
288
    }
289
    fn unesc(s: &str) -> String {
290
        s.replace("~1", "/").replace("~0", "~")
291
    }
292
}
293

            
294
/// A generic application-state undo/redo history — a "mini-git" for the app's
295
/// state `RefAny`, storing reversible **JSON diffs** between commits rather than
296
/// full snapshots (memory-efficient for large models like a text document).
297
///
298
/// Workflow: [`commit`](Self::commit) the current state at action / auto-save
299
/// boundaries (e.g. from a timer callback, or driven by the `RefAny` `update_fn`
300
/// hook marking the state dirty), then [`undo`](Self::undo) / [`redo`](Self::redo)
301
/// walk the history. Like git, committing a new state *after* an undo discards
302
/// the now-orphaned redo branch. Requires the state's JSON (de)serialize fns
303
/// (`AZ_REFLECT_JSON`); all ops are no-ops returning `false` otherwise.
304
///
305
/// Wired into `CallbackInfo` (`commit_undo_snapshot` / `undo` / `redo`) so a
306
/// callback — including a timer callback — can manage history on the app model.
307
#[cfg(feature = "json")]
308
#[derive(Debug, Clone, Default)]
309
pub struct RefAnyUndoManager {
310
    /// The last committed state (serde value): the base the next diff is computed
311
    /// against and that undo/redo diffs are applied to. `None` until first commit.
312
    head: Option<serde_json::Value>,
313
    /// Reversible diffs, each from commit N-1 → N (top = most recent).
314
    undo_diffs: Vec<Vec<jsondiff::Change>>,
315
    /// Diffs of undone commits, available to redo.
316
    redo_diffs: Vec<Vec<jsondiff::Change>>,
317
    /// Maximum number of undo diffs retained (`0` = unlimited).
318
    capacity: usize,
319
}
320

            
321
#[cfg(feature = "json")]
322
impl RefAnyUndoManager {
323
    /// Creates a history with a maximum depth (`0` = unlimited).
324
    #[must_use] 
325
66
    pub const fn new(capacity: usize) -> Self {
326
66
        Self {
327
66
            head: None,
328
66
            undo_diffs: Vec::new(),
329
66
            redo_diffs: Vec::new(),
330
66
            capacity,
331
66
        }
332
66
    }
333

            
334
    /// Commits `state` as a new history point, recording the reversible diff from
335
    /// the previous commit. The first commit just seeds the base. A commit that
336
    /// changed something discards the redo branch (git-like). Returns `true` if a
337
    /// commit was recorded (JSON supported and, after the first, state changed).
338
    pub fn commit(&mut self, state: &RefAny) -> bool {
339
        let cur = match serialize_refany_to_json(state) {
340
            Some(j) => j.to_serde_value(),
341
            None => return false,
342
        };
343
        match self.head.take() {
344
            None => {
345
                self.head = Some(cur); // seed base, no diff yet
346
                true
347
            }
348
            Some(prev) => {
349
                let d = jsondiff::diff(&prev, &cur);
350
                if d.is_empty() {
351
                    self.head = Some(prev);
352
                    return false; // nothing changed
353
                }
354
                self.undo_diffs.push(d);
355
                self.redo_diffs.clear(); // new commit orphans the redo branch
356
                if self.capacity != 0 && self.undo_diffs.len() > self.capacity {
357
                    self.undo_diffs.remove(0);
358
                }
359
                self.head = Some(cur);
360
                true
361
            }
362
        }
363
    }
364

            
365
    /// True if there is a commit to undo.
366
    #[must_use] 
367
    pub const fn can_undo(&self) -> bool {
368
        !self.undo_diffs.is_empty()
369
    }
370

            
371
    /// True if there is an undone commit to redo.
372
    #[must_use] 
373
    pub const fn can_redo(&self) -> bool {
374
        !self.redo_diffs.is_empty()
375
    }
376

            
377
    /// Reverts the most recent commit, restoring the previous state into `state`.
378
    pub fn undo(&mut self, state: &mut RefAny) -> bool {
379
        let Some(d) = self.undo_diffs.pop() else { return false };
380
        let Some(head) = self.head.take() else { return false };
381
        let reverted = jsondiff::apply(&head, &d, false);
382
        let ok = Self::restore(state, &reverted);
383
        self.head = Some(reverted);
384
        self.redo_diffs.push(d);
385
        ok
386
    }
387

            
388
    /// Re-applies the most recently undone commit.
389
    pub fn redo(&mut self, state: &mut RefAny) -> bool {
390
        let Some(d) = self.redo_diffs.pop() else { return false };
391
        let Some(head) = self.head.take() else { return false };
392
        let applied = jsondiff::apply(&head, &d, true);
393
        let ok = Self::restore(state, &applied);
394
        self.head = Some(applied);
395
        self.undo_diffs.push(d);
396
        ok
397
    }
398

            
399
    /// Drops all recorded history.
400
    pub fn clear(&mut self) {
401
        self.head = None;
402
        self.undo_diffs.clear();
403
        self.redo_diffs.clear();
404
    }
405

            
406
    fn restore(state: &mut RefAny, value: &serde_json::Value) -> bool {
407
        restore_refany_from_json(state, Json::from_serde_value(value.clone())).is_ok()
408
    }
409
}
410

            
411
// ============================================================================
412
// Tests
413
// ============================================================================
414

            
415
#[cfg(test)]
416
mod tests {
417
    use super::*;
418

            
419
    #[test]
420
    #[cfg(feature = "json")]
421
    fn test_parse_null() {
422
        let json = Json::parse("null").unwrap();
423
        assert!(json.is_null());
424
    }
425

            
426
    #[test]
427
    #[cfg(feature = "json")]
428
    fn test_parse_bool() {
429
        let json_true = Json::parse("true").unwrap();
430
        assert_eq!(json_true.as_bool().into_option(), Some(true));
431

            
432
        let json_false = Json::parse("false").unwrap();
433
        assert_eq!(json_false.as_bool().into_option(), Some(false));
434
    }
435

            
436
    #[test]
437
    #[cfg(feature = "json")]
438
    fn test_parse_number() {
439
        let json = Json::parse("42.5").unwrap();
440
        assert_eq!(json.as_number().into_option(), Some(42.5));
441

            
442
        let json_int = Json::parse("100").unwrap();
443
        assert_eq!(json_int.as_i64().into_option(), Some(100));
444
    }
445

            
446
    #[test]
447
    #[cfg(feature = "json")]
448
    fn test_parse_string() {
449
        let json = Json::parse("\"hello world\"").unwrap();
450
        assert_eq!(
451
            json.as_string().into_option().unwrap().as_str(),
452
            "hello world"
453
        );
454
    }
455

            
456
    #[test]
457
    #[cfg(feature = "json")]
458
    fn test_parse_array() {
459
        let json = Json::parse("[1, 2, 3]").unwrap();
460
        assert!(json.is_array());
461
        assert_eq!(json.len(), 3);
462

            
463
        let first = json.get_index(0).unwrap();
464
        assert_eq!(first.as_number().into_option(), Some(1.0));
465
    }
466

            
467
    #[test]
468
    #[cfg(feature = "json")]
469
    fn test_parse_object() {
470
        let json = Json::parse(r#"{"name": "test", "value": 42}"#).unwrap();
471
        assert!(json.is_object());
472
        assert_eq!(json.len(), 2);
473

            
474
        let name = json.get_key("name").unwrap();
475
        assert_eq!(name.as_string().into_option().unwrap().as_str(), "test");
476

            
477
        let value = json.get_key("value").unwrap();
478
        assert_eq!(value.as_number().into_option(), Some(42.0));
479
    }
480

            
481
    #[test]
482
    #[cfg(feature = "json")]
483
    fn test_nested() {
484
        let json = Json::parse(r#"{"items": [1, 2, {"nested": true}]}"#).unwrap();
485

            
486
        let items = json.get_key("items").unwrap();
487
        assert!(items.is_array());
488

            
489
        let nested_obj = items.get_index(2).unwrap();
490
        let nested = nested_obj.get_key("nested").unwrap();
491
        assert_eq!(nested.as_bool().into_option(), Some(true));
492
    }
493

            
494
    #[test]
495
    #[cfg(feature = "json")]
496
    fn test_roundtrip_serde_parity() {
497
        // A nested value round-trips through pretty-print + re-parse unchanged —
498
        // exercises the AzJson <-> serde_json bridge in both directions.
499
        let src = r#"{"a":1,"b":[true,null,"x"],"c":{"d":2.5}}"#;
500
        let json = Json::parse(src).unwrap();
501
        let reparsed = Json::parse(json.to_string_pretty().as_str()).unwrap();
502
        assert_eq!(json, reparsed);
503
    }
504

            
505
    #[test]
506
    #[cfg(feature = "json")]
507
    fn test_undo_manager_roundtrip() {
508
        use azul_core::refany::RefAny;
509

            
510
        extern "C" fn ser(mut r: RefAny) -> Json {
511
            match r.downcast_ref::<i64>() {
512
                Some(v) => Json::integer(*v),
513
                None => Json::null(),
514
            }
515
        }
516
        extern "C" fn deser(j: Json) -> ResultRefAnyString {
517
            match j.as_i64().into_option() {
518
                Some(v) => Ok(RefAny::new(v)),
519
                None => Err("not an i64".to_string()),
520
            }
521
            .into()
522
        }
523

            
524
        let mut state = RefAny::new(10i64);
525
        state.set_serialize_fn(ser as usize);
526
        state.set_deserialize_fn(deser as usize);
527

            
528
        let mut undo = RefAnyUndoManager::new(0);
529
        undo.commit(&state); // commit 10 (seeds base)
530
        if let Some(mut v) = state.downcast_mut::<i64>() {
531
            *v = 20;
532
        }
533
        undo.commit(&state); // commit 20
534
        if let Some(mut v) = state.downcast_mut::<i64>() {
535
            *v = 30;
536
        }
537
        undo.commit(&state); // commit 30
538

            
539
        assert!(undo.can_undo());
540
        assert!(undo.undo(&mut state));
541
        assert_eq!(*state.downcast_ref::<i64>().unwrap(), 20);
542
        assert!(undo.undo(&mut state));
543
        assert_eq!(*state.downcast_ref::<i64>().unwrap(), 10);
544
        assert!(undo.redo(&mut state));
545
        assert_eq!(*state.downcast_ref::<i64>().unwrap(), 20);
546

            
547
        // mini-git branching: a new commit after an undo discards the orphaned
548
        // redo branch ("do a -> undo -> do b clears a").
549
        assert!(undo.can_redo()); // 30 is still redoable here
550
        if let Some(mut v) = state.downcast_mut::<i64>() {
551
            *v = 99;
552
        }
553
        undo.commit(&state); // branch from 20 -> 99
554
        assert!(!undo.can_redo()); // the 30 branch is gone
555
        assert!(undo.undo(&mut state));
556
        assert_eq!(*state.downcast_ref::<i64>().unwrap(), 20);
557
    }
558

            
559
    #[test]
560
    #[cfg(feature = "json")]
561
    fn test_json_diff_apply_reversible() {
562
        // A word-editor-like model: text + cursor + nested meta. The reversible
563
        // diff is the heart of the mini-git history, so it must round-trip both
564
        // directions.
565
        let a = Json::parse(r#"{"text":"hello","cursor":0,"meta":{"saved":true}}"#)
566
            .unwrap()
567
            .to_serde_value();
568
        let b = Json::parse(
569
            r#"{"text":"hello world","cursor":11,"meta":{"saved":false},"tags":[1,2]}"#,
570
        )
571
        .unwrap()
572
        .to_serde_value();
573
        let d = super::jsondiff::diff(&a, &b);
574
        assert!(!d.is_empty());
575
        assert_eq!(super::jsondiff::apply(&a, &d, true), b); // forward: a -> b
576
        assert_eq!(super::jsondiff::apply(&b, &d, false), a); // backward: b -> a
577
        assert!(super::jsondiff::diff(&a, &a).is_empty()); // unchanged -> empty diff
578
    }
579

            
580
    #[test]
581
    #[cfg(feature = "json")]
582
    fn test_parse_error() {
583
        let result = Json::parse("{ invalid }");
584
        assert!(result.is_err());
585

            
586
        let err = result.unwrap_err();
587
        assert!(err.line > 0);
588
    }
589
}
590

            
591
// ============================================================================
592
// Adversarial tests (autotest)
593
// ============================================================================
594

            
595
/// Adversarial coverage for this module. The whole file is already behind
596
/// `#[cfg(feature = "json")]` (see `lib.rs`), so no per-test feature gate is
597
/// needed here.
598
///
599
/// Deliberately NOT tested: passing a non-zero *bogus* `usize` as a
600
/// `deserialize_fn`. `deserialize_refany_from_json` transmutes it to a function
601
/// pointer and calls it, so any value other than `0` or a real
602
/// `extern "C" fn(Json) -> ResultRefAnyString` is UB by contract, not a case the
603
/// function can defend against.
604
#[cfg(test)]
605
mod autotest_generated {
606
    use super::*;
607

            
608
    // ------------------------------------------------------------------
609
    // Fixtures
610
    // ------------------------------------------------------------------
611

            
612
    /// The canonical AZ_REFLECT_JSON pair for an `i64` state.
613
    extern "C" fn ser_i64(mut r: RefAny) -> Json {
614
        match r.downcast_ref::<i64>() {
615
            Some(v) => Json::integer(*v),
616
            None => Json::null(),
617
        }
618
    }
619

            
620
    /// Rejects anything that is not an exactly-representable `i64`.
621
    extern "C" fn deser_i64(j: Json) -> ResultRefAnyString {
622
        match j.as_i64().into_option() {
623
            Some(v) => ResultRefAnyString::Ok(RefAny::new(v)),
624
            None => ResultRefAnyString::Err(AzString::from("not an i64".to_string())),
625
        }
626
    }
627

            
628
    /// A serializer that always yields JSON `null` — i.e. "no JSON form".
629
    extern "C" fn ser_null(_r: RefAny) -> Json {
630
        Json::null()
631
    }
632

            
633
    /// A deserializer that always fails.
634
    extern "C" fn deser_always_err(_j: Json) -> ResultRefAnyString {
635
        ResultRefAnyString::Err(AzString::from("always fails".to_string()))
636
    }
637

            
638
    /// An object-shaped state whose JSON key is hostile to JSON Pointer syntax
639
    /// (contains both `/` and `~`), so the diff path must be escaped/unescaped.
640
    #[derive(Debug, Clone, PartialEq)]
641
    struct Doc {
642
        text: String,
643
        cursor: i64,
644
    }
645

            
646
    extern "C" fn ser_doc(mut r: RefAny) -> Json {
647
        let (text, cursor) = match r.downcast_ref::<Doc>() {
648
            Some(d) => (d.text.clone(), d.cursor),
649
            None => return Json::null(),
650
        };
651
        Json::object(JsonKeyValueVec::from_vec(vec![
652
            JsonKeyValue::create(AzString::from("a/b~c".to_string()), Json::string(text)),
653
            JsonKeyValue::create(AzString::from("cursor".to_string()), Json::integer(cursor)),
654
        ]))
655
    }
656

            
657
    extern "C" fn deser_doc(j: Json) -> ResultRefAnyString {
658
        let text = match j.get_key("a/b~c").and_then(|t| t.as_string().into_option()) {
659
            Some(s) => s.as_str().to_string(),
660
            None => return ResultRefAnyString::Err(AzString::from("missing text".to_string())),
661
        };
662
        let cursor = match j.get_key("cursor").and_then(|c| c.as_i64().into_option()) {
663
            Some(c) => c,
664
            None => return ResultRefAnyString::Err(AzString::from("missing cursor".to_string())),
665
        };
666
        ResultRefAnyString::Ok(RefAny::new(Doc { text, cursor }))
667
    }
668

            
669
    fn state_i64(v: i64) -> RefAny {
670
        let mut s = RefAny::new(v);
671
        s.set_serialize_fn(ser_i64 as usize);
672
        s.set_deserialize_fn(deser_i64 as usize);
673
        s
674
    }
675

            
676
    fn read_i64(s: &mut RefAny) -> i64 {
677
        let g = s.downcast_ref::<i64>().expect("state holds an i64");
678
        *g
679
    }
680

            
681
    fn write_i64(s: &mut RefAny, v: i64) {
682
        let mut g = s.downcast_mut::<i64>().expect("state holds an i64");
683
        *g = v;
684
    }
685

            
686
    // ------------------------------------------------------------------
687
    // json_parse — parser: malformed / huge / boundary / unicode
688
    // ------------------------------------------------------------------
689

            
690
    #[test]
691
    fn json_parse_empty_and_whitespace_only_is_err() {
692
        for src in ["", " ", "   ", "\t\n\r ", "\u{feff}"] {
693
            let r = json_parse(src);
694
            assert!(r.is_err(), "{src:?} must be rejected, got {r:?}");
695
        }
696
    }
697

            
698
    #[test]
699
    fn json_parse_garbage_is_err_and_never_panics() {
700
        for src in [
701
            "{ invalid }",
702
            "]]]",
703
            "}{",
704
            "nul",
705
            "tru",
706
            "'single quoted'",
707
            "{\"a\":1,}",
708
            "[1,2,]",
709
            "{a:1}",
710
            "\u{0}\u{1}\u{2}",
711
            "\\",
712
            "\"unterminated",
713
            "01",
714
            "--1",
715
            "[,]",
716
            "{\"a\"}",
717
            "{\"a\":}",
718
        ] {
719
            let r = json_parse(src);
720
            assert!(r.is_err(), "{src:?} must be rejected, got {r:?}");
721
        }
722
    }
723

            
724
    #[test]
725
    fn json_parse_leading_trailing_junk_is_deterministic() {
726
        // Surrounding whitespace is fine ...
727
        let ok = json_parse("  \n\t{\"a\":1}  \n").expect("whitespace-padded JSON parses");
728
        assert!(ok.is_object());
729
        assert_eq!(ok.len(), 1);
730

            
731
        // ... trailing non-whitespace is not.
732
        for src in [
733
            "{\"a\":1};garbage",
734
            "[1,2,3]extra",
735
            "null null",
736
            "1 2",
737
            "\"a\"\"b\"",
738
        ] {
739
            assert!(json_parse(src).is_err(), "{src:?} must be rejected");
740
        }
741
    }
742

            
743
    #[test]
744
    fn json_parse_deeply_nested_is_rejected_without_stack_overflow() {
745
        // serde_json's default recursion limit (128) must turn this into an
746
        // `Err` rather than blowing the stack.
747
        let deep_arrays = format!("{}{}", "[".repeat(10_000), "]".repeat(10_000));
748
        assert!(
749
            json_parse(&deep_arrays).is_err(),
750
            "10k-deep arrays must be rejected"
751
        );
752

            
753
        let deep_objects = format!("{}1{}", "{\"a\":".repeat(10_000), "}".repeat(10_000));
754
        assert!(
755
            json_parse(&deep_objects).is_err(),
756
            "10k-deep objects must be rejected"
757
        );
758

            
759
        // Unbalanced garbage of the same shape: still an error, still no crash.
760
        assert!(json_parse(&"[".repeat(1_000_000)).is_err());
761

            
762
        // Positive control: a nesting depth inside the limit still parses.
763
        let shallow = format!("{}1{}", "[".repeat(64), "]".repeat(64));
764
        assert!(json_parse(&shallow).expect("64-deep parses").is_array());
765
    }
766

            
767
    #[test]
768
    fn json_parse_extremely_long_input_does_not_panic_or_hang() {
769
        // 1M-char string payload.
770
        let long = "a".repeat(1_000_000);
771
        let j = json_parse(&format!("\"{long}\"")).expect("1M-char string parses");
772
        assert_eq!(
773
            j.as_string().into_option().expect("string").as_str().len(),
774
            1_000_000
775
        );
776

            
777
        // 50k-element array (each `len()` call re-parses the payload).
778
        let arr_src = format!("[{}]", vec!["0"; 50_000].join(","));
779
        let arr = json_parse(&arr_src).expect("50k-element array parses");
780
        assert!(arr.is_array());
781
        assert_eq!(arr.len(), 50_000);
782
        assert_eq!(
783
            arr.get_index(49_999).expect("last").as_i64().into_option(),
784
            Some(0)
785
        );
786
        assert!(
787
            arr.get_index(50_000).is_none(),
788
            "out-of-range index must be None"
789
        );
790
        assert!(
791
            arr.get_index(usize::MAX).is_none(),
792
            "usize::MAX index must be None"
793
        );
794
    }
795

            
796
    #[test]
797
    fn json_parse_boundary_numbers() {
798
        assert_eq!(json_parse("0").expect("0").as_i64().into_option(), Some(0));
799

            
800
        // "-0": the sign of zero is not preserved through the f64 store.
801
        let neg_zero = json_parse("-0").expect("-0");
802
        assert_eq!(neg_zero.as_number().into_option(), Some(0.0));
803
        assert_eq!(json_stringify(&neg_zero).as_str(), "0");
804

            
805
        // i64::MIN is exactly -2^63 in f64, so it round-trips.
806
        let min = json_parse(&i64::MIN.to_string()).expect("i64::MIN");
807
        assert_eq!(min.as_i64().into_option(), Some(i64::MIN));
808

            
809
        // i64::MAX is NOT exactly representable — f64 rounds it up to 2^63.
810
        // `as_i64` must refuse it (None) rather than wrap around to i64::MIN.
811
        let max = json_parse(&i64::MAX.to_string()).expect("i64::MAX");
812
        assert_eq!(max.as_number().into_option(), Some(i64::MAX as f64));
813
        assert_eq!(max.as_i64().into_option(), None);
814

            
815
        // u64::MAX is far out of i64 range: None, never a wrapped negative.
816
        let umax = json_parse(&u64::MAX.to_string()).expect("u64::MAX");
817
        assert_eq!(umax.as_i64().into_option(), None);
818
        assert!(umax.as_number().into_option().expect("number") > 0.0);
819

            
820
        // Smallest subnormal and largest finite double stay finite and typed.
821
        let tiny = json_parse("5e-324").expect("subnormal");
822
        let t = tiny.as_number().into_option().expect("number");
823
        assert!(t > 0.0 && t.is_finite(), "subnormal decoded to {t}");
824
        let big = json_parse("1.7976931348623157e308").expect("f64::MAX");
825
        assert!(big.as_number().into_option().expect("number").is_finite());
826

            
827
        // Non-integral numbers are numbers, but never integers.
828
        let frac = json_parse("0.5").expect("0.5");
829
        assert_eq!(frac.as_number().into_option(), Some(0.5));
830
        assert_eq!(frac.as_i64().into_option(), None);
831
    }
832

            
833
    #[test]
834
    fn json_parse_rejects_non_json_number_literals() {
835
        for src in [
836
            "NaN",
837
            "nan",
838
            "Infinity",
839
            "-Infinity",
840
            "inf",
841
            "-inf",
842
            "+1",
843
            ".5",
844
            "5.",
845
            "1e",
846
            "1e+",
847
            "0x10",
848
            "1_000",
849
            "1,0",
850
        ] {
851
            assert!(json_parse(src).is_err(), "{src:?} is not valid JSON");
852
        }
853
    }
854

            
855
    #[test]
856
    fn json_parse_huge_magnitude_numbers_do_not_panic() {
857
        let nines = "9".repeat(400);
858
        for src in ["1e309", "-1e309", "1e-400", nines.as_str()] {
859
            match json_parse(src) {
860
                Err(_) => {} // rejecting is fine
861
                Ok(j) => {
862
                    // Whatever it decodes to, it is never a NaN and always
863
                    // stringifies without panicking.
864
                    if let Some(n) = j.as_number().into_option() {
865
                        assert!(!n.is_nan(), "{src:?} decoded to NaN");
866
                    }
867
                    assert!(!json_stringify(&j).as_str().is_empty());
868
                }
869
            }
870
        }
871
    }
872

            
873
    #[test]
874
    fn json_parse_unicode_payloads() {
875
        // Astral-plane emoji.
876
        let emoji = json_parse("\"\u{1F600}\"").expect("emoji");
877
        assert_eq!(
878
            emoji.as_string().into_option().expect("string").as_str(),
879
            "\u{1F600}"
880
        );
881

            
882
        // Combining marks in a key, bidi override + ZWJ in a value.
883
        let obj = json_parse("{\"e\u{301}\":\"\u{202E}abc\u{200D}\u{1F468}\"}")
884
            .expect("combining / bidi payload");
885
        assert!(obj.is_object());
886
        assert_eq!(obj.len(), 1);
887
        assert!(obj.get_key("e\u{301}").is_some());
888
        assert!(obj.get_key("e").is_none(), "key lookup must not normalize");
889

            
890
        // Escaped NUL survives the round trip.
891
        let nul = json_parse("\"\\u0000\"").expect("escaped NUL");
892
        assert_eq!(
893
            nul.as_string().into_option().expect("string").as_str(),
894
            "\0"
895
        );
896
        assert_eq!(
897
            json_parse(json_stringify(&nul).as_str()).expect("re-parse"),
898
            nul
899
        );
900

            
901
        // Broken escapes / lone surrogates are rejected, not silently replaced.
902
        for src in ["\"\\ud800\"", "\"\\udfff\"", "\"\\x\"", "\"\\u00\""] {
903
            assert!(json_parse(src).is_err(), "{src:?} must be rejected");
904
        }
905
    }
906

            
907
    #[test]
908
    fn json_parse_error_is_reported_with_a_position() {
909
        let e = json_parse("{\n  \"a\": ,\n}").unwrap_err();
910
        assert!(e.line >= 1, "line must be reported");
911
        assert!(!e.message.as_str().is_empty());
912
        // Display impl must not panic on either shape.
913
        assert!(!format!("{e}").is_empty());
914
    }
915

            
916
    // ------------------------------------------------------------------
917
    // json_stringify / round-trip: encode == decode
918
    // ------------------------------------------------------------------
919

            
920
    #[test]
921
    fn json_roundtrip_parse_stringify_parse_is_stable() {
922
        for src in [
923
            "null",
924
            "true",
925
            "false",
926
            "0",
927
            "-1",
928
            "1.5",
929
            "\"\"",
930
            "\"\\n\\t\\\"\\\\\"",
931
            "[]",
932
            "{}",
933
            "[1,2,3]",
934
            "{\"a\":1}",
935
            "{\"a\":[1,{\"b\":null}],\"c\":\"\u{1F600}\"}",
936
            "[[[[[1]]]]]",
937
        ] {
938
            let a = json_parse(src).unwrap_or_else(|e| panic!("{src:?} must parse: {e}"));
939
            let encoded = json_stringify(&a);
940
            let b = json_parse(encoded.as_str())
941
                .unwrap_or_else(|e| panic!("re-parse of {:?} failed: {e}", encoded.as_str()));
942
            assert_eq!(a, b, "value changed across encode -> decode for {src:?}");
943
            assert_eq!(
944
                encoded.as_str(),
945
                json_stringify(&b).as_str(),
946
                "stringify is not idempotent for {src:?}"
947
            );
948
        }
949
    }
950

            
951
    #[test]
952
    fn json_roundtrip_constructed_values() {
953
        for v in [
954
            Json::null(),
955
            Json::bool(true),
956
            Json::bool(false),
957
            Json::integer(0),
958
            Json::integer(-1),
959
            Json::integer(i64::MIN),
960
            // i64::MAX is stored as 2^63 and emitted as such — it still decodes
961
            // back to the identical (lossy) f64, so the round trip is stable.
962
            Json::integer(i64::MAX),
963
            Json::number(1.5),
964
            Json::number(-0.0),
965
            Json::number(1e300),
966
            Json::number(f64::MAX),
967
            Json::number(f64::MIN_POSITIVE),
968
            Json::string(""),
969
            Json::string("quote\" backslash\\ newline\n tab\t"),
970
            Json::string("\u{1F600}e\u{301}\u{0}"),
971
        ] {
972
            let encoded = json_stringify(&v);
973
            let back = json_parse(encoded.as_str())
974
                .unwrap_or_else(|e| panic!("{:?} did not re-parse: {e}", encoded.as_str()));
975
            assert_eq!(
976
                v,
977
                back,
978
                "{:?} did not survive the round trip",
979
                encoded.as_str()
980
            );
981
        }
982
    }
983

            
984
    #[test]
985
    fn json_stringify_non_finite_numbers_does_not_panic() {
986
        // JSON has no representation for NaN / ±Infinity. `to_json_string` falls
987
        // back to Rust's float `Display` ("NaN" / "inf"), which is *not* valid
988
        // JSON, so such a value does not round-trip. Pinned as observed
989
        // behaviour: the hard requirement is only that nothing panics, and that
990
        // the serde bridge maps them to `null` instead of emitting garbage.
991
        for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
992
            let j = Json::number(v);
993
            let encoded = json_stringify(&j);
994
            assert!(!encoded.as_str().is_empty());
995
            let _ = json_parse(encoded.as_str()); // allowed to fail, must not panic
996
            assert!(
997
                j.to_serde_value().is_null(),
998
                "serde bridge must null out {v}"
999
            );
        }
    }
    #[test]
    fn json_with_corrupt_ffi_payload_does_not_panic() {
        // `Json`'s fields are `pub` (C ABI), so a C caller can hand us an
        // Array/Object whose serialized payload is not JSON at all. Every
        // accessor must degrade gracefully rather than panic.
        for value_type in [JsonType::Array, JsonType::Object] {
            let bogus = Json {
                value_type,
                internal: JsonInternal {
                    string_value: AzString::from("not-json".to_string()),
                    number_value: f64::NAN,
                    bool_value: true,
                },
            };
            assert_eq!(bogus.len(), 0);
            assert!(bogus.is_empty());
            assert!(bogus.get_index(0).is_none());
            assert!(bogus.get_key("a").is_none());
            assert!(bogus.keys().is_empty());
            assert!(bogus.to_serde_value().is_null());
            assert!(!json_stringify(&bogus).as_str().is_empty());
            assert!(!bogus.to_string_pretty().as_str().is_empty());
            // Wrong-type accessors stay None instead of reading the wrong union arm.
            assert_eq!(bogus.as_bool().into_option(), None);
            assert_eq!(bogus.as_number().into_option(), None);
            assert_eq!(bogus.as_i64().into_option(), None);
            assert_eq!(bogus.as_string().into_option(), None);
        }
    }
    // ------------------------------------------------------------------
    // ResultRefAnyString — predicates / getters: invariants
    // ------------------------------------------------------------------
    #[test]
    fn result_refany_string_predicates_are_mutually_exclusive() {
        let ok = ResultRefAnyString::Ok(RefAny::new(1i64));
        assert!(ok.is_ok());
        assert!(!ok.is_err());
        // Edge payload: an *empty* error message is still the Err variant.
        let err = ResultRefAnyString::Err(AzString::from(String::new()));
        assert!(err.is_err());
        assert!(!err.is_ok());
        // ok()/err() partition exactly one value into exactly one Option.
        assert!(ok.clone().ok().is_some());
        assert!(ok.clone().err().is_none());
        assert!(err.clone().ok().is_none());
        assert_eq!(err.clone().err().expect("err").as_str(), "");
    }
    #[test]
    fn result_refany_string_err_payload_edges() {
        // Huge multi-byte error message: no truncation, no panic.
        let big = "\u{1F600}".repeat(100_000);
        let e = ResultRefAnyString::Err(AzString::from(big.clone()));
        assert!(e.is_err());
        assert_eq!(e.err().expect("err").as_str().len(), big.len());
    }
    #[test]
    fn result_refany_string_from_result_parity() {
        let ok: Result<RefAny, String> = Ok(RefAny::new(7i64));
        let ok: ResultRefAnyString = ok.into();
        assert!(ok.is_ok() && !ok.is_err());
        let mut inner = ok.ok().expect("ok");
        assert_eq!(read_i64(&mut inner), 7);
        let err: Result<RefAny, String> = Err("boom".to_string());
        let err: ResultRefAnyString = err.into();
        assert!(err.is_err() && !err.is_ok());
        assert_eq!(err.err().expect("err").as_str(), "boom");
    }
    #[test]
    fn result_refany_string_clone_keeps_the_payload_alive() {
        let r = ResultRefAnyString::Ok(RefAny::new(7i64));
        for _ in 0..64 {
            let c = r.clone();
            assert!(c.is_ok());
        }
        // 64 clone/drop cycles later the shared data is intact (no double-free)
        // and no clone leaked a strong reference.
        let mut inner = r.ok().expect("ok");
        assert_eq!(read_i64(&mut inner), 7);
        assert_eq!(inner.get_ref_count(), 1);
    }
    // ------------------------------------------------------------------
    // serialize_refany_to_json / refany_serialize_to_json
    // ------------------------------------------------------------------
    #[test]
    fn serialize_refany_without_hook_is_none() {
        let plain = RefAny::new(5i64);
        assert!(serialize_refany_to_json(&plain).is_none());
        assert!(matches!(refany_serialize_to_json(&plain), OptionJson::None));
    }
    #[test]
    fn serialize_refany_with_hook_agrees_with_the_c_wrapper() {
        let s = state_i64(42);
        let j = serialize_refany_to_json(&s).expect("hook is set");
        assert_eq!(j.as_i64().into_option(), Some(42));
        match refany_serialize_to_json(&s) {
            OptionJson::Some(j2) => assert_eq!(j2, j),
            OptionJson::None => panic!("hook is set, must be Some"),
        }
        // The temporary clone handed to the hook must be released again.
        assert_eq!(s.get_ref_count(), 1);
    }
    #[test]
    fn serialize_refany_null_result_is_treated_as_unsupported() {
        let mut s = RefAny::new(5i64);
        s.set_serialize_fn(ser_null as usize);
        assert!(serialize_refany_to_json(&s).is_none());
        assert!(matches!(refany_serialize_to_json(&s), OptionJson::None));
    }
    // ------------------------------------------------------------------
    // deserialize_refany_from_json / json_deserialize_to_refany — numeric
    // ------------------------------------------------------------------
    #[test]
    fn deserialize_refany_with_zero_fn_pointer_is_err() {
        let e = deserialize_refany_from_json(Json::integer(1), 0).unwrap_err();
        assert_eq!(e, "Type does not support JSON deserialization");
        let r = json_deserialize_to_refany(Json::null(), 0);
        assert!(r.is_err());
        assert_eq!(
            r.err().expect("err").as_str(),
            "Type does not support JSON deserialization"
        );
    }
    #[test]
    fn deserialize_refany_numeric_boundaries() {
        let fnptr = deser_i64 as usize;
        let mut zero = deserialize_refany_from_json(Json::integer(0), fnptr).expect("0");
        assert_eq!(read_i64(&mut zero), 0);
        let mut neg = deserialize_refany_from_json(Json::integer(-1), fnptr).expect("-1");
        assert_eq!(read_i64(&mut neg), -1);
        // i64::MIN is exactly -2^63 in f64 and survives.
        let mut min =
            deserialize_refany_from_json(Json::integer(i64::MIN), fnptr).expect("i64::MIN");
        assert_eq!(read_i64(&mut min), i64::MIN);
        // i64::MAX rounds up to 2^63 in the f64 store, which is out of range —
        // it must be reported as an error, never wrapped around to i64::MIN.
        assert!(deserialize_refany_from_json(Json::integer(i64::MAX), fnptr).is_err());
        // Saturation / NaN / non-integral / wrong-type inputs all fail cleanly.
        for j in [
            Json::number(f64::NAN),
            Json::number(f64::INFINITY),
            Json::number(f64::NEG_INFINITY),
            Json::number(1e300),
            Json::number(-1e300),
            Json::number(0.5),
            Json::null(),
            Json::bool(true),
            Json::string("7"),
        ] {
            let described = json_stringify(&j).as_str().to_string();
            let r = json_deserialize_to_refany(j, fnptr);
            assert!(r.is_err(), "{described} must not deserialize into an i64");
            assert_eq!(r.err().expect("err").as_str(), "not an i64");
        }
    }
    #[test]
    fn deserialize_refany_propagates_the_hook_error_message() {
        let r = json_deserialize_to_refany(Json::integer(1), deser_always_err as usize);
        assert!(r.is_err() && !r.is_ok());
        assert_eq!(r.err().expect("err").as_str(), "always fails");
    }
    // ------------------------------------------------------------------
    // restore_refany_from_json
    // ------------------------------------------------------------------
    #[test]
    fn restore_refany_without_deserialize_fn_is_err_and_leaves_state_intact() {
        let mut plain = RefAny::new(1i64);
        let e = restore_refany_from_json(&mut plain, Json::integer(2)).unwrap_err();
        assert!(e.contains("no deserialize fn"), "unexpected message: {e}");
        assert_eq!(read_i64(&mut plain), 1);
    }
    #[test]
    fn restore_refany_preserves_the_hooks_across_the_swap() {
        let mut s = state_i64(1);
        let (ser, deser) = (s.get_serialize_fn(), s.get_deserialize_fn());
        restore_refany_from_json(&mut s, Json::integer(2)).expect("restore");
        assert_eq!(read_i64(&mut s), 2);
        assert_eq!(s.get_serialize_fn(), ser, "serialize hook was lost");
        assert_eq!(s.get_deserialize_fn(), deser, "deserialize hook was lost");
        assert!(s.can_serialize() && s.can_deserialize());
        // ... and the restored value is itself serializable again.
        assert_eq!(
            serialize_refany_to_json(&s)
                .expect("still serializable")
                .as_i64()
                .into_option(),
            Some(2)
        );
    }
    #[test]
    fn restore_refany_rejects_json_the_hook_refuses() {
        let mut s = state_i64(3);
        let e = restore_refany_from_json(&mut s, Json::string("nope")).unwrap_err();
        assert_eq!(e, "not an i64");
        assert_eq!(read_i64(&mut s), 3, "state must be untouched on failure");
    }
    #[test]
    fn restore_refany_fails_while_a_borrow_is_live() {
        let mut s = state_i64(4);
        let mut sibling = s.clone(); // clones share the RefCountInner
        let guard = sibling.downcast_ref::<i64>().expect("shared borrow");
        let e = restore_refany_from_json(&mut s, Json::integer(9)).unwrap_err();
        assert!(
            e.contains("replace_contents failed"),
            "unexpected message: {e}"
        );
        assert_eq!(*guard, 4, "the live borrow must still see the old value");
        drop(guard);
        // Once the borrow is released the very same call succeeds, and every
        // clone observes the swap.
        restore_refany_from_json(&mut s, Json::integer(9)).expect("restore after drop");
        assert_eq!(read_i64(&mut s), 9);
        assert_eq!(read_i64(&mut sibling), 9);
    }
    // ------------------------------------------------------------------
    // RefAnyUndoManager — constructor + predicates + invariants
    // ------------------------------------------------------------------
    #[test]
    fn undo_manager_new_holds_its_invariants() {
        for capacity in [0usize, 1, 2, usize::MAX] {
            let m = RefAnyUndoManager::new(capacity);
            assert_eq!(m.capacity, capacity);
            assert!(m.head.is_none());
            assert!(m.undo_diffs.is_empty());
            assert!(m.redo_diffs.is_empty());
            assert!(!m.can_undo());
            assert!(!m.can_redo());
        }
        let d = RefAnyUndoManager::default();
        assert!(!d.can_undo() && !d.can_redo());
    }
    #[test]
    fn undo_manager_ops_on_empty_history_are_noops() {
        let mut m = RefAnyUndoManager::new(0);
        let mut s = state_i64(5);
        assert!(!m.undo(&mut s));
        assert!(!m.redo(&mut s));
        m.clear(); // clearing an empty history must not panic
        assert!(!m.can_undo() && !m.can_redo());
        assert_eq!(read_i64(&mut s), 5, "state must be untouched");
    }
    #[test]
    fn undo_manager_requires_a_json_representation() {
        let mut m = RefAnyUndoManager::new(0);
        let plain = RefAny::new(1i64); // no serialize hook at all
        assert!(!m.commit(&plain));
        assert!(!m.can_undo());
        assert!(m.head.is_none());
        let mut null_ser = RefAny::new(1i64); // hook exists but yields `null`
        null_ser.set_serialize_fn(ser_null as usize);
        assert!(!m.commit(&null_ser));
        assert!(m.head.is_none(), "a null body must not seed the history");
    }
    #[test]
    fn undo_manager_unchanged_commit_keeps_the_redo_branch() {
        let mut m = RefAnyUndoManager::new(0);
        let mut s = state_i64(1);
        assert!(m.commit(&s)); // seeds the base
        write_i64(&mut s, 2);
        assert!(m.commit(&s));
        assert!(m.undo(&mut s));
        assert_eq!(read_i64(&mut s), 1);
        assert!(m.can_redo());
        // Re-committing an *unchanged* state records nothing and must not
        // orphan the redo branch.
        assert!(!m.commit(&s));
        assert!(m.can_redo());
        assert!(m.redo(&mut s));
        assert_eq!(read_i64(&mut s), 2);
        assert!(!m.can_redo());
    }
    #[test]
    fn undo_manager_capacity_caps_the_retained_history() {
        let mut m = RefAnyUndoManager::new(2);
        let mut s = state_i64(0);
        assert!(m.commit(&s));
        for v in 1..=5i64 {
            write_i64(&mut s, v);
            assert!(m.commit(&s));
        }
        assert_eq!(
            m.undo_diffs.len(),
            2,
            "capacity must evict the oldest diffs"
        );
        // Only the two most recent steps are reachable: 5 -> 4 -> 3.
        assert!(m.undo(&mut s));
        assert_eq!(read_i64(&mut s), 4);
        assert!(m.undo(&mut s));
        assert_eq!(read_i64(&mut s), 3);
        assert!(!m.can_undo());
        assert!(
            !m.undo(&mut s),
            "an exhausted history returns false, not a panic"
        );
        assert_eq!(read_i64(&mut s), 3);
    }
    #[test]
    fn undo_manager_capacity_one_keeps_exactly_one_step() {
        let mut m = RefAnyUndoManager::new(1);
        let mut s = state_i64(0);
        assert!(m.commit(&s));
        for v in 1..=3i64 {
            write_i64(&mut s, v);
            assert!(m.commit(&s));
        }
        assert_eq!(m.undo_diffs.len(), 1);
        assert!(m.undo(&mut s));
        assert_eq!(read_i64(&mut s), 2);
        assert!(!m.can_undo());
    }
    #[test]
    fn undo_manager_deep_history_round_trips() {
        let mut m = RefAnyUndoManager::new(0); // unlimited
        let mut s = state_i64(0);
        assert!(m.commit(&s));
        for v in 1..=100i64 {
            write_i64(&mut s, v);
            assert!(m.commit(&s));
        }
        assert_eq!(m.undo_diffs.len(), 100);
        for expected in (0..100i64).rev() {
            assert!(m.undo(&mut s));
            assert_eq!(read_i64(&mut s), expected);
        }
        assert!(!m.can_undo());
        assert!(m.can_redo());
        for expected in 1..=100i64 {
            assert!(m.redo(&mut s));
            assert_eq!(read_i64(&mut s), expected);
        }
        assert!(!m.can_redo());
        m.clear();
        assert!(!m.can_undo() && !m.can_redo());
        assert!(m.head.is_none());
        assert_eq!(read_i64(&mut s), 100, "clear() must not touch the state");
    }
    #[test]
    fn undo_manager_reports_false_when_the_restore_hook_fails() {
        // Serialization works (so commits land) but deserialization always
        // fails, so `undo` cannot write the state back: it must report `false`
        // instead of panicking or silently claiming success.
        let mut s = RefAny::new(1i64);
        s.set_serialize_fn(ser_i64 as usize);
        s.set_deserialize_fn(deser_always_err as usize);
        let mut m = RefAnyUndoManager::new(0);
        assert!(m.commit(&s));
        write_i64(&mut s, 2);
        assert!(m.commit(&s));
        assert!(!m.undo(&mut s), "restore failed -> undo must report false");
        assert_eq!(read_i64(&mut s), 2, "the state is left as it was");
        assert!(!m.can_undo());
    }
    #[test]
    fn undo_manager_round_trips_an_object_state_with_pointer_hostile_keys() {
        // The JSON key contains both '/' and '~', so the diff path only works if
        // esc()/unesc() are exact inverses (RFC 6901: ~1 then ~0, in that order).
        let mut s = RefAny::new(Doc {
            text: "hello".to_string(),
            cursor: 0,
        });
        s.set_serialize_fn(ser_doc as usize);
        s.set_deserialize_fn(deser_doc as usize);
        let mut m = RefAnyUndoManager::new(0);
        assert!(m.commit(&s));
        {
            let mut g = s.downcast_mut::<Doc>().expect("doc");
            g.text = "hello world".to_string();
            g.cursor = 11;
        }
        assert!(m.commit(&s));
        assert!(m.undo(&mut s));
        {
            let g = s.downcast_ref::<Doc>().expect("doc");
            assert_eq!(g.text, "hello");
            assert_eq!(g.cursor, 0);
        }
        assert!(m.redo(&mut s));
        let g = s.downcast_ref::<Doc>().expect("doc");
        assert_eq!(g.text, "hello world");
        assert_eq!(g.cursor, 11);
    }
    // ------------------------------------------------------------------
    // jsondiff::diff / apply — reversibility invariants
    // ------------------------------------------------------------------
    #[test]
    fn diff_of_identical_values_is_empty_and_apply_of_nothing_is_identity() {
        use serde_json::json;
        for v in [
            json!(null),
            json!(0),
            json!("x"),
            json!([1, 2]),
            json!({"a": {"b": [1]}}),
        ] {
            assert!(super::jsondiff::diff(&v, &v).is_empty());
            assert_eq!(super::jsondiff::apply(&v, &[], true), v);
            assert_eq!(super::jsondiff::apply(&v, &[], false), v);
        }
    }
    #[test]
    fn diff_apply_is_reversible_for_every_change_shape() {
        use serde_json::json;
        let cases = [
            (json!(1), json!(2)),                       // scalar at the root
            (json!(null), json!({"a": 1})),             // type change at the root
            (json!({"a": 1}), json!({"a": 1, "b": 2})), // key added
            (json!({"a": 1, "b": 2}), json!({"a": 1})), // key removed
            (json!({"a": {"b": {"c": 1}}}), json!({"a": {"b": {"c": 2}}})), // nested leaf
            (json!({"a": [1, 2]}), json!({"a": [2, 1]})), // arrays are leaves
            (json!({"a": 1}), json!({"a": "1"})),       // leaf type change
            (json!({"a": 1}), json!([1])),              // object -> array
            (json!({}), json!({})),                     // no-op
            (json!({"": 1}), json!({"": 2})),           // empty key
        ];
        for (a, b) in &cases {
            let d = super::jsondiff::diff(a, b);
            assert_eq!(
                &super::jsondiff::apply(a, &d, true),
                b,
                "forward {a} -> {b}"
            );
            assert_eq!(
                &super::jsondiff::apply(b, &d, false),
                a,
                "backward {b} -> {a}"
            );
        }
    }
    #[test]
    fn diff_apply_handles_pointer_escapes_and_unicode_keys() {
        use serde_json::json;
        // Keys that collide with RFC-6901 pointer syntax, plus an empty key and
        // a multi-byte key (the path is sliced at a byte offset).
        let a = json!({
            "a/b": 1,
            "~": 2,
            "~0": 3,
            "~1": 4,
            "a~1b": 5,
            "": 6,
            "\u{1F600}": 7,
        });
        let mut b = a.clone();
        for (_k, v) in b.as_object_mut().expect("object").iter_mut() {
            *v = json!(0);
        }
        let d = super::jsondiff::diff(&a, &b);
        assert_eq!(d.len(), 7, "each key must yield exactly one change");
        assert_eq!(
            super::jsondiff::apply(&a, &d, true),
            b,
            "escaping is not round-tripping"
        );
        assert_eq!(super::jsondiff::apply(&b, &d, false), a);
    }
    #[test]
    fn apply_ignores_changes_whose_path_cannot_be_resolved() {
        use serde_json::json;
        let base = json!({"a": 1});
        let changes = vec![
            // parent does not exist
            super::jsondiff::Change {
                path: "/x/y".to_string(),
                old: None,
                new: Some(json!(1)),
            },
            // not a JSON Pointer (no leading '/')
            super::jsondiff::Change {
                path: "a/b".to_string(),
                old: None,
                new: Some(json!(2)),
            },
            // root "removal" is a documented no-op
            super::jsondiff::Change {
                path: String::new(),
                old: None,
                new: None,
            },
        ];
        assert_eq!(super::jsondiff::apply(&base, &changes, true), base);
        assert_eq!(super::jsondiff::apply(&base, &changes, false), base);
    }
    #[test]
    fn diff_of_a_large_object_is_reversible() {
        let mut a = serde_json::Map::new();
        let mut b = serde_json::Map::new();
        for i in 0..2_000i64 {
            a.insert(format!("k{i}"), serde_json::json!(i));
            b.insert(format!("k{i}"), serde_json::json!(i + 1));
        }
        let a = serde_json::Value::Object(a);
        let b = serde_json::Value::Object(b);
        let d = super::jsondiff::diff(&a, &b);
        assert_eq!(d.len(), 2_000);
        assert_eq!(super::jsondiff::apply(&a, &d, true), b);
        assert_eq!(super::jsondiff::apply(&b, &d, false), a);
    }
    #[test]
    fn diff_of_deeply_nested_objects_does_not_overflow() {
        fn nest(depth: usize, leaf: i64) -> serde_json::Value {
            let mut v = serde_json::json!(leaf);
            for _ in 0..depth {
                v = serde_json::json!({ "a": v });
            }
            v
        }
        let a = nest(200, 1);
        let b = nest(200, 2);
        let d = super::jsondiff::diff(&a, &b);
        assert_eq!(d.len(), 1, "only the leaf changed");
        assert_eq!(d[0].path, "/a".repeat(200));
        assert_eq!(super::jsondiff::apply(&a, &d, true), b);
        assert_eq!(super::jsondiff::apply(&b, &d, false), a);
    }
}