Skip to main content

Options

Struct Options 

Source
#[non_exhaustive]
pub struct Options {
Show 22 fields pub budget: Option<Budget>, pub budget_report: Option<fn(&BudgetReport)>, pub budget_report_cb: Option<BudgetReportCallback>, pub emit_comments: bool, pub strict_indentation: bool, pub duplicate_keys: DuplicateKeyPolicy, pub merge_keys: MergeKeyPolicy, pub alias_limits: AliasLimits, pub legacy_octal_numbers: bool, pub leading_zero_numbers_as_strings: bool, pub underscored_numbers_as_strings: bool, pub strict_booleans: bool, pub ignore_binary_tag_for_string: bool, pub angle_conversions: bool, pub no_schema: bool, pub reject_unsupported_tags: bool, pub reject_tagged_field_names: bool, pub non_finite_float_policy: NonFiniteFloatPolicy, pub reject_non_finite_typeless_float: bool, pub with_snippet: bool, pub crop_radius: usize, pub require_indent: RequireIndent,
}
Expand description

Parser configuration options.

Use this to configure comment emission, duplicate-key policy, alias-replay limits, and an optional pre-parse YAML Budget.

Example: parse a small Config using custom Options.

use serde::Deserialize;

use serde_saphyr::options::DuplicateKeyPolicy;
use serde_saphyr::{from_str_with_options, Budget, Options};

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

let yaml = r#"
name: My Application
enabled: true
retries: 5
"#;

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

let cfg: Config = from_str_with_options(yaml, options).unwrap();
assert_eq!(cfg.name, "My Application");

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§budget: Option<Budget>

Optional YAML budget enforced during parsing and deserialization, including raw events, retained anchor copies, and property interpolation. None disables budget enforcement.

§budget_report: Option<fn(&BudgetReport)>

Optional callback invoked with the final budget report after parsing. It is invoked both when parsing is successful and when budget was breached.

§budget_report_cb: Option<BudgetReportCallback>

Invoked both when parsing is successful and when budget was breached.

§emit_comments: bool

Whether the parser emits comment events for deserialization.

The default is true. When this is false, comments are still recognized and validated as YAML syntax, but their text is not captured and crate::Commented values receive an empty comment string. Comment bytes are still consumed and validated, so disabling emission is not an input-size or processing-time limit.

Comment-related budget accounting follows emitted, retained parser data. Setting this to false also:

§strict_indentation: bool

Enforce YAML indentation rules for flow collections ([...] and {...}).

When enabled, flow entries, delimiters, and scalar continuation lines must be indented beyond the enclosing block collection. Applies to included YAML as well. Default: false (accept under-indented flow collections for compatibility).

Accepted with strict_indentation: true: entries and closing delimiters are indented beyond the enclosing block mapping.

sequence: [
  first,
  second
 ]
mapping: {
  first: one,
  second: two
 }

Accepted with strict_indentation: false, but rejected with true because the closing delimiters are at the same indentation as the enclosing block mapping:

sequence: [
  first,
  second
]
mapping: {
  first: one,
  second: two
}

Relaxed mode also accepts under-indented entries, not just closing delimiters. This is accepted with strict_indentation: false, but rejected with true at the unindented "value" entry:

key: [
"value",
]
§duplicate_keys: DuplicateKeyPolicy

Policy for duplicate keys.

§merge_keys: MergeKeyPolicy

Policy for YAML merge keys (<< and explicit !!merge <<).

MergeKeyPolicy::Merge expands merge keys and counts them against Budget::max_merge_keys. MergeKeyPolicy::AsOrdinary accepts << as a regular key. MergeKeyPolicy::Error rejects merge keys.

Default: MergeKeyPolicy::Merge.

§alias_limits: AliasLimits

Limits for alias replay to harden against alias bombs.

§legacy_octal_numbers: bool

Enable legacy octal parsing where values starting with 0 are treated as base-8. They are deprecated in YAML 1.2. Default: false.

