Bitstrings
Build and parse a length-prefixed packet. Binary contains whole bytes;
Bitstring also permits values whose length is not a multiple of eight.
Segment sizes describe the wire layout, not a range check on the input.
A length-prefixed packet
Section titled “A length-prefixed packet”The first two bytes give the payload length. encode rejects payloads that
would overflow that header; decode accepts exactly the declared number of
bytes, rejecting truncated packets and extra trailing bytes.
mod bitstrings
@moduledoc """Build and parse a length-prefixed packet. `Binary` contains whole bytes;`Bitstring` also permits values whose length is not a multiple of eight.Segment sizes describe the wire layout, not a range check on the input."""
pub fn encode(payload: Binary) -> Result<Binary, :too_large> { size = byte_size(payload) if size <= 65_535 { Ok(<<size::16, payload::binary>>) } else { Error(:too_large) }}
pub fn decode(packet: Binary) -> Result<Binary, :invalid_packet> { case packet { <<size::16, payload::binary-size(size)>> -> Ok(payload) _ -> Error(:invalid_packet) }}
pub fn flags(urgent: Boolean, compressed: Boolean) -> Bitstring { first = if urgent { 1 } else { 0 } second = if compressed { 1 } else { 0 } <<first::1, second::1>>}Integer segments default to unsigned, big-endian bytes. size::16 writes
sixteen bits; payload::binary appends all payload bytes. Integer encoding
keeps the low bits, so the explicit length check prevents a wrapped header.
In a pattern, binary-size(size) counts bytes and can use a previous segment’s
binding. The fallback handles malformed packets. encode("hi") produces
<<0, 2, "hi">>, and decode returns Ok("hi").
Bits, bytes, and text
Section titled “Bits, bytes, and text”flags(true, false) produces two bits, <<1::1, 0::1>>. It is a Bitstring
but not a byte-aligned Binary. bit_size counts bits; byte_size counts
bytes. A String is a UTF-8 Binary, but arbitrary bytes need validation
through gale_std.string.from_binary before use as text.
A bits-size(n) pattern counts bits instead of bytes. Only the final binary
or bitstring segment may omit its size. See matching for
patterns and errors for UTF-8 validation.