Sqids (pronounced "squids") is a small library that lets you generate unique IDs from numbers. It's good for link shortening, fast & URL-safe ID generation and decoding back into numbers for quicker database lookups.
Features:
Good for:
Not good for:
To add sqids-zig to your Zig application or library, follow these steps:
zig fetch --save https://github.com/lvignoli/sqids-zig/archive/<commitID>.tar.gz
build.zig.zon
file:.dependencies = .{
.sqids = .{
.url = "https://github.com/lvignoli/sqids-zig/archive/<commitID>.tar.gz",
.hash = "<hash>",
},
}
build.zig
and add it where needed:const sqids_dep = b.dependency("sqids", .{});
const sqids_mod = sqids_dep.module("sqids");
[...]
exe.addModule("sqids", sqids_mod); // for an executable
lib.addModule("sqids", sqids_mod); // for a library
tests.addModule("sqids", sqids_mod); // for tests
const sqids = @import("sqids");
The import string is the one provided in the addModule
call.
[!TIP] Check lvignoli/sqidify for a self-contained Zig executable example.
Simple encode & decode:
const s = try sqids.Sqids.init(allocator, .{})
defer s.deinit();
const id = try s.encode(&.{1, 2, 3});
defer allocator.free(id); // Caller owns the memory.
const numbers = try s.decode(id);
defer allocator.free(numbers); // Caller owns the memory.
Note 🚧 Because of the algorithm's design, multiple IDs can decode back into the same sequence of numbers. If it's important to your design that IDs are canonical, you have to manually re-encode decoded numbers and check that the generated ID matches.
The sqids.Options
struct is used at initialization to customize the encoder.
Enforce a minimum length for IDs:
const s = try sqids.Sqids.init(allocator, .{.min_length = 10});
const id = try s.encode(&.{1, 2, 3}); // "86Rf07xd4z"
Randomize IDs by providing a custom alphabet:
const s = try sqids.Sqids.init(allocator, .{.alphabet = "FxnXM1kBN6cuhsAvjW3Co7l2RePyY8DwaU04Tzt9fHQrqSVKdpimLGIJOgb5ZE"});
const id = try s.encode(&.{1, 2, 3}); // "B4aajs"
Prevent specific words from appearing anywhere in the auto-generated IDs:
const s = try sqids.Sqids.init(allocator, .{.blocklist = &.{"86Rf07"}});
const id = try s.encode(&.{1, 2, 3}); // "se8ojk"