prelude.Bytes

Part of prelude.

let Bytes.empty (): Bytes

No bytes.

let Bytes.len (b: Bytes): Int

How many bytes.

let Bytes.is_empty (b: Bytes): Bool

Whether there are no bytes.

let Bytes.from_string (s: String): Bytes

The string's UTF-8 bytes. The same as String.as_bytes, named for a caller thinking in bytes.

let Bytes.is_utf8 (b: Bytes): Bool

Whether these bytes are valid UTF-8, without building a string.

let Bytes.as_string (b: Bytes): Result[String, String]

Decodes UTF-8 into a string.

Err when the bytes are not valid UTF-8 — which is why this is a Result and String.as_bytes is not. Bytes arrive from files and sockets, and not all of them are text.

let Bytes.slice (b: Bytes) (start: Int) (end: Int): Bytes

BYTE indices, throughout. Bytes.slice can and will split a multi-byte character in half, which is the operation String deliberately does not offer, and the reason a program reaching for bytes reached for them.

Clamped rather than aborting, matching Array.slice. Bytes from start up to but not including end, with bounds clamped. A slice can split a multi-byte character, so the result is not guaranteed to be valid UTF-8.

let Bytes.concat (a: Bytes) (b: Bytes): Bytes

The two runs of bytes, joined.

let Bytes.at (b: Bytes) (i: Int): Option[Int]

None rather than an abort for an out-of-range index: a byte buffer is usually being walked by a parser that does not know how long it is yet, and Option is how the rest of this prelude says "nothing there" (Array.first, Map.get). The byte at i as a number 0-255, or None when out of range.

let Bytes.from_array (xs: Array[Int]): Bytes

Each element is one byte, 0-255. Values outside that range are masked to their low 8 bits rather than rejected. from_array is a construction helper, and a Result here would put error handling in front of every literal buffer. Bytes from numbers. Values outside 0-255 are truncated to their low eight bits.

let Bytes.from_cstr (c: CStr) (len: Int): Bytes

Copies len bytes from a C pointer.

For extern \"C\" results only, and unsafe for the obvious reason: nothing checks that the pointer is valid or that len is right.

let Bytes.to_array (b: Bytes): Array[Int]

The bytes as numbers 0-255.

let Bytes.to_hex (b: Bytes): String

Lowercase hex, two characters per byte. Encoding.hex_decode reads it back.