fast_yaml_core/
parser.rs

1use crate::error::ParseResult;
2use crate::value::Value;
3use saphyr::LoadableYamlNode;
4
5/// Parser for YAML documents.
6///
7/// Wraps saphyr's YAML loading to provide a consistent API.
8#[derive(Debug)]
9pub struct Parser;
10
11impl Parser {
12    /// Parse a single YAML document from a string.
13    ///
14    /// Returns the first document if multiple are present, or None if the input is empty.
15    ///
16    /// # Errors
17    ///
18    /// Returns `ParseError::Scanner` if the YAML syntax is invalid.
19    ///
20    /// # Examples
21    ///
22    /// ```
23    /// use fast_yaml_core::Parser;
24    ///
25    /// let result = Parser::parse_str("name: test\nvalue: 123")?;
26    /// # Ok::<(), Box<dyn std::error::Error>>(())
27    /// ```
28    pub fn parse_str(input: &str) -> ParseResult<Option<Value>> {
29        let docs = Value::load_from_str(input)?;
30        Ok(docs.into_iter().next())
31    }
32
33    /// Parse all YAML documents from a string.
34    ///
35    /// Returns a vector of all documents found in the input.
36    ///
37    /// # Errors
38    ///
39    /// Returns `ParseError::Scanner` if the YAML syntax is invalid.
40    ///
41    /// # Examples
42    ///
43    /// ```
44    /// use fast_yaml_core::Parser;
45    ///
46    /// let docs = Parser::parse_all("---\nfoo: 1\n---\nbar: 2")?;
47    /// assert_eq!(docs.len(), 2);
48    /// # Ok::<(), Box<dyn std::error::Error>>(())
49    /// ```
50    pub fn parse_all(input: &str) -> ParseResult<Vec<Value>> {
51        Ok(Value::load_from_str(input)?)
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn test_parse_str_simple() {
61        let result = Parser::parse_str("name: test\nvalue: 123").unwrap();
62        assert!(result.is_some());
63    }
64
65    #[test]
66    fn test_parse_str_empty() {
67        let result = Parser::parse_str("").unwrap();
68        assert!(result.is_none());
69    }
70
71    #[test]
72    fn test_parse_all_multiple_docs() {
73        let docs = Parser::parse_all("---\nfoo: 1\n---\nbar: 2").unwrap();
74        assert_eq!(docs.len(), 2);
75    }
76
77    #[test]
78    fn test_parse_str_invalid() {
79        let result = Parser::parse_str("invalid: [\n  missing: bracket");
80        assert!(result.is_err());
81    }
82
83    #[test]
84    fn test_parse_nested() {
85        let yaml = r"
86person:
87  name: John
88  age: 30
89  hobbies:
90    - reading
91    - coding
92";
93        let result = Parser::parse_str(yaml).unwrap();
94        assert!(result.is_some());
95    }
96
97    #[test]
98    fn test_parse_anchors() {
99        let yaml = r"
100defaults: &defaults
101  adapter: postgres
102  host: localhost
103
104development:
105  <<: *defaults
106  database: dev_db
107";
108        let result = Parser::parse_str(yaml).unwrap();
109        assert!(result.is_some());
110    }
111}