Crate serde_yaml_bw

Crate serde_yaml_bw 

Source
Expand description

Rust library for using the Serde serialization framework with data in YAML file format.

§Examples

use std::collections::BTreeMap;

fn main() -> Result<(), serde_yaml_bw::Error> {
    // You have some type.
    let mut map = BTreeMap::new();
    map.insert("x".to_string(), 1.0);
    map.insert("y".to_string(), 2.0);

    // Serialize it to a YAML string.
    let yaml = serde_yaml_bw::to_string(&map)?;
    assert_eq!(yaml, "x: 1.0\ny: 2.0\n");

    // Deserialize it back to a Rust type.
    let deserialized_map: BTreeMap<String, f64> = serde_yaml_bw::from_str(&yaml)?;
    assert_eq!(map, deserialized_map);
    Ok(())
}

§Errors

Attempting to serialize a value with an invalid YAML tag will result in an Error whose cause is internally represented by the private TagError variant.

§Using Serde derive

It can also be used with Serde’s derive macros to handle structs and enums defined in your program.

Structs serialize in the obvious way:

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Point {
    x: f64,
    y: f64,
}

fn main() -> Result<(), serde_yaml_bw::Error> {
    let point = Point { x: 1.0, y: 2.0 };

    let yaml = serde_yaml_bw::to_string(&point)?;
    assert_eq!(yaml, "x: 1.0\ny: 2.0\n");

    let deserialized_point: Point = serde_yaml_bw::from_str(&yaml)?;
    assert_eq!(point, deserialized_point);
    Ok(())
}

Enums serialize using a YAML map whose key is the variant name.

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum Enum {
    Unit,
    Newtype(usize),
    Tuple(usize, usize, usize),
    Struct { x: f64, y: f64 },
}

fn main() -> Result<(), serde_yaml_bw::Error> {
    let yaml = "
        - Newtype: 1
        - Tuple:
          - 0
          - 0
          - 0
        - Struct:
            x: 1.0
            y: 2.0
    ";
    let values: Vec<Enum> = serde_yaml_bw::from_str(yaml)?;
    assert_eq!(values[0], Enum::Newtype(1));
    assert_eq!(values[1], Enum::Tuple(0, 0, 0));
    assert_eq!(values[2], Enum::Struct { x: 1.0, y: 2.0 });

    // The last two in YAML's block style instead:
    let yaml = "
        - Tuple:
          - 0
          - 0
          - 0
        - Struct:
            x: 1.0
            y: 2.0
    ";
    let values: Vec<Enum> = serde_yaml_bw::from_str(yaml)?;
    assert_eq!(values[0], Enum::Tuple(0, 0, 0));
    assert_eq!(values[1], Enum::Struct { x: 1.0, y: 2.0 });

    // Variants with no data are written as just the string name.
    let yaml = "
        - Unit
    ";
    let values: Vec<Enum> = serde_yaml_bw::from_str(yaml)?;
    assert_eq!(values[0], Enum::Unit);

    Ok(())
}

§Using Value

The Value enum represents any YAML node at runtime. It is useful when you don’t have a fixed Rust type or when you need to preserve YAML features such as anchors and aliases.

Basic construction examples:

use serde_yaml_bw::{Mapping, Value};

// Scalars
let n = Value::from(42);                // number
let b = Value::from(true);              // bool
let s = Value::from("hello");           // string

// Sequence from Vec and from iterator
let seq = Value::from(vec![1, 2, 3]);
let seq2: Value = ["a", "b", "c"].into_iter().collect();

// Mapping (a key to value map)
let mut m = Mapping::new();
m.set("name", Value::from("app"));
m.set("version", Value::from(1));
let doc = Value::from(m);

// Serialize to YAML
let yaml = serde_yaml_bw::to_string(&doc).unwrap();
assert!(yaml.contains("name: app"));

§Anchors and aliases

When building Values manually you can attach an anchor to scalars, sequences, and mappings, and you can create Value::Alias nodes that refer to them by name. During serialization, aliases to missing anchors are rejected by default.

use serde_yaml_bw::{Mapping, Value};

// Create a scalar with an anchor "greet"
let anchored = Value::String("Hello".to_string(), Some("greet".to_string()));

// Build a small document that reuses the anchored value via an alias
let mut root = Mapping::new();
root.set("first", anchored.clone());
root.set("second", Value::Alias("greet".to_string()));
let yaml = serde_yaml_bw::to_string(&Value::from(root)).unwrap();

// The exact formatting may vary, but both an anchor and an alias are emitted
assert!(yaml.contains("&greet"), "expected an anchor in: {yaml}");
assert!(yaml.contains("*greet"), "expected an alias in: {yaml}");

Anchors can be attached to complex nodes too:

use serde_yaml_bw::{Mapping, Value};

// An anchored mapping
let mut base = Mapping::with_anchor("base");
base.set("x", 1.into());
base.set("y", 2.into());

