ayaml 1.0.0

A safe, pure-Rust YAML parser, event stream, value model, Serde layer, and emitter
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
#![cfg_attr(docsrs, feature(doc_cfg))]

//! ayaml is a safe, pure-Rust YAML 1.2.2 parser, event stream, value model,
//! Serde implementation, and emitter.
//!
//! One scanner and grammar back every surface, so the spanned event stream,
//! generic values, typed Serde decoding, and emitted output use the same
//! syntax, resolution, and resource limits.
//!
//! # Quick start
//!
//! Parse a document into the generic value model:
//!
//! ```
//! use ayaml::{parse_value, to_string};
//!
//! let value = parse_value("name: example\nitems:\n  - one\n  - two\n")?;
//! assert_eq!(value["name"].as_str(), Some("example"));
//!
//! let output = to_string(&value)?;
//! assert!(output.contains("name: example"));
//! # Ok::<(), ayaml::Error>(())
//! ```
//!
//! Decode into a typed value:
//!
//! ```
//! use serde::Deserialize;
//!
//! #[derive(Debug, Deserialize)]
//! struct Config {
//!     name: String,
//!     retries: u32,
//! }
//!
//! let config: Config = ayaml::from_str("name: example\nretries: 3\n")?;
//! assert_eq!(config.retries, 3);
//! # Ok::<(), ayaml::Error>(())
//! ```
//!
//! Walk the event stream when source spans matter:
//!
//! ```
//! use ayaml::Event;
//!
//! let events: Vec<Event<'_>> = ayaml::parse_events("a: 1\n")?
//!     .collect::<Result<_, _>>()?;
//! assert!(events.iter().any(|event| matches!(event, Event::MappingStart { .. })));
//! # Ok::<(), ayaml::Error>(())
//! ```
//!
//! Configure options and limits with [`ParseOptions`] and [`EmitOptions`]:
//!
//! ```
//! use ayaml::{EmitOptions, Limits, ParseOptions, parse_value_with, to_string_value_with};
//!
//! const PARSE: ParseOptions =
//!     ParseOptions::new().with_limits(Limits::new().with_max_depth(64));
//! let value = parse_value_with("a: [1, 2, 3]\n", &PARSE)?;
//! assert_eq!(value["a"][1].as_u64(), Some(2));
//!
//! let yaml = to_string_value_with(&value, &EmitOptions::flow())?;
//! assert_eq!(yaml, "{a: [1, 2, 3]}\n");
//! # Ok::<(), ayaml::Error>(())
//! ```
//!
//! # Compatibility
//!
//! The default parser follows YAML 1.2.2. The additive `libyaml-compat`
//! feature exposes `ayaml::compat` for callers that need libyaml-compatible
//! behavior; it never changes the root functions. The deliberate deviations
//! are listed in the workspace's
//! `tests/data/yaml-test-suite-deviations.txt` file.
//!
//! # Features
//!
//! - `libyaml-compat`: adds `ayaml::compat` and its decoding entry points.
//! - `bench-internals`: unstable hooks for ayaml's benchmark and conformance
//!   harnesses. This module is hidden and outside `SemVer`.
//!
//! # Resource limits
//!
//! Every parse, decode, and emit operation has a `_with` form taking one
//! options value ([`ParseOptions`], `compat::ParseOptions`, or
//! [`EmitOptions`]), which carries its [`Limits`]; [`Value::apply_merge_keys`]
//! and [`Value::apply_merge_keys_with_limits`] bound merge depth and merged
//! mapping sizes; `from_value`,
//! `from_value_seed`, and `to_value` operate on an in-memory [`Value`] and do
//! not take limits. Exceeding a limit
//! returns [`ErrorKind::Limit`]; [`Error::limit`] exposes the structured
//! [`LimitExceeded`] value. See the `docs/limits.md` file for the defaults and
//! the alias-budget formula.
//!
//! # Errors and spans
//!
//! [`Error`] implements [`Clone`], [`PartialEq`], and [`Eq`], and carries a
//! coarse category ([`Error::kind`] -> [`ErrorKind`]), a stable
//! machine-readable code ([`Error::code`] -> [`ErrorCode`], with
//! [`ErrorCode::as_str`] returning `yaml.<kebab-name>`), an optional byte
//! span, an optional source error, and a human-readable message. Input-related
//! errors carry a span and [`Error::location`] returns the one-based line and
//! column. Normal [`Display`](std::fmt::Display) and [`Debug`](std::fmt::Debug)
//! output on [`Error`] may include text from the document (such as scalar
//! values, mapping keys, paths, tags, or directives); use [`Error::masked`]
//! ([`MaskedError`]) when logging or returning errors from sensitive or
//! untrusted documents. See the documentation site
//! (<https://asamarts.github.io/ayaml/>) — including `docs/error-codes.md`,
//! `docs/security.md`, and `docs/stability.md` — for the full code reference,
//! security and untrusted-input guidance, stability guarantees, and masked
//! error formatting. Events carry their own spans for source-aware tooling.
//!
//! # Minimum supported Rust version
//!
//! Rust 1.88. The crate is dual-licensed under MIT or Apache-2.0.
#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![warn(rustdoc::all)]

#[allow(
    dead_code,
    reason = "the conformance and benchmark layers use these hooks only under their features"
)]
mod composer;
mod emitter;
mod event_emitter;
mod frontmatter;
mod merge;
mod options;
#[allow(
    dead_code,
    reason = "the conformance and benchmark layers use these hooks only under their features"
)]
mod parser;
#[allow(
    dead_code,
    reason = "the conformance and benchmark layers use these hooks only under their features"
)]
mod position;
#[allow(
    dead_code,
    reason = "the conformance and benchmark layers use these hooks only under their features"
)]
mod resolver;
#[allow(
    dead_code,
    reason = "the conformance and benchmark layers use these hooks only under their features"
)]
mod scanner;
mod scratch;
mod serde_impl;
mod spanned;
mod typed;

pub mod error;
pub mod event;
pub mod limits;
pub mod mapping;
pub mod number;
pub mod span;
pub mod tag;
pub mod tape;
pub mod value;

pub use error::{Error, ErrorCode, ErrorKind, MaskedError};
pub use event::{Anchor, CollectionStyle, Event, ScalarStyle};
pub use frontmatter::{Frontmatter, FrontmatterDelimiter, ParsedFrontmatter};
pub use limits::{
    ALIAS_BYTES_PER_INPUT_BYTE, COMPAT_MAX_DOCUMENTS, DEFAULT_MAX_DOCUMENTS, LimitExceeded,
    LimitKind, Limits, MAX_ALIAS_EXPANSION_BYTES, MAX_DEPTH, MAX_DEPTH_CAP, MAX_INPUT_BYTES,
    MAX_TAG_EXPANSION_BYTES, NODE_COST_BYTES,
};
pub use mapping::{Entry, Mapping};
pub use number::Number;
pub use options::{EmitOptions, ParseOptions};
pub use position::{ColumnEncoding, LineIndex, PositionError};
pub use scratch::ParserBuf;
pub use span::{Location, Position, Span, Spanned};
pub use spanned::{SpannedMapIter, SpannedNode, SpannedTree};
pub use tag::{Tag, TaggedValue};
pub use tape::{
    Tape, TapeDocuments, TapeDocumentsIter, TapeKind, TapeMapIter, TapeRef, TapeSeqIter,
};
pub use typed::DocumentDeserializer;
pub use value::Value;