§leading_zero_numbers_as_strings: bool

Preserve plain decimal integer spellings with redundant leading zeros as strings during implicit type inference (deserialize_any).

Examples include 0755, -007, and +00. Floating-point spellings such as 0.5, 00.5, and 01e2, and explicit radix prefixes, are unaffected. This supports compatibility with serde_yaml when reading untyped values. Default: false.

Applies to untyped values and Serde’s buffering for untagged enums and flattened fields. Takes precedence over Self::legacy_octal_numbers during inference. Direct typed deserialization, explicit !!int/!!float tags, and mapping-key equality retain their existing behavior.

§underscored_numbers_as_strings: bool

Preserve plain scalars containing underscores as strings during implicit type inference (deserialize_any), including numeric spellings such as 1_000, 0xFF_FF, and 0b10_01.

This supports compatibility with serde_yaml when reading untyped values. It also applies to untagged enums and flattened fields, and takes precedence over Self::legacy_octal_numbers during inference. Direct typed deserialization, explicit !!int/!!float tags, and mapping-key equality retain their existing behavior. Default: false.

§strict_booleans: bool

If true, accept only YAML 1.2 Core boolean spellings: true, True, TRUE, false, False, and FALSE. Other spellings, including YAML 1.1 forms such as yes/no/on/off, are rejected for boolean targets and are not inferred as booleans. Default: false (accept YAML 1.1 boolean forms).

§ignore_binary_tag_for_string: bool

When a field marked with the !!binary tag is deserialized into a String, serde-saphyr normally expects the value to be base64-encoded UTF-8. If you want to treat the value as a plain string and ignore the !!binary tag, set this to true (the default is false).

§angle_conversions: bool

Activates YAML conventions common in robotics community. 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). robotics feature must also be enabled. The !degrees, !radians, and !time tags select floating-point conversions. !time represents a duration in seconds; the standard !!timestamp tag does not.

§no_schema: bool

If true, values that can be parsed as booleans or numbers are rejected as unquoted strings. This flag is intended for teams that want to enforce compatibility with YAML parsers that infer types from unquoted values, requiring such strings to be explicitly quoted. The default is false (a number or boolean will be stored in the string field exactly as provided, without quoting).

§reject_unsupported_tags: bool

Reject explicitly specified YAML tags that serde-saphyr does not recognize.

This includes application-specific local and global tags. YAML 1.1 !!merge and !!value tags are accepted only on their exact scalar mapping keys, << and = respectively. Known scalar, sequence, and mapping tags are accepted only on matching node kinds; this node-kind requirement is enforced regardless of this option. Robotics-only !degrees, !radians, and !time tags are supported only when the robotics crate feature and Self::angle_conversions are both enabled. The !include tag is supported only when the include crate feature is enabled and an include resolver is configured.

Default: false (preserve unsupported tags for compatibility with tagged enums and otherwise ignore them where possible).

§reject_tagged_field_names: bool

Reject explicit tags on struct field names, except standard string tags.

A derived struct normally matches each mapping key by its text alone. A custom tag on that key can therefore be discarded without the struct ever seeing it. Such a tag has no effect on field selection and may be a value annotation accidentally placed on the field name. Enable this option to report crate::Error::TaggedStructFieldName instead of silently accepting it.

For example, an application can inspect a value’s !secret tag by reading that value as crate::Tagged<T>:

password: !secret API_TOKEN

This misplaced annotation is rejected when the option is enabled:

!secret password: API_TOKEN

Untagged and quoted field names remain accepted. Explicit standard string tags (!!str, including equivalent verbatim or directive-expanded forms) and the non-specific ! tag are also accepted. Field names are the external strings used by Serde: !!str 0.0: Alice can populate a Rust field marked #[serde(rename = "0.0")]. Here !!str explicitly gives 0.0 string semantics, and Serde’s rename handles the external field name. The exception uses the resolved tag identity; a local !str tag is still rejected, including when a directive rebinds !! to an application namespace.

