Skip to main content

strict_yaml_rust/
lib.rs

1// Copyright 2015, Yuheng Chen. See the LICENSE file at the top-level
2// directory of this distribution.
3
4//! Strict YAML implementation in pure Rust.
5//!
6//! # Usage
7//!
8//! This crate is [on github](https://github.com/fralalonde/strict-yaml-rust) and can be
9//! used by adding `strict-yaml` to the dependencies in your project's `Cargo.toml`.
10//!
11//! ```sh
12//! cargo add strict-yaml-rust
13//! ```
14//!
15//! # Examples
16//!
17//! ```
18//! use strict_yaml_rust::{StrictYamlLoader, StrictYamlEmitter};
19//!
20//! let docs = StrictYamlLoader::load_from_str("zug: [1, 2, 3]").unwrap();
21//! let doc = &docs[0]; // select the first document
22//! assert_eq!(doc["zug"].as_str(), Some("[1, 2, 3]")); // access elements by key
23//!
24//! let mut out_str = String::new();
25//! let mut emitter = StrictYamlEmitter::new(&mut out_str);
26//! emitter.dump(doc).unwrap(); // dump the YAML object to a String
27//! ```
28//!
29//! # Serde
30//!
31//! The crate also provides a [`serde`](https://serde.rs) implementation. The functions
32//! in the [`serde`](module@crate::serde) module can be enabled with the `serde` feature flag.
33
34pub mod emitter;
35pub mod parser;
36pub mod scanner;
37#[cfg(feature = "serde")]
38pub mod serde;
39pub mod strict_yaml;
40
41// reexport key APIs
42pub use crate::emitter::{EmitError, StrictYamlEmitter};
43pub use crate::parser::Event;
44pub use crate::scanner::ScanError;
45pub use crate::strict_yaml::{StrictYaml, StrictYamlLoader};
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn test_api() {
53        let s = "
54# from yaml-cpp example
55- name: Ogre
56  position: [0, 5, 0]
57  powers:
58    - name: Club
59      damage: 10
60    - name: Fist
61      damage: 8
62- name: Dragon
63  position: [1, 0, 10]
64  powers:
65    - name: Fire Breath
66      damage: 25
67    - name: Claws
68      damage: 15
69- name: Wizard
70  position: [5, -3, 0]
71  powers:
72    - name: Acid Rain
73      damage: 50
74    - name: Staff
75      damage: 3
76";
77        let docs = StrictYamlLoader::load_from_str(s).unwrap();
78        let doc = &docs[0];
79
80        assert_eq!(doc[0]["name"].as_str().unwrap(), "Ogre");
81
82        let mut writer = String::new();
83        {
84            let mut emitter = StrictYamlEmitter::new(&mut writer);
85            emitter.dump(doc).unwrap();
86        }
87
88        assert!(!writer.is_empty());
89    }
90
91    fn try_fail(s: &str) -> Result<Vec<StrictYaml>, ScanError> {
92        let t = StrictYamlLoader::load_from_str(s)?;
93        Ok(t)
94    }
95
96    #[test]
97    fn test_fail() {
98        let s = "
99# syntax error
100scalar
101key: [1, 2]]
102key1:a2
103";
104        assert!(StrictYamlLoader::load_from_str(s).is_err());
105        assert!(try_fail(s).is_err());
106    }
107}