jshift 0.4.0

Schema-guided, safe in-place JSON path reader and mutator for raw byte buffers.
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
//! Structural indexing for fast path navigation (safe Rust).
//!
//! **Opt-in only:** default [`crate::find_value`] / mutate APIs never build an index.
//! Call [`IndexedDocument::build`], [`IndexedDocument::index_array`],
//! [`IndexedDocument::index_object`], or derive helpers like `indexed_document()` when
//! you want to pay a one-time scan for many random hops.
//!
//! This is **not** a full simdjson-style DOM. It builds read-only metadata that
//! accelerates jshift's own job: path finds and bulk iteration.
//!
//! # Layers
//!
//! 1. **Array side-tables** — `element_starts[i]` for `path[i].…` in O(1).
//! 2. **Object key maps** — key → value span for wide / hot objects.
//! 3. **Stage-1 structural list** — offsets of `{ } [ ] : ,` outside strings; used to
//!    skip large containers by walking structurals instead of every byte.
//!
//! # Mutation (indexes go stale)
//!
//! Indexes bind to a fixed `&[u8]` snapshot. After **any** in-place mutate/delete/
//! upsert that changes offsets, the index is **invalid**: using it is a logic error
//! (wrong spans / panics in debug if out of range). There is no dirty flag in 0.4;
//! rebuild or drop after writes.
//!
//! Preferred ETL: **index → many reads → write a new buffer (or rebuild) → optional
//! reindex**.
//!
//! # Safety
//!
//! Fully safe: `Vec<u32>`, `HashMap`, existing cursors. No `unsafe`.

use std::collections::HashMap;

use crate::error::Error;
use crate::path::{OwnedPathSegment, PathSegment};
use crate::scan::{
    byte_at, find_from_value, find_string_end, find_value_offsets, skip_value, skip_whitespace,
};

// ─── Stage-1 structural list ────────────────────────────────────────────────

/// Sorted absolute offsets of structural characters **outside** JSON strings:
/// `{ } [ ] : ,`
///
/// Built with the same escape-aware string rules as the rest of jshift (safe loops /
/// `memchr` under the hood via existing string helpers).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct StructuralIndex {
    structurals: Vec<u32>,
}

impl StructuralIndex {
    /// Number of structural positions.
    #[inline]
    pub fn len(&self) -> usize {
        self.structurals.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.structurals.is_empty()
    }

    /// All structural offsets (sorted ascending).
    #[inline]
    pub fn offsets(&self) -> &[u32] {
        &self.structurals
    }

    /// Index of the first structural at or after `pos`, if any.
    pub fn first_at_or_after(&self, pos: usize) -> Option<usize> {
        let p = pos.min(u32::MAX as usize) as u32;
        match self.structurals.binary_search(&p) {
            Ok(i) => Some(i),
            Err(i) if i < self.structurals.len() => Some(i),
            Err(_) => None,
        }
    }

    /// Skip a container starting at `open_pos` (`[` or `{`) using only the
    /// structural list (not a full byte scan of the interior).
    pub fn skip_container(&self, json: &[u8], open_pos: usize) -> Result<usize, Error> {
        if open_pos >= json.len() || !matches!(json[open_pos], b'{' | b'[') {
            return Err(Error::InvalidJsonSyntax {
                pos: open_pos,
                msg: "Expected container open for structural skip",
            });
        }
        let mut depth = 1isize;
        let mut si = self
            .first_at_or_after(open_pos + 1)
            .ok_or(Error::InvalidJsonSyntax {
                pos: open_pos,
                msg: "Unclosed container (structural index)",
            })?;
        while si < self.structurals.len() {
            let off = self.structurals[si] as usize;
            if off >= json.len() {
                break;
            }
            match json[off] {
                b'{' | b'[' => depth += 1,
                b'}' | b']' => {
                    depth -= 1;
                    if depth == 0 {
                        return Ok(off + 1);
                    }
                }
                b':' | b',' => {}
                _ => {}
            }
            si += 1;
        }
        Err(Error::InvalidJsonSyntax {
            pos: open_pos,
            msg: "Unclosed container (structural index)",
        })
    }
}

