Skip to content
Projekte

Über uns

YAML (de)serializer for Serde, emphasizing panic-free parsing, fast builds and good error reporting. Supports properties, include, tag and comment capture"

Entwicklerwerkzeuge

So werden diese Zahlen gemessen

What you can do

  • Configurable budgets: Enforce input limits to mitigate resource exhaustion (e.g., deeply nested structures or very large arrays); see Budget.
  • Precise error reporting with snippet rendering.
  • Optional !include support with a custom or default resolver (inclusion of either a complete document or the node referenced by a specified anchor).
  • Tag support: The Tagged<T> wrapper captures and emits a node's resolved YAML tag.

Gemessener Sternzuwachs

in 24h
0
in 7 days
+4
in 15 days
+7
in 1 month
Verlauf wird gesammelt

Nettoänderungen in überlappenden Zeiträumen, keine Tagessummen. Fehlende Messwerte bleiben leer. Sterne zeigen Interesse, nicht Qualität.

README.md

Original

serde-saphyr

unsafe forbidden Miri panic-free GitHub Workflow Status docs.rs codecov

Fuzz & Audit crates.io API compatibility CodSpeed

Socket dependency status crates.io crates.io

serde-saphyr is a strongly typed YAML deserializer built on top of granit-parser.

The parser is fuzz-tested and designed not to panic on malformed YAML. This design does not cover out-of-memory conditions, panics in user-provided callbacks, or similar cases. The library build is configured to deny unsafe code. This does not extend to transitive dependencies.

The crate deserializes YAML directly into your Rust types without constructing an intermediate tree of “abstract values.” Try it online as a WebAssembly application here.

See release history on GitHub.

Overview

Why this approach?

  • Light on resources: Having almost no intermediate data structures should result in more efficient parsing, especially if anchors are used only lightly.
  • Also, simpler: No code to support intermediate Values of all kinds.
  • Type-driven parsing: YAML that doesn’t match the expected Rust types is rejected early.
  • Safer by construction: serde-saphyr avoids the typical YAML remote code execution vulnerability because it does not support or implement tag-driven object construction. When used for linting, it can be configured to reject unknown tags.

