noyalib 0.0.5

A pure Rust YAML library with zero unsafe code and full serde integration
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
//! Multi-document YAML loading.
//!
//! This module provides functionality for parsing YAML documents that contain
//! multiple documents separated by `---`.
//!
//! # Examples
//!
//! ```rust
//! use noyalib::document::load_all;
//!
//! let yaml = "---
//! name: doc1
//! ---
//! name: doc2
//! ";
//!
//! let docs: Vec<_> = load_all(yaml).unwrap().collect();
//! assert_eq!(docs.len(), 2);
//! ```

// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 Noyalib. All rights reserved.

use crate::de::ParserConfig;
use crate::error::{Error, Result};
use crate::parser;
use crate::prelude::*;
#[cfg(feature = "std")]
use crate::span_context::{self, SpanTree};
use crate::value::Value;
#[cfg(not(feature = "std"))]
use alloc::vec::IntoIter;
#[cfg(feature = "std")]
use core::marker::PhantomData;
#[cfg(feature = "std")]
use std::vec::IntoIter;

/// An iterator over YAML documents in a string.
///
/// Created by the [`load_all`] function.
///
/// # Examples
///
/// ```
/// use noyalib::document::load_all;
/// let iter = load_all("---\na: 1\n---\nb: 2\n").unwrap();
/// assert_eq!(iter.len(), 2);
/// ```
#[derive(Debug)]
pub struct DocumentIterator {
    docs: IntoIter<Value>,
    #[cfg(feature = "std")]
    _span_trees: Vec<SpanTree>,
    total: usize,
}

impl DocumentIterator {
    /// Returns the total number of documents parsed.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::document::load_all;
    /// let iter = load_all("a: 1\n").unwrap();
    /// assert_eq!(iter.len(), 1);
    /// ```
    #[must_use]
    pub fn len(&self) -> usize {
        self.total
    }

    /// Returns true if there are no documents.
    ///
    /// # Examples
    ///
    /// ```
    /// use noyalib::document::load_all;
    /// let iter = load_all("a: 1\n").unwrap();
    /// assert!(!iter.is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.total == 0
    }
}

impl Iterator for DocumentIterator {
    type Item = Result<Value>;

    fn next(&mut self) -> Option<Self::Item> {
        self.docs.next().map(Ok)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.docs.size_hint()
    }
}

impl ExactSizeIterator for DocumentIterator {}

/// Load all YAML documents from a string.
///
/// This function parses a YAML string that may contain multiple documents
/// separated by `---` markers. Default security limits are applied.
///
/// # Examples
///
/// ```rust
/// use noyalib::document::load_all;
///
/// let yaml = "---
/// first: 1
/// ---
/// second: 2
/// ";
///
/// let docs: Vec<_> = load_all(yaml).unwrap().filter_map(Result::ok).collect();
/// assert_eq!(docs.len(), 2);
/// ```
///
/// # Errors
///
/// Returns an error if the YAML syntax is invalid.
pub fn load_all(input: &str) -> Result<DocumentIterator> {
    load_all_with_config(input, &ParserConfig::default())
}

/// Load all YAML documents from a string with custom security limits.
///
/// # Errors
///
/// Returns an error if the YAML syntax is invalid or the document
/// exceeds the configured limits.
///
/// # Examples
///
/// ```
/// use noyalib::{document::load_all_with_config, ParserConfig};
/// let cfg = ParserConfig::new();
/// let iter = load_all_with_config("a: 1\n---\nb: 2\n", &cfg).unwrap();
/// assert_eq!(iter.len(), 2);
/// ```
pub fn load_all_with_config(input: &str, config: &ParserConfig) -> Result<DocumentIterator> {
    if input.len() > config.max_document_length {
        return Err(Error::Parse(format!(
            "document exceeds maximum length of {} bytes",
            config.max_document_length
        )));
    }
    let parse_config = parser::ParseConfig::from(config);

    #[cfg(feature = "std")]
    {
        let pairs = parser::parse(input, &parse_config)?;
        let (docs, span_trees): (Vec<_>, Vec<_>) = pairs.into_iter().unzip();
        let total = docs.len();
        Ok(DocumentIterator {
            docs: docs.into_iter(),
            _span_trees: span_trees,
            total,
        })
    }

    #[cfg(not(feature = "std"))]
    {
        let docs = parser::parse_all_values(input, &parse_config)?;
        let total = docs.len();
        Ok(DocumentIterator {
            docs: docs.into_iter(),
            total,
        })
    }
}

