serde-saphyr 0.0.19

YAML (de)serializer for Serde, emphasizing panic-free parsing and good error reporting
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
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
#![forbid(unsafe_code)]
// Options structs expose their fields for now, but callers are expected to migrate to the
// `options!` / `ser_options!` macros. The fields are deprecated to guide downstream
// users, while this crate still legitimately reads them internally.
#![allow(deprecated)]
//! Serialization public API is defined at crate root

pub use anchors::{
    ArcAnchor, ArcRecursion, ArcRecursive, ArcWeakAnchor, RcAnchor, RcRecursion, RcRecursive,
    RcWeakAnchor,
};
pub use de::{Budget, DuplicateKeyPolicy, Error, Options};
pub use de_error::TransformReason;
pub use de_error::CroppedRegion;
pub use de_error::{MessageFormatter, RenderOptions, SnippetMode, UserMessageFormatter};
pub use localizer::{DefaultEnglishLocalizer, ExternalMessage, ExternalMessageSource, Localizer, DEFAULT_ENGLISH_LOCALIZER};
pub use message_formatters::{DefaultMessageFormatter, DeveloperMessageFormatter};
pub use location::{Location, Locations, Span};
pub use long_strings::{FoldStr, FoldString, LitStr, LitString};
pub use ser::{Commented, FlowMap, FlowSeq, SpaceAfter};
pub use spanned::Spanned;

use crate::budget::EnforcingPolicy;
use crate::de::{Ev, Events};
use crate::live_events::LiveEvents;
use crate::parse_scalars::scalar_is_nullish;
pub use crate::serializer_options::SerializerOptions;
use serde::de::DeserializeOwned;
use std::io::Read;

#[cfg(feature = "garde")]
use garde::Validate;
#[cfg(feature = "validator")]
use validator::Validate as ValidatorValidate;

mod anchor_store;
mod anchors;
mod base64;
pub mod budget;
mod de;
mod message_formatters;
mod de_error;
#[path = "localizer.rs"]
pub mod localizer;
#[path = "de/snippet.rs"]
mod de_snipped;
mod live_events;
mod long_strings;
pub mod options;
mod parse_scalars;
pub mod ser;
mod spanned;

#[cfg(any(feature = "garde", feature = "validator"))]
pub mod path_map;

pub mod ser_error;

pub use de::YamlDeserializer as Deserializer;
pub use ser::YamlSerializer as Serializer;

pub use de::{
    with_deserializer_from_reader, with_deserializer_from_reader_with_options,
    with_deserializer_from_slice, with_deserializer_from_slice_with_options,
    with_deserializer_from_str, with_deserializer_from_str_with_options,
};

mod serializer_options;
mod macros;
mod tags;

pub(crate) mod ser_quoting;

mod buffered_input;
mod location;
#[cfg(feature = "robotics")]
pub mod robotics;

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

#[cfg(feature = "figment")]
pub mod figment;
pub(crate) mod ring_reader;
mod wrapping;
mod zmij_format;
// ---------------- Serialization (public API) ----------------

/// Serialize a value to a YAML `String`.
///
/// This is the easiest entry point when you just want a YAML string.
///
/// Example
///
/// ```rust
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Foo { a: i32, b: bool }
///
/// let s = serde_saphyr::to_string(&Foo { a: 1, b: true }).unwrap();
/// assert!(s.contains("a: 1"));
/// ```
pub fn to_string<T: serde::Serialize>(value: &T) -> std::result::Result<String, crate::ser::Error> {
    let mut out = String::new();
    to_fmt_writer(&mut out, value)?;
    Ok(out)
}

/// Serialize a value to a YAML `String`, with [`SerializerOptions`].
///
/// This is like [`to_string`], but lets you control formatting and serialization
/// behavior through the provided `options`.
///
/// Example
///
/// ```rust
/// use serde::Serialize;
/// use serde_saphyr::SerializerOptions;
///
/// #[derive(Serialize)]
/// struct Foo { a: i32, b: bool }
///
/// let options = SerializerOptions::default();
/// let s = serde_saphyr::to_string_with_options(&Foo { a: 1, b: true }, options).unwrap();
/// assert!(s.contains("a: 1"));
/// ```
pub fn to_string_with_options<T: serde::Serialize>(
    value: &T,
    options: SerializerOptions,
) -> std::result::Result<String, crate::ser::Error> {
    let mut out = String::new();
    to_fmt_writer_with_options(&mut out, value, options)?;
    Ok(out)
}

/// Deprecated: use `to_fmt_writer` or `to_io_writer`
/// Kept for a transition release to avoid instant breakage.
#[deprecated(
    since = "0.0.7",
    note = "Use `to_fmt_writer` for `fmt::Write` (String, fmt::Formatter) or `to_io_writer` for files/sockets."
)]
pub fn to_writer<W: std::fmt::Write, T: serde::Serialize>(
    output: &mut W,
    value: &T,
) -> std::result::Result<(), crate::ser::Error> {
    let mut ser = crate::ser::YamlSerializer::new(output);
    value.serialize(&mut ser)
}

/// Serialize a value as YAML into any [`fmt::Write`] target.
pub fn to_fmt_writer<W: std::fmt::Write, T: serde::Serialize>(
    output: &mut W,
    value: &T,
) -> std::result::Result<(), crate::ser::Error> {
    to_fmt_writer_with_options(output, value, SerializerOptions::default())
}

/// Serialize a value as YAML into any [`io::Write`] target.
pub fn to_io_writer<W: std::io::Write, T: serde::Serialize>(
    output: &mut W,
    value: &T,
) -> std::result::Result<(), crate::ser::Error> {
    to_io_writer_with_options(output, value, SerializerOptions::default())
}

/// Serialize a value as YAML into any [`fmt::Write`] target, with options.
/// Options are consumed because anchor generator may be taken from them.
pub fn to_fmt_writer_with_options<W: std::fmt::Write, T: serde::Serialize>(
    output: &mut W,
    value: &T,
    mut options: SerializerOptions,
) -> std::result::Result<(), crate::ser::Error> {
    options.consistent()?;
    let mut ser = crate::ser::YamlSerializer::with_options(output, &mut options);
    value.serialize(&mut ser)
}

/// Serialize a value as YAML into any [`io::Write`] target, with options.
/// Options are consumed because anchor generator may be taken from them.
pub fn to_io_writer_with_options<W: std::io::Write, T: serde::Serialize>(
    output: &mut W,
    value: &T,
    mut options: SerializerOptions,
) -> std::result::Result<(), crate::ser::Error> {
    options.consistent()?;
    struct Adapter<'a, W: std::io::Write> {
        output: &'a mut W,
        last_err: Option<std::io::Error>,
    }
    impl<'a, W: std::io::Write> std::fmt::Write for Adapter<'a, W> {
        fn write_str(&mut self, s: &str) -> std::fmt::Result {
            if let Err(e) = self.output.write_all(s.as_bytes()) {
                self.last_err = Some(e);
                return Err(std::fmt::Error);
            }
            Ok(())
        }
        fn write_char(&mut self, c: char) -> std::fmt::Result {
            let mut buf = [0u8; 4];
            let s = c.encode_utf8(&mut buf);
            self.write_str(s)
        }
    }
    let mut adapter = Adapter {
        output,
        last_err: None,
    };
    let mut ser = crate::ser::YamlSerializer::with_options(&mut adapter, &mut options);
    match value.serialize(&mut ser) {
        Ok(()) => Ok(()),
        Err(e) => {
            if let Some(io_error) = adapter.last_err.take() {
                return Err(crate::ser::Error::from(io_error));
            }
            Err(e)
        }
    }
}