Notable features

  • Configurable budgets: Enforce input limits to mitigate resource exhaustion (e.g., deeply nested structures or very large arrays); see Budget.
  • Precise error reporting with snippet rendering.
  • Optional !include support with a custom or default resolver (inclusion of either a complete document or the node referenced by a specified anchor).
  • Tag support: The Tagged<T> wrapper captures and emits a node's resolved YAML tag.
  • Comment support. Wrapper Commented<T> both captures and emits comments.
  • Optional property support, with redaction (removal) of property values from crate-generated diagnostics.
  • Serializer supports emitting anchors (Rc, Arc, Weak) if they are properly wrapped (see below).
  • Declarative validation with optional validator (example) or garde (example).
  • Optional miette (example) integration for more advanced error reporting.
  • serde_json::Value is supported when parsing without a target structure (non-finite floats are rejected by default; NonFiniteFloatPolicy can instead preserve them as strings or pass them to the visitor).
  • Serializer and Deserializer are public (due to how it's implemented, Deserializer is available in the closure only).
  • Serialized floats are official YAML floats.
  • Correct handling for JSON-style Unicode surrogate pairs.
  • robotic extensions to support YAML dialect common in robotics (see below).

serde-saphyr is compatible with WebAssembly. The CI flow includes builds for both wasm32-unknown-unknown (browser / JS) and wasm32-wasip1 (WASI runtimes), with most of the test suite running and passing (excluding tests that require file access or similarly unsupported functionality). We also wrote yva in Dioxus to deploy serde-saphyr on the web.

Testing

The test suite currently includes over 4000 passing tests. For YAML Test Suite v2022-01-17, all 350 active test IDs and all 402 active cases from the data-2022-01-17 release are represented (9C9N is intentionally relaxed to keep the library compatible with PyYAML and ruamel.yaml). Although we made a reasonable effort, accidental omissions or conversion errors remain possible. Some additional cases are taken from the original serde-yaml tests.

Project relationship

serde-saphyr is not a fork of the older serde-yaml crate and shares no code with it (apart from some reused tests). It is also not part of the saphyr project. The name was historically chosen to reflect the use of saphyr parser at a time when the Saphyr project did not provide its own Serde integration. granit-parser it's currently using is the fork of Saphyr parser.

Getting started

serde-saphyr requires Rust 1.89 or newer. This minimum supported Rust version (MSRV) is tested in CI.

Usage

This branch targets the 3.0.0-rc.1 prerelease. To test this exact candidate after it is published, opt in explicitly:

[dependencies]
serde-saphyr = "=3.0.0-rc.1"

Ordinary "2" and "3" requirements do not select this prerelease. See Cargo's prerelease rules and YAML changes in 3.0.0 before upgrading.

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Config {
  name: String,
  enabled: bool,
  retries: i32,
}

fn main() {
let yaml_input = r#"
  name: "My Application"
  enabled: true
  retries: 5
...
"#;

    let config: Result<Config, _> = serde_saphyr::from_str(yaml_input);

    match config {
        Ok(parsed_config) => {
            println!("Parsed successfully: {:?}", parsed_config);
        }
        Err(e) => {
            eprintln!("Failed to parse YAML: {}", e);
        }
    }
}

Using serializer or deserializer specifically

To speed up compilation, you can link only the deserializer or only the serializer (along with their respective dependencies). The serialize, deserialize, and comments features are enabled by default.

If you only need one side, you can disable default features and enable only the API surface you use:

serde-saphyr = { version = "=3.0.0-rc.1", default-features = false, features = ["deserialize"] }

or

serde-saphyr = { version = "=3.0.0-rc.1", default-features = false, features = ["serialize"] }

Disabling both will produce a "Invalid feature configuration" error (such configuration makes no sense).

These configurations omit comment support. Add "comments" to the feature list to use Commented<T>, CommentPosition, or comment-specific options and budget fields. The feature also enables granit-parser's comments feature when deserialization is enabled; serialization alone does not pull in granit-parser. YAML comments are still accepted and validated when the feature is disabled, but their text is not retained.

The optional huge_documents feature switches span storage from u32 indices to a packed 48-bit internal representation so spans can cover YAML inputs far beyond 4 GiB without widening every coordinate to a full u64. Public getters still return u64, and values beyond the packed range saturate instead of wrapping.

Migrating from serde_yaml

Duplicate mapping entries

serde-saphyr rejects duplicate mapping keys by default. To use serde_yaml's visitor-driven handling of explicit entries, select DuplicateKeyPolicy::PassThrough:

let options = serde_saphyr::options! {
    duplicate_keys: serde_saphyr::DuplicateKeyPolicy::PassThrough,
};

This forwards repeated entries to the receiving Serde visitor. Ordinary derived structs reject repeated fields, HashMap and BTreeMap keep the last value, and custom visitors can retain all pairs for a multimap. Unlike LastWins, this policy does not collapse struct fields or numerically equivalent keys before Serde sees them. For example, string keys 0xB and 11 are both delivered with their original spelling.

Merge expansion still follows MergeKeyPolicy: explicit entries override merged entries, earlier merge sources override later sources, and repeated keys within a merge source retain the first entry. Use MergeKeyPolicy::AsOrdinary to forward literal << entries without expansion.

PassThrough is an opt-in extension, not a YAML-conformance requirement or a promise of complete serde_yaml compatibility. YAML requires unique mapping keys; DuplicateKeyPolicy::Error remains the default.

Numeric-looking strings in untyped values

lowercase_radix_prefixes_only defaults to false: both lowercase (0x, 0o, 0b) and uppercase (0X, 0O, 0B) prefixes are accepted by the shared integer parser. Set it to true to require lowercase prefixes everywhere. Uppercase-prefixed plain scalars then remain strings during implicit inference, including untagged enums and flattened fields, while integer and float targets and explicit !!int and !!float tags reject them. This includes optional + or - signs. Uppercase hexadecimal digits remain valid with a lowercase prefix, such as 0xFF. Binary notation (0b101) remains a supported extension to the YAML 1.2 Core schema.

When deserializing an untyped value, implicitly resolved integers and explicit !!int values use the same Serde visitors. Integers with a minus sign use i64 when they fit and i128 otherwise. Other integers use u64 or u128. This preserves accepted decimal, radix-prefixed, underscored, and enabled legacy-octal integers exactly within the supported range. Visitors without support for 128-bit integers, including serde_json::Value without arbitrary_precision, report an error when a value requires that width. Beyond the 128-bit range, explicit !!int reports an error. During implicit inference, plain decimals retain their floating-point fallback and radix-prefixed, underscored, and legacy-octal integers remain strings. Direct float targets and explicit !!float tags can convert integers within the shared i128/u128 parsing range, with possible rounding.

When migrating code that reads generic values such as serde_json::Value, configure these independent options to preserve numeric spellings as strings:

let options = serde_saphyr::options! {
    leading_zero_numbers_as_strings: true,
    allow_numeric_underscores: false,
    lowercase_radix_prefixes_only: true,
};
let value: serde_json::Value = serde_saphyr::from_str_with_options(
    "[0755, -007, +00, 1_000, 0xFF_FF, 0XFF]",
    options,
).unwrap();
assert_eq!(value, serde_json::json!(["0755", "-007", "+00", "1_000", "0xFF_FF", "0XFF"]));

leading_zero_numbers_as_strings defaults to false. Enabling it preserves digit-only decimal spellings with redundant leading zeros and an optional sign; floats such as 0.5, 00.5, and 01e2 still infer as numbers. The restriction applies to implicit type inference through Serde's deserialize_any, including buffering for #[serde(untagged)] and #[serde(flatten)], and to typed integer and float parsing. Explicit numeric tags and legacy_octal_numbers cannot override it. Mapping-key comparison keeps these strings distinct from integers, including inside composite keys and during merge expansion. In no_schema mode, these spellings can be read as strings without quoting.

allow_numeric_underscores defaults to true. Setting it to false disallows underscores in numbers everywhere. Plain scalars such as 1_000, 0xFF_FF, and 1_000.5 remain strings during implicit inference, including untagged enums and flattened fields. Integer and float targets reject these spellings, for both keys and values, even with explicit !!int or !!float tags or with legacy_octal_numbers: true. Mapping-key comparison follows the same rule: 1_000 and 1000 are distinct keys, including inside composite keys and during merge expansion. Leave this option true to retain the supported numeric underscore syntax and compare underscored integer keys by their numeric value. Integer spellings use the same syntax when converted to floats; underscores in fractional or exponential spellings still require robotics angle conversions.

Null values for string fields

For a field declared as hi: String, serde_yaml accepts the plain null forms below as their original text. By default, serde-saphyr treats these forms as null and reports Error::NullIntoString. This also applies with the default no_schema: false setting, and to string mapping keys.

YAML input serde_yaml string value serde-saphyr result
hi: "" Error::NullIntoString
hi: ~ "~" Error::NullIntoString
hi: null "null" Error::NullIntoString

Here, hi: supplies an empty mapping value, which is YAML null.

  • If null means no value, use Option<String>. All three inputs above deserialize as None; the original null spelling is not retained.
  • If text is intended, quote the value: hi: "", hi: "~", or hi: "null". These produce "", "~", and "null", respectively. An explicit string tag also works, for example hi: !!str null produces "null".

To accept the original text of plain null-like scalars for string targets, enable null_as_string (default: false). It applies to both mapping keys and values, including null, Null, NULL, ~, and empty scalars:

let options = serde_saphyr::options! {
    null_as_string: true,
};
let values: std::collections::HashMap<String, String> =
    serde_saphyr::from_str_with_options("null: ~\nempty:\n", options).unwrap();
assert_eq!(values["null"], "~");
assert_eq!(values["empty"], "");

This also supports &str and Cow<str>. Borrowing retains the usual input constraints: use an in-memory input such as from_str_with_options or from_slice_with_options, and #[serde(borrow)] on Cow<str> fields when borrowing is wanted.

The option changes direct string deserialization only. Untagged null still gives None for Option<T>, and untyped values still infer null, including Serde's buffering for untagged enums and flattened fields. A serde_json::Value object can use "null" as a key because its keys deserialize as strings; null values inside it remain JSON null. Explicit !!null tags still reject string targets, and no_schema: true still requires quoting null-like strings. Mapping-key comparison and the skipping of null documents in multi-document APIs are unchanged.

YAML changes in 3.0.0

Version 3.0 changes YAML interpretation and serialization, even where the same Rust code still compiles. Existing documents can produce different values or errors, and some serialized output changes. These rules are the defaults in 3.0.0-rc.1; there is no legacy local-type-alias mode. Test existing configuration files and stored YAML, not just compilation, before upgrading from 2.x.

Check the following options when upgrading from 2.2.0.

  • Struct field names now reject misplaced tags by default. Move the tag to its value or set reject_tagged_field_names: false to retain the previous behavior. See Tags.
  • Replace underscored_numbers_as_strings: true with allow_numeric_underscores: false. Typed numeric targets now reject underscores with this setting.
  • Uppercase radix prefixes such as 0XFF now infer as integers by default. With lowercase_radix_prefixes_only: true they infer as strings and are rejected for numeric targets. Numeric spelling restrictions also apply to integer key comparison. See Numeric-looking strings in untyped values.
  • leading_zero_numbers_as_strings: true now rejects redundant leading-zero integer spellings for typed numeric targets and explicit numeric tags, and takes precedence over legacy_octal_numbers everywhere. Composite keys and merges treat these spellings as strings. With the option disabled, floating-point targets first try the shared integer parser: 010 becomes 8.0 with legacy octal enabled, and 0x10 becomes 16.0. With default options, 010 instead falls back to decimal float parsing as 10.0, while integer targets reject it. Invalid legacy octal spellings, such as 09, and those outside the shared i128/u128 parsing range no longer fall back to decimal float parsing. Untyped values also preserve legacy octal that exceeds their i64/u64 range as strings.

The examples below assume the default tag handles unless a %TAG directive is shown. YAML tag handles are expanded before interpretation; counting exclamation marks alone is not sufficient.

Quoted scalars remain strings

Quoted and block scalars without an explicit type tag, and scalars tagged with standalone !, now reject integer, float, and boolean targets. For example, depth: "16", depth: '16', and depth: ! 16 no longer fill a u16 field. Use depth: 16 or an explicit standard type tag such as depth: !!int "16". Likewise, !!float "1.5" and !!bool "true" remain valid for matching targets. This rule is always enabled, independently of no_schema and strict_booleans; there is no option to restore the previous coercion.

Local type aliases are removed

Earlier releases treated the following local application tags as aliases of standard YAML types. Version 3.0 removes those aliases:

Former local alias Use for a standard type annotation
!str !!str, or quote the string
!int !!int
!float !!float
!bool !!bool
!null !!null, or an untagged null
!seq !!seq, or an untagged sequence
!map !!map, or an untagged mapping
!timestamp !!timestamp
!binary !!binary

The old spellings remain valid application tags; they are not invalid YAML. They no longer request the corresponding built-in conversion or node-shape check. By default they follow the same policy as other application tags: they can select enum variants, are captured by Tagged<T>, and are otherwise ignored where possible. With reject_unsupported_tags: true, these newly unsupported aliases are rejected, including when used as enum selectors. Strict mode already rejects unknown custom enum tags; this change adds the former aliases to that category.

This can silently change successfully parsed values. For example, when the target is serde_json::Value with default options:

Input Previous alias behavior 3.0 behavior
!str 123 String "123" Number 123
!int '123' Number 123 String "123"
!null 123 Null Number 123
!!str 123 String "123" String "123"

For concrete Rust targets the target type still controls deserialization, so an input can instead produce a type error. For example, use !!binary AQID to request base64 decoding; local !binary AQID no longer requests that conversion.

Nonstandard global aliases such as !<tag:yaml.org,2002:!str> are also removed. The standard URI is tag:yaml.org,2002:str, without the extra ! after the colon. The same distinction applies to all nine type names above, on both input and output.

Replace local tags only where they were intended as type annotations. Do not change an intentional enum selector such as !timestamp into !!timestamp. Likewise, inspect %TAG directives rather than performing a blanket text replacement:

%TAG ! tag:yaml.org,2002:
---
value: !str 123  # Still a standard string: the directive changes the resolved tag.

Conversely, %TAG !! ! makes !!str resolve to the local application tag !str. Verbatim tags and named handles use the same resolved-identity rule.

Standalone ! remains a separate non-specific tag: ! 123 is a string, and ! [123, ! 123] is a sequence containing a number and a string. It does not select an enum variant and is not changed by %TAG remapping. Bare !! is not an alias for standalone !; a shorthand using the !! handle requires a suffix.

Intentional extensions !include, !time, !degrees, and !radians remain available under their feature and configuration requirements. Their supported extension aliases are not removed with the standard-type aliases.

Enum selection precedes payload interpretation

A resolved local tag matching a Rust enum variant selects that variant before its payload is interpreted, including names such as str, int, null, seq, map, and timestamp. The selector is then removed and the payload is deserialized into the variant's actual field type. A local !int can therefore select a variant whose field is a string or a collection; it does not impose an integer conversion.

Do not depend on a former type alias overriding a matching enum selector, or on an unmatched local alias being ignored as a built-in string annotation. Recognized global built-in tags remain type annotations, not selectors for similarly named variants. Use local selectors or externally tagged mappings for those variants. Tagged<T> serialization follows the same distinction; a recognized global built-in tag cannot be used to suppress a payload variant's external representation.

Serde's buffering for untagged enums does not provide the direct enum's variant list. In particular, a local !map is no longer a standard mapping annotation through that buffering, so an ordinary mapping arm that accepted it can stop matching. Use !!map or no tag for an ordinary mapping, and a compatible tagged enum representation when the tag is part of the data. The existing !!EnumName VARIANT syntax for supported single-level scalar enums is unchanged; it does not make recognized standard tags into variant selectors.

Tagged values are present inside options

Previously, some application-tagged empty or null-like scalars were consumed as None before the inner target could see the tag. An explicit application tag now denotes a present value: Option<T> passes the intact node to T and wraps a successful result in Some. This does not depend on whether T is an enum.

For an enum with unit variant Timestamp, newtype variant Count(u32), and newtype variant Maybe(Option<u32>), using their lowercase local selectors:

Input Result as Option<E> in 3.0
Untagged empty scalar, null, or ~ None
!!null None
!timestamp, !timestamp null, or !timestamp ~ Some(E::Timestamp)
!count 42 Some(E::Count(42))
!maybe, !maybe null, or !maybe ~ Some(E::Maybe(None))
!maybe 42 Some(E::Maybe(Some(42)))
!count or an unknown selector The same error as for the direct enum target

A null payload is not an absent enum value. Local !null payload no longer forces absence either: it can select a Null(String) variant with payload "payload". Nested options, optional fields and keys, NullableTilde<T>, and tagged wrappers follow the same presence rule. Untagged nulls and resolved standard null tags still represent absence; %TAG and verbatim forms of the standard null tag work as before.

One formerly supported round-trip intentionally changes: Tagged(None::<String>, Some("!foo".into())) still writes !foo null, but reading that node as Tagged<Option<String>> now errors with the default options. Reading it as Tagged<Option<()>> produces a tagged Some(()). Likewise, wrapping an absent NullableTilde<T> in an application tag writes !foo ~, which is now a present tagged node. For absence, use an untagged or standard-tagged null. For a present tagged value with an absent payload, use an enum variant with an optional field. Do not attach an application tag to outer None and expect to preserve absence on reading.

Mapping-key identity includes local tags

Duplicate detection and merge expansion now preserve resolved local tag identities, including inside composite keys. Local !str a is distinct from standard !!str a and from untagged a; different local tags also remain distinct. For example:

{!str a: 1, a: 2}

These are two distinct YAML keys, rather than an alias-tagged duplicate. Similarly, local !int 0xB and !int 11 retain their payload spellings and are distinct. Standard !!int 0xB and !!int 11 still compare numerically, as do equivalent untagged integer keys. Equivalent spellings of the same local tag, including verbatim and directive-expanded forms, still compare equally.

This changes which entries are duplicates and which entries survive FirstWins, LastWins, or merge expansion. YAML key equality is separate from Rust key equality: if conversion discards a tag, a receiving HashMap or BTreeMap can still combine otherwise distinct YAML keys. Preserve the distinction in the target key type when it matters; do not rely on the previous alias-based duplicate detection.

Multi-document APIs retain tagged null-like documents

As in 2.1 and 2.2, application-tagged scalar documents reach the target deserializer even when their payload is empty or null-like. In 3.0 this also applies to former local type aliases such as !null. String, byte, reader, and validation APIs follow the same rule for local and global application tags. The multi-document null filter skips untagged null scalars, including those produced by DockerComposeWithNulls interpolation, and resolved standard-null scalars.

For example, --- !null was skipped as a null document in 2.2. It can now select a unit enum variant named null, including through Option<E>. A retained document with an unknown selector or invalid payload can now report an error. Review assumptions about document counts and ignored invalid data when upgrading.

Tagged unit variants omit the written null payload

A matching local tag on a unit enum variant now writes only the tag:

# Previously written for Tagged(E::Timestamp, Some("!timestamp".into())):
!timestamp null
# Written in 3.0:
!timestamp

This also applies through optional and tagged wrappers and inside containers. Reading still accepts omitted content and explicit plain null spellings, including null, Null, NULL, and ~. Non-null content is rejected for a unit variant, not silently discarded: quoted "null", numbers, and collections are not unit payloads. Use a variant with fields when the content is meaningful.

Actual fields keep their serialized payloads: !count 42, !maybe null, and !maybe 42 are not shortened. Empty tuple and struct variants retain [] and {} respectively. Ordinary enum serialization without an explicit matching local tag is unchanged. Update exact-output snapshots for tag-only units, and test old readers before exchanging new output with applications still using 2.x.

Additional scalar and collection corrections since 2.0

Recognized scalar tags are checked consistently for numeric, boolean, character, and enum targets. Incompatible tags no longer disappear during conversion. For example, do not use standard !!timestamp as a numeric duration annotation or !time on a boolean. The robotics tags !time, !degrees, and !radians require the robotics feature and angle_conversions: true for floating-point conversions and untyped reads. Enabled conversions also run for skipped and flattened values; invalid tagged payloads can therefore fail in paths that previously ignored them. Use !time for durations in seconds, not !!timestamp, and remove annotations where an ordinary number or boolean is intended. Local robotics tags can still select matching typed enum variants before their payloads are interpreted; include processing and strict tag rejection retain their separate requirements.

YAML null no longer constructs empty sequences, mappings, or mapping-based structs. This covers blank values, ~, null, Null, NULL, and standard-tagged nulls. Write the intended collection explicitly:

items: []     # Not items: or items: null
settings: {}  # Not settings: or settings: null

Conversely, a mapping no longer constructs a unit struct: {} and other mappings are rejected, and a unit struct reads only from null.

A mapping-based struct must still satisfy its field requirements. Ordinary null continues to produce None for Option<T>. #[serde(default)] still handles an absent field; it does not make a present null valid for a collection field.

For compatibility, single-document APIs accept a stream with no documents (empty, whitespace-only, or comment-only input) as an empty collection or a struct whose fields can all be omitted. An explicit empty document (---) has a null root and follows the null rules above. Multi-document APIs return no items for a stream with no documents.

SerializerOptions::empty_as_braces is deprecated since 2.1.0: leave it at its default true to write [] and {}. The retained false setting emits blank values for empty block collections without tags or anchors; those values are null and no longer round-trip into collection types.

Implicit null recognition uses only the standard plain spellings: empty, ~, null, Null, and NULL. Mixed capitalization such as NulL remains a string, not null, so it is not skipped as a null document or treated as outer None. An explicit !!null tag requires the same spellings, quoted or not: !!null foo is rejected instead of read as null, and a multi-document stream does not skip it. With strict_booleans: true, only true, True, TRUE, false, False, and FALSE are boolean spellings. Mixed forms such as tRuE remain strings during inference, are allowed as unquoted text with no_schema, and are rejected for boolean targets. Use standard spellings for nulls and booleans, and quote text whose exact spelling must be preserved.

Before upgrading, check type-like local tags and %TAG directives, tagged optional values, duplicate and merged keys, document streams, empty collections, and exact serialized-output assertions. Test with both the intended Rust types and generic values where your application uses them; those paths need not coerce scalars alike.

Migrating from 1.x

When upgrading from 1.x, also apply the YAML changes in 3.0.0 above. The following API migration notes describe the earlier 2.0 transition.

Version 2.0 lets from_multiple, from_slice_multiple, and their _with_options variants deserialize values that borrow from the input by changing their bound from DeserializeOwned to Deserialize<'de>. These functions retain their names, single type parameter, and Vec<T> returns and are not deprecated. Ordinary calls such as from_multiple::<Config>(input) and generic callers with T: DeserializeOwned continue to work.

Direct function pointers or callbacks that must accept arbitrary input lifetimes may need a forwarding closure:

use serde_saphyr::{Error, from_multiple, from_slice_multiple};

let parse: fn(&str) -> Result<Vec<String>, Error> =
    |input| from_multiple::<String>(input);
let parse_bytes: fn(&[u8]) -> Result<Vec<String>, Error> =
    |input| from_slice_multiple::<String>(input);

The new from_str_multiple, from_bytes_multiple, and their _with_options variants also support borrowing and let you choose a collection implementing Default + Extend<T>.

Version 2.0 keeps Error::AliasError and adds a mandatory error: Box<Error> field containing the original error. Manual constructors must supply it, and patterns listing every field must add error or ... The msg field remains available as a deprecated compatibility string populated from error.to_string().

Rendering passes the original error through alias and snippet wrappers to the active formatter. Plain messages compose the alias definition and use locations once using the active localizer; snippet and miette diagnostics use their location labels without embedding plain-text location suffixes. Since version 2.1, Error::WithSnippet forwards the wrapped error's source() to avoid duplicate messages in error chains. Use without_snippet() to inspect the wrapped error itself. As an exception, Error::AliasError and its snippet wrappers return the wrapped error directly, preserving the complete alias source chain.

use serde_saphyr::Error;

fn report(err: &Error) {
    // Existing matches still work, with a deprecation warning for `msg`.
    if let Error::AliasError { msg, .. } = err.without_snippet() {
        eprintln!("{msg}");
    }

    // Use the original error for formatting or inspecting its variant.
    if let Error::AliasError { error, .. } = err.without_snippet() {
        eprintln!("{error}");
    }
}

Migrating from 0.0.x

Version 1.0 removes the APIs that were deprecated during the 0.0.x series and makes a few intentional naming and extensibility changes:

  • Replace the removed to_writer and to_writer_with_options functions with to_fmt_writer* for std::fmt::Write targets or to_io_writer* for std::io::Write targets.
  • Construct configuration with options!, budget!, ser_options!, alias_limits!, and render_options!. Configuration and public request/result structs are non-exhaustive so fields can be added compatibly; use constructors such as ResolvedInclude::new when returning include content. Fields themselves are no longer deprecated.
  • ExternalMessageSource::Parser now carries the parser's ScanError, and the source field of Error::ExternalMessage is boxed. Prefer .. when matching fields you do not need.
  • Create weak anchors from a borrowed strong pointer, for example RcWeakAnchor::from(&rc); consuming a strong pointer no longer creates a weak anchor that immediately dangles.
  • The direct serializer's with_indent and with_options constructors validate settings and return Result; options are passed by value. Serializer::new follows SerializerOptions::default, including compact list indentation. SerializerOptions is Clone, but intentionally not Copy.
  • read now returns impl Iterator, matching the other streaming entry points and avoiding an allocation. Code that explicitly required a boxed iterator can wrap it with Box::new.
  • Concrete formatter wrappers such as DefaultMessageFormatterWithLocalizer and UserMessageFormatterWithLocalizer are no longer public, and serializer helper types such as TupleSer are now opaque implementation details. Use the returned impl MessageFormatter values or serde::Serializer associated types instead. When both serialization and deserialization are enabled, the new root aliases SerializeError and DeserializeError distinguish their error types.

Executable

serde-saphyr comes with a simple executable (CLI) that can be used to check the budget of a given YAML file, and can also be used as a YAML validator, printing the YAML error line, column numbers, and excerpt.

The CLI includes filesystem-backed !include support, so it must be built with the include_fs feature. To install and run it (no Rust knowledge required):

cargo install serde-saphyr --version 3.0.0-rc.1 --features include_fs

# binary name is the package name by default
serde-saphyr path/to/file.yaml

To enable fancy error reporting (graphical diagnostics) via the optional miette integration, install/build the CLI with the miette feature enabled:

# install with miette enabled
cargo install serde-saphyr --version 3.0.0-rc.1 --features miette,include_fs

# or run from a git checkout
cargo run --features miette,include_fs -- path/to/file.yaml

If you want to keep the previous plain-text error output even when built with miette, pass --plain:

serde-saphyr --plain path/to/file.yaml

If you want to allow file inclusion (!include tags) during parsing, configure the filesystem root path using --include:

serde-saphyr --include path/to/root path/to/file.yaml

Configuration and safety controls

Options

Serde-saphyr provides control over serialization and deserialization behavior. We generally welcome feature requests, but we also recognize that not every user wants every feature enabled by default.

To support different use cases, most behavior can be enabled, disabled, or tuned via Options (deserializers) and SerializerOptions (serializers). Serde-saphyr uses a macro-driven approach based on the options!, budget!, and ser_options! macros.

use serde_saphyr::DuplicateKeyPolicy;

fn main() {
    let options = serde_saphyr::options! {
     budget: serde_saphyr::budget! {
         max_documents: 2,
     },
     duplicate_keys: DuplicateKeyPolicy::LastWins,
 };
}

Struct literals cannot be used because option structures are non-exhaustive (to allow new fields without an API-breaking change).

Pathological inputs & budgets

Fuzzing shows that certain adversarial inputs can make YAML parsers consume excessive time or memory, enabling denial-of-service scenarios. To counter this, serde-saphyr offers a configurable Budget, available through Options. It accounts for parser events, retained copies used to replay anchors, and property-interpolation depth and work. Defaults are intentionally quite permissive; tighten them when you know your input shape, or disable the budget if you only parse YAML you generate yourself. During reader-based deserialization, serde-saphyr does not buffer the entire payload; it parses incrementally, counting bytes and enforcing configured budgets. Reader-based APIs enforce configured byte and structural limits while reading. When streaming from the reader through the iterator, other budget limits apply on a per-document basis, since such a reader may be expected to stream indefinitely. The total size of the input is not limited in this case. To find the typical budget requirements for your file, use our web demo or run the main() executable of this library, providing a YAML file path as a program parameter. You can also fetch the budget programmatically by registering a closure with Options::with_budget_report.

Indentation checking

Adding or removing a single space in YAML indentation may result in a document that is still syntactically correct but semantically wrong. To mitigate such issues, serde-saphyr can enforce indentation rules during deserialization via RequireIndent.

You can require the number of indentation columns to be consistent throughout the document, ensure it is even, or enforce that it is divisible by a specific number (for example, 4 or 6). Configure the desired policy using Options.

Set strict_indentation: true in options! to enforce YAML indentation rules for flow collections ([...] and {...}), including their entries, delimiters, and multiline scalar content. It also rejects under-indented quoted scalar continuations in block context and tabs before quoted continuations. This also applies to included YAML. The default is false, allowing these forms for compatibility.

Set block_scalar_indent_at_least_one: true to give auto-detected block scalars at least one column of indentation (matching libyaml).

Duplicate keys

Duplicate key handling is configurable. By default it’s an error; “first wins”, “last wins”, and PassThrough strategies are available via Options. PassThrough delegates duplicate handling to the receiving Serde visitor; see the migration note. The duplicate key policy applies not just to strings but also to other types (if used as keys when deserializing into a map).

With Error, FirstWins, and LastWins, YAML integer keys are parsed to their numeric meaning before checking for duplicates, regardless of the target Rust type. For example, 0xB and 11 are the same integer key, even in a HashMap<String, _>. This comparison uses exact integer values within the supported i128/u128 range and respects legacy_octal_numbers; values outside that range retain text-based comparison. The same rule applies inside composite keys. Merge expansion uses this comparison under every duplicate key policy.

With allow_numeric_underscores: false, underscores are disallowed in numbers, so plain 1_000 is a string key distinct from the integer key 1000. The same restriction applies inside composite keys and during merge expansion. Deserializing an underscored key into an integer is an error; an explicit !!int tag does not override the restriction.

With lowercase_radix_prefixes_only: true, the same shared integer parser rejects uppercase radix prefixes: plain 0XFF is a string key distinct from 255 and 0xFF, including inside composite keys and during merge expansion. Integer key targets and explicit !!int tags cannot override the restriction. With the default false, all three spellings compare as the same integer key.

With leading_zero_numbers_as_strings: true, plain 010 stays distinct from the integer 8, including when legacy_octal_numbers is enabled. Numeric targets and explicit numeric tags reject 010; string targets preserve its spelling. The restriction applies recursively to composite keys and during merge expansion.

Deserialization into a string still preserves the original scalar spelling: 0xB becomes "0xB". “First wins” and “last wins” retain the selected entry's spelling and value; when integer keys require numeric comparison, “last wins” buffers the remaining mapping to select entries before passing them to Serde. Quoted keys and keys tagged !!str remain strings, so "0xB" and "11" are distinct keys. Duplicate checking uses YAML key identity; the target Rust map can still combine distinct YAML keys if they become equal after deserialization.

Local tags retain their resolved identity and scalar spelling when comparing keys, including inside composite keys. For example, !str foo differs from !!str foo, and !int 1 differs from 1. This prevents local enum selectors from colliding with type annotations or untagged values. Likewise, !int 0xB and !int 11 are distinct because their payload may be an enum's string value. Untagged, unquoted integer keys such as 0xB and 11 already compare by numeric value, as do keys explicitly tagged !!int. Equivalent local tags written through different %TAG handles or verbatim syntax still compare equally.

Discarded duplicate values have no requested Rust type. Their robotics extension tags may have been enum selectors, so deferred robotics shape checks do not run on them. Global tag checks and reject_unsupported_tags still apply while reading the input.

Buffered “last wins” entries use the same replay mechanism as struct fields: trailing comments and comments nested inside buffered values are not preserved, and nested Spanned::referenced locations use the buffered value's reference location. The default error policy and “first wins” do not require this additional buffering.

Booleans

By default, if the target field is boolean, serde-saphyr will attempt to interpret standard YAML 1.1 values as boolean (not just false but also no, etc.). If you do not want this (or if you are parsing into a JSON Value where it might be incorrectly inferred), set strict_booleans to true in Options.

With strict_booleans: true, the accepted spellings are true, True, TRUE, false, False, and FALSE. Other capitalization, such as tRuE, remains a string during type inference and is rejected when the target is bool.

Deserialization patterns and YAML types

Rust types as schema

To address the “Norway problem,” the target Rust types serve as an explicit schema. Because the parser knows whether a field expects a string or a boolean, it can correctly accept 1.2 either as a number or as the string "1.2", and interpret the common YAML boolean shorthands (y, on, n, off) as actual booleans when appropriate (can be disabled). Likewise, 0x2A is parsed as a hexadecimal integer when the target field is numeric, and as a string when the target is String. As with StrictYAML, serde-saphyr uses the Rust type system as the schema for typed deserialization. Integer key comparison is an exception: duplicate checking uses the integer's numeric meaning while preserving its original spelling for string targets.

Quoted and block scalars without an explicit type tag, and scalars tagged with standalone !, remain strings and are rejected for numeric and boolean targets. Explicit standard tags still apply to quoted scalars, such as !!int "16".

YAML null values are rejected for string targets by default. Set null_as_string: true to accept plain null-like scalars as their text in string keys and values. See null values for string fields for the difference from serde_yaml and the available representations.

Schema-based parsing can be disabled by setting no_schema to true in Options. In this case all unquoted values that are parsed into strings, but can be understood as something else, are rejected. This can be used for enforcing compatibility with another YAML parser that reads the same content and requires this quoting. Default setting is false.

Legacy octal notation such as 0052 can be enabled via Options, but it is disabled by default. For untyped values, numeric spelling options can preserve leading-zero, underscored, and uppercase-prefixed numbers as strings. All three options also restrict numeric parsing for typed targets and explicit numeric tags.

The concept that “Rust code is the schema” naturally extends to implemented support for validator and garde, as these crates allow annotations to be added directly to Rust types, providing even stricter control over permissible values.

Multiple documents

Multiple documents can be deserialized into a Vec<T> with serde_saphyr::from_multiple for strings or from_slice_multiple for UTF-8 byte slices. Both support owned values and values that borrow from the input, with _with_options variants for custom options. Empty and null-like documents are skipped; other documents retain their input order. Use an enum to represent diverse documents while retaining strong typing on the Rust side.

use serde::Deserialize;

#[derive(Debug, Deserialize, PartialEq)]
enum Document {
    #[serde(rename = "person")]
    Person { name: String, age: u8 },
    #[serde(rename = "pet")]
    Pet { kind: String },
}

fn main() {
    let input = r#"---
 person:
   name: Alice
   age: 30
---
 pet:
  kind: cat
---
 person:
   name: Bob
   age: 25
"#;
    let docs: Vec<Document> =
        serde_saphyr::from_multiple(input).expect("valid YAML stream");
}

To choose a different collection, use serde_saphyr::from_str_multiple. It supports any collection implementing Default + Extend<T>, such as Vec<T>, VecDeque<T>, BTreeSet<T>, or custom storage like SmallVec<T>. Documents are added in input order, but sets may change the order or discard duplicates. Explicit type arguments specify both the document and collection types. Specifying the document type also resolves ambiguity when the collection implements Extend for multiple item types:

use std::collections::BTreeSet;

let input = String::from("pear\n---\napple\n---\npear\n");
let names = serde_saphyr::from_str_multiple::<&str, BTreeSet<_>>(&input).unwrap();
assert_eq!(names, BTreeSet::from(["apple", "pear"]));

The same collection support is available for from_bytes_multiple and both _with_options variants.

Nested enums

Externally tagged enums nest naturally in YAML as maps keyed by the variant name. This enables strict, expressive models (enums with associated data) instead of generic maps.

use serde::Deserialize;

#[derive(Deserialize)]
struct Move {
  by: f32,
  constraints: Vec<Constraint>,
}

#[derive(Deserialize)]
enum Constraint {
  StayWithin { x: f32, y: f32, r: f32 },
  MaxSpeed { v: f32 },
}

fn main() {
let yaml = r#"
- by: 10.0
  constraints:
    - StayWithin:
        x: 0.0
        y: 0.0
        r: 5.0
    - StayWithin:
        x: 4.0
        y: 0.0
        r: 5.0
    - MaxSpeed:
        v: 3.5
      "#;

  let robot_moves: Vec<Move> = serde_saphyr::from_str(yaml).unwrap();
  println!("Parsed {} moves", robot_moves.len());
  }

There are two variants of the deserialization functions: from_* and from_*_with_options. The latter accepts an Options object that allows you to configure budget and other aspects of parsing. For larger projects that require consistent parsing behavior, we recommend defining a wrapper function so that all option and budget settings are managed in one place (see examples/wrapper_function.rs).

Tuple enum variants

It is possible to deserialize tuple enum variants:

use serde::Deserialize;

#[derive(Debug, PartialEq, Eq, Deserialize)]
pub enum Value {
  Expression(String),
  Pair(String, i32),
}

#[derive(Debug, PartialEq, Eq, Deserialize)]
pub struct Context {
    value: Value,
}

serde_saphyr::from_str::<Context>(yaml) would take the value: !Expression 1 + 1 or value: !Pair [a, 12]. Both YAML lists and Rust tuples allow their elements to have different types.

To verify support for polymorphism of arbitrary objects, not just enums, serde-saphyr is also tested with typetag.

Composite keys

YAML supports complex (non-string) mapping keys. Rust maps can mirror this, allowing you to parse such structures directly.

use serde::{Deserialize};
use std::collections::HashMap;

#[derive(Debug, PartialEq, Eq, Hash, Deserialize)]
struct Point {
  x: i32,
  y: i32
}

#[derive(Debug, PartialEq, Deserialize)]
struct Transform {
    // Transform between locations
    map: HashMap<Point, Point>,
}

fn main() {
    let yaml = r#"
    map:
      {x: 1, y: 2}: {x: 3, y: 4}
      {x: 5, y: 6}: {x: 7, y: 8}
    "#;
    let transform: Transform = serde_saphyr::from_str(yaml).unwrap();
    println!("{} entries", transform.map.len());
}

Binary scalars

!!binary-tagged YAML values are base64-decoded when deserializing into Vec<u8> or String (reporting an error if they are not valid UTF-8).

use serde::Deserialize;

#[derive(Debug, Deserialize, PartialEq)]
struct Blob {
    data: Vec<u8>,
}

fn main() {
    let blob: Blob = serde_saphyr::from_str("data: !!binary aGVsbG8=").unwrap();
    assert_eq!(blob.data, b"hello");
}

Important: some projects add the !!binary tag while actually expecting a verbatim string value (for example, the literal string "aGVsbG8="). This works with parsers that simply ignore the tag. However, serde-saphyr decodes !!binary values by default, attempting to interpret them as UTF-8 bytes.

If you use !!binary only as a documentation or annotation tag, enable ignore_binary_tag_for_string = true in Options.

use serde::Deserialize;

#[derive(Deserialize)]
struct ContainsString {
    name: String,
}

fn main() -> Result<(), serde_saphyr::Error> {
    let value: ContainsString = serde_saphyr::from_str_with_options(
        "name: !!binary H4sIAA==",
        serde_saphyr::options! {
            ignore_binary_tag_for_string: true
        },
    )?;
    assert_eq!(value.name, "H4sIAA==");
    Ok(())
}

!!binary for other types like Vec<u8> will stay supported.

Deserializing into abstract JSON Value

If you must work with abstract types, you can also deserialize YAML into serde_json::Value. Serde will drive the process through deserialize_any because Value does not fix a Rust primitive type ahead of time. You lose the strict type control provided by Rust struct data types. Also, unlike YAML, JSON does not allow composite keys; keys must be strings. Mapping entries are presented to Serde in source order. Whether the target retains that order depends on its implementation.

Set Options::local_tags_as_maps to true to read a node with a local tag as a single-entry map. The resolved tag name without the leading ! is the key. The tagged scalar, sequence, or mapping is the value. Tag validation and include resolution happen before the value reaches the visitor.

By default, deserialize_any rejects .nan, .inf, and -.inf with an error and source location. Set Options::non_finite_float_policy to choose how these values are delivered:

Policy Behavior
Reject Rejects non-finite floats; this is the default behavior.
AsString Passes canonical strings (".nan", ".inf", "-.inf") to the visitor.
PassThrough Passes actual non-finite floats to the visitor. JSON's Value visitor converts them to Null without an error.

For example, to preserve non-finite values as strings in JSON:

use serde_saphyr::{NonFiniteFloatPolicy, from_str_with_options, options};

let options = options! {
    non_finite_float_policy: NonFiniteFloatPolicy::AsString,
};
let value: serde_json::Value = from_str_with_options("value: .NaN", options).unwrap();
assert_eq!(value["value"], ".nan");

Overflowing literals such as 1e999 follow the same policy: Reject returns an error, AsString produces ".inf", and PassThrough sends infinity to the visitor. Untagged quoted scalars and !!str scalars remain strings. Direct f32/f64 targets are unaffected: they accept YAML non-finite spellings and reject overflowing decimal literals.

The YAML 1.2 Core schema allows a sign on .inf only, so plain +.nan and -.nan infer as strings under every policy. These spellings also remain valid unquoted string values and mapping keys with no_schema: true. Direct f32/f64 targets and explicit !!float tags still read them as NaN. Explicit !!float scalars preserve the supplied NaN sign when deserialized as floats; direct untagged float targets keep their existing behavior.

Borrowed string deserialization

serde-saphyr supports zero-copy deserialization for string fields when using from_str, from_slice, from_multiple, or from_slice_multiple (including their _with_options variants). This allows deserializing into &str fields that borrow directly from the input, avoiding allocation overhead. For multiple documents, use from_multiple for strings or from_slice_multiple for UTF-8 byte slices to collect into a Vec<T>. The from_str_multiple and from_bytes_multiple families support borrowing into any collection implementing Default + Extend<T>. All of these functions also support owned values.

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Data<'a> {
    name: &'a str,
    value: i32,
}

