dataflow-rs 4.0.1

A lightweight rules engine for building IFTTT-style automation and data processing pipelines in Rust. Define rules with JSONLogic conditions, execute actions, and chain workflows.
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
//! Paths into a context: a root plus v3's segment rules.
//!
//! A segment means one thing on an object and another on an array: on an
//! object it is a key, with one leading `#` stripped; on an array it is an
//! index, parsed from the raw segment, so `#20` is never an index. Both
//! readings are resolved at parse time, so no write re-parses.
//!
//! The write rules are v3's `set_nested_value`, stated once in
//! [`rules`](super::rules). `set`, `get` and `remove` here are hand-inlined
//! forms of [`rules::step`](super::rules::step) for the hot path (the
//! checkpoint and every clean read), held to
//! [`rules::resolve`](super::rules::resolve) on every small tree and path
//! (`state::tests::splice_property`), and `tests/it/path.rs` checks them
//! against the corpus's model. A write either applies in full or changes
//! nothing: containers are created only past the last existing one, and a
//! hop that cannot continue (a scalar, a `null` under an object, a key on
//! an array) comes before any creation.

use super::rules::{self, Shape};
use crate::base::{Error, ErrorKind, Result};
use datavalue::OwnedDataValue;
use std::fmt;
use std::str::FromStr;
use std::sync::Arc;

/// The most segments a [`Path`] holds, the root's own included. The write
/// log and the splice keep a path's resolved hops in a 64-bit mask.
pub(crate) const MAX_PATH_SEGMENTS: usize = 64;

/// One of the three context roots a path starts at.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Root {
    /// The message's data.
    Data,
    /// The message's metadata.
    Metadata,
    /// The message's scratch space.
    TempData,
}

impl Root {
    /// The root's row in [`ROOTS`](crate::base::ROOTS), written out so
    /// reordering the enum cannot silently name another root.
    fn row(self) -> usize {
        match self {
            Self::Data => 0,
            Self::Metadata => 1,
            Self::TempData => 2,
        }
    }

    /// The root at `row` in [`ROOTS`](crate::base::ROOTS), if any.
    fn from_row(row: usize) -> Option<Self> {
        match row {
            0 => Some(Self::Data),
            1 => Some(Self::Metadata),
            2 => Some(Self::TempData),
            _ => None,
        }
    }

    /// The root's key in the context, as a path spells it: its row of the
    /// context's roots, which the variants follow.
    pub fn as_str(self) -> &'static str {
        crate::base::ROOTS[self.row()]
    }
}

/// One path segment: its object key and, when the raw segment parses as one,
/// its array index.
///
/// Built only through its constructors, which compute `hash` from `key`, so
/// the derived equality stays consistent.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Seg {
    /// The key on an object: the raw segment with one leading `#` stripped.
    pub(crate) key: Box<str>,
    /// The index on an array: the raw segment parsed as `usize`.
    pub(crate) index: Option<usize>,
    /// [`key_hash`] of `key`, computed once, so the write log rejects a
    /// sibling of another name with one compare. Two keys may share a hash,
    /// so a match is always confirmed on the names.
    pub(crate) hash: u32,
}

/// FNV-1a (32-bit) over a key's bytes: [`Seg::hash`].
pub(crate) fn key_hash(key: &str) -> u32 {
    key.bytes().fold(0x811c_9dc5, |h, b| {
        (h ^ u32::from(b)).wrapping_mul(0x0100_0193)
    })
}

impl Seg {
    pub(crate) fn parse(raw: &str) -> Self {
        let key = seg_key(raw);
        Self {
            key: key.into(),
            index: seg_index(raw),
            hash: key_hash(key),
        }
    }

    /// A segment that is always an object key, never an index.
    #[cfg(test)]
    pub(crate) fn key(key: &str) -> Self {
        Self {
            key: key.into(),
            index: None,
            hash: key_hash(key),
        }
    }

    /// The segment naming array element `i`: its key is `i`'s text. `i` is
    /// at most [`MAX_ARRAY_INDEX`], or the text would parse back as a key.
    pub(crate) fn index(i: usize) -> Self {
        debug_assert!(i <= MAX_ARRAY_INDEX, "index {i} is past the cap");
        let key = i.to_string();
        Self {
            hash: key_hash(&key),
            key: key.into(),
            index: Some(i),
        }
    }

