serde-saphyr 0.0.27

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
use std::io::Read;

use serde::de::DeserializeOwned;

use super::{Error, Ev, Events, Options, ring_reader};
use crate::budget::EnforcingPolicy;
use crate::live_events::LiveEvents;
use crate::parse_scalars::scalar_is_nullish;
use crate::properties_redaction::with_interp_redaction_scope;

#[cfg(all(feature = "deserialize", feature = "include"))]
pub(crate) fn resolver_from_options<'a>(
    options: Options,
) -> Option<Box<crate::input_source::IncludeResolver<'a>>> {
    options.include_resolver.clone().map(|rc_refcell| {
        Box::new(move |req: crate::input_source::IncludeRequest<'_>| rc_refcell.borrow_mut()(req))
            as Box<crate::input_source::IncludeResolver<'a>>
    })
}

/// 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);
/// ```
#[cfg(feature = "deserialize")]
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)]
#[cfg(feature = "deserialize")]
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, false);
    let value_res = crate::anchor_store::with_document_scope(|| {
        with_interp_redaction_scope(|| {
            crate::de::with_root_redaction(crate::de::YamlDeserializer::new(&mut src, cfg), |de| {
                T::deserialize(de)
            })
        })
    });
    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_from_events(
                    err,
                    input,
                    &src,
                    with_snippet,
                    crop_radius,
                ));
            }
            return Err(maybe_with_snippet_from_events(
                e,
                input,
                &src,
                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_from_events(
                err,
                input,
                &src,
                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_from_events(
                    e,
                    input,
                    &src,
                    with_snippet,
                    crop_radius,
                ));
            }
        }
    }

    if let Err(e) = src.finish() {
        return Err(maybe_with_snippet_from_events(
            e,
            input,
            &src,
            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)]
#[cfg(feature = "deserialize")]
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)
}

#[cfg(feature = "deserialize")]
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()) {
        return err;
    }

    err.with_snippet(input, crop_radius)
}

#[cfg(feature = "deserialize")]
pub(crate) struct RootFragment<'a> {
    pub text: &'a str,
    pub start_line: usize,
    pub source_name: &'a str,
}

#[cfg(feature = "deserialize")]
pub(crate) struct ReaderSnippetContext<R> {
    shared_ring: ring_reader::SharedRingReader<R>,
    with_snippet: bool,
    crop_radius: usize,
}

#[cfg(feature = "deserialize")]
impl<R: Read> ReaderSnippetContext<R> {
    pub(crate) fn new(
        reader: R,
        with_snippet: bool,
        crop_radius: usize,
    ) -> (Self, ring_reader::SharedRingReaderHandle<R>) {
        let shared_ring = ring_reader::SharedRingReader::new(reader);
        let ring_handle = ring_reader::SharedRingReaderHandle::new(&shared_ring);
        (
            Self {
                shared_ring,
                with_snippet,
                crop_radius,
            },
            ring_handle,
        )
    }

    pub(crate) fn attach_snippet(&self, err: Error, src: &LiveEvents<'_>) -> Error {
        if !self.with_snippet || self.crop_radius == 0 {
            return err;
        }

        match self.shared_ring.get_recent() {
            Ok(snapshot) => {
                let text = String::from_utf8_lossy(&snapshot.bytes);
                let root = RootFragment {
                    text: text.as_ref(),
                    start_line: snapshot.start_line,
                    source_name: "input",
                };
                maybe_with_snippet_from_events_and_root_fragment(
                    err,
                    Some(&root),
                    text.as_ref(),
                    src,
                    self.with_snippet,
                    self.crop_radius,
                )
            }
            Err(_) => err,
        }
    }
}

#[cfg(all(feature = "deserialize", feature = "include"))]
fn with_root_additional_snippet(
    err: Error,
    root: Option<&RootFragment<'_>>,
    input: &str,
    location: &crate::Location,
    crop_radius: usize,
) -> Error {
    match root {
        Some(root) => err.with_additional_snippet_offset_named(
            root.text,
            root.start_line,
            root.source_name,
            location,
            crop_radius,
        ),
        None => err.with_additional_snippet_named(input, "input", location, crop_radius),
    }
}