pub use emitter::{
    Chomping, Emitter, EmitterOptions, EmitterStyles, NodeStyle, PathSegment, to_string,
    to_string_documents, to_string_documents_with, to_string_value, to_string_value_with,
    to_string_with, to_writer, to_writer_documents, to_writer_documents_with, to_writer_value,
    to_writer_value_with, to_writer_with,
};
pub use event_emitter::{
    to_string_events, to_string_events_with, to_writer_event_stream, to_writer_event_stream_with,
    to_writer_events, to_writer_events_with,
};
pub use serde_impl::{from_value, from_value_seed, to_value};

/// Libyaml-compatible parsing and decoding.
///
/// This module is additive: enabling [`libyaml-compat`](crate#features) never
/// changes the root parsing functions. It reproduces libyaml-compatible
/// behavior for callers that need it, including scanner quirks that the
/// default YAML 1.2.2 parser deliberately does not adopt.
#[cfg(feature = "libyaml-compat")]
#[cfg_attr(docsrs, doc(cfg(feature = "libyaml-compat")))]
pub mod compat {
    use crate::error::{Error, ErrorCode, ErrorKind};
    use crate::limits::LimitKind;
    use serde::de::Visitor;

    /// How compatibility typed readers treat global tags outside the YAML 1.2 core schema, such as
    /// `!!timestamp`, `!!binary`, `!<tag:example.com,2000:x>`, or a `%TAG` handle mapped to a URI.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum GlobalTags {
        /// Keep global tags on their nodes, as the default readers do.
        #[default]
        Keep,
        /// Drop global tags outside the core schema, as a libyaml-based reader does.
        ///
        /// A scalar beneath a dropped global tag reads as its text for a target that reads any
        /// value and parses as the requested type for a typed target. A collection beneath one
        /// reads as if it had no tag. Core-schema tags, the non-specific `!` tag, and local tags
        /// keep their usual reading.
        Drop,
    }

    /// Options for [`compat`](crate::compat) readers.
    #[derive(Clone, Debug, PartialEq, Eq)]
    #[non_exhaustive]
    pub struct ParseOptions {
        /// Resource limits applied to the parse.
        pub limits: crate::Limits,
        /// How global tags outside the YAML 1.2 core schema are handled by
        /// typed and visitor readers. Event readers and
        /// [`SpannedTree::parse_compat_with`](crate::SpannedTree::parse_compat_with)
        /// preserve syntax tags as written.
        pub global_tags: GlobalTags,
        /// Whether duplicate mapping keys are accepted (last-wins, matching
        /// libyaml) or rejected with [`ErrorCode::DuplicateKey`].
        ///
        /// Defaults to `true` for libyaml compatibility. Set to `false` to keep
        /// relaxed libyaml flow-collection scanning while rejecting duplicate
        /// mapping keys in typed and visitor readers.
        pub allow_duplicates: bool,
    }

    impl Default for ParseOptions {
        fn default() -> Self {
            Self::new()
        }
    }

    impl From<crate::Limits> for ParseOptions {
        fn from(limits: crate::Limits) -> Self {
            Self::new().with_limits(limits)
        }
    }

    impl ParseOptions {
        /// Compatibility parse options with the default limits, [`GlobalTags::Keep`],
        /// and `allow_duplicates = true`.
        #[must_use]
        pub const fn new() -> Self {
            Self {
                limits: crate::Limits::default_profile(),
                global_tags: GlobalTags::Keep,
                allow_duplicates: true,
            }
        }

        /// Compatibility parse options using [`Limits::for_max_input`](crate::Limits::for_max_input),
        /// [`GlobalTags::Keep`], and `allow_duplicates = true`.
        #[must_use]
        pub const fn for_max_input() -> Self {
            Self {
                limits: crate::Limits::for_max_input(),
                global_tags: GlobalTags::Keep,
                allow_duplicates: true,
            }
        }

        /// Set the resource limits applied to the parse.
        #[must_use]
        pub const fn with_limits(mut self, limits: crate::Limits) -> Self {
            self.limits = limits;
            self
        }

        /// Set how global tags outside the YAML 1.2 core schema are handled.
        #[must_use]
        pub const fn with_global_tags(mut self, global_tags: GlobalTags) -> Self {
            self.global_tags = global_tags;
            self
        }

        /// Set whether duplicate mapping keys are accepted (`true`, last-wins) or
        /// rejected with [`ErrorCode::DuplicateKey`] (`false`).
        #[must_use]
        pub const fn with_allow_duplicates(mut self, allow_duplicates: bool) -> Self {
            self.allow_duplicates = allow_duplicates;
            self
        }
    }

    pub(crate) const fn node_options(options: &ParseOptions) -> crate::typed::NodeOptions {
        crate::typed::NodeOptions {
            allow_duplicates: options.allow_duplicates,
            compat_flow: true,
            drop_global_tags: matches!(options.global_tags, GlobalTags::Drop),
        }
    }

    fn preserve_span_and_location(mut mapped: Error, original: &Error) -> Error {
        if let Some(span) = original.span() {
            mapped = mapped.with_span(span);
        }
        if let Some(location) = original.location() {
            mapped = mapped.with_location(location);
        }
        mapped
    }

    /// Translate ayaml diagnostics into the strings expected by
    /// libyaml-compatible consumers. Each branch is a documented compatibility
    /// deviation keyed by the parser's structured failure, never by the text of
    /// the input or of the message.
    pub(crate) fn map_error(error: Error) -> Error {
        if error.is_reserved_after_bom() {
            let mapped = Error::coded(
                ErrorKind::Scanner,
                ErrorCode::ReservedIndicator,
                "found character that cannot start any token",
            );
            return preserve_span_and_location(mapped, &error);
        }
        if let Some(limit) = error
            .limit()
            .filter(|limit| limit.kind() == LimitKind::Depth)
        {
            let mapped = Error::coded(
                ErrorKind::Serde,
                ErrorCode::DepthLimit,
                "recursion limit exceeded",
            )
            .with_limit(limit);
            return preserve_span_and_location(mapped, &error);
        }
        if error.code() == ErrorCode::UnexpectedMappingValue {
            let mapped = Error::coded(
                ErrorKind::Parser,
                ErrorCode::UnexpectedMappingValue,
                "mapping values are not allowed in this context",
            );
            return preserve_span_and_location(mapped, &error);
        }
        if error.code() == ErrorCode::TrailingDocuments
            || error
                .limit()
                .is_some_and(|limit| limit.kind() == LimitKind::Documents)
        {
            let mut mapped = Error::coded(
                ErrorKind::Parser,
                error.code(),
                "more than one document in stream",
            );
            if let Some(limit) = error.limit() {
                mapped = mapped.with_limit(limit);
            }
            return preserve_span_and_location(mapped, &error);
        }
        error
    }

    /// Deserialize one document with a caller-supplied seed under the
    /// compatibility policies.
    ///
    /// Inputs at every size are streamed directly into the seed as they are parsed, as
    /// [`from_str`](crate::from_str) says. A seed that writes to its caller's data as it reads
    /// may have written the start of a document that is then refused, so on an error what it
    /// wrote is to be dropped.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_seed<'de, T: serde::de::DeserializeSeed<'de>>(
        input: &'de str,
        seed: T,
    ) -> Result<T::Value, Error> {
        from_str_seed_with(input, &ParseOptions::new(), seed)
    }

    /// Deserialize one document with a caller-supplied seed and compatibility options.
    ///
    /// What [`from_str_seed`] says of a document that is refused holds here.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_seed_with<'de, T: serde::de::DeserializeSeed<'de>>(
        input: &'de str,
        options: &ParseOptions,
        seed: T,
    ) -> Result<T::Value, Error> {
        crate::typed::from_str_seed_with_options(
            input,
            &options.limits,
            node_options(options),
            seed,
        )
        .map_err(map_error)
    }

    /// Deserialize a typed value with compatibility policies, using borrowed
    /// scalar text where possible.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str<'de, T: serde::Deserialize<'de>>(input: &'de str) -> Result<T, Error> {
        from_str_with(input, &ParseOptions::new())
    }

    /// Deserialize a typed value with compatibility options, using borrowed scalar text where
    /// possible.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_with<'de, T: serde::Deserialize<'de>>(
        input: &'de str,
        options: &ParseOptions,
    ) -> Result<T, Error> {
        crate::typed::from_str_with_options(input, &options.limits, node_options(options))
            .map_err(map_error)
    }

    /// Deserialize a typed value with compatibility policies, reusing scratch from `buf`.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_in<'de, T: serde::Deserialize<'de>>(
        input: &'de str,
        buf: &mut crate::ParserBuf,
    ) -> Result<T, Error> {
        from_str_with_in(input, &ParseOptions::new(), buf)
    }

    /// Deserialize a typed value with compatibility options, reusing scratch from `buf`.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_with_in<'de, T: serde::Deserialize<'de>>(
        input: &'de str,
        options: &ParseOptions,
        buf: &mut crate::ParserBuf,
    ) -> Result<T, Error> {
        crate::typed::from_str_with_options_in(input, &options.limits, node_options(options), buf)
            .map_err(map_error)
    }

    /// Deserialize one document with a caller-supplied seed under compatibility policies,
    /// reusing scratch from `buf`.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_seed_in<'de, T: serde::de::DeserializeSeed<'de>>(
        input: &'de str,
        seed: T,
        buf: &mut crate::ParserBuf,
    ) -> Result<T::Value, Error> {
        from_str_seed_with_in(input, &ParseOptions::new(), seed, buf)
    }

    /// Deserialize one document with a caller-supplied seed and compatibility options,
    /// reusing scratch from `buf`.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_seed_with_in<'de, T: serde::de::DeserializeSeed<'de>>(
        input: &'de str,
        options: &ParseOptions,
        seed: T,
        buf: &mut crate::ParserBuf,
    ) -> Result<T::Value, Error> {
        crate::typed::from_str_seed_with_options_in(
            input,
            &options.limits,
            node_options(options),
            seed,
            buf,
        )
        .map_err(map_error)
    }

    /// Parse a stream into a lazy event traversal with the libyaml-compatible scanner.
    ///
    /// As in default mode, an alias is reported as written and is not checked against earlier
    /// anchors; the compatibility value readers do that check.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn parse_events(input: &str) -> Result<crate::EventStream<'_>, Error> {
        parse_events_with(input, &ParseOptions::new())
    }

    /// Parse a stream into a lazy event traversal with explicit compatibility
    /// options and the libyaml-compatible scanner.
    ///
    /// Applies `options.limits`. Aliases and tags are reported as written;
    /// `options.global_tags` applies only to typed and visitor readers.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn parse_events_with<'a>(
        input: &'a str,
        options: &ParseOptions,
    ) -> Result<crate::EventStream<'a>, Error> {
        crate::parser::EventCursor::with_compat(input, &options.limits, true)
            .map(crate::EventStream::from_cursor)
    }

    /// Parse a whole stream into an eager event vector with explicit
    /// compatibility options and the libyaml-compatible scanner. The
    /// conformance runner uses this to check compatibility deviations.
    ///
    /// Applies `options.limits`. Aliases and tags are reported as written;
    /// `options.global_tags` applies only to typed and visitor readers.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn parse_events_eager_with<'a>(
        input: &'a str,
        options: &ParseOptions,
    ) -> Result<Vec<crate::Event<'a>>, Error> {
        crate::parser::parse_events_compat(input, &options.limits)
    }

    /// Deserialize one document with a visitor and compatibility policies.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn deserialize_any<'de, V: Visitor<'de>>(
        input: &'de str,
        visitor: V,
    ) -> Result<V::Value, Error> {
        deserialize_any_with(input, &ParseOptions::new(), visitor)
    }

    /// Deserialize one document with a visitor and compatibility options.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn deserialize_any_with<'de, V: Visitor<'de>>(
        input: &'de str,
        options: &ParseOptions,
        visitor: V,
    ) -> Result<V::Value, Error> {
        crate::typed::from_str_visitor(input, &options.limits, node_options(options), visitor)
            .map_err(map_error)
    }
}