let yaml = "name: hello\nvalue: 42\n";
let data: Data = serde_saphyr::from_str(yaml).unwrap();
assert_eq!(data.name, "hello");

UTF-16

Reader-based entry points (from_reader, from_reader_with_options, read, and read_with_options) accept BOM-marked UTF-8, UTF-16LE, and UTF-16BE. If no recognized BOM is present, reader input is treated as UTF-8. String- and slice-based entry points take UTF-8 only.

YAML composition, comments, and external values

Anchors

Anchor defines the value that can be referenced elsewhere. A value, referenced by the anchor, can also be used as a key:

  aaa: &anchor zzz
  *anchor : *anchor

It produces {"aaa": "zzz", "zzz": "zzz"}. Mind space before semicolon (':') is required, as semicolon is a otherwise a valid part of the key.

Merge keys

serde-saphyr supports merge keys, which reduce redundancy and verbosity by specifying shared key-value pairs once and then reusing them across multiple mappings. Here is an example with merge keys (inherited properties):

use serde::Deserialize;

/// Configuration to parse into. Does not include "defaults"
#[derive(Debug, Deserialize, PartialEq)]
struct Config {
    development: Connection,
    production: Connection,
}

#[derive(Debug, Deserialize, PartialEq)]
struct Connection {
    adapter: String,
    host: String,
    database: String,
}