/// Load all YAML documents from a string, returning an error if parsing fails.
///
/// This is an alias for [`load_all`] which also returns errors on invalid
/// syntax.
///
/// # Examples
///
/// ```rust
/// use noyalib::document::try_load_all;
///
/// let yaml = "---
/// first: 1
/// ---
/// second: 2
/// ";
///
/// let iter = try_load_all(yaml).unwrap();
/// assert_eq!(iter.len(), 2);
/// ```
///
/// # Errors
///
/// Returns an error if the YAML syntax is invalid.
pub fn try_load_all(input: &str) -> Result<DocumentIterator> {
    load_all(input)
}

/// Load all YAML documents and deserialize them into a typed vector.
///
/// # Examples
///
/// ```rust
/// use noyalib::document::load_all_as;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Doc {
///     name: String,
/// }
///
/// let yaml = "---
/// name: first
/// ---
/// name: second
/// ";
///
/// let docs: Vec<Doc> = load_all_as(yaml).unwrap();
/// assert_eq!(docs.len(), 2);
/// assert_eq!(docs[0].name, "first");
/// assert_eq!(docs[1].name, "second");
/// ```
///
/// # Errors
///
/// Returns an error if parsing fails or if any document cannot be
/// deserialized into the target type.
pub fn load_all_as<T>(input: &str) -> Result<Vec<T>>
where
    T: for<'de> serde::Deserialize<'de> + 'static,
{
    let parse_config = parser::ParseConfig::from(&ParserConfig::default());

    #[cfg(feature = "std")]
    {
        let pairs = parser::parse(input, &parse_config)?;
        let mut results = Vec::with_capacity(pairs.len());
        let source: Arc<str> = input.into();

        for (value, span_tree) in &pairs {
            let spans = span_context::build_span_map(value, span_tree);
            let ctx = span_context::SpanContext {
                spans,
                source: source.clone(),
            };
            let _guard = span_context::set_span_context(ctx);
            let typed: T = crate::from_value(value)?;
            results.push(typed);
        }

        Ok(results)
    }

    #[cfg(not(feature = "std"))]
    {
        let docs = parser::parse_all_values(input, &parse_config)?;
        let mut results = Vec::with_capacity(docs.len());
        for value in &docs {
            let typed: T = crate::from_value(value)?;
            results.push(typed);
        }
        Ok(results)
    }
}

/// Lazy iterator that yields `Result<T>` per YAML document parsed
/// from a reader.
///
/// Created by [`read`] / [`read_with_config`]. Deserialisation
/// errors on individual documents are surfaced as `Err` values; the
/// iterator continues so callers can recover and process subsequent
/// documents. Syntax errors during the initial parse are returned
/// from [`read`] / [`read_with_config`] before iteration starts.
///
/// # Memory
///
/// Today the reader is fully drained into a `String` before the
/// underlying parser runs, so memory is `O(input_len)`. True
/// `O(1)`-document streaming requires a parser-level rewrite that
/// can accept incremental byte chunks; that work is tracked
/// separately.
#[cfg(feature = "std")]
#[derive(Debug)]
pub struct DocumentReadIterator<T> {
    docs: IntoIter<Value>,
    _phantom: PhantomData<fn() -> T>,
}

#[cfg(feature = "std")]
impl<T> DocumentReadIterator<T> {
    /// Total number of documents pending iteration.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::io::Cursor;
    /// let yaml = "a: 1\n---\nb: 2\n";
    /// let iter: noyalib::DocumentReadIterator<noyalib::Value> =
    ///     noyalib::read(Cursor::new(yaml)).unwrap();
    /// assert_eq!(iter.len(), 2);
    /// ```
    #[must_use]
    pub fn len(&self) -> usize {
        self.docs.len()
    }