/// Unstable layer hooks for the benchmark harness.
///
/// **Unstable and outside SemVer.** This module is hidden from the public
/// documentation and exists only for ayaml's benchmark and
/// conformance harnesses. It may change or disappear in any release.
#[cfg(feature = "bench-internals")]
#[cfg_attr(docsrs, doc(cfg(feature = "bench-internals")))]
#[doc(hidden)]
pub mod internals {
    use crate::error::Error;
    use crate::event::Event;
    use crate::limits::Limits;
    use crate::value::Value;

    /// Scan all tokens and return their count.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn scan_tokens(input: &str, limits: &Limits) -> Result<usize, Error> {
        let mut scanner = crate::scanner::Scanner::new(input, limits).map_err(|error| *error)?;
        let mut count = 0;
        while scanner
            .next_token(limits)
            .map_err(|error| *error)?
            .is_some()
        {
            count += 1;
        }
        Ok(count)
    }

    /// Parse all events into an owned vector.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn parse_events<'a>(input: &'a str, limits: &Limits) -> Result<Vec<Event<'a>>, Error> {
        crate::parser::parse_events(input, limits)
    }

    /// Compose an already-collected event vector. Like every entry point that takes limits, it
    /// refuses limits that would turn a budget off.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn compose_events(
        events: &[Event<'_>],
        input_len: usize,
        limits: &Limits,
    ) -> Result<Vec<Value>, Error> {
        limits.validate()?;
        crate::composer::compose_documents(events, input_len, limits)
    }

    /// Decode one document into a typed value by building its whole tree first (internal oracle).
    /// `compat` reads with the compatibility scanner and keeps duplicate
    /// keys, as `compat::from_str` does, but reports errors as default mode words them. The
    /// tests compare this reader with [`from_str_by_events`].
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_by_tree<'de, T: serde::Deserialize<'de>>(
        input: &'de str,
        limits: &Limits,
        compat: bool,
    ) -> Result<T, Error> {
        from_str_by_tree_with(input, limits, compat, false)
    }

    /// [`from_str_by_tree`], with an opt-in to drop non-core global tags.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_by_tree_with<'de, T: serde::Deserialize<'de>>(
        input: &'de str,
        limits: &Limits,
        compat: bool,
        drop_global_tags: bool,
    ) -> Result<T, Error> {
        crate::typed::from_str_by_tree(
            input,
            limits,
            crate::typed::NodeOptions {
                allow_duplicates: compat,
                compat_flow: compat,
                drop_global_tags,
            },
            std::marker::PhantomData::<T>,
        )
    }

    /// Decode one document into a typed value directly from the parser's events, matching
    /// [`crate::from_str`]. `compat` is as for [`from_str_by_tree`].
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_by_events<'de, T: serde::Deserialize<'de>>(
        input: &'de str,
        limits: &Limits,
        compat: bool,
    ) -> Result<T, Error> {
        from_str_by_events_with(input, limits, compat, false)
    }

    /// [`from_str_by_events`], with an opt-in to drop non-core global tags.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_by_events_with<'de, T: serde::Deserialize<'de>>(
        input: &'de str,
        limits: &Limits,
        compat: bool,
        drop_global_tags: bool,
    ) -> Result<T, Error> {
        crate::typed::from_str_by_events(
            input,
            limits,
            crate::typed::NodeOptions {
                allow_duplicates: compat,
                compat_flow: compat,
                drop_global_tags,
            },
            std::marker::PhantomData::<T>,
        )
    }
}