#[cfg(all(feature = "deserialize", feature = "include"))]
fn recorded_source_snippet_chain<'a>(
    events: &'a crate::live_events::LiveEvents<'_>,
    location: &crate::Location,
) -> Option<Vec<&'a crate::include_stack::RecordedSource>> {
    let chain = events.recorded_source_chain(location.source_id());
    // Bail unless the innermost source has recorded text — the snippet renderer needs it.
    chain.first()?.text.as_deref()?;
    Some(chain)
}

#[cfg(all(feature = "deserialize", feature = "include"))]
fn with_recorded_source_snippets(
    err: Error,
    root: Option<&RootFragment<'_>>,
    input: &str,
    chain: &[&crate::include_stack::RecordedSource],
    crop_radius: usize,
) -> Error {
    let Some(current) = chain.first() else {
        return with_root_or_input_snippet(err, root, input, crop_radius);
    };
    let Some(source_text) = current.text.as_deref() else {
        return with_root_or_input_snippet(err, root, input, crop_radius);
    };
    let mut err_with_snippet =
        err.with_snippet_named(source_text, current.name.as_str(), crop_radius);

    for window in chain.windows(2) {
        let child = window[0];
        let parent = window[1];
        if child.include_location == crate::Location::UNKNOWN {
            continue;
        }

        match parent.text.as_deref() {
            Some(parent_text) => {
                err_with_snippet = err_with_snippet.with_additional_snippet_named(
                    parent_text,
                    parent.name.as_str(),
                    &child.include_location,
                    crop_radius,
                );
            }
            None if parent.parent_source_id.is_none() => {
                err_with_snippet = with_root_additional_snippet(
                    err_with_snippet,
                    root,
                    input,
                    &child.include_location,
                    crop_radius,
                );
            }
            None => {}
        }
    }
    err_with_snippet
}

#[cfg(all(feature = "deserialize", feature = "include"))]
fn with_root_or_input_snippet(
    err: Error,
    root: Option<&RootFragment<'_>>,
    input: &str,
    crop_radius: usize,
) -> Error {
    match root {
        Some(root) => {
            err.with_snippet_offset_named(root.text, root.start_line, root.source_name, crop_radius)
        }
        None => maybe_with_snippet(err, input, true, crop_radius),
    }
}

#[cfg(feature = "deserialize")]
pub(crate) fn maybe_with_snippet_from_events_and_root_fragment(
    err: Error,
    root: Option<&RootFragment<'_>>,
    input: &str,
    #[allow(unused_variables)] events: &crate::live_events::LiveEvents<'_>,
    with_snippet: bool,
    crop_radius: usize,
) -> Error {
    if !(with_snippet && crop_radius > 0 && err.location().is_some()) {
        return err;
    }

    #[cfg(feature = "include")]
    if let Some(loc) = err.location()
        && let Some(chain) = recorded_source_snippet_chain(events, &loc)
    {
        return with_recorded_source_snippets(err, root, input, &chain, crop_radius);
    }

    match root {
        Some(root) => {
            err.with_snippet_offset_named(root.text, root.start_line, root.source_name, crop_radius)
        }
        None => maybe_with_snippet(err, input, with_snippet, crop_radius),
    }
}

#[cfg(feature = "deserialize")]
pub(crate) fn maybe_with_snippet_from_events(
    err: Error,
    input: &str,
    #[allow(unused_variables)] events: &crate::live_events::LiveEvents<'_>,
    with_snippet: bool,
    crop_radius: usize,
) -> Error {
    maybe_with_snippet_from_events_and_root_fragment(
        err,
        None,
        input,
        events,
        with_snippet,
        crop_radius,
    )
}

/// Deserialize multiple YAML documents from a single string into a vector of `T`.
/// Completely empty documents are ignored and not included in the 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");
/// ```
#[cfg(feature = "deserialize")]
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)]
#[cfg(feature = "deserialize")]
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, 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,
                tag,
                ..
            }) if *tag == crate::tags::SfTag::Null
                || (*tag != crate::tags::SfTag::String && 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(|| {
                    with_interp_redaction_scope(|| {
                        crate::de::with_root_redaction(
                            crate::de::YamlDeserializer::new(&mut src, cfg),
                            |de| T::deserialize(de),
                        )
                    })
                });
                let value = match value_res {
                    Ok(v) => v,
                    Err(e) => {
                        return Err(maybe_with_snippet_from_events(
                            e,
                            input,
                            &src,
                            with_snippet,
                            crop_radius,
                        ));
                    }
                };
                values.push(value);
            }
            None => break,
        }
    }

    if let Err(e) = src.finish() {
        return Err(maybe_with_snippet_from_events(
            e,
            input,
            &src,
            with_snippet,
            crop_radius,
        ));
    }
    Ok(values)
}