fn main() {
    let yaml_input = r#"
defaults: &defaults # Here we define "default configuration"
  adapter: postgres
  host: localhost

development:
  <<: *defaults
  database: dev_db

production:
  <<: *defaults
  database: prod_db
"#;

    // Deserialize YAML with anchors, aliases and merge keys into the Config struct
    let parsed: Config = serde_saphyr::from_str(yaml_input).expect("Failed to deserialize YAML");

    // Define expected Config structure explicitly
    let expected = Config {
        development: Connection {
            adapter: "postgres".into(),
            host: "localhost".into(),
            database: "dev_db".into(),
        },
        production: Connection {
            adapter: "postgres".into(),
            host: "localhost".into(),
            database: "prod_db".into(),
        },
    };

    // Assert parsed config matches expected
    assert_eq!(parsed, expected);
}

Merge keys are standard in YAML 1.1. Although YAML 1.2 no longer includes merge keys in its specification, it doesn't explicitly disallow them either, and many parsers implement this feature.

Merge-key handling is configurable with the merge_keys option. The default MergeKeyPolicy::Merge expands both implicitly resolved << entries and explicit YAML 1.1 !!merge << entries. The verbatim !<tag:yaml.org,2002:merge> form and equivalent %TAG handles are also recognized. Use MergeKeyPolicy::AsOrdinary to accept these as regular mapping keys, or MergeKeyPolicy::Error to reject them.

