### Check Budget Usage Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md An example of running `serde-saphyr` on a configuration file and displaying the resulting budget report, which details resource usage metrics. ```bash $ serde-saphyr config.yaml ✓ Valid YAML Budget report: - Total events: 1234 - Max depth: 8 - Max node: 123 - Scalar bytes: 45678 - Comments: 5678 - Anchors: 2 - Aliases: 5 - Merge keys: 0 - Documents: 1 ``` -------------------------------- ### Setup Filesystem Includes in Rust Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/06_special_features.md Configure serde-saphyr to resolve includes from the filesystem by setting a root directory. This example demonstrates deserializing a configuration struct with filesystem include support. ```rust use serde::Deserialize; #[derive(Deserialize)] struct Config { database: String, logging: String, } // Enable filesystem-backed resolution let options = serde_saphyr::options! {} .with_filesystem_root("config/") .expect("failed to setup includes"); let cfg: Config = serde_saphyr::from_str_with_options(yaml, options)?; ``` -------------------------------- ### Install serde-saphyr CLI from crates.io Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md Installs the serde-saphyr CLI tool using Cargo from the crates.io registry. ```bash cargo install serde-saphyr ``` -------------------------------- ### Install serde-saphyr CLI from Git Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md Installs the serde-saphyr CLI tool using Cargo directly from its Git repository. ```bash cargo install --git https://github.com/bourumir-wyngs/serde-saphyr ``` -------------------------------- ### Profile Budget for YAML Configuration Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md An example of using the `serde-saphyr` CLI to profile a YAML configuration file and obtain a budget report. ```bash $ serde-saphyr myconfig.yaml ✓ Valid YAML Budget report: - Total events: 512 - Max depth: 12 - Nodes: 67 - Scalar bytes: 8192 - Anchors: 0 - Aliases: 0 - Merge keys: 0 - Documents: 1 ``` -------------------------------- ### Install Serde Saphyr CLI with Miette for Fancy Errors Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/README.md Installs the `serde-saphyr` CLI with the `miette` feature enabled for enhanced, graphical error reporting. Alternatively, run from a git checkout with the feature. ```bash cargo install serde-saphyr --features miette ``` ```bash cargo run --features miette -- path/to/file.yaml ``` -------------------------------- ### Documentation Generation using Budget Report Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md An example of using the `serde-saphyr` CLI to generate documentation by extracting and displaying the budget report section from a sample configuration file. ```bash echo "## Configuration Budget" echo "" echo "Based on sample configurations:" echo "" serde-saphyr config/sample1.yaml | grep "Budget report" -A 20 ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/03_configuration.md Demonstrates setting up comprehensive parsing options, including budget constraints, duplicate key policies, merge key policies, indentation checks, and incorporating environment properties. ```rust use serde::Deserialize; use serde_saphyr::{DuplicateKeyPolicy, MergeKeyPolicy, RequireIndent}; use std::collections::HashMap; #[derive(Debug, Deserialize)] struct Database { host: String, port: u16, } let yaml = r#"# host: localhost port: 5432 #"#; let mut props = HashMap::new(); props.insert("DB_HOST".to_string(), "prod.example.com".to_string()); let options = serde_saphyr::options! { budget: serde_saphyr::budget! { max_depth: 50, max_anchors: 100, max_total_scalar_bytes: 10_000_000, }, duplicate_keys: DuplicateKeyPolicy::LastWins, merge_keys: MergeKeyPolicy::Merge, indentation_check: RequireIndent::MultipleOf(2), with_snippet: true, crop_radius: 3, } .with_properties(props); let db: Database = serde_saphyr::from_str_with_options(yaml, options)?; ``` -------------------------------- ### Example of !include Tag Processing Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md Demonstrates how the `--include` option works by showing a YAML file with an `!include` tag and the corresponding file that will be included. ```bash # Assuming config.yaml contains: app: !include app.yaml # The file ./config/app.yaml will be included serde-saphyr --include ./config config.yaml ``` -------------------------------- ### YAML Merge Key Syntax Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/06_special_features.md Demonstrates the syntax for YAML merge keys using the `<<` operator to include content from an anchor. ```yaml defaults: &defaults timeout: 30 retries: 3 log_level: info development: <<: *defaults # Merges all keys from defaults database: dev.db # Override/add new key production: <<: *defaults database: prod.db log_level: warn # Override from defaults ``` -------------------------------- ### Validate Configuration File Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md A basic example of validating a configuration file located at a specific path. ```bash serde-saphyr /etc/myapp/config.yaml ``` -------------------------------- ### Validate with Include Support Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md Shows how to use the `--include` option to enable `!include` tag processing for a main YAML file, specifying a directory for included files. ```bash serde-saphyr --include ./configs/ main.yaml ``` -------------------------------- ### Construct Serializer Options Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/02_serialization.md Use the `ser_options!` macro to create a `SerializerOptions` instance. This example customizes indentation, quoting, and provides a custom anchor generator. ```rust let opts = serde_saphyr::ser_options! { indent_step: 4, quote_all: true, anchor_generator: Some(|id| format!("ref{}", id)), }; ``` -------------------------------- ### Configure Filesystem Include Resolver Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/03_configuration.md When the `include_fs` feature is enabled, you can use `SafeFileResolver` to load included files from the filesystem. This example configures the resolver with a specific root directory. ```rust let opts = serde_saphyr::options! {} .with_filesystem_root("config/").expect("setup failed"); ``` -------------------------------- ### FlowSeq Serialization Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/04_types_and_wrappers.md Demonstrates serializing a vector of integers using FlowSeq, resulting in an inline sequence representation in the YAML output. ```rust use serde::Serialize; use serde_saphyr::FlowSeq; #[derive(Serialize)] struct Coords { points: FlowSeq>, } let coords = Coords { points: FlowSeq(vec![1, 2, 3, 4, 5]), }; let yaml = serde_saphyr::to_string(&coords)?; // Output: points: [1, 2, 3, 4, 5] ``` -------------------------------- ### Successful Validation Output Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md Example output when a YAML file is valid, showing a success message and a detailed budget report. ```text ✓ Valid YAML Budget report: - Total events: 42 - Max depth: 3 - Nodes: 15 - Scalar bytes: 128 - Anchors: 2 - Aliases: 1 - Merge keys: 0 - Documents: 1 ``` -------------------------------- ### NullableTilde Serialization Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/04_types_and_wrappers.md Shows how NullableTilde serializes an `Option::None` value as '~' in the YAML output, as demonstrated with an 'optional_value' field. ```rust use serde::Serialize; use serde_saphyr::NullableTilde; #[derive(Serialize)] struct Config { optional_value: NullableTilde, } let cfg = Config { optional_value: NullableTilde(None), }; let yaml = serde_saphyr::to_string(&cfg)?; // Output: optional_value: ~ ``` -------------------------------- ### LitString Serialization Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/04_types_and_wrappers.md Shows how LitString serializes a multi-line string using the literal block scalar style ('|'), preserving all newlines and whitespace. ```rust use serde::Serialize; use serde_saphyr::LitString; #[derive(Serialize)] struct Poem { text: LitString, } let poem = Poem { text: LitString("Line 1\nLine 2\nLine 3".to_string()), }; let yaml = serde_saphyr::to_string(&poem)?; // Output: // text: | // Line 1 // Line 2 // Line 3 ``` -------------------------------- ### Handling Budget Breach Errors Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/05_error_handling.md Example of how to match and handle a `BudgetBreach` error during deserialization using `serde_saphyr::from_str`. It prints specific budget exceeded information or a generic error message. ```rust match serde_saphyr::from_str::(yaml) { Ok(_) => { /* success */ } Err(Error::BudgetBreached { breach }) => { eprintln!( "Budget exceeded: {} (limit: {}, observed: {})", breach.limit_name, breach.limit_value, breach.observed_value ); } Err(e) => eprintln!("Other error: {}", e.render()), } ``` -------------------------------- ### Robotics YAML Extensions Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/README.md Example of YAML content with robotics extensions, including radian and degree tags, mathematical expressions, and function calls. Ensure 'robotics' feature and 'angle_conversions' option are enabled. ```yaml 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 longitude: !radians 8:32:53.2 # Nautical, ETH Zürich Main Building (8°32′53.2″ E) ``` -------------------------------- ### Example Error Output with Serde-Saphyr Snippet Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/README.md This is a typical output when Serde-Saphyr renders a YAML snippet for a validation error. It shows the error location, the problematic line, and the origin of YAML anchors. ```text error: line 3 column 23: invalid here, validation error: length is lower than 2 for `secondString` --> the value is used here:3:23 | 1 | 2 | firstString: &A "x" 3 | secondString: *A | ^ invalid here, validation error: length is lower than 2 for `secondString` 4 | | | This value comes indirectly from the anchor at line 2 column 25: | 1 | 2 | firstString: &A "x" | ^ 3 | secondString: *A 4 | ``` -------------------------------- ### Simple Configuration with Options Macro Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Create a basic `Options` struct using the `options!` macro with default settings. This is useful for standard parsing scenarios. ```rust let opts = serde_saphyr::options! {}; let cfg: Config = serde_saphyr::from_str_with_options(yaml, opts)?; ``` -------------------------------- ### Custom PirateFormatter Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/05_error_handling.md An example of a custom `MessageFormatter` that provides pirate-themed error messages for specific error types. This demonstrates how to match on `Error` variants and return custom `Cow<'a, str>`. ```rust use serde_saphyr::{Error, MessageFormatter}; use std::borrow::Cow; struct PirateFormatter; impl MessageFormatter for PirateFormatter { fn format_message<'a>(&self, err: &'a Error) -> Cow<'a, str> { match err { Error::Eof { .. } => Cow::Borrowed("Arr! Ye YAML be incomplete, matey!"), Error::UnexpectedType { .. } => { Cow::Borrowed("Shiver me timbers! Wrong type in the treasure map!") } _ => Cow::Borrowed("Ye scallywag misconfigured yer YAML"), } } } let err = serde_saphyr::from_str::("").unwrap_err(); println!("{}", err.render_with_formatter(&PirateFormatter)); ``` -------------------------------- ### Construct Options with Macro Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/03_configuration.md Use the `options!` macro to create a new configuration. You can set various fields like budget limits, duplicate key policies, and snippet inclusion. ```rust let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { max_depth: 100, max_anchors: 500, }, duplicate_keys: DuplicateKeyPolicy::LastWins, with_snippet: false, }; ``` -------------------------------- ### DoubleQuoted Serialization Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/04_types_and_wrappers.md Shows how DoubleQuoted forces a string value to be serialized with double quotes, as demonstrated with a 'password' field. ```rust use serde::Serialize; use serde_saphyr::DoubleQuoted; #[derive(Serialize)] struct Config { password: DoubleQuoted, } let cfg = Config { password: DoubleQuoted("secret".to_string()), }; let yaml = serde_saphyr::to_string(&cfg)?; // Output: password: "secret" ``` -------------------------------- ### Validation Error Output Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md Example output when a YAML file fails validation, indicating a parse error with location details. ```text ✗ Parse error error at line 5 column 10: unexpected mapping value --> config.yaml:5:10 | 3 | timeout: 30 4 | retries: three 5 | ^-- value is not an integer ``` -------------------------------- ### Configuration with Custom Budget and Snippet Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Loads YAML configuration safely using custom budget and snippet options. Requires importing `serde_saphyr`. ```rust fn load_config_safely(yaml: &str) -> Result { let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { max_depth: 50, max_total_scalar_bytes: 1_000_000, }, with_snippet: true, }; serde_saphyr::from_str_with_options(yaml, opts) } ``` -------------------------------- ### Define Budget Options in Rust Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md Shows how to define budget options in Rust code using `serde_saphyr::options!` and `serde_saphyr::budget!`, based on a budget report from the CLI. ```rust let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { max_events: 1000, // Some headroom above 512 max_depth: 30, max_nodes: 200, max_total_scalar_bytes: 20_000, }, }; ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md The fundamental syntax for invoking the serde-saphyr CLI, requiring options and a file path. ```bash serde-saphyr [OPTIONS] ``` -------------------------------- ### Commented Serialization Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/04_types_and_wrappers.md Demonstrates serializing a struct containing a Commented field. The output YAML includes the comment appended to the value. ```rust use serde::{Serialize, Deserialize}; use serde_saphyr::Commented; #[derive(Serialize, Deserialize)] struct Config { timeout: Commented, } let cfg = Config { timeout: Commented { value: 30, comment: "seconds".to_string(), }, }; let yaml = serde_saphyr::to_string(&cfg)?; // Output: timeout: 30 # seconds ``` -------------------------------- ### Run Serde Saphyr with Miette via CLI Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/06_special_features.md Demonstrates how to invoke the `serde-saphyr` CLI tool with the `--miette` flag to enable fancy error diagnostics when processing a configuration file. ```bash serde-saphyr --miette config.yaml ``` -------------------------------- ### FoldString Serialization Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/04_types_and_wrappers.md Demonstrates serializing a long string with FoldString, resulting in a folded block scalar ('>') with automatic line wrapping at whitespace. ```rust use serde::Serialize; use serde_saphyr::FoldString; #[derive(Serialize)] struct Description { text: FoldString, } let desc = Description { text: FoldString("This is a long description that spans multiple words and will be wrapped at the configured line width.".to_string()), }; let yaml = serde_saphyr::to_string(&desc)?; // Output: // text: > // This is a long description that spans multiple words // and will be wrapped at the configured line width. ``` -------------------------------- ### options! Macro Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Constructs an `Options` struct with custom settings for Serde-saphyr parsing. It allows overriding default values for various configuration fields. ```APIDOC ## options! Macro ### Description Constructs an `Options` struct with custom settings for Serde-saphyr parsing. It allows overriding default values for various configuration fields. ### Syntax ```rust let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { ... }, duplicate_keys: DuplicateKeyPolicy::LastWins, with_snippet: true, // ... other fields }; ``` ### Available Fields | Field | Type | Default | |-------|------|---------| | `budget` | `Budget` | `Budget::default()` | | `duplicate_keys` | `DuplicateKeyPolicy` | `Error` | | `merge_keys` | `MergeKeyPolicy` | `Merge` | | `alias_limits` | `AliasLimits` | Default limits | | `with_snippet` | `bool` | `true` | | `crop_radius` | `usize` | `2` | | `strict_booleans` | `bool` | `false` | | `no_schema` | `bool` | `false` | | `legacy_octal` | `bool` | `false` | | `ignore_binary_tag_for_string` | `bool` | `false` | | `angle_conversions` | `bool` | `false` | | `indentation_check` | `RequireIndent` | `None` | | `property_syntax` | `PropertySyntax` | `Braced` | ### Examples **Simple configuration**: ```rust let opts = serde_saphyr::options! {}; let cfg: Config = serde_saphyr::from_str_with_options(yaml, opts)?; ``` **With custom budget**: ```rust let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { max_depth: 50, max_anchors: 100, }, }; ``` **Multiple settings**: ```rust let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { max_events: 500_000, }, duplicate_keys: DuplicateKeyPolicy::FirstWins, with_snippet: false, crop_radius: 5, }; ``` ``` -------------------------------- ### SpaceAfter Usage Example Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/04_types_and_wrappers.md Illustrates using SpaceAfter to visually separate 'section_a' from 'section_b' in the YAML output by adding a blank line after 'section_a'. ```rust use serde::Serialize; use serde_saphyr::SpaceAfter; #[derive(Serialize)] struct Doc { section_a: SpaceAfter, section_b: String, } ``` -------------------------------- ### Provide Helpful User Feedback Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/05_error_handling.md Shows how to read a configuration file and provide user-friendly error messages that include the file path and the specific Serde Saphyr error. Useful for command-line applications. ```rust fn load_config(path: &str) -> Result { let content = std::fs::read_to_string(path) .map_err(|e| format!("Cannot read {}: {}", path, e))?; serde_saphyr::from_str(&content) .map_err(|e| format!("Invalid config in {}\n{}", path, e.render())) } ``` -------------------------------- ### Configure Indentation Enforcement Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/03_configuration.md Enforce consistent indentation using `RequireIndent::MultipleOf(n)`. This example requires indentation to be a multiple of 4 spaces. ```rust let opts = serde_saphyr::options! { indentation_check: RequireIndent::MultipleOf(4), }; ``` -------------------------------- ### Get Error Source Location Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/05_error_handling.md Use `location` to retrieve the source location of an error. Returns `None` for structural errors like `IOError`. ```rust pub fn location(&self) -> Option<&Location> ``` -------------------------------- ### Configure Filesystem Include Resolver Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/README.md Configure `serde-saphyr` to resolve `!include` tags from the filesystem. This requires enabling the `include` and `include_fs` feature flags. The `with_filesystem_root` method sets the base directory for included files. ```rust fn main() { let options = options! {} .with_filesystem_root("examples").expect("failed to create filesystem include resolver"); let config: Config = from_str_with_options(yaml_to_parse, options) .expect("failed to parse filesystem include example"); } ``` -------------------------------- ### Validation Error Output with --plain flag Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md Example output for a validation error when the `--plain` flag is used, showing only text-based error messages. ```text error at line 5 column 10: unexpected mapping value ``` -------------------------------- ### Configuration with Angle and Time Parsing Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/06_special_features.md Demonstrates enabling `angle_conversions` and parsing custom time formats via `serde_saphyr::options!`. The `robotics` feature must be enabled. ```rust use serde::Deserialize; #[derive(Deserialize)] struct RobotConfig { angle: f32, duration: f32, } let yaml = r#"# angle: !degrees 90 duration: 0:30:00 "#; let options = serde_saphyr::options! { angle_conversions: true, // MUST be enabled }; let cfg: RobotConfig = serde_saphyr::from_str_with_options(yaml, options)?; assert_eq!(cfg.angle, std::f32::consts::PI / 2.0); // 90° → π/2 rad ``` -------------------------------- ### Basic YAML Interpolation Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/06_special_features.md Illustrates the basic syntax for variable interpolation in YAML configuration files using braced syntax. ```yaml database_url: ${DATABASE_URL} log_level: ${LOG_LEVEL:-INFO} ``` -------------------------------- ### Render Error Message Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/05_error_handling.md Use `render` to get a plain-text error message. It includes the error message, location if available, and a YAML snippet if `with_snippet` was used. ```rust pub fn render(&self) -> String ``` ```rust match serde_saphyr::from_str::(yaml) { Ok(cfg) => { /* use cfg */ } Err(e) => eprintln!("{}", e.render()) } ``` -------------------------------- ### Deprecated Direct Construction vs. Macro Usage Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Illustrates the deprecated direct construction of Options and contrasts it with the recommended macro usage. ```rust // DEPRECATED - don't use #[allow(deprecated)] let opts = Options { budget: Some(Budget { /* ... */ }), duplicate_keys: DuplicateKeyPolicy::Error, // ... }; // CORRECT - use the macro let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { /* ... */ }, duplicate_keys: DuplicateKeyPolicy::Error, }; ``` -------------------------------- ### Configuration with Properties and Braced Syntax Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/06_special_features.md Demonstrates deserializing a configuration from YAML with property interpolation using braced syntax. Requires the `properties` feature. ```rust use serde::Deserialize; use std::collections::HashMap; #[derive(Deserialize)] struct Config { database_url: String, log_level: String, } let mut props = HashMap::new(); props.insert("DATABASE_URL".to_string(), "postgresql://localhost".to_string()); props.insert("LOG_LEVEL".to_string(), "debug".to_string()); let options = serde_saphyr::options! { property_syntax: serde_saphyr::PropertySyntax::Braced, } .with_properties(props); let yaml = r#" database_url: ${DATABASE_URL} log_level: ${LOG_LEVEL} "#; let cfg: Config = serde_saphyr::from_str_with_options(yaml, options)?; assert_eq!(cfg.database_url, "postgresql://localhost"); ``` -------------------------------- ### Configure Serde-saphyr Options with Macros Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/README.md Use the `options!` macro to configure deserialization behavior, including budget settings and duplicate key policies. This approach avoids struct literals and direct field access, which are being deprecated. ```rust fn main() { let options = serde_saphyr::options! { budget: serde_saphyr::budget! { max_documents: 2, }, duplicate_keys: DuplicateKeyPolicy::LastWins, }; } ``` -------------------------------- ### Constructing a Budget with the `budget!` Macro Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/03_configuration.md Use the `budget!` macro to create a `Budget` instance. You can specify limits for various fields like `max_depth`, `max_anchors`, and `max_reader_input_bytes`. Fields not explicitly set will use their default values. ```rust let budget = serde_saphyr::budget! { max_depth: 100, max_anchors: 200, max_reader_input_bytes: Some(10_000_000), // 10 MiB }; ``` -------------------------------- ### Serde Saphyr Options with Budget Macro Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Configure specific budget settings within the options macro. Omitted fields use defaults. ```rust let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { max_depth: 100, }, }; ``` -------------------------------- ### Nested Serde Saphyr Macros for Options Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Demonstrates nesting macros like 'budget' and 'alias_limits' within the main 'options' macro. ```rust let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { max_reader_input_bytes: Some(10_000_000), }, alias_limits: serde_saphyr::alias_limits! { max_replay_stack_depth: 32, }, }; ``` -------------------------------- ### Construct Alias Limits Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/03_configuration.md Use the `alias_limits!` macro to define constraints on alias replay to prevent alias bombs. This example sets a custom maximum nesting depth for the alias replay stack. ```rust let limits = serde_saphyr::alias_limits! { max_replay_stack_depth: 32, }; ``` -------------------------------- ### Show CLI Help Message Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md Displays the help message for the serde-saphyr CLI, outlining available commands and options. ```bash serde-saphyr --help ``` -------------------------------- ### Custom Budget Configuration with Options Macro Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Configure custom budget settings within the `options!` macro by nesting the `budget!` macro. This allows control over parsing resource limits. ```rust let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { max_depth: 50, max_anchors: 100, }, }; ``` -------------------------------- ### Configure Serde Saphyr Dependencies Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/README.md Shows how to configure `serde-saphyr` in `Cargo.toml` to include only the deserializer or serializer, reducing compile times. Default features include both. ```toml serde-saphyr = { version = "0.0.27", default-features = false, features = ["deserialize"] } ``` ```toml serde-saphyr = { version = "0.0.27", default-features = false, features = ["serialize"] } ``` -------------------------------- ### Include Entire YAML Document Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/06_special_features.md Use `!include` to embed an entire external YAML file into your configuration. ```yaml # Include entire document config: !include config.yaml ``` -------------------------------- ### Construct RenderOptions with render_options! Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Use `render_options!` to create a `RenderOptions` struct for error rendering. Configure the `formatter` and `snippets` mode. ```rust use serde_saphyr::{UserMessageFormatter, SnippetMode}; let render_opts = serde_saphyr::render_options! { formatter: &UserMessageFormatter, snippets: SnippetMode::Off, }; let err = serde_saphyr::from_str::(yaml).unwrap_err(); let message = err.render_with_options(render_opts); ``` ```rust use serde_saphyr::{DefaultMessageFormatter, SnippetMode}; let render_opts = serde_saphyr::render_options! { formatter: &DefaultMessageFormatter, snippets: SnippetMode::Auto, }; ``` -------------------------------- ### Configure Parsing Budget Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/INDEX.md Define resource limits for parsing using the `serde_saphyr::options!` macro and `serde_saphyr::budget!` for `max_depth` and `max_anchors`. ```rust let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { max_depth: 100, max_anchors: 500, }, }; ``` -------------------------------- ### Configure Budget Report Callback Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/03_configuration.md Register a callback function to be invoked after parsing to inspect budget consumption. The callback receives a `BudgetReport` struct. ```rust let opts = serde_saphyr::options! {} .with_budget_report(|report| { println!("Events: {}", report.event_count); println!("Depth: {}", report.max_depth); }); ``` -------------------------------- ### Construct Options with Custom Settings Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Use the `options!` macro to create an `Options` struct with custom settings. This macro supports various fields for fine-tuning parsing behavior. ```rust let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { ... }, duplicate_keys: DuplicateKeyPolicy::LastWins, with_snippet: true, // ... other fields }; ``` -------------------------------- ### Minimal Serde Saphyr Options Macro Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Use the minimal macro to create default options. All fields are optional. ```rust let opts = serde_saphyr::options! {}; ``` -------------------------------- ### Basic File Inclusion in Rust Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/08_usage_patterns.md Perform basic file inclusion using `!include` directive in YAML. Configure the filesystem root using `serde_saphyr::options!().with_filesystem_root()`. ```rust let yaml = r#"# defaults: &defaults timeout: 30 retries: 3 config: <<: !include common.yaml database: prod.db #"#; let opts = serde_saphyr::options! {} .with_filesystem_root("config/")?; let cfg: Config = serde_saphyr::from_str_with_options(yaml, opts)?; ``` -------------------------------- ### Configuration Migration Workflow Script Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md A bash script demonstrating a configuration migration workflow. It first validates all YAML files in an 'old_configs' directory using `serde-saphyr` and exits if any are invalid, before proceeding with the migration. ```bash # Before migrating, ensure all existing configs are valid for f in old_configs/*.yaml; do serde-saphyr "$f" || { echo "Invalid YAML: $f" exit 1 } done # ... perform migration ... echo "Migration successful!" ``` -------------------------------- ### Use Serde Saphyr CLI with File Inclusion Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/README.md Executes the `serde-saphyr` CLI, enabling file inclusion (`!include` tags) by specifying the root path for the filesystem. ```bash serde-saphyr --include path/to/root path/to/file.yaml ``` -------------------------------- ### Configuration with Unbraced Syntax Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/06_special_features.md Shows how to enable and use unbraced syntax (`$NAME`) for property interpolation by setting `PropertySyntax::BracedOrBare`. ```rust let options = serde_saphyr::options! { property_syntax: serde_saphyr::PropertySyntax::BracedOrBare, } .with_properties(props); let yaml = r#" database_url: $DATABASE_URL log_level: ${LOG_LEVEL} "#; ``` -------------------------------- ### Profile Budget Usage in Serde Saphyr Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/08_usage_patterns.md Enable budget reporting to analyze parsing performance, including event count, maximum depth reached, and total scalar bytes processed. The `yaml` string must be defined. ```rust let opts = serde_saphyr::options! {} .with_budget_report(|report| { println!("Events: {}", report.event_count); println!("Max depth: {}", report.max_depth); println!("Total scalar bytes: {}", report.total_scalar_bytes); }); let _: MyType = serde_saphyr::from_str_with_options(yaml, opts)?; ``` -------------------------------- ### Loading Configuration from a File in Rust Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/08_usage_patterns.md Read configuration from a file path and parse its content. This function returns a `Result` to handle file I/O and parsing errors. ```rust fn load_from_file(path: &str) -> Result> { let content = std::fs::read_to_string(path)?; serde_saphyr::from_str(&content).map_err(|e| e.into()) } ``` -------------------------------- ### Enable CLI and Miette Features in Cargo.toml Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md Configures the `serde-saphyr` dependency in `Cargo.toml` to include CLI support features and the `miette` feature for enhanced error reporting. ```toml [dependencies] serde-saphyr = { version = "0.0.28", features = ["serialize", "deserialize", "include", "include_fs", "miette"] } ``` -------------------------------- ### Internal Macros Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/09_module_graph.md Macros for constructing various configuration types. ```APIDOC ## Internal Macros ### Description This private module contains macros used internally for constructing configuration objects. ### Macros - `options!`: Macro to construct `Options`. - `budget!`: Macro to construct `Budget`. - `alias_limits!`: Macro to construct `AliasLimits`. - `ser_options!`: Macro to construct `SerializerOptions`. - `render_options!`: Macro to construct `RenderOptions`. ``` -------------------------------- ### Multiple Settings with Options Macro Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Configure multiple options simultaneously using the `options!` macro, including custom budgets and other parsing-related fields. This provides fine-grained control over the parsing process. ```rust let opts = serde_saphyr::options! { budget: serde_saphyr::budget! { max_events: 500_000, }, duplicate_keys: DuplicateKeyPolicy::FirstWins, with_snippet: false, crop_radius: 5, }; ``` -------------------------------- ### Control Merge Key Behavior Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/06_special_features.md Illustrates how to configure the merge key behavior using `MergeKeyPolicy`. Options include `Error`, `AsOrdinary`, and the default `Merge`. ```rust use serde_saphyr::MergeKeyPolicy; let options = serde_saphyr::options! { merge_keys: MergeKeyPolicy::Error, // Forbid merges }; // Or: MergeKeyPolicy::AsOrdinary (treat << as regular key) // Or: MergeKeyPolicy::Merge (default) ``` -------------------------------- ### Load App Configuration with Figment Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/06_special_features.md Loads application configuration from a YAML file using the Figment crate. This snippet demonstrates how to merge a YAML provider and extract configuration into a struct. ```rust use serde::Deserialize; use figment::Figment; #[derive(Deserialize)] struct AppConfig { name: String, port: u16, } let figment = Figment::new() .merge(figment::providers::Yaml::file("config.yaml")); let config: AppConfig = figment.extract()?; ``` -------------------------------- ### Minimal Imports for Deserialization Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/09_module_graph.md Use this for basic deserialization from a string. Ensure `serde::Deserialize` is in scope. ```rust use serde::Deserialize; let cfg: MyConfig = serde_saphyr::from_str(yaml)?; ``` -------------------------------- ### Use Serde Saphyr CLI with Plain Text Errors Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/README.md Runs the `serde-saphyr` CLI, explicitly requesting plain-text error output even when the `miette` feature is enabled. ```bash serde-saphyr --plain path/to/file.yaml ``` -------------------------------- ### Enable CLI Features in Cargo.toml Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/10_cli_reference.md Specifies the necessary features (`serialize`, `deserialize`, `include`, `include_fs`) for the `serde-saphyr` dependency in `Cargo.toml` to enable CLI support. ```toml [dependencies] serde-saphyr = { version = "0.0.28", features = ["serialize", "deserialize", "include", "include_fs"] } ``` -------------------------------- ### Serialization with Formatting Options Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/09_module_graph.md Serialize data to YAML with specific formatting options, such as indentation step. Uses `to_string_with_options` and `ser_options!` macro. ```rust use serde::Serialize; use serde_saphyr::{to_string_with_options, ser_options, Commented}; let opts = ser_options! { indent_step: 4, }; let yaml = to_string_with_options(&config, opts)?; ``` -------------------------------- ### Include and Merge YAML Content Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/06_special_features.md Use `!include` with YAML merge keys (`<<:`) to include and merge content from an external file. ```yaml # Include and merge defaults: &defaults timeout: 30 retries: 3 development: <<: !include defaults.yaml database: dev.db ``` -------------------------------- ### Serialization Entry Points Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/09_module_graph.md Functions for serializing data to various output formats. ```APIDOC ## Serialization Functions ### Description Provides entry points for serializing data into different formats, including strings and writers, with support for options. ### Functions - `to_fmt_writer` - `to_fmt_writer_with_options` - `to_io_writer` - `to_io_writer_with_options` - `to_string` - `to_string_multiple` - `to_string_multiple_with_options` - `to_string_with_options` - `to_writer` - `to_writer_with_options` ``` -------------------------------- ### Unit Testing Configuration Parsing Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/08_usage_patterns.md Write unit tests to verify that your configuration parsing logic handles valid inputs correctly, invalid YAML formats, and missing required fields. Use `unwrap()` for expected success cases and check for errors in failure cases. ```rust #[cfg(test)] mod tests { use super::*; #[test] fn test_valid_config() { let yaml = "host: localhost\nport: 8080\n"; let cfg: Config = serde_saphyr::from_str(yaml).unwrap(); assert_eq!(cfg.host, "localhost"); assert_eq!(cfg.port, 8080); } #[test] fn test_invalid_yaml() { let yaml = "host: localhost\nport: not_a_number\n"; let result: Result = serde_saphyr::from_str(yaml); assert!(result.is_err()); } #[test] fn test_missing_required_field() { let yaml = "host: localhost\n"; let result: Result = serde_saphyr::from_str(yaml); assert!(result.is_err()); } } ``` -------------------------------- ### Minimal Config Loading in Rust Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/08_usage_patterns.md Load configuration from a string using a minimal struct definition. Ensure your struct derives `Deserialize`. ```rust use serde::Deserialize; #[derive(Deserialize)] struct AppConfig { host: String, port: u16, } let yaml = "host: localhost\nport: 8080\n"; let config: AppConfig = serde_saphyr::from_str(yaml)?; ``` -------------------------------- ### Pretty Printing with Serialization Options Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Sets serialization options for pretty printing YAML output, including indentation and block scalar preference. Requires importing `serde_saphyr`. ```rust let ser_opts = serde_saphyr::ser_options! { indent_step: 4, prefer_block_scalars: true, }; let yaml = serde_saphyr::to_string_with_options(&value, ser_opts)?; println!("{}", yaml); ``` -------------------------------- ### Construct Budget with Custom Limits Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Use the `budget!` macro to create a `Budget` struct with specific resource constraints. This is useful for controlling memory and computation limits during parsing. ```rust let budget = serde_saphyr::budget! { max_depth: 100, max_anchors: 200, // ... other fields }; ``` ```rust let budget = serde_saphyr::budget! { max_depth: 20, max_nodes: 1_000, }; ``` ```rust let budget = serde_saphyr::budget! { max_reader_input_bytes: None, }; ``` ```rust let budget = serde_saphyr::budget! { max_events: 100_000, enforcing_policy: serde_saphyr::EnforcingPolicy::PerDocument, }; ``` -------------------------------- ### Construct Serializer Options with Custom Formatting Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/07_macros.md Use the `ser_options!` macro to create a `SerializerOptions` struct for customizing YAML output. This allows control over indentation, quoting, and other formatting aspects. ```rust let opts = serde_saphyr::ser_options! { indent_step: 4, quote_all: true, // ... other fields }; ``` ```rust let opts = serde_saphyr::ser_options! { indent_step: 4, }; let yaml = serde_saphyr::to_string_with_options(&value, opts)?; ``` ```rust let opts = serde_saphyr::ser_options! { quote_all: true, }; ``` ```rust let opts = serde_saphyr::ser_options! { anchor_generator: Some(|id| format!("ref_{}", id)), }; ``` ```rust let opts = serde_saphyr::ser_options! { indent_step: 2, compact_list_indent: true, empty_as_braces: true, }; ``` -------------------------------- ### Deserialization Entry Points Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/09_module_graph.md Functions for deserializing data from various sources with options. ```APIDOC ## Deserialization Functions ### Description Provides entry points for deserializing data from different sources like strings, slices, and readers, with support for various options and configurations. ### Functions - `from_multiple` - `from_multiple_with_options` - `from_reader` - `from_reader_with_options` - `from_slice` - `from_slice_multiple` - `from_slice_multiple_with_options` - `from_slice_with_options` - `from_str` - `from_str_with_options` - `read` - `read_with_options` ### With Deserializer - `with_deserializer_from_reader` - `with_deserializer_from_reader_with_options` - `with_deserializer_from_slice` - `with_deserializer_from_slice_with_options` - `with_deserializer_from_str` - `with_deserializer_from_str_with_options` ``` -------------------------------- ### Include external YAML files Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/INDEX.md Include external YAML files using the `!include` tag. Specify the root directory for included files using `serde_saphyr::options!().with_filesystem_root()`. ```yaml # main.yaml database: !include database.yaml ``` ```rust let opts = serde_saphyr::options! {} .with_filesystem_root("config/")?; let cfg: Config = serde_saphyr::from_str_with_options(yaml, opts)?; ``` -------------------------------- ### Deserialize from Reader with Custom Options Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/01_deserialization.md Employ `from_reader_with_options` to deserialize data from a reader while applying custom configurations, such as setting input size limits via `budget`. ```rust pub fn from_reader_with_options( reader: R, options: Options, ) -> Result ``` ```rust use serde::Deserialize; use std::io::Cursor; let options = serde_saphyr::options! { budget: serde_saphyr::budget! { max_reader_input_bytes: Some(10_000_000), // 10 MiB limit }, }; let reader = Cursor::new(b"..."); let cfg: Config = serde_saphyr::from_reader_with_options(reader, options)?; ``` -------------------------------- ### Config Loading with Error Handling in Rust Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/08_usage_patterns.md Handle potential parsing errors when loading configuration. Use a `match` statement to differentiate between success and failure, rendering errors for debugging. ```rust match serde_saphyr::from_str::(yaml) { Ok(cfg) => println!("Loaded: {:?}", cfg), Err(e) => eprintln!("Parse error: {}", e.render()), } ``` -------------------------------- ### Deserialization with Options Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/09_module_graph.md Deserialize with custom options, such as handling duplicate keys. Requires `serde::Deserialize` and `serde_saphyr::DuplicateKeyPolicy`. ```rust use serde::Deserialize; use serde_saphyr::DuplicateKeyPolicy; let opts = serde_saphyr::options! { duplicate_keys: DuplicateKeyPolicy::Error, }; let cfg: MyConfig = serde_saphyr::from_str_with_options(yaml, opts)?; ``` -------------------------------- ### to_io_writer_with_options Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/02_serialization.md Serialize a value to an `io::Write` target with custom options. ```APIDOC ## to_io_writer_with_options ### Description Serialize to an `io::Write` target with options. ### Signature ```rust pub fn to_io_writer_with_options( output: &mut W, value: &T, options: SerializerOptions, ) -> Result<(), Error> ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `output` | `&mut W` | Yes | I/O sink (implements `std::io::Write`) | | `value` | `&T` | Yes | Value to serialize | | `options` | `SerializerOptions` | Yes | Formatting and serialization configuration | ### Returns `Result<(), Error>` ``` -------------------------------- ### Resilient Parsing with Fallbacks Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/08_usage_patterns.md Implement a function that attempts to load configuration from multiple file paths, falling back to a default configuration if all specified files fail to load or parse. ```rust fn load_config(paths: &[&str]) -> Result { for path in paths { if let Ok(content) = std::fs::read_to_string(path) { if let Ok(cfg) = serde_saphyr::from_str::(&content) { return Ok(cfg); } } } // Fallback to default serde_saphyr::from_str(DEFAULT_CONFIG_YAML) } ``` -------------------------------- ### Apply Default Values to Configuration Source: https://github.com/bourumir-wyngs/serde-saphyr/blob/master/_autodocs/08_usage_patterns.md Load configuration from a YAML string and merge it with default values defined in the struct's `Default` implementation. Only specified fields in the YAML will override defaults. ```rust #[derive(Deserialize)] struct AppConfig { host: String, port: u16, workers: Option, timeout: Option, } impl Default for AppConfig { fn default() -> Self { Self { host: "localhost".to_string(), port: 8080, workers: Some(4), timeout: Some(30), } } } let yaml = "host: prod.example.com\n"; let mut config = AppConfig::default(); // Only override what's in the YAML let partial: serde_json::Value = serde_saphyr::from_str(yaml)?; // Then merge with defaults... ```