jshift 0.7.0

Schema-guided typed JSON on raw bytes: path get/mutate, open views, project — without a Value tree.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
#![forbid(unsafe_code)]

//! `jshift` — Schema-guided, safe in-place JSON path reader and mutator.
//!
//! This crate provides a 100% safe Rust engine to selectively read, mutate, upsert,
//! and delete values inside raw JSON byte buffers (`&[u8]` and `Vec<u8>`) without
//! building a full AST. Path scans return zero-copy slices; mutations resize the
//! buffer and shift the tail with safe slice rotations.
//!
//! # What jshift is (and is not)
//!
//! | Do | Don't |
//! | --- | --- |
//! | Path index + mutate | Full JSON DOM as the eval spine |
//! | Schema-guided projection ([`JsonView`]) / [`TypedDoc`] | Multi-format serde (bincode, …) |
//! | Safe structural side-tables | Promise simdjson Stage-1 crowns |
//! | Preserve unmentioned fields | Full RFC validator (unless you add one) |
//!
//! **Open documents:** paths you don't name are left unread (and byte-preserved on
//! write). That is a feature for API evolution (same spirit as prost unknown fields).
//!
//! # Cargo features
//!
//! | Feature | Default | Purpose |
//! | --- | --- | --- |
//! | `derive` | yes | `JsonMutatorSchema` / `JsonView` (structs + externally tagged enums) |
//! | `serde` | no | `AsJshiftView` Deserialize/Serialize bridge — see the [serde bridge guide](crate::serde_bridge_guide) |
//! | `axum` | no | `JshiftJson` / `JshiftDoc` extractors |
//! | `parallel` | no | Rayon-backed parallel list projections on large indexed arrays |
//! | `dhat-heap` | no | dhat global allocator for `examples/alloc_profile` (local profiling only) |
//!
//! Core path engine and structural indexing always compile. Indexing is **opt-in at
//! the call site** (`IndexedDocument`, `read_from_indexed`); never taxed on default finds.
//! Parallel project is opt-in (`project_parallel` / `project_indexed_parallel`); use
//! [`project_indexed_auto`] / [`project_parallel_auto`] to enable Rayon only when
//! [`plan_prefers_parallel`] says the plan is CPU-heavy. Streaming cards:
//! [`project_each`] / [`project_jsonl_write`] (no giant output array).
//!
//! ```toml
//! jshift = { version = "0.7", features = ["derive"] }
//! # core only (no proc-macros):
//! jshift = { version = "0.7", default-features = false }
//! # axum extractors / serde bridge:
//! jshift = { version = "0.7", features = ["axum", "serde"] }
//! # bulk array project with rayon:
//! jshift = { version = "0.7", features = ["parallel"] }
//! ```
//!
//! Measurement: Criterion (`benches/`), RSS (`scripts/measure_rss.sh`), dhat/heaptrack
//! (`examples/alloc_profile`). Large fixtures: `scripts/fetch_teefury.sh` +
//! `scripts/build_large_catalog.sh` → gitignored `benches/data/large.json`.
//!
//! CI verifies both default and `--no-default-features` builds.
//!
//! # Features
//! * **Zero-copy reads:** Find values as slices into the raw buffer.
//! * **In-place mutations:** Safe byte-shifting (including resize) via slice rotations.
//! * **[`JsonView`] trait:** one protocol surface for typed projections of bytes.
//! * **Macro-generated schemas:** `#[derive(JsonView)]` / `JsonMutatorSchema` (structs +
//!   nested views, maps, **`#[json(flatten)]`**, **externally tagged enums**).
//! * **Duplicate keys:** [`DuplicateKeyPolicy`] / [`check_duplicate_keys`] (first / last / error).
//! * **Typed documents:** [`JsonDoc`] + [`TypedDoc`] / [`TypedDocRef`], [`ViewList`] /
//!   [`ValueList`], [`NestedView`], [`MapView`], [`RawJson`], exclusive [`TypedMutator`].
//! * **Collect policies:** [`CollectPolicy`] / [`Collected`] (stream / owned / projected).
//! * **Build without Value:** [`ObjectBuilder`] / [`JsonWriter`]; [`JsonView::to_schema_bytes`].
//! * **Enums:** external (default), internal, adjacent, untagged — free functions +
//!   derive (`#[json(tag)]` / `content` / `untagged`). See [`enums`] and the [API guide](crate::api_guide).
//! * **Ecosystem bridges (opt-in):** feature `serde` → [`AsJshiftView`]; feature `axum` →
//!   [`JshiftJson`] / [`JshiftDoc`].
//! * **When to use what:** [`api_guide`] — ingest vs `JsonView` vs project vs raw land.
//! * **Batch mutate:** [`MutateOp`] / [`BatchPlan`] / [`apply_ops`]; [`rename_key`],
//!   [`merge_object_shallow`].
//! * **Validate:** [`require_paths`], [`deny_unknown_keys`], [`validate_closed`] /
//!   [`validate_open`] (no DOM).
//! * **Shared buffers:** [`SharedDocument`] (`Arc<[u8]>`) for read-heavy fan-out.
//! * **JSONL helpers:** [`json_lines`], [`jsonl_docs`], [`read_jsonl`],
//!   [`write_jsonl_views`]; array→NDJSON cards via [`project_jsonl_write`].
//! * **Multi-file / pages:** [`for_each_page_items`], [`for_each_jsonl_multi`],
//!   incremental [`JsonlDecoder`] (chunked JSONL without merging buffers).
//!   Live catalog demo: `examples/teefury_ingest_bench` (Shopify pages → listing cards).
//! * **Field projection:** [`project`] / [`project_paths`] / [`project_jmespath`] /
//!   [`ProjectPlan`] (keep-list + JMESPath subset → new JSON); streaming
//!   [`project_each`] for per-row cards without a giant output array.
//! * **Projection estimates:** [`estimate_projected_len`] / [`projected_len`].
//! * **Structural array indexes:** [`IndexedDocument`] side-tables for large arrays.
//! * **Parallel auto-pick:** [`plan_prefers_parallel`] + [`project_indexed_auto`].
//!
//! # Quick Start
//! ```
//! use jshift::{find_value, mutate_value, parse_path};
//!
//! let mut json = b"{\"user\": \"farmer\", \"score\": 9.5}".to_vec();
//! let path = parse_path("score");
//!
//! // Read value
//! let score_bytes = find_value(&json, &path).unwrap();
//! assert_eq!(score_bytes, b"9.5");
//!
//! // Mutate in-place
//! mutate_value(&mut json, &path, b"10.0").unwrap();
//! assert_eq!(json, b"{\"user\": \"farmer\", \"score\": 10.0}".to_vec());
//! ```
//!
//! # TypedDoc: typed fields without `Value`
//! ```
//! use jshift::{JsonDoc, TypedDoc};
//!
//! let mut doc = TypedDoc::from_slice(br#"{"status":"ok","id":7,"items":[{"n":1}],"extra":true}"#);
//! assert_eq!(doc.get::<u64>("id").unwrap(), 7);
//! assert_eq!(doc.get_str("status").unwrap(), "ok");
//! // sparse array field stream (relative path parsed once)
//! assert_eq!(doc.collect_each_get::<u64>("items", "n").unwrap(), vec![1]);
//!
//! doc.mutate().set("status", "accepted").unwrap();
//! assert_eq!(doc.get_str("status").unwrap(), "accepted");
//! assert!(doc.contains("extra").unwrap());
//! ```
//!
//! # JsonView: typed projections (open partial structs)
//! ```
//! # #[cfg(feature = "derive")]
//! # {
//! use jshift::{JsonView, JsonMutatorSchema};
//!
//! #[derive(JsonMutatorSchema)]
//! struct ListingCard {
//!     #[json(path = "id")]
//!     id: u64,
//!     #[json(path = "title")]
//!     title: String,
//!     // intentionally no variants / images: partial view
//! }
//!
//! fn ingest<T: JsonView>(buf: &[u8]) -> Result<T, jshift::Error> {
//!     T::read_from(buf)
//! }
//!
//! let json = br#"{"id":7,"title":"Hat","images":[1,2,3],"variants":[]}"#;
//! let card: ListingCard = ingest(json).unwrap();
//! assert_eq!(card.id, 7);
//! assert_eq!(card.title, "Hat");
//!
//! // write_into only touches named paths; other keys stay put
//! let mut buf = json.to_vec();
//! card.write_into(&mut buf).unwrap();
//! assert!(buf.windows(8).any(|w| w == b"\"images\""));
//! # }
//! ```
//!
//! # Enums (external default; also internal / adjacent / untagged)
//!
//! ```
//! # #[cfg(feature = "derive")]
//! # {
//! use jshift::JsonView;
//!
//! #[derive(Debug, PartialEq, JsonView)]
//! enum Status {
//!     Ready,
//!     #[json(rename = "in_progress")]
//!     Running,
//!     Done,
//! }
//!
//! #[derive(Debug, PartialEq, JsonView)]
//! #[json(tag = "type")]
//! enum InternalEv {
//!     Ready,
//!     Click {
//!         #[json(path = "x")]
//!         x: u64,
//!         #[json(path = "y")]
//!         y: u64,
//!     },
//! }
//!
//! assert_eq!(Status::read_from(br#""Ready""#).unwrap(), Status::Ready);
//! assert_eq!(
//!     InternalEv::read_from(br#"{"type":"Click","x":1,"y":2}"#).unwrap(),
//!     InternalEv::Click { x: 1, y: 2 }
//! );
//! # }
//! ```
//!
//! Also: `#[json(tag = "t", content = "c")]` (adjacent), `#[json(untagged)]`.
//! See [`enums`] and [`api_guide`].
//!
//! # Byte flatten (0.7 / Track B)
//! ```
//! # #[cfg(feature = "derive")]
//! # {
//! use jshift::JsonView;
//!
//! #[derive(Debug, PartialEq, JsonView)]
//! struct Meta {
//!     #[json(path = "created_at")]
//!     created_at: String,
//!     #[json(path = "source")]
//!     source: String,
//! }
//!
//! #[derive(Debug, PartialEq, JsonView)]
//! struct Event {
//!     #[json(path = "id")]
//!     id: u64,
//!     #[json(flatten)]
//!     meta: Meta,
//! }
//!
//! let raw = br#"{"id":7,"created_at":"t0","source":"api","noise":true}"#;
//! let e = Event::read_from(raw).unwrap();
//! assert_eq!(e.meta.source, "api");
//! let out = e.to_schema_bytes().unwrap();
//! assert!(!out.windows(6).any(|w| w == b"\"meta\"")); // flat wire
//! # }
//! ```
//!
//! # Project: keep-list / JMESPath subset → smaller JSON
//! ```
//! use jshift::{project_jmespath, project_paths, ProjectPlan, ProjectStyle};
//!
//! let json = br#"{"id":7,"title":"Hat","images":[1,2,3],"meta":{"x":1}}"#;
//! let out = project_paths(json, &["id", "title", "meta.x"]).unwrap();
//! assert_eq!(out, br#"{"id":7,"title":"Hat","meta":{"x":1}}"#);
//!
//! // Keep-list wildcards preserve ancestor keys:
//! let catalog = br#"{"products":[{"sku":"A","blob":1},{"sku":"B","blob":2}]}"#;
//! assert_eq!(
//!     project_paths(catalog, &["products[].sku"]).unwrap(),
//!     br#"{"products":[{"sku":"A"},{"sku":"B"}]}"#
//! );
//!
//! // JMESPath subset: multi-select hash + rename (result is the projected array):
//! assert_eq!(
//!     project_jmespath(catalog, "products[*].{sku: sku}").unwrap(),
//!     br#"[{"sku":"A"},{"sku":"B"}]"#
//! );
//!
//! let pretty = ProjectPlan::from_paths(&["id"]).unwrap().style(ProjectStyle::Pretty { indent: 2 });
//! let _ = jshift::project(json, &pretty).unwrap();
//! ```
//!
//! # High-Impact Real-World Use Case: LLM Dataset Processing (JSONL)
//! In AI training pipelines (e.g., LoRA finetuning), datasets are stored as JSONL files.
//! You can inspect token lengths and mark records as skipped or cleaned in-place:
//!
//! ```
//! # #[cfg(feature = "derive")]
//! # {
//! use jshift::JsonMutatorSchema;
//!
//! #[derive(JsonMutatorSchema)]
//! struct TrainingRecord {
//!     #[json(path = "tokens")]
//!     tokens: usize,
//!     #[json(path = "status")]
//!     status: String,
//! }
//!
//! let mut line = b"{\"instruction\": \"Translate...\", \"tokens\": 1024, \"status\": \"pending\"}".to_vec();
//!
//! // Parse selectively
//! let record = TrainingRecord::read_from_json(&line).unwrap();
//!
//! // Skip long contexts in-place!
//! if record.tokens > 512 {
//!     let mut mutator = TrainingRecord::mutator(&mut line);
//!     mutator.set_status("skipped").unwrap();
//! }
//!
//! assert_eq!(
//!     line,
//!     b"{\"instruction\": \"Translate...\", \"tokens\": 1024, \"status\": \"skipped\"}".to_vec()
//! );
//! # }
//! ```

