Skip to main content

from_slice

Function from_slice 

Source
pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result<T, Error>
where T: Deserialize<'de>,
Expand description

Deserialize a single YAML document from a UTF-8 byte slice.

UTF-8 only (due borrowing). For UTF-16 input, use from_reader instead: let reader = std::io::Cursor::new(bytes); let cfg: Config = serde_saphyr::from_reader(reader)?;

This is equivalent to from_str, but accepts &[u8] and validates it is valid UTF-8 before parsing.

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 byte slice’s lifetime.

Example: read a small Config structure from bytes.

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 bytes = yaml.as_bytes();
let cfg: Config = serde_saphyr::from_slice(bytes).unwrap();
assert!(cfg.enabled);