grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
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
// Project:   grippo
// File:      src/json/keys.rs
// Purpose:   A JSON record's top-level keys indexed, stripped, set and spliced on its raw bytes
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A record's top-level keys, found, stripped and set on its raw bytes.
//!
//! [`KeyIndex::read`] walks the top level of a JSON object record once, with
//! [`Paths`](super::Paths)' skipping, and keeps each member's decoded name
//! and where its value lies. [`Members`] counts and finds members by name, and
//! [`Members::splice`] writes the record with keys stripped or set, copying
//! every other member's bytes as they were. [`KeyIndex::read_tail_first`]
//! reads keys appended at a record's end from the end, and walks the whole
//! record only when the end doesn't hold them all.
//!
//! ```
//! use grippo::json::{Edit, KeyIndex, Park, Text};
//!
//! let mut index = KeyIndex::new();
//! let record = br#"{"tenant":"a","x":1.50,"tag":"t"}"#;
//! let mut members = index.read(record)?;
//! assert_eq!(members.count("tenant"), 1);
//!
//! let edits = [
//!     Edit::strip("tenant"),
//!     Edit::set("tag", Text::string("web"), Park::Always("_original")),
//! ];
//! let mut out = Vec::new();
//! let spliced = members.splice(&edits, &mut out)?;
//! assert_eq!(spliced.bytes(), br#"{"x":1.50,"tag":"web","tag_original":"t"}"#);
//! # Ok::<(), grippo::json::KeyError>(())
//! ```

use std::borrow::Cow;
use std::ops::Range;

use memchr::{memchr, memrchr};
use thiserror::Error;

use super::paths::{Kind, Malformed, Raw, checked, close, string_end, unescape, valid, value_end};

/// Why a record can't be indexed, or an edit can't be made.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum KeyError {
    /// The record's first byte opens a value of another type.
    #[error("the record is {0:?}, not an object")]
    NotAnObject(Kind),
    /// The record, or a [`Text::json`] value, isn't JSON where it was read.
    #[error("malformed JSON at byte {at}")]
    Malformed {
        /// The offset of the token being read.
        at: usize,
    },
    /// Two edits of one splice name the same key.
    #[error("edits {first} and {second} name the same key")]
    SameKey {
        /// The earlier edit's index.
        first: usize,
        /// The later edit's index.
        second: usize,
    },
    /// A splice of members read from the tail, which may not be all of them.
    #[error("a splice needs every member, and a tail read has only the last ones")]
    Tail,
}

/// Where one member lies in the record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Span {
    /// The key's opening quote.
    key: usize,
    /// Just past the key's closing quote.
    key_end: usize,
    /// The value's first byte.
    value: usize,
    /// Just past the value.
    end: usize,
    kind: Kind,
    /// The key holds a backslash.
    escaped: bool,
}

impl Span {
    /// The key between its quotes, as the record spells it.
    fn raw_key(self, json: &[u8]) -> &[u8] {
        &json[self.key + 1..self.key_end - 1]
    }

    /// Whether the key decodes to `name`.
    fn named(self, json: &[u8], name: &str) -> bool {
        decodes_to(self.raw_key(json), self.escaped, name.as_bytes())
    }
}

/// What one edit found among the members.
#[derive(Debug, Clone, Copy, Default)]
struct Plan {
    count: usize,
    first: usize,
}

/// Scratch for reading a record's top-level keys, reused record to record.
///
/// Once it has grown to the widest record, a read allocates nothing. So does
/// a splice, past the caller's buffer, unless it parks a value or compares
/// two strings that both hold escapes. `Send + Sync`, one per worker.
#[derive(Debug, Clone, Default)]
pub struct KeyIndex {
    spans: Vec<Span>,
    /// The edit naming each member, for a splice.
    tags: Vec<Option<usize>>,
    plans: Vec<Plan>,
}