mod batch;
mod build;
mod collect;
mod convert;
mod document;
mod dupe_keys;
/// Enum tagging free functions and types (also re-exported at crate root).
pub mod enums;
/// Product map: which API for which job (ingest, views, project, enums, bridges).
pub mod api_guide;
mod error;
mod flatten;
mod index;
mod jsonl;
mod limits;
mod map_view;
mod merge_patch;
mod multi_json;
mod mutate;
mod nested;
mod path;
mod project;
mod raw;
mod scan;
mod typed_doc;
mod validate;
mod view;
mod view_list;

#[cfg(feature = "serde")]
mod serde_bridge;
#[cfg(feature = "axum")]
mod axum_ext;

#[cfg(feature = "serde")]
pub mod serde_bridge_guide;

pub use batch::{apply_ops, set_at, upsert_at, BatchPlan, MutateOp};
pub use build::{
    array_from_iter, build_array, build_object, object_from_iter, ArrayBuilder, JsonWriter,
    ObjectBuilder,
};
pub use collect::{CollectPolicy, Collected};
pub use enums::{
    is_external_object_shape, is_external_unit_shape, payload_as_view, peek_external_object,
    read_adjacent, read_external, read_external_object, read_external_unit, read_internal,
    read_tag_field, read_untagged, write_adjacent_content, write_adjacent_unit,
    write_external_object, write_external_unit, write_internal_fields, write_internal_unit,
    ExternalTag,
};
pub use dupe_keys::{
    check_duplicate_keys, check_duplicate_keys_at, check_duplicate_keys_deep,
    check_duplicate_keys_path, object_key_wins, validate_unique_keys, validate_unique_keys_at,
    validate_unique_keys_deep, validate_unique_keys_path, DuplicateKeyPolicy, ObjectKeyReport,
    ResolvedObjectKey,
};
pub use flatten::{
    append_object_members_raw, merge_field_paths, merge_flatten_object, object_member_count,
    project_plan_with_flatten, read_flattened, read_flattened_opt, write_flattened,
    write_flattened_opt,
};
pub use limits::{check_depth, check_document, measure_depth, Limits};
pub use map_view::{
    read_btreemap_at, read_hashmap_at, write_btreemap_at, write_hashmap_at, write_map_iter_at,
    IndexedMapView, MapView,
};
pub use merge_patch::{merge_patch, merge_patch_at};
pub use nested::NestedView;

#[cfg(feature = "serde")]
pub use serde_bridge::{
    from_raw_value, from_slice_view, from_str_view, from_value, to_value, AsJshiftView,
    AsJshiftViewOwned,
};
#[cfg(feature = "axum")]
pub use axum_ext::{JshiftDoc, JshiftJson, JshiftRejection};
pub use convert::{
    escape_json_key, escape_json_string, from_json_string, write_json_string,
    write_json_string_content, FromJsonSlice, ToJsonBytes,
};
pub use document::SharedDocument;
pub use error::Error;
pub use raw::RawJson;
pub use typed_doc::{
    ArrayElems, JsonDoc, ObjectEntries, ObjectEntry, Presence, RootKind, TypedDoc, TypedDocRef,
    TypedMutator,
};
pub use validate::{
    deny_unknown_keys, deny_unknown_keys_at, require_paths, require_paths_non_null, require_type,
    type_at, validate_closed, validate_open, JsonType,
};
pub use view_list::{
    IndexedValueList, IndexedViewList, ValueList, ValueListIter, ViewList, ViewListIter,
};
pub use index::{
    build_array_index, build_object_key_index, build_structural_index, static_array_prefixes_from_path,
    ArrayIndex, IndexedDocument, ObjectKeyIndex, StructuralIndex,
};
pub use jsonl::{
    for_each_jsonl_doc, for_each_jsonl_line, json_lines, jsonl_docs, jsonl_docs_owned, read_jsonl,
    read_jsonl_indexed, read_line_indexed, write_jsonl_docs, write_jsonl_line, write_jsonl_views,
    JsonLines,
};
pub use multi_json::{
    for_each_jsonl_multi, for_each_jsonl_view_multi, for_each_page_array, for_each_page_doc,
    for_each_page_item_raw, for_each_page_items, read_jsonl_multi, JsonlDecoder, StreamPos,
};
pub use mutate::{
    append_to_array, array_len, delete_index, delete_key, insert_array_element, merge_object_shallow,
    mutate_value, mutate_value_checked, prepend_to_array, rename_key, upsert_at_path,
    upsert_object_key,
};
pub use path::{parse_path, try_parse_path, OwnedPathSegment, Path, PathSegment};
pub use project::{
    estimate_projected_len, estimate_values_len, parse_jmespath_expr, parse_project_path,
    plan_object_fields, plan_prefers_parallel, project, project_auto_indexed, project_each,
    project_each_indexed, project_indexed, project_indexed_auto, project_indexed_prepare,
    project_into, project_jmespath, project_jsonl_write, project_jsonl_write_indexed,
    project_object_fields, project_object_fields_each, project_object_fields_each_indexed,
    project_object_fields_jsonl_write, project_parallel_auto, project_paths, project_write,
    projected_len, select_from_project_path, ArraySelect, CmpOp, CountingSink, HashField,
    MissingPolicy, ObjectSelect, ProjectPathSegment, ProjectPlan, ProjectStyle, SelectExpr,
    Transform, TransformPipeline, WriteSink,
};
#[cfg(feature = "parallel")]
pub use project::{project_indexed_parallel, project_object_fields_parallel, project_parallel};
pub use scan::find_value;
pub use view::{
    build_schema_bytes, from_jshift_bytes, project_as_view, project_view_collect, project_view_each,
    read_view, read_view_at, read_view_at_opt, write_view, write_view_at, write_view_at_closed,
    write_view_at_closed_opt, write_view_at_open, write_view_at_opt, JsonView,
};