#[allow(
    clippy::large_enum_variant,
    reason = "the default EventCursor path stays unboxed to avoid an extra heap allocation on every parse_events call"
)]
#[derive(Debug)]
enum EventStreamInner<'a> {
    Cursor(parser::EventCursor<'a>),
    Merged(Box<merge::events::MergedEventStream<'a>>),
}

/// A pull traversal over spanned parser events.
///
/// Events are produced lazily through a bounded line/token window and event queue.
/// Pulling stops further scanning when the consumer drops the stream, and syntax
/// errors are returned as iterator items rather than being discovered only after
/// the whole input is parsed. An alias is reported as written and is not checked
/// against earlier anchors; composing values does that check.
#[derive(Debug)]
pub struct EventStream<'a> {
    inner: EventStreamInner<'a>,
}

impl<'a> EventStream<'a> {
    pub(crate) fn next_document(
        &mut self,
        budget: &mut limits::AliasBudget,
    ) -> Result<Option<Vec<Event<'a>>>, Error> {
        match &mut self.inner {
            EventStreamInner::Cursor(cursor) => cursor.next_document(),
            EventStreamInner::Merged(merged) => merged.next_document_with_budget(budget),
        }
    }
}

#[cfg(feature = "libyaml-compat")]
impl<'a> EventStream<'a> {
    pub(crate) fn from_cursor(inner: parser::EventCursor<'a>) -> Self {
        Self {
            inner: EventStreamInner::Cursor(inner),
        }
    }
}

impl<'a> Iterator for EventStream<'a> {
    type Item = Result<Event<'a>, Error>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.inner {
            EventStreamInner::Cursor(cursor) => cursor.next_event().transpose(),
            EventStreamInner::Merged(merged) => merged.next_event().transpose(),
        }
    }
}

/// A document-bounded typed deserializer.
///
/// This consumes one YAML document at a time from the public event traversal.
/// Both [`next`](Self::next) and [`next_borrowed`](Self::next_borrowed) decode
/// directly from spanned events, preserving per-node source spans on Serde
/// errors without composing an intermediate owned [`Value`];
/// [`next_borrowed`](Self::next_borrowed) additionally allows targets to borrow
/// simple scalar strings from the input. The aliases of every document draw on
/// one alias budget for the whole stream.
#[derive(Debug)]
pub struct Deserializer<'a> {
    events: EventStream<'a>,
    limits: Limits,
    input: &'a str,
    input_len: usize,
    finished: bool,
    /// One alias budget for the whole stream.
    budget: limits::AliasBudget,
}

impl<'a> Deserializer<'a> {
    /// Create a typed document cursor over one UTF-8 YAML input.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    #[allow(
        clippy::should_implement_trait,
        reason = "the cursor deliberately mirrors Iterator::next with a different return type"
    )]
    pub fn from_str(input: &'a str) -> Result<Self, Error> {
        Self::from_str_with(input, &ParseOptions::new())
    }

    /// Create a typed document cursor with explicit parse options.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn from_str_with(input: &'a str, options: &ParseOptions) -> Result<Self, Error> {
        let events = parse_events_with(input, options)?;
        Ok(Self {
            events,
            limits: options.limits.clone(),
            input,
            input_len: input.len(),
            finished: false,
            budget: limits::AliasBudget::default(),
        })
    }

    /// Deserialize the next document, or return `None` at end of stream.
    ///
    /// Decodes directly from spanned events so Serde errors preserve per-node
    /// source spans without materializing an intermediate owned [`Value`].
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    #[allow(
        clippy::should_implement_trait,
        reason = "the cursor deliberately mirrors Iterator::next with a different return type"
    )]
    pub fn next<T: serde::de::DeserializeOwned>(&mut self) -> Result<Option<T>, Error> {
        self.next_borrowed()
    }

    /// Deserialize the next document, borrowing simple strings from the input.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn next_borrowed<T: serde::Deserialize<'a>>(&mut self) -> Result<Option<T>, Error> {
        let Some(events) = self.next_events()? else {
            return Ok(None);
        };
        typed::from_events(events, self.input_len, &self.limits, &mut self.budget)
            .map(Some)
            .map_err(|error| error.with_input_location(self.input, false))
    }

    /// Deserialize the next document with a seed, borrowing simple strings.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn next_seed_borrowed<T: serde::de::DeserializeSeed<'a>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>, Error> {
        let Some(events) = self.next_events()? else {
            return Ok(None);
        };
        typed::from_events_seed(events, self.input_len, &self.limits, &mut self.budget, seed)
            .map(Some)
            .map_err(|error| error.with_input_location(self.input, false))
    }

    /// Deserialize the next document using a caller-supplied seed.
    ///
    /// Decodes directly from spanned events so Serde errors preserve per-node
    /// source spans without materializing an intermediate owned [`Value`].
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
    pub fn next_seed<'de, T: serde::de::DeserializeSeed<'de>>(
        &mut self,
        seed: T,
    ) -> Result<Option<T::Value>, Error> {
        let Some(events) = self.next_events()? else {
            return Ok(None);
        };
        typed::from_events_seed_owned(events, self.input_len, &self.limits, &mut self.budget, seed)
            .map(Some)
            .map_err(|error| error.with_input_location(self.input, false))
    }

    fn next_events(&mut self) -> Result<Option<Vec<Event<'a>>>, Error> {
        if self.finished {
            return Ok(None);
        }
        match self.events.next_document(&mut self.budget) {
            Ok(Some(events)) => Ok(Some(events)),
            Ok(None) => {
                self.finished = true;
                Ok(None)
            }
            Err(error) => {
                self.finished = true;
                Err(error)
            }
        }
    }
}

