---
title: "Limit YAML nesting depth in Rust"
url: https://recursiveai.org/oneyaml/rust/cookbook/set-yaml-parser-depth-limit/
description: "Limit YAML nesting depth in Rust with Settings::max_depth and from_str_with. Count maps and lists, then handle Y2000 when input goes too deep."
version: "1.2.0"
---

# Limit YAML nesting depth 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/set-yaml-parser-depth-limit/set-yaml-parser-depth-limit.zip)

Use `max_depth` to cap how many levels of maps and lists the parser accepts.

```shell
cargo add oneyaml
```

```rust
use oneyaml::{Settings, Value};

fn main() {
    let settings = Settings::new().max_depth(2);
    let yaml = "ports: [[80]]";
    let parsed: Result<Value, _> =
        oneyaml::from_str_with(yaml, &settings);
    match parsed {
        Ok(_) => println!("Accepted"),
        Err(error) => {
            let code = error.code();
            println!("Rejected: {code}");
        }
    }
}
```

Prints:

```text
Rejected: Y2000
```

`Y2000` means the YAML exceeded the nesting-depth limit.

Unzip [the example](https://recursiveai.org/oneyaml/rust/cookbook/set-yaml-parser-depth-limit/set-yaml-parser-depth-limit.zip), then `cargo run`.

Requires Rust 1.85 or later.

## Full program

The download compares `ports: [80, 443]` with `ports: [[80]]`. The first has a mapping and a list; the second adds an inner list.

```rust
use oneyaml::{Settings, Value, code};

fn main() -> Result<(), oneyaml::Error> {
    let settings = Settings::new().max_depth(2);
    let cases = ["ports: [80, 443]", "ports: [[80]]"];
    for yaml in cases {
        let result: Result<Value, _> =
            oneyaml::from_str_with(yaml, &settings);
        match result {
            Ok(_) => println!("Accepted: {yaml}"),
            Err(error) => {
                if error.code() != code::DEPTH_LIMIT_EXCEEDED {
                    return Err(error);
                }
                let code = error.code();
                println!("Rejected: {yaml} ({code})");
            }
        }
    }
    Ok(())
}
```

`cargo run` prints:

```text
Accepted: ports: [80, 443]
Rejected: ports: [[80]] (Y2000)
```

The full program handles `Y2000` as a depth rejection and returns any other error to the caller rather than reporting it as a depth problem.

## Variations

### Keep the other limits for untrusted input

Replace the `settings` line with this to cap nesting at two levels while keeping the other resource budgets in the untrusted profile:

```rust
let settings = Settings::new()
    .limits(oneyaml::Limits::untrusted())
    .max_depth(2);
```

The two sample inputs produce the same result with these settings.

## Related recipes

- [Parse untrusted YAML in Rust](https://recursiveai.org/oneyaml/rust/cookbook/untrusted-input/)
- [Show YAML errors with line and column in Rust](https://recursiveai.org/oneyaml/rust/cookbook/errors-with-line-and-column/)
- [Parse YAML into Rust structs](https://recursiveai.org/oneyaml/rust/cookbook/parse-yaml-into-structs/)

## The short answer

Set `Settings::new().max_depth(n)` and pass those settings to [`from_str_with`](https://docs.rs/oneyaml/1.2.0/oneyaml/fn.from_str_with.html). A parse that exceeds the collection depth returns `Y2000` (`DEPTH_LIMIT_EXCEEDED`). The settings apply to that call; `from_str` on its own uses the defaults.

## How is YAML nesting depth counted?

Count mappings and sequences on the deepest path, starting with the root collection at depth one. The [pinned limit documentation](https://github.com/recursive-ai-oss/oneyaml-rust/blob/14445615f5a5b2895fdaa1da7719584ef15d9d6b/crates/oneyaml-core/src/limits.rs#L157-L165) says it counts “block and flow collections together.” Writing lists with hyphens instead of brackets doesn’t change their depth. Scalars such as `80` don’t add a collection level.

For `ports: [80, 443]`, the root map is level one and the list is level two. Adding ports to that same list doesn’t increase the depth. Wrapping a port in a second list does, and `ports: [[80]]` reaches level three.

## What YAML nesting limit should I set for a configuration file?

Start with the deepest valid example your application accepts. If the configuration has a fixed shape, test a valid document at that depth and another with an extra collection below it, as the download does. If a section accepts nested values of its own, account for the outer maps and lists too. A global cap won’t tell you whether `ports` is supposed to be a list of integers or a list of lists; check the structure separately with a typed configuration or application validation.

The default parser depth is 1,024; the untrusted profile sets it to 128 and tightens other budgets. Changing depth alone doesn’t cap input size or alias expansion. There’s also a separate `max_typed_depth` bound for Serde recursion: increasing the parser’s depth limit doesn’t increase that bound.