#[cfg(feature = "derive")]
pub use jshift_derive::JsonMutatorSchema;

// Derive macro shares the `JsonView` name (macro namespace) with the trait.
// `#[derive(JsonView)]` and `T: JsonView` both work with `use jshift::JsonView`.
#[cfg(feature = "derive")]
#[doc(inline)]
pub use jshift_derive::JsonView;

#[cfg(test)]
mod tests {
    extern crate self as jshift;
    use super::*;

    #[test]
    fn test_find_simple_values() {
        let json = b"{\"a\": 123, \"b\": \"hello\", \"c\": true}";

        assert_eq!(find_value(json, &parse_path("a")), Ok(&b"123"[..]));
        assert_eq!(find_value(json, &parse_path("b")), Ok(&b"\"hello\""[..]));
        assert_eq!(find_value(json, &parse_path("c")), Ok(&b"true"[..]));
        assert_eq!(find_value(json, &parse_path("d")), Err(Error::PathNotFound));
    }

    #[test]
    fn test_find_nested_values() {
        let json = b"{\"metadata\": {\"version\": 1, \"author\": \"farmer\"}, \"data\": [1,2,3]}";

        assert_eq!(
            find_value(json, &parse_path("metadata.version")),
            Ok(&b"1"[..])
        );
        assert_eq!(
            find_value(json, &parse_path("metadata.author")),
            Ok(&b"\"farmer\""[..])
        );
        assert_eq!(
            find_value(json, &parse_path("data")),
            Ok(&b"[1,2,3]"[..])
        );
    }

    #[test]
    fn test_mutate_equal_size() {
        let mut json = b"{\"a\": 123, \"b\": \"hello\"}".to_vec();
        mutate_value(&mut json, &parse_path("a"), b"999").unwrap();
        assert_eq!(json, b"{\"a\": 999, \"b\": \"hello\"}");
    }

    #[test]
    fn test_mutate_smaller_size() {
        let mut json = b"{\"a\": 12345, \"b\": \"hello\"}".to_vec();
        mutate_value(&mut json, &parse_path("a"), b"9").unwrap();
        assert_eq!(json, b"{\"a\": 9, \"b\": \"hello\"}");
    }

    #[test]
    fn test_mutate_larger_size() {
        let mut json = b"{\"a\": 1, \"b\": \"hello\"}".to_vec();
        mutate_value(&mut json, &parse_path("a"), b"99999").unwrap();
        assert_eq!(json, b"{\"a\": 99999, \"b\": \"hello\"}");
    }

    #[test]
    fn test_mutate_nested() {
        let mut json = b"{\"meta\": {\"ver\": 1}, \"data\": true}".to_vec();
        mutate_value(&mut json, &parse_path("meta.ver"), b"100").unwrap();
        assert_eq!(json, b"{\"meta\": {\"ver\": 100}, \"data\": true}");
    }

    #[test]
    fn test_array_indexing() {
        let json = b"{\"data\": [{\"id\": 1}, {\"id\": 2}], \"tags\": [\"a\", \"b\"]}";

        assert_eq!(find_value(json, &parse_path("data[0].id")), Ok(&b"1"[..]));
        assert_eq!(find_value(json, &parse_path("data[1].id")), Ok(&b"2"[..]));
        assert_eq!(find_value(json, &parse_path("tags[1]")), Ok(&b"\"b\""[..]));
        assert_eq!(
            find_value(json, &parse_path("tags[2]")),
            Err(Error::IndexOutOfBounds { index: 2 })
        );
    }

    #[test]
    fn test_array_append_raw() {
        let mut json = b"{\"list\": []}".to_vec();
        append_to_array(&mut json, &parse_path("list"), b"1").unwrap();
        assert_eq!(json, b"{\"list\": [1]}");

        append_to_array(&mut json, &parse_path("list"), b"2").unwrap();
        assert_eq!(json, b"{\"list\": [1,2]}");
    }

    #[test]
    fn test_array_prepend_and_insert() {
        let mut json = b"{\"list\": []}".to_vec();
        prepend_to_array(&mut json, &parse_path("list"), b"1").unwrap();
        assert_eq!(json, b"{\"list\": [1]}");
        prepend_to_array(&mut json, &parse_path("list"), b"0").unwrap();
        assert_eq!(json, b"{\"list\": [0,1]}");
        insert_array_element(&mut json, &parse_path("list"), 1, b"x").unwrap();
        assert_eq!(json, b"{\"list\": [0,x,1]}");
        insert_array_element(&mut json, &parse_path("list"), 3, b"9").unwrap(); // append
        assert_eq!(json, b"{\"list\": [0,x,1,9]}");
        assert!(matches!(
            insert_array_element(&mut json, &parse_path("list"), 99, b"z"),
            Err(Error::PathNotFound)
        ));
    }

    #[test]
    fn test_array_prepend_insert_nested_path() {
        let mut json = br#"{"a":{"b":[10,30],"c":true}}"#.to_vec();
        let path = parse_path("a.b");
        insert_array_element(&mut json, &path, 1, b"20").unwrap();
        assert_eq!(find_value(&json, &parse_path("a.b[1]")).unwrap(), b"20");
        assert_eq!(array_len(&json, &path).unwrap(), 3);
        prepend_to_array(&mut json, &path, b"5").unwrap();
        assert_eq!(find_value(&json, &parse_path("a.b[0]")).unwrap(), b"5");
        assert_eq!(array_len(&json, &path).unwrap(), 4);
        // sibling key preserved
        assert_eq!(find_value(&json, &parse_path("a.c")).unwrap(), b"true");
    }

    #[test]
    fn test_array_len() {
        let json = b"{\"empty\": [], \"list\": [1, 2, 3]}";
        assert_eq!(array_len(json, &parse_path("empty")), Ok(0));
        assert_eq!(array_len(json, &parse_path("list")), Ok(3));
    }

    #[test]
    fn test_upsert_object_key() {
        let mut json = b"{\"a\": 1}".to_vec();
        // Insert new key
        upsert_object_key(&mut json, &[], "b", b"2").unwrap();
        assert_eq!(json, b"{\"a\": 1,\"b\":2}");

        // Update existing key
        upsert_object_key(&mut json, &[], "a", b"99").unwrap();
        assert_eq!(json, b"{\"a\": 99,\"b\":2}");
    }

    #[test]
    fn test_delete_key() {
        let mut json = b"{\"a\": 1, \"b\": 2, \"c\": 3}".to_vec();
        delete_key(&mut json, &[], "b").unwrap();
        // Preceding-comma delete + ws expand: space before removed comma is trimmed.
        assert_eq!(json, b"{\"a\": 1, \"c\": 3}");

        delete_key(&mut json, &[], "a").unwrap();
        // First-member delete: no leftover space after `{`.
        assert_eq!(json, b"{\"c\": 3}");

        delete_key(&mut json, &[], "c").unwrap();
        // Sole member: collapses to empty object without interior spaces.
        assert_eq!(json, b"{}");
    }

    #[test]
    fn test_delete_index() {
        let mut json = b"[10, 20, 30]".to_vec();
        delete_index(&mut json, &[], 1).unwrap();
        assert_eq!(json, b"[10, 30]");

        delete_index(&mut json, &[], 0).unwrap();
        assert_eq!(json, b"[30]");

        delete_index(&mut json, &[], 0).unwrap();
        assert_eq!(json, b"[]");
    }