    /// Updates the index of an existing index segment in place, without
    /// allocating a new `Box<str>` when the caller only writes into a known
    /// array (such as a fan-out's `into` array).
    pub(crate) fn set_index(&mut self, i: usize) {
        debug_assert!(i <= MAX_ARRAY_INDEX, "index {i} is past the cap");
        self.index = Some(i);
    }
}

/// A raw segment's key on an object: one leading `#` stripped.
fn seg_key(raw: &str) -> &str {
    raw.strip_prefix('#').unwrap_or(raw)
}

/// The largest index a bare numeric segment names on an array. A larger
/// number is a key, so no path can make a write pad an array past it: a
/// trace read from outside the engine, or a computed path, could otherwise
/// name `data.list.4294967295` and have a write allocate for every slot
/// before it, which overflows on wasm32 and exhausts memory anywhere.
pub const MAX_ARRAY_INDEX: usize = (1 << 20) - 1;

/// A raw segment's index on an array: the raw segment parsed as `usize`, at
/// most [`MAX_ARRAY_INDEX`], so `#20` is never one and nor is a number past
/// the cap.
fn seg_index(raw: &str) -> Option<usize> {
    raw.parse().ok().filter(|&i| i <= MAX_ARRAY_INDEX)
}

/// A root plus typed segments, parsed once. A segment is a key on an object
/// (one leading `#` stripped) and an index on an array (the raw segment parsed
/// as `usize`, up to [`MAX_ARRAY_INDEX`]; a larger number is a key), resolved
/// at parse.
///
/// `Debug` prints the dotted text, `Path("metadata.errors")`.
#[derive(Clone, PartialEq, Eq)]
pub struct Path {
    root: Root,
    /// The root's own segment first, then the segments below it: the chain the
    /// functions below run over the context. Shared, so a clone allocates
    /// nothing: a host call's overlay keeps one for each write.
    segs: Arc<[Seg]>,
    dotted: Arc<str>,
}

impl FromStr for Path {
    type Err = Error;

    fn from_str(dotted: &str) -> Result<Self> {
        let (first, rest) = match dotted.split_once('.') {
            Some((first, rest)) => (first, Some(rest)),
            None => (dotted, None),
        };
        let root = match crate::base::ROOTS
            .iter()
            .position(|root| *root == first)
            .and_then(Root::from_row)
        {
            Some(root) => root,
            None => {
                return Err(Error::new(
                    ErrorKind::Config,
                    format!("path `{dotted}` must start at `data`, `metadata` or `temp_data`"),
                ));
            }
        };
        let mut segs = vec![Seg::parse(first)];
        if let Some(rest) = rest {
            segs.extend(rest.split('.').map(Seg::parse));
        }
        if segs.len() > MAX_PATH_SEGMENTS {
            return Err(Error::new(
                ErrorKind::Config,
                format!(
                    "path `{dotted}` has {} segments; a path holds at most {MAX_PATH_SEGMENTS}",
                    segs.len()
                ),
            ));
        }
        Ok(Self {
            root,
            segs: segs.into(),
            dotted: Arc::from(dotted),
        })
    }
}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.dotted)
    }
}

impl fmt::Debug for Path {
    /// The dotted text, `Path("metadata.errors")`: the segments are the
    /// text parsed, so they say nothing more.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Path").field(&&*self.dotted).finish()
    }
}

impl Path {
    /// The root the path starts at.
    pub fn root(&self) -> Root {
        self.root
    }

    /// Does the path name a root itself, with nothing below it?
    pub fn is_root(&self) -> bool {
        self.segs.len() == 1
    }

    /// The segments, the root's own first.
    pub(crate) fn segs(&self) -> &[Seg] {
        &self.segs
    }

    /// The dotted spelling, shared: what a `Change` records as its path.
    pub(crate) fn dotted(&self) -> &Arc<str> {
        &self.dotted
    }

    /// The path to element `index` of the array at this path: what
    /// `{self}.{index}` parses to, built from these segments and one more
    /// rather than re-parsed. `None` when this path already holds the most
    /// segments a path can.
    #[cfg(test)]
    pub(crate) fn index_child(&self, index: usize) -> Option<Self> {
        if self.segs.len() >= MAX_PATH_SEGMENTS {
            return None;
        }
        let segs = self.segs.iter().cloned().chain([Seg::index(index)]);
        Some(Self {
            root: self.root,
            segs: segs.collect(),
            dotted: Arc::from(format!("{}.{index}", self.dotted)),
        })
    }