/// Deprecated: use `to_fmt_writer_with_options` for `fmt::Write` or `to_io_writer_with_options` for `io::Write`.
#[deprecated(
    since = "0.0.7",
    note = "Use `to_fmt_writer_with_options` for fmt::Write or `to_io_writer_with_options` for io::Write."
)]
pub fn to_writer_with_options<W: std::fmt::Write, T: serde::Serialize>(
    output: &mut W,
    value: &T,
    options: SerializerOptions,
) -> std::result::Result<(), crate::ser::Error> {
    to_fmt_writer_with_options(output, value, options)
}

/// Deserialize any `T: serde::de::Deserialize<'de>` directly from a YAML string.
///
/// This is the simplest entry point; it parses a single YAML document. If the
/// input contains multiple documents, this returns an error advising to use
/// [`from_multiple`] or [`from_multiple_with_options`].
///
/// This function supports both owned types (like `String`) and borrowed types
/// (like `&str`). For borrowed types, the deserialized value's lifetime is tied
/// to the input string's lifetime.
///
/// **Note**: Borrowing only works for simple plain scalars that don't require
/// any transformation (no multi-line folding, no escape processing). For
/// transformed strings, deserialization to `&str` will fail with a helpful
/// error message suggesting to use `String` or `Cow<str>` instead.
///
/// Example: read a small `Config` structure from a YAML string.
///
/// ```rust
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Config {
///     name: String,
///     enabled: bool,
///     retries: i32,
/// }
///
/// let yaml = r#"
///     name: My Application
///     enabled: true
///     retries: 5
/// "#;
///
/// let cfg: Config = serde_saphyr::from_str(yaml).unwrap();
/// assert!(cfg.enabled);
/// ```
///
/// Example: read a structure with borrowed string fields.
///
/// Borrowed strings are supported when deserializing from an in-memory input (`from_str` / `from_slice`),
/// and only when the scalar exists verbatim in the input (i.e., no escape processing, folding, or other
/// normalization is required). If the YAML scalar requires transformation, deserializing into `&str`
/// fails with an error suggesting `String` or `Cow<str>`.
///
/// Note: reader-based entry points like [`from_reader`] require `DeserializeOwned` and therefore cannot
/// return values that borrow from the input.
///
/// ```rust
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Data<'a> {
///     name: &'a str,
///     value: i32,
/// }
///
/// let yaml = "name: hello\nvalue: 42\n";
///
/// let data: Data = serde_saphyr::from_str(yaml).unwrap();
/// assert_eq!(data.name, "hello");
/// assert_eq!(data.value, 42);
/// ```
pub fn from_str<'de, T>(input: &'de str) -> Result<T, Error>
where
    T: serde::de::Deserialize<'de>,
{
    from_str_with_options(input, Options::default())
}

#[allow(deprecated)]
fn from_str_with_options_impl<'de, T>(input: &'de str, options: Options) -> Result<T, Error>
where
    T: serde::de::Deserialize<'de>,
{
    // Normalize: ignore a single leading UTF-8 BOM if present.
    let input = if let Some(rest) = input.strip_prefix('\u{FEFF}') {
        rest
    } else {
        input
    };

    let with_snippet = options.with_snippet;
    let crop_radius = options.crop_radius;

    let cfg = crate::de::Cfg::from_options(&options);
    // Do not stop at DocumentEnd; we'll probe for trailing content/errors explicitly.
    let mut src = LiveEvents::from_str(
        input,
        options.budget,
        options.budget_report,
        options.budget_report_cb,
        options.alias_limits,
        false,
    );
    let value_res = crate::anchor_store::with_document_scope(|| {
        T::deserialize(crate::de::YamlDeserializer::new(&mut src, cfg))
    });
    let value = match value_res {
        Ok(v) => v,
        Err(e) => {
            if src.synthesized_null_emitted() {
                let err = Error::eof().with_location(src.last_location());
                return Err(maybe_with_snippet(err, input, with_snippet, crop_radius));
            } else {
                return Err(maybe_with_snippet(e, input, with_snippet, crop_radius));
            }
        }
    };

    match src.peek() {
        Ok(Some(_)) => {
            let err = Error::multiple_documents(
                "use from_multiple or from_multiple_with_options",
            )
            .with_location(src.last_location());
            return Err(maybe_with_snippet(err, input, with_snippet, crop_radius));
        }
        Ok(None) => {}
        Err(e) => {
            if src.seen_doc_end() {
                // Trailing garbage after a proper document end marker is ignored.
            } else {
                return Err(maybe_with_snippet(e, input, with_snippet, crop_radius));
            }
        }
    }

    src.finish()
        .map_err(|e| maybe_with_snippet(e, input, with_snippet, crop_radius))?;
    Ok(value)
}

/// Deserialize a single YAML document with configurable [`Options`].
///
/// This function supports both owned types (like `String`) and borrowed types
/// (like `&str`). For borrowed types, the deserialized value's lifetime is tied
/// to the input string's lifetime.
///
/// Example: read a small `Config` with a custom budget and default duplicate-key policy.
///
/// ```rust
/// use serde::Deserialize;
/// use serde_saphyr::DuplicateKeyPolicy;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Config {
///     name: String,
///     enabled: bool,
///     retries: i32,
/// }
///
/// let yaml = r#"
///      name: My Application
///      enabled: true
///      retries: 5
/// "#;
///
/// let options = serde_saphyr::options! {
///     budget: serde_saphyr::budget! {
///         max_anchors: 200,
///     },
///     duplicate_keys: DuplicateKeyPolicy::FirstWins,
/// };
/// let cfg: Config = serde_saphyr::from_str_with_options(yaml, options).unwrap();
/// assert_eq!(cfg.retries, 5);
/// ```
#[allow(deprecated)]
pub fn from_str_with_options<'de, T>(input: &'de str, options: Options) -> Result<T, Error>
where
    T: serde::de::Deserialize<'de>,
{
    from_str_with_options_impl(input, options)
}

/// Deserialize a single YAML document with configurable [`Options`], and also
/// return a map from validation paths to source [`Location`]s.
#[cfg(any(feature = "garde", feature = "validator"))]
#[allow(deprecated)]
fn from_str_with_options_and_path_recorder<T: DeserializeOwned>(
    input: &str,
    options: Options,
) -> Result<(T, crate::path_map::PathRecorder), Error> {
    // Normalize: ignore a single leading UTF-8 BOM if present.
    let input = if let Some(rest) = input.strip_prefix('\u{FEFF}') {
        rest
    } else {
        input
    };

    let with_snippet = options.with_snippet;
    let crop_radius = options.crop_radius;

    let cfg = crate::de::Cfg::from_options(&options);
    let mut src = LiveEvents::from_str(
        input,
        options.budget,
        options.budget_report,
        options.budget_report_cb,
        options.alias_limits,
        false,
    );

    let mut recorder = crate::path_map::PathRecorder::new();

    let value_res = crate::anchor_store::with_document_scope(|| {
        T::deserialize(crate::de::YamlDeserializer::new_with_path_recorder(
            &mut src,
            cfg,
            &mut recorder,
        ))
    });
    let value = match value_res {
        Ok(v) => v,
        Err(e) => {
            if src.synthesized_null_emitted() {
                let err = Error::eof().with_location(src.last_location());
                return Err(maybe_with_snippet(err, input, with_snippet, crop_radius));
            } else {
                return Err(maybe_with_snippet(e, input, with_snippet, crop_radius));
            }
        }
    };

    match src.peek() {
        Ok(Some(_)) => {
            let err = Error::multiple_documents(
                "use from_multiple or from_multiple_with_options",
            )
            .with_location(src.last_location());
            return Err(maybe_with_snippet(err, input, with_snippet, crop_radius));
        }
        Ok(None) => {}
        Err(e) => {
            if src.seen_doc_end() {
                // ignore trailing garbage
            } else {
                return Err(maybe_with_snippet(e, input, with_snippet, crop_radius));
            }
        }
    }

    src.finish()
        .map_err(|e| maybe_with_snippet(e, input, with_snippet, crop_radius))?;

    Ok((value, recorder))
}

