images/ppm
PPM (Portable Pixmap, P6) encode + decode.
Converts between a raw byte stream in the binary P6 format and a structured
Ppm value. P6 is an ASCII header (P6 width height maxval) followed by the
raw RGB raster: 3 samples per pixel, row-major, top-to-bottom. A sample is 1
byte when maxval < 256 (8-bit) and 2 bytes, most-significant byte first
(big-endian), when maxval >= 256 (16-bit). pixels always holds the raster
exactly as it appears on disk, so encode/decode round-trip byte-for-byte and
the 16-bit byte order is preserved without reinterpretation.
Scope: P6 binary only (no P3 ASCII variant). The header may carry # comment
lines between tokens, per the netpbm spec.
Types
Ppm :: struct An RGB pixmap decoded from / to be encoded as binary PPM (P6).
Fields
width: u32 height: u32 maxval: u32 Maximum sample value, in 1..=65535. < 256 ⇒ 8-bit (1 byte/sample),
otherwise 16-bit (2 bytes/sample, most-significant byte first).
pixels: u8[] Raw raster, row-major, exactly as stored on disk:
width*height*3 bytes when 8-bit, width*height*6 (MSB-first pairs)
when 16-bit.
PpmError :: struct Error raised by decode (malformed stream) or encode (inconsistent Ppm).
Fields
msg: string Functions
bytes_per_sample :: fn(maxval: u32) -> i64 Bytes per colour sample for a given maxval: 1 when maxval < 256, else 2.
Exposed so callers can index Ppm.pixels correctly for 16-bit images.
Parameters
| maxval | u32 | the image's maximum sample value. |
Returns
i64 decode :: fn(data: u8[]) -> Ppm | PpmError Decode a binary P6 PPM byte stream into a Ppm.
Validates the P6 magic, parses the width height maxval header (skipping
whitespace and # comments), consumes exactly one whitespace byte after
maxval, and checks the remaining raster length against
width * height * 3 * bytes_per_sample(maxval). pixels is an owned copy of
that raster.
Parameters
| data | u8[] | the full P6 byte stream. |
Errors
PpmErroron a bad magic, a missing/invalid header integer, a maxval outside1..=65535, a missing whitespace after maxval, or a raster whose length disagrees with the header.
encode :: fn(img: Ppm) -> u8[] | PpmError Encode a Ppm as a binary P6 byte stream (ASCII header + raw raster).
Parameters
| img | Ppm | the image to encode ; img.pixels.len() must equal width * height * 3 * bytes_per_sample(maxval). |
Returns
u8[] | PpmError the P6 byte stream.Errors
PpmErrorwhenmaxvalis outside1..=65535, or whenpixels.len()disagrees with the dimensions.