//! TID - Timestamp Identifier //! //! tids encode a timestamp and clock id in a base32-sortable format. //! format: 13 characters using alphabet "234567abcdefghijklmnopqrstuvwxyz" //! - first char encodes the top three bits: 234567ab //! - remaining chars encode 53-bit timestamp + 10-bit clock id //! //! the encoding is designed to be lexicographically sortable by time. //! see: https://atproto.com/specs/record-key#record-key-type-tid const std = @import("std"); const alphabet = "234567abcdefghijklmnopqrstuvwxyz"; fn valueToChar(v: u5) u8 { return alphabet[v]; } fn charToValue(c: u8) ?u5 { comptime var values: [256]?u5 = @splat(null); inline for (alphabet, 0..) |c_idx, i| values[c_idx] = i; return values[c]; } const ClockId = packed struct(u10) { low: u5, high: u5, fn fromInt(int: u10) @This() { return @fromBackingInt(int); } fn toInt(self: @This()) u10 { return @backingInt(self); } const Str = [2]u8; fn fromStr(s: Str) ?@This() { return .{ .high = charToValue(s[0]) orelse return null, .low = charToValue(s[1]) orelse return null, }; } fn toStr(self: @This()) Str { return .{ valueToChar(self.high), valueToChar(self.low) }; } }; const Timestamp = packed struct(u53) { u5s: u50, // 10 u5s high: u3, const Vec = @Vector(10, u5); fn fromInt(int: u53) @This() { return @fromBackingInt(int); } fn toInt(self: @This()) u53 { return @backingInt(self); } const Str = [11]u8; fn fromStr(s: Str) ?@This() { const high = charToValue(s[0]) orelse return null; if (high > std.math.maxInt(u3)) return null; var u5s: [10]u5 = undefined; for (&u5s, 0..) |*u, i| u.* = charToValue(s[10 - i]) orelse return null; return .{ .high = @intCast(high), .u5s = @bitCast(@as(Vec, u5s)), }; } fn toStr(self: @This()) Str { var s: Str = undefined; s[0] = valueToChar(self.high); const u5s_vec: Vec = @bitCast(self.u5s); inline for (s[1..], 0..) |*c, i| c.* = valueToChar(u5s_vec[9 - i]); return s; } }; const Internal = packed struct(u63) { clock_id: ClockId, timestamp: Timestamp, fn fromTimestamp(ts: u64, clock_id: u10) @This() { return .{ .timestamp = .fromInt(@intCast(ts)), .clock_id = .fromInt(clock_id), }; } fn fromInt(int: u63) @This() { return @fromBackingInt(int); } fn toInt(self: @This()) u63 { return @backingInt(self); } fn fromStr(s: []const u8) ?@This() { if (s.len != 13) return null; const s13 = s[0..13]; return .{ .timestamp = Timestamp.fromStr(s13[0..11].*) orelse return null, .clock_id = ClockId.fromStr(s13[11..].*) orelse return null, }; } fn toStr(self: @This()) Tid.Str { return self.timestamp.toStr() ++ self.clock_id.toStr(); } }; pub const Tid = packed struct(u64) { store: u63, _: u1 = 0, fn internal(self: Tid) Internal { return .fromInt(self.store); } fn fromInternal(intern: Internal) @This() { return .{ .store = intern.toInt() }; } /// parse a tid string. returns null if invalid. pub fn parse(s: []const u8) ?Tid { return .fromInternal(Internal.fromStr(s) orelse return null); } /// timestamp in microseconds since unix epoch pub fn timestamp(self: Tid) u64 { return self.internal().timestamp.toInt(); } /// clock identifier (lower 10 bits) pub fn clockId(self: Tid) u10 { return self.internal().clock_id.toInt(); } /// generate tid from timestamp and clock id pub fn fromTimestamp(ts: u64, clock_id: u10) Tid { return .fromInternal(.fromTimestamp(ts, clock_id)); } pub const Str = [13]u8; /// get the raw string representation pub fn str(self: Tid) Str { return self.internal().toStr(); } }; test "TID wire encoding" { const tid: Tid = .fromTimestamp(1, 1); const tid_str = "2222222222323"; try std.testing.expectEqual(tid_str.*, tid.str()); const parsed = Tid.parse(tid_str); try std.testing.expectEqual(tid, parsed); } test "parse valid tid" { // generate a valid tid and parse it back const ts: u64 = 1704067200000000; // 2024-01-01 00:00:00 UTC in microseconds const clock: u10 = 42; const generated: Tid = .fromTimestamp(ts, clock); const tid = Tid.parse(&generated.str()) orelse return error.InvalidTid; try std.testing.expectEqual(ts, tid.timestamp()); try std.testing.expectEqual(clock, tid.clockId()); } test "reject invalid tid" { // wrong length try std.testing.expect(Tid.parse("abc") == null); try std.testing.expect(Tid.parse("") == null); // invalid chars try std.testing.expect(Tid.parse("0000000000000") == null); try std.testing.expect(Tid.parse("1111111111111") == null); try std.testing.expect(Tid.parse("c222222222222") == null); try std.testing.expect(Tid.parse("z222222222222") == null); } test "roundtrip" { const ts: u64 = 1704067200000000; // 2024-01-01 00:00:00 UTC in microseconds const clock: u10 = 42; const tid: Tid = .fromTimestamp(ts, clock); try std.testing.expectEqual(ts, tid.timestamp()); try std.testing.expectEqual(clock, tid.clockId()); } test "valid first chars" { try std.testing.expect(Tid.parse("2222222222222") != null); try std.testing.expect(Tid.parse("3222222222222") != null); try std.testing.expect(Tid.parse("4222222222222") != null); try std.testing.expect(Tid.parse("5222222222222") != null); try std.testing.expect(Tid.parse("6222222222222") != null); try std.testing.expect(Tid.parse("7222222222222") != null); } test "all valid chars in non-first position" { // chars 2-7 and a-z are valid after first position try std.testing.expect(Tid.parse("2aaaaaaaaaaaa") != null); try std.testing.expect(Tid.parse("2zzzzzzzzzzzz") != null); try std.testing.expect(Tid.parse("2234567234567") != null); } test "uppercase rejected" { try std.testing.expect(Tid.parse("2AAAAAAAAAAAA") == null); try std.testing.expect(Tid.parse("2AAAAAAAAaaaa") == null); } test "TID roundtrips the full timestamp range" { for ([_]u64{ 6 << 50, 7 << 50, std.math.maxInt(u53) }) |timestamp| { const generated = Tid.fromTimestamp(timestamp, 1023); const parsed = Tid.parse(&generated.str()) orelse return error.InvalidTid; try std.testing.expectEqual(timestamp, parsed.timestamp()); try std.testing.expectEqual(@as(u10, 1023), parsed.clockId()); try std.testing.expectEqual(generated.str(), parsed.str()); } for ("cdefghijklmnopqrstuvwxyz") |first| { var text = "2222222222222".*; text[0] = first; try std.testing.expect(Tid.parse(&text) == null); } }