Skip to content

Migrating from yaml-rust2, saphyr, and serde-saphyr

yaml-rust2, saphyr, and serde-saphyr are pure-Rust YAML 1.2 libraries. ayaml brings event scanning, generic Value DOM, spanned trees, owned and borrowed Serde decoding, deterministic emission, and source-preserving edits under one parser.

On geometric mean across 26 shared fixtures (v1.0.0), ayaml runs 2.12x to 2.44x faster than yaml-rust2 and saphyr (with 4.1x fewer allocations than yaml-rust2 and lower peak heap than both), and 4.98x faster than serde-saphyr across 25 shared fixtures (where serde-saphyr targets serde_json::Value). Across all 26 fixtures, flat-array Tape runs a further 1.43x faster than ayaml::Value with 1.51x lower peak heap (see Benchmarks and Benchmark methodology).

[dependencies]
ayaml = "1.0.0"
# Optional: verified source-preserving edits
ayaml-edit = "1.0.0"
yaml-rust2 / saphyr / serde-saphyr / marked-yaml ayaml Notes
YamlLoader::load_from_str(s) ayaml::parse_documents(s) or ayaml::parse_value(s) parse_documents("") and comment-only inputs return Ok(vec![]) (matching YamlLoader); parse_value("") returns Ok(Value::Null) and enforces single-document input (TrailingDocuments on extra docs).
Yaml::Hash / Array / Boolean (yaml-rust2), yaml.as_hash(), yaml.as_vec(), yaml_rust2::yaml::Hash Value::Mapping / Sequence / Bool, val.as_mapping(), val.as_sequence(), ayaml::Mapping Mapping::get("key") looks up &str directly with zero allocations (replace hash.get(&Yaml::String(k.to_owned()))). Number stores exact i64/u64/i128/u128 integers and IEEE-754 f64 floats; also Value::Tagged, Value::Null.
doc["missing"].is_badvalue() (Yaml::BadValue) doc.get("missing") (Option<&Value>) ayaml’s doc["missing"] returns &Value::Null, not a distinct BadValue variant. Use .get(...) to distinguish missing keys from explicit null.
yaml_rust2::Parser + EventReceiver, saphyr_parser::Parser, or granit_parser::Parser ayaml::parse_events(s) pull Iterator Pull iterator yielding Result<Event<'a>, Error> with exact byte Spans; validates pure syntax without resolving aliases (ideal for --unsafe linters).
MarkedYaml / marked-yaml / saphyr::LoadableYamlNode ayaml::SpannedTree + SpannedNode or ayaml::Tape or Spanned<T> Traverse SpannedNode via as_mapping(), as_sequence(), get(), lookup(), scalar_value(), scalar_text(), scalar_style(), scalar_tag(), and span() / entry_span(); use Tape for lowest-memory resolved DOM with byte spans; map Span directly to miette::SourceSpan and compute lines lazily with LineIndex.
YamlEmitter::new(&mut out).dump(&doc) ayaml::to_string_value(&doc) / to_string_value_with(&doc, &EmitOptions) YamlEmitter writes a leading --- by default; pass EmitOptions::new().with_explicit_start(true) in ayaml when you want ---.
serde_saphyr::from_str::<T>(s) (borrowed 'de) / serde_saphyr::Spanned<T> ayaml::from_str::<T>(s) (owned) or ayaml::from_str_borrowed::<T>(s) / ayaml::Spanned<T> ayaml::from_str requires DeserializeOwned; use from_str_borrowed or from_str_with whenever a generic signature preserves 'de. serde-saphyr expands <<: merges by default; pass ParseOptions::new().with_merge_keys(true) in ayaml.
serde_saphyr::from_multiple_with_options ayaml::Deserializer::from_str_with(s, &opts) + next_borrowed::<Option<T>>() Pull loop skips empty/null documents while preserving quoted 'null'/"~" strings; raise Limits::new().with_max_documents(usize::MAX) when document counts are unbounded.
serde_saphyr::with_deserializer_from_str* ayaml::DocumentDeserializer::from_str / from_str_with Implements serde::Deserializer<'de, Error = ayaml::Error> directly without a closure wrapper.
serde_saphyr::to_io_writer(&mut w, &val) / SingleQuoted / DoubleQuoted ayaml::to_writer(&mut w, &val) / EmitOptions::with_scalar_style Pass EmitOptions::new().with_scalar_style(Some(ScalarStyle::SingleQuoted)) (or ScalarStyle::DoubleQuoted) to force quote styles without wrapper types.
Validation-only serde_saphyr::from_str::<IgnoredAny> ayaml::Tape::parse / TapeDocuments::parse or ayaml::from_str::<IgnoredAny> Tape::parse / TapeDocuments::parse validates syntax, duplicate keys, anchors, and document counts fastest; from_str::<IgnoredAny> minimizes peak heap on large single files.
Manual string slicing for config updates ayaml_edit::replace_scalar, remove_entry, apply_batch Preserves comments, blank lines, and indentation; verifies canonical event diff (see Source-preserving editing).

ayaml::parse_value and ayaml::parse_documents return insertion-ordered Value trees with indexing and typed accessors. Use .get(...) whenever you previously checked .is_badvalue():

use ayaml::{parse_documents, parse_value};
// Single document (rejects accidental extra `---` documents).
let doc = parse_value("server:\n host: 127.0.0.1\n ports: [8080, 8443]\n")?;
assert_eq!(doc["server"]["host"].as_str(), Some("127.0.0.1"));
assert_eq!(doc["server"]["ports"][1].as_u64(), Some(8443));
// Missing keys return `None` via `.get(...)`, whereas `doc["missing"]` returns `&Value::Null`.
assert!(doc.get("missing").is_none());
assert!(doc["missing"].is_null());
// Multi-document stream (equivalent to `YamlLoader::load_from_str`).
let docs = parse_documents("kind: ConfigMap\n---\nkind: Secret\n")?;
assert_eq!(docs.len(), 2);
assert_eq!(docs[0]["kind"].as_str(), Some("ConfigMap"));
assert_eq!(docs[1]["kind"].as_str(), Some("Secret"));

2. Replacing push EventReceiver with pull parse_events

Section titled “2. Replacing push EventReceiver with pull parse_events”

Instead of implementing a stateful callback trait (EventReceiver), iterate directly over ayaml::parse_events (or parse_events_with for custom ParseOptions):

use ayaml::{Event, parse_events};
let input = "name: ayaml\nversion: 1\n";
let mut scalars = Vec::new();
for item in parse_events(input)? {
if let Event::Scalar { value, span, .. } = item? {
scalars.push((value.into_owned(), span));
}
}
assert_eq!(scalars.len(), 4);
assert_eq!(scalars[0].0, "name");
assert_eq!(scalars[1].1.slice(input), Some("ayaml"));

3. Replacing MarkedYaml and marked-yaml with SpannedTree and Spanned<T>

Section titled “3. Replacing MarkedYaml and marked-yaml with SpannedTree and Spanned<T>”

ayaml provides two span APIs without carrying line/column metadata on every node:

  • Use SpannedTree::parse when you need an untyped AST with exact byte spans (span, entry_span), decoded scalar values (scalar_value), presentation styles (scalar_style to distinguish quoted strings from plain scalars), explicit scalar tags (scalar_tag), and full collection traversal (as_mapping, as_sequence, get, lookup). Pass span.start() and span.len() directly to diagnostic crates like miette::SourceSpan, and construct LineIndex lazily only when formatting errors (to_position returns Result<Position, PositionError>). On multi-document streams, top-level span_at / lookup / entry_span_at return None; iterate tree.documents() or index tree.document(i) instead.
  • Use Spanned<T> inside Serde structs when you want typed deserialization and exact spans in one pass.
use ayaml::{ColumnEncoding, LineIndex, Location, PathSegment, ScalarStyle, SpannedTree};
let input = "database:\n host: \"localhost\"\n pool_size: 16\n";
let tree = SpannedTree::parse(input)?;
let root = tree.document(0).expect("root document");
let db = root.get("database").expect("database mapping");
let host = db.get("host").expect("host scalar");
assert_eq!(host.scalar_value(), Some("localhost"));
assert_eq!(host.scalar_style(), Some(ScalarStyle::DoubleQuoted));
let path = [PathSegment::key("database"), PathSegment::key("pool_size")];
let span = tree.span_at(&path).expect("pool_size span");
assert_eq!(span.slice(input), Some("16"));
assert_eq!(
tree.entry_span_at(&path).and_then(|s| s.slice(input)),
Some(" pool_size: 16\n")
);
let index = LineIndex::new(input);
let pos = index
.to_position(span.start(), ColumnEncoding::Utf16)
.expect("utf-16 column");
let loc = Location::from(pos);
assert_eq!((loc.line(), loc.column()), (3, 14));

4. Multi-document streams, tag linters, and quote-preserving emission

Section titled “4. Multi-document streams, tag linters, and quote-preserving emission”

For serde-saphyr callers migrating from_multiple_with_options, tag checks (--disallow-unknown-tags), or SingleQuoted / DoubleQuoted wrappers:

use ayaml::{
ColumnEncoding, Deserializer, EmitOptions, Event, Limits, LineIndex, Location, ParseOptions,
ScalarStyle, parse_events, to_string_with,
};
use serde::Deserialize;
#[derive(Debug, PartialEq, Deserialize)]
struct Rule {
id: String,
}
// Multi-document stream skipping empty/null documents while keeping real entries:
let stream = "---\n# comment-only doc\n---\nid: no-eval\n---\nnull\n";
let opts = ParseOptions::new().with_limits(Limits::new().with_max_documents(usize::MAX));
let mut de = Deserializer::from_str_with(stream, &opts)?;
let mut rules = Vec::new();
while let Some(doc) = de.next_borrowed::<Option<Rule>>()? {
if let Some(rule) = doc {
rules.push(rule);
}
}
assert_eq!(rules, vec![Rule { id: "no-eval".into() }]);
// Inspecting unknown tags via parse_events + Tag::is_core() / handle() / suffix():
let tagged_src = "v: !custom 1\n";
let index = LineIndex::new(tagged_src);
let mut unknown_tags = Vec::new();
for ev in parse_events(tagged_src)? {
if let Event::Scalar { tag: Some(tag), span, .. } = ev? {
if !tag.is_core() {
let loc = Location::from(
index
.to_position(span.start(), ColumnEncoding::Scalar)
.expect("valid offset"),
);
unknown_tags.push((format!("{}{}", tag.handle(), tag.suffix()), loc.line()));
}
}
}
assert_eq!(unknown_tags, vec![("!custom".to_string(), 1)]);
// Quote-preserving scalar emission (replacing serde_saphyr::SingleQuoted / DoubleQuoted):
let single = to_string_with(
&"0.12.24",
&EmitOptions::new().with_scalar_style(Some(ScalarStyle::SingleQuoted)),
)?;
assert_eq!(single, "'0.12.24'\n");

5. Replacing YamlEmitter and source-preserving edits

Section titled “5. Replacing YamlEmitter and source-preserving edits”

Use ayaml::to_string_value_with with EmitOptions for canonical re-emission (add .with_explicit_start(true) to match YamlEmitter’s leading ---), or use the companion ayaml-edit crate (see Source-preserving editing) when updating existing configuration files while preserving comments and formatting:

use ayaml::{EmitOptions, PathSegment, Value, parse_value, to_string_value_with};
use ayaml_edit::replace_scalar;
let val = parse_value("env: prod\nreplicas: 2\n")?;
let flow = to_string_value_with(&val, &EmitOptions::flow())?;
assert_eq!(flow, "{env: prod, replicas: 2}\n");
let config = "# Production replicas\nenv: prod\nreplicas: 2\n";
let edited = replace_scalar(config, &[PathSegment::key("replicas")], &Value::from(4_u64))?;
assert_eq!(edited.output(), "# Production replicas\nenv: prod\nreplicas: 4\n");
  • Missing-key indexing: doc["missing"] returns &Value::Null (not Yaml::BadValue). Check doc.get("missing") wherever presence matters.
  • Zero-config YAML 1.2.2 defaults: Options that serde-saphyr callers often set manually (strict_booleans, literal << keys, .inf/.nan pass-through, rejecting duplicate keys) are already ayaml’s out-of-the-box defaults, eliminating boilerplate options builders.
  • Duplicate keys and relaxed flow indentation: ayaml rejects duplicate mapping keys during Value composition, Tape construction, and typed Serde decoding (ErrorCode::DuplicateKey), while parse_events and SpannedNode::as_mapping expose every raw pair for linters. If a linter needs libyaml-style under-indented flow continuations while keeping duplicate key rejection, enable libyaml-compat and pass ayaml::compat::ParseOptions::new().with_allow_duplicates(false).
  • YAML 1.2 vs YAML 1.1 plain-scalar emission: ayaml emits YAML 1.2.2 scalars, so dotted versions like 0.12.24 stay unquoted without workarounds and leading-zero numerals like 0644 are quoted, while YAML 1.1-only booleans (yes/no/on/off) and ISO dates (2026-10-09) emit unquoted unless callers targeting PyYAML quote them explicitly.
  • Native limits: All entry points enforce default ceilings (Limits). For dense documents within the 32 MiB default input limit (> 1M events or > 1M entries), use ParseOptions::for_max_input(). For trusted documents larger than 32 MiB, also raise max_input_bytes explicitly via ParseOptions::new().with_limits(Limits::for_max_input().with_max_input_bytes(...)) (see Sizing resource limits).
  • Merge keys: Unlike serde-saphyr (which expands <<: by default), ayaml keeps << literal in YAML 1.2.2 mode; opt in explicitly via ParseOptions::new().with_merge_keys(true).
  • Binary size tradeoffs: In non-LTO release builds replacing a parse-only crate like yaml-rust2, ayaml’s unified surface (parser, Value, Tape, SpannedTree, Serde, emitter) can add ~500 KiB stripped; under LTO in CLI tools replacing serde-saphyr, binaries typically shrink by ~600 to 650 KiB. See Real-world migration validation for measured results on syntect, ast-grep, prek, and rattler-build.