/// Build a document-wide Stage-1 structural index (safe).
pub fn build_structural_index(json: &[u8]) -> Result<StructuralIndex, Error> {
    let mut structurals = Vec::new();
    let mut i = 0usize;
    let len = json.len();
    while i < len {
        match json[i] {
            b'"' => {
                // Jump past the whole string (closing quote + 1).
                let end_q = find_string_end(json, i + 1)?;
                i = end_q + 1;
            }
            b'{' | b'}' | b'[' | b']' | b':' | b',' => {
                if i > u32::MAX as usize {
                    return Err(Error::InvalidJsonSyntax {
                        pos: i,
                        msg: "Document too large for u32 structural index",
                    });
                }
                structurals.push(i as u32);
                i += 1;
            }
            _ => {
                // Bulk skip non-interesting bytes.
                let start = i;
                i += 1;
                while i < len {
                    match json[i] {
                        b'"' | b'{' | b'}' | b'[' | b']' | b':' | b',' => break,
                        _ => i += 1,
                    }
                }
                let _ = start;
            }
        }
    }
    Ok(StructuralIndex { structurals })
}

// ─── Array side-table ───────────────────────────────────────────────────────

/// Side-table for one array value: start offset of each element.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArrayIndex {
    element_starts: Vec<u32>,
    open: u32,
    close: u32,
}

impl ArrayIndex {
    #[inline]
    pub fn len(&self) -> usize {
        self.element_starts.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.element_starts.is_empty()
    }

    #[inline]
    pub fn open(&self) -> usize {
        self.open as usize
    }

    #[inline]
    pub fn close(&self) -> usize {
        self.close as usize
    }

    #[inline]
    pub fn element_start(&self, i: usize) -> Option<usize> {
        self.element_starts.get(i).map(|&o| o as usize)
    }

    /// Offset of the region after element `i` (next start or `]`). Not a precise value end.
    /// Prefer [`Self::element_value_span`] for a true JSON value range.
    pub fn element_end(&self, i: usize) -> Option<usize> {
        if i >= self.element_starts.len() {
            return None;
        }
        if i + 1 < self.element_starts.len() {
            Some(self.element_starts[i + 1] as usize)
        } else {
            Some(self.close as usize)
        }
    }

    /// Precise on-wire value span for element `i`: `[start, end)` via `skip_value`.
    ///
    /// O(1) jump to the element start, then a single value scan for its end.
    /// Does **not** scan sibling elements — critical for `products[i]` on huge arrays.
    pub fn element_value_span(&self, json: &[u8], i: usize) -> Result<(usize, usize), Error> {
        let start = self
            .element_start(i)
            .ok_or(Error::IndexOutOfBounds { index: i })?;
        if start >= json.len() {
            return Err(Error::InvalidJsonSyntax {
                pos: start,
                msg: "Array index points past end of buffer",
            });
        }
        let end = skip_value(json, start)?;
        Ok((start, end))
    }

    pub fn starts(&self) -> &[u32] {
        &self.element_starts
    }
}

// ─── Object key map ─────────────────────────────────────────────────────────

/// Map of object keys (on-wire bytes between quotes) → value span.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectKeyIndex {
    /// Key content as stored between quotes (escaped form).
    entries: HashMap<Vec<u8>, (u32, u32)>,
    open: u32,
    close: u32,
}

impl ObjectKeyIndex {
    #[inline]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    #[inline]
    pub fn open(&self) -> usize {
        self.open as usize
    }

    #[inline]
    pub fn close(&self) -> usize {
        self.close as usize
    }

    /// Lookup by on-wire key bytes (as in a path segment / JSON key content).
    pub fn get(&self, key: &[u8]) -> Option<(usize, usize)> {
        self.entries
            .get(key)
            .map(|&(s, e)| (s as usize, e as usize))
    }

    /// All keys (on-wire form).
    pub fn keys(&self) -> impl Iterator<Item = &[u8]> {
        self.entries.keys().map(|k| k.as_slice())
    }
}

// ─── Indexed document ───────────────────────────────────────────────────────

/// A JSON buffer plus structural / array / object indexes for path-accelerated reads.
#[derive(Debug, Clone)]
pub struct IndexedDocument<'a> {
    json: &'a [u8],
    /// Optional Stage-1 list for the whole document.
    structural: Option<StructuralIndex>,
    arrays: Vec<(Vec<OwnedPathSegment>, ArrayIndex)>,
    objects: Vec<(Vec<OwnedPathSegment>, ObjectKeyIndex)>,
}