/// Parse a YAML input into a pull traversal of spanned events.
///
/// This exposes the shared scanner/parser pipeline without composing values.
/// Duplicate mapping entries remain visible to the caller. Syntax and limit
/// errors are returned by the iterator.
///
/// An [`Event::Alias`] is reported as written. These readers do not check that an earlier anchor
/// in the document defines it; the value readers compose and check aliases. A consumer that
/// resolves aliases must track anchors itself.
///
/// ```
/// let events: Vec<ayaml::Event<'_>> = ayaml::parse_events("a: *missing\n")?
///     .collect::<Result<_, _>>()?;
/// assert!(events.iter().any(|event| matches!(event, ayaml::Event::Alias { .. })));
/// assert!(ayaml::parse_value("a: *missing\n").is_err());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn parse_events(input: &str) -> Result<EventStream<'_>, Error> {
    parse_events_with(input, &ParseOptions::new())
}

/// Parse a YAML input into a pull traversal with explicit parse options.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn parse_events_with<'a>(
    input: &'a str,
    options: &ParseOptions,
) -> Result<EventStream<'a>, Error> {
    options.limits.validate()?;
    options.limits.check_input(input.len()).map_err(|error| {
        Error::from(error)
            .with_span(Span::empty(0))
            .with_location(Location::new(1, 1))
    })?;
    if options.merge_keys {
        merge::events::MergedEventStream::new(input, &options.limits).map(|merged| EventStream {
            inner: EventStreamInner::Merged(Box::new(merged)),
        })
    } else {
        parser::EventCursor::new(input, &options.limits).map(|cursor| EventStream {
            inner: EventStreamInner::Cursor(cursor),
        })
    }
}

/// Parse one YAML document into the generic value model.
///
/// The default YAML 1.2.2 profile is used: `yes` and date-like scalars stay
/// strings, legacy octal-looking scalars such as `0123` stay strings, `0b11`
/// and `0x1f` become integers, and `1e3` becomes a float. Custom tags remain
/// represented as [`Value::Tagged`]. Anchors and aliases are materialized under
/// the default alias-expansion budget; merge keys stay literal.
///
/// This is a single-document convenience API. Trailing documents are rejected;
/// use [`parse_documents`] for a document stream.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn parse_value(input: &str) -> Result<Value, Error> {
    parse_value_with(input, &ParseOptions::new())
}

/// Parse one YAML document with explicit parse options.
///
/// Limits are checked before scanning and again during composition. The input
/// is never allowed to exceed `options.limits.max_input_bytes`, and alias
/// materialization is charged before allocation. Trailing documents are
/// rejected even when the limits would otherwise permit them.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn parse_value_with(input: &str, options: &ParseOptions) -> Result<Value, Error> {
    if options.merge_keys {
        let (events, mut budget) = merge::events::expand_single_document(input, &options.limits)?;
        let mut docs = composer::compose_documents_with_budget(
            events,
            input.len(),
            &options.limits,
            &mut budget,
        )
        .map_err(|error| error.with_input_location(input, false))?;
        return Ok(docs.pop().unwrap_or(Value::Null));
    }
    parse_single_value(input, &options.limits)
}

fn parse_single_value(input: &str, limits: &Limits) -> Result<Value, Error> {
    limits.validate()?;
    limits.check_input(input.len()).map_err(|error| {
        Error::from(error)
            .with_span(Span::empty(0))
            .with_location(Location::new(1, 1))
    })?;
    parser::parse_value(input, limits)
}

/// Parse every YAML document in the stream into generic values.
///
/// The same default resolver and composition budgets as [`parse_value`]
/// apply. The configured `max_documents` limit is enforced by the event parser.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn parse_documents(input: &str) -> Result<Vec<Value>, Error> {
    parse_documents_with(input, &ParseOptions::new())
}

/// Parse every YAML document in the stream with explicit parse options.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn parse_documents_with(input: &str, options: &ParseOptions) -> Result<Vec<Value>, Error> {
    if options.merge_keys {
        let (events, mut budget) = merge::events::expand_all_documents(input, &options.limits)?;
        return composer::compose_documents_with_budget(
            events,
            input.len(),
            &options.limits,
            &mut budget,
        )
        .map_err(|error| error.with_input_location(input, false));
    }
    parse_stream_documents(input, &options.limits)
}

fn parse_stream_documents(input: &str, limits: &Limits) -> Result<Vec<Value>, Error> {
    limits.validate()?;
    limits.check_input(input.len()).map_err(|error| {
        Error::from(error)
            .with_span(Span::empty(0))
            .with_location(Location::new(1, 1))
    })?;
    parser::parse_documents(input, limits, false)
}

/// Deserialize one YAML document into a typed Serde value.
///
/// An empty document can decode into a defaulted struct. A duplicate key is an error, placed
/// at the key that repeats an earlier one, and the alias limits are enforced. Trailing
/// documents are rejected. An error names the span of the YAML node it is about. Use
/// `ayaml::compat` for libyaml-compatible decoding.
///
/// Inputs at every size are streamed directly into the target as they are parsed. The value and
/// the error are what they would be otherwise, but the target's `Deserialize` may have run on the
/// start of a document that is then refused, and collection size hints are bounded by the
/// parser's lookahead window (exact for root flow collections and small collections inside the
/// lookahead queue).
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn from_str<T: serde::de::DeserializeOwned>(input: &str) -> Result<T, Error> {
    typed::from_str(input, &Limits::default_profile())
}

/// Deserialize one YAML document into a typed Serde value with explicit parse
/// options, borrowing simple strings from `input` where possible.
///
/// Accepts both owned (`DeserializeOwned`) and borrowed (`Deserialize<'de>`)
/// targets. See [`from_str`] and [`from_str_borrowed`] for the decoding rules.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn from_str_with<'de, T: serde::Deserialize<'de>>(
    input: &'de str,
    options: &ParseOptions,
) -> Result<T, Error> {
    if options.merge_keys {
        return typed::from_str_with_merged(input, &options.limits, std::marker::PhantomData::<T>);
    }
    typed::from_str(input, &options.limits)
}

/// Deserialize one YAML document while borrowing simple strings from `input`.
///
/// It reads as [`from_str`] does, and its target may borrow from `input`: a plain,
/// single-quoted, or unescaped double-quoted scalar string on one line can be returned as
/// `&str` or `Cow::Borrowed`. A string that decoding changes, such as a folded or escaped one,
/// is owned, so only a `Cow` or a `String` can hold it.
///
/// ```
/// #[derive(serde::Deserialize)]
/// struct Config<'a> {
///     name: &'a str,
/// }
///
/// let config: Config<'_> = ayaml::from_str_borrowed("name: ayaml\n").unwrap();
/// assert_eq!(config.name, "ayaml");
/// ```
///
/// Trailing documents are rejected.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn from_str_borrowed<'de, T: serde::Deserialize<'de>>(input: &'de str) -> Result<T, Error> {
    typed::from_str(input, &Limits::default_profile())
}

