Bytes
Borrowed read-only byte views in std.bytes.
std.bytes provides Bytes, a borrowed read-only byte view for text values
and byte slices. Creating a view does not allocate. Bytes is the boundary
between text and arbitrary bytes: byte views do not promise UTF-8 validity and
may contain NUL bytes.
import std.bytes;
fn main() {
let literal = bytes.Bytes("hello");
assert literal.length == 5;
assert literal[0] == 104 as u8;
}
When arbitrary bytes are needed, start from byte storage or a byte slice. Text
literals and String values cannot contain embedded NUL bytes in 0.0.0-dev.
import std.bytes;
import std.mem;
fn check(data: bytes.Bytes) {
assert data.length == 2;
assert data[0] == 0 as u8;
assert data[1] == 65 as u8;
}
fn main() {
let raw = [0 as u8, 65 as u8];
check(bytes.Bytes(mem.slice_of<u8>(raw.ptr, raw.length)));
}
Borrowed views remain valid while the source value is alive and has not been mutated in a way that changes its storage.
| Item | Purpose |
|---|---|
bytes.Bytes(value: str) | Borrow bytes from a string literal or str. |
bytes.Bytes(value: const &String) | Borrow bytes from an owned String. |
bytes.Bytes(value: [u8]) | Borrow bytes from a byte slice. |
When starting from fixed array storage, use std.mem.slice_of<u8>(ptr, len) to
create the [u8] slice passed to bytes.Bytes. The resulting Bytes view
borrows the same backing storage.
Functions with bytes.Bytes parameters can usually be documented with that one
canonical signature. Callers may pass string literals, String, borrowed
String, existing Bytes, or [u8] slices directly; the compiler creates a
borrowed, zero-copy view for the duration of the call.
import std.hash;
fn main() {
assert hash.crc32.sum("hello") == 0x3610a686;
}
The conversion is call-only. Stored or returned Bytes views remain explicit:
use bytes.Bytes(...), text.utf8(), stream.bytes(), or another API that
returns Bytes.
Bytes[index] and Bytes.slice(start, length) use byte offsets and may split a
UTF-8 sequence. Validate or decode with std.unicode.utf8 before treating a
byte view as text.
| Member | Purpose |
|---|---|
length | Number of bytes in the view. |
is_empty() | Return true when the view is empty. |
slice(start, length) | Return a bounded sub-view. |
ptr() | Borrow a read-only pointer to the first byte. |
[] | Read one byte by index. |
std.io.MemoryStream owns mutable bytes. To borrow its contents as Bytes,
use stream.bytes(). The view is valid until the stream is mutated or dropped.