    /// The path of the first `len` segments, the root's own counted: what
    /// the first `len` pieces of the dotted spelling parse to.
    pub(crate) fn prefix(&self, len: usize) -> Self {
        debug_assert!((1..=self.segs.len()).contains(&len), "a prefix of {self}");
        let end = self
            .dotted
            .match_indices('.')
            .nth(len - 1)
            .map_or(self.dotted.len(), |(at, _)| at);
        Self {
            root: self.root,
            segs: Arc::from(&self.segs[..len]),
            dotted: Arc::from(&self.dotted[..end]),
        }
    }

    /// The value at the path in `context`, an object holding the three roots.
    pub fn get<'v>(&self, context: &'v OwnedDataValue) -> Option<&'v OwnedDataValue> {
        get(context, &self.segs)
    }

    /// Assigns `value` at the path. At a root it replaces the root and accepts
    /// only an object. A hop that cannot continue writes nothing and is `Ok`.
    pub fn set(&self, context: &mut OwnedDataValue, value: OwnedDataValue) -> Result<()> {
        self.check_set(&value)?;
        self.assign(context, value);
        Ok(())
    }

    /// Removes the value at the path and returns it. A root cannot be removed.
    pub fn remove(&self, context: &mut OwnedDataValue) -> Result<Option<OwnedDataValue>> {
        self.check_remove()?;
        Ok(remove(context, &self.segs))
    }

    /// Checks a write of `value` here: a root takes only an object.
    pub(crate) fn check_set(&self, value: &OwnedDataValue) -> Result<()> {
        if self.is_root() && !matches!(value, OwnedDataValue::Object(_)) {
            return Err(Error::new(
                ErrorKind::Config,
                format!(
                    "`{}` is a root and takes only an object, not {}",
                    self.dotted,
                    kind(value)
                ),
            ));
        }
        Ok(())
    }

    /// Checks a removal here: a root cannot be removed.
    pub(crate) fn check_remove(&self) -> Result<()> {
        if self.is_root() {
            return Err(Error::new(
                ErrorKind::Config,
                format!("`{}` is a root and cannot be removed", self.dotted),
            ));
        }
        Ok(())
    }

    /// Assigns `value` at the path, reporting whether it wrote.
    pub(crate) fn assign(&self, context: &mut OwnedDataValue, value: OwnedDataValue) -> bool {
        set(context, &self.segs, value)
    }

    /// `map`'s append and extend at the path: the tests' owned reference for
    /// the splice's.
    #[cfg(test)]
    pub(crate) fn append(
        &self,
        context: &mut OwnedDataValue,
        items: Vec<OwnedDataValue>,
    ) -> std::result::Result<bool, &'static str> {
        append(context, &self.segs, items)
    }
}

/// The empty container a missing hop creates: an array when the next segment
/// is an index, an object otherwise.
fn empty(next: &Seg) -> OwnedDataValue {
    if next.index.is_some() {
        OwnedDataValue::Array(Vec::new())
    } else {
        OwnedDataValue::Object(Vec::new())
    }
}

/// What writing `value` at `segs` into a new, empty container produces: the
/// owned twin of the splice's chain, for a write marked where it starts
/// creating.
pub(crate) fn chain(segs: &[Seg], value: OwnedDataValue) -> OwnedDataValue {
    let Some(first) = segs.first() else {
        return value;
    };
    let mut container = empty(first);
    set(&mut container, segs, value);
    container
}

/// One step of a read: `key` on an object, `index` on an array.
fn hop<'v>(v: &'v OwnedDataValue, key: &str, index: Option<usize>) -> Option<&'v OwnedDataValue> {
    match v {
        OwnedDataValue::Object(pairs) => pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v),
        OwnedDataValue::Array(items) => items.get(index?),
        _ => None,
    }
}

pub(crate) fn get<'v>(v: &'v OwnedDataValue, segs: &[Seg]) -> Option<&'v OwnedDataValue> {
    segs.iter()
        .try_fold(v, |v, seg| hop(v, &seg.key, seg.index))
}

/// [`get`] over a dotted path read segment by segment, by the same rules,
/// allocating nothing: for a lookup that is not worth parsing once.
pub(crate) fn get_dotted<'v>(v: &'v OwnedDataValue, dotted: &str) -> Option<&'v OwnedDataValue> {
    dotted
        .split('.')
        .try_fold(v, |v, raw| hop(v, seg_key(raw), seg_index(raw)))
}

