Something went wrong. Try again.
Parse/validate ISBNs in Zig
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie// SPDX-License-Identifier: MIT
//! Parsing, validation, and conversion of International Standard Book//! Numbers (ISBNs) in both the 10-digit and 13-digit formats.//!//! ISO 2108 is not freely available; the check digit algorithms and the//! 978/979 prefixes are documented in the ISBN Users' Manual.//! https://www.iso.org/standard/65483.html//! https://www.isbn-international.org/content/isbn-users-manual
const std = @import("std");const options = @import("options");const ranges = @import("ranges.zig");
/// An International Standard Book Number in either the legacy 10-digit/// format or the current 13-digit (EAN-13) format.////// The digits are stored as ASCII characters (`'0'`–`'9'`, plus `'X'` as/// the final check digit of an ISBN-10), without separators.pub const ISBN = union(enum) { /// A 10-digit ISBN, used for books published before 2007. @"10": [10]u8, /// A 13-digit ISBN, prefixed with `978` or `979`. @"13": [13]u8,
/// Parses an ISBN from text, accepting the 10- and 13-digit formats /// with optional `-` separators anywhere in the string. /// /// Returns `error.ParseError` if `s` contains characters other than /// digits, `-`, or `X` (`X` is only accepted as the last digit of an /// ISBN-10), or if the number of digits is not exactly 10 or 13. /// Returns `error.InvalidCheckDigit` if the final digit does not match /// the checksum computed from the preceding digits. pub fn parse(s: []const u8) !ISBN { var buf: [13]u8 = undefined; var n: usize = 0; for (s) |c| { switch (c) { '-' => {}, '0'...'9', 'X' => { // Checked here rather than at the top of the loop so // that a separator past the last digit is treated the // same whatever the length: `-` is a separator // anywhere, and only digits can overrun `buf`. if (n >= 13) return error.ParseError; if (c == 'X' and n != 9) return error.ParseError; buf[n] = c; n += 1; }, else => return error.ParseError, } } switch (n) { 10 => { var tmp: ISBN = .{ .@"10" = undefined, }; @memcpy(&tmp.@"10", buf[0..10]); const c = tmp.computeCheckDigit(); if (tmp.@"10"[9] != c) return error.InvalidCheckDigit; return tmp; }, 13 => { // 'X' is only valid as the check digit of an ISBN-10; the // scan loop can only have accepted it at index 9. if (buf[9] == 'X') return error.ParseError; var tmp: ISBN = .{ .@"13" = undefined, }; @memcpy(&tmp.@"13", buf[0..13]); const c = tmp.computeCheckDigit(); if (tmp.@"13"[12] != c) return error.InvalidCheckDigit; return tmp; }, else => return error.ParseError, } }
/// Computes the check digit from the ISBN's leading digits, ignoring /// the stored final digit. /// /// The result is returned as an ASCII character: `'0'`–`'9'`, or `'X'` /// (representing 10) for an ISBN-10. When the `simd` build option is /// enabled, the checksum is computed with vector operations. pub fn computeCheckDigit(self: *const ISBN) u8 { return self.computeCheckDigitWith(options.simd); }
/// Computes the check digit with an explicitly chosen implementation: /// vectorized when `simd` is true, scalar otherwise. Exposed so the /// two implementations can be benchmarked against each other; most /// callers should use `computeCheckDigit`, which follows the `simd` /// build option. pub fn computeCheckDigitWith(self: *const ISBN, comptime simd: bool) u8 { switch (self.*) { .@"10" => |buf| { std.debug.assert(buf.len == 10);
if (simd) { // The lanes are widened to u16 because the weighted // sum can reach 486, which would wrap in u8, and // padded to 16 so the vector maps to real SIMD // registers. const factors = comptime factors: { var tmp: [16]u16 = @splat(0); for (0..9) |i| tmp[i] = 10 - i; const x = @as(@Vector(16, u16), tmp); break :factors x; }; var padded: [16]u8 = @splat('0'); padded[0..10].* = buf; const chars: @Vector(16, u8) = padded; const digits: @Vector(16, u16) = @intCast(chars -% @as(@Vector(16, u8), @splat('0'))); const sum: usize = @reduce(.Add, digits * factors); return switch (@mod(11 - @mod(sum, 11), 11)) { 10 => 'X', 0...9 => |d| '0' + @as(u8, @intCast(d)), else => unreachable, }; }
const factors = comptime factors: { var factors: [9]u8 = undefined; for (0..9) |i| factors[i] = 10 - i; const x = factors; break :factors x; }; std.debug.assert(factors.len == 9); var sum: usize = 0; for (buf[0..9], factors) |char, factor| { std.debug.assert(factor >= 2 and factor <= 10); std.debug.assert(char >= '0' and char <= '9'); sum += factor * (char - '0'); } return switch (@mod(11 - @mod(sum, 11), 11)) { 10 => 'X', 0...9 => |d| '0' + @as(u8, @intCast(d)), else => unreachable, }; }, .@"13" => |buf| { std.debug.assert(buf.len == 13);
if (simd) { // Widened and padded like the ISBN-10 path; the // maximum weighted sum here is 216, but a 13-lane // vector produces poor scalarized code. const factors = comptime factors: { var tmp: [16]u16 = @splat(0); for (0..12) |i| tmp[i] = 1 + (2 * (i & 0x1)); const x = @as(@Vector(16, u16), tmp); break :factors x; }; var padded: [16]u8 = @splat('0'); padded[0..13].* = buf; const chars: @Vector(16, u8) = padded; const digits: @Vector(16, u16) = @intCast(chars -% @as(@Vector(16, u8), @splat('0'))); const sum: usize = @reduce(.Add, digits * factors); return switch (10 - (@mod(sum, 10))) { 10 => '0', 1...9 => |d| '0' + @as(u8, @intCast(d)), else => unreachable, }; }
const factors = comptime factors: { var tmp: [12]u8 = undefined; for (0..12) |i| tmp[i] = 1 + (2 * (i & 0x1)); const factors = tmp; break :factors factors; }; std.debug.assert(factors.len == 12); std.debug.assert(buf.len == 13); var sum: usize = 0; for (buf[0..12], factors) |char, factor| { std.debug.assert(factor == 1 or factor == 3); std.debug.assert(char >= '0' and char <= '9'); sum += factor * (char - '0'); } return switch (10 - (@mod(sum, 10))) { 10 => '0', 1...9 => |d| '0' + @as(u8, @intCast(d)), else => unreachable, }; }, } }
/// Converts an ISBN-10 to its equivalent ISBN-13 by prepending the /// `978` prefix and recomputing the check digit. An ISBN-13 is /// returned unchanged. pub fn upgrade(self: *const ISBN) ISBN { switch (self.*) { .@"10" => |v| { var tmp: ISBN = .{ .@"13" = undefined, }; @memcpy(tmp.@"13"[0..3], "978"); @memcpy(tmp.@"13"[3..13], v[0..10]); tmp.@"13"[12] = tmp.computeCheckDigit(); return tmp; }, .@"13" => return self.*, } }
/// The maximum length of a hyphenated ISBN: 13 digits plus 4 hyphens. pub const max_hyphenated_len = 17;
pub const HyphenateError = error{ /// The ISBN does not fall in a range assigned by the /// International ISBN Agency, so the element boundaries are /// unknown. UnknownRange, };
/// Writes the canonically hyphenated form into `out` and returns the /// written slice: prefix, registration group, registrant, and /// publication elements separated by `-` (the prefix element only for /// an ISBN-13), followed by the check digit. /// /// The element boundaries come from the International ISBN Agency's /// range data embedded at build time (see `tools/generate_ranges.zig`); /// returns `error.UnknownRange` for an ISBN outside the assigned /// ranges. pub fn hyphenate(self: *const ISBN, out: *[max_hyphenated_len]u8) HyphenateError![]const u8 { switch (self.*) { .@"10" => |buf| return writeHyphenated(out, null, buf[0..9], buf[9]), .@"13" => |buf| return writeHyphenated(out, buf[0..3], buf[3..12], buf[12]), } }
/// Splits `digits` (registration group + registrant + publication) /// per the range data and writes `prefix-group-registrant-publication-check` /// (without the prefix element when `prefix` is null, for ISBN-10s, /// which all live in the 978 prefix). fn writeHyphenated( out: *[max_hyphenated_len]u8, prefix: ?*const [3]u8, digits: *const [9]u8, check: u8, ) HyphenateError![]const u8 { const ean: u16 = if (prefix) |p| ean: { var v: u16 = 0; for (p) |c| v = v * 10 + (c - '0'); break :ean v; } else 978;
const group = for (ranges.groups) |*g| { if (g.ean == ean and std.mem.startsWith(u8, digits, g.digits)) break g; } else return error.UnknownRange; const group_len = group.digits.len;
// The registrant length is determined by the value of the seven // digits that follow the group, padded with zeros on the right. var v: u32 = 0; for (0..7) |i| { const idx = group_len + i; const d: u32 = if (idx < 9) digits[idx] - '0' else 0; v = v * 10 + d; } const registrant_len = for (group.rules) |r| { if (v >= r.min and v <= r.max) break r.len; } else 0; if (registrant_len == 0 or group_len + registrant_len >= 9) return error.UnknownRange;
var n: usize = 0; if (prefix) |p| { @memcpy(out[n..][0..3], p); n += 3; out[n] = '-'; n += 1; } @memcpy(out[n..][0..group_len], group.digits); n += group_len; out[n] = '-'; n += 1; @memcpy(out[n..][0..registrant_len], digits[group_len..][0..registrant_len]); n += registrant_len; out[n] = '-'; n += 1; const publication_len = 9 - group_len - registrant_len; @memcpy(out[n..][0..publication_len], digits[group_len + registrant_len ..][0..publication_len]); n += publication_len; out[n] = '-'; n += 1; out[n] = check; n += 1; return out[0..n]; }
/// Formats the ISBN for `{f}`: hyphenated when it falls in a range /// assigned by the International ISBN Agency, as bare digits /// otherwise. pub fn format(self: *const ISBN, writer: *std.Io.Writer) std.Io.Writer.Error!void { var buf: [max_hyphenated_len]u8 = undefined; if (self.hyphenate(&buf)) |s| { try writer.writeAll(s); } else |_| { try writer.writeAll(switch (self.*) { .@"10" => |*b| b[0..], .@"13" => |*b| b[0..], }); } }
/// Returns true if the two ISBNs identify the same book. ISBNs of /// different formats are compared by upgrading both to ISBN-13, so an /// ISBN-10 is equal to its 13-digit equivalent. pub fn eql(self: *const ISBN, other: *const ISBN) bool { if (self.* == .@"10" and other.* == .@"10") { return std.mem.eql(u8, &self.@"10", &other.@"10"); } if (self.* == .@"13" and other.* == .@"13") { return std.mem.eql(u8, &self.@"13", &other.@"13"); } const a = self.upgrade(); const b = other.upgrade(); return std.mem.eql(u8, &a.@"13", &b.@"13"); }};
test "10 1" { const x: ISBN = try .parse("0-306-40615-2"); try std.testing.expect(x == .@"10"); try std.testing.expectEqualSlices(u8, "0306406152", &x.@"10"); const c = x.computeCheckDigit(); try std.testing.expectEqual('2', c);}
test "10 2" { const x: ISBN = try .parse("0-590-76484-5"); try std.testing.expect(x == .@"10"); try std.testing.expectEqualSlices(u8, "0590764845", &x.@"10"); const c = x.computeCheckDigit(); try std.testing.expectEqual('5', c);}
test "10 3" { const x: ISBN = try .parse("0-8044-2957-X"); try std.testing.expect(x == .@"10"); try std.testing.expectEqualSlices(u8, "080442957X", &x.@"10"); const c = x.computeCheckDigit(); try std.testing.expectEqual('X', c);}
test "13 1" { const x: ISBN = try .parse("978-0-306-40615-7"); try std.testing.expect(x == .@"13"); try std.testing.expectEqualSlices(u8, "9780306406157", &x.@"13"); const c = x.computeCheckDigit(); try std.testing.expectEqual('7', c);}
test "13 2" { const x: ISBN = try .parse("979-10-90636-07-1"); try std.testing.expect(x == .@"13"); try std.testing.expectEqualSlices(u8, "9791090636071", &x.@"13"); const c = x.computeCheckDigit(); try std.testing.expectEqual('1', c);}
test "10 maximum weighted sum" { // The weighted sum of 999999999 is 486, which overflows u8; this // guards against the SIMD path accumulating in 8-bit lanes. const x: ISBN = try .parse("9999999999"); try std.testing.expect(x == .@"10"); const c = x.computeCheckDigit(); try std.testing.expectEqual('9', c);}
test "10 check digit 0" { const x: ISBN = try .parse("0-00-000000-0"); try std.testing.expect(x == .@"10"); const c = x.computeCheckDigit(); try std.testing.expectEqual('0', c);}
test "13 check digit 0" { const x: ISBN = try .parse("978-0-00-000020-0"); try std.testing.expect(x == .@"13"); const c = x.computeCheckDigit(); try std.testing.expectEqual('0', c);}
test "parse rejects malformed input" { try std.testing.expectError(error.ParseError, ISBN.parse("")); try std.testing.expectError(error.ParseError, ISBN.parse("---")); try std.testing.expectError(error.ParseError, ISBN.parse("0-306-40615")); // 9 digits try std.testing.expectError(error.ParseError, ISBN.parse("0-306-40615-22")); // 11 digits try std.testing.expectError(error.ParseError, ISBN.parse("978-0-306-40615")); // 12 digits try std.testing.expectError(error.ParseError, ISBN.parse("978-0-306-40615-72")); // 14 digits try std.testing.expectError(error.ParseError, ISBN.parse("0-306-4X615-2")); // X in wrong position try std.testing.expectError(error.ParseError, ISBN.parse("0-306-40615-A")); // invalid character try std.testing.expectError(error.ParseError, ISBN.parse("0 306 40615 2")); // space separator}
test "parse accepts separators anywhere" { // `-` is a separator wherever it appears, and that has to hold for // both lengths: a trailing separator on a 13-digit ISBN used to be // rejected while the same thing on a 10-digit one was accepted. try std.testing.expect(try ISBN.parse("-0-306-40615-2-") == .@"10"); try std.testing.expect(try ISBN.parse("-978-0-306-40615-7-") == .@"13"); try std.testing.expect(try ISBN.parse("978--0--306--40615--7") == .@"13");
// The digit count is still what decides, so a fourteenth digit is an // error however many separators surround it. try std.testing.expectError(error.ParseError, ISBN.parse("978-0-306-40615-7-0"));}
test "parse rejects X in an ISBN-13" { // 'X' - '0' is 40, which at position 9 (weight 3) contributes // 120 = 0 (mod 10), so this string is checksum-valid and must be // rejected before the check-digit comparison. try std.testing.expectError(error.ParseError, ISBN.parse("978-0-306-40X15-5"));}
test "parse rejects invalid check digits" { try std.testing.expectError(error.InvalidCheckDigit, ISBN.parse("0-306-40615-3")); try std.testing.expectError(error.InvalidCheckDigit, ISBN.parse("0-8044-2957-4")); // expects X try std.testing.expectError(error.InvalidCheckDigit, ISBN.parse("978-0-306-40615-8"));}
test "upgrade and eql" { const ten: ISBN = try .parse("0-306-40615-2"); const thirteen: ISBN = try .parse("978-0-306-40615-7"); const other: ISBN = try .parse("0-590-76484-5");
const upgraded = ten.upgrade(); try std.testing.expect(upgraded == .@"13"); try std.testing.expectEqualSlices(u8, &thirteen.@"13", &upgraded.@"13"); try std.testing.expectEqualSlices(u8, &thirteen.@"13", &thirteen.upgrade().@"13");
try std.testing.expect(ten.eql(&ten)); try std.testing.expect(thirteen.eql(&thirteen)); try std.testing.expect(ten.eql(&thirteen)); try std.testing.expect(thirteen.eql(&ten)); try std.testing.expect(!ten.eql(&other)); try std.testing.expect(!thirteen.eql(&other));}
test "hyphenate" { var buf: [ISBN.max_hyphenated_len]u8 = undefined;
const ten: ISBN = try .parse("0306406152"); try std.testing.expectEqualStrings("0-306-40615-2", try ten.hyphenate(&buf));
const ten_x: ISBN = try .parse("080442957X"); try std.testing.expectEqualStrings("0-8044-2957-X", try ten_x.hyphenate(&buf));
const thirteen: ISBN = try .parse("9780306406157"); try std.testing.expectEqualStrings("978-0-306-40615-7", try thirteen.hyphenate(&buf));
const nine_seven_nine: ISBN = try .parse("9791090636071"); try std.testing.expectEqualStrings("979-10-90636-07-1", try nine_seven_nine.hyphenate(&buf));
// 978-99999 is not an assigned registration group. const unknown: ISBN = try .parse("9999999999"); try std.testing.expectError(error.UnknownRange, unknown.hyphenate(&buf));}
test "format" { const thirteen: ISBN = try .parse("978-0-306-40615-7"); try std.testing.expectFmt("978-0-306-40615-7", "{f}", .{thirteen});
const ten: ISBN = try .parse("0-306-40615-2"); try std.testing.expectFmt("0-306-40615-2", "{f}", .{ten});
// An ISBN outside the assigned ranges falls back to bare digits. const unknown: ISBN = try .parse("9999999999"); try std.testing.expectFmt("9999999999", "{f}", .{unknown});}
fn fuzz(_: void, smith: *std.testing.Smith) !void { { const len_weights: []const std.testing.Smith.Weight = &.{ .{ .min = 8, .max = 15, .weight = 100, }, }; const byte_weights: []const std.testing.Smith.Weight = &.{ .{ .min = '0', .max = '9', .weight = 100, }, .{ .min = 'X', .max = 'X', .weight = 50, }, .{ .min = '-', .max = '-', .weight = 10, }, .{ .min = 'A', .max = 'A', .weight = 1, }, }; var buf: [64]u8 = undefined; const len = smith.sliceWeighted(&buf, len_weights, byte_weights);
_ = ISBN.parse(buf[0..len]) catch |err| switch (err) { error.ParseError => {}, error.InvalidCheckDigit => {}, else => |e| return e, }; }}
test "fuzz" { try std.testing.fuzz({}, fuzz, .{});}
// -- Examples ----------------------------------------------------------------//// One test per public declaration, named after it. Zig does not compile code// inside doc comments, so an example meant to stay true has to be a test.
test "ISBN.parse" { // Hyphens are ignored and the check digit is verified. Only digits, `-`, // and a trailing `X` are accepted -- spaces are not a separator here. const ten = try ISBN.parse("0-306-40615-2"); try std.testing.expect(ten == .@"10"); const thirteen = try ISBN.parse("9780306406157"); try std.testing.expect(thirteen == .@"13");
try std.testing.expectError(error.ParseError, ISBN.parse("not an isbn")); try std.testing.expectError(error.ParseError, ISBN.parse("978 0 306 40615 7")); try std.testing.expectError(error.InvalidCheckDigit, ISBN.parse("0-306-40615-3"));}
test "ISBN.computeCheckDigit" { const isbn = try ISBN.parse("0-306-40615-2"); try std.testing.expectEqual(@as(u8, '2'), isbn.computeCheckDigit());}
test "ISBN.computeCheckDigitWith" { // The two implementations must agree. The build option picks one, so // only a test that calls both can show they match in a single run. for ([_][]const u8{ "0-306-40615-2", "978-0-306-40615-7", "0-8044-2957-X", "978-92-95055-02-5", }) |text| { const isbn = try ISBN.parse(text); try std.testing.expectEqual( isbn.computeCheckDigitWith(true), isbn.computeCheckDigitWith(false), ); }}
test "ISBN.upgrade" { // A 10-digit ISBN becomes the 978-prefixed 13, with a recomputed check // digit; a 13 is already upgraded and is returned unchanged. const ten = try ISBN.parse("0-306-40615-2"); const upgraded = ten.upgrade(); try std.testing.expect(upgraded == .@"13");
var buf: [ISBN.max_hyphenated_len]u8 = undefined; try std.testing.expectEqualStrings("978-0-306-40615-7", try upgraded.hyphenate(&buf)); try std.testing.expect(upgraded.upgrade().eql(&upgraded));}
test "ISBN.hyphenate" { // Hyphenation needs the agency range data: the split between registration // group, registrant, and publication is not derivable from the digits. var buf: [ISBN.max_hyphenated_len]u8 = undefined; const isbn = try ISBN.parse("9780306406157"); try std.testing.expectEqualStrings("978-0-306-40615-7", try isbn.hyphenate(&buf));}
test "ISBN.format" { // `{f}` hyphenates when the ISBN falls in a known range. var buf: [32]u8 = undefined; const isbn = try ISBN.parse("0306406152"); try std.testing.expectEqualStrings( "0-306-40615-2", try std.fmt.bufPrint(&buf, "{f}", .{isbn}), );}
test "ISBN.eql" { const ten = try ISBN.parse("0-306-40615-2"); const same = try ISBN.parse("0306406152"); try std.testing.expect(ten.eql(&same));
// Equality is over the book, not the digits: a 10 equals its 13, because // both are upgraded before comparison. const thirteen = try ISBN.parse("978-0-306-40615-7"); try std.testing.expect(ten.eql(&thirteen)); try std.testing.expect(thirteen.eql(&ten));
const other = try ISBN.parse("0-8044-2957-X"); try std.testing.expect(!ten.eql(&other));}