/// Deserialize one YAML document with a caller-supplied seed, borrowing simple strings from
/// `input`.
///
/// It reads as [`from_str_borrowed`] does, under the default YAML 1.2.2 rules and limits.
/// Duplicate keys and trailing documents are rejected. Inputs at every size are streamed directly
/// into the seed as they are parsed, as [`from_str`] says: a seed that writes to its caller's data
/// as it reads may have written the start of a document that is then refused, so on an error what
/// it wrote is to be dropped.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn from_str_seed<'de, T: serde::de::DeserializeSeed<'de>>(
    input: &'de str,
    seed: T,
) -> Result<T::Value, Error> {
    from_str_seed_with(input, &ParseOptions::new(), seed)
}

/// Deserialize one YAML document with a caller-supplied seed and explicit
/// parse options, borrowing simple strings from `input`.
///
/// What [`from_str_seed`] says of a document that is refused holds here.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn from_str_seed_with<'de, T: serde::de::DeserializeSeed<'de>>(
    input: &'de str,
    options: &ParseOptions,
    seed: T,
) -> Result<T::Value, Error> {
    if options.merge_keys {
        return typed::from_str_with_merged(input, &options.limits, seed);
    }
    typed::from_str_seed_with_options(input, &options.limits, typed::NodeOptions::default(), seed)
}

/// Deserialize one UTF-8 YAML document from bytes, borrowing simple strings.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn from_slice_borrowed<'de, T: serde::Deserialize<'de>>(input: &'de [u8]) -> Result<T, Error> {
    from_slice_with(input, &ParseOptions::new())
}

/// Deserialize one UTF-8 YAML document from bytes.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn from_slice<T: serde::de::DeserializeOwned>(input: &[u8]) -> Result<T, Error> {
    from_slice_with(input, &ParseOptions::new())
}

/// Deserialize one UTF-8 YAML document from bytes with explicit parse options,
/// borrowing simple strings from `input` where possible.
///
/// Checks `options.limits` before validating UTF-8 so oversized byte slices
/// fail without scanning the whole buffer. Accepts both owned
/// (`DeserializeOwned`) and borrowed (`Deserialize<'de>`) targets.
///
/// # Errors
///
/// Returns an error when the input is invalid, a configured limit is exceeded, or the target cannot be decoded.
pub fn from_slice_with<'de, T: serde::Deserialize<'de>>(
    input: &'de [u8],
    options: &ParseOptions,
) -> Result<T, Error> {
    from_str_with(text_of_with(input, &options.limits)?, options)
}

/// Deserialize one UTF-8 YAML document from an I/O reader under the default limits.
///
/// Reads at most `Limits::default().max_input_bytes + 1` bytes from `reader` before
/// failing with [`ErrorKind::Limit`] (`LimitKind::InputBytes`), preventing unbounded
/// reads from hostile or infinite streams.
///
/// ```
/// #[derive(serde::Deserialize)]
/// struct Config {
///     name: String,
/// }
///
/// let config: Config = ayaml::from_reader("name: ayaml\n".as_bytes()).unwrap();
/// assert_eq!(config.name, "ayaml");
/// ```
///
/// Trailing documents are rejected.
///
/// # Errors
///
/// Returns [`ErrorKind::Io`] when reading from `reader` fails, [`ErrorKind::Limit`]
/// when a configured limit is exceeded, [`ErrorKind::InvalidEncoding`] when the input
/// is not valid UTF-8, or a parse/Serde error when the document or target is invalid.
pub fn from_reader<R: std::io::Read, T: serde::de::DeserializeOwned>(
    reader: R,
) -> Result<T, Error> {
    from_reader_with(reader, &ParseOptions::new())
}

/// Deserialize one UTF-8 YAML document from an I/O reader with explicit parse options.
///
/// Reads at most `options.limits.max_input_bytes + 1` bytes from `reader` before
/// failing with [`ErrorKind::Limit`] (`LimitKind::InputBytes`), preventing unbounded
/// reads from hostile or infinite streams.
///
/// # Errors
///
/// Returns [`ErrorKind::Io`] when reading from `reader` fails, [`ErrorKind::Limit`]
/// when `options.limits` is invalid or a configured limit is exceeded,
/// [`ErrorKind::InvalidEncoding`] when the input is not valid UTF-8, or a parse/Serde
/// error when the document or target is invalid.
pub fn from_reader_with<R: std::io::Read, T: serde::de::DeserializeOwned>(
    reader: R,
    options: &ParseOptions,
) -> Result<T, Error> {
    let bytes = read_bounded(reader, &options.limits)?;
    let text = text_of_with(&bytes, &options.limits)?;
    from_str_with(text, options)
}

/// Read at most `limits.max_input_bytes + 1` bytes from `reader` after validating `limits`.
fn read_bounded<R: std::io::Read>(reader: R, limits: &Limits) -> Result<Vec<u8>, Error> {
    use std::io::Read as _;

    limits.validate()?;
    let read_cap = u64::try_from(limits.max_input_bytes)
        .unwrap_or(u64::MAX)
        .saturating_add(1);
    let mut bytes = Vec::new();
    reader
        .take(read_cap)
        .read_to_end(&mut bytes)
        .map_err(|error| {
            Error::new(ErrorKind::Io, "failed to read YAML input").with_source(error)
        })?;
    Ok(bytes)
}

/// The bytes as text, checking the configured limits before UTF-8 validation
/// so oversized slices fail without scanning all of them.
fn text_of_with<'a>(input: &'a [u8], limits: &Limits) -> Result<&'a str, Error> {
    limits.validate()?;
    limits.check_input(input.len()).map_err(|error| {
        Error::from(error)
            .with_span(Span::empty(0))
            .with_location(Location::new(1, 1))
    })?;
    std::str::from_utf8(input).map_err(|error| {
        Error::new(ErrorKind::InvalidEncoding, "input is not valid UTF-8").with_source(error)
    })
}

/// Split a leading YAML frontmatter block (`---` ... `---` or `...`) from the remaining body.
///
/// Returns `Ok(None)` when `input` does not start with a standalone `---` opening line
/// (optionally preceded by a UTF-8 BOM). When frontmatter is present, [`Frontmatter::yaml`]
/// starts at byte `0` of `input` so any [`Span`] or [`Error`] produced when parsing it aligns
/// directly with [`LineIndex::new(input)`](LineIndex::new), and [`Frontmatter::body_offset`]
/// gives the exact byte offset of [`Frontmatter::body`] into `input`.
///
/// ```
/// let doc = "---\ntitle: Hello\n---\n# Body\n";
/// let split = ayaml::split_frontmatter(doc)?.expect("frontmatter");
/// assert_eq!(split.body(), "# Body\n");
/// assert_eq!(&doc[split.body_offset()..], split.body());
/// # Ok::<(), ayaml::Error>(())
/// ```
///
/// # Errors
///
/// Returns [`ErrorKind::Limit`] when the frontmatter exceeds the default `max_input_bytes`,
/// or [`ErrorKind::Parser`] when an opening `---` line has no closing `---` or `...` delimiter.
pub fn split_frontmatter(input: &str) -> Result<Option<Frontmatter<'_>>, Error> {
    frontmatter::split_frontmatter_with_limits(input, &Limits::default_profile())
}

