---
title: "Get the byte span of a YAML field in Rust"
url: https://recursiveai.org/oneyaml/rust/cookbook/track-yaml-field-byte-spans/
description: "Deserialize a YAML field into Spanned<u16> and use its UTF-8 byte offsets to recover the original text, even when non-ASCII characters precede it."
version: "1.2.0"
---

# Get the byte span of a YAML field in Rust

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

[crates.io](https://crates.io/crates/oneyaml) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-rust) · [Docs](https://recursiveai.org/oneyaml/rust/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/rust/cookbook/track-yaml-field-byte-spans/track-yaml-field-byte-spans.zip)

Use `Spanned<T>` to locate a parsed value in the original YAML.

```shell
cargo add oneyaml
cargo add serde --features derive
```

```rust
#[derive(serde::Deserialize)]
struct Config {
    port: oneyaml::Spanned<u16>,
}
fn main() -> Result<(), oneyaml::Error> {
    let yaml = "# Café\nport: 8080\n";
    let config: Config =
        oneyaml::from_str(yaml)?;
    let span = config.port.span();
    let range = span.start..span.end;
    let source = &yaml[range.clone()];
    println!("port: {}", *config.port);
    println!("bytes: {range:?}");
    println!("source: {source}");
    Ok(())
}
```

Unzip [the example](https://recursiveai.org/oneyaml/rust/cookbook/track-yaml-field-byte-spans/track-yaml-field-byte-spans.zip), then `cargo run`.

Requires Rust 1.85 or later.

```text
port: 8080
bytes: 14..18
source: 8080
```

## The full program

The full example adds a second input, where `port` refers to an anchored number. If `port` is missing or not a `u16`, deserialization returns an error instead of a spanned value.

```rust
#[derive(serde::Deserialize)]
struct Config {
    port: oneyaml::Spanned<u16>,
}
fn main() -> Result<(), oneyaml::Error> {
    let yaml = "# Café\nport: 8080\n";
    let config: Config =
        oneyaml::from_str(yaml)?;
    let span = config.port.span();
    let range = span.start..span.end;
    let source = &yaml[range.clone()];
    println!("port: {}", *config.port);
    println!("bytes: {range:?}");
    println!("source: {source}");

    let yaml = "base: &number 8080\nport: *number\n";
    let config: Config = oneyaml::from_str(yaml)?;
    let span = config.port.span();
    println!("alias: {}", &yaml[span.start..span.end]);
    Ok(())
}
```

`cargo run` prints:

```text
port: 8080
bytes: 14..18
source: 8080
alias: *number
```

## Related recipes

- [Parse YAML into Rust structs](https://recursiveai.org/oneyaml/rust/cookbook/parse-yaml-into-structs/)
- [Read YAML anchors and aliases](https://recursiveai.org/oneyaml/rust/cookbook/anchors-aliases-merge-keys/)
- [Show YAML errors with line and column](https://recursiveai.org/oneyaml/rust/cookbook/errors-with-line-and-column/)

## The short answer

Change the field type from `u16` to `Spanned<u16>` and deserialize it with oneyaml-rust. The wrapper gives you both the parsed port and the location of its source text. Use `*config.port` to read the number and `config.port.span()` to recover the byte range. Leave fields you don’t need to locate unwrapped.

## How do you get source locations when deserializing with Serde?

A typed field tells you what the text means, not where you typed it. A span is useful when the YAML is syntactically valid and matches the Rust type but fails one of your application’s rules. For example, `0` fits in a `u16`, but an application that requires a fixed, nonzero port can still reject it. Keep the original YAML beside the parsed config so you can highlight the offending value without looking up the key again. For a parse error, use the location on the error instead: there may be no decoded field to inspect.

The [pinned `Spanned` documentation](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/spanned.rs#L23-L30) says only this library’s deserializers know how to read the wrapper. If one config type needs to work with several formats, keep the wrapper in the YAML input type and pass only the decoded value to your shared application type.

## Are YAML spans byte offsets or character positions?

They’re zero-based UTF-8 byte offsets. The start is included and the end is excluded, just like a Rust range. In the example, `é` takes two bytes, so `8080` starts at byte 14, not character 14. Slice the same string you deserialized, before trimming it or changing its line endings. The span is for the value node, not the whole `port: 8080` line.

For an alias, the [same documentation](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml/src/spanned.rs#L25-L30) distinguishes two cases. A value reached through an alias spans the alias token itself, such as `*number`. If the alias refers to a mapping or sequence, nodes **inside** that collection keep the spans of their anchored source. This matters if you want to highlight the alias the reader sees at the use site rather than the original value elsewhere in the file.
