Skip to content

std.bytes

Safe helpers around the compiler-known ByteBuf storage.

std.bytes is a small set of safe helpers over ByteBuf, the compiler-known owned byte buffer. ByteBuf itself has a method surface for the common in-place operations; std.bytes adds construction and bulk-copy helpers that read more clearly at the call site.

ByteBuf is an owned, growable byte buffer with deterministic drop. It is built in to the compiler (not declared in source) and exposes:

ByteBuf.new() -> ByteBuf
b.len # -> usize
b.push(byte: u8) -> None
b.push_bytes(src: view [u8]) -> None
b.reserve(additional: usize) -> None
b.clear() -> None
b.truncate(len: usize) -> None
b.as_slice() -> view [u8]
b.as_mut_slice() -> mut view [u8]

Structural mutations (push, push_bytes, reserve, clear, truncate) may reallocate, so they conflict with any live borrowed view of the same buffer until that view’s last use.

import std.bytes as bytes
export def with_capacity(capacity: usize) -> ByteBuf
export def filled(len: usize, value: u8) -> ByteBuf
export def zeroed(len: usize) -> ByteBuf
export def from_slice(src: view [u8]) -> ByteBuf
export def append(dst: mut view ByteBuf, src: view [u8]) -> None
export def clear(buf: mut view ByteBuf) -> None
export def truncate(buf: mut view ByteBuf, len: usize) -> None
export def resize_zeroed(buf: mut view ByteBuf, len: usize) -> None
export def copy_from(dst: mut view [u8], src: view [u8]) -> usize
  • with_capacity(n): an empty buffer that has reserved room for n bytes.
  • filled(len, value) / zeroed(len): a buffer of len bytes set to value (or 0).
  • from_slice(src): a fresh buffer holding a copy of src.
  • append(dst, src): append src to dst (a thin wrapper over push_bytes).
  • clear / truncate: drop the tail while retaining capacity.
  • resize_zeroed(buf, len): grow with zero bytes or truncate so the buffer is exactly len long.
  • copy_from(dst, src): copy min(dst.len, src.len) bytes into dst and return how many were copied. Neither side reallocates, so this works on any mutable byte slice, not just ByteBuf.
import std.bytes as bytes
import std.io as io
def main() -> None:
var buf: ByteBuf = bytes.with_capacity(16)
bytes.append(buf, b"GET / HTTP/1.1\r\n")
bytes.append(buf, b"\r\n")
io.stdout_write_bytes(buf.as_slice())
return None