This option applies only to struct mappings entered through Serde’s deserialize_struct, including externally tagged struct enum variants. It checks every key in such a mapping, including unknown keys that Serde would otherwise ignore without #[serde(deny_unknown_fields)]. It also checks field names replayed through aliases and expanded merges. Keys are checked before duplicate-key or merge precedence filtering, even when their values would otherwise be discarded. Ordinary map keys, including string, numeric, and enum keys, and tags on values retain their existing behavior. Unlike Self::reject_unsupported_tags, it does not reject application tags throughout the document. Tags consumed by enabled preprocessing, such as !include, retain that behavior before this check.

Serde can match fields without calling deserialize_struct: structs using #[serde(flatten)] enter through deserialize_map, while internally tagged and untagged enums buffer their fields first. Adjacently tagged enums also buffer content that precedes the discriminator. Fields handled by those paths, including structs nested in their buffers, are not covered by this option; it is not a document-wide guarantee against tagged field names.

Default: false (retain existing field-name handling).

§non_finite_float_policy: NonFiniteFloatPolicy

Handling of NaN, positive/negative infinity, and decimal literals that overflow f64 (e.g. 1e999) in deserialize_any.

If left at its default, this uses Self::reject_non_finite_typeless_float, preserving rejection by default and string conversion when that legacy flag is false. Explicit NonFiniteFloatPolicy::PassThrough, NonFiniteFloatPolicy::Reject, and NonFiniteFloatPolicy::AsString values override the legacy flag.

PassThrough lets float-capable visitors preserve non-finite values, including untagged enums and flattened float fields. serde_json::Value instead converts them to Null without an error. Reject prevents that loss; AsString passes canonical strings (.nan, .inf, -.inf) to the visitor.

Untagged quoted scalars and !!str scalars remain strings under every policy. Direct f32/f64 targets are unaffected: YAML non-finite spellings remain accepted, while overflowing decimal/exponential literals remain invalid.

§reject_non_finite_typeless_float: bool
👎Deprecated since 2.0.0:

use non_finite_float_policy instead

Legacy handling of non-finite floats in deserialize_any.

When Self::non_finite_float_policy is left at its default, true (the default) rejects non-finite floats and false converts them to canonical strings. An explicit policy overrides this flag.

Options::default() sets this to true. When deserializing options with serde_derived_types, an omitted flag defaults to false for compatibility with 1.3.0. If the policy is also omitted, non-finite values become strings.

Use Self::non_finite_float_policy with NonFiniteFloatPolicy::Reject instead of true, or NonFiniteFloatPolicy::AsString instead of false.

§with_snippet: bool

If true (default), public APIs that have access to the original YAML input will wrap returned errors with a snippet wrapper, enabling rustc-like snippet rendering when a location is available.

§crop_radius: usize

Horizontal crop radius (in character columns) when rendering snippet diagnostics.

The renderer crops all displayed lines (including the context lines) to the same column window around the reported error column, so they stay vertically aligned.

If set to 0, snippet wrapping is disabled (the original, unwrapped error is returned).

§require_indent: RequireIndent

Indentation requirement for the parsed document.

Implementations§

Source§

impl Options

Source

pub fn with_budget_report<F>(self, cb: F) -> Self
where F: FnMut(BudgetReport) + 'static,

Registers a budget-report callback. Any closure can be used, including ones that capture state from the surrounding scope.

The callback is invoked with the final crate::budget::BudgetReport after parsing completes, both on success and when the budget is breached.

use serde_saphyr::options;
use serde_saphyr::budget::BudgetReport;

let options = options! {}.with_budget_report(|report: BudgetReport| {
    // e.g. update your state / emit metrics / log the report
    let _ = report;
});

Trait Implementations§

Source§

impl Clone for Options

Source§

fn clone(&self) -> Options

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Options

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Options

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.