impl KeyIndex {
    /// Empty scratch. The first read sizes it.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            spans: Vec::new(),
            tags: Vec::new(),
            plans: Vec::new(),
        }
    }

    /// Indexes every top-level member of the object `json`, in order.
    ///
    /// The read checks the object's braces, colons and commas, each key in
    /// full, and that nothing but whitespace follows the closing brace. A
    /// value is read by its extent only, its brackets and quotes, and checked
    /// when [`Member::value`] asks for it.
    ///
    /// # Errors
    ///
    /// [`KeyError::NotAnObject`] when the first byte past any whitespace opens
    /// another type, [`KeyError::Malformed`] when the object isn't JSON where
    /// it was read, or there's no value at all.
    pub fn read<'s, 'a>(&'s mut self, json: &'a [u8]) -> Result<Members<'s, 'a>, KeyError> {
        let close = top_level(json, &mut self.spans)?;
        Ok(self.members(json, close, true))
    }

    /// The members `names` name, read from the end of `json` where it ends
    /// in them, else every member as [`read`](Self::read) gives them.
    ///
    /// From the closing brace back, each member is read whole: its value, a
    /// string or a number or a literal, then its colon and key, and the comma
    /// or opening brace before it. The read stops as soon as every name has
    /// been seen, and the members read come back with
    /// [`is_whole`](Members::is_whole) unset. A member it doesn't want, a
    /// container value, or anything it can't read that way sends it to the
    /// forward read. Reaching the opening brace reads them all.
    ///
    /// [`Members::last`] answers the same either way, for a name in `names`.
    /// A tail read checks only the members it reads, so a fault before them
    /// goes unseen.
    ///
    /// # Errors
    ///
    /// As [`read`](Self::read), when it falls back to it.
    pub fn read_tail_first<'s, 'a>(
        &'s mut self,
        json: &'a [u8],
        names: &[&str],
    ) -> Result<Members<'s, 'a>, KeyError> {
        match tail(json, names, &mut self.spans) {
            Some((close, whole)) => Ok(self.members(json, close, whole)),
            None => self.read(json),
        }
    }

    fn members<'a>(&mut self, json: &'a [u8], close: usize, whole: bool) -> Members<'_, 'a> {
        Members {
            json,
            spans: &self.spans,
            tags: &mut self.tags,
            plans: &mut self.plans,
            close,
            whole,
        }
    }
}

/// One record's top-level members, from [`KeyIndex::read`] or
/// [`KeyIndex::read_tail_first`].
#[derive(Debug)]
pub struct Members<'s, 'a> {
    json: &'a [u8],
    spans: &'s [Span],
    tags: &'s mut Vec<Option<usize>>,
    plans: &'s mut Vec<Plan>,
    /// The object's closing brace.
    close: usize,
    whole: bool,
}