/// Deserialize a single YAML document from a YAML string and validate it with `garde`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "garde")]
pub fn from_str_valid<T>(input: &str) -> Result<T, Error>
where
    T: DeserializeOwned + garde::Validate,
    <T as garde::Validate>::Context: Default,
{
    from_str_with_options_valid(input, Options::default())
}

/// Deserialize a single YAML document with configurable [`Options`] and validate it with `garde`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "garde")]
pub fn from_str_with_options_valid<T>(input: &str, options: Options) -> Result<T, Error>
where
    T: DeserializeOwned + garde::Validate,
    <T as garde::Validate>::Context: Default,
{
    let with_snippet = options.with_snippet;
    let crop_radius = options.crop_radius;

    let (v, recorder) = from_str_with_options_and_path_recorder::<T>(input, options)?;
    match Validate::validate(&v) {
        Ok(()) => Ok(v),
        Err(report) => {
            let err = Error::ValidationError {
                report,
                locations: recorder.map,
            };
            Err(maybe_with_snippet(err, input, with_snippet, crop_radius))
        }
    }
}

/// Deserialize a single YAML document with configurable [`Options`] and validate it with `garde` in context [`<T as garde::Validate>::Context`].
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "garde")]
pub fn from_str_with_options_context_valid<T>(
    input: &str,
    options: Options,
    context: &<T as garde::Validate>::Context,
) -> Result<T, Error>
where
    T: DeserializeOwned + garde::Validate,
{
    let with_snippet = options.with_snippet;
    let crop_radius = options.crop_radius;

    let (v, recorder) = from_str_with_options_and_path_recorder::<T>(input, options)?;
    match Validate::validate_with(&v, context) {
        Ok(()) => Ok(v),
        Err(report) => {
            let err = Error::ValidationError {
                report,
                locations: recorder.map,
            };
            Err(maybe_with_snippet(err, input, with_snippet, crop_radius))
        }
    }
}

/// Deserialize multiple YAML documents from a YAML string and validate each with `garde`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "garde")]
pub fn from_multiple_valid<T: DeserializeOwned + garde::Validate>(
    input: &str,
) -> Result<Vec<T>, Error>
where
    <T as garde::Validate>::Context: Default,
{
    from_multiple_with_options_valid(input, Options::default())
}

/// Deserialize multiple YAML documents with configurable [`Options`] and validate each with `garde`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "garde")]
#[allow(deprecated)]
pub fn from_multiple_with_options_valid<T>(input: &str, options: Options) -> Result<Vec<T>, Error>
where
    T: DeserializeOwned + garde::Validate,
    <T as garde::Validate>::Context: Default,
{
    let with_snippet = options.with_snippet;
    let crop_radius = options.crop_radius;

    let cfg = crate::de::Cfg::from_options(&options);
    let mut src = LiveEvents::from_str(
        input,
        options.budget,
        options.budget_report,
        options.budget_report_cb,
        options.alias_limits,
        false,
    );
    let mut values = Vec::new();
    let mut validation_errors: Vec<Error> = Vec::new();

    loop {
        match src.peek()? {
            // Skip documents that are explicit null-like scalars ("", "~", or "null").
            Some(Ev::Scalar {
                value: s, style, ..
            }) if scalar_is_nullish(s, style) => {
                let _ = src.next()?; // consume the null scalar document
                continue;
            }
            Some(_) => {
                let mut recorder = crate::path_map::PathRecorder::new();
                let value_res = crate::anchor_store::with_document_scope(|| {
                    T::deserialize(crate::de::YamlDeserializer::new_with_path_recorder(
                        &mut src,
                        cfg,
                        &mut recorder,
                    ))
                });
                let value = match value_res {
                    Ok(v) => v,
                    Err(e) => return Err(maybe_with_snippet(e, input, with_snippet, crop_radius)),
                };

                match Validate::validate(&value) {
                    Ok(()) => {
                        values.push(value);
                    }
                    Err(report) => {
                        let err = Error::ValidationError {
                            report,
                            locations: recorder.map,
                        };
                        validation_errors.push(maybe_with_snippet(
                            err,
                            input,
                            with_snippet,
                            crop_radius,
                        ));
                    }
                }
            }
            None => break,
        }
    }

    src.finish()
        .map_err(|e| maybe_with_snippet(e, input, with_snippet, crop_radius))?;

    if validation_errors.is_empty() {
        Ok(values)
    } else {
        Err(Error::ValidationErrors {
            errors: validation_errors,
        })
    }
}

/// Deserialize a single YAML document from bytes and validate it with `garde`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "garde")]
pub fn from_slice_valid<T: DeserializeOwned + garde::Validate>(bytes: &[u8]) -> Result<T, Error>
where
    <T as garde::Validate>::Context: Default,
{
    from_slice_with_options_valid(bytes, Options::default())
}

/// Deserialize a single YAML document from bytes and validate it with `garde`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "garde")]
pub fn from_slice_with_options_valid<T: DeserializeOwned + garde::Validate>(
    bytes: &[u8],
    options: Options,
) -> Result<T, Error>
where
    <T as garde::Validate>::Context: Default,
{
    let s = std::str::from_utf8(bytes).map_err(|_| Error::InvalidUtf8Input)?;
    from_str_with_options_valid(s, options)
}

/// Deserialize multiple YAML documents from bytes with options and validate each with `garde`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "garde")]
pub fn from_slice_multiple_with_options_valid<T>(
    bytes: &[u8],
    options: Options,
) -> Result<Vec<T>, Error>
where
    T: DeserializeOwned + garde::Validate,
    <T as garde::Validate>::Context: Default,
{
    let s = std::str::from_utf8(bytes).map_err(|_| Error::InvalidUtf8Input)?;
    from_multiple_with_options_valid(s, options)
}

/// Deserialize a single YAML document from a reader and validate it with `garde`.
/// As there is no access to the full text of the document, the error message will not contain
/// a snippet.
#[cfg(feature = "garde")]
pub fn from_reader_valid<R: std::io::Read, T>(reader: R) -> Result<T, Error>
where
    T: DeserializeOwned + garde::Validate,
    <T as garde::Validate>::Context: Default,
{
    from_reader_with_options_valid(reader, Options::default())
}

/// Deserialize a single YAML document from a reader with options and validate it with `garde`.
/// As there is no access to the full text of the document, the error message will not contain
/// a snippet.
#[cfg(feature = "garde")]
#[allow(deprecated)]
pub fn from_reader_with_options_valid<R: std::io::Read, T>(
    reader: R,
    options: Options,
) -> Result<T, Error>
where
    T: DeserializeOwned + garde::Validate,
    <T as garde::Validate>::Context: Default,
{
    let cfg = crate::de::Cfg::from_options(&options);
    let mut src = LiveEvents::from_reader(
        reader,
        options.budget,
        options.budget_report,
        options.budget_report_cb,
        options.alias_limits,
        false,
        EnforcingPolicy::AllContent,
    );

    let mut recorder = crate::path_map::PathRecorder::new();

    let value_res = crate::anchor_store::with_document_scope(|| {
        T::deserialize(crate::de::YamlDeserializer::new_with_path_recorder(
            &mut src,
            cfg,
            &mut recorder,
        ))
    });
    let value = match value_res {
        Ok(v) => v,
        Err(e) => {
            if src.synthesized_null_emitted() {
                // If the only thing in the input was an empty document (synthetic null),
                // surface this as an EOF error to preserve expected error semantics
                // for incompatible target types (e.g., bool).
                return Err(Error::eof().with_location(src.last_location()));
            } else {
                return Err(e);
            }
        }
    };

    if let Err(report) = Validate::validate(&value) {
        return Err(Error::ValidationError {
            report,
            locations: recorder.map,
        });
    }

    // After finishing first document, peek ahead to detect either another document/content
    // or trailing garbage. If a scan error occurs but we have seen a DocumentEnd ("..."),
    // ignore the trailing garbage. Otherwise, surface the error.
    match src.peek() {
        Ok(Some(_)) => {
            return Err(
                Error::multiple_documents(
                    "use read_valid or read_with_options_valid to obtain the iterator",
                )
                .with_location(src.last_location()),
            );
        }
        Ok(None) => {}
        Err(e) => {
            if src.seen_doc_end() {
                // Trailing garbage after a proper document end marker is ignored.
            } else {
                return Err(e);
            }
        }
    }

    src.finish()?;
    Ok(value)
}

