dbt_yaml/lib.rs
1//! [![github]](https://github.com/dtolnay/serde-yaml) [![crates-io]](https://crates.io/crates/serde-yaml) [![docs-rs]](https://docs.rs/serde-yaml)
2//!
3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6//!
7//! <br>
8//!
9//! Rust library for using the [Serde] serialization framework with data in
10//! [YAML] file format. _(This project is forked from
11//! [serde-yaml](https://github.com/dtolnay/serde-yaml) and maintained by dbt
12//! Labs.)_
13//!
14//! [Serde]: https://github.com/serde-rs/serde
15//! [YAML]: https://yaml.org/
16//!
17//! # Examples
18//!
19//! ```
20//! use std::collections::BTreeMap;
21//!
22//! fn main() -> Result<(), dbt_yaml::Error> {
23//! // You have some type.
24//! let mut map = BTreeMap::new();
25//! map.insert("x".to_string(), 1.0);
26//! map.insert("y".to_string(), 2.0);
27//!
28//! // Serialize it to a YAML string.
29//! let yaml = dbt_yaml::to_string(&map)?;
30//! assert_eq!(yaml, "x: 1.0\ny: 2.0\n");
31//!
32//! // Deserialize it back to a Rust type.
33//! let deserialized_map: BTreeMap<String, f64> = dbt_yaml::from_str(&yaml)?;
34//! assert_eq!(map, deserialized_map);
35//! Ok(())
36//! }
37//! ```
38//!
39//! ## Using Serde derive
40//!
41//! It can also be used with Serde's derive macros to handle structs and enums
42//! defined in your program.
43//!
44//! Structs serialize in the obvious way:
45//!
46//! ```
47//! # use serde_derive::{Serialize, Deserialize};
48//! use serde::{Serialize as _, Deserialize as _};
49//!
50//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
51//! struct Point {
52//! x: f64,
53//! y: f64,
54//! }
55//!
56//! fn main() -> Result<(), dbt_yaml::Error> {
57//! let point = Point { x: 1.0, y: 2.0 };
58//!
59//! let yaml = dbt_yaml::to_string(&point)?;
60//! assert_eq!(yaml, "x: 1.0\ny: 2.0\n");
61//!
62//! let deserialized_point: Point = dbt_yaml::from_str(&yaml)?;
63//! assert_eq!(point, deserialized_point);
64//! Ok(())
65//! }
66//! ```
67//!
68//! Enums serialize using YAML's `!tag` syntax to identify the variant name.
69//!
70//! ```
71//! # use serde_derive::{Serialize, Deserialize};
72//! use serde::{Serialize as _, Deserialize as _};
73//!
74//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
75//! enum Enum {
76//! Unit,
77//! Newtype(usize),
78//! Tuple(usize, usize, usize),
79//! Struct { x: f64, y: f64 },
80//! }
81//!
82//! fn main() -> Result<(), dbt_yaml::Error> {
83//! let yaml = "
84//! - !Newtype 1
85//! - !Tuple [0, 0, 0]
86//! - !Struct {x: 1.0, y: 2.0}
87//! ";
88//! let values: Vec<Enum> = dbt_yaml::from_str(yaml).unwrap();
89//! assert_eq!(values[0], Enum::Newtype(1));
90//! assert_eq!(values[1], Enum::Tuple(0, 0, 0));
91//! assert_eq!(values[2], Enum::Struct { x: 1.0, y: 2.0 });
92//!
93//! // The last two in YAML's block style instead:
94//! let yaml = "
95//! - !Tuple
96//! - 0
97//! - 0
98//! - 0
99//! - !Struct
100//! x: 1.0
101//! y: 2.0
102//! ";
103//! let values: Vec<Enum> = dbt_yaml::from_str(yaml).unwrap();
104//! assert_eq!(values[0], Enum::Tuple(0, 0, 0));
105//! assert_eq!(values[1], Enum::Struct { x: 1.0, y: 2.0 });
106//!
107//! // Variants with no data can be written using !Tag or just the string name.
108//! let yaml = "
109//! - Unit # serialization produces this one
110//! - !Unit
111//! ";
112//! let values: Vec<Enum> = dbt_yaml::from_str(yaml).unwrap();
113//! assert_eq!(values[0], Enum::Unit);
114//! assert_eq!(values[1], Enum::Unit);
115//!
116//! Ok(())
117//! }
118//! ```
119
120#![doc(html_root_url = "https://docs.rs/serde_yaml/0.9.34+deprecated")]
121#![deny(missing_docs, unsafe_op_in_unsafe_fn)]
122// Suppressed clippy_pedantic lints
123#![allow(
124 // buggy
125 clippy::iter_not_returning_iterator, // https://github.com/rust-lang/rust-clippy/issues/8285
126 clippy::ptr_arg, // https://github.com/rust-lang/rust-clippy/issues/9218
127 clippy::question_mark, // https://github.com/rust-lang/rust-clippy/issues/7859
128 // private Deserializer::next
129 clippy::should_implement_trait,
130 // things are often more readable this way
131 clippy::cast_lossless,
132 clippy::checked_conversions,
133 clippy::if_not_else,
134 clippy::manual_assert,
135 clippy::match_like_matches_macro,
136 clippy::match_same_arms,
137 clippy::module_name_repetitions,
138 clippy::needless_pass_by_value,
139 clippy::redundant_else,
140 clippy::single_match_else,
141 // code is acceptable
142 clippy::blocks_in_conditions,
143 clippy::cast_possible_truncation,
144 clippy::cast_possible_wrap,
145 clippy::cast_precision_loss,
146 clippy::cast_sign_loss,
147 clippy::derive_partial_eq_without_eq,
148 clippy::derived_hash_with_manual_eq,
149 clippy::doc_markdown,
150 clippy::items_after_statements,
151 clippy::let_underscore_untyped,
152 clippy::manual_map,
153 clippy::missing_panics_doc,
154 clippy::never_loop,
155 clippy::return_self_not_must_use,
156 clippy::too_many_lines,
157 clippy::uninlined_format_args,
158 clippy::unsafe_removed_from_name,
159 clippy::wildcard_in_or_patterns,
160 // noisy
161 clippy::missing_errors_doc,
162 clippy::must_use_candidate,
163)]
164
165pub use crate::de::{from_reader, from_slice, from_str, Deserializer};
166pub use crate::error::{Error, Result};
167pub use crate::ser::{to_string, to_writer, Serializer};
168#[doc(inline)]
169pub use crate::spanned::{reset_marker, set_marker, Marker, Span, Spanned};
170
171#[cfg(feature = "filename")]
172#[doc(inline)]
173pub use crate::spanned::with_filename;
174
175#[doc(inline)]
176pub use crate::shouldbe::{ShouldBe, WhyNot};
177#[doc(inline)]
178pub use crate::value::{from_value, to_value, Index, Number, Sequence, Value};
179#[cfg(feature = "schemars")]
180pub use crate::verbatim::maybe_transformable;
181#[doc(inline)]
182pub use crate::verbatim::Verbatim;
183
184#[doc(inline)]
185pub use crate::mapping::Mapping;
186
187#[doc(inline)]
188pub use crate::path::Path;
189
190mod de;
191mod error;
192mod libyaml;
193mod loader;
194pub mod mapping;
195mod number;
196pub mod path;
197mod ser;
198mod shouldbe;
199pub mod spanned;
200pub mod value;
201mod verbatim;
202pub mod with;
203
204// Prevent downstream code from implementing the Index trait.
205mod private {
206 pub trait Sealed {}
207 impl Sealed for usize {}
208 impl Sealed for str {}
209 impl Sealed for String {}
210 impl Sealed for crate::Value {}
211 impl<T> Sealed for &T where T: ?Sized + Sealed {}
212}
213
214#[cfg(feature = "flatten_dunder")]
215#[inline]
216pub(crate) fn is_flatten_key(key: &[u8]) -> bool {
217 key.len() > 4
218 && key[0] == b'_'
219 && key[1] == b'_'
220 && key[key.len() - 2] == b'_'
221 && key[key.len() - 1] == b'_'
222}
223
224#[cfg(not(feature = "flatten_dunder"))]
225#[inline]
226pub(crate) fn is_flatten_key(_key: &[u8]) -> bool {
227 false
228}
229
230pub use dbt_yaml_derive::UntaggedEnumDeserialize;
231
232/// Private API for internally tagged unit variant deserialization.
233pub mod __private {
234 /// Visitor for deserializing an internally tagged unit variant.
235 ///
236 /// Not public API.
237 pub struct InternallyTaggedUnitVisitor<'a> {
238 type_name: &'a str,
239 variant_name: &'a str,
240 }
241
242 impl<'a> InternallyTaggedUnitVisitor<'a> {
243 /// Not public API.
244 pub fn new(type_name: &'a str, variant_name: &'a str) -> Self {
245 InternallyTaggedUnitVisitor {
246 type_name,
247 variant_name,
248 }
249 }
250 }
251
252 impl<'de, 'a> serde::de::Visitor<'de> for InternallyTaggedUnitVisitor<'a> {
253 type Value = ();
254
255 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
256 write!(
257 formatter,
258 "unit variant {}::{}",
259 self.type_name, self.variant_name
260 )
261 }
262
263 fn visit_seq<S>(self, _: S) -> Result<(), S::Error>
264 where
265 S: serde::de::SeqAccess<'de>,
266 {
267 Ok(())
268 }
269
270 fn visit_map<M>(self, mut access: M) -> Result<(), M::Error>
271 where
272 M: serde::de::MapAccess<'de>,
273 {
274 while match access.next_entry::<serde::de::IgnoredAny, serde::de::IgnoredAny>() {
275 Ok(val) => val,
276 Err(err) => return Err(err),
277 }
278 .is_some()
279 {}
280 Ok(())
281 }
282 }
283}
284
285#[cfg(feature = "schemars")]
286pub use dbt_yaml_schemars_derive::{DbtSchema, JsonSchema};