1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
//! 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);
}
}