/// Create an iterator over validated YAML documents from a reader.
/// As there is no access to the full text of the document, the error message will not contain
/// a snippet.
#[cfg(feature = "garde")]
pub fn read_valid<'a, R, T>(reader: &'a mut R) -> impl Iterator<Item = Result<T, Error>> + 'a
where
    R: Read + 'a,
    T: DeserializeOwned + garde::Validate + 'a,
    <T as garde::Validate>::Context: Default,
{
    read_with_options_valid(reader, Default::default())
}

/// Create an iterator over validated YAML documents from a reader with configurable options.
/// As there is no access to the full text of the document, the error message will not contain
/// a snippet.
#[cfg(feature = "garde")]
#[allow(deprecated)]
pub fn read_with_options_valid<'a, R, T>(
    reader: &'a mut R,
    options: Options,
) -> impl Iterator<Item = Result<T, Error>> + 'a
where
    R: Read + 'a,
    T: DeserializeOwned + garde::Validate + 'a,
    <T as garde::Validate>::Context: Default,
{
    struct ReadValidIter<'a, T> {
        src: LiveEvents<'a>, // borrows from `reader`
        cfg: crate::de::Cfg,
        finished: bool,
        _marker: std::marker::PhantomData<T>,
    }

    impl<'a, T> Iterator for ReadValidIter<'a, T>
    where
        T: DeserializeOwned + garde::Validate + 'a,
        <T as garde::Validate>::Context: Default,
    {
        type Item = Result<T, Error>;

        fn next(&mut self) -> Option<Self::Item> {
            if self.finished {
                return None;
            }
            loop {
                match self.src.peek() {
                    Ok(Some(Ev::Scalar { value, style, .. }))
                        if scalar_is_nullish(value, style) =>
                    {
                        let _ = self.src.next();
                        continue;
                    }
                    Ok(Some(_)) => {
                        let mut recorder = crate::path_map::PathRecorder::new();
                        let value_res = crate::anchor_store::with_document_scope(|| {
                            T::deserialize(crate::de::YamlDeserializer::new_with_path_recorder(
                                &mut self.src,
                                self.cfg,
                                &mut recorder,
                            ))
                        });
                        let value = match value_res {
                            Ok(v) => v,
                            Err(e) => {
                                // After a deserialization error, skip remaining events in the
                                // current document and try to recover at the next document boundary.
                                if !self.src.skip_to_next_document() {
                                    self.finished = true;
                                }
                                return Some(Err(e));
                            }
                        };

                        match Validate::validate(&value) {
                            Ok(()) => return Some(Ok(value)),
                            Err(report) => {
                                // Validation errors occur after successful deserialization,
                                // so the parser is already at the document boundary.
                                // No need to skip or mark as finished - continue to next document.
                                return Some(Err(Error::ValidationError {
                                    report,
                                    locations: recorder.map,
                                }));
                            }
                        }
                    }
                    Ok(None) => {
                        self.finished = true;
                        if let Err(e) = self.src.finish() {
                            return Some(Err(e));
                        }
                        return None;
                    }
                    Err(e) => {
                        self.finished = true;
                        let _ = self.src.finish();
                        return Some(Err(e));
                    }
                }
            }
        }
    }

    let cfg = crate::de::Cfg::from_options(&options);
    let src = LiveEvents::from_reader(
        reader,
        options.budget,
        options.budget_report,
        options.budget_report_cb,
        options.alias_limits,
        false,
        EnforcingPolicy::PerDocument,
    );

    ReadValidIter::<T> {
        src,
        cfg,
        finished: false,
        _marker: std::marker::PhantomData,
    }
}

/// Deserialize a single YAML document from a YAML string and validate it with `validator`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "validator")]
pub fn from_str_validate<T>(input: &str) -> Result<T, Error>
where
    T: DeserializeOwned + ValidatorValidate,
{
    from_str_with_options_validate(input, Options::default())
}

/// Deserialize a single YAML document with configurable [`Options`] and validate it with `validator`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "validator")]
pub fn from_str_with_options_validate<T>(input: &str, options: Options) -> Result<T, Error>
where
    T: DeserializeOwned + ValidatorValidate,
{
    let with_snippet = options.with_snippet;
    let crop_radius = options.crop_radius;

    let (v, recorder) = from_str_with_options_and_path_recorder::<T>(input, options)?;
    match ValidatorValidate::validate(&v) {
        Ok(()) => Ok(v),
        Err(errors) => {
            let err = Error::ValidatorError {
                errors,
                locations: recorder.map,
            };
            Err(maybe_with_snippet(err, input, with_snippet, crop_radius))
        }
    }
}

/// Deserialize multiple YAML documents from a YAML string and validate each with `validator`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "validator")]
pub fn from_multiple_validate<T: DeserializeOwned + ValidatorValidate>(
    input: &str,
) -> Result<Vec<T>, Error> {
    from_multiple_with_options_validate(input, Options::default())
}

/// Deserialize multiple YAML documents with configurable [`Options`] and validate each with `validator`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "validator")]
#[allow(deprecated)]
pub fn from_multiple_with_options_validate<T>(
    input: &str,
    options: Options,
) -> Result<Vec<T>, Error>
where
    T: DeserializeOwned + ValidatorValidate,
{
    let with_snippet = options.with_snippet;
    let crop_radius = options.crop_radius;

    let cfg = crate::de::Cfg::from_options(&options);
    let mut src = LiveEvents::from_str(
        input,
        options.budget,
        options.budget_report,
        options.budget_report_cb,
        options.alias_limits,
        false,
    );
    let mut values = Vec::new();
    let mut validation_errors: Vec<Error> = Vec::new();

    loop {
        match src.peek()? {
            // Skip documents that are explicit null-like scalars ("", "~", or "null").
            Some(Ev::Scalar {
                value: s, style, ..
            }) if scalar_is_nullish(s, style) => {
                let _ = src.next()?; // consume the null scalar document
                continue;
            }
            Some(_) => {
                let mut recorder = crate::path_map::PathRecorder::new();
                let value_res = crate::anchor_store::with_document_scope(|| {
                    T::deserialize(crate::de::YamlDeserializer::new_with_path_recorder(
                        &mut src,
                        cfg,
                        &mut recorder,
                    ))
                });
                let value = match value_res {
                    Ok(v) => v,
                    Err(e) => return Err(maybe_with_snippet(e, input, with_snippet, crop_radius)),
                };

                match ValidatorValidate::validate(&value) {
                    Ok(()) => {
                        values.push(value);
                    }
                    Err(errors) => {
                        let err = Error::ValidatorError {
                            errors,
                            locations: recorder.map,
                        };
                        validation_errors.push(maybe_with_snippet(
                            err,
                            input,
                            with_snippet,
                            crop_radius,
                        ));
                    }
                }
            }
            None => break,
        }
    }

    src.finish()
        .map_err(|e| maybe_with_snippet(e, input, with_snippet, crop_radius))?;

    if validation_errors.is_empty() {
        Ok(values)
    } else {
        Err(Error::ValidatorErrors {
            errors: validation_errors,
        })
    }
}