impl<'a> IndexedDocument<'a> {
    /// Empty index over `json` (no side-tables yet).
    pub fn empty(json: &'a [u8]) -> Self {
        Self {
            json,
            structural: None,
            arrays: Vec::new(),
            objects: Vec::new(),
        }
    }

    /// Build array side-tables for each path (lenient path parse).
    ///
    /// ```
    /// use jshift::IndexedDocument;
    ///
    /// let json = br#"{"products":[{"id":1},{"id":2},{"id":3}]}"#;
    /// let doc = IndexedDocument::build(json, &["products"]).unwrap();
    /// assert_eq!(doc.array_len(&jshift::parse_path("products")).unwrap(), 3);
    /// assert_eq!(
    ///     doc.find(&jshift::parse_path("products[2].id")).unwrap(),
    ///     b"3"
    /// );
    /// ```
    pub fn build(json: &'a [u8], array_paths: &[&str]) -> Result<Self, Error> {
        let mut doc = Self::empty(json);
        for p in array_paths {
            doc.index_array_str(p)?;
        }
        Ok(doc)
    }

    /// Build array side-tables from segment slices.
    pub fn build_paths(json: &'a [u8], array_paths: &[&[PathSegment<'_>]]) -> Result<Self, Error> {
        let mut doc = Self::empty(json);
        for p in array_paths {
            doc.index_array(p)?;
        }
        Ok(doc)
    }

    /// Build Stage-1 structural index only (no array/object tables yet).
    pub fn build_structural(json: &'a [u8]) -> Result<Self, Error> {
        let mut doc = Self::empty(json);
        doc.index_structural()?;
        Ok(doc)
    }

    /// Full convenience: structural + arrays + objects.
    pub fn build_full(
        json: &'a [u8],
        array_paths: &[&str],
        object_paths: &[&str],
    ) -> Result<Self, Error> {
        let mut doc = Self::empty(json);
        doc.index_structural()?;
        for p in array_paths {
            doc.index_array_str(p)?;
        }
        for p in object_paths {
            doc.index_object_str(p)?;
        }
        Ok(doc)
    }

    #[inline]
    pub fn as_bytes(&self) -> &'a [u8] {
        self.json
    }

    /// Build or replace the document-wide Stage-1 structural list.
    pub fn index_structural(&mut self) -> Result<(), Error> {
        self.structural = Some(build_structural_index(self.json)?);
        Ok(())
    }

    pub fn structural(&self) -> Option<&StructuralIndex> {
        self.structural.as_ref()
    }

    /// Index the array at `path`.
    pub fn index_array(&mut self, path: &[PathSegment]) -> Result<(), Error> {
        let owned = path_to_owned(path);
        self.arrays.retain(|(p, _)| p != &owned);
        let table = build_array_index(self.json, path, self.structural.as_ref())?;
        self.arrays.push((owned, table));
        Ok(())
    }

    pub fn index_array_str(&mut self, path: &str) -> Result<(), Error> {
        let segs = crate::path::parse_path(path);
        self.index_array(&segs)
    }

    /// Index every array path a [`crate::ProjectPlan`] will walk (idempotent).
    ///
    /// Builds Stage-1 structurals when missing (helps large-array table builds), then
    /// array side-tables for each path from [`crate::ProjectPlan::array_paths_for_index`].
    /// Already-indexed paths are left unchanged.
    ///
    /// ```
    /// use jshift::{IndexedDocument, ProjectPlan, project_indexed};
    ///
    /// let json = br#"{"products":[{"id":1},{"id":2},{"id":3}]}"#;
    /// let plan = ProjectPlan::from_paths(&["products[2].id"]).unwrap();
    /// let mut doc = IndexedDocument::empty(json);
    /// doc.index_for_plan(&plan).unwrap();
    /// assert_eq!(project_indexed(&doc, &plan).unwrap(), br#"{"products":{"id":3}}"#);
    /// ```
    pub fn index_for_plan(&mut self, plan: &crate::ProjectPlan) -> Result<(), Error> {
        if self.structural.is_none() {
            self.index_structural()?;
        }
        for p in plan.array_paths_for_index() {
            let segs = crate::path::parse_path(&p);
            if self.lookup_array(&segs).is_none() {
                // Path may not exist in this document (soft project); skip quietly.
                match self.index_array(&segs) {
                    Ok(()) => {}
                    Err(Error::PathNotFound) | Err(Error::TypeMismatch { .. }) => {}
                    Err(e) => return Err(e),
                }
            }
        }
        Ok(())
    }

    /// Index all keys of the object at `path` (value must be `{...}`).
    pub fn index_object(&mut self, path: &[PathSegment]) -> Result<(), Error> {
        let owned = path_to_owned(path);
        self.objects.retain(|(p, _)| p != &owned);
        let table = build_object_key_index(self.json, path, self.structural.as_ref())?;
        self.objects.push((owned, table));
        Ok(())
    }

    pub fn index_object_str(&mut self, path: &str) -> Result<(), Error> {
        let segs = crate::path::parse_path(path);
        self.index_object(&segs)
    }

    pub fn array_len(&self, path: &[PathSegment]) -> Option<usize> {
        self.lookup_array(path).map(|(_, t)| t.len())
    }

    pub fn array_index(&self, path: &[PathSegment]) -> Option<&ArrayIndex> {
        self.lookup_array(path).map(|(_, t)| t)
    }

    pub fn object_index(&self, path: &[PathSegment]) -> Option<&ObjectKeyIndex> {
        self.lookup_object(path).map(|(_, t)| t)
    }

    /// Look up an array side-table by the absolute offset of its opening `[`.
    ///
    /// Used by the projector to jump elements in O(1) when the array was indexed
    /// (path-based) and emit visits the same on-wire span.
    pub fn array_index_at_open(&self, open: usize) -> Option<&ArrayIndex> {
        self.arrays
            .iter()
            .find(|(_, t)| t.open() == open)
            .map(|(_, t)| t)
    }

    /// Look up an object key map by the absolute offset of its opening `{`.
    pub fn object_index_at_open(&self, open: usize) -> Option<&ObjectKeyIndex> {
        self.objects
            .iter()
            .find(|(_, t)| t.open() == open)
            .map(|(_, t)| t)
    }

    /// Find using array / object indexes when applicable; else normal path scan.
    pub fn find(&self, path: &[PathSegment]) -> Result<&'a [u8], Error> {
        let (start, end) = self.find_offsets(path)?;
        Ok(&self.json[start..end])
    }

    pub fn find_offsets(&self, path: &[PathSegment]) -> Result<(usize, usize), Error> {
        if let Some((rest_start, rest_path)) = self.try_accelerated_jump(path)? {
            return find_from_value(self.json, rest_start, rest_path);
        }
        find_value_offsets(self.json, path)
    }

    pub fn for_each_element<F>(&self, array_path: &[PathSegment], mut f: F) -> Result<(), Error>
    where
        F: FnMut(usize, &'a [u8]) -> Result<(), Error>,
    {
        let table = self
            .lookup_array(array_path)
            .map(|(_, t)| t)
            .ok_or(Error::PathNotFound)?;
        for i in 0..table.len() {
            let start = table.element_start(i).unwrap();
            let end = skip_value_maybe_structural(self.json, start, self.structural.as_ref())?;
            f(i, &self.json[start..end])?;
        }
        Ok(())
    }

    pub fn for_each_element_str<F>(&self, array_path: &str, f: F) -> Result<(), Error>
    where
        F: FnMut(usize, &'a [u8]) -> Result<(), Error>,
    {
        let segs = crate::path::parse_path(array_path);
        self.for_each_element(&segs, f)
    }

    pub fn indexed_array_count(&self) -> usize {
        self.arrays.len()
    }

    pub fn indexed_object_count(&self) -> usize {
        self.objects.len()
    }
}

impl<'a> IndexedDocument<'a> {
    fn lookup_array(&self, path: &[PathSegment]) -> Option<(usize, &ArrayIndex)> {
        for (i, (owned, table)) in self.arrays.iter().enumerate() {
            if path_eq_owned(path, owned) {
                return Some((i, table));
            }
        }
        None
    }

    fn lookup_object(&self, path: &[PathSegment]) -> Option<(usize, &ObjectKeyIndex)> {
        for (i, (owned, table)) in self.objects.iter().enumerate() {
            if path_eq_owned(path, owned) {
                return Some((i, table));
            }
        }
        None
    }

    /// Array jump: `array_path + Index(i) + rest` → element start + rest.  
    /// Object jump: `object_path + Key(k) + rest` → value start + rest.
    fn try_accelerated_jump<'p>(
        &self,
        path: &'p [PathSegment<'p>],
    ) -> Result<Option<(usize, &'p [PathSegment<'p>])>, Error> {
        let mut best: Option<(usize, usize)> = None; // (prefix_len, value_start)

        for (owned, table) in &self.arrays {
            let plen = owned.len();
            if path.len() <= plen || !path_prefix_eq_owned(&path[..plen], owned) {
                continue;
            }
            let PathSegment::Index(idx) = path[plen] else {
                continue;
            };
            let Some(start) = table.element_start(idx) else {
                return Err(Error::IndexOutOfBounds { index: idx });
            };
            if best.is_none_or(|(bp, _)| plen > bp) {
                best = Some((plen + 1, start)); // consume the Index segment
            }
        }

        for (owned, table) in &self.objects {
            let plen = owned.len();
            if path.len() <= plen || !path_prefix_eq_owned(&path[..plen], owned) {
                continue;
            }
            let PathSegment::Key(k) = path[plen] else {
                continue;
            };
            let Some((vs, _ve)) = table.get(k.as_bytes()) else {
                // Key missing in map → treat as path not found (object was fully indexed).
                return Err(Error::PathNotFound);
            };
            if best.is_none_or(|(bp, _)| plen > bp) {
                best = Some((plen + 1, vs));
            }
        }

        if let Some((consumed, start)) = best {
            Ok(Some((start, &path[consumed..])))
        } else {
            Ok(None)
        }
    }
}

