Skip to content

Commit

Permalink
yaml: add YamlLoader::load_from_parser(&Parser)
Browse files Browse the repository at this point in the history
Make it easier to load documents from a prebuilt Parser.
  • Loading branch information
davvid committed Mar 24, 2024
1 parent 02a4451 commit ba547b3
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 7 additions & 6 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
14 changes: 13 additions & 1 deletion src/yaml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,8 +234,20 @@ impl YamlLoader {
/// # Errors
/// Returns `ScanError` when loading fails.
pub fn load_from_iter<I: Iterator<Item = char>>(source: I) -> Result<Vec<Yaml>, 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<I: Iterator<Item = char>>(
parser: &mut Parser<I>,
) -> Result<Vec<Yaml>, ScanError> {
let mut loader = YamlLoader::default();
parser.load(&mut loader, true)?;
Ok(loader.docs)
}
Expand Down

0 comments on commit ba547b3

Please sign in to comment.