/// Deserialize a single YAML document from bytes and validate it with `validator`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "validator")]
pub fn from_slice_validate<T: DeserializeOwned + ValidatorValidate>(
    bytes: &[u8],
) -> Result<T, Error> {
    from_slice_with_options_validate(bytes, Options::default())
}

/// Deserialize a single YAML document from bytes and validate it with `validator`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "validator")]
pub fn from_slice_with_options_validate<T: DeserializeOwned + ValidatorValidate>(
    bytes: &[u8],
    options: Options,
) -> Result<T, Error> {
    let s = std::str::from_utf8(bytes).map_err(|_| Error::InvalidUtf8Input)?;
    from_str_with_options_validate(s, options)
}

/// Deserialize multiple YAML documents from bytes with options and validate each with `validator`.
/// The error message will contain a snippet with exact location information, and if the
/// invalid value comes from anchor, serde-saphyr will also tell where it is defined.
#[cfg(feature = "validator")]
pub fn from_slice_multiple_with_options_validate<T>(
    bytes: &[u8],
    options: Options,
) -> Result<Vec<T>, Error>
where
    T: DeserializeOwned + ValidatorValidate,
{
    let s = std::str::from_utf8(bytes).map_err(|_| Error::InvalidUtf8Input)?;
    from_multiple_with_options_validate(s, options)
}

/// Deserialize a single YAML document from a reader and validate it with `validator`.
/// As there is no access to the full text of the document, the error message will not contain
/// a snippet.
#[cfg(feature = "validator")]
pub fn from_reader_validate<R: std::io::Read, T>(reader: R) -> Result<T, Error>
where
    T: DeserializeOwned + ValidatorValidate,
{
    from_reader_with_options_validate(reader, Options::default())
}

/// Deserialize a single YAML document from a reader with options and validate it with `validator`.
/// As there is no access to the full text of the document, the error message will not contain
/// a snippet.
#[cfg(feature = "validator")]
#[allow(deprecated)]
pub fn from_reader_with_options_validate<R: std::io::Read, T>(
    reader: R,
    options: Options,
) -> Result<T, Error>
where
    T: DeserializeOwned + ValidatorValidate,
{
    let cfg = crate::de::Cfg::from_options(&options);
    let mut src = LiveEvents::from_reader(
        reader,
        options.budget,
        options.budget_report,
        options.budget_report_cb,
        options.alias_limits,
        false,
        EnforcingPolicy::AllContent,
    );

    let mut recorder = crate::path_map::PathRecorder::new();

    let value_res = crate::anchor_store::with_document_scope(|| {
        T::deserialize(crate::de::YamlDeserializer::new_with_path_recorder(
            &mut src,
            cfg,
            &mut recorder,
        ))
    });
    let value = match value_res {
        Ok(v) => v,
        Err(e) => {
            if src.synthesized_null_emitted() {
                // If the only thing in the input was an empty document (synthetic null),
                // surface this as an EOF error to preserve expected error semantics
                // for incompatible target types (e.g., bool).
                return Err(Error::eof().with_location(src.last_location()));
            } else {
                return Err(e);
            }
        }
    };

    if let Err(errors) = ValidatorValidate::validate(&value) {
        return Err(Error::ValidatorError {
            errors,
            locations: recorder.map,
        });
    }

    // After finishing first document, peek ahead to detect either another document/content
    // or trailing garbage. If a scan error occurs but we have seen a DocumentEnd ("..."),
    // ignore the trailing garbage. Otherwise, surface the error.
    match src.peek() {
        Ok(Some(_)) => {
            return Err(
                Error::multiple_documents(
                    "use read_validate or read_with_options_validate to obtain the iterator",
                )
                .with_location(src.last_location()),
            );
        }
        Ok(None) => {}
        Err(e) => {
            if src.seen_doc_end() {
                // Trailing garbage after a proper document end marker is ignored.
            } else {
                return Err(e);
            }
        }
    }

    src.finish()?;
    Ok(value)
}

/// Create an iterator over validated YAML documents from a reader.
/// As there is no access to the full text of the document, the error message will not contain
/// a snippet.
#[cfg(feature = "validator")]
pub fn read_validate<'a, R, T>(reader: &'a mut R) -> impl Iterator<Item = Result<T, Error>> + 'a
where
    R: Read + 'a,
    T: DeserializeOwned + ValidatorValidate + 'a,
{
    read_with_options_validate(reader, Default::default())
}

/// Create an iterator over validated YAML documents from a reader with configurable options.
/// As there is no access to the full text of the document, the error message will not contain
/// a snippet.
#[cfg(feature = "validator")]
#[allow(deprecated)]
pub fn read_with_options_validate<'a, R, T>(
    reader: &'a mut R,
    options: Options,
) -> impl Iterator<Item = Result<T, Error>> + 'a
where
    R: Read + 'a,
    T: DeserializeOwned + ValidatorValidate + 'a,
{
    struct ReadValidateIter<'a, T> {
        src: LiveEvents<'a>, // borrows from `reader`
        cfg: crate::de::Cfg,
        finished: bool,
        _marker: std::marker::PhantomData<T>,
    }

    impl<'a, T> Iterator for ReadValidateIter<'a, T>
    where
        T: DeserializeOwned + ValidatorValidate + 'a,
    {
        type Item = Result<T, Error>;

        fn next(&mut self) -> Option<Self::Item> {
            if self.finished {
                return None;
            }
            loop {
                match self.src.peek() {
                    Ok(Some(Ev::Scalar { value, style, .. }))
                        if scalar_is_nullish(value, style) =>
                    {
                        let _ = self.src.next();
                        continue;
                    }
                    Ok(Some(_)) => {
                        let mut recorder = crate::path_map::PathRecorder::new();
                        let value_res = crate::anchor_store::with_document_scope(|| {
                            T::deserialize(crate::de::YamlDeserializer::new_with_path_recorder(
                                &mut self.src,
                                self.cfg,
                                &mut recorder,
                            ))
                        });
                        let value = match value_res {
                            Ok(v) => v,
                            Err(e) => {
                                // After a deserialization error, skip remaining events in the
                                // current document and try to recover at the next document boundary.
                                if !self.src.skip_to_next_document() {
                                    self.finished = true;
                                }
                                return Some(Err(e));
                            }
                        };

                        match ValidatorValidate::validate(&value) {
                            Ok(()) => return Some(Ok(value)),
                            Err(errors) => {
                                // Validation errors occur after successful deserialization,
                                // so the parser is already at the document boundary.
                                // No need to skip or mark as finished - continue to next document.
                                return Some(Err(Error::ValidatorError {
                                    errors,
                                    locations: recorder.map,
                                }));
                            }
                        }
                    }
                    Ok(None) => {
                        self.finished = true;
                        if let Err(e) = self.src.finish() {
                            return Some(Err(e));
                        }
                        return None;
                    }
                    Err(e) => {
                        self.finished = true;
                        let _ = self.src.finish();
                        return Some(Err(e));
                    }
                }
            }
        }
    }

    let cfg = crate::de::Cfg::from_options(&options);
    let src = LiveEvents::from_reader(
        reader,
        options.budget,
        options.budget_report,
        options.budget_report_cb,
        options.alias_limits,
        false,
        EnforcingPolicy::PerDocument,
    );

    ReadValidateIter::<T> {
        src,
        cfg,
        finished: false,
        _marker: std::marker::PhantomData,
    }
}

pub(crate) fn maybe_with_snippet(
    err: Error,
    input: &str,
    with_snippet: bool,
    crop_radius: usize,
) -> Error {
    if with_snippet && crop_radius > 0 && err.location().is_some() {
        err.with_snippet(input, crop_radius)
    } else {
        err
    }
}

