# zig-wuffs
Zig bindings to [WUFFS](https://github.com/google/wuffs) — Google's "Wrangling
Untrusted File Formats Safely", a language for writing image decoders that
cannot index out of bounds, overflow an integer or leak memory, and that proves
it when it compiles rather than discovering it when it runs. Decoding somebody
else's PNG is the classic way to be handed a shell, and WUFFS is the answer to
it; this is that answer with a Zig-shaped door on the front.
```zig
const wuffs = @import("wuffs");
const image = try wuffs.png.decode(allocator, bytes);
defer allocator.free(image.data);
std.debug.print("{d}x{d}\n", .{ image.width, image.height });
```
Five decoders and a pixel swizzler:
| | |
| --- | --- |
| `wuffs.png` | PNG |
| `wuffs.jpeg` | JPEG |
| `wuffs.gif` | GIF |
| `wuffs.bmp` | BMP — [all of it but the embedded ones](#bmp-and-the-two-that-are-not-bmps) |
| `wuffs.netpbm` | Netpbm — the [binary variants only](#netpbm-is-only-half-a-format) |
| `wuffs.swizzle` | grayscale, grayscale-and-alpha and RGB into premultiplied RGBA |
Every decoder has the same signature and returns the same thing:
```zig
pub fn decode(alloc: Allocator, data: []const u8) Error!Image
```
where `Image` is a width, a height, and `data`: interleaved RGBA, alpha
premultiplied, four bytes per pixel, owned by the caller and freed with the
allocator it was decoded with. Nothing here holds a decoder open or keeps state
between calls — one buffer in, one image out.
The [API documentation](https://jeff.jcollie.page/zig-wuffs/) is generated from
the doc comments, which carry the explanations that do not fit here — why the
decoder structs are allocated the way they are, what each WUFFS module costs to
enable, which BMP and Netpbm variants exist.
Requires Zig 0.17.0. The `zig-0.16` branch, tagged `v0.1.0`, is the last that
builds with Zig 0.16 and gets critical fixes only.
## Adding it to a project
```console
$ zig fetch --save git+https://git.jcollie.dev/jeff/zig-wuffs.git
```
Then in `build.zig`:
```zig
const wuffs = b.dependency("wuffs", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("wuffs", wuffs.module("wuffs"));
```
The module compiles WUFFS' single-file C release itself, so there is nothing
else to install and no system library to find. `target` and `optimize` have to
be passed through, because the C source is built for the target the importing
program is built for.
The C declarations come from
[translate-c](https://codeberg.org/ziglang/translate-c) as a package, its
`zig-0.17.x` branch, which translates with
[Aro](https://codeberg.org/ziglang/arocc) rather than Clang. Zig 0.17 has no
C translation of its own any more, so there is no `@cImport` to fall back on.
The cost is that a first build compiles Aro and the translate-c tool before it
compiles anything of yours.
## Without libc
WUFFS wants a few declarations from `stdlib.h` and `string.h` and nothing else,
so `include/` supplies minimal versions of both; and it wants `calloc` and
`free` for the `wuffs_*__decoder__alloc` constructors it generates, which
`src/c_allocator.zig` supplies in Zig. So the package builds *and links* for
targets that have no libc at all. It links libc where there is one to link, and
`-Dlink-libc=false` forces it off anywhere:
```console
$ zig build check # links a wasm32-freestanding program
$ zig build test -Dlink-libc=false
```
`malloc`, `calloc`, `realloc` and `free` are exported under their C names only
when this module is built without libc, so that they cannot collide with the
real ones. Take that as a rule rather than a detail: **do not build this module
without libc inside a program that links libc.** The link would succeed — a
definition in an object file wins over one in an archive, which is how a
program swaps in jemalloc — and these would quietly become the whole program's
allocator.
They allocate from `wuffs.c_allocator.allocator`. On wasm that is
`std.heap.wasm_allocator` and needs nothing set up; on any other target with no
libc there is no heap a library may assume, so it starts as null and every
allocation fails — which those constructors report by returning NULL, their
ordinary out-of-memory answer. Set it before any call that could allocate:
```zig
wuffs.c_allocator.allocator = my_allocator;
```
None of this is on the path the decoders here take. `decode` allocates with the
Zig allocator you hand it and never reaches the C functions; the exports exist
so that WUFFS' own C code has something to call.
The other thing to know is that the decoders log through `std.log` when WUFFS
returns an error, and std's default log implementation writes to stderr, which
freestanding has not got. A freestanding program has to say what logging means
by setting `std_options.logFn` — `tools/freestanding.zig` is a small example
that says it means nothing.
That program is what `zig build check` links, and it is a program rather than a
library on purpose: what goes wrong without libc is a link error, and a static
library never links.
## BMP, and the two that are not BMPs
WUFFS' BMP decoder covers the format as it is actually met: uncompressed
`BI_RGB` at 1, 2, 4, 8, 16, 24 and 32 bits per pixel, the run-length encoded
`BI_RLE8` and `BI_RLE4`, and `BI_BITFIELDS` at 16 and 32 bits per pixel with
arbitrary channel masks. It reads the 12-byte BITMAPCOREHEADER and every later
header up to the 124-byte BITMAPV5HEADER, so an alpha channel declared by a V4
or V5 header is honoured — and since this library hands back premultiplied
RGBA, a half-transparent pixel comes out multiplied. Rows may run either way
up.
The two it does not decode are the ones whose pixel data is not pixels:
`BI_JPEG` and `BI_PNG`, where a BMP header is wrapped around a whole JPEG or
PNG file. WUFFS answers those by asking to be redirected to the other decoder
rather than by decoding them, and `decode` takes one buffer in and gives one
image out with nowhere to put that request, so such a file is an
`error.WuffsError` with `@base: I/O redirect` logged. They exist for print
spoolers and scanner drivers; nothing that calls itself an image editor writes
one.
## Netpbm is only half a format
WUFFS' netpbm decoder accepts `P5` and `P6` — the binary grayscale and binary
RGB variants — and refuses everything else with `unsupported Netpbm file`. The
plain ASCII forms `P1`, `P2` and `P3`, where the samples are written out as
decimal numbers, are not implemented, and neither is the `P7` PAM container.
This is worth knowing because the ASCII forms are what a lot of tooling writes
by default. `src/netpbm.zig` has a test that pins the `P3` rejection, so if
WUFFS ever grows support for it that test will fail and say so.
## Where this came from
The initial commit was a lift of `pkg/wuffs` out of
[Ghostty](https://github.com/ghostty-org/ghostty), which is MIT licensed and
whose copyright is retained on every file that descends from it. Ghostty needed
PNG and JPEG for its terminal graphics; this is the same code pulled out into a
package of its own, updated to Zig 0.17, and with the decoders factored into
one implementation in `src/decoder.zig` that the format modules name by WUFFS
module. GIF, Netpbm and BMP came after that refactor, since by then they cost
a wrapper each.
The comment in `src/decoder.zig` about allocating the decoder structs with the
Zig allocator rather than on the stack is Ghostty's, and is still the reason
the code is shaped the way it is: the generated structs are `extern` as far as
Zig is concerned, WUFFS' own constructors use C `malloc`, and this gets an
arbitrary allocator back into the picture.
## Building and testing
```console
$ nix develop
$ zig build test # unit tests, against 1x1 fixtures
$ zig build check # compile everything without running it
$ zig fmt --check .
$ reuse lint
```
The tests decode a one-pixel black image and a one-pixel white one in each
format and check the four bytes that come back, which is a small claim but it
is the whole path: the C compiles, the struct sizes agree, the status codes are
read correctly and the pixel format conversion lands where it should. BMP gets
a few more, because it is several formats wearing one extension: a palette, a
run-length encoded row, an alpha channel that has to be premultiplied on the
way out, and the embedded-JPEG case that is refused.
`zig build check` exists because this project installs no artifact. Without it
the only thing the build graph ever compiled was the test binary, which is a
separate copy of the module, and an error reachable only from the published
module could have gone unnoticed.
The fixtures come from
[pixels](https://github.com/make-github-pseudonymous-again/pixels), fetched by
the package manager. Its PPM files are plain ASCII `P3` and so cannot be used —
see above — which is why `src/netpbm.zig` carries binary test data of its own
instead, and there are no BMPs in it at all, which is why `src/bmp.zig` builds
its own headers byte by byte.
## The API documentation
, rebuilt from `main` on every push.
```console
$ zig build docs-serve # then open http://127.0.0.1:8000/
$ zig build docs # or just build it, into zig-out/docs
```
It has to be served rather than opened. What Zig emits is not a page but a
program: a WebAssembly viewer that fetches the source of everything it shows
out of a tar file beside it, and a browser refuses to fetch anything from a
`file://` page. That is the same reason `zig std` runs a server rather than
opening a file. `tools/docs_server.zig` is that server — one directory, one
person, the loopback interface, and nothing else. `-Ddocs-port` moves it.
## Building it with Nix
```console
$ nix build .#zig-wuffs # builds and runs the tests in a sandbox
$ nix develop # the toolchain this is developed with
```
A Nix build has no network and the Zig package manager wants one, so the
dependencies are made available through `build.zig.zon.nix`, generated from the
manifest by [zon2nix](https://github.com/jcollie/zon2nix) and handed to Zig as
a system package directory. Regenerate it whenever `build.zig.zon` changes —
that is the whole of adding, removing or updating a dependency, since every
hash then comes from the manifest rather than being kept by hand:
```console
$ nix develop -c zon2nix --17 --nix=build.zig.zon.nix build.zig.zon
```
zon2nix is an input of the flake rather than something fetched on the spot, and
the devshell wraps it with this flake's Zig on its `PATH`. It shells out to
`zig env` to read the manifest, and with no Zig to find it prints `unable to
execute zig` and leaves the old file untouched — a regeneration that silently
did nothing looks exactly like one that found no changes.
`--system` forbids fetching outright rather than merely offering the directory,
so a dependency missing from `build.zig.zon.nix` is a build error naming the
package. The package runs the tests too, which is the strongest thing that can
be said for the generated file being complete.
What the package installs is `lib/libwuffs.a`. That is not really what this is
for — a Zig consumer takes the module and compiles it into their own program —
but building it is the only way `zig build` compiles the published module at
all, and a package with nothing to install is not one Nix can express.
## Where this lives
The repository lives in three places that carry the same history. The Forgejo
instance at is the web-visible one:
```console
$ git clone https://git.jcollie.dev/jeff/zig-wuffs.git
```
it is mirrored on Tangled at , and
it is also on the Radicle network, where the repository's identifier is
```
rad:z3yf1ZuYoKMfbb6oiFcuJoyUdLWcA
```
and `rad clone rad:z3yf1ZuYoKMfbb6oiFcuJoyUdLWcA` fetches it from any node that
seeds it. Any of the three is the whole project.
## Licence
MIT. The project follows the [REUSE](https://reuse.software/) specification;
run `reuse lint` in a checkout to verify.
Nothing is vendored here; the package manager fetches all three dependencies
from `build.zig.zon`. WUFFS comes from
[the C release mirror](https://github.com/google/wuffs-mirror-release-c) and is
dual licensed Apache-2.0 or MIT;
[translate-c](https://codeberg.org/ziglang/translate-c) and the
[pixels](https://github.com/make-github-pseudonymous-again/pixels) fixtures are
MIT.