// ─── Builders ───────────────────────────────────────────────────────────────

/// Build an [`ArrayIndex`] for the array at `path`.
///
/// When `structural` is provided, container close is still taken from
/// `find_value_offsets`; element walk uses structural-accelerated `skip_value`
/// when beneficial.
pub fn build_array_index(
    json: &[u8],
    path: &[PathSegment],
    structural: Option<&StructuralIndex>,
) -> Result<ArrayIndex, Error> {
    let (start, end) = find_value_offsets(json, path)?;
    if start >= json.len() || byte_at(json, start)? != b'[' {
        return Err(Error::TypeMismatch {
            expected: "array",
            found: "primitive/object",
        });
    }
    let close = end.saturating_sub(1);
    if close < start || json.get(close) != Some(&b']') {
        return Err(Error::InvalidJsonSyntax {
            pos: end,
            msg: "Array value missing closing bracket",
        });
    }

    let mut element_starts = Vec::new();
    let mut pos = skip_whitespace(json, start + 1);
    if pos >= json.len() {
        return Err(Error::InvalidJsonSyntax {
            pos,
            msg: "Unexpected EOF inside array",
        });
    }
    if json[pos] == b']' {
        return Ok(ArrayIndex {
            element_starts,
            open: start as u32,
            close: pos as u32,
        });
    }

    loop {
        if pos >= json.len() {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Unexpected EOF inside array",
            });
        }
        if pos > u32::MAX as usize {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Document too large for u32 structural index",
            });
        }
        element_starts.push(pos as u32);
        pos = skip_value_maybe_structural(json, pos, structural)?;
        pos = skip_whitespace(json, pos);
        if pos >= json.len() {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Unexpected EOF inside array",
            });
        }
        match json[pos] {
            b',' => pos = skip_whitespace(json, pos + 1),
            b']' => {
                return Ok(ArrayIndex {
                    element_starts,
                    open: start as u32,
                    close: pos as u32,
                });
            }
            _ => {
                return Err(Error::InvalidJsonSyntax {
                    pos,
                    msg: "Expected comma ',' or closing bracket ']'",
                });
            }
        }
    }
}

