zulid
babiabeo/zulid
ULID package for Zig
babiabeo/zulid
ULID package for Zig
Universally Unique Lexicographically Sortable Identifier for Zig.
UUID can be suboptimal for many use-cases because:
Instead, herein is ULID:
First, fetch zulid
using Zig's package manager. This will download and add the
package to build.zig.zon
:
zig fetch --save git+https://github.com/babiabeo/zulid
Then, update your build.zig
in order to use the package:
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const zulid = b.dependency("zulid", .{
.target = target,
.optimize = optimize,
}).module("zulid");
const exe = b.addExecutable(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("zulid", zulid);
// ...
}
Here is a simple usage:
const std = @import("std");
const zulid = @import("zulid");
pub fn main() !void {
const id = zulid.Generator.init(null);
var out: [zulid.encoded_size]u8 = undefined;
id.encode(&out);
std.debug.print("{s}", .{out});
}
With custom timestamp:
const std = @import("std");
const zulid = @import("zulid");
pub fn main() !void {
const id = zulid.Generator.init(1732434408285);
var out: [zulid.encoded_size]u8 = undefined;
id.encode(&out);
std.debug.print("{s}", .{out});
}
Below is the current specification of ULID as implemented in zulid.
01AN4Z07BY 79KA1307SR9X4MV3
|----------| |----------------|
Timestamp Randomness
48bits 80bits
Timestamp
Randomness
ttttttttttrrrrrrrrrrrrrrrr
where
t is Timestamp (10 characters)
r is Randomness (16 characters)
Crockford's Base32 is used as shown. This alphabet excludes the letters I, L, O, and U to avoid confusion and abuse.
0123456789ABCDEFGHJKMNPQRSTVWXYZ
The components are encoded as 16 octets. Each component is encoded with the Most Significant Byte first (network byte order).
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 32_bit_uint_time_high |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 16_bit_uint_time_low | 16_bit_uint_random |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 32_bit_uint_random |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 32_bit_uint_random |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Add compare function to compare 2 ULIDs.
Add monotonicity version.
MIT License