/// Split a leading YAML frontmatter block from `input` with explicit parse options.
///
/// Validates `options.limits` first and enforces `options.limits.max_input_bytes` on the
/// frontmatter slice without scanning past it into an oversized or non-YAML body.
///
/// # Errors
///
/// Returns [`ErrorKind::Limit`] when `options.limits` is invalid or the frontmatter exceeds
/// `options.limits.max_input_bytes`, or [`ErrorKind::Parser`] when an opening `---` line has
/// no closing `---` or `...` delimiter.
pub fn split_frontmatter_with<'a>(
    input: &'a str,
    options: &ParseOptions,
) -> Result<Option<Frontmatter<'a>>, Error> {
    frontmatter::split_frontmatter_with_limits(input, &options.limits)
}

/// Parse a leading YAML frontmatter block into a typed Serde value under the default limits,
/// returning the decoded value alongside the remaining non-YAML body slice and its byte offset.
///
/// Accepts both owned (`DeserializeOwned`) and borrowed (`Deserialize<'de>`) targets.
///
/// ```
/// #[derive(serde::Deserialize)]
/// struct Header<'a> {
///     title: &'a str,
/// }
///
/// let doc = "---\ntitle: Guide\n---\n# Heading\n";
/// let parsed: ayaml::ParsedFrontmatter<'_, Header<'_>> =
///     ayaml::parse_frontmatter(doc)?.expect("frontmatter");
/// assert_eq!(parsed.frontmatter.title, "Guide");
/// assert_eq!(parsed.body, "# Heading\n");
/// assert_eq!(&doc[parsed.body_offset..], parsed.body);
/// # Ok::<(), ayaml::Error>(())
/// ```
///
/// # Errors
///
/// Returns an error when an opening `---` line is missing its closing delimiter, when the
/// frontmatter YAML or target decoding fails, or when a configured limit is exceeded.
pub fn parse_frontmatter<'de, T: serde::Deserialize<'de>>(
    input: &'de str,
) -> Result<Option<ParsedFrontmatter<'de, T>>, Error> {
    frontmatter::parse_frontmatter_with(input, &ParseOptions::new())
}

/// Parse a leading YAML frontmatter block into a typed Serde value with explicit parse options.
///
/// # Errors
///
/// Returns an error when `options.limits` is invalid, when an opening `---` line is missing
/// its closing delimiter, when the frontmatter YAML or target decoding fails, or when a
/// configured limit is exceeded.
pub fn parse_frontmatter_with<'de, T: serde::Deserialize<'de>>(
    input: &'de str,
    options: &ParseOptions,
) -> Result<Option<ParsedFrontmatter<'de, T>>, Error> {
    frontmatter::parse_frontmatter_with(input, options)
}

/// Parse a leading YAML frontmatter block into a generic [`Value`] under the default limits.
///
/// # Errors
///
/// Returns an error when an opening `---` line is missing its closing delimiter, when the
/// frontmatter YAML is invalid, or when a configured limit is exceeded.
pub fn parse_frontmatter_value(input: &str) -> Result<Option<ParsedFrontmatter<'_, Value>>, Error> {
    frontmatter::parse_frontmatter_value_with(input, &ParseOptions::new())
}

/// Parse a leading YAML frontmatter block into a generic [`Value`] with explicit parse options.
///
/// # Errors
///
/// Returns an error when `options.limits` is invalid, when an opening `---` line is missing
/// its closing delimiter, when the frontmatter YAML is invalid, or when a configured limit
/// is exceeded.
pub fn parse_frontmatter_value_with<'a>(
    input: &'a str,
    options: &ParseOptions,
) -> Result<Option<ParsedFrontmatter<'a, Value>>, Error> {
    frontmatter::parse_frontmatter_value_with(input, options)
}

/// Parse one YAML document into a zero-copy flat-array [`Tape`].
///
/// Uses the same YAML 1.2.2 grammar, resolution, duplicate-key checks, and default
/// resource limits as [`parse_value`], storing all nodes in a compact flat array and
/// borrowing unmodified scalar slices directly from `input`.
///
/// # Errors
///
/// Returns an error when the input is invalid, contains trailing documents, or exceeds
/// a configured limit.
pub fn parse_tape(input: &str) -> Result<Tape<'_>, Error> {
    Tape::parse(input)
}

/// Parse one YAML document into a [`Tape`] with explicit parse options.
///
/// # Errors
///
/// Returns an error when `options.limits` is invalid, the input is invalid, contains
/// trailing documents, or exceeds a configured limit.
pub fn parse_tape_with<'a>(input: &'a str, options: &ParseOptions) -> Result<Tape<'a>, Error> {
    Tape::parse_with(input, options)
}

/// Parse one YAML document into a [`Tape`], reusing internal scratch buffers from `buf`.
///
/// # Errors
///
/// Returns the same errors as [`parse_tape`].
pub fn parse_tape_in<'a>(input: &'a str, buf: &mut ParserBuf) -> Result<Tape<'a>, Error> {
    Tape::parse_in(input, buf)
}

/// Parse one YAML document into a [`Tape`] with explicit options, reusing internal
/// scratch buffers from `buf`.
///
/// # Errors
///
/// Returns the same errors as [`parse_tape_with`].
pub fn parse_tape_with_in<'a>(
    input: &'a str,
    options: &ParseOptions,
    buf: &mut ParserBuf,
) -> Result<Tape<'a>, Error> {
    Tape::parse_with_in(input, options, buf)
}

/// Parse every YAML document in a stream into a zero-copy flat-array [`TapeDocuments`].
///
/// # Errors
///
/// Returns an error when the input is invalid or exceeds a configured limit.
pub fn parse_tape_documents(input: &str) -> Result<TapeDocuments<'_>, Error> {
    TapeDocuments::parse(input)
}

/// Parse every YAML document in a stream into [`TapeDocuments`] with explicit parse options.
///
/// # Errors
///
/// Returns an error when `options.limits` is invalid, the input is invalid, or a
/// configured limit is exceeded.
pub fn parse_tape_documents_with<'a>(
    input: &'a str,
    options: &ParseOptions,
) -> Result<TapeDocuments<'a>, Error> {
    TapeDocuments::parse_with(input, options)
}

/// Parse every YAML document in a stream into [`TapeDocuments`], reusing internal
/// scratch buffers from `buf`.
///
/// # Errors
///
/// Returns the same errors as [`parse_tape_documents`].
pub fn parse_tape_documents_in<'a>(
    input: &'a str,
    buf: &mut ParserBuf,
) -> Result<TapeDocuments<'a>, Error> {
    TapeDocuments::parse_in(input, buf)
}