/// Build an [`ObjectKeyIndex`] for the object at `path`.
pub fn build_object_key_index(
    json: &[u8],
    path: &[PathSegment],
    structural: Option<&StructuralIndex>,
) -> Result<ObjectKeyIndex, Error> {
    let (start, end) = find_value_offsets(json, path)?;
    if start >= json.len() || byte_at(json, start)? != b'{' {
        return Err(Error::TypeMismatch {
            expected: "object",
            found: "primitive/array",
        });
    }
    let close = end.saturating_sub(1);
    if close < start || json.get(close) != Some(&b'}') {
        return Err(Error::InvalidJsonSyntax {
            pos: end,
            msg: "Object value missing closing brace",
        });
    }

    let mut entries = HashMap::new();
    let mut pos = skip_whitespace(json, start + 1);
    if pos >= json.len() {
        return Err(Error::InvalidJsonSyntax {
            pos,
            msg: "Unexpected EOF inside object",
        });
    }
    if json[pos] == b'}' {
        return Ok(ObjectKeyIndex {
            entries,
            open: start as u32,
            close: pos as u32,
        });
    }

    loop {
        pos = skip_whitespace(json, pos);
        if pos >= json.len() {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Unexpected EOF inside object",
            });
        }
        if json[pos] == b'}' {
            return Ok(ObjectKeyIndex {
                entries,
                open: start as u32,
                close: pos as u32,
            });
        }
        if json[pos] != b'"' {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Expected object key string",
            });
        }
        let key_start = pos + 1;
        let key_end = find_string_end(json, key_start)?;
        let key = json[key_start..key_end].to_vec();
        pos = key_end + 1;
        pos = skip_whitespace(json, pos);
        if pos >= json.len() || json[pos] != b':' {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Expected colon after object key",
            });
        }
        pos += 1;
        pos = skip_whitespace(json, pos);
        let val_start = pos;
        let val_end = skip_value_maybe_structural(json, val_start, structural)?;
        if val_start > u32::MAX as usize || val_end > u32::MAX as usize {
            return Err(Error::InvalidJsonSyntax {
                pos: val_start,
                msg: "Document too large for u32 structural index",
            });
        }
        entries.insert(key, (val_start as u32, val_end as u32));
        pos = skip_whitespace(json, val_end);
        if pos >= json.len() {
            return Err(Error::InvalidJsonSyntax {
                pos,
                msg: "Unexpected EOF inside object",
            });
        }
        match json[pos] {
            b',' => pos += 1,
            b'}' => {
                return Ok(ObjectKeyIndex {
                    entries,
                    open: start as u32,
                    close: pos as u32,
                });
            }
            _ => {
                return Err(Error::InvalidJsonSyntax {
                    pos,
                    msg: "Expected comma or closing brace in object",
                });
            }
        }
    }
}