impl<'a> Members<'_, 'a> {
    /// The number of members read.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.spans.len()
    }

    /// Whether none were read.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.spans.is_empty()
    }

    /// Whether these are all the record's members. A tail read that found
    /// every name short of the opening brace has only the last ones, so a
    /// count or a first match speaks of those alone.
    #[must_use]
    pub const fn is_whole(&self) -> bool {
        self.whole
    }

    /// Checks every member's value in full, so the record reads with
    /// `serde_json` when this returns `Ok`: each string's escapes and UTF-8,
    /// a lone surrogate included, each number and that it's finite as an
    /// f64, and nesting within `serde_json`'s 128 levels. A read checks a
    /// value's extent only.
    ///
    /// # Errors
    ///
    /// [`KeyError::Malformed`] at the first token that fails, and
    /// [`KeyError::Tail`] for members from a tail read, which may not be
    /// all of them.
    pub fn check(&self) -> Result<(), KeyError> {
        // serde_json's 128 counts the record's own object and errors on reaching it.
        const DEPTH: usize = 126;
        if !self.whole {
            return Err(KeyError::Tail);
        }
        for span in self.spans {
            valid(self.json, span.value, span.end, DEPTH)
                .map_err(|at| KeyError::Malformed { at })?;
        }
        Ok(())
    }

    /// Member `i`, in record order.
    #[must_use]
    pub fn get(&self, i: usize) -> Option<Member<'a>> {
        self.spans.get(i).map(|&span| self.member(span))
    }

    /// Every member, in record order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = Member<'a>> {
        self.spans.iter().map(|&span| self.member(span))
    }

    /// How many members decode to `name`.
    #[must_use]
    pub fn count(&self, name: &str) -> usize {
        self.spans
            .iter()
            .filter(|span| span.named(self.json, name))
            .count()
    }

    /// The first member that decodes to `name`, the one a forward reader such
    /// as [`Paths`](super::Paths) takes.
    #[must_use]
    pub fn first(&self, name: &str) -> Option<Member<'a>> {
        self.spans
            .iter()
            .find(|span| span.named(self.json, name))
            .map(|&span| self.member(span))
    }

    /// The last member that decodes to `name`.
    #[must_use]
    pub fn last(&self, name: &str) -> Option<Member<'a>> {
        self.spans
            .iter()
            .rfind(|span| span.named(self.json, name))
            .map(|&span| self.member(span))
    }

    const fn member(&self, span: Span) -> Member<'a> {
        Member {
            json: self.json,
            span,
        }
    }

    /// The record with `edits` made, appended to `out`, or the record as it
    /// came when they change nothing.
    ///
    /// Every member no edit names keeps its bytes, in order, and so does the
    /// whitespace around them. A stripped member goes with the comma before
    /// it, or after it when it was first. A set member keeps its key as
    /// spelled and takes the new value in place, every later member of that
    /// name is removed, and each value they held is parked as `park` says.
    /// Added and parked members go before the closing brace, edit by edit in
    /// the order of `edits`: a set's key where the record lacks it, else its
    /// parked values in record order.
    ///
    /// # Errors
    ///
    /// [`KeyError::SameKey`] when two edits name one key, [`KeyError::Tail`]
    /// on members from a tail read that stopped short of the opening brace.
    pub fn splice<'o>(
        &mut self,
        edits: &[Edit<'_>],
        out: &'o mut Vec<u8>,
    ) -> Result<Spliced<'a, 'o>, KeyError> {
        if !self.whole {
            return Err(KeyError::Tail);
        }
        for (second, edit) in edits.iter().enumerate() {
            if let Some(first) = edits[..second].iter().position(|e| e.name == edit.name) {
                return Err(KeyError::SameKey { first, second });
            }
        }
        if !self.plan(edits) {
            return Ok(Spliced::Unchanged(self.json));
        }
        let start = out.len();
        out.reserve(self.json.len() + 64 * edits.len());
        let mut kept = self.write_members(edits, out);
        self.write_appended(edits, out, &mut kept);
        out.extend_from_slice(&self.json[self.close..]);
        Ok(Spliced::Written(&out[start..]))
    }

    /// Tags each member with the edit naming it and counts each edit's
    /// members, and gives whether the edits change anything.
    fn plan(&mut self, edits: &[Edit<'_>]) -> bool {
        let json = self.json;
        let spans = self.spans;
        self.plans.clear();
        self.plans.resize(edits.len(), Plan::default());
        self.tags.clear();
        for (i, span) in spans.iter().enumerate() {
            let tag = edits.iter().position(|edit| span.named(json, edit.name));
            if let Some(j) = tag {
                let plan = &mut self.plans[j];
                if plan.count == 0 {
                    plan.first = i;
                }
                plan.count += 1;
            }
            self.tags.push(tag);
        }
        edits
            .iter()
            .zip(self.plans.iter())
            .any(|(edit, plan)| match edit.op {
                Op::Strip => plan.count > 0,
                Op::Set(text, park) => {
                    plan.count != 1
                        || matches!(park, Park::Always(_))
                        || !text.holds(self.member(self.spans[plan.first]))
                }
            })
    }

    /// Writes the record as edited up to its closing brace, and gives whether
    /// any member stays.
    fn write_members(&self, edits: &[Edit<'_>], out: &mut Vec<u8>) -> bool {
        let json = self.json;
        let spans = self.spans;
        let mut cursor = 0;
        let mut kept = false;
        for (i, (span, tag)) in spans.iter().zip(self.tags.iter()).enumerate() {
            let Some(j) = *tag else {
                kept = true;
                continue;
            };
            match edits[j].op {
                Op::Set(text, _) if self.plans[j].first == i => {
                    out.extend_from_slice(&json[cursor..span.value]);
                    text.write(out);
                    cursor = span.end;
                    kept = true;
                }
                // A strip, or a later member of a name a set takes.
                _ if kept => {
                    out.extend_from_slice(&json[cursor..spans[i - 1].end]);
                    cursor = span.end;
                }
                _ => {
                    out.extend_from_slice(&json[cursor..span.key]);
                    cursor = spans.get(i + 1).map_or(span.end, |next| next.key);
                }
            }
        }
        out.extend_from_slice(&json[cursor..self.close]);
        kept
    }

    /// Adds each set key the record lacks, then each set's parked values.
    fn write_appended(&self, edits: &[Edit<'_>], out: &mut Vec<u8>, kept: &mut bool) {
        let json = self.json;
        let mut parked: Vec<String> = Vec::new();
        for (j, edit) in edits.iter().enumerate() {
            let Op::Set(text, park) = edit.op else {
                continue;
            };
            if self.plans[j].count == 0 {
                push_key(out, kept, edit.name);
                text.write(out);
                continue;
            }
            let (Park::Always(suffix) | Park::IfChanged(suffix)) = park else {
                continue;
            };
            for (span, _) in self
                .spans
                .iter()
                .zip(self.tags.iter())
                .filter(|(_, tag)| **tag == Some(j))
            {
                if matches!(park, Park::IfChanged(_)) && text.holds(self.member(*span)) {
                    continue;
                }
                let name = self.free_name(edits, &parked, edit.name, suffix);
                push_key(out, kept, &name);
                out.extend_from_slice(&json[span.value..span.end]);
                parked.push(name);
            }
        }
    }

    /// `<name><suffix>`, or the first `<name><suffix>_<n>` from 2 that no
    /// member, edit or earlier park in this splice holds.
    fn free_name(&self, edits: &[Edit<'_>], parked: &[String], name: &str, suffix: &str) -> String {
        let mut candidate = format!("{name}{suffix}");
        let base = candidate.len();
        let mut n: u64 = 1;
        while self
            .spans
            .iter()
            .any(|span| span.named(self.json, &candidate))
            || edits.iter().any(|edit| edit.name == candidate)
            || parked.contains(&candidate)
        {
            n += 1;
            candidate.truncate(base);
            candidate.push('_');
            candidate.push_str(&n.to_string());
        }
        candidate
    }
}

/// One top-level member: its key, decoded on request, and where its value lies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Member<'a> {
    json: &'a [u8],
    span: Span,
}

impl<'a> Member<'a> {
    /// The key with its escapes decoded, borrowed when it holds none.
    #[must_use]
    pub fn name(&self) -> Cow<'a, str> {
        let raw = self.span.raw_key(self.json);
        if !self.span.escaped {
            return String::from_utf8_lossy(raw);
        }
        let mut decoded = Vec::with_capacity(raw.len());
        // The read checked the escapes, so this can't fail.
        let _ = unescape(raw, |part| decoded.extend_from_slice(part));
        Cow::Owned(
            String::from_utf8(decoded)
                .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()),
        )
    }

    /// The value's type, by its first byte.
    #[must_use]
    pub const fn kind(&self) -> Kind {
        self.span.kind
    }

    /// The value, checked as [`Values::get`](super::Values::get) checks a
    /// found one. `None` when it's malformed.
    #[must_use]
    pub fn value(&self) -> Option<Raw<'a>> {
        let text = checked(self.span.kind, &self.json[self.span.value..self.span.end])?;
        Some(Raw::new(text, self.span.kind, self.span.value))
    }

    /// The value's offsets in the record.
    #[must_use]
    pub const fn value_span(&self) -> Range<usize> {
        self.span.value..self.span.end
    }

    /// The member's offsets in the record, from its key's opening quote to
    /// the end of its value.
    #[must_use]
    pub const fn span(&self) -> Range<usize> {
        self.span.key..self.span.end
    }
}