/// Parse every YAML document in a stream into [`TapeDocuments`] with explicit options,
/// reusing internal scratch buffers from `buf`.
///
/// # Errors
///
/// Returns the same errors as [`parse_tape_documents_with`].
pub fn parse_tape_documents_with_in<'a>(
    input: &'a str,
    options: &ParseOptions,
    buf: &mut ParserBuf,
) -> Result<TapeDocuments<'a>, Error> {
    TapeDocuments::parse_with_in(input, options, buf)
}

/// Parse one YAML document into a generic [`Value`], reusing internal scratch buffers from `buf`.
///
/// # Errors
///
/// Returns the same errors as [`parse_value`].
pub fn parse_value_in(input: &str, buf: &mut ParserBuf) -> Result<Value, Error> {
    parse_value_with_in(input, &ParseOptions::new(), buf)
}

/// Parse one YAML document into a generic [`Value`] with explicit parse options,
/// reusing internal scratch buffers from `buf`.
///
/// # Errors
///
/// Returns the same errors as [`parse_value_with`].
pub fn parse_value_with_in(
    input: &str,
    options: &ParseOptions,
    buf: &mut ParserBuf,
) -> Result<Value, Error> {
    if options.merge_keys {
        return parse_value_with(input, options);
    }
    options.limits.validate()?;
    options.limits.check_input(input.len()).map_err(|error| {
        Error::from(error)
            .with_span(Span::empty(0))
            .with_location(Location::new(1, 1))
    })?;
    parser::parse_value_in(input, &options.limits, buf)
}

/// Parse every YAML document in a stream into `Vec<Value>`, reusing internal scratch
/// buffers from `buf`.
///
/// # Errors
///
/// Returns the same errors as [`parse_documents`].
pub fn parse_documents_in(input: &str, buf: &mut ParserBuf) -> Result<Vec<Value>, Error> {
    parse_documents_with_in(input, &ParseOptions::new(), buf)
}

/// Parse every YAML document in a stream into `Vec<Value>` with explicit parse options,
/// reusing internal scratch buffers from `buf`.
///
/// # Errors
///
/// Returns the same errors as [`parse_documents_with`].
pub fn parse_documents_with_in(
    input: &str,
    options: &ParseOptions,
    buf: &mut ParserBuf,
) -> Result<Vec<Value>, Error> {
    if options.merge_keys {
        return parse_documents_with(input, options);
    }
    options.limits.validate()?;
    options.limits.check_input(input.len()).map_err(|error| {
        Error::from(error)
            .with_span(Span::empty(0))
            .with_location(Location::new(1, 1))
    })?;
    parser::parse_documents_in(input, &options.limits, false, buf)
}

/// Deserialize one YAML document into `T`, reusing internal scratch buffers from `buf`.
///
/// Accepts both owned (`DeserializeOwned`) and borrowed (`Deserialize<'de>`) targets.
///
/// # Errors
///
/// Returns the same errors as [`from_str`].
pub fn from_str_in<'de, T: serde::Deserialize<'de>>(
    input: &'de str,
    buf: &mut ParserBuf,
) -> Result<T, Error> {
    typed::from_str_in(input, &Limits::default_profile(), buf)
}

/// Deserialize one YAML document into `T` with explicit parse options, reusing internal
/// scratch buffers from `buf`.
///
/// # Errors
///
/// Returns the same errors as [`from_str_with`].
pub fn from_str_with_in<'de, T: serde::Deserialize<'de>>(
    input: &'de str,
    options: &ParseOptions,
    buf: &mut ParserBuf,
) -> Result<T, Error> {
    if options.merge_keys {
        return typed::from_str_with_merged(input, &options.limits, std::marker::PhantomData::<T>);
    }
    typed::from_str_in(input, &options.limits, buf)
}

/// Deserialize one YAML document with a caller-supplied seed, reusing internal scratch
/// buffers from `buf`.
///
/// # Errors
///
/// Returns the same errors as [`from_str_seed`].
pub fn from_str_seed_in<'de, T: serde::de::DeserializeSeed<'de>>(
    input: &'de str,
    seed: T,
    buf: &mut ParserBuf,
) -> Result<T::Value, Error> {
    from_str_seed_with_in(input, &ParseOptions::new(), seed, buf)
}

/// Deserialize one YAML document with a caller-supplied seed and explicit parse options,
/// reusing internal scratch buffers from `buf`.
///
/// # Errors
///
/// Returns the same errors as [`from_str_seed_with`].
pub fn from_str_seed_with_in<'de, T: serde::de::DeserializeSeed<'de>>(
    input: &'de str,
    options: &ParseOptions,
    seed: T,
    buf: &mut ParserBuf,
) -> Result<T::Value, Error> {
    if options.merge_keys {
        return typed::from_str_with_merged(input, &options.limits, seed);
    }
    typed::from_str_seed_with_options_in(
        input,
        &options.limits,
        typed::NodeOptions::default(),
        seed,
        buf,
    )
}

/// The crate version.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

#[cfg(all(test, feature = "libyaml-compat"))]
mod compat_tests {
    use crate::{Error, ErrorCode, ErrorKind, LimitExceeded, LimitKind, Location, Span};

    #[test]
    fn compat_map_error_preserves_limit_metadata_on_remapped_limits() {
        let span = Span::new(4, 5);
        let loc = Location::new(2, 3);

        let depth = Error::from(LimitExceeded::new(LimitKind::Depth, 128, 129))
            .with_span(span)
            .with_location(loc);
        let mapped_depth = crate::compat::map_error(depth);
        assert_eq!(mapped_depth.kind(), ErrorKind::Serde);
        assert_eq!(mapped_depth.code(), ErrorCode::DepthLimit);
        assert_eq!(mapped_depth.span(), Some(span));
        assert_eq!(mapped_depth.location(), Some(loc));
        assert_eq!(
            mapped_depth.limit().map(LimitExceeded::kind),
            Some(LimitKind::Depth)
        );
        assert_eq!(mapped_depth.limit().map(LimitExceeded::observed), Some(129));

        let docs = Error::from(LimitExceeded::new(LimitKind::Documents, 1, 2))
            .with_span(span)
            .with_location(loc);
        let mapped_docs = crate::compat::map_error(docs);
        assert_eq!(mapped_docs.kind(), ErrorKind::Parser);
        assert_eq!(mapped_docs.code(), ErrorCode::DocumentCountLimit);
        assert_eq!(
            mapped_docs.limit().map(LimitExceeded::kind),
            Some(LimitKind::Documents)
        );
        assert_eq!(mapped_docs.limit().map(LimitExceeded::observed), Some(2));

        let trailing = Error::coded(
            ErrorKind::Parser,
            ErrorCode::TrailingDocuments,
            "trailing docs",
        )
        .with_span(span)
        .with_location(loc);
        let mapped_trailing = crate::compat::map_error(trailing);
        assert_eq!(mapped_trailing.kind(), ErrorKind::Parser);
        assert_eq!(mapped_trailing.code(), ErrorCode::TrailingDocuments);
        assert!(mapped_trailing.limit().is_none());

        let other = Error::coded(ErrorKind::Scanner, ErrorCode::UnexpectedToken, "bad token")
            .with_span(span)
            .with_location(loc);
        let mapped_other = crate::compat::map_error(other.clone());
        assert_eq!(mapped_other, other);
    }
}