    #[test]
    fn test_pretty_delete_trims_whitespace() {
        let mut json = br#"{ "a" : 1 , "b" : 2 }"#.to_vec();
        delete_key(&mut json, &[], "a").unwrap();
        assert_eq!(json, br#"{"b" : 2 }"#);
        delete_key(&mut json, &[], "b").unwrap();
        assert_eq!(json, br#"{}"#);

        let mut json = br#"[ 1 , 2 , 3 ]"#.to_vec();
        delete_index(&mut json, &[], 1).unwrap();
        assert_eq!(json, br#"[ 1, 3 ]"#);
        delete_index(&mut json, &[], 0).unwrap();
        assert_eq!(json, br#"[3 ]"#);
        delete_index(&mut json, &[], 0).unwrap();
        assert_eq!(json, br#"[]"#);

        // Multiline: no blank-line residue after member drop.
        let mut json = b"{\n  \"a\": 1,\n  \"b\": 2\n}".to_vec();
        delete_key(&mut json, &[], "a").unwrap();
        assert_eq!(json, b"{\"b\": 2\n}");
    }

    #[cfg(feature = "derive")]
    #[derive(JsonMutatorSchema)]
    struct Config {
        #[json(path = "metadata.version")]
        version: u32,
        #[json(path = "user.score")]
        score: f64,
        #[json(path = "user.name")]
        name: String,
        #[json(path = "user.tags")]
        tags: Vec<String>,
    }

    #[cfg(feature = "derive")]
    #[test]
    fn test_procedural_macro() {
        let mut json = b"{\"metadata\": {\"version\": 1}, \"user\": {\"score\": 9.5, \"name\": \"farmer\", \"tags\": [\"rust\", \"fast\"]}}".to_vec();

        let config = Config::read_from_json(&json).unwrap();
        assert_eq!(config.version, 1);
        assert_eq!(config.score, 9.5);
        assert_eq!(config.name, "farmer");
        assert_eq!(
            config.tags,
            vec!["rust".to_string(), "fast".to_string()]
        );

        {
            let mut mutator = Config::mutator(&mut json);
            mutator.set_version(&2).unwrap();
            mutator.set_score(&99.9).unwrap();
            mutator.set_name("new_name").unwrap();
            mutator.append_tags("cool").unwrap();
            mutator.prepend_tags("first").unwrap();
            mutator.insert_tags(1, "mid").unwrap();
        }

        let updated = Config::read_from_json(&json).unwrap();
        assert_eq!(updated.version, 2);
        assert_eq!(updated.score, 99.9);
        assert_eq!(updated.name, "new_name");
        assert_eq!(
            updated.tags,
            vec![
                "first".to_string(),
                "mid".to_string(),
                "rust".to_string(),
                "fast".to_string(),
                "cool".to_string()
            ]
        );

        // delete_<field>_at on Vec; delete_<field> removes object member
        {
            let mut mutator = Config::mutator(&mut json);
            mutator.delete_tags_at(1).unwrap(); // drop "mid"
            mutator.delete_name().unwrap();
        }
        // name is required → PathNotFound after delete
        assert!(Config::read_from_json(&json).is_err());
        let tags_slice = find_value(&json, &parse_path("user.tags")).unwrap();
        let tags: Vec<String> = FromJsonSlice::from_json_slice(tags_slice).unwrap();
        assert_eq!(
            tags,
            vec![
                "first".to_string(),
                "rust".to_string(),
                "fast".to_string(),
                "cool".to_string()
            ]
        );
        assert!(find_value(&json, &parse_path("user.name")).is_err());
    }

    #[cfg(feature = "derive")]
    #[test]
    fn test_mutator_delete_nested_and_vec_at() {
        #[derive(JsonMutatorSchema)]
        struct Nested {
            #[json(path = "meta.status")]
            status: String,
            #[json(path = "meta.labels")]
            labels: Vec<String>,
        }

        let mut json = br#"{"meta":{"status":"live","labels":["a","b","c"],"keep":1}}"#.to_vec();
        let mut m = Nested::mutator(&mut json);
        m.delete_labels_at(0).unwrap();
        m.delete_status().unwrap();
        assert_eq!(
            &json[..],
            br#"{"meta":{"labels":["b","c"],"keep":1}}"#
        );
    }

    #[test]
    fn test_escape_json_string() {
        assert_eq!(escape_json_string("plain"), br#""plain""#);
        assert_eq!(escape_json_string(r#"say "hi""#), br#""say \"hi\"""#);
        assert_eq!(escape_json_string("a\\b"), br#""a\\b""#);
        assert_eq!(escape_json_string("a\nb\tc"), br#""a\nb\tc""#);
        assert_eq!(escape_json_string("\u{0001}"), br#""\u0001""#);
    }

    #[test]
    fn test_to_json_bytes_escapes_strings() {
        assert_eq!(r#"he"llo"#.to_json_bytes(), br#""he\"llo""#);
        assert_eq!(String::from("x\ny").to_json_bytes(), br#""x\ny""#);
    }

    #[test]
    fn test_upsert_escapes_keys() {
        let mut json = b"{}".to_vec();
        upsert_object_key(&mut json, &[], r#"a"b"#, b"1").unwrap();
        assert_eq!(json, br#"{"a\"b":1}"#);

        // Path matching compares raw key bytes inside quotes (escaped form).
        assert_eq!(find_value(&json, &parse_path(r#"a\"b"#)), Ok(&b"1"[..]));
    }

    #[test]
    fn test_upsert_updates_escaped_key_without_duplicate() {
        let mut json = b"{}".to_vec();
        upsert_object_key(&mut json, &[], r#"a"b"#, b"1").unwrap();
        upsert_object_key(&mut json, &[], r#"a"b"#, b"2").unwrap();
        assert_eq!(json, br#"{"a\"b":2}"#);
        // Must not have duplicated the key (escaped form is 4 bytes: a \ " b).
        let needle = br#"a\"b"#;
        assert_eq!(
            json.windows(needle.len()).filter(|w| *w == needle).count(),
            1
        );
    }

    #[test]
    fn test_delete_key_with_escapes() {
        let mut json = br#"{"plain":1,"a\"b":2,"c\\d":3}"#.to_vec();
        delete_key(&mut json, &[], r#"a"b"#).unwrap();
        assert_eq!(json, br#"{"plain":1,"c\\d":3}"#);

        delete_key(&mut json, &[], r#"c\d"#).unwrap();
        assert_eq!(json, br#"{"plain":1}"#);

        // First key with escapes-only remaining siblings already covered above.
        let mut json2 = br#"{"x\"y":10,"z":20}"#.to_vec();
        delete_key(&mut json2, &[], r#"x"y"#).unwrap();
        assert_eq!(json2, br#"{"z":20}"#);
    }

    #[test]
    fn test_parse_path_hardens_invalid_segments() {
        assert_eq!(
            parse_path("a.b[0].c"),
            vec![
                PathSegment::Key("a"),
                PathSegment::Key("b"),
                PathSegment::Index(0),
                PathSegment::Key("c"),
            ]
        );
        // Empty keys from dots are skipped.
        assert_eq!(
            parse_path("..a..b."),
            vec![PathSegment::Key("a"), PathSegment::Key("b")]
        );
        // Unclosed bracket stops parsing (does not emit a fake key of the rest).
        assert_eq!(parse_path("a[1"), vec![PathSegment::Key("a")]);
        // Non-numeric index is skipped.
        assert_eq!(
            parse_path("a[foo].b"),
            vec![PathSegment::Key("a"), PathSegment::Key("b")]
        );
        // Empty brackets skipped.
        assert_eq!(
            parse_path("a[].b"),
            vec![PathSegment::Key("a"), PathSegment::Key("b")]
        );
    }

    #[test]
    fn test_from_json_slice_unescapes_strings() {
        assert_eq!(
            String::from_json_slice(br#""say \"hi\"""#).as_deref(),
            Some(r#"say "hi""#)
        );
        assert_eq!(
            String::from_json_slice(br#""a\\b\n""#).as_deref(),
            Some("a\\b\n")
        );
        assert_eq!(
            String::from_json_slice(br#""\u0041""#).as_deref(),
            Some("A")
        );
    }

    #[test]
    fn test_escape_json_key_matches_on_wire_form() {
        assert_eq!(escape_json_key(r#"a"b"#), r#"a\"b"#);
        assert_eq!(escape_json_key("a\\b"), r#"a\\b"#);
        assert_eq!(escape_json_key("a\nb"), r#"a\nb"#);
    }

    #[test]
    fn test_mutate_via_to_json_bytes_keeps_valid_json() {
        let mut json = br#"{"msg":"old"}"#.to_vec();
        let bytes = r#"say "hi""#.to_json_bytes();
        mutate_value(&mut json, &parse_path("msg"), &bytes).unwrap();
        assert_eq!(json, br#"{"msg":"say \"hi\""}"#);
        assert_eq!(
            find_value(&json, &parse_path("msg")),
            Ok(&br#""say \"hi\"""#[..])
        );
    }

    #[test]
    fn test_nested_upsert_delete() {
        let mut json = br#"{"outer":{"inner":1}}"#.to_vec();
        upsert_object_key(&mut json, &parse_path("outer"), "x", b"true").unwrap();
        assert_eq!(
            find_value(&json, &parse_path("outer.x")),
            Ok(&b"true"[..])
        );
        delete_key(&mut json, &parse_path("outer"), "inner").unwrap();
        assert_eq!(json, br#"{"outer":{"x":true}}"#);
    }

    #[test]
    fn test_array_ops_nested() {
        let mut json = br#"{"a":{"b":[1,2]}}"#.to_vec();
        assert_eq!(array_len(&json, &parse_path("a.b")), Ok(2));
        append_to_array(&mut json, &parse_path("a.b"), b"3").unwrap();
        assert_eq!(array_len(&json, &parse_path("a.b")), Ok(3));
        delete_index(&mut json, &parse_path("a.b"), 0).unwrap();
        assert_eq!(find_value(&json, &parse_path("a.b[0]")), Ok(&b"2"[..]));
        assert_eq!(find_value(&json, &parse_path("a.b[1]")), Ok(&b"3"[..]));
    }

    #[test]
    fn test_strings_with_escaped_quotes_inside_values() {
        let json = br#"{"k":"before \"mid\" after","n":1}"#;
        assert_eq!(
            find_value(json, &parse_path("k")),
            Ok(&br#""before \"mid\" after""#[..])
        );
        assert_eq!(find_value(json, &parse_path("n")), Ok(&b"1"[..]));
    }

    #[test]
    fn test_type_mismatch_and_errors() {
        let json = br#"{"a":1,"b":[1]}"#;
        assert_eq!(
            array_len(json, &parse_path("a")),
            Err(Error::TypeMismatch {
                expected: "array",
                found: "primitive/object"
            })
        );
        let mut json = br#"{"a":1}"#.to_vec();
        assert_eq!(
            append_to_array(&mut json, &parse_path("a"), b"2"),
            Err(Error::TypeMismatch {
                expected: "array",
                found: "primitive/object"
            })
        );
        assert_eq!(
            delete_key(&mut json, &[], "missing"),
            Err(Error::PathNotFound)
        );
    }

    #[test]
    fn test_empty_buffer_and_empty_payload_are_errors() {
        let mut empty = Vec::new();
        assert!(matches!(
            mutate_value(&mut empty, &[], b"1"),
            Err(Error::InvalidJsonSyntax { .. })
        ));
        assert!(matches!(
            append_to_array(&mut empty, &[], b"1"),
            Err(Error::InvalidJsonSyntax { .. } | Error::TypeMismatch { .. })
        ));
        assert!(matches!(
            upsert_object_key(&mut empty, &[], "a", b"1"),
            Err(Error::InvalidJsonSyntax { .. } | Error::TypeMismatch { .. })
        ));

        let mut json = br#"{"a":1}"#.to_vec();
        assert!(matches!(
            mutate_value(&mut json, &parse_path("a"), b""),
            Err(Error::InvalidJsonSyntax { .. })
        ));
        assert!(matches!(
            append_to_array(&mut json, &parse_path("a"), b""),
            Err(Error::InvalidJsonSyntax { .. } | Error::TypeMismatch { .. })
        ));
        // Empty payload rejected before type checks when path is object root.
        let mut obj = br#"{}"#.to_vec();
        assert!(matches!(
            upsert_object_key(&mut obj, &[], "k", b""),
            Err(Error::InvalidJsonSyntax { .. })
        ));
    }

    #[test]
    fn test_unescape_rejects_controls_and_lone_surrogates() {
        assert_eq!(String::from_json_slice(b"\"\t\""), None); // raw tab
        assert_eq!(String::from_json_slice(br#""\uDC00""#), None); // lone low surrogate
        // Surrogate pair for U+1F600 😀
        assert_eq!(
            String::from_json_slice(br#""\uD83D\uDE00""#).as_deref(),
            Some("\u{1F600}")
        );
    }

    #[test]
    fn test_find_on_empty_and_whitespace() {
        assert!(matches!(
            find_value(b"", &parse_path("a")),
            Err(Error::InvalidJsonSyntax { .. })
        ));
        assert!(matches!(
            find_value(b"   ", &parse_path("a")),
            Err(Error::InvalidJsonSyntax { .. })
        ));
        assert_eq!(find_value(b"{}", &[]), Ok(&b"{}"[..]));
    }

    #[test]
    fn test_escaped_slash_and_quotes_in_strings() {
        let json = br#"{"p":"a\/b","q":"\\"}"#;
        assert_eq!(find_value(json, &parse_path("p")), Ok(&br#""a\/b""#[..]));
        assert_eq!(find_value(json, &parse_path("q")), Ok(&br#""\\""#[..]));
        assert_eq!(String::from_json_slice(br#""a\/b""#).as_deref(), Some("a/b"));
    }

    // --- Wave B / hardening coverage -----------------------------------------

    #[test]
    fn test_try_parse_path_rejects_bad_segments() {
        assert!(matches!(
            try_parse_path("a[x]"),
            Err(Error::InvalidPath { .. })
        ));
        assert!(matches!(
            try_parse_path("a[]"),
            Err(Error::InvalidPath { .. })
        ));
        assert!(matches!(
            try_parse_path("a[1"),
            Err(Error::InvalidPath { .. })
        ));
        assert!(matches!(
            try_parse_path("a[1a]"),
            Err(Error::InvalidPath { .. })
        ));
        // Lenient parse_path still drops bad index without error.
        assert_eq!(
            parse_path("a[x].b"),
            vec![PathSegment::Key("a"), PathSegment::Key("b")]
        );
        assert_eq!(
            try_parse_path("a[0].b").unwrap(),
            vec![
                PathSegment::Key("a"),
                PathSegment::Index(0),
                PathSegment::Key("b")
            ]
        );
    }

    #[test]
    fn test_delete_key_tracks_forward_key_start_not_reverse_scan() {
        // Multiple escaped quotes: reverse-scan would stop on the wrong `"`.
        let mut json = br#"{"a\"b\"c":1,"z":2}"#.to_vec();
        delete_key(&mut json, &[], r#"a"b"c"#).unwrap();
        assert_eq!(json, br#"{"z":2}"#);

        let mut json = br#"{"first":0,"x\\\"y":1,"last":2}"#.to_vec();
        delete_key(&mut json, &[], r#"x\"y"#).unwrap();
        assert_eq!(
            find_value(&json, &parse_path("first")),
            Ok(&b"0"[..])
        );
        assert_eq!(find_value(&json, &parse_path("last")), Ok(&b"2"[..]));
        assert!(find_value(&json, &parse_path(r#"x\\\"y"#)).is_err());
    }

    #[test]
    fn test_from_json_string_requires_quotes() {
        assert_eq!(from_json_string(br#""ok""#).as_deref(), Some("ok"));
        assert_eq!(from_json_string(b"ok"), None);
        assert_eq!(from_json_string(br#""a\nb""#).as_deref(), Some("a\nb"));
    }

    #[test]
    fn test_mutate_value_checked_sniffs_value() {
        let mut json = br#"{"n":1,"s":"a"}"#.to_vec();
        mutate_value_checked(&mut json, &parse_path("n"), b"99").unwrap();
        mutate_value_checked(&mut json, &parse_path("s"), br#""hi""#).unwrap();
        assert_eq!(json, br#"{"n":99,"s":"hi"}"#);

        assert!(matches!(
            mutate_value_checked(&mut json, &parse_path("n"), b"1,2"),
            Err(Error::InvalidJsonSyntax { .. })
        ));
        assert!(matches!(
            mutate_value_checked(&mut json, &parse_path("n"), b"{"),
            Err(Error::InvalidJsonSyntax { .. })
        ));
        assert!(matches!(
            mutate_value_checked(&mut json, &parse_path("n"), b""),
            Err(Error::InvalidJsonSyntax { .. })
        ));
        // Raw mutate_value still accepts non-JSON garbage (documented contract).
        mutate_value(&mut json, &parse_path("n"), b"@@@").unwrap();
        assert!(json.windows(3).any(|w| w == b"@@@"));
    }

    #[test]
    fn test_container_delimiter_and_empty_primitive() {
        // Truncated array span should not panic.
        let mut bad = br#"{"a":[1,2}"#.to_vec(); // missing ]
        // find may still locate something depending on skip_value balance — append
        // must not panic even if structure is wrong.
        let _ = append_to_array(&mut bad, &parse_path("a"), b"3");

        // Empty primitive after colon.
        let json = br#"{"a":,"b":1}"#;
        assert!(matches!(
            find_value(json, &parse_path("a")),
            Err(Error::InvalidJsonSyntax { .. })
        ));
    }

    #[test]
    fn test_mismatched_container_on_array_ops() {
        // Value is a number, not array.
        let json = br#"{"a":1}"#;
        assert!(matches!(
            array_len(json, &parse_path("a")),
            Err(Error::TypeMismatch { .. })
        ));
    }

    // --- Wave C --------------------------------------------------------------

    #[test]
    fn test_owned_path_reuse() {
        let path = Path::parse("user.score");
        let json = br#"{"user":{"score":9.5}}"#;
        assert_eq!(path.find(json).unwrap(), b"9.5");
        assert_eq!(
            find_value(json, &path.borrowed()).unwrap(),
            b"9.5"
        );
        let mut json = json.to_vec();
        path.mutate(&mut json, b"10").unwrap();
        assert_eq!(path.find(&json).unwrap(), b"10");
    }

    #[test]
    fn test_json_pointer() {
        let path = Path::from_json_pointer("/a~1b/0").unwrap();
        assert_eq!(
            path.owned_segments(),
            &[
                OwnedPathSegment::Key("a/b".into()),
                OwnedPathSegment::Index(0),
            ]
        );
        let path = Path::from_json_pointer("/tags/1").unwrap();
        let json = br#"{"tags":["x","y"]}"#;
        assert_eq!(path.find(json).unwrap(), br#""y""#);
        assert!(Path::from_json_pointer("no-slash").is_err());
        assert!(Path::from_json_pointer("").unwrap().is_empty());
    }

    #[test]
    fn test_option_null_and_missing() {
        assert_eq!(
            Option::<u32>::from_json_slice(b"null"),
            Some(None)
        );
        assert_eq!(Option::<u32>::from_json_slice(b"3"), Some(Some(3)));
        assert_eq!(Option::<u32>::from_json_slice(b"nope"), None);
        assert_eq!((None::<u32>).to_json_bytes(), b"null");
        assert_eq!(Some(7u32).to_json_bytes(), b"7");
    }

    #[cfg(feature = "derive")]
    #[test]
    fn test_option_null_and_missing_derive() {
        #[derive(JsonMutatorSchema)]
        struct Row {
            #[json(path = "a")]
            a: Option<u32>,
            #[json(path = "b")]
            b: Option<String>,
        }

        let json = br#"{"a":null,"b":"hi"}"#;
        let row = Row::read_from_json(json).unwrap();
        assert_eq!(row.a, None);
        assert_eq!(row.b.as_deref(), Some("hi"));

        let json = br#"{"b":"only"}"#;
        let row = Row::read_from_json(json).unwrap();
        assert_eq!(row.a, None); // missing path
        assert_eq!(row.b.as_deref(), Some("only"));

        let mut json = br#"{"a":1}"#.to_vec();
        let mut m = Row::mutator(&mut json);
        m.set_a(&None::<u32>).unwrap();
        assert_eq!(find_value(&json, &parse_path("a")).unwrap(), b"null");
    }

    #[test]
    #[cfg(feature = "derive")]
    fn test_json_default_attr_derive() {
        #[derive(JsonMutatorSchema)]
        struct WithDefault {
            #[json(path = "id")]
            id: u64,
            #[json(path = "score", default)]
            score: u64,
        }

        let row = WithDefault::read_from_json(br#"{"id":7}"#).unwrap();
        assert_eq!(row.id, 7);
        assert_eq!(row.score, 0); // Default::default()

        let row = WithDefault::read_from_json(br#"{"id":1,"score":42}"#).unwrap();
        assert_eq!(row.score, 42);
    }

    #[test]
    fn test_rename_merge_validate() {
        let mut json = br#"{"old":1,"keep":true}"#.to_vec();
        rename_key(&mut json, &[], "old", "new").unwrap();
        merge_object_shallow(&mut json, &[], br#"{"extra":9}"#).unwrap();
        assert_eq!(find_value(&json, &parse_path("new")).unwrap(), b"1");
        assert_eq!(find_value(&json, &parse_path("extra")).unwrap(), b"9");
        require_paths(&json, &["new", "keep", "extra"]).unwrap();
        validate_closed(&json, &["new", "keep", "extra"]).unwrap();
        assert!(validate_closed(&json, &["new", "keep"]).is_err());
    }

    #[cfg(feature = "derive")]
    #[test]
    fn test_derive_nested_view_and_map() {
        use std::collections::{BTreeMap, HashMap};

        #[derive(Debug, PartialEq, JsonView)]
        struct Meta {
            #[json(path = "rank")]
            rank: u64,
            #[json(path = "sku")]
            sku: String,
        }

        #[derive(Debug, PartialEq, JsonView)]
        struct Product {
            #[json(path = "id")]
            id: u64,
            #[json(path = "meta")]
            meta: Meta,
            #[json(path = "scores")]
            scores: HashMap<String, u64>,
            #[json(path = "labels")]
            labels: BTreeMap<String, String>,
        }

        let raw = br#"{"id":9,"meta":{"rank":3,"sku":"A1","noise":true},"scores":{"alice":10,"bob":20},"labels":{"env":"prod"},"extra":1}"#;
        let p = Product::read_from(raw).unwrap();
        assert_eq!(p.id, 9);
        assert_eq!(p.meta.rank, 3);
        assert_eq!(p.meta.sku, "A1");
        assert_eq!(p.scores.get("bob"), Some(&20));
        assert_eq!(p.labels.get("env").map(|s| s.as_str()), Some("prod"));

        let schema = p.to_schema_bytes().unwrap();
        // Nested meta is an object key, not flatten
        assert!(schema.windows(6).any(|w| w == b"\"meta\""));
        assert!(schema.windows(8).any(|w| w == b"\"scores\""));
        assert!(!schema.windows(7).any(|w| w == b"\"extra\""));
        assert!(!schema.windows(7).any(|w| w == b"\"noise\""));

        let mut buf = raw.to_vec();
        let updated = Product {
            id: 9,
            meta: Meta {
                rank: 5,
                sku: "B2".into(),
            },
            scores: {
                let mut m = HashMap::new();
                m.insert("alice".into(), 11);
                m
            },
            labels: p.labels.clone(),
        };
        updated.write_into(&mut buf).unwrap();
        assert_eq!(find_value(&buf, &parse_path("meta.rank")).unwrap(), b"5");
        assert!(find_value(&buf, &parse_path("extra")).is_ok()); // open parent preserves
        // Open nested write: unknown keys inside meta are preserved
        assert!(find_value(&buf, &parse_path("meta.noise")).is_ok());

        // Closed nested write drops child unknowns
        write_view_at_closed(&mut buf, &parse_path("meta"), &updated.meta).unwrap();
        assert!(find_value(&buf, &parse_path("meta.noise")).is_err());
        assert_eq!(find_value(&buf, &parse_path("meta.rank")).unwrap(), b"5");

        // Optional nested
        #[derive(Debug, PartialEq, JsonView)]
        struct Maybe {
            #[json(path = "id")]
            id: u64,
            #[json(path = "meta")]
            meta: Option<Meta>,
        }
        assert!(Maybe::read_from(br#"{"id":1}"#).unwrap().meta.is_none());
        assert_eq!(
            Maybe::read_from(br#"{"id":1,"meta":{"rank":1,"sku":"x"}}"#)
                .unwrap()
                .meta
                .unwrap()
                .sku,
            "x"
        );
    }

    #[test]
    fn test_duplicate_key_policy() {
        let bad = br#"{"a":1,"b":2,"a":3}"#;
        assert!(check_duplicate_keys(bad, DuplicateKeyPolicy::Error).is_err());
        assert!(validate_unique_keys(bad).is_err());

        let first = check_duplicate_keys(bad, DuplicateKeyPolicy::First).unwrap();
        assert!(first.has_duplicates);
        assert_eq!(first.value_span(bad, "a").unwrap(), b"1");
        assert_eq!(first.get("a").unwrap().occurrences, 2);

        let last = check_duplicate_keys(bad, DuplicateKeyPolicy::Last).unwrap();
        assert_eq!(last.value_span(bad, "a").unwrap(), b"3");

        let ok = check_duplicate_keys(br#"{"a":1,"b":2}"#, DuplicateKeyPolicy::Error).unwrap();
        assert!(!ok.has_duplicates);
        validate_unique_keys(br#"{"a":1,"b":2}"#).unwrap();

        assert!(validate_unique_keys_deep(br#"{"ok":1,"nest":{"x":1,"x":2}}"#).is_err());
        assert!(matches!(
            check_duplicate_keys_deep(br#"{}"#, DuplicateKeyPolicy::First),
            Err(Error::InvalidPath { .. })
        ));
    }

    #[cfg(feature = "derive")]
    #[test]
    fn test_derive_byte_flatten() {
        #[derive(Debug, PartialEq, JsonView)]
        struct Meta {
            #[json(path = "created_at")]
            created_at: String,
            #[json(path = "source")]
            source: String,
        }

        #[derive(Debug, PartialEq, JsonView)]
        struct Event {
            #[json(path = "id")]
            id: u64,
            #[json(flatten)]
            meta: Meta,
        }

        let raw = br#"{"id":7,"created_at":"t0","source":"api","noise":true}"#;
        let e = Event::read_from(raw).unwrap();
        assert_eq!(e.id, 7);
        assert_eq!(e.meta.created_at, "t0");
        assert_eq!(e.meta.source, "api");

        // Open write: update flattened field, preserve noise
        let mut buf = raw.to_vec();
        e.meta;
        let updated = Event {
            id: 7,
            meta: Meta {
                created_at: "t1".into(),
                source: "web".into(),
            },
        };
        updated.write_into(&mut buf).unwrap();
        assert_eq!(find_value(&buf, &parse_path("source")).unwrap(), br#""web""#);
        assert!(find_value(&buf, &parse_path("noise")).is_ok());

        // Schema emit is flat (no nested "meta" object)
        let schema = updated.to_schema_bytes().unwrap();
        assert!(schema.windows(4).any(|w| w == b"\"id\""));
        assert!(schema.windows(8).any(|w| w == b"\"source\""));
        assert!(!schema.windows(6).any(|w| w == b"\"meta\""));
        assert!(!schema.windows(7).any(|w| w == b"\"noise\""));

        // Project keep-list includes flattened child paths
        let projected = Event::project_json(raw).unwrap();
        assert!(projected.windows(4).any(|w| w == b"\"id\""));
        assert!(projected.windows(8).any(|w| w == b"\"source\""));
        assert!(!projected.windows(7).any(|w| w == b"\"noise\""));

        // Option flatten: absent child paths → None
        #[derive(Debug, PartialEq, JsonView)]
        struct Maybe {
            #[json(path = "id")]
            id: u64,
            #[json(flatten)]
            meta: Option<Meta>,
        }
        let m = Maybe::read_from(br#"{"id":1}"#).unwrap();
        assert_eq!(m.id, 1);
        assert!(m.meta.is_none());
        let m2 = Maybe::read_from(br#"{"id":1,"source":"x","created_at":"y"}"#).unwrap();
        assert_eq!(m2.meta.unwrap().source, "x");

        // Dual flatten
        #[derive(Debug, PartialEq, JsonView)]
        struct Tags {
            #[json(path = "env")]
            env: String,
        }
        #[derive(Debug, PartialEq, JsonView)]
        struct Dual {
            #[json(path = "id")]
            id: u64,
            #[json(flatten)]
            meta: Meta,
            #[json(flatten)]
            tags: Tags,
        }
        let d = Dual::read_from(
            br#"{"id":1,"created_at":"t","source":"s","env":"prod","z":0}"#,
        )
        .unwrap();
        assert_eq!(d.tags.env, "prod");
        assert_eq!(d.meta.source, "s");
    }

    #[cfg(feature = "derive")]
    #[test]
    fn test_derive_externally_tagged_enums() {
        #[derive(Debug, PartialEq, JsonView)]
        enum Status {
            Ready,
            #[json(rename = "in_progress")]
            Running,
            Done,
        }

        #[derive(Debug, PartialEq, JsonView)]
        enum Event {
            Click {
                #[json(path = "x")]
                x: u64,
                #[json(path = "y")]
                y: u64,
            },
            Id(u64),
            Note(String),
        }

        // Unit variants ↔ JSON strings
        assert_eq!(Status::read_from(br#""Ready""#).unwrap(), Status::Ready);
        assert_eq!(
            Status::read_from(br#""in_progress""#).unwrap(),
            Status::Running
        );
        assert_eq!(
            Status::Done.to_schema_bytes().unwrap(),
            br#""Done""#
        );
        assert!(Status::read_from(br#""Unknown""#).is_err());

        // Struct variant ↔ {"Tag":{...}}
        let click = Event::read_from(br#"{"Click":{"x":3,"y":4,"noise":true}}"#).unwrap();
        assert_eq!(click, Event::Click { x: 3, y: 4 });
        let out = Event::Click { x: 3, y: 4 }.to_schema_bytes().unwrap();
        assert_eq!(out, br#"{"Click":{"x":3,"y":4}}"#);

        // Newtype variants
        assert_eq!(
            Event::read_from(br#"{"Id":42}"#).unwrap(),
            Event::Id(42)
        );
        assert_eq!(
            Event::Note("hi".into()).to_schema_bytes().unwrap(),
            br#"{"Note":"hi"}"#
        );

        // Mixed unit + object shapes on one enum
        #[derive(Debug, PartialEq, JsonView)]
        enum Mixed {
            None,
            Value(u64),
        }
        assert_eq!(Mixed::read_from(br#""None""#).unwrap(), Mixed::None);
        assert_eq!(
            Mixed::read_from(br#"{"Value":9}"#).unwrap(),
            Mixed::Value(9)
        );
        assert_eq!(Mixed::None.to_schema_bytes().unwrap(), br#""None""#);
        assert_eq!(
            Mixed::Value(1).to_schema_bytes().unwrap(),
            br#"{"Value":1}"#
        );

        // Internal / adjacent / untagged
        #[derive(Debug, PartialEq, JsonView)]
        #[json(tag = "type")]
        enum InternalEv {
            Ready,
            Click {
                #[json(path = "x")]
                x: u64,
                #[json(path = "y")]
                y: u64,
            },
        }
        assert_eq!(
            InternalEv::read_from(br#"{"type":"Ready"}"#).unwrap(),
            InternalEv::Ready
        );
        assert_eq!(
            InternalEv::read_from(br#"{"type":"Click","x":1,"y":2,"noise":true}"#).unwrap(),
            InternalEv::Click { x: 1, y: 2 }
        );
        assert_eq!(
            InternalEv::Click { x: 1, y: 2 }.to_schema_bytes().unwrap(),
            br#"{"type":"Click","x":1,"y":2}"#
        );

        #[derive(Debug, PartialEq, JsonView)]
        #[json(tag = "t", content = "c")]
        enum Adj {
            Ready,
            Id(u64),
            Click {
                #[json(path = "x")]
                x: u64,
            },
        }
        assert_eq!(Adj::read_from(br#"{"t":"Ready"}"#).unwrap(), Adj::Ready);
        assert_eq!(Adj::read_from(br#"{"t":"Id","c":7}"#).unwrap(), Adj::Id(7));
        assert_eq!(
            Adj::read_from(br#"{"t":"Click","c":{"x":9}}"#).unwrap(),
            Adj::Click { x: 9 }
        );
        assert_eq!(
            Adj::Id(7).to_schema_bytes().unwrap(),
            br#"{"t":"Id","c":7}"#
        );

        #[derive(Debug, PartialEq, JsonView)]
        #[json(untagged)]
        enum Either {
            N(u64),
            S(String),
        }
        assert_eq!(Either::read_from(br#"3"#).unwrap(), Either::N(3));
        assert_eq!(
            Either::read_from(br#""z""#).unwrap(),
            Either::S("z".into())
        );
        assert_eq!(Either::N(3).to_schema_bytes().unwrap(), b"3");

        // Default field name = path when #[json(path)] omitted
        #[derive(Debug, PartialEq, JsonView)]
        enum Point {
            XY { x: i32, y: i32 },
        }
        let p = Point::read_from(br#"{"XY":{"x":-1,"y":2}}"#).unwrap();
        assert_eq!(p, Point::XY { x: -1, y: 2 });
    }

    #[test]
    #[cfg(feature = "derive")]
    fn test_v06_nested_map_collect_schema() {
        #[derive(JsonView)]
        struct Card {
            #[json(path = "id")]
            id: u64,
            #[json(path = "title")]
            title: String,
        }

        let doc = TypedDoc::from_slice(
            br#"{"user":{"id":1,"scores":{"a":10,"b":20}},"items":[{"id":1,"title":"x","blob":9},{"id":2,"title":"y","blob":8}]}"#,
        );

        // NestedView
        let user = doc.nest("user").unwrap();
        assert_eq!(user.get::<u64>("id").unwrap(), 1);
        assert_eq!(user.map::<u64>("scores").unwrap().get("b").unwrap(), 20);

        // Collect policies
        let list = doc.view_list::<Card>("items").unwrap();
        assert!(matches!(
            list.collect(CollectPolicy::Stream).unwrap(),
            Collected::Stream
        ));
        let owned = match list.collect(CollectPolicy::Owned).unwrap() {
            Collected::Owned(v) => v,
            _ => panic!(),
        };
        assert_eq!(owned.len(), 2);
        assert_eq!(owned[0].id, 1);
        let projected = list.collect_projected().unwrap();
        assert_eq!(projected.len(), 2);
        // thin cards drop blob
        assert!(!projected[0].windows(4).any(|w| w == b"blob"));

        // each_field / collect_field
        assert_eq!(list.collect_field::<u64>("id").unwrap(), vec![1, 2]);

        // schema build strips unknowns from open write
        let card = Card {
            id: 9,
            title: "z".into(),
        };
        let schema = card.to_schema_json().unwrap();
        let round: Card = Card::read_from_json(&schema).unwrap();
        assert_eq!(round.id, 9);
        assert_eq!(round.title, "z");
        assert!(!schema.is_empty());
    }

    #[test]
    fn test_upsert_at_path_creates_parents() {
        let mut json = b"{}".to_vec();
        upsert_at_path(&mut json, &parse_path("a.b.c"), b"1").unwrap();
        assert_eq!(find_value(&json, &parse_path("a.b.c")).unwrap(), b"1");
        serde_json::from_slice::<serde_json::Value>(&json).unwrap();

        // Update existing leaf.
        upsert_at_path(&mut json, &parse_path("a.b.c"), b"2").unwrap();
        assert_eq!(find_value(&json, &parse_path("a.b.c")).unwrap(), b"2");

        // Array terminal: append when idx == len.
        let mut json = br#"{"list":[0]}"#.to_vec();
        upsert_at_path(&mut json, &parse_path("list[1]"), b"9").unwrap();
        assert_eq!(find_value(&json, &parse_path("list[1]")).unwrap(), b"9");
    }

    #[cfg(feature = "derive")]
    #[test]
    fn test_derive_uses_static_paths() {
        // Compile-time path constants are exercised by any derive test; this
        // additionally covers nested paths without re-parse regressions.
        #[derive(JsonMutatorSchema)]
        struct Nested {
            #[json(path = "meta.ver")]
            ver: u32,
            #[json(path = "tags[0]")]
            first_tag: String,
        }
        let mut json = br#"{"meta":{"ver":1},"tags":["a","b"]}"#.to_vec();
        let n = Nested::read_from_json(&json).unwrap();
        assert_eq!(n.ver, 1);
        assert_eq!(n.first_tag, "a");
        Nested::mutator(&mut json).set_ver(&2).unwrap();
        assert_eq!(find_value(&json, &parse_path("meta.ver")).unwrap(), b"2");
        // Auto-index inferred from tags[0]
        assert!(Nested::INDEXED_ARRAY_PATHS.contains(&"tags"));
        let n2 = Nested::read_from_json_indexed(&json).unwrap();
        assert_eq!(n2.first_tag, "a");
        assert_eq!(Nested::FIELD_PATHS, &["meta.ver", "tags[0]"]);
    }

    #[cfg(feature = "derive")]
    #[test]
    fn test_derive_jmes_project_and_read() {
        #[derive(JsonMutatorSchema)]
        struct Card {
            #[json(path = "id")]
            id: u64,
            #[json(path = "title", jmes = "title")]
            title: String,
            #[json(path = "price", jmes = "variants[0].price")]
            price: String,
        }

        let json = br#"{"id":1,"title":"Hat","variants":[{"price":"9.99"},{"price":"1.00"}],"noise":true}"#;
        let c = Card::read_from_json(json).unwrap();
        assert_eq!(c.id, 1);
        assert_eq!(c.title, "Hat");
        assert_eq!(c.price, "9.99");

        let slim = Card::project_json(json).unwrap();
        let v: serde_json::Value = serde_json::from_slice(&slim).unwrap();
        assert_eq!(v["id"], 1);
        assert_eq!(v["title"], "Hat");
        assert_eq!(v["price"], "9.99");
        assert!(v.get("noise").is_none());
        assert!(v.get("variants").is_none());
        assert!(Card::FIELD_JMES.iter().any(|s| s.contains("variants")));
    }

    #[cfg(feature = "derive")]
    #[test]
    fn test_json_view_trait_generic_pipeline() {
        #[derive(JsonMutatorSchema)]
        struct Card {
            #[json(path = "id")]
            id: u64,
            #[json(path = "title")]
            title: String,
        }

        fn ingest<T: JsonView>(buf: &[u8]) -> Result<T, Error> {
            T::read_from(buf)
        }

        let json = br#"{"id":7,"title":"Hat","images":[1,2,3]}"#;
        let card: Card = ingest(json).unwrap();
        assert_eq!(card.id, 7);
        assert_eq!(card.title, "Hat");

        // write_into preserves unmentioned fields
        let mut buf = json.to_vec();
        let updated = Card {
            id: 8,
            title: "Cap".into(),
        };
        updated.write_into(&mut buf).unwrap();
        assert_eq!(find_value(&buf, &parse_path("id")).unwrap(), b"8");
        assert_eq!(
            find_value(&buf, &parse_path("title")).unwrap(),
            br#""Cap""#
        );
        assert!(
            find_value(&buf, &parse_path("images")).unwrap().starts_with(b"[")
        );

        // SharedDocument + trait
        let shared = SharedDocument::from_slice(json);
        let c2: Card = shared.read().unwrap();
        assert_eq!(c2.id, 7);

        // JSONL
        let lines = br#"{"id":1,"title":"a"}
{"id":2,"title":"b"}
"#;
        let ids: Vec<u64> = read_jsonl::<Card>(lines)
            .map(|r| r.unwrap().id)
            .collect();
        assert_eq!(ids, vec![1, 2]);

        // estimate
        let est = estimate_projected_len(json, Card::FIELD_PATHS).unwrap();
        assert!(est < json.len());
        assert_eq!(Card::estimate_projected_len(json).unwrap(), est);

        // project keep-list
        let slim = Card::project_json(json).unwrap();
        assert_eq!(slim, br#"{"id":7,"title":"Hat"}"#);
        assert_eq!(Card::project_bytes(json).unwrap(), slim);
    }


    #[test]
    fn test_json_view_manual_impl_core_only() {
        // Verifies the trait surface without the derive feature / proc-macro.
        struct IdOnly {
            id: u64,
        }

        impl JsonView for IdOnly {
            fn read_from(json: &[u8]) -> Result<Self, Error> {
                let slice = find_value(json, &parse_path("id"))?;
                let id = u64::from_json_slice(slice).ok_or(Error::TypeMismatch {
                    expected: "u64",
                    found: "invalid format",
                })?;
                Ok(Self { id })
            }

            fn write_into(&self, json: &mut Vec<u8>) -> Result<(), Error> {
                let bytes = self.id.to_json_bytes();
                upsert_at_path(json, &parse_path("id"), &bytes)
            }
        }

        fn ingest<T: JsonView>(buf: &[u8]) -> Result<T, Error> {
            T::read_from(buf)
        }

        let json = br#"{"id":42,"extra":true}"#;
        let v: IdOnly = ingest(json).unwrap();
        assert_eq!(v.id, 42);
        assert_eq!(read_view::<IdOnly>(json).unwrap().id, 42);

        let mut buf = json.to_vec();
        IdOnly { id: 99 }.write_into(&mut buf).unwrap();
        assert_eq!(find_value(&buf, &parse_path("id")).unwrap(), b"99");
        // open document: unmentioned field preserved
        assert_eq!(find_value(&buf, &parse_path("extra")).unwrap(), b"true");

        let shared = SharedDocument::from_slice(json);
        assert_eq!(shared.read::<IdOnly>().unwrap().id, 42);

        let lines = br#"{"id":1}
{"id":2}
"#;
        let ids: Vec<u64> = read_jsonl::<IdOnly>(lines)
            .map(|r| r.unwrap().id)
            .collect();
        assert_eq!(ids, vec![1, 2]);
    }

    #[test]
    fn test_json_lines_and_shared_doc() {
        let buf = b"\n{\"a\":1}\r\n\n{\"a\":2}\n";
        let lines: Vec<&[u8]> = json_lines(buf).collect();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0], br#"{"a":1}"#);
        assert_eq!(lines[1], br#"{"a":2}"#);

        let doc = SharedDocument::from_vec(br#"{"products":[{"id":1},{"id":2}]}"#.to_vec());
        let idx = doc.indexed(&["products"]).unwrap();
        assert_eq!(
            idx.find(&parse_path("products[1].id")).unwrap(),
            b"2"
        );
    }

    #[test]
    fn test_property_safe_ops_keep_serde_json_valid() {
        fn assert_still_valid(json: &[u8]) {
            let v: serde_json::Value = serde_json::from_slice(json).unwrap_or_else(|e| {
                panic!(
                    "serde_json rejected result after op: {e}; bytes={}",
                    String::from_utf8_lossy(json)
                )
            });
            let _ = v.is_object() || v.is_array();
        }

        let mut json = br#"{"a":1,"b":[true,"x"],"c":{"d":null}}"#.to_vec();
        mutate_value_checked(&mut json, &parse_path("a"), b"2").unwrap();
        assert_still_valid(&json);

        let mut json = br#"{"a":1,"b":[1,2,3]}"#.to_vec();
        append_to_array(&mut json, &parse_path("b"), b"4").unwrap();
        delete_index(&mut json, &parse_path("b"), 0).unwrap();
        assert_still_valid(&json);

        let mut json = br#"{"k":1}"#.to_vec();
        upsert_object_key(&mut json, &[], "m", b"true").unwrap();
        delete_key(&mut json, &[], "k").unwrap();
        upsert_object_key(&mut json, &[], r#"q"w"#, b"0").unwrap();
        delete_key(&mut json, &[], r#"q"w"#).unwrap();
        assert_still_valid(&json);

        let mut json = br#"[0,1,2]"#.to_vec();
        delete_index(&mut json, &[], 1).unwrap();
        mutate_value_checked(&mut json, &parse_path("[0]"), b"9").unwrap();
        assert_still_valid(&json);
    }
}