# How do I parse length-prefixed binary data from the network without trusting the length?
Source: https://ruststudio.org/community/t/99/how-do-i-parse-length-prefixed-binary-data-from-the-network-without-trusting-the
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, Windows 11
Category: Help and questions | Kind: FAQ | Tags: security, parsing, binary | Views: 0

## Short answer
Treat the length field as a claim. Read it with from_be_bytes, convert with try_from, compare against a hard maximum before allocating, add with checked_add and take the payload with slice get so a short buffer gives an error instead of a panic. Never allocate a buffer the size the sender asks for.

## Answer
## Answer
Many protocols send "this many bytes follow". A hostile sender can announce four billion bytes and send five, or send nothing. Rust prevents the memory-corruption version of this mistake, but your parser can still panic on a bad slice, or allocate gigabytes because the sender said so.

The parser below does four things in order: it needs the four header bytes, converts the length without truncation, refuses lengths above a limit **before** doing anything with them, and uses `get` so that a short buffer is an error.

```rust title=src/main.rs
#[derive(Debug, PartialEq)]
enum FrameError {
    Truncated,
    TooLarge,
}

const MAX_FRAME: usize = 1 << 20; // 1 MiB

/// A frame is a 4-byte big-endian length, then that many bytes. The length comes from the sender.
fn parse_frame(data: &[u8]) -> Result<&[u8], FrameError> {
    let header: [u8; 4] = data.get(..4).ok_or(FrameError::Truncated)?.try_into().unwrap();
    let len = usize::try_from(u32::from_be_bytes(header)).map_err(|_| FrameError::TooLarge)?;
    if len > MAX_FRAME {
        return Err(FrameError::TooLarge); // refuse before allocating or slicing anything
    }
    let end = 4usize.checked_add(len).ok_or(FrameError::TooLarge)?;
    data.get(4..end).ok_or(FrameError::Truncated)
}

fn main() {
    println!("{:?}", parse_frame(&[0, 0, 0, 3, b'a', b'b', b'c', b'!']));
    println!("{:?}", parse_frame(&[0, 0, 0, 9, b'a']));
    println!("{:?}", parse_frame(&[0xFF, 0xFF, 0xFF, 0xFF, 1, 2]));
    println!("{:?}", parse_frame(&[0, 0]));
}
```

```text
Ok([97, 98, 99])
Err(Truncated)
Err(TooLarge)
Err(Truncated)
```

The four calls show a good frame, a frame that claims 9 bytes but holds 1, a length of about four billion that is refused as too large, and a buffer too short to contain a header.

## How to do it
1. Define a maximum size per message type and enforce it before allocating.
2. Use `u32::from_be_bytes` (or `from_le_bytes`, as the protocol says) on a fixed-size array; get the array with `try_into` from a slice you obtained with `get`.
3. Use `checked_add` or `checked_mul` for offsets and sizes.
4. Return a typed error; the caller decides whether to close the connection.
5. Keep reading incrementally (a streaming parser) when messages may be large, with a limit on the total.

## Common mistakes
- `Vec::with_capacity(len)` with `len` from the packet. This is the allocation attack.
- `data[4..4 + len]`, which panics on short data and can overflow in the addition.
- Casting with `as usize` on a 32-bit target after checking on a 64-bit machine; `try_from` keeps the check honest.

## Related questions
### How do I test a parser like this?
With normal unit tests for the known cases, and then with fuzzing and random inputs. See the thread on fuzzing basics.

### What about text-based formats?
The same rules hold: limit the total size, the number of items and the nesting depth before you allocate based on any count in the text.

## Sources
- Standard library, `slice::get`: https://doc.rust-lang.org/std/primitive.slice.html#method.get
- Standard library, `u32::from_be_bytes`: https://doc.rust-lang.org/std/primitive.u32.html#method.from_be_bytes
- CWE-770, "Allocation of Resources Without Limits or Throttling": https://cwe.mitre.org/data/definitions/770.html
