Skip to main content

from_str

Function from_str 

Source
pub fn from_str<'de, T>(input: &'de str) -> Result<T, Error>
where T: Deserialize<'de>,
Expand description

Deserialize any T: serde::de::Deserialize<'de> directly from a YAML string.

This is the simplest entry point; it parses a single YAML document. If the input contains multiple documents, this returns an error advising to use from_str_multiple or from_str_multiple_with_options.

This function supports both owned types (like String) and borrowed types (like &str). For borrowed types, the deserialized value’s lifetime is tied to the input string’s lifetime.

Note: Borrowing only works for simple plain scalars that don’t require any transformation (no multi-line folding, no escape processing). For transformed strings, deserialization to &str will fail with a helpful error message suggesting to use String or Cow<str> instead.

Example: read a small Config structure from a YAML string.

use serde::Deserialize;

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

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

let cfg: Config = serde_saphyr::from_str(yaml).unwrap();
assert!(cfg.enabled);

Example: read a structure with borrowed string fields.

Borrowed strings are supported when deserializing from an in-memory input (from_str / from_slice), and only when the scalar exists verbatim in the input (i.e., no escape processing, folding, or other normalization is required). If the YAML scalar requires transformation, deserializing into &str fails with an error suggesting String or Cow<str>.

Note: reader-based entry points like from_reader require DeserializeOwned and therefore cannot return values that borrow from the input.

use serde::Deserialize;

#[derive(Debug, Deserialize, PartialEq)]
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");
assert_eq!(data.value, 42);