    /// Whether the iterator has no further documents.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::io::Cursor;
    /// let iter: noyalib::DocumentReadIterator<noyalib::Value> =
    ///     noyalib::read(Cursor::new("")).unwrap();
    /// assert!(iter.is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.docs.len() == 0
    }
}

#[cfg(feature = "std")]
impl<T> Iterator for DocumentReadIterator<T>
where
    T: for<'de> serde::Deserialize<'de> + 'static,
{
    type Item = Result<T>;
    fn next(&mut self) -> Option<Self::Item> {
        let value = self.docs.next()?;
        Some(crate::from_value(&value))
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.docs.size_hint()
    }
}

#[cfg(feature = "std")]
impl<T> ExactSizeIterator for DocumentReadIterator<T> where
    T: for<'de> serde::Deserialize<'de> + 'static
{
}

/// Stream-decode every YAML document from a reader into typed
/// values, yielding one `Result<T>` per document.
///
/// The reader is drained eagerly (see [`DocumentReadIterator`] for
/// the memory caveat); document-by-document deserialisation is then
/// produced lazily on demand. Per-document deserialisation errors
/// surface as `Err` values inside the iterator so callers can
/// recover and continue. A syntax error in the underlying YAML is
/// returned synchronously from this function before any iteration
/// happens.
///
/// # Errors
///
/// Returns an error if the reader fails, the YAML cannot be parsed,
/// or any document exceeds the default security limits. Per-document
/// deserialisation errors are *not* surfaced here; they appear
/// inside the iterator.
///
/// # Examples
///
/// ```
/// use std::io::Cursor;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, PartialEq)]
/// struct Doc { id: u32 }
///
/// let yaml = "id: 1\n---\nid: 2\n---\nid: 3\n";
/// let docs: Vec<Doc> = noyalib::read::<_, Doc>(Cursor::new(yaml))
///     .unwrap()
///     .filter_map(Result::ok)
///     .collect();
/// assert_eq!(docs, vec![Doc { id: 1 }, Doc { id: 2 }, Doc { id: 3 }]);
/// ```
#[cfg(feature = "std")]
pub fn read<R, T>(reader: R) -> Result<DocumentReadIterator<T>>
where
    R: std::io::Read,
    T: for<'de> serde::Deserialize<'de> + 'static,
{
    read_with_config(reader, &ParserConfig::default())
}

/// [`read`] with a custom [`ParserConfig`] for tightened security
/// limits.
///
/// # Errors
///
/// Same as [`read`].
///
/// # Examples
///
/// ```
/// use std::io::Cursor;
/// use noyalib::{read_with_config, ParserConfig, Value};
///
/// let cfg = ParserConfig::strict();
/// let yaml = "a: 1\n---\nb: 2\n";
/// let count = read_with_config::<_, Value>(Cursor::new(yaml), &cfg)
///     .unwrap()
///     .count();
/// assert_eq!(count, 2);
/// ```
#[cfg(feature = "std")]
pub fn read_with_config<R, T>(
    mut reader: R,
    config: &ParserConfig,
) -> Result<DocumentReadIterator<T>>
where
    R: std::io::Read,
    T: for<'de> serde::Deserialize<'de> + 'static,
{
    let mut buf = String::new();
    let _read_bytes = reader
        .read_to_string(&mut buf)
        .map_err(|e| Error::Parse(format!("reader I/O failed: {e}")))?;
    if buf.len() > config.max_document_length.saturating_mul(64) {
        // Soft cap on the *aggregated* multi-document buffer to
        // bound memory regardless of per-document caps.
        return Err(Error::Parse(format!(
            "reader payload exceeds 64× max_document_length ({} bytes)",
            config.max_document_length
        )));
    }
    let parse_config = parser::ParseConfig::from(config);
    let pairs = parser::parse(&buf, &parse_config)?;
    let docs: Vec<Value> = pairs.into_iter().map(|(value, _)| value).collect();
    Ok(DocumentReadIterator {
        docs: docs.into_iter(),
        _phantom: PhantomData,
    })
}