.nib std
nib 0.3.0

module always in scope

Bytes

A sequence of raw bytes, written b"…" — what a socket or a file carries before anyone has decided it is text.

Bytes is a byte string that makes no claim about encoding. A String is text; a Bytes value is what arrives from a socket, and the only way between the two is a named call — Bytes.from_string or Bytes.to_string — so the place where data becomes text is always visible in the code.

A literal is written b"…". Each byte is read as a number from 0 to 255. A short value prints as its bytes in hex, b<6869>; a longer one prints only its length.

let greeting = b"hi";
(greeting, Bytes.length(greeting), Bytes.from_string("a much longer buffer"))
(b<6869>, 2, b<20 bytes>)

Bytes is immutable: Bytes.set answers a new value and leaves its argument as it was. It also has no equality — b"a" == b"a" is refused by the checker, a byte literal cannot be a pattern, and a Bytes cannot be a Map key or a Set member. To compare or key on the contents, convert with Bytes.to_string first.

let cat = b"cat";
let bat = Bytes.set(cat, 0, 98);
Bytes.to_string(cat) == Bytes.to_string(bat)
false

Functions

funclength
func length :: Bytes -> Int

The number of bytes.

(Bytes.length(b"nib"), Bytes.length(b""))
(3, 0)
funcget
func get :: Bytes, Int -> Int raises Err.IndexOutOfRange

The byte at index i, counting from 0, as an Int from 0 to 255. Raises Err.IndexOutOfRange when i is negative or not less than Bytes.length.

let b = b"hi";
(Bytes.get(b, 0), Bytes.get(b, 1))
(104, 105)
try Bytes.get(b"ab", 2)
rescue Err.IndexOutOfRange(i, msg) => -1 end
-1
funcset
func set :: Bytes, Int, Int -> Bytes raises Err.IndexOutOfRange, Err.OutOfRange

A new Bytes with the byte at index i replaced by x. The value given is not changed. Raises Err.IndexOutOfRange when i is outside the value — set replaces, it never grows — and Err.OutOfRange when x is not between 0 and 255, rather than silently truncating it.

let cat = b"cat";
let bat = Bytes.set(cat, 0, 98);
(Bytes.to_string(cat), Bytes.to_string(bat))
("cat", "bat")
try Bytes.to_string(Bytes.set(b"cat", 0, 256))
rescue Err.OutOfRange(msg) => msg end
Bytes.set writes a byte, which is 0 to 255, and 256 is neither
func from_string :: String -> Bytes

The bytes of a String, in a fresh value. A character outside ASCII becomes the several bytes of its UTF-8 encoding.

let b = Bytes.from_string("é!");
(Bytes.length(b), Bytes.get(b, 0), Bytes.get(b, 1), Bytes.get(b, 2))
(3, 195, 169, 33)
func to_string :: Bytes -> String

The same bytes as a String. This never fails and does not validate anything: a String is a sequence of bytes too, so whatever the value holds is carried across unchanged.

Bytes.to_string(b"hello")
hello