/// A value a splice writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Text<'v> {
    text: &'v str,
    /// The text is a string's contents, written quoted and escaped.
    quote: bool,
}

impl<'v> Text<'v> {
    /// `s` as a JSON string, quoted and escaped as `serde_json` writes one.
    #[must_use]
    pub const fn string(s: &'v str) -> Self {
        Self {
            text: s,
            quote: true,
        }
    }

    /// `json` written as it is: one JSON value with no whitespace around it,
    /// checked as [`Values::get`](super::Values::get) checks a found one. An
    /// object or array is checked by its brackets and quotes only.
    ///
    /// # Errors
    ///
    /// [`KeyError::Malformed`] when `json` isn't one value.
    pub fn json(json: &'v str) -> Result<Self, KeyError> {
        let bytes = json.as_bytes();
        let kind = bytes
            .first()
            .copied()
            .and_then(Kind::of)
            .ok_or(KeyError::Malformed { at: 0 })?;
        let end = match kind {
            Kind::Object | Kind::Array => close(bytes, 1).ok(),
            Kind::String => string_end(bytes, 1).ok().map(|(quote, _)| quote + 1),
            Kind::Number | Kind::Bool | Kind::Null => Some(bytes.len()),
        };
        let closer = match kind {
            Kind::Object => Some(b'}'),
            Kind::Array => Some(b']'),
            _ => None,
        };
        let whole = end == Some(bytes.len())
            && closer.is_none_or(|b| bytes.last() == Some(&b))
            && checked(kind, bytes).is_some();
        if !whole {
            return Err(KeyError::Malformed {
                at: end.unwrap_or(0),
            });
        }
        Ok(Self {
            text: json,
            quote: false,
        })
    }

