Slice

1

Buffers, Slices, and Vec

6 minute

In C, a binary buffer is often represented as pointer plus length:

int parse_packet(const uint8_t *buf, size_t len);

This pattern is flexible, but it carries risk. Whether buf may be null, whether len is trustworthy, whether the function mutates data, whether it stores the pointer, and when the caller may free memory are all conventions outside the type.

Rust does not remove this pattern. It splits it into more precise types:

read-only view: &[u8]
writable view: &mut [u8]
owned buffer: Vec<u8>
fixed array: [u8; N]

This article is only about binary buffers. Strings, String, and &str come later.

Read More