Migrating from serde_yaml
serde_yaml (archived upstream) wrapped C-transpiled unsafe-libyaml with YAML
1.1 heuristics and unbounded alias expansion by default (while enforcing a
128-level recursion cap). ayaml provides a safe, pure-Rust
(#![forbid(unsafe_code)]) YAML 1.2.2 replacement with Serde entry
points, native DoS Limits (including byte-weighted alias expansion budgets),
byte-accurate spans, and an optional libyaml-compat boundary for legacy
documents.
Quick API mapping
Section titled “Quick API mapping”serde_yaml |
ayaml |
Notes |
|---|---|---|
serde_yaml::from_str::<T>(s) |
ayaml::from_str::<T>(s) |
Also from_str_with(s, &opts) and zero-copy from_str_borrowed(s). |
serde_yaml::from_slice::<T>(b) |
ayaml::from_slice::<T>(b) |
Also from_slice_with and zero-copy from_slice_borrowed; rejects inputs over Limits::max_input_bytes before UTF-8 validation. |
serde_yaml::from_reader::<R, T>(r) |
ayaml::from_reader::<R, T>(r) |
Also from_reader_with; reads at most max_input_bytes + 1 bytes before returning ErrorKind::Limit. |
serde_yaml::to_string(&v) |
ayaml::to_string(&v) |
Deterministic emission; customize via to_string_with(&v, &EmitOptions). |
serde_yaml::to_writer(w, &v) |
ayaml::to_writer(w, &v) |
Also to_writer_with(w, &v, &EmitOptions). |
serde_yaml::from_value::<T>(v) |
ayaml::from_value::<T>(v) |
Same typed shape checks as from_str, except String targets require Value::String, Value::Null is explicit null (cannot supply empty collections or defaulted structs), and Spanned<T> is refused. |
serde_yaml::to_value(&v) |
ayaml::to_value(&v) |
Converts any Serialize value into ayaml::Value. |
serde_yaml::Deserializer::from_str(s) |
ayaml::Deserializer::from_str(s) |
Fallible (Result<Deserializer, Error>) lazy multi-document cursor (de.next::<T>()?); does not implement Iterator or serde::Deserializer directly (use DocumentDeserializer for single-doc middleware; read UTF-8 first for multi-doc Read/&[u8]). |
Value::apply_merge(&mut self) |
ParseOptions::new().with_merge_keys(true) or Value::apply_merge_keys(&mut self) |
with_merge_keys(true) preserves quoted "<<" keys, spans, and borrowed strings; Value::apply_merge_keys / apply_merge_keys_with_limits operate post-parse (where quoted "<<" and plain << are indistinguishable). |
serde_yaml::with::singleton_map |
ayaml::with::singleton_map |
Drop-in #[serde(with = "ayaml::with::singleton_map")] helper for serializing and deserializing externally tagged enum variants as single-entry mappings (Env: API_TOKEN). |
serde_yaml::value::TaggedValue |
ayaml::TaggedValue or generic ayaml::Tagged<T> |
Use Tagged<T> in typed Serde structs to capture an explicit YAML Tag alongside a strongly typed payload T (composable with Spanned<T>). |
Error::location() (Location::index()) |
Error::span() + Error::location() |
Error::span().start() replaces Location::index(); Error::location() gives one-based (line, column); format err.masked() for untrusted logs. |
1. Updating Cargo.toml
Section titled “1. Updating Cargo.toml”Replace serde_yaml with ayaml:
[dependencies]ayaml = "1.0.0"serde = { version = "1", features = ["derive"] }2. Typed Serde decode and multi-document streams
Section titled “2. Typed Serde decode and multi-document streams”Single-document calls map directly, while multi-document streams become a
pull loop on ayaml::Deserializer::next:
use ayaml::{Deserializer, from_str, to_string};use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Deserialize, Serialize)]struct Service { name: String, port: u16,}
let single: Service = from_str("name: billing\nport: 8080\n")?;assert_eq!(single.port, 8080);
let yaml = to_string(&single)?;assert_eq!(from_str::<Service>(&yaml)?, single);
let stream = "name: api\nport: 8080\n---\nname: worker\nport: 9090\n";let mut de = Deserializer::from_str(stream)?;let mut services = Vec::new();while let Some(svc) = de.next::<Service>()? { services.push(svc);}assert_eq!(services.len(), 2);assert_eq!(services[1].name, "worker");3. Behavioral differences to check
Section titled “3. Behavioral differences to check”Moving from serde_yaml to YAML 1.2.2 introduces several intentional
differences:
- Duplicate mapping keys are rejected by default.
serde_yamlsilently overwrote earlier keys in mappings.ayamlreturnsErrorCode::DuplicateKeyso typos and shadowed security policies fail loudly. - YAML 1.1 plain scalars stay strings. Values like
yes,no,on,off,0644, and2026-05-01decode as strings in YAML 1.2.2, while special floats follow YAML 1.2.2 (.nan,.inf,-.inf; bareNaN/Infinityremain strings; see Migrating from YAML 1.1). - Merge keys (
<<:) are opt-in. Replaceval.apply_merge()withParseOptions::new().with_merge_keys(true)so merge expansion works directly with typed Serde structs and respects alias budgets while keeping quoted"<<"literal. When mutating an already-parsedValue, useValue::apply_merge_keysorValue::apply_merge_keys_with_limits. - Externally tagged Rust enums (
!VariantandVariant: payload),with::singleton_map, andTagged<T>. Likeserde_yaml0.9,ayamlserializes externally tagged data-carrying enum variants with!VariantYAML tags (and unit variants as plainVariant), and deserializes both!Variant payloadand single-entry mappings (Variant: payload) out of the box. Replace#[serde(with = "serde_yaml::with::singleton_map")]with#[serde(with = "ayaml::with::singleton_map")]to serialize data-carrying variants (newtype, tuple, and struct) as single-entry mappings (Env: API_TOKEN) while preservingayaml’s enum decoding rules and spans. When a field expects an explicit YAML tag alongside a typed payload without dropping down toValue::Tagged, useayaml::Tagged<T>(composable as bothSpanned<Tagged<T>>andTagged<Spanned<T>>). - Indented sequences and block-scalar indentation.
serde_yaml(libyaml) always emits indentless block sequences beneath mapping keys;ayamlsupports both indentless (default) and indented block sequences viaEmitOptions::new().with_indent_sequences(true). For multiline block scalars with leading spaces,ayamlfollows YAML 1.2.2 indentation indicators strictly (|3-for a 2-space-indented root scalar where the document root has indentation-1, versus|2-beneath a mapping key). If a custom formatter splices a single emitted scalar under a mapping key, emit it inside a mapping value (or letayaml::to_string_value_withformat the whole document withwith_indent_sequences(true)). - Empty documents,
Number,Value::Tagged, andMapping.- An empty document (
"") decodes asValue::Null(parse_value/from_str::<Value>) and fills a#[serde(default)]struct viafrom_str, whereasfrom_value(Value::Null)treatsNullas an explicit null. ayaml::Numberstores exacti64/u64/i128/u128integers and IEEE-754f64floats, implementsFromacross all primitive integer and float widths (i8..i128,u8..u128,isize,usize,f32,f64), and formats non-finite floats as.nan/.inf/-.inf.Valueaccessors (as_str,as_u64, indexing) look throughValue::Tagged,TaggedValue.tagis a structuredayaml::Tag(handle(),suffix()), and serializingValue::Taggedto non-YAML Serde serializers (such asserde_json) encodes as{"!Tag": value}.Mappingis insertion-ordered with privateindexmapbacking (noindexmaptypes in the public API), zero-alloc&strlookups, andshift_remove/swap_remove.
- An empty document (
- Resource limits are always active. Untrusted payloads cannot trigger billion-laughs alias expansion or unbounded reader allocation.
use ayaml::{ErrorCode, ParseOptions, Tag, Tagged, from_str, from_str_with, parse_value, to_string};use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Serialize, Deserialize)]enum SecretRef { Env(String), Literal(String),}
#[derive(Debug, PartialEq, Serialize, Deserialize)]struct AppConfig { country: String, retries: u8, #[serde(with = "ayaml::with::singleton_map")] token: SecretRef,}
// Duplicate keys are rejected rather than silently overwritten.let dup_err = parse_value("port: 80\nport: 443\n").unwrap_err();assert_eq!(dup_err.code(), ErrorCode::DuplicateKey);
// Opt-in merge keys + YAML 1.2.2 strings (`NO` stays "NO") + `!Tag` enums.let input = "\defaults: &def country: NO retries: 3app: <<: *def token: !Env API_TOKEN";
#[derive(Debug, Deserialize)]struct Root { app: AppConfig,}
let opts = ParseOptions::new().with_merge_keys(true);let root: Root = from_str_with(input, &opts)?;assert_eq!( root.app, AppConfig { country: "NO".into(), retries: 3, token: SecretRef::Env("API_TOKEN".into()), });
// `ayaml::with::singleton_map` emits single-entry mappings (`Env: API_TOKEN`) instead of `!Env`.let emitted = to_string(&root.app)?;assert!(emitted.contains("token:\n Env: API_TOKEN\n"));assert_eq!(from_str::<AppConfig>(&emitted)?, root.app);
// Capture an explicit YAML tag alongside a typed payload via `ayaml::Tagged<T>`.let tagged: Tagged<u16> = from_str("!Port 8080\n")?;assert_eq!(tagged.tag, Tag::local("Port"));assert_eq!(tagged.value, 8080);assert_eq!(to_string(&tagged)?, "!Port 8080\n");
// Single-doc readers reject trailing documents.let trailing = from_str::<u32>("1\n---\n2\n").unwrap_err();assert_eq!(trailing.code(), ErrorCode::TrailingDocuments);4. Spans, limits, and safe error logging
Section titled “4. Spans, limits, and safe error logging”serde_yaml::Error::to_string() can echo raw YAML fragments into logs. In
ayaml, match on Error::code(), use Error::span() (span.start() replaces
Location::index()) with LineIndex for user-facing editors, and log
err.masked() for untrusted inputs:
use std::collections::HashMap;use ayaml::{ErrorCode, Limits, ParseOptions, from_str_with};
let opts = ParseOptions::new().with_limits(Limits::new().with_max_depth(32));let err = from_str_with::<HashMap<String, u16>>("api_key: super-secret\n", &opts).unwrap_err();
assert_eq!(err.code(), ErrorCode::InvalidType);assert!(err.location().is_some());assert!(err.span().is_some());let safe_log = err.masked().to_string();assert!(!safe_log.contains("super-secret"));assert!(safe_log.contains("yaml.invalid-type"));5. Legacy fallback with ayaml::compat
Section titled “5. Legacy fallback with ayaml::compat”If you have legacy inputs that rely on last-wins duplicate keys or non-core
global tags (such as !!timestamp), enable the additive libyaml-compat
feature and call ayaml::compat::* at that boundary without relaxing the rest
of your application:
[dependencies]ayaml = { version = "1.0.0", features = ["libyaml-compat"] }See Compatibility profile for the exact rules in
ayaml::compat, and Real-world migration validation
for measured results from migrating prefix-dev/rattler-build off serde_yaml.