From ba547b311a44abef83415ff50f3943a8a13ec27a Mon Sep 17 00:00:00 2001 From: David Aguilar Date: Sun, 24 Mar 2024 03:07:15 -0700 Subject: [PATCH] yaml: add YamlLoader::load_from_parser(&Parser) Make it easier to load documents from a prebuilt Parser. --- CHANGELOG.md | 2 ++ src/parser.rs | 13 +++++++------ src/yaml.rs | 14 +++++++++++++- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da322fb..2a933e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,8 @@ using that feature. - `YamlLoader` structs now have a `documents()` method that returns the parsed documents associated with a loader. +- `Parser::new_from_str(&str)` and `YamlLoader::load_from_parser(&Parser)` were added. + **Development**: ## v0.7.0 diff --git a/src/parser.rs b/src/parser.rs index 3164f5a..82947f0 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1126,13 +1126,14 @@ foo: "bar" --- !t!2 &2 baz: "qux" "#; - let mut loader = YamlLoader::default(); - let mut parser = Parser::new(text.chars()).keep_tags(true); - assert!(parser.load(&mut loader, true).is_ok()); - assert_eq!(loader.documents().len(), 2); - let yaml = &loader.documents()[0]; + let mut parser = Parser::new_from_str(text).keep_tags(true); + let result = YamlLoader::load_from_parser(&mut parser); + assert!(result.is_ok()); + let docs = result.unwrap(); + assert_eq!(docs.len(), 2); + let yaml = &docs[0]; assert_eq!(yaml["foo"].as_str(), Some("bar")); - let yaml = &loader.documents()[1]; + let yaml = &docs[1]; assert_eq!(yaml["baz"].as_str(), Some("qux")); let mut loader = YamlLoader::default() diff --git a/src/yaml.rs b/src/yaml.rs index b869fcc..6d58653 100644 --- a/src/yaml.rs +++ b/src/yaml.rs @@ -234,8 +234,20 @@ impl YamlLoader { /// # Errors /// Returns `ScanError` when loading fails. pub fn load_from_iter>(source: I) -> Result, ScanError> { - let mut loader = YamlLoader::default(); let mut parser = Parser::new(source); + Self::load_from_parser(&mut parser) + } + + /// Load the contents from the specified Parser as a set of YAML documents. + /// + /// Parsing succeeds if and only if all documents are parsed successfully. + /// An error in a latter document prevents the former from being returned. + /// # Errors + /// Returns `ScanError` when loading fails. + pub fn load_from_parser>( + parser: &mut Parser, + ) -> Result, ScanError> { + let mut loader = YamlLoader::default(); parser.load(&mut loader, true)?; Ok(loader.docs) }