/// Deserialize multiple YAML documents from a single string into a vector of `T`.
/// Completely empty documents are ignored and not included into returned vector.
///
/// Example: read two `Config` documents separated by `---`.
///
/// ```rust
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Config {
///     name: String,
///     enabled: bool,
///     retries: i32,
/// }
///
/// let yaml = r#"
/// name: First
/// enabled: true
/// retries: 1
/// ---
/// name: Second
/// enabled: false
/// retries: 2
/// "#;
///
/// let cfgs: Vec<Config> = serde_saphyr::from_multiple(yaml).unwrap();
/// assert_eq!(cfgs.len(), 2);
/// assert_eq!(cfgs[0].name, "First");
/// ```
pub fn from_multiple<T: DeserializeOwned>(input: &str) -> Result<Vec<T>, Error> {
    from_multiple_with_options(input, Options::default())
}

/// Deserialize multiple YAML documents into a vector with configurable [`Options`].
///
/// Example: two `Config` documents with a custom budget.
///
/// ```rust
/// use serde::Deserialize;
/// use serde_saphyr::DuplicateKeyPolicy;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Config {
///     name: String,
///     enabled: bool,
///     retries: i32,
/// }
///
/// let yaml = r#"
/// name: First
/// enabled: true
/// retries: 1
/// ---
/// name: Second
/// enabled: false
/// retries: 2
/// "#;
///
/// let options = serde_saphyr::options! {
///     budget: serde_saphyr::budget! {
///         max_anchors: 200,
///     },
///     duplicate_keys: DuplicateKeyPolicy::FirstWins,
/// };
/// let cfgs: Vec<Config> = serde_saphyr::from_multiple_with_options(yaml, options).unwrap();
/// assert_eq!(cfgs.len(), 2);
/// assert!(!cfgs[1].enabled);
/// ```
#[allow(deprecated)]
pub fn from_multiple_with_options<T: DeserializeOwned>(
    input: &str,
    options: Options,
) -> Result<Vec<T>, Error> {
    // Normalize: ignore a single leading UTF-8 BOM if present.
    let input = if let Some(rest) = input.strip_prefix('\u{FEFF}') {
        rest
    } else {
        input
    };
    let with_snippet = options.with_snippet;
    let crop_radius = options.crop_radius;

    let cfg = crate::de::Cfg::from_options(&options);
    let mut src = LiveEvents::from_str(
        input,
        options.budget,
        options.budget_report,
        options.budget_report_cb,
        options.alias_limits,
        false,
    );
    let mut values = Vec::new();

    loop {
        match src.peek()? {
            // Skip documents that are explicit null-like scalars ("", "~", or "null").
            Some(Ev::Scalar {
                value: s, style, ..
            }) if scalar_is_nullish(s, style) => {
                let _ = src.next()?; // consume the null scalar document
                // Do not push anything for this document; move to the next one.
                continue;
            }
            Some(_) => {
                let value_res = crate::anchor_store::with_document_scope(|| {
                    T::deserialize(crate::de::YamlDeserializer::new(&mut src, cfg))
                });
                let value = match value_res {
                    Ok(v) => v,
                    Err(e) => return Err(maybe_with_snippet(e, input, with_snippet, crop_radius)),
                };
                values.push(value);
            }
            None => break,
        }
    }

    src.finish()
        .map_err(|e| maybe_with_snippet(e, input, with_snippet, crop_radius))?;
    Ok(values)
}

/// Deserialize a single YAML document from a UTF-8 byte slice.
///
/// This is equivalent to [`from_str`], but accepts `&[u8]` and validates it is
/// valid UTF-8 before parsing.
///
/// Example: read a small `Config` structure from bytes.
///
/// ```rust
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Config {
///     name: String,
///     enabled: bool,
///     retries: i32,
/// }
///
/// let yaml = r#"
/// name: My Application
/// enabled: true
/// retries: 5
/// "#;
/// let bytes = yaml.as_bytes();
/// let cfg: Config = serde_saphyr::from_slice(bytes).unwrap();
/// assert!(cfg.enabled);
/// ```
///
pub fn from_slice<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, Error> {
    from_slice_with_options(bytes, Options::default())
}

/// Deserialize a single YAML document from a UTF-8 byte slice with configurable [`Options`].
///
/// Example: read a small `Config` with a custom budget from bytes.
///
/// ```rust
/// use serde::Deserialize;
/// use serde_saphyr::DuplicateKeyPolicy;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Config {
///     name: String,
///     enabled: bool,
///     retries: i32,
/// }
///
/// let yaml = r#"
///      name: My Application
///      enabled: true
///      retries: 5
/// "#;
/// let bytes = yaml.as_bytes();
/// let options = serde_saphyr::options! {
///     budget: serde_saphyr::budget! {
///         max_anchors: 200,
///     },
///     duplicate_keys: DuplicateKeyPolicy::FirstWins,
/// };
/// let cfg: Config = serde_saphyr::from_slice_with_options(bytes, options).unwrap();
/// assert_eq!(cfg.retries, 5);
/// ```
pub fn from_slice_with_options<'de, T>(
    bytes: &'de [u8],
    options: Options,
) -> Result<T, Error>
where
    T: serde::Deserialize<'de>,
{
    let s = std::str::from_utf8(bytes).map_err(|_| Error::InvalidUtf8Input)?;
    from_str_with_options(s, options)
}

/// Deserialize multiple YAML documents from a UTF-8 byte slice into a vector of `T`.
///
/// Example: read two `Config` documents separated by `---` from bytes.
///
/// ```rust
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Config {
///     name: String,
///     enabled: bool,
///     retries: i32,
/// }
///
/// let yaml = r#"
/// name: First
/// enabled: true
/// retries: 1
/// ---
/// name: Second
/// enabled: false
/// retries: 2
/// "#;
/// let bytes = yaml.as_bytes();
/// let cfgs: Vec<Config> = serde_saphyr::from_slice_multiple(bytes).unwrap();
/// assert_eq!(cfgs.len(), 2);
/// assert_eq!(cfgs[0].name, "First");
/// ```
pub fn from_slice_multiple<T: DeserializeOwned>(bytes: &[u8]) -> Result<Vec<T>, Error> {
    from_slice_multiple_with_options(bytes, Options::default())
}

/// Deserialize multiple YAML documents from bytes with configurable [`Options`].
/// Completely empty documents are ignored and not included into returned vector.
///
/// Example: two `Config` documents with a custom budget from bytes.
///
/// ```rust
/// use serde::Deserialize;
/// use serde_saphyr::DuplicateKeyPolicy;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Config {
///     name: String,
///     enabled: bool,
///     retries: i32,
/// }
///
/// let yaml = r#"
/// name: First
/// enabled: true
/// retries: 1
/// ---
/// name: Second
/// enabled: false
/// retries: 2
/// "#;
/// let bytes = yaml.as_bytes();
/// let options = serde_saphyr::options! {
///     budget: serde_saphyr::budget! {
///         max_anchors: 200,
///     },
///     duplicate_keys: DuplicateKeyPolicy::FirstWins,
/// };
/// let cfgs: Vec<Config> = serde_saphyr::from_slice_multiple_with_options(bytes, options).unwrap();
/// assert_eq!(cfgs.len(), 2);
/// assert!(!cfgs[1].enabled);
/// ```
pub fn from_slice_multiple_with_options<T: DeserializeOwned>(
    bytes: &[u8],
    options: Options,
) -> Result<Vec<T>, Error> {
    let s = std::str::from_utf8(bytes).map_err(|_| Error::InvalidUtf8Input)?;
    from_multiple_with_options(s, options)
}

/// Serialize multiple documents into a YAML string.
///
/// Serializes each value in the provided slice as an individual YAML document.
/// Documents are separated by a standard YAML document start marker ("---\n").
/// No marker is emitted before the first document.
///
/// Example
///
/// ```rust
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Point { x: i32 }
///
/// let docs = vec![Point { x: 1 }, Point { x: 2 }];
/// let out = serde_saphyr::to_string_multiple(&docs).unwrap();
/// assert_eq!(out, "x: 1\n---\nx: 2\n");
/// ```
pub fn to_string_multiple<T: serde::Serialize>(
    values: &[T],
) -> std::result::Result<String, crate::ser::Error> {
    let mut out = String::new();
    let mut first = true;
    for v in values {
        if !first {
            out.push_str("---\n");
        }
        first = false;
        to_fmt_writer(&mut out, v)?;
    }
    Ok(out)
}

/// Deserialize a single YAML document from any `std::io::Read`.
///
///
/// This method parsers as it reads, without loading the entire input into memory first. Hence,
/// budget limits protect against large (potentially malicious) input.
///
/// Example
///
/// ```rust
/// use serde::{Deserialize, Serialize};
/// use std::collections::HashMap;
/// use serde_json::Value;
///
/// #[derive(Debug, PartialEq, Serialize, Deserialize)]
/// struct Point {
///     x: i32,
///     y: i32,
/// }
///
/// let yaml = "x: 3\ny: 4\n";
/// let reader = std::io::Cursor::new(yaml.as_bytes());
/// let p: Point = serde_saphyr::from_reader(reader).unwrap();
/// assert_eq!(p, Point { x: 3, y: 4 });
///
/// // It also works for dynamic values like serde_json::Value
/// let mut big = String::new();
/// let mut i = 0usize;
/// while big.len() < 64 * 1024 { big.push_str(&format!("k{0}: v{0}\n", i)); i += 1; }
/// let reader = std::io::Cursor::new(big.as_bytes().to_owned());
/// let _value: Value = serde_saphyr::from_reader(reader).unwrap();
/// ```
pub fn from_reader<'a, R: std::io::Read + 'a, T: DeserializeOwned>(reader: R) -> Result<T, Error> {
    from_reader_with_options(reader, Options::default())
}

/// Deserialize a single YAML document from any `std::io::Read` with configurable `Options`.
///
/// This is the reader-based counterpart to [`from_str_with_options`]. It consumes a
/// byte-oriented reader, decodes it to UTF-8, and streams events into the deserializer.
///
/// This method parsers as it reads, without loading the entire input into memory first. Hence,
/// budget limits protect against large (potentially malicious) input.
///
/// Notes on limits and large inputs
/// - Parsing limits: Use [`Options::budget`] to constrain YAML complexity (events, nodes,
///   nesting depth, total scalar bytes, number of documents, anchors, aliases, etc.). These
///   limits are enforced during parsing and are enabled by default via `Options::default()`.
/// - Byte-level input cap: from_slice_multiple hard cap on input bytes is enforced via `Options::budget.max_reader_input_bytes`.
///   The default budget sets this to 256 MiB. You can override it by customizing `Options::budget`.
///   When the cap is exceeded, deserialization fails early with a budget error.
///
/// Example: limit raw input bytes and customize options
/// ```rust
/// use std::io::{Read, Cursor};
/// use serde::Deserialize;
/// use serde_saphyr::{Budget, Options};
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Point { x: i32, y: i32 }
///
/// let yaml = "x: 3\ny: 4\n";
/// let reader = Cursor::new(yaml.as_bytes());
///
/// let opts = serde_saphyr::options! {
///     budget: serde_saphyr::budget! {
///         max_events: 10_000,
///         max_reader_input_bytes: Some(1024),
///     },
/// };
///
/// let p: Point = serde_saphyr::from_reader_with_options(reader, opts).unwrap();
/// assert_eq!(p, Point { x: 3, y: 4 });
/// ```
///
/// Error behavior
/// - If an empty document is provided (no content), a type-mismatch (eof) error is returned when
///   attempting to deserialize into non-null-like targets.
/// - If the reader contains multiple documents, an error is returned suggesting the
///   `read`/`read_with_options` iterator APIs.
/// - If `Options::budget` is set and a limit is exceeded, an error is returned early.
#[allow(deprecated)]
pub fn from_reader_with_options<'a, R: std::io::Read + 'a, T: DeserializeOwned>(
    reader: R,
    options: Options,
) -> Result<T, Error> {
    let cfg = crate::de::Cfg::from_options(&options);
    let crop_radius = options.crop_radius;

    // Wrap the reader in a SharedRingReader to capture context for error snippets
    let shared_ring = ring_reader::SharedRingReader::new(reader);
    let ring_handle = ring_reader::SharedRingReaderHandle::new(&shared_ring);

    let mut src = LiveEvents::from_reader(
        ring_handle,
        options.budget,
        options.budget_report,
        options.budget_report_cb,
        options.alias_limits,
        false,
        EnforcingPolicy::AllContent,
    );

    // Helper to attach snippet to an error using the RingReader's context
    let attach_snippet = |e: Error| -> Error {
        if crop_radius == 0 {
            return e;
        }
        match shared_ring.get_recent() {
            Ok(snapshot) => {
                let text = String::from_utf8_lossy(&snapshot.bytes);
                e.with_snippet_offset(&text, snapshot.start_line, crop_radius)
            }
            Err(_) => e, // If we can't get the snapshot, return the error as-is
        }
    };

    let value_res = crate::anchor_store::with_document_scope(|| {
        T::deserialize(crate::de::YamlDeserializer::new(&mut src, cfg))
    });
    let value = match value_res {
        Ok(v) => v,
        Err(e) => {
            if src.synthesized_null_emitted() {
                // If the only thing in the input was an empty document (synthetic null),
                // surface this as an EOF error to preserve expected error semantics
                // for incompatible target types (e.g., bool).
                return Err(attach_snippet(
                    Error::eof().with_location(src.last_location()),
                ));
            } else {
                return Err(attach_snippet(e));
            }
        }
    };

    // After finishing first document, peek ahead to detect either another document/content
    // or trailing garbage. If a scan error occurs but we have seen a DocumentEnd ("..."),
    // ignore the trailing garbage. Otherwise, surface the error.
    match src.peek() {
        Ok(Some(_)) => {
            return Err(attach_snippet(
                Error::multiple_documents(
                    "use read or read_with_options to obtain the iterator",
                )
                .with_location(src.last_location()),
            ));
        }
        Ok(None) => {}
        Err(e) => {
            if src.seen_doc_end() {
                // Trailing garbage after a proper document end marker is ignored.
            } else {
                return Err(attach_snippet(e));
            }
        }
    }

    if let Err(e) = src.finish() {
        return Err(attach_snippet(e));
    }
    Ok(value)
}

/// Create an iterator over YAML documents from any `std::io::Read` using default options.
///
/// This is a convenience wrapper around [`read_with_options`] that uses the
/// same defaults as [`Options::default`] **except** it disables the
/// `max_reader_input_bytes` budget to better support long-lived streams.
///
/// - It streams the reader without loading the whole input into memory.
/// - Each item produced by the returned iterator is one deserialized YAML document of type `T`.
/// - Documents that are completely empty or null-like (e.g., `"", ~, null`) are skipped.
///
/// Generic parameters
/// - `R`: the concrete reader type implementing [`std::io::Read`]. You almost never need to
///   write this explicitly; the compiler will infer it from the `reader` you pass. When using
///   turbofish, write `_` to let the compiler infer `R`.
/// - `T`: the type to deserialize each YAML document into. Must implement [`serde::de::DeserializeOwned`].
///
/// Lifetimes
/// - `'a`: the lifetime of the returned iterator, tied to the lifetime of the provided `reader`.
///   The iterator cannot outlive the reader it was created from.
///
/// Limits and budget
/// - Uses the same limits as `Options::default()` (events, nodes, nesting depth, total scalar
///   bytes) and the default alias-replay caps. The only change is that
///   `Budget::max_reader_input_bytes` is set to `None` so the streaming iterator can handle
///   arbitrarily long inputs. To customize these limits, call [`read_with_options`] and set
///   `Options::budget.max_reader_input_bytes` in the provided `Options`.
/// - Alias replay limits are also enforced with their default values to mitigate alias bombs.
///
/// ```rust
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Simple { id: usize }
///
/// let yaml = b"id: 1\n---\nid: 2\n";
/// let mut reader = std::io::Cursor::new(&yaml[..]);
///
/// // Type `T` is inferred from the collection target (Vec<Simple>).
/// let values: Vec<Simple> = serde_saphyr::read(&mut reader)
///     .map(|r| r.unwrap())
///     .collect();
/// assert_eq!(values.len(), 2);
/// assert_eq!(values[0].id, 1);
/// ```
///
/// Specifying only `T` with turbofish and letting `R` be inferred using `_`:
/// ```rust
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Simple { id: usize }
///
/// let yaml = b"id: 10\n---\nid: 20\n";
/// let mut reader = std::io::Cursor::new(&yaml[..]);
///
/// // First turbofish parameter is R (reader type), `_` lets the compiler infer it.
/// let iter = serde_saphyr::read::<_, Simple>(&mut reader);
/// let ids: Vec<usize> = iter.map(|res| res.unwrap().id).collect();
/// assert_eq!(ids, vec![10, 20]);
/// ```
///
/// - Each `next()` yields either `Ok(T)` for a successfully deserialized document or `Err(Error)`
///   if parsing fails or a limit is exceeded. After an error, the iterator ends.
/// - Empty/null-like documents are skipped and produce no items.
///
/// *Note* Some content of the next document is read before the current parsed document is emitted.
/// Hence, while streaming is good for safely parsing large files with multiple documents without
/// loading it into RAM in advance, it does not emit each document exactly
/// after `---`  is encountered.
pub fn read<'a, R, T>(reader: &'a mut R) -> Box<dyn Iterator<Item = Result<T, Error>> + 'a>
where
    R: Read + 'a,
    T: DeserializeOwned + 'a,
{
    Box::new(read_with_options(
        reader,
        crate::options! {
            budget: crate::budget! {
                max_reader_input_bytes: None,
            },
        },
    ))
}

/// Create an iterator over YAML documents from any `std::io::Read`, with configurable options.
///
/// This is the multi-document counterpart to [`from_reader_with_options`]. It does not load
/// the entire input into memory. Instead, it streams the reader, deserializing one document
/// at a time into values of type `T`, yielding them through the returned iterator. Documents
/// that are completely empty or null-like (e.g., `""`, `~`, or `null`) are skipped.
///
/// Generic parameters
/// - `R`: the concrete reader type that implements [`std::io::Read`]. You rarely need to spell
///   this out; it is almost always inferred from the `reader` value you pass in. When using
///   turbofish, you can write `_` for this parameter to let the compiler infer it.
/// - `T`: the type to deserialize each YAML document into. This must implement [`serde::de::DeserializeOwned`].
///
/// Lifetimes
/// - `'a`: the lifetime of the returned iterator. It is tied to the lifetime of the provided
///   `reader` value because the iterator borrows internal state that references the reader.
///   In practice, this means the iterator cannot outlive the reader it was created from.
///
/// Limits and budget
/// - All parsing limits configured via [`Options::budget`] (such as maximum events, nodes,
///   nesting depth, total scalar bytes) are enforced while streaming. from_slice_multiple hard input-byte cap
///   is also enforced via `Budget::max_reader_input_bytes` (256 MiB by default), set this
///   to None if you need a streamer to exist for arbitrary long time.
/// - Alias replay limits from [`Options::alias_limits`] are also enforced to mitigate alias bombs.
///
/// ```rust
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Simple { id: usize }
///
/// let yaml = b"id: 1\n---\nid: 2\n";
/// let mut reader = std::io::Cursor::new(&yaml[..]);
///
/// // Type `T` is inferred from the collection target (Vec<Simple>).
/// let values: Vec<Simple> = serde_saphyr::read(&mut reader)
///     .map(|r| r.unwrap())
///     .collect();
/// assert_eq!(values.len(), 2);
/// assert_eq!(values[0].id, 1);
/// ```
///
/// Specifying only `T` with turbofish and letting `R` be inferred using `_`:
/// ```rust
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Simple { id: usize }
///
/// let yaml = b"id: 10\n---\nid: 20\n";
/// let mut reader = std::io::Cursor::new(&yaml[..]);
///
/// // First turbofish parameter is R (reader type) which we let the compiler infer via `_`.
/// let iter = serde_saphyr::read_with_options::<_, Simple>(&mut reader, serde_saphyr::Options::default());
/// let ids: Vec<usize> = iter.map(|res| res.unwrap().id).collect();
/// assert_eq!(ids, vec![10, 20]);
/// ```
///
/// - Each `next()` yields either `Ok(T)` for a successfully deserialized document or `Err(Error)`
///   if parsing or deserialization fails.
/// - After a **deserialization error** (e.g., type mismatch, missing field), the iterator
///   automatically recovers by skipping to the next document boundary (`---`) and continues
///   iteration. This allows processing subsequent valid documents even when some fail.
/// - After a **syntax error** or **budget/alias limit exceeded**, the iterator ends because
///   the parser state may be unrecoverable.
/// - Empty/null-like documents are skipped and produce no items.
#[allow(deprecated)]
pub fn read_with_options<'a, R, T>(
    reader: &'a mut R, // iterator must not outlive this borrow
    options: Options,
) -> impl Iterator<Item = Result<T, Error>> + 'a
where
    R: Read + 'a,
    T: DeserializeOwned + 'a,
{
    struct ReadIter<'a, T> {
        src: LiveEvents<'a>, // borrows from `reader`
        cfg: crate::de::Cfg,
        finished: bool,
        _marker: std::marker::PhantomData<T>,
    }

    impl<'a, T> Iterator for ReadIter<'a, T>
    where
        T: DeserializeOwned + 'a,
    {
        type Item = Result<T, Error>;

        fn next(&mut self) -> Option<Self::Item> {
            if self.finished {
                return None;
            }
            loop {
                match self.src.peek() {
                    Ok(Some(Ev::Scalar { value, style, .. }))
                        if scalar_is_nullish(value, style) =>
                    {
                        let _ = self.src.next();
                        continue;
                    }
                    Ok(Some(_)) => {
                        let res = crate::anchor_store::with_document_scope(|| {
                            T::deserialize(crate::de::YamlDeserializer::new(
                                &mut self.src,
                                self.cfg,
                            ))
                        });
                        if res.is_err() {
                            // After a deserialization error, skip remaining events in the
                            // current document and try to recover at the next document boundary.
                            // If no next document is found, mark as finished.
                            if !self.src.skip_to_next_document() {
                                self.finished = true;
                            }
                        }
                        return Some(res);
                    }
                    Ok(None) => {
                        self.finished = true;
                        if let Err(e) = self.src.finish() {
                            return Some(Err(e));
                        }
                        return None;
                    }
                    Err(e) => {
                        self.finished = true;
                        let _ = self.src.finish();
                        return Some(Err(e));
                    }
                }
            }
        }
    }

    let cfg = crate::de::Cfg::from_options(&options);
    let src = LiveEvents::from_reader(
        reader,
        options.budget,
        options.budget_report,
        options.budget_report_cb,
        options.alias_limits,
        false,
        EnforcingPolicy::PerDocument,
    );

    ReadIter::<T> {
        src,
        cfg,
        finished: false,
        _marker: std::marker::PhantomData,
    }
}