Skip to main content

noyalib/
document.rs

1//! Multi-document YAML loading.
2//!
3//! This module provides functionality for parsing YAML documents that contain
4//! multiple documents separated by `---`.
5//!
6//! # Examples
7//!
8//! ```rust
9//! use noyalib::document::load_all;
10//!
11//! let yaml = "---
12//! name: doc1
13//! ---
14//! name: doc2
15//! ";
16//!
17//! let docs: Vec<_> = load_all(yaml).unwrap().collect();
18//! assert_eq!(docs.len(), 2);
19//! ```
20
21// SPDX-License-Identifier: MIT OR Apache-2.0
22// Copyright (c) 2026 Noyalib. All rights reserved.
23
24use crate::de::ParserConfig;
25use crate::error::{Error, Result};
26use crate::parser;
27use crate::prelude::*;
28#[cfg(feature = "std")]
29use crate::span_context::{self, SpanTree};
30use crate::value::Value;
31#[cfg(not(feature = "std"))]
32use alloc::vec::IntoIter;
33#[cfg(feature = "std")]
34use core::marker::PhantomData;
35#[cfg(feature = "std")]
36use std::vec::IntoIter;
37
38/// An iterator over YAML documents in a string.
39///
40/// Created by the [`load_all`] function.
41///
42/// # Examples
43///
44/// ```
45/// use noyalib::document::load_all;
46/// let iter = load_all("---\na: 1\n---\nb: 2\n").unwrap();
47/// assert_eq!(iter.len(), 2);
48/// ```
49#[derive(Debug)]
50pub struct DocumentIterator {
51    docs: IntoIter<Value>,
52    #[cfg(feature = "std")]
53    _span_trees: Vec<SpanTree>,
54    total: usize,
55}
56
57impl DocumentIterator {
58    /// Returns the total number of documents parsed.
59    ///
60    /// # Examples
61    ///
62    /// ```
63    /// use noyalib::document::load_all;
64    /// let iter = load_all("a: 1\n").unwrap();
65    /// assert_eq!(iter.len(), 1);
66    /// ```
67    #[must_use]
68    pub fn len(&self) -> usize {
69        self.total
70    }
71
72    /// Returns true if there are no documents.
73    ///
74    /// # Examples
75    ///
76    /// ```
77    /// use noyalib::document::load_all;
78    /// let iter = load_all("a: 1\n").unwrap();
79    /// assert!(!iter.is_empty());
80    /// ```
81    #[must_use]
82    pub fn is_empty(&self) -> bool {
83        self.total == 0
84    }
85}
86
87impl Iterator for DocumentIterator {
88    type Item = Result<Value>;
89
90    fn next(&mut self) -> Option<Self::Item> {
91        self.docs.next().map(Ok)
92    }
93
94    fn size_hint(&self) -> (usize, Option<usize>) {
95        self.docs.size_hint()
96    }
97}
98
99impl ExactSizeIterator for DocumentIterator {}
100
101/// Load all YAML documents from a string.
102///
103/// This function parses a YAML string that may contain multiple documents
104/// separated by `---` markers. Default security limits are applied.
105///
106/// # Examples
107///
108/// ```rust
109/// use noyalib::document::load_all;
110///
111/// let yaml = "---
112/// first: 1
113/// ---
114/// second: 2
115/// ";
116///
117/// let docs: Vec<_> = load_all(yaml).unwrap().filter_map(Result::ok).collect();
118/// assert_eq!(docs.len(), 2);
119/// ```
120///
121/// # Errors
122///
123/// Returns an error if the YAML syntax is invalid.
124pub fn load_all(input: &str) -> Result<DocumentIterator> {
125    load_all_with_config(input, &ParserConfig::default())
126}
127
128/// Load all YAML documents from a string with custom security limits.
129///
130/// # Errors
131///
132/// Returns an error if the YAML syntax is invalid or the document
133/// exceeds the configured limits.
134///
135/// # Examples
136///
137/// ```
138/// use noyalib::{document::load_all_with_config, ParserConfig};
139/// let cfg = ParserConfig::new();
140/// let iter = load_all_with_config("a: 1\n---\nb: 2\n", &cfg).unwrap();
141/// assert_eq!(iter.len(), 2);
142/// ```
143pub fn load_all_with_config(input: &str, config: &ParserConfig) -> Result<DocumentIterator> {
144    if input.len() > config.max_document_length {
145        return Err(Error::Parse(format!(
146            "document exceeds maximum length of {} bytes",
147            config.max_document_length
148        )));
149    }
150    let parse_config = parser::ParseConfig::from(config);
151
152    #[cfg(feature = "std")]
153    {
154        let pairs = parser::parse(input, &parse_config)?;
155        let (docs, span_trees): (Vec<_>, Vec<_>) = pairs.into_iter().unzip();
156        let total = docs.len();
157        Ok(DocumentIterator {
158            docs: docs.into_iter(),
159            _span_trees: span_trees,
160            total,
161        })
162    }
163
164    #[cfg(not(feature = "std"))]
165    {
166        let docs = parser::parse_all_values(input, &parse_config)?;
167        let total = docs.len();
168        Ok(DocumentIterator {
169            docs: docs.into_iter(),
170            total,
171        })
172    }
173}
174
175/// Load all YAML documents from a string, returning an error if parsing fails.
176///
177/// This is an alias for [`load_all`] which also returns errors on invalid
178/// syntax.
179///
180/// # Examples
181///
182/// ```rust
183/// use noyalib::document::try_load_all;
184///
185/// let yaml = "---
186/// first: 1
187/// ---
188/// second: 2
189/// ";
190///
191/// let iter = try_load_all(yaml).unwrap();
192/// assert_eq!(iter.len(), 2);
193/// ```
194///
195/// # Errors
196///
197/// Returns an error if the YAML syntax is invalid.
198pub fn try_load_all(input: &str) -> Result<DocumentIterator> {
199    load_all(input)
200}
201
202/// Load all YAML documents and deserialize them into a typed vector.
203///
204/// # Examples
205///
206/// ```rust
207/// use noyalib::document::load_all_as;
208///
209/// #[derive(Debug, serde::Deserialize, PartialEq)]
210/// struct Doc {
211///     name: String,
212/// }
213///
214/// let yaml = "---
215/// name: first
216/// ---
217/// name: second
218/// ";
219///
220/// let docs: Vec<Doc> = load_all_as(yaml).unwrap();
221/// assert_eq!(docs.len(), 2);
222/// assert_eq!(docs[0].name, "first");
223/// assert_eq!(docs[1].name, "second");
224/// ```
225///
226/// # Errors
227///
228/// Returns an error if parsing fails or if any document cannot be
229/// deserialized into the target type.
230pub fn load_all_as<T>(input: &str) -> Result<Vec<T>>
231where
232    T: for<'de> serde_core::Deserialize<'de> + 'static,
233{
234    let parse_config = parser::ParseConfig::from(&ParserConfig::default());
235
236    #[cfg(feature = "std")]
237    {
238        let pairs = parser::parse(input, &parse_config)?;
239        let mut results = Vec::with_capacity(pairs.len());
240        let source: Arc<str> = input.into();
241
242        for (value, span_tree) in &pairs {
243            let spans = span_context::build_span_map(value, span_tree);
244            let ctx = span_context::SpanContext {
245                spans,
246                source: source.clone(),
247            };
248            let _guard = span_context::set_span_context(ctx);
249            let typed: T = crate::from_value(value)?;
250            results.push(typed);
251        }
252
253        Ok(results)
254    }
255
256    #[cfg(not(feature = "std"))]
257    {
258        let docs = parser::parse_all_values(input, &parse_config)?;
259        let mut results = Vec::with_capacity(docs.len());
260        for value in &docs {
261            let typed: T = crate::from_value(value)?;
262            results.push(typed);
263        }
264        Ok(results)
265    }
266}
267
268/// Lazy iterator that yields `Result<T>` per YAML document parsed
269/// from a reader.
270///
271/// Created by [`read`] / [`read_with_config`]. Deserialisation
272/// errors on individual documents are surfaced as `Err` values; the
273/// iterator continues so callers can recover and process subsequent
274/// documents. Syntax errors during the initial parse are returned
275/// from [`read`] / [`read_with_config`] before iteration starts.
276///
277/// # Memory
278///
279/// Today the reader is fully drained into a `String` before the
280/// underlying parser runs, so memory is `O(input_len)`. True
281/// `O(1)`-document streaming requires a parser-level rewrite that
282/// can accept incremental byte chunks; that work is tracked
283/// separately.
284#[cfg(feature = "std")]
285#[derive(Debug)]
286pub struct DocumentReadIterator<T> {
287    docs: IntoIter<Value>,
288    _phantom: PhantomData<fn() -> T>,
289}
290
291#[cfg(feature = "std")]
292impl<T> DocumentReadIterator<T> {
293    /// Total number of documents pending iteration.
294    ///
295    /// # Examples
296    ///
297    /// ```
298    /// use std::io::Cursor;
299    /// let yaml = "a: 1\n---\nb: 2\n";
300    /// let iter: noyalib::DocumentReadIterator<noyalib::Value> =
301    ///     noyalib::read(Cursor::new(yaml)).unwrap();
302    /// assert_eq!(iter.len(), 2);
303    /// ```
304    #[must_use]
305    pub fn len(&self) -> usize {
306        self.docs.len()
307    }
308
309    /// Whether the iterator has no further documents.
310    ///
311    /// # Examples
312    ///
313    /// ```
314    /// use std::io::Cursor;
315    /// let iter: noyalib::DocumentReadIterator<noyalib::Value> =
316    ///     noyalib::read(Cursor::new("")).unwrap();
317    /// assert!(iter.is_empty());
318    /// ```
319    #[must_use]
320    pub fn is_empty(&self) -> bool {
321        self.docs.len() == 0
322    }
323}
324
325#[cfg(feature = "std")]
326impl<T> Iterator for DocumentReadIterator<T>
327where
328    T: for<'de> serde_core::Deserialize<'de> + 'static,
329{
330    type Item = Result<T>;
331    fn next(&mut self) -> Option<Self::Item> {
332        let value = self.docs.next()?;
333        Some(crate::from_value(&value))
334    }
335    fn size_hint(&self) -> (usize, Option<usize>) {
336        self.docs.size_hint()
337    }
338}
339
340#[cfg(feature = "std")]
341impl<T> ExactSizeIterator for DocumentReadIterator<T> where
342    T: for<'de> serde_core::Deserialize<'de> + 'static
343{
344}
345
346/// Stream-decode every YAML document from a reader into typed
347/// values, yielding one `Result<T>` per document.
348///
349/// The reader is drained eagerly (see [`DocumentReadIterator`] for
350/// the memory caveat); document-by-document deserialisation is then
351/// produced lazily on demand. Per-document deserialisation errors
352/// surface as `Err` values inside the iterator so callers can
353/// recover and continue. A syntax error in the underlying YAML is
354/// returned synchronously from this function before any iteration
355/// happens.
356///
357/// # Errors
358///
359/// Returns an error if the reader fails, the YAML cannot be parsed,
360/// or any document exceeds the default security limits. Per-document
361/// deserialisation errors are *not* surfaced here; they appear
362/// inside the iterator.
363///
364/// # Examples
365///
366/// ```
367/// use std::io::Cursor;
368///
369/// #[derive(Debug, serde::Deserialize, PartialEq)]
370/// struct Doc { id: u32 }
371///
372/// let yaml = "id: 1\n---\nid: 2\n---\nid: 3\n";
373/// let docs: Vec<Doc> = noyalib::read::<_, Doc>(Cursor::new(yaml))
374///     .unwrap()
375///     .filter_map(Result::ok)
376///     .collect();
377/// assert_eq!(docs, vec![Doc { id: 1 }, Doc { id: 2 }, Doc { id: 3 }]);
378/// ```
379#[cfg(feature = "std")]
380pub fn read<R, T>(reader: R) -> Result<DocumentReadIterator<T>>
381where
382    R: std::io::Read,
383    T: for<'de> serde_core::Deserialize<'de> + 'static,
384{
385    read_with_config(reader, &ParserConfig::default())
386}
387
388/// [`read`] with a custom [`ParserConfig`] for tightened security
389/// limits.
390///
391/// # Errors
392///
393/// Same as [`read`].
394///
395/// # Examples
396///
397/// ```
398/// use std::io::Cursor;
399/// use noyalib::{read_with_config, ParserConfig, Value};
400///
401/// let cfg = ParserConfig::strict();
402/// let yaml = "a: 1\n---\nb: 2\n";
403/// let count = read_with_config::<_, Value>(Cursor::new(yaml), &cfg)
404///     .unwrap()
405///     .count();
406/// assert_eq!(count, 2);
407/// ```
408#[cfg(feature = "std")]
409pub fn read_with_config<R, T>(
410    mut reader: R,
411    config: &ParserConfig,
412) -> Result<DocumentReadIterator<T>>
413where
414    R: std::io::Read,
415    T: for<'de> serde_core::Deserialize<'de> + 'static,
416{
417    let mut buf = String::new();
418    let _read_bytes = reader
419        .read_to_string(&mut buf)
420        .map_err(|e| Error::Parse(format!("reader I/O failed: {e}")))?;
421    if buf.len() > config.max_document_length.saturating_mul(64) {
422        // Soft cap on the *aggregated* multi-document buffer to
423        // bound memory regardless of per-document caps.
424        return Err(Error::Parse(format!(
425            "reader payload exceeds 64× max_document_length ({} bytes)",
426            config.max_document_length
427        )));
428    }
429    let parse_config = parser::ParseConfig::from(config);
430    let pairs = parser::parse(&buf, &parse_config)?;
431    let docs: Vec<Value> = pairs.into_iter().map(|(value, _)| value).collect();
432    Ok(DocumentReadIterator {
433        docs: docs.into_iter(),
434        _phantom: PhantomData,
435    })
436}