    fn write(self, out: &mut Vec<u8>) {
        if self.quote {
            push_string(out, self.text);
        } else {
            out.extend_from_slice(self.text.as_bytes());
        }
    }

    /// Whether `held` holds this value: the same text, or the same string
    /// however it's escaped.
    fn holds(self, held: Member<'_>) -> bool {
        let raw = &held.json[held.span.value..held.span.end];
        let is_string = held.span.kind == Kind::String;
        if self.quote {
            return is_string && string_is(raw, self.text.as_bytes());
        }
        if raw == self.text.as_bytes() {
            return true;
        }
        let ours = self.text.as_bytes();
        if !is_string || ours.first() != Some(&b'"') {
            return false;
        }
        let inner = &ours[1..ours.len() - 1];
        let held_inner = &raw[1..raw.len() - 1];
        match (
            memchr(b'\\', inner).is_some(),
            memchr(b'\\', held_inner).is_some(),
        ) {
            (false, held_escaped) => decodes_to(held_inner, held_escaped, inner),
            (true, false) => decodes_to(inner, true, held_inner),
            (true, true) => {
                let mut decoded = Vec::with_capacity(inner.len());
                unescape(inner, |part| decoded.extend_from_slice(part)).is_ok()
                    && decodes_to(held_inner, true, &decoded)
            }
        }
    }
}

impl<'v> From<Raw<'v>> for Text<'v> {
    /// A value found in a record, written as it was spelled there.
    fn from(raw: Raw<'v>) -> Self {
        Self {
            text: raw.text(),
            quote: false,
        }
    }
}

