Zig 0.17.0

qrcode

On this page:

spider.qrcode

Public API — a 100% Zig, from-spec (ISO/IEC 18004:2015) QR Code encoder. No vendored C, no ported code: every module here was written from the spec text and cross-validated against it (and, for the geometrically fiddly parts, against an instrumented reference oracle) — see each submodule's doc comment for what was verified and how.

Scope: QR Code versions 1-40, all 4 error correction levels (L/M/Q/H), Numeric/Alphanumeric/Byte modes. Kanji mode and Micro QR are out of scope (see project scope notes).

spider.qrcode.Ecc

zig
pub const Ecc = enum(u2) { low = 0, medium = 1, quartile = 2, high = 3 }

The error correction level: how much of a damaged or covered symbol a scanner can still recover. .low (about 7%), .medium (15%), .quartile (25%), .high (30%). A higher level leaves less room for data in the same version.

spider.qrcode.QR

zig
pub const QR = struct

An encoded QR Code: a square of size x size modules, read with getModule. Drawing it (SVG, PNG, table cells) is up to the app.

zig
var qr = try spider.qrcode.QR.encode(allocator, "HELLO WORLD", 1, .medium);
defer qr.deinit();
// qr.size == 21; qr.getModule(x, y) is true for a dark module

encode takes the version; encodeAuto picks the smallest one the text fits in.

Fields

  • allocator: std.mem.Allocator: The allocator given to encode; deinit frees with it.
  • version: u8: The version asked for, 1 to 40.
  • ecc: Ecc: The error correction level asked for.
  • mask: u3: The mask pattern (0 to 7) the encoder chose.
  • size: u16: Modules per side: version * 4 + 17 (21 for version 1, 177 for version 40).
  • modules: []u8: The modules, one bit each, row by row, most significant bit first. Read them with getModule.

qrcode.QR.encode

zig
pub fn encode(allocator: std.mem.Allocator, text: []const u8, version: u8, ecc: Ecc) !QR

Encodes text as a QR Code of the given version (1-40) and error correction level. Picks the tightest applicable mode (numeric/alphanumeric/byte) automatically, one mode for the whole text; in byte mode the bytes are stored as given.

The result owns its modules, allocated with allocator: free it with deinit. Returns error.DataTooLarge if text does not fit the data capacity of that version and level, error.InvalidVersion for a version outside 1-40, or error.OutOfMemory.

qrcode.QR.encodeAuto

zig
pub fn encodeAuto(allocator: std.mem.Allocator, text: []const u8, ecc: Ecc) !QR

encode with the smallest version (1 to 40) that holds text at this error correction level. error.DataTooLarge when not even version 40 does.

zig
var qr = try spider.qrcode.QR.encodeAuto(c.arena, link, .medium);

qrcode.QR.deinit

zig
pub fn deinit(self: QR) void

Frees the modules.

qrcode.QR.getModule

zig
pub fn getModule(self: QR, x: u16, y: u16) bool

True if the module at (x, y) is dark. Out-of-range coordinates return false (matches matrix.Grid.getModule's convention).