The YAML 1.1 !!value tag is recognized but intentionally has no special default-value behavior. Its scalar content is deserialized normally, and a tagged = key in an ordinary map remains an ordinary "=" key. With reject_unsupported_tags: true, this tag is accepted only on that exact scalar mapping key. The same strict-mode context check limits !!merge to a scalar << mapping key.

Tags

serde-saphyr can capture tags. Applications can use custom tags to express units, priorities, accessibility and the like.

Options::reject_tagged_field_names defaults to true: struct mappings entered through Serde's deserialize_struct reject explicit tags on field names, except standard !!str and non-specific ! tags. For example, !secret password: token is rejected; put the value tag after the colon (password: !secret token). Set the option to false to accept tagged field names. See the option documentation for coverage limits involving flattened structs and buffered enum content.

The Tagged<T> wrapper stores a value and the resolved YAML tag attached to its node. The tag is represented as an Option<String>. An empty string is not a valid tag value; use None instead.

With local_tags_as_maps enabled, reading !T 5 as Tagged<serde_json::Value> stores {"T": 5} in the value and Some("!T") in the metadata. Reading it as Tagged<u32> stores 5 and Some("!T") with either setting.

Tag handles are resolved while parsing. For example, !!str becomes tag:yaml.org,2002:str, while the local tag !nanoseconds remains !nanoseconds. Given:

%TAG !css! tag:app.styles,2026:
---
font: !css!important bold

When the font value is deserialized as Tagged<String>, the captured tag is Some("tag:app.styles,2026:important").

Serialization round-trips the resolved tag identity, but may normalize its source spelling. When constructing Tagged<T> directly, a tag beginning with ! is local; every other tag identity must have valid absolute URI syntax. Characters requiring URI escaping are percent-encoded on output.

When deserializing an enum directly, a local tag matching a variant name selects that variant before its payload is interpreted. This includes names such as !timestamp, !str, !int, !null, !seq, and !map. These are application tags, not standard YAML type annotations, and impose no built-in payload shape. For example, a variant renamed timestamp can be selected by !timestamp (unit) or !timestamp text (a string newtype). Unit variants require empty or null content. Tagged<T> serialization follows the same rule. Option<E> preserves the same selector and payload: !timestamp becomes Some(E::Timestamp), and !maybe null becomes Some(E::Maybe(None)) when Maybe has an optional payload. Untagged plain nulls and !!null scalars with a null spelling represent None. Unknown selectors and invalid payloads produce the same errors as they do without the outer Option.

Multi-document APIs retain application-tagged documents and pass them to the target deserializer; only untagged and standard-tagged null documents are skipped.

Matching uses the resolved tag identity: !<!timestamp> is equivalent to the default !timestamp, whereas !!timestamp is the global YAML timestamp tag. %TAG directives can change that identity. Only resolved standard tags, such as !!str and !!int, apply the corresponding YAML type semantics. Local !str, !int, !bool, !float, !null, !seq, !map, !timestamp, and !binary are ordinary application tags; outside a matching enum context they follow the unsupported-tag policy below.

A matching local tag on a unit enum variant is emitted without a payload: Tagged(E::Timestamp, Some("!timestamp".into())) writes !timestamp, not !timestamp null. The same form round-trips through Option<E>, nested options, and tagged wrappers. Reading still accepts an omitted payload or an explicit plain null or ~ for unit variants; non-null payloads are rejected. Variants with fields keep their payloads: for example, a tagged E::Maybe(None) writes !maybe null, while empty tuple and struct payloads retain [] and {}. Ordinary untagged enum serialization is unchanged.

The standalone ! is a separate non-specific tag, not an enum selector. It resolves scalars as strings and collections as ordinary sequences or mappings, without changing how their children resolve. For example, ! [12, ! 12] contains a number and a string. This behavior is unchanged by %TAG directives; bare !! is not another spelling of it.

See YAML changes in 3.0.0 for the complete migration guide.

Migration: replace former local type aliases with standard tags (!int becomes !!int, !binary becomes !!binary, and so on); quote strings or use !!str. Tags such as !<tag:yaml.org,2002:!str> are also distinct from standard type tags. Intentional application extensions (!time, !degrees, !radians, and !include) retain their existing meanings. Matching local robotics tags can still select typed enum variants.

An explicit application tag denotes a present value, including inside NullableTilde<T> and Tagged<Option<T>>. Attaching !foo to None still emits !foo null, but that node no longer deserializes as absence: its payload must be accepted by the inner type. With default options, Tagged<Option<String>> rejects its null payload; Tagged<Option<()>> reads it as Some(()). Use an untagged or standard-tagged null for absence, or an enum variant with an optional payload for a present tagged value whose payload is absent.

Serde's generic buffering, including untagged enums, does not provide a variant list for that precedence rule. Include expansion and strict tag eligibility still apply.

By default, unknown application-specific YAML tags remain available for tagged-enum handling and are otherwise ignored where possible. Set reject_unsupported_tags: true in Options to reject any explicit tag that serde-saphyr does not recognize. This strict mode also rejects custom tags used to select enum variants. YAML 1.1 !!merge and !!value tags remain accepted only on their exact scalar mapping keys, << and = respectively; using either tag on a value, a collection, or any other scalar is rejected in strict mode. Standard scalar, sequence, and mapping tags are accepted only on matching node kinds, even when reject_unsupported_tags is false. Local robotics tag shape checks are deferred until a non-enum consumer is known. Robotics-only !degrees, !radians, and !time tags require the robotics crate feature and angle_conversions: true to convert their payloads to floats. With local_tags_as_maps: true, an untyped visitor reads the local tag as a map key.

Likewise, in strict mode, !include is accepted only when the include crate feature is enabled and an include resolver is configured. Tag capture does not bypass normal YAML tag semantics or the reject_unsupported_tags option.

Tagged enums written as !!EnumName VARIANT are also supported, but only for single-level scalar variants. Use mapping-based representations (EnumName: RED) if you need to embed enums within other enums.

Comments

Comment support requires the default-enabled comments feature. With default-features = false, enable it explicitly when using Commented<T>, CommentPosition, Options::emit_comments, SerializerOptions::comment_position, Budget::{max_total_comment_bytes, max_buffered_comment_events}, BudgetReport::total_comment_bytes, or BudgetBreach::CommentBytes. These APIs are absent without the feature, so using them produces a compile error. Ordinary YAML parsing continues to accept and validate comments.

  • As granit-parser now supports comments, the wrapper Commented will also capture the relevant YAML comment into its field when deserializing YAML.

  • Comment capture is enabled by default. Set emit_comments: false in Options to recognize and validate YAML comments without retaining their text or emitting parser comment events. In this mode, deserialized Commented<T> values have an empty comment string. Comment bytes are still consumed and validated, so this is not an input-size or processing-time limit.

    Budget enforcement and reporting then treat comments as unretained data:

    • Budget::max_total_comment_bytes is not enforced;
    • Budget::max_buffered_comment_events has no effect;
    • comments do not count toward Budget::max_events or BudgetReport::events; and
    • BudgetReport::total_comment_bytes remains 0.
  • During serialization, Commented also emits a comment next to a scalar or reference (handy when the reference is far from its definition and needs explanation).

  • For container values, a comment attached to the parent value itself, such as root: # comment, is captured only by Commented<Container> and is not inherited by the first child. A comment inside the container, directly above a child key or sequence item, is captured by that child.

  • Comments are not copied from anchor definitions through aliases or merge keys. In actual: { <<: *defaults }, a Commented field materialized from &defaults will not receive a comment that was written at the definition site above defaults.port; that comment belongs to the original field.

  • For aliases to containers used as nested values, leading comments above the alias follow the same rule as comments inside a direct nested container. In root:\n # comment\n *defaults, the comment remains available to the expanded container's first child rather than being captured as a comment on the alias use itself.

  • See example commented.rs.

Properties

Many configuration formats contain secret values that should not live in checked-in YAML or leak into error snippets. The optional properties feature adds docker-compose-style ${NAME} interpolation for that use case, with values supplied through Options. It is also useful for generated values or values that change between releases or deployments.

By default, interpolation is intentionally narrow:

  • it only applies to plain scalars; quoted and block scalars stay literal,
  • the supported forms are listed in the table below,
  • the unbraced $NAME form is opt-in (see below) so a bare $NAME stays a literal by default,
  • $${NAME} escapes to a literal ${NAME},
  • selected default/replacement/error text supports nested braced references, subject to the configured budget,
  • if no property map is configured, every ${...} form remains unchanged.
Form NAME unset NAME set to empty NAME set to non-empty
${NAME} error "" the value
${NAME-default} default "" the value
${NAME:-default} default default the value
${NAME+replacement} "" replacement replacement
${NAME:+replacement} "" "" replacement
${NAME?error} error (with error as hint) "" the value
${NAME:?error} error (with error as hint) error (with error as hint) the value

default, replacement, and error are source text from the YAML and are not treated as secret. Selected operator text can contain nested braced references, for example ${PRIMARY:-${FALLBACK:-default}}. The error hint may be empty (${NAME?} / ${NAME:?}), matching docker-compose. If expanding an error hint would include a non-empty property-map value, the reported hint keeps its original source text instead. For example, ${MISSING:?configure ${SECRET}} reports configure ${SECRET} without exposing the value of SECRET.

properties is gated behind the properties feature flag. Once enabled, pass a property map through Options::with_properties(...):

use serde::Deserialize;

#[cfg(feature = "properties")]
#[derive(Debug, PartialEq, Eq, Deserialize)]
struct Config {
    database_url: String,
    mode: String,
}

#[cfg(feature = "properties")]
fn property_map() -> Result<Config, serde_saphyr::Error> {
    use serde_saphyr::{options, from_str_with_options};
    use std::collections::HashMap;
    let mut properties = HashMap::new();
    properties.insert(
        "DATABASE_URL".to_string(),
        "postgres://db.example/app".to_string(),
    );
    properties.insert("MODE".to_string(), "production".to_string());

    let options = options! {
        budget: serde_saphyr::budget! {
            max_property_expansion_depth: 16,
            max_total_property_interpolation_work: 1_048_576,
        },
    }
    .with_properties(properties);

    let yaml = r#"
        database_url: ${DATABASE_URL}
        mode: ${MODE}
"#;

    let parsed: Config = from_str_with_options(yaml, options)?;
    Ok(parsed)
}

#[cfg(feature = "properties")]
fn main() {
    let parsed = property_map().unwrap();
    assert_eq!(
        parsed,
        Config {
            database_url: "postgres://db.example/app".to_string(),
            mode: "production".to_string(),
        }
    );
}
# #[cfg(not(feature = "properties"))]
# fn main() {}

