Recursive AI

Read a UTF-16 YAML file in Rust

oneyaml is a free, open-source YAML library for Rust from Recursive AI. MIT or Apache-2.0, no unsafe code.

Pass the file directly to from_reader; it detects the encoding.

Terminal
cargo add oneyaml

The zip’s config.yaml contains port: 8080 and a newline, in UTF-16LE with a byte order mark (BOM).

RUST
use std::collections::BTreeMap;
use std::{error::Error, fs::File};
 
fn main() -> Result<(), Box<dyn Error>> {
    let file = File::open("config.yaml")?;
    let config: BTreeMap<String, u16> =
        oneyaml::from_reader(file)?;
    let port = config.get("port").ok_or("no port")?;
    println!("port: {port}");
    Ok(())
}

Unzip the example, then cargo run.

Text
port: 8080

Requires Rust 1.85 or later. The printed 8080 comes from a u16, not from a string. A file that can’t be opened returns an I/O error; invalid encoding or a value that doesn’t fit u16 returns a deserialization error.

Variations

If the bytes are already in memory, use from_slice instead of opening a file. Replace the file read and the from_reader call with:

RUST
let bytes = include_bytes!("../config.yaml");
let config: BTreeMap<String, u16> =
    oneyaml::from_slice(bytes)?;

The short answer

Open the UTF-16 file with File::open and pass the file handle to oneyaml::from_reader. Give the result a type: BTreeMap<String, u16> tells the deserializer to read string keys and unsigned 16-bit values. Use this shape when all values in the mapping are numbers. For mixed fields such as a port and a host name, use a struct whose field types match the YAML.

Is a Rust string UTF-8, and does UTF-16 YAML need to be converted first?

A Rust String holds UTF-8. Reading UTF-16 through read_to_string doesn’t decode it as UTF-16. If the file is already in UTF-16, keep it as bytes at the parser boundary. oneyaml-rust uses the byte order mark or the opening bytes to detect UTF-8, UTF-16, or UTF-32. In the example, the first two bytes are FF FE, the UTF-16 little-endian mark. Typing port: 8080 into a UTF-8 editor produces different bytes, even though the visible YAML is the same.

How do you read YAML from bytes instead of a file?

Use from_slice for a byte slice and from_reader for a file or another Read source. Both use the encoding detection described in the pinned byte-reader API. Both deserialize one YAML document. The reader puts a bound on how much it reads based on the decoded UTF-8 size limit and the detected encoding; it isn’t an iterator over documents. If you show locations for encoding or parse errors, the byte spans refer to the decoded UTF-8 text, not offsets into the original UTF-16 file.

All oneyaml Rust recipes