/// [`get`], mutably.
pub(crate) fn get_mut<'v>(
    mut v: &'v mut OwnedDataValue,
    segs: &[Seg],
) -> Option<&'v mut OwnedDataValue> {
    for seg in segs {
        v = match v {
            OwnedDataValue::Object(pairs) => {
                &mut pairs.iter_mut().find(|(k, _)| **k == *seg.key)?.1
            }
            OwnedDataValue::Array(items) => items.get_mut(seg.index?)?,
            _ => return None,
        };
    }
    Some(v)
}

/// Sets `value` at `segs` in `v`, returning whether it wrote.
pub(crate) fn set(v: &mut OwnedDataValue, segs: &[Seg], value: OwnedDataValue) -> bool {
    let Some((last, parents)) = segs.split_last() else {
        return false;
    };
    let mut current = v;
    for (i, seg) in parents.iter().enumerate() {
        let next = &segs[i + 1];
        current = match current {
            OwnedDataValue::Object(pairs) => {
                let at = match pairs.iter().position(|(k, _)| **k == *seg.key) {
                    Some(at) => at,
                    None => {
                        // `String::from`, not `to_string`: a `Box<str>`
                        // formats through `Display`.
                        pairs.push((String::from(&*seg.key), empty(next)));
                        pairs.len() - 1
                    }
                };
                &mut pairs[at].1
            }
            OwnedDataValue::Array(items) => {
                let Some(at) = seg.index else {
                    return false;
                };
                if items.len() <= at {
                    items.resize(at + 1, OwnedDataValue::Null);
                }
                if items[at].is_null() {
                    items[at] = empty(next);
                }
                &mut items[at]
            }
            _ => return false,
        };
    }
    match current {
        OwnedDataValue::Object(pairs) => {
            match pairs.iter_mut().find(|(k, _)| **k == *last.key) {
                Some(slot) => slot.1 = value,
                None => pairs.push((String::from(&*last.key), value)),
            }
            true
        }
        OwnedDataValue::Array(items) => {
            let Some(at) = last.index else {
                return false;
            };
            if items.len() <= at {
                items.resize(at + 1, OwnedDataValue::Null);
            }
            items[at] = value;
            true
        }
        _ => false,
    }
}

/// v3's `remove_nested_value_parts`: an object key leaves with the order of
/// the rest kept, an array element with the tail shifted down.
pub(crate) fn remove(v: &mut OwnedDataValue, segs: &[Seg]) -> Option<OwnedDataValue> {
    let (last, parents) = segs.split_last()?;
    let parent = get_mut(v, parents)?;
    match parent {
        OwnedDataValue::Object(pairs) => {
            let at = pairs.iter().position(|(k, _)| **k == *last.key)?;
            Some(pairs.remove(at).1)
        }
        OwnedDataValue::Array(items) => {
            let at = last.index?;
            (at < items.len()).then(|| items.remove(at))
        }
        _ => None,
    }
}

/// The kind of a value, for an error.
pub(crate) fn kind(v: &OwnedDataValue) -> &'static str {
    Shape::of_owned(v).describe()
}

/// `map`'s append and extend: extend the array at `segs`, or create it over a
/// missing or `null` target. `Ok(false)` when the path is unreachable, which
/// is treated as success with nothing written; `Err` names the kind of any
/// other target.
pub(crate) fn append(
    v: &mut OwnedDataValue,
    segs: &[Seg],
    items: Vec<OwnedDataValue>,
) -> std::result::Result<bool, &'static str> {
    let target = get_mut(v, segs);
    if rules::append_to(target.as_deref().map(Shape::of_owned))? {
        if let Some(OwnedDataValue::Array(existing)) = target {
            existing.extend(items);
        }
        return Ok(true);
    }
    Ok(set(v, segs, OwnedDataValue::Array(items)))
}