Property expansion limits are configured through Budget. Exceeding either limit returns Error::Budget with a BudgetBreach::PropertyExpansionDepth or BudgetBreach::PropertyInterpolationWork value. Setting Options::budget to None disables these limits together with the rest of budget enforcement.

Set property_syntax: PropertySyntax::BracedOrBare to also accept the unbraced $NAME shorthand. It uses the same Required semantics as ${NAME}, including "$$NAME" being a literal "$NAME". Name boundaries are greedy. $NAMEfoo looks up NAMEfoo, so write ${NAME}foo instead when you need to concatenate. Unset names produce an error. Modifiers stay brace-only:

use serde::Deserialize;

#[derive(Debug, Deserialize, PartialEq)]
struct Config {
    db: String,
}

#[cfg(feature = "properties")]
fn main() -> Result<(), serde_saphyr::Error> {
    use serde_saphyr::{PropertySyntax, options, from_str_with_options};
    use std::collections::HashMap;

    let mut properties = HashMap::from([
        ("DATABASE_URL".to_string(), "postgres://db.example/app".to_string()),
    ]);
    let opts = options! { property_syntax: PropertySyntax::BracedOrBare }
        .with_properties(properties);

    let parsed: Config = from_str_with_options("db: $DATABASE_URL\n", opts)?;
    let expected = Config { db: "postgres://db.example/app".to_string() };
    assert_eq!(expected, parsed);
    Ok(())
}
# #[cfg(not(feature = "properties"))]
# fn main() {}

In the Braced and BracedOrBare modes, a bare ${NAME} with no value in the map (and no -/:- default), a ${NAME?msg} / ${NAME:?msg} that triggers its error condition, or a malformed ${...} candidate (invalid name, unsupported modifier), fails deserialization with a dedicated error pointing at the YAML source location. Configuration mistakes fail closed rather than silently producing partial values.

Select PropertySyntax::DockerCompose for Docker Compose interpolation semantics:

  • Both $NAME and ${NAME} expand in plain, single-quoted, double-quoted, and block string values. Mapping keys and !!binary scalars are not interpolated.
  • Unset direct references silently produce an empty string, not an error. The default, alternative, and required operators use the conditions in the table above.
  • Selected default, replacement, and error text recursively expands both reference forms and $$ escapes. Property-map values are not expanded again.
  • Malformed or unclosed braced references fail. Each braced reference must fit on one line, and literal braces inside operator text follow Compose's delimiter matching.
  • Expanded strings remain strings when deserializing generic values, even when they contain null, true, or a number. Numeric and boolean targets can parse expansions from plain scalars. Quoted and block scalars, and scalars tagged with !!str or standalone !, are rejected for these targets.

Select PropertySyntax::DockerComposeWithNulls for the same interpolation when an expansion should be able to produce YAML null, as configuration loaders that previously expanded environment variables in a Value tree often expect:

  • A value consisting solely of $NAME or ${NAME} is null when NAME is unset, so it deserializes into None for an Option field.
  • A value whose expansion is exactly null, Null, NULL, or ~ is null.
  • An explicitly empty property is still an empty string (Some("") for Option<String>), and so is an empty selected default such as ${A:-${B}} with both unset. Surrounding text is kept: prefix-$MISSING is prefix-.
  • These rules apply to the scalar's text whatever its style, so "$NAME" is null as well, while a | block keeps its trailing newline and is not a sole reference. !!str and ! keep the value a string, and scalars without an expansion resolve as usual.
  • A value that becomes null behaves exactly like a literal null; numbers and booleans convert as in DockerCompose.

When the property values are secrets, interpolation resolves the final value before Serde finishes deserializing the surrounding type, so a downstream custom deserializer or validation path could otherwise echo the resolved secret. serde-saphyr tracks interpolated values and redacts them back to their ${...} form in later error messages. Treat the property map itself as sensitive - do not log or format it directly.

If you write a loaded data structure with resolved properties, the resolved values will obviously appear in the output. If this is unwanted, do not write the structure that has been loaded with property resolver.

Includes

The need for including YAML (not part of the official specs) can be seen from the popularity of the command-line yaml-include crate. That crate is very feature-complete. However, if the YAML parser and validator are separate from the pre-processor, they usually only report the line number and snippet in the processed document. For large documents with multiple and deep includes, this becomes challenging to interpret. YAML indentation and security requirements like path confinement or anchor isolation make "quick adding" of includes non-trivial.

serde-saphyr allows resolving !include tags via a custom resolver configured in Options. When using a single !include directly as a value, it works naturally for replacing a scalar, sequence, or an entire mapping:

# Replacing the entire mapping value
my_mapping: !include my_mapping.yaml

# Supplying a list/sequence value
my_list: !include my_list.yaml

However, if you want to include a mapping and merge its keys into a parent mapping alongside other keys, you must use the merge key (<<). Attempting to list !include inside a mapping without a merge key is invalid YAML syntax:

# INVALID: `!include` is treated as a key missing a value (`:`)
a: 1
!include my_mapping.yaml
b: 2

Instead, use the merge key to correctly inject the included mapping:

# VALID: merges the contents of my_mapping.yaml
a: 1
<<: !include my_mapping.yaml
b: 2

!include is gated behind the include feature flag. If it is not enabled, or the resolver is not set, this tag has no special treatment; with reject_unsupported_tags: true, it is rejected as unsupported. The include feature allows resolvers that do not access the filesystem. For the most common case, where files are included from the filesystem, include_fs must be enabled as well. Then the most common way to enable includes looks like this:

use serde::Deserialize;
use serde_saphyr::{from_str_with_options, options};

#[derive(Debug, Deserialize)]
struct Config {
    selected_users: Vec<User>,
}

#[derive(Debug, Deserialize)]
struct User {
    name: String,
}

# #[cfg(feature = "include_fs")]
fn main() {
    let yaml = "selected_users: !include#users value.yaml\n";
    let options = options! {}
        .with_filesystem_root("examples")
        .expect("failed to create filesystem include resolver");

    let config: Config = from_str_with_options(yaml, options)
        .expect("failed to parse filesystem include example");
    assert_eq!(config.selected_users[0].name, "Alice");
}
# #[cfg(not(feature = "include_fs"))]
# fn main() {}

You can alternatively use SafeFileResolver to configure more options, or provide your own IncludeResolver callback that resolves a name into YAML text, which can be useful for custom storage backends or generated YAML without using the filesystem.

Instead of including the whole document, you can also include only the value of a specific anchor defined in the included YAML document:

  !include my_mapping.yaml#anchor_name

SafeFileResolver has a built-in capability for anchor extraction. For flexibility, custom IncludeResolver implementations must do this on their own, splitting anchor from the reference and then returning InputSource::AnchoredText.

Unless otherwise stated, the anchor scope is restricted to the document where it is defined. Overriding a parent anchor value somewhere deep inside included content would be challenging to debug and could even become a security issue.

