Zig is a systems programming language that prioritizes explicit control over allocations and behavior. UUID v7 fits the Zig philosophy: it is a fixed-size value type (16 bytes), requires no heap allocation, and its structure is fully specified in RFC 9562. See UUID Bit Fields for the complete 128-bit layout.
UUID v7 implementation in Zig
const std = @import("std");
pub const Uuid = [16]u8;
/// Generate a UUID v7 value.
/// No heap allocation — uses a [16]u8 on the stack.
pub fn newV7() Uuid {
var bytes: Uuid = undefined;
// Fill with cryptographically random bytes
std.crypto.random.bytes(&bytes);
// Millisecond Unix timestamp (48 bits)
const ms: u64 = @intCast(std.time.milliTimestamp());
// Set bytes 0–5: 48-bit big-endian timestamp
bytes[0] = @truncate(ms >> 40);
bytes[1] = @truncate(ms >> 32);
bytes[2] = @truncate(ms >> 24);
bytes[3] = @truncate(ms >> 16);
bytes[4] = @truncate(ms >> 8);
bytes[5] = @truncate(ms);
// Byte 6: version nibble = 7 in top 4 bits, rand_a low 4 bits preserved
bytes[6] = (bytes[6] & 0x0F) | 0x70;
// Byte 8: variant = 0b10 in top 2 bits
bytes[8] = (bytes[8] & 0x3F) | 0x80;
return bytes;
}
/// Format UUID bytes as canonical 8-4-4-4-12 lowercase hex string.
pub fn format(uuid: Uuid, buf: *[36]u8) void {
const hex = "0123456789abcdef";
var i: usize = 0;
var out: usize = 0;
const groups = [_]usize{ 4, 2, 2, 2, 6 };
for (groups, 0..) |g, gi| {
if (gi > 0) { buf[out] = '-'; out += 1; }
for (0..g) |_| {
buf[out] = hex[uuid[i] >> 4];
buf[out + 1] = hex[uuid[i] & 0x0F];
out += 2;
i += 1;
}
}
}
pub fn main() !void {
const uuid = newV7();
var buf: [36]u8 = undefined;
format(uuid, &buf);
const stdout = std.io.getStdOut().writer();
try stdout.print("{s}\n", .{buf});
}
Version and variant validation
/// Return the version nibble (4 bits at byte 6 high).
pub fn getVersion(uuid: Uuid) u4 {
return @truncate(uuid[6] >> 4);
}
/// Return true if this is an RFC 9562 variant UUID (variant bits = 0b10).
pub fn isRfcVariant(uuid: Uuid) bool {
return (uuid[8] & 0xC0) == 0x80;
}
/// Extract the 48-bit Unix millisecond timestamp from UUID v7.
pub fn extractTimestampMs(uuid: Uuid) u64 {
return (@as(u64, uuid[0]) << 40) |
(@as(u64, uuid[1]) << 32) |
(@as(u64, uuid[2]) << 24) |
(@as(u64, uuid[3]) << 16) |
(@as(u64, uuid[4]) << 8) |
(@as(u64, uuid[5]));
}
Packed struct representation
/// UUID v7 as a packed struct — useful for bit-level access.
pub const UuidV7 = packed struct(u128) {
node: u48, // bytes 10–15 (random)
clock_seq: u14, // rand_b (14 bits)
variant: u2, // = 0b10
rand_a: u12, // sub-millisecond randomness
ver: u4, // = 7
timestamp_ms: u48, // Unix ms since epoch
pub fn generate() UuidV7 {
var raw: [16]u8 = undefined;
std.crypto.random.bytes(&raw);
const ms: u64 = @intCast(std.time.milliTimestamp());
// Interpret random bytes as the struct fields
var u: UuidV7 = @bitCast(raw);
u.timestamp_ms = @truncate(ms);
u.ver = 7;
u.variant = 0b10;
return u;
}
};
Comptime UUID from a string literal
/// Parse a UUID string at compile time.
pub fn comptime_parse(comptime s: []const u8) Uuid {
comptime {
if (s.len != 36) @compileError("UUID string must be 36 characters");
var bytes: Uuid = undefined;
var hex_str: [32]u8 = undefined;
var j: usize = 0;
for (s) |c| {
if (c == '-') continue;
hex_str[j] = c;
j += 1;
}
var i: usize = 0;
while (i < 16) : (i += 1) {
bytes[i] = std.fmt.parseInt(u8, hex_str[i * 2 .. i * 2 + 2], 16) catch
@compileError("Invalid hex in UUID");
}
return bytes;
}
}
// Usage: embed a fixed UUID at compile time (e.g. namespace UUID)
const DNS_NAMESPACE = comptime_parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
Further reading
- UUID Bit Fields — Version and Variant Layout
- UUID String Format — Canonical Hex
- Random Bits — UUID Entropy
- UUID in Rust — uuid Crate
- UUID v7 in Distributed Systems
External references
Frequently asked questions
Does Zig have a built-in UUID library?
The Zig standard library (as of Zig 0.13) does not include a UUID module. The community package uuid-zig provides UUID v4 and v7. For systems code, implementing UUID v7 directly using std.crypto.random.bytes() is straightforward — the layout is fully specified in RFC 9562 and requires no heap allocation.
How do I generate UUID v7 in Zig without heap allocation?
Use a [16]u8 array for the UUID bytes. Call std.crypto.random.bytes(&bytes) to fill it with random data, then set the 48-bit timestamp prefix, version nibble (7), and variant bits (0b10) with bitwise operations. The entire operation is stack-allocated. See UUID Bit Fields for the exact layout.
How do I format a UUID v7 as a string in Zig?
Use std.fmt.bufPrint with the format string "{x:0>8}-{x:0>4}-{x:0>4}-{x:0>4}-{x:0>12}" applied to the byte groups, or write a helper that formats each byte as two hex chars. Zig's std.fmt does not have a built-in UUID formatter, but a 36-character buffer plus one std.fmt.bufPrint call is sufficient.