/// `map`'s write to a root slot: two objects merge, existing keys replaced in
/// place and new keys appended in order; anything else replaces the slot. The
/// owned statement of the rules the splice's `merge_root` follows, which a
/// trace's replay applies.
pub(crate) fn merge_root(context: &mut OwnedDataValue, key: &str, value: OwnedDataValue) {
    if !matches!(context, OwnedDataValue::Object(_)) {
        *context = OwnedDataValue::Object(vec![(key.to_string(), value)]);
        return;
    }
    match (rules::owned_child_mut(context, rules::Hop::Key(key)), value) {
        (Some(slot @ OwnedDataValue::Object(_)), OwnedDataValue::Object(new_pairs)) => {
            for (k, v) in new_pairs {
                rules::put(slot, rules::Hop::Key(&k), v);
            }
        }
        (_, value) => {
            rules::put(context, rules::Hop::Key(key), value);
        }
    }
}

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

    fn json(text: &str) -> OwnedDataValue {
        serde_json::from_str(text).unwrap()
    }

    fn text(v: &OwnedDataValue) -> String {
        serde_json::to_string(v).unwrap()
    }

    fn path(s: &str) -> Path {
        s.parse().unwrap()
    }

    #[test]
    fn a_path_parses_to_its_root_and_displays_back() {
        let p = path("data.rows.#20.total");
        assert_eq!(p.root(), Root::Data);
        assert!(!p.is_root());
        assert_eq!(p.to_string(), "data.rows.#20.total");
        assert_eq!(path("temp_data.x").root(), Root::TempData);
        assert_eq!(path("metadata.x").root().as_str(), "metadata");
    }

    #[test]
    fn what_is_not_a_context_root_is_refused() {
        for bad in ["", "rows.x", "#data.x", "payload", "payload.x", "Data.x"] {
            let error = bad.parse::<Path>().unwrap_err();
            assert_eq!(error.kind(), &ErrorKind::Config, "{bad}");
        }
    }

    #[test]
    fn a_bare_root_is_a_root_path() {
        assert!(path("data").is_root());
        assert!(path("temp_data").is_root());
    }

    #[test]
    fn empty_segments_below_the_root_are_empty_keys() {
        let mut ctx = json(r#"{"data":{}}"#);
        path("data..x").set(&mut ctx, json("1")).unwrap();
        assert_eq!(text(&ctx), r#"{"data":{"":{"x":1}}}"#);
    }

    #[test]
    fn set_at_a_root_replaces_with_an_object_and_refuses_anything_else() {
        let mut ctx = json(r#"{"data":{"a":1},"metadata":{}}"#);
        path("data").set(&mut ctx, json(r#"{"b":2}"#)).unwrap();
        assert_eq!(text(&ctx), r#"{"data":{"b":2},"metadata":{}}"#);
        let error = path("data").set(&mut ctx, json(r#""s""#)).unwrap_err();
        assert_eq!(error.kind(), &ErrorKind::Config);
        assert_eq!(text(&ctx), r#"{"data":{"b":2},"metadata":{}}"#);
    }

    #[test]
    fn remove_at_a_root_is_refused() {
        let mut ctx = json(r#"{"data":{}}"#);
        let error = path("data").remove(&mut ctx).unwrap_err();
        assert_eq!(error.kind(), &ErrorKind::Config);
    }

    #[test]
    fn a_hop_that_cannot_continue_writes_nothing_and_is_ok() {
        let mut ctx = json(r#"{"data":{"a":5}}"#);
        path("data.a.b").set(&mut ctx, json("1")).unwrap();
        assert_eq!(text(&ctx), r#"{"data":{"a":5}}"#);
        assert!(!path("data.a.b").assign(&mut ctx, json("1")));
    }

    #[test]
    fn get_set_remove_work_below_a_root() {
        let mut ctx = json(r#"{"data":{"rows":[{"t":1}]},"metadata":{}}"#);
        assert_eq!(text(path("data.rows.0.t").get(&ctx).unwrap()), "1");
        path("temp_data.x.y").set(&mut ctx, json("2")).unwrap();
        assert_eq!(
            text(&ctx),
            r#"{"data":{"rows":[{"t":1}]},"metadata":{},"temp_data":{"x":{"y":2}}}"#
        );
        let gone = path("data.rows.0.t").remove(&mut ctx).unwrap();
        assert_eq!(gone.map(|v| text(&v)), Some("1".into()));
    }

    #[test]
    fn a_dotted_read_follows_the_parsed_segments_rules() {
        let v = json(r##"{"a":{"20":"key","#b":"x","b":"hash","rows":[{"t":1},{"t":2}]}}"##);
        for dotted in [
            "a.20",
            "a.#20",
            "a.b",
            "a.#b",
            "a.##b",
            "a.rows.1.t",
            "a.rows.#1",
            "a.rows.x",
            "a",
            "a.",
            "",
            "zz",
        ] {
            let segs: Vec<Seg> = dotted.split('.').map(Seg::parse).collect();
            assert_eq!(
                get_dotted(&v, dotted).map(text),
                get(&v, &segs).map(text),
                "{dotted}"
            );
        }
        assert_eq!(get_dotted(&v, "a.#b").map(text), Some(r#""hash""#.into()));
        assert_eq!(get_dotted(&v, "a.rows.#1"), None);
    }

    #[test]
    fn a_path_holds_at_most_64_segments() {
        let deep = |n: usize| format!("data{}", ".k".repeat(n - 1));
        let ok: Path = deep(64).parse().expect("64 segments parse");
        assert_eq!(ok.segs().len(), 64);
        let err = deep(65)
            .parse::<Path>()
            .expect_err("65 segments are refused");
        assert_eq!(*err.kind(), ErrorKind::Config);
        assert!(err.to_string().contains("at most 64"), "{err}");
    }

    #[test]
    fn an_index_stops_at_the_cap_and_a_larger_number_is_a_key() {
        let at_cap = path(&format!("data.list.{MAX_ARRAY_INDEX}"));
        assert_eq!(at_cap.segs().last().unwrap().index, Some(MAX_ARRAY_INDEX));
        let past = path(&format!("data.list.{}", MAX_ARRAY_INDEX + 1));
        assert_eq!(past.segs().last().unwrap().index, None);
        assert_eq!(&*past.segs().last().unwrap().key, "1048576");

        // On an array a key writes nothing, so the array cannot be grown past
        // the cap; a small index pads with `null` as before.
        let mut ctx = json(r#"{"data":{"list":[]}}"#);
        assert!(!path("data.list.4294967295").assign(&mut ctx, json("7")));
        assert!(!path("data.list.3000000000").assign(&mut ctx, json("7")));
        assert_eq!(text(&ctx), r#"{"data":{"list":[]}}"#);
        assert!(path("data.list.2").assign(&mut ctx, json("7")));
        assert_eq!(text(&ctx), r#"{"data":{"list":[null,null,7]}}"#);
        // Where there is no array, the number is an ordinary key.
        assert!(path("data.obj.4294967295").assign(&mut ctx, json("1")));
        assert_eq!(
            get_dotted(&ctx, "data.obj.4294967295").map(text),
            Some("1".into())
        );
    }

    #[test]
    fn an_index_child_is_its_dotted_spelling_parsed() {
        for (parent, index) in [("data.rs", 0), ("temp_data.a.#b.2", 17), ("metadata", 3)] {
            let child = path(parent).index_child(index).expect("room for the index");
            assert_eq!(child, path(&format!("{parent}.{index}")));
            assert_eq!(child.segs().last().unwrap().index, Some(index));
        }
        // A path at the most segments has no room for one more.
        let deep = format!("data{}", ".k".repeat(63));
        assert!(path(&deep).index_child(0).is_none());
        let roomy = format!("data{}", ".k".repeat(62));
        assert_eq!(path(&roomy).index_child(0).unwrap().segs().len(), 64);
    }

    #[test]
    fn append_extends_or_creates() {
        let mut ctx = json(r#"{"data":{"a":[1]}}"#);
        assert_eq!(path("data.a").append(&mut ctx, vec![json("2")]), Ok(true));
        assert_eq!(path("data.b").append(&mut ctx, vec![json("3")]), Ok(true));
        assert_eq!(text(&ctx), r#"{"data":{"a":[1,2],"b":[3]}}"#);
        path("data.s").set(&mut ctx, json(r#""x""#)).unwrap();
        assert_eq!(path("data.s").append(&mut ctx, vec![]), Err("a string"));
    }

    #[test]
    fn merge_root_merges_objects_and_replaces_the_rest() {
        let mut ctx = json(r#"{"data":{"a":1,"b":2}}"#);
        merge_root(&mut ctx, "data", json(r#"{"b":3,"c":4}"#));
        assert_eq!(text(&ctx), r#"{"data":{"a":1,"b":3,"c":4}}"#);
        merge_root(&mut ctx, "data", json("5"));
        merge_root(&mut ctx, "metadata", json("{}"));
        assert_eq!(text(&ctx), r#"{"data":5,"metadata":{}}"#);
    }

    #[test]
    fn chain_builds_the_containers_a_write_would_create() {
        let segs = &path("data.a.0").segs[1..];
        assert_eq!(text(&chain(segs, json("1"))), r#"{"a":[1]}"#);
        assert_eq!(text(&chain(&[], json("1"))), "1");
    }
}