// Refer to it elsewhere using an alias node
let mut root = Mapping::new();
root.set("anchor", Value::from(base));
root.set("alias", Value::Alias("base".into()));

let out = serde_yaml_bw::to_string(&Value::from(root)).unwrap();
assert!(out.contains("&base"));
assert!(out.contains("*base"));

If you serialize an alias whose anchor has not appeared earlier in the document, serialization fails by default. You can change this behavior using SerializerBuilder::check_unresolved_anchors(false) if you prefer deferred checking on the consumer side.

use serde::Serialize;
use serde_yaml_bw::{SerializerBuilder, Value};

// Try to serialize a dangling alias and observe the error.
let mut buf = Vec::new();
let mut ser = SerializerBuilder::default()
    .check_unresolved_anchors(true)
    .build(&mut buf)
    .unwrap();

let err = Value::Alias("missing".into()).serialize(&mut ser).unwrap_err();
assert!(err.to_string().starts_with("reference to non existing anchor"));

For in-memory processing of YAML Values that contain anchors/aliases, you can expand aliases after parsing:

use serde_yaml_bw::Value;

let yaml = "a: &id 1\nb: *id\n";
let mut v: Value = serde_yaml_bw::from_str_value_preserve(yaml).unwrap();
v.resolve_aliases().unwrap();
assert_eq!(v["a"].as_i64(), v["b"].as_i64());

Modules§

budget
Streaming YAML budget checker using saphyr-parser (YAML 1.2).
mapping
A YAML mapping and its iterator types.
value
The Value enum, a loosely typed way of representing any valid YAML value.

Structs§

ArcAnchor
Wrapper that associates an anchor with the first serialized occurrence of an Arc and emits aliases for subsequent clones.
ArcWeakAnchor
Wrapper that serializes a Weak pointer as an alias if the strong pointer is still alive, otherwise it emits null.
Deserializer
A structure that deserializes YAML into Rust values.
DeserializerOptions
Configuration options for YAML deserialization.
Error
An error that happened serializing or deserializing YAML data.
FlowMap
Wrapper type that serializes the contained mapping using YAML flow style.
FlowSeq
Wrapper type that serializes the contained sequence using YAML flow style.
Location
The input location that an error occured.
Mapping
A YAML mapping in which the keys and values are both serde_yaml_bw::Value.
Number
Represents a YAML number, whether integer or floating point.
RcAnchor
Wrapper that associates an anchor with the first serialized occurrence of an Rc and emits aliases for subsequent clones.
RcWeakAnchor
Wrapper that serializes a Weak pointer as an alias if the strong pointer is still alive, otherwise it emits null.
Sequence
A YAML sequence in which the elements are serde_yaml_bw::Value.
Serializer
A structure for serializing Rust values into YAML.
SerializerBuilder
Builder to configure Serializer.
SerializerOptions
Options influencing how the serializer behaves.
StreamDeserializer
Iterator that deserializes a stream into multiple YAML values.

Enums§

SequenceStyle
Style of an emitted YAML sequence.
Value
Represents any valid YAML value or in some cases error

Functions§

digits_but_not_number
Check if a digit string should be treated as a YAML string rather than a number.
from_multiple
Deserialize multiple YAML documents from a single string into a vector of T. Completely empty documents are ignored and not included into returned vector.
from_reader
Deserialize an instance of type T from an IO stream of YAML.
from_reader_multi
Deserialize a list of T from multiple YAML documents provided in an IO stream.
from_slice
Deserialize an instance of type T from bytes of YAML text.
from_slice_multi
Deserialize a list of T from multiple YAML documents provided in bytes.
from_str
Deserialize an instance of type T from a string of YAML text.
from_str_multi
Deserialize a list of T from multiple YAML documents provided in a string.
from_str_value
Deserialize a YAML Value, applying merges and resolving aliases.
from_str_value_preserve
Deserialize a YAML string into a Value while preserving anchors and aliases.
from_value
Interpret a serde_yaml_bw::Value as an instance of type T.
parse_bool_casefold
Parse a scalar as a boolean using ASCII case-insensitive matching.
parse_f64
Parse a scalar as a floating point value.
to_string
Serialize the given data structure as a String of YAML.
to_string_multi
Serialize the given array of data structures as a YAML multi-document string.
to_string_multi_with_options
Serialize the given array of data structures as a YAML multi-document string using explicit options.
to_string_with_options
Serialize the given data structure to a YAML string using explicit options.
to_value
Convert a T into serde_yaml_bw::Value which is an enum that can represent any valid YAML data.
to_writer
Serialize the given data structure as YAML into the IO stream.
to_writer_multi
Serialize the given array of data structures as multiple YAML documents into the IO stream.
to_writer_multi_with_options
Serialize the given array of data structures as multiple YAML documents using explicit options.
to_writer_with_options
Serialize the given data structure using explicit serializer options.
unexpected
Convert a Number into its matching Unexpected variant.

Type Aliases§

Result
Alias for a Result with the error type serde_yaml_bw::Error.