Skip to content

bytes

Helpers for byte slices and sizes that the standard library does not provide.

Reading integers at an offset without panicking, a ByteReader cursor for binary formats (fixed-size values, LEB128 varints, zigzag, NUL-terminated strings), a byte-slice search, a constant-time comparison, XOR, human-readable sizes (1.5 KiB) in both directions, and the media type of an image from its first bytes or of a file from its extension.

Cargo feature bytes (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features bytes

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.11", default-features = false, features = ["bytes"] }

Import path: helpers4::bytes.

ItemWhat it does
ByteReaderA cursor over a byte slice, for decoding binary formats: fixed-size integers and floats, LEB128 varints (signed ones zigzag-encoded), byte runs and NUL-terminated strings.
constant_time_eqCompares two byte slices without stopping at the first difference.
EndianThe byte order of a multi-byte integer.
findThe index of the first occurrence of needle in haystack.
format_sizeFormats a number of bytes with a binary unit and at most one decimal, such as "1.5 KiB".
media_type_ofFinds the media type of an image from its first bytes (its magic number), whatever its name says: PNG, JPEG, GIF, WebP, AVIF and SVG.
media_type_of_pathFinds the media type of a file from the extension of its path or URL: images, fonts, web documents, scripts and styles, data, audio and video.
parse_sizeParses a human-written size such as "1.5 KiB", "10MB" or "512" into a number of bytes.
read_u16Reads a u16 from bytes at offset, in the given byte order.
read_u32Reads a u32 from bytes at offset, in the given byte order.
read_u64Reads a u64 from bytes at offset, in the given byte order.
xorThe bytewise XOR of two slices of the same length.
zigzag_decodeReverses zigzag_encode: 0, 1, 2, 3, 4, ... become 0, -1, 1, -2, 2, ....
zigzag_encodeMaps a signed integer to an unsigned one so that small magnitudes stay small: 0, -1, 1, -2, 2, ... become 0, 1, 2, 3, 4, ....

Documented on the page of the helper that returns them.

TypeReturned by
ParseSizeErrorparse_size