fn skip_value_maybe_structural(
    json: &[u8],
    pos: usize,
    structural: Option<&StructuralIndex>,
) -> Result<usize, Error> {
    let pos = skip_whitespace(json, pos);
    if pos >= json.len() {
        return Err(Error::InvalidJsonSyntax {
            pos,
            msg: "Unexpected EOF",
        });
    }
    if let Some(st) = structural {
        if matches!(json[pos], b'{' | b'[') {
            // Prefer structural skip for containers when Stage-1 is available.
            return st.skip_container(json, pos);
        }
    }
    skip_value(json, pos)
}

fn path_to_owned(path: &[PathSegment]) -> Vec<OwnedPathSegment> {
    path.iter()
        .map(|s| match s {
            PathSegment::Key(k) => OwnedPathSegment::Key((*k).to_string()),
            PathSegment::Index(i) => OwnedPathSegment::Index(*i),
        })
        .collect()
}

fn path_eq_owned(path: &[PathSegment], owned: &[OwnedPathSegment]) -> bool {
    path.len() == owned.len() && path_prefix_eq_owned(path, owned)
}

fn path_prefix_eq_owned(path: &[PathSegment], owned: &[OwnedPathSegment]) -> bool {
    if path.len() != owned.len() {
        return false;
    }
    path.iter().zip(owned.iter()).all(|(a, b)| match (a, b) {
        (PathSegment::Key(k), OwnedPathSegment::Key(ok)) => *k == ok.as_str(),
        (PathSegment::Index(i), OwnedPathSegment::Index(oi)) => i == oi,
        _ => false,
    })
}