/// What becomes of a value a set replaces.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Park<'p> {
    /// It's dropped.
    Never,
    /// It's kept as `<name><suffix>`, or the first `<name><suffix>_<n>` from
    /// 2 the record and the splice don't hold.
    Always(&'p str),
    /// As `Always`, except a value equal to the new one is dropped: the same
    /// text, or the same string however it's escaped.
    IfChanged(&'p str),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op<'e> {
    Strip,
    Set(Text<'e>, Park<'e>),
}

/// One change a splice makes, to the top-level members a decoded name names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Edit<'e> {
    name: &'e str,
    op: Op<'e>,
}

impl<'e> Edit<'e> {
    /// Removes every member named `name`.
    #[must_use]
    pub const fn strip(name: &'e str) -> Self {
        Self {
            name,
            op: Op::Strip,
        }
    }

    /// Gives `name` the value `value`: in place of the first member of that
    /// name, every later one removed, or added at the end when there's none.
    /// Each value replaced or removed goes as `park` says.
    #[must_use]
    pub const fn set(name: &'e str, value: Text<'e>, park: Park<'e>) -> Self {
        Self {
            name,
            op: Op::Set(value, park),
        }
    }
}

/// What a splice made of the record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[must_use]
pub enum Spliced<'a, 'o> {
    /// The edits change nothing, so nothing was written: the record as it came.
    Unchanged(&'a [u8]),
    /// The record as edited, the part of the caller's buffer the splice wrote.
    Written(&'o [u8]),
}

impl Spliced<'_, '_> {
    /// The record's bytes, edited or not.
    #[must_use]
    pub const fn bytes<'x>(&'x self) -> &'x [u8] {
        let same: &Spliced<'x, 'x> = self;
        match *same {
            Spliced::Unchanged(bytes) | Spliced::Written(bytes) => bytes,
        }
    }
}

#[inline]
const fn is_space(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
}

/// The first offset from `at` that isn't whitespace.
#[inline]
fn space(json: &[u8], mut at: usize) -> usize {
    while json.get(at).copied().is_some_and(is_space) {
        at += 1;
    }
    at
}

/// The offset just past the last byte before `at` that isn't whitespace.
#[inline]
const fn space_back(json: &[u8], mut at: usize) -> usize {
    while at > 0 && is_space(json[at - 1]) {
        at -= 1;
    }
    at
}

/// Walks the object `json` holds, one span per member into `spans`, and gives
/// the offset of its closing brace.
fn top_level(json: &[u8], spans: &mut Vec<Span>) -> Result<usize, KeyError> {
    spans.clear();
    let open = space(json, 0);
    match json.get(open) {
        Some(b'{') => {}
        Some(&b) => {
            return Err(Kind::of(b).map_or(KeyError::Malformed { at: open }, KeyError::NotAnObject));
        }
        None => return Err(KeyError::Malformed { at: open }),
    }
    let mut at = space(json, open + 1);
    let close = if json.get(at) == Some(&b'}') {
        at
    } else {
        loop {
            let span = member(json, at)?;
            spans.push(span);
            at = space(json, span.end);
            match json.get(at) {
                Some(b',') => at = space(json, at + 1),
                Some(b'}') => break at,
                _ => return Err(KeyError::Malformed { at }),
            }
        }
    };
    let rest = space(json, close + 1);
    if rest < json.len() {
        return Err(KeyError::Malformed { at: rest });
    }
    Ok(close)
}

/// The member whose key's opening quote should be at `at`.
fn member(json: &[u8], at: usize) -> Result<Span, KeyError> {
    let bad = |at| KeyError::Malformed { at };
    if json.get(at) != Some(&b'"') {
        return Err(bad(at));
    }
    let (quote, escaped) = string_end(json, at + 1).map_err(|_| bad(at))?;
    key_ok(&json[at + 1..quote], escaped).map_err(|_| bad(at))?;
    let colon = space(json, quote + 1);
    if json.get(colon) != Some(&b':') {
        return Err(bad(colon));
    }
    let value = space(json, colon + 1);
    let kind = json
        .get(value)
        .copied()
        .and_then(Kind::of)
        .ok_or_else(|| bad(value))?;
    let end = value_end(json, value, kind).map_err(|_| bad(value))?;
    Ok(Span {
        key: at,
        key_end: quote + 1,
        value,
        end,
        kind,
        escaped,
    })
}

/// Whether a key's text between its quotes is a JSON string's: no raw
/// control character, good escapes, and UTF-8.
fn key_ok(raw: &[u8], escaped: bool) -> Result<(), Malformed> {
    if escaped {
        unescape(raw, |_| {})?;
    } else if raw.iter().all(|&b| (0x20..0x80).contains(&b)) {
        return Ok(());
    } else if raw.iter().any(|&b| b < 0x20) {
        return Err(Malformed);
    }
    if raw.is_ascii() || std::str::from_utf8(raw).is_ok() {
        Ok(())
    } else {
        Err(Malformed)
    }
}

/// Whether a string's text between its quotes decodes to `want`, compared as
/// it decodes, with no copy.
fn decodes_to(raw: &[u8], escaped: bool, want: &[u8]) -> bool {
    if !escaped {
        return raw == want;
    }
    // Decoding never lengthens a string.
    if want.len() > raw.len() {
        return false;
    }
    let mut at = 0;
    let mut same = true;
    let decoded = unescape(raw, |part| {
        same = same && want.get(at..at + part.len()) == Some(part);
        at += part.len();
    });
    decoded.is_ok() && same && at == want.len()
}

/// Whether the quoted string `raw` decodes to `want`.
fn string_is(raw: &[u8], want: &[u8]) -> bool {
    let Some(inner) = raw.get(1..raw.len().saturating_sub(1)) else {
        return false;
    };
    decodes_to(inner, memchr(b'\\', inner).is_some(), want)
}

/// Appends `s` as a JSON string, escaping what `serde_json` escapes: the
/// quote, the backslash and control characters.
fn push_string(out: &mut Vec<u8>, s: &str) {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    out.push(b'"');
    let bytes = s.as_bytes();
    let mut run = 0;
    for (i, &b) in bytes.iter().enumerate() {
        let short = match b {
            b'"' => b'"',
            b'\\' => b'\\',
            b'\n' => b'n',
            b'\r' => b'r',
            b'\t' => b't',
            0x08 => b'b',
            0x0c => b'f',
            0x00..=0x1f => 0,
            _ => continue,
        };
        out.extend_from_slice(&bytes[run..i]);
        if short == 0 {
            out.extend_from_slice(&[
                b'\\',
                b'u',
                b'0',
                b'0',
                HEX[usize::from(b >> 4)],
                HEX[usize::from(b & 0xf)],
            ]);
        } else {
            out.extend_from_slice(&[b'\\', short]);
        }
        run = i + 1;
    }
    out.extend_from_slice(&bytes[run..]);
    out.push(b'"');
}

/// Writes `"name":`, with a comma first once a member is written.
fn push_key(out: &mut Vec<u8>, kept: &mut bool, name: &str) {
    if *kept {
        out.push(b',');
    }
    *kept = true;
    push_string(out, name);
    out.push(b':');
}

/// Reads the members `names` name from the end of `json`, into `spans` in
/// record order, and gives the closing brace and whether every member was
/// read. `None` when the end doesn't hold every name in members read whole.
fn tail(json: &[u8], names: &[&str], spans: &mut Vec<Span>) -> Option<(usize, bool)> {
    spans.clear();
    let close = space_back(json, json.len()).checked_sub(1)?;
    if json[close] != b'}' {
        return None;
    }
    let wanted = names
        .iter()
        .enumerate()
        .filter(|(i, name)| !names[..*i].contains(name))
        .count();
    if wanted == 0 {
        return Some((close, false));
    }
    let mut seen = 0;
    let mut end = space_back(json, close);
    if json.get(end.checked_sub(1)?) == Some(&b'{') {
        return opened(json, end - 1, close, spans);
    }
    loop {
        let span = member_back(json, end)?;
        let name = names.iter().find(|name| span.named(json, name))?;
        if !spans.iter().any(|earlier| earlier.named(json, name)) {
            seen += 1;
        }
        spans.push(span);
        let before = space_back(json, span.key).checked_sub(1)?;
        match json[before] {
            b'{' => return opened(json, before, close, spans),
            b',' if seen == wanted => {
                spans.reverse();
                return Some((close, false));
            }
            b',' => end = space_back(json, before),
            _ => return None,
        }
    }
}

/// The tail read reached the brace at `open`, so it read every member, once
/// nothing but whitespace comes before that brace.
fn opened(json: &[u8], open: usize, close: usize, spans: &mut [Span]) -> Option<(usize, bool)> {
    if !json[..open].iter().copied().all(is_space) {
        return None;
    }
    spans.reverse();
    Some((close, true))
}

/// Whether `b` can be part of a number or a literal.
const fn is_scalar(b: u8) -> bool {
    b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.')
}

/// The member whose value, a string, number or literal, ends just before
/// `end`, read from the end. Its key and value are checked in full.
fn member_back(json: &[u8], end: usize) -> Option<Span> {
    let last = *json.get(end.checked_sub(1)?)?;
    let value = if last == b'"' {
        string_back(json, end - 1)?
    } else if is_scalar(last) {
        json[..end].iter().rposition(|&b| !is_scalar(b))? + 1
    } else {
        return None;
    };
    let kind = Kind::of(json[value])?;
    checked(kind, &json[value..end])?;
    let colon = space_back(json, value).checked_sub(1)?;
    if json[colon] != b':' {
        return None;
    }
    let quote = space_back(json, colon).checked_sub(1)?;
    if json[quote] != b'"' {
        return None;
    }
    let key = string_back(json, quote)?;
    let escaped = memchr(b'\\', &json[key + 1..quote]).is_some();
    key_ok(&json[key + 1..quote], escaped).ok()?;
    Some(Span {
        key,
        key_end: quote + 1,
        value,
        end,
        kind,
        escaped,
    })
}

/// The opening quote of the string whose closing quote is at `quote`, proved
/// by reading forward from it to that same closing quote.
fn string_back(json: &[u8], quote: usize) -> Option<usize> {
    let mut at = quote;
    let open = loop {
        let candidate = memrchr(b'"', &json[..at])?;
        let slashes = json[..candidate]
            .iter()
            .rev()
            .take_while(|&&b| b == b'\\')
            .count();
        if slashes % 2 == 0 {
            break candidate;
        }
        at = candidate;
    };
    (string_end(json, open + 1).ok()?.0 == quote).then_some(open)
}

#[cfg(test)]
mod tests;