Whole-document includes only support sources that contain a single YAML document. Fragment includes also require the included source to contain a single YAML document; multi-document sources are rejected instead of scanning across document boundaries. Recursive inclusion is not permitted (and the file, not the fragment, is the include's identity).

Validation and diagnostics

Snippets

To make debugging easier, serde-saphyr renders snippets of the YAML that caused an error (similar to how many compilers report errors). These snippets include the line where the error occurred along with some surrounding context. Any terminal control sequences that might be present in the YAML are stripped out. If not desired, snippets can be removed for a specific error using without_snippet, or disabled entirely via the Options configuration.

Garde and Validator integration

This crate optionally integrates with validator or garde to run declarative validation. serde-saphyr error will print the snippet, providing location information. If the invalid value comes from the YAML anchor, serde-saphyr will also tell where this anchor has been defined.

Garde

# #[cfg(feature = "garde")]
use garde::Validate;
# #[cfg(feature = "garde")]
use serde::Deserialize;

# #[cfg(feature = "garde")]
#[derive(Debug, Deserialize, Validate)]
#[serde(rename_all = "camelCase")] // Rust in snake_case, YAML in camelCase.
struct AB {
    // Just defined here (we validate `second_string` only).
    #[garde(skip)]
    first_string: String,

    #[garde(length(min = 2))]
    second_string: String,
}

# #[cfg(feature = "garde")]
fn main() {
    let yaml = r#"
        firstString: &A "x"
        secondString: *A
   "#;

    let err = serde_saphyr::from_str_valid::<AB>(yaml)
        .expect_err("must fail validation");

    // Field in error message in camelCase (as in YAML).
    eprintln!("{err}");
}
# #[cfg(not(feature = "garde"))]
# fn main() {}

Validator

# #[cfg(feature = "validator")]
use serde::Deserialize;
# #[cfg(feature = "validator")]
use validator::Validate;

# #[cfg(feature = "validator")]
#[derive(Debug, Deserialize, Validate)]
#[serde(rename_all = "camelCase")] // Rust in snake_case, YAML in camelCase.
struct AB {
    // Just defined here (we validate `second_string` only).
    #[allow(dead_code)]
    first_string: String,

    #[validate(length(min = 2))]
    second_string: String,
}

# #[cfg(feature = "validator")]
fn main() {
    let yaml = r#"
        firstString: &A "x"
        secondString: *A
   "#;

    let err = serde_saphyr::from_str_validate::<AB>(yaml)
        .expect_err("must fail validation");

    eprintln!("{err}");
}
# #[cfg(not(feature = "validator"))]
# fn main() {}

serde-saphyr marks the anchor definition and alias use in the same excerpt.

error: line 3 column 23: invalid here, validation error: length (min=2, value="x") for `secondString`
 --> <input>:3:23
  |
1 |
2 |         firstString: &A "x"
  |                         ^ defined here
3 |         secondString: *A
  |                       ^ the value is used here
4 |
  |

The integration of garde is feature-gated and disabled by default. Use serde-saphyr = { version = "=3.0.0-rc.1", features = ["garde"] } (or features = ["validator"]) in Cargo.toml to enable it.

If you prefer to validate without validation crates, use the Spanned<T> wrapper to retain YAML locations for manual checks. Location information can be lost when Serde buffers values, as described in the limitations below.

Custom messages

The default error messages are developer-oriented. They may mention serde-saphyr APIs and options and include “action items” intended to help fix the problem.

If error messages are shown to end users, switch to the built-in user-facing formatter or provide your own formatter (for example, to translate messages into another language).

See:

  • MessageFormatter — controls the main message text for each Error.
  • Localizer — controls message pieces that are composed outside MessageFormatter::format_message (location suffixes, validation/snippet labels, etc.).

Use the built-in user-facing formatter

use serde_saphyr::UserMessageFormatter;

# let err = serde_saphyr::from_str::<String>("").unwrap_err();
println!("\n[User Error]:\n{}", err.render_with_formatter(&UserMessageFormatter));

To append a diagnostic to an existing std::fmt::Write, use err.render_to(&mut writer, render_options). It accepts the same RenderOptions as render_with_options, including the formatter, snippet mode, source name, and line offset. It avoids an intermediate string for the complete output.

Use a custom formatter with miette

If you want fancy diagnostics via miette, you can convert a serde-saphyr error to a miette::Report while still controlling the message text via a custom formatter:

use serde_saphyr::{MessageFormatter, UserMessageFormatter};

# #[cfg(feature = "miette")]
fn main() {
    let yaml = "not_a_bool\n";
    let opts = serde_saphyr::options! { with_snippet: false };
    let err = serde_saphyr::from_str_with_options::<bool>(yaml, opts)
        .expect_err("bool parse error expected");

    // You can plug in `&UserMessageFormatter` or your own `&dyn MessageFormatter`.
    let formatter: &dyn MessageFormatter = &UserMessageFormatter;

    let report = serde_saphyr::miette::to_miette_report_with_formatter(
        &err,
        yaml,
        "config.yaml",
        formatter,
    );

    eprintln!("{report:?}");
}
# #[cfg(not(feature = "miette"))]
# fn main() {}

This requires enabling the crate’s miette feature.

For a complete custom formatter/localizer example, see examples/pirate_formatter.rs. For an end-to-end miette example, see examples/miette.rs.

Figment

Both figment and figment2 are supported as optional features (see examples/figment_yaml).

Serialization and round-tripping

Serialization

use serde::Serialize;

#[derive(Serialize)]
struct User { name: String, active: bool }

let yaml = serde_saphyr::to_string(&User { name: "Ada".into(), active: true }).unwrap();
assert!(yaml.contains("name: Ada"));

Anchors (Rc/Arc/Weak)

Serde-saphyr can conceptually connect YAML anchors with Rust shared references (Rc, Weak and Arc). You need to use wrappers to activate this feature:

use serde::{Deserialize, Serialize};
use serde_saphyr::RcAnchor;
use std::rc::Rc;

#[derive(Debug, Deserialize, Serialize)]
struct Node {
    name: String,
}

#[derive(Debug, Deserialize, Serialize)]
struct Document {
    primary: RcAnchor<Node>,
    alias: RcAnchor<Node>,
}

fn main() {
    let shared = Rc::new(Node {
        name: "shared node".to_string(),
    });
    let document = Document {
        primary: RcAnchor::from(shared.clone()),
        alias: RcAnchor::from(shared),
    };

    let yaml = serde_saphyr::to_string(&document).expect("serialize anchors");
    assert!(yaml.contains("&a1"));
    assert!(yaml.contains("*a1"));

    let deserialized: Document =
        serde_saphyr::from_str(&yaml).expect("deserialize anchors");
    assert!(Rc::ptr_eq(
        &deserialized.primary.0,
        &deserialized.alias.0,
    ));
}

When anchors are highly repetitive and also large, packing them into references can make YAML more human-readable.

To support round-tripping, the library can also deserialize into these anchor structures; this deserialization is identity-preserving. A field or structure that is defined once and subsequently referenced will exist as a single instance in memory, with all anchor fields pointing to it. This is crucial when the topology of references itself constitutes important information to be transferred.

Recursive YAML

While recursive YAML is unusual, it is not forbidden by the specification. Real-world examples and requests to implement it exist.

Serde-saphyr supports recursive structures, but Rust requires being very explicit about this. A structure that may hold recursive references to itself must be wrapped in a RcRecursive<T>, and any reference that points to it must be RcRecursion<T>. Arc varieties exist. See also examples/recursive_yaml.rs.

Controlling serialization

  • Empty maps are serialized as {} and empty lists as [] by default.
  • Strings containing newlines and very long strings are serialized as appropriate block scalars, except when they contain characters that require escaping (such as carriage returns).
  • Indentation is configurable.
  • The wrapper SpaceAfter adds an empty line after the wrapped value, useful for visually separating sections in the output YAML.
  • It is possible to request that all strings be quoted — using single quotes when no escape sequences are present, and double quotes otherwise. This is very explicit and unambiguous, but such YAML may be less readable for humans. Line wrapping is disabled in this mode.
  • YAML 1.1 booleans (y, yes, on, etc.) are normally quoted as both keys and values. If this is undesired (y is a coordinate), set yaml_12 to true.
  • Set no_lang_directive to omit the %YAML 1.2 directive.

These settings can be changed in SerializerOptions.

Feature-gated domain extensions

Robotics

The feature-gated "robotics" capability enables parsing of YAML extensions commonly used in robotics (ROS). These extensions support conversion functions (deg, rad) and simple mathematical expressions such as deg(180), rad(pi), 1 + 2*(3 - 4/5), or rad(pi/2). This capability is gated behind the robotics feature and is not enabled by default. Additionally, angle_conversions must be set to true in the Options. Just adding the robotics feature is not enough to activate this mode of parsing. This parser is still just a simple expression calculator implemented directly in Rust, not some hook into a language interpreter.

rad_tag: !radians 0.15 # value in radians, stays in radians
deg_tag: !degrees 180 # value in degrees, converts to radians
expr_complex: 1 + 2*(3 - 4/5) # simple expressions supported
func_deg: deg(180) # value in degrees, converts to radians
func_rad: rad(pi) # value in radians (stays in radians)
hh_mm_secs: -0:30:30.5 # Time
duration: !time 1:02:03 # duration in seconds: 3723.0
longitude: !radians 8:32:53.2 # Nautical, ETH Zürich Main Building (8°32′53.2″ E)
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct RoboFloats {
    func_deg: f64,
    func_rad: f64,
}

# #[cfg(feature = "robotics")]
fn main() {
    let yaml = "func_deg: deg(180)\nfunc_rad: rad(pi)\n";
    let options = serde_saphyr::options! {
        angle_conversions: true,
    };

    let v: RoboFloats = serde_saphyr::from_str_with_options(yaml, options)
        .expect("parse robotics YAML");
    assert!((v.func_deg - std::f64::consts::PI).abs() < 1e-12);
    assert!((v.func_rad - std::f64::consts::PI).abs() < 1e-12);
}
# #[cfg(not(feature = "robotics"))]
# fn main() {}

The !time tag denotes a duration in seconds, including hh:mm[:ss] notation. It is distinct from the standard YAML !!timestamp tag, which denotes a date or point in time and is not accepted as a floating-point value. Explicit robotics tags apply the same conversions in typed reads, untyped reads, skipped fields, and #[serde(flatten)] fields.

Safety hardening measures with this feature enabled include limits on maximal expression depth, maximal number of digits, strict underscore placement, and fraction parsing limits to the precision-relevant digit.

Limitations

Unsupported features

  • Common Serde renames made to follow naming conventions (case changes, snake_case, kebab-case, r# stripping) are supported in snippets, as long as they do not introduce ambiguity. Arbitrary renames, flattening, aliases and other complex manipulations possible with serde are not. Parsing and validation will still work, but error messages for arbitrarily renamed fields will only show the Rust path.
  • Spanned<T> deserializes successfully within variants of untagged or internally tagged enums, but Serde buffers the values without preserving YAML location of the possible error. Values passing through #[serde(flatten)] buffering can also lose their locations. Wrap the entire enum in Spanned<T> to retain the enum's location, or use externally tagged enums (the default).
  • Anchors are not fully compatible with #[serde(flatten)] directive (this is Serde limitation we can't work around). Deserialization succeeds, but full strong-pointer identity may be lost for nested anchors inside flattened payloads.
  • Borrowing works for any scalar whose parsed value exists verbatim in the input. This includes plain scalars and simple quoted strings without escape sequences (e.g., "hello world" can be borrowed, but "hello\nworld" cannot because \n is transformed to a newline). To allow both borrowed and owned strings, use a Cow<'a, str> field annotated with #[serde(borrow)]. It borrows when the deserializer can provide borrowed data and otherwise owns the string, for example when transformation is required. Borrowing is explicit because it ties the result’s lifetime to the input. Without this annotation, Serde’s default deserialization of Cow produces Cow::Owned, even when the input could be borrowed.
  • Reader-based entry points (from_reader) require DeserializeOwned and cannot return borrowed values.
  • serde-saphyr does not capture freestanding comments, not obviously attached to any node (separated by multiple empty lines, or at the end of the document). Use granit-parser directly to capture such comments (serde-saphyr re-exports it).

Financial Support

Let's all donate strategically to David Tolnay. Without his serde, serde-saphyr would not make any sense. If all donations go to a single person, this is more likely to make a difference. We are not affiliated with him.

Ähnliche Projekte entdecken

Wird geladen…