/// Extract static array path prefixes from a field path for derive auto-index.
///
/// For `products[0].title` → `["products"]`.  
/// For `a.b[0].c` → `["a.b"]`.  
/// Dynamic nested arrays (`items[0].tags[1]`) only contribute the **static**
/// prefix before the first index (`items`).
pub fn static_array_prefixes_from_path(path: &str) -> Vec<String> {
    let segs = crate::path::parse_path(path);
    let mut out = Vec::new();
    let mut keys: Vec<&str> = Vec::new();
    for s in &segs {
        match s {
            PathSegment::Key(k) => keys.push(*k),
            PathSegment::Index(_) => {
                if !keys.is_empty() {
                    out.push(keys.join("."));
                }
                // Stop at first index for static auto-index (dynamic nested arrays
                // need per-element indexes built at runtime).
                break;
            }
        }
    }
    out
}

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

    #[test]
    fn index_jump_mid_array() {
        let mut s = String::from(r#"{"products":["#);
        for i in 0..500 {
            if i > 0 {
                s.push(',');
            }
            s.push_str(&format!(r#"{{"id":{i},"title":"item_{i}"}}"#));
        }
        s.push_str("]}");
        let json = s.into_bytes();
        let doc = IndexedDocument::build(&json, &["products"]).unwrap();
        assert_eq!(doc.array_len(&parse_path("products")).unwrap(), 500);
        assert_eq!(
            doc.find(&parse_path("products[250].id")).unwrap(),
            b"250"
        );
        assert_eq!(
            doc.find(&parse_path("products[499].title")).unwrap(),
            br#""item_499""#
        );
    }

    #[test]
    fn structural_skip_matches_skip_value() {
        let json = br#"{"a":[1,{"x":2},[3,4]],"b":true}"#;
        let st = build_structural_index(json).unwrap();
        assert!(!st.is_empty());
        // Skip the array value of "a"
        let (start, end) = find_value_offsets(json, &parse_path("a")).unwrap();
        assert_eq!(json[start], b'[');
        let via_st = st.skip_container(json, start).unwrap();
        let via_scan = skip_value(json, start).unwrap();
        assert_eq!(via_st, via_scan);
        assert_eq!(via_st, end);
    }

    #[test]
    fn object_key_map() {
        let json = br#"{"cfg":{"alpha":1,"beta":true,"gamma":"z"}}"#;
        let mut doc = IndexedDocument::empty(json);
        doc.index_object_str("cfg").unwrap();
        assert_eq!(doc.find(&parse_path("cfg.beta")).unwrap(), b"true");
        assert_eq!(doc.find(&parse_path("cfg.gamma")).unwrap(), br#""z""#);
        assert!(matches!(
            doc.find(&parse_path("cfg.missing")),
            Err(Error::PathNotFound)
        ));
        let oi = doc.object_index(&parse_path("cfg")).unwrap();
        assert_eq!(oi.len(), 3);
    }

    #[test]
    fn build_full_and_for_each() {
        let json = br#"{"a":[1,2,3],"o":{"k":9}}"#;
        let doc = IndexedDocument::build_full(json, &["a"], &["o"]).unwrap();
        assert!(doc.structural().is_some());
        assert_eq!(doc.indexed_array_count(), 1);
        assert_eq!(doc.indexed_object_count(), 1);
        let mut n = 0;
        doc.for_each_element(&parse_path("a"), |_, _| {
            n += 1;
            Ok(())
        })
        .unwrap();
        assert_eq!(n, 3);
        assert_eq!(doc.find(&parse_path("o.k")).unwrap(), b"9");
    }

    #[test]
    fn static_array_prefixes() {
        assert_eq!(
            static_array_prefixes_from_path("products[0].title"),
            vec!["products".to_string()]
        );
        assert_eq!(
            static_array_prefixes_from_path("a.b[0].c"),
            vec!["a.b".to_string()]
        );
        assert!(static_array_prefixes_from_path("plain.field").is_empty());
    }

    #[test]
    fn for_each_counts() {
        let json = br#"{"a":[1,2,3,4]}"#;
        let doc = IndexedDocument::build(json, &["a"]).unwrap();
        let mut n = 0;
        doc.for_each_element(&parse_path("a"), |i, slice| {
            assert_eq!(slice, [b'1' + i as u8].as_slice());
            n += 1;
            Ok(())
        })
        .unwrap();
        assert_eq!(n, 4);
    }
}