/// Deserialize a single YAML document from a UTF-8 byte slice.
///
/// UTF-8 only (due borrowing). For UTF-16 input, use [`from_reader`] instead:
/// `let reader = std::io::Cursor::new(bytes);`
/// `let cfg: Config = serde_saphyr::from_reader(reader)?;`
///
/// This is equivalent to [`from_str`], but accepts `&[u8]` and validates it is
/// valid UTF-8 before parsing.
///
/// 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 byte slice's lifetime.
///
/// 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);
/// ```
///
#[cfg(feature = "deserialize")]
pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result<T, Error>
where
    T: serde::Deserialize<'de>,
{
    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);
/// ```
#[cfg(feature = "deserialize")]
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");
/// ```
#[cfg(feature = "deserialize")]
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 in the 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);
/// ```
#[cfg(feature = "deserialize")]
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)
}

/// Deserialize a single YAML document from any `std::io::Read`.
///
/// Reader-based entry points accept BOM-marked UTF-8, UTF-16LE, and UTF-16BE. If no
/// recognized BOM is present, the input bytes are treated as UTF-8.
///
/// This method parses 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();
/// ```
#[cfg(feature = "deserialize")]
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 and streams events into the deserializer. BOM-marked
/// UTF-8, UTF-16LE, and UTF-16BE inputs are transcoded to UTF-8 internally
/// before parsing. If no recognized BOM is present, the input bytes are
/// treated as UTF-8.
///
/// This method parses 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, total comment 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: `Budget::max_reader_input_bytes` is enforced while reading.
///   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)]
#[cfg(feature = "deserialize")]
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 (snippet_ctx, ring_handle) =
        ReaderSnippetContext::new(reader, options.with_snippet, options.crop_radius);

    let mut src = LiveEvents::from_reader(ring_handle, options, false, EnforcingPolicy::AllContent);

    let value_res = crate::anchor_store::with_document_scope(|| {
        with_interp_redaction_scope(|| {
            crate::de::with_root_redaction(crate::de::YamlDeserializer::new(&mut src, cfg), |de| {
                T::deserialize(de)
            })
        })
    });
    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(snippet_ctx
                    .attach_snippet(Error::eof().with_location(src.last_location()), &src));
            }
            return Err(snippet_ctx.attach_snippet(e, &src));
        }
    };

    // 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(snippet_ctx.attach_snippet(
                Error::multiple_documents("use read or read_with_options to obtain the iterator")
                    .with_location(src.last_location()),
                &src,
            ));
        }
        Ok(None) => {}
        Err(e) => {
            if src.seen_doc_end() {
                // Trailing garbage after a proper document end marker is ignored.
            } else {
                return Err(snippet_ctx.attach_snippet(e, &src));
            }
        }
    }

    if let Err(e) = src.finish() {
        return Err(snippet_ctx.attach_snippet(e, &src));
    }
    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, total comment 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.
#[cfg(feature = "deserialize")]
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.
/// Like [`from_reader_with_options`], BOM-marked UTF-8, UTF-16LE, and UTF-16BE
/// inputs are transcoded to UTF-8 internally before parsing. If no recognized
/// BOM is present, the input bytes are treated as UTF-8.
///
/// 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, total comment bytes) are enforced while streaming. The
///   reader input-byte cap is also enforced via `Budget::max_reader_input_bytes` (256 MiB by
///   default). Set this to `None` if the stream may legitimately run without a fixed byte cap.
/// - 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)]
#[cfg(feature = "deserialize")]
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(|| {
                            with_interp_redaction_scope(|| {
                                crate::de::with_root_redaction(
                                    crate::de::YamlDeserializer::new(&mut self.src, self.cfg),
                                    |de| T::deserialize(de),
                                )
                            })
                        });
                        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, false, EnforcingPolicy::PerDocument);

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