forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomptime_string_map.zig
482 lines (417 loc) · 13.7 KB
/
comptime_string_map.zig
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
const std = @import("std");
const mem = std.mem;
const strings = @import("./string_immutable.zig");
/// Comptime string map optimized for small sets of disparate string keys.
/// Works by separating the keys by length at comptime and only checking strings of
/// equal length at runtime.
///
/// `kvs` expects a list literal containing list literals or an array/slice of structs
/// where `.@"0"` is the `[]const u8` key and `.@"1"` is the associated value of type `V`.
/// TODO: https://github.com/ziglang/zig/issues/4335
pub fn ComptimeStringMapWithKeyType(comptime KeyType: type, comptime V: type, comptime kvs_list: anytype) type {
const KV = struct {
key: []const KeyType,
value: V,
};
const precomputed = comptime blk: {
@setEvalBranchQuota(99999);
var sorted_kvs: [kvs_list.len]KV = undefined;
const lenAsc = (struct {
fn lenAsc(context: void, a: KV, b: KV) bool {
_ = context;
if (a.key.len != b.key.len) {
return a.key.len < b.key.len;
}
// https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array
@setEvalBranchQuota(999999);
return std.mem.order(KeyType, a.key, b.key) == .lt;
}
}).lenAsc;
if (KeyType == u8) {
for (kvs_list, 0..) |kv, i| {
if (V != void) {
sorted_kvs[i] = .{ .key = kv.@"0", .value = kv.@"1" };
} else {
sorted_kvs[i] = .{ .key = kv.@"0", .value = {} };
}
}
} else {
@compileError("Not implemented for this key type");
}
std.sort.block(KV, &sorted_kvs, {}, lenAsc);
const min_len = sorted_kvs[0].key.len;
const max_len = sorted_kvs[sorted_kvs.len - 1].key.len;
var len_indexes: [max_len + 1]usize = undefined;
var len: usize = 0;
var i: usize = 0;
while (len <= max_len) : (len += 1) {
@setEvalBranchQuota(99999);
// find the first keyword len == len
while (len > sorted_kvs[i].key.len) {
i += 1;
}
len_indexes[len] = i;
}
break :blk .{
.min_len = min_len,
.max_len = max_len,
.sorted_kvs = sorted_kvs,
.len_indexes = len_indexes,
};
};
return struct {
const len_indexes = precomputed.len_indexes;
pub const kvs = precomputed.sorted_kvs;
const keys_list: []const []const KeyType = blk: {
var k: [kvs.len][]const KeyType = undefined;
for (kvs, 0..) |kv, i| {
k[i] = kv.key;
}
break :blk k[0..];
};
pub const Value = V;
pub fn keys() []const []const KeyType {
return keys_list;
}
pub fn has(str: []const KeyType) bool {
return get(str) != null;
}
pub fn getWithLength(str: []const KeyType, comptime len: usize) ?V {
const end = comptime brk: {
var i = len_indexes[len];
@setEvalBranchQuota(99999);
while (i < kvs.len and kvs[i].key.len == len) : (i += 1) {}
break :brk i;
};
comptime var i = len_indexes[len];
// This benchmarked faster for both small and large lists of strings than using a big switch statement
// But only so long as the keys are a sorted list.
inline while (i < end) : (i += 1) {
if (strings.eqlComptimeCheckLenWithType(KeyType, str, kvs[i].key, false)) {
return kvs[i].value;
}
}
return null;
}
pub fn getWithLengthAndEql(str: anytype, comptime len: usize, comptime eqls: anytype) ?V {
const end = comptime brk: {
var i = len_indexes[len];
@setEvalBranchQuota(99999);
while (i < kvs.len and kvs[i].key.len == len) : (i += 1) {}
break :brk i;
};
comptime var i = len_indexes[len];
// This benchmarked faster for both small and large lists of strings than using a big switch statement
// But only so long as the keys are a sorted list.
inline while (i < end) : (i += 1) {
if (eqls(str, kvs[i].key)) {
return kvs[i].value;
}
}
return null;
}
pub fn getWithLengthAndEqlList(str: anytype, comptime len: usize, comptime eqls: anytype) ?V {
const end = comptime brk: {
var i = len_indexes[len];
@setEvalBranchQuota(99999);
while (i < kvs.len and kvs[i].key.len == len) : (i += 1) {}
break :brk i;
};
const start = comptime len_indexes[len];
const range = comptime keys()[start..end];
if (eqls(str, range)) |k| {
return kvs[start + k].value;
}
return null;
}
pub fn get(str: []const KeyType) ?V {
if (str.len < precomputed.min_len or str.len > precomputed.max_len)
return null;
comptime var i: usize = precomputed.min_len;
inline while (i <= precomputed.max_len) : (i += 1) {
if (str.len == i) {
return getWithLength(str, i);
}
}
return null;
}
pub fn getWithEql(input: anytype, comptime eql: anytype) ?V {
const Input = @TypeOf(input);
const length = if (comptime std.meta.trait.isSlice(Input) or std.meta.trait.isZigString(Input)) input.len else input.length();
if (length < precomputed.min_len or length > precomputed.max_len)
return null;
comptime var i: usize = precomputed.min_len;
inline while (i <= precomputed.max_len) : (i += 1) {
if (length == i) {
return getWithLengthAndEql(input, i, eql);
}
}
return null;
}
pub fn getWithEqlList(input: anytype, comptime eql: anytype) ?V {
const Input = @TypeOf(input);
const length = if (comptime std.meta.trait.isSlice(Input) or std.meta.trait.isZigString(Input)) input.len else input.length();
if (length < precomputed.min_len or length > precomputed.max_len)
return null;
comptime var i: usize = precomputed.min_len;
inline while (i <= precomputed.max_len) : (i += 1) {
if (length == i) {
return getWithLengthAndEqlList(input, i, eql);
}
}
return null;
}
};
}
pub fn ComptimeStringMap(comptime V: type, comptime kvs_list: anytype) type {
return ComptimeStringMapWithKeyType(u8, V, kvs_list);
}
pub fn ComptimeStringMap16(comptime V: type, comptime kvs_list: anytype) type {
return ComptimeStringMapWithKeyType(u16, V, kvs_list);
}
const TestEnum = enum {
A,
B,
C,
D,
E,
};
test "ComptimeStringMap list literal of list literals" {
const map = ComptimeStringMap(TestEnum, .{
.{ "these", .D },
.{ "have", .A },
.{ "nothing", .B },
.{ "incommon", .C },
.{ "samelen", .E },
});
try testMap(map);
}
test "ComptimeStringMap array of structs" {
const KV = struct {
@"0": []const u8,
@"1": TestEnum,
};
const map = ComptimeStringMap(TestEnum, [_]KV{
.{ .@"0" = "these", .@"1" = .D },
.{ .@"0" = "have", .@"1" = .A },
.{ .@"0" = "nothing", .@"1" = .B },
.{ .@"0" = "incommon", .@"1" = .C },
.{ .@"0" = "samelen", .@"1" = .E },
});
try testMap(map);
}
test "ComptimeStringMap slice of structs" {
const KV = struct {
@"0": []const u8,
@"1": TestEnum,
};
const slice: []const KV = &[_]KV{
.{ .@"0" = "these", .@"1" = .D },
.{ .@"0" = "have", .@"1" = .A },
.{ .@"0" = "nothing", .@"1" = .B },
.{ .@"0" = "incommon", .@"1" = .C },
.{ .@"0" = "samelen", .@"1" = .E },
};
const map = ComptimeStringMap(TestEnum, slice);
try testMap(map);
}
fn testMap(comptime map: anytype) !void {
try std.testing.expectEqual(TestEnum.A, map.get("have").?);
try std.testing.expectEqual(TestEnum.B, map.get("nothing").?);
try std.testing.expect(null == map.get("missing"));
try std.testing.expectEqual(TestEnum.D, map.get("these").?);
try std.testing.expectEqual(TestEnum.E, map.get("samelen").?);
try std.testing.expect(!map.has("missing"));
try std.testing.expect(map.has("these"));
}
test "ComptimeStringMap void value type, slice of structs" {
const KV = struct {
@"0": []const u8,
};
const slice: []const KV = &[_]KV{
.{ .@"0" = "these" },
.{ .@"0" = "have" },
.{ .@"0" = "nothing" },
.{ .@"0" = "incommon" },
.{ .@"0" = "samelen" },
};
const map = ComptimeStringMap(void, slice);
try testSet(map);
}
test "ComptimeStringMap void value type, list literal of list literals" {
const map = ComptimeStringMap(void, .{
.{"these"},
.{"have"},
.{"nothing"},
.{"incommon"},
.{"samelen"},
});
try testSet(map);
}
fn testSet(comptime map: anytype) !void {
try std.testing.expectEqual({}, map.get("have").?);
try std.testing.expectEqual({}, map.get("nothing").?);
try std.testing.expect(null == map.get("missing"));
try std.testing.expectEqual({}, map.get("these").?);
try std.testing.expectEqual({}, map.get("samelen").?);
try std.testing.expect(!map.has("missing"));
try std.testing.expect(map.has("these"));
}
const TestEnum2 = enum {
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
FZ,
FA,
FB,
FC,
FD,
FE,
FF,
FG,
FH,
FI,
FJ,
FK,
FL,
pub const map = ComptimeStringMap(TestEnum2, .{
.{ "these", .A },
.{ "have", .B },
.{ "nothing", .C },
.{ "nothinz", .D },
.{ "nothinc", .E },
.{ "nothina", .F },
.{ "nothinb", .G },
.{ "nothiaa", .H },
.{ "nothaaa", .I },
.{ "notaaaa", .J },
.{ "noaaaaa", .K },
.{ "naaaaaa", .L },
.{ "incommon", .M },
.{ "ancommon", .N },
.{ "ab1ommon", .O },
.{ "ab2ommon", .P },
.{ "ab3ommon", .Q },
.{ "ab4ommon", .R },
.{ "ab5ommon", .S },
.{ "ab6ommon", .T },
.{ "ab7ommon", .U },
.{ "ab8ommon", .V },
.{ "ab9ommon", .W },
.{ "abAommon", .X },
.{ "abBommon", .Y },
.{ "abCommon", .FZ },
.{ "abZommon", .FA },
.{ "abEommon", .FB },
.{ "abFommon", .FC },
.{ "ab10omon", .FD },
.{ "ab11omon", .FE },
.{ "ab12omon", .FF },
.{ "ab13omon", .FG },
.{ "ab14omon", .FH },
.{ "ab15omon", .FI },
.{ "ab16omon", .FJ },
.{ "ab16omon1", .FH },
.{ "samelen", .FK },
.{ "0", .FL },
.{ "00", .FL },
});
pub const official = std.ComptimeStringMap(TestEnum2, .{
.{ "these", .A },
.{ "have", .B },
.{ "naaaaaa", .L },
.{ "noaaaaa", .K },
.{ "notaaaa", .J },
.{ "nothaaa", .I },
.{ "nothiaa", .H },
.{ "nothina", .F },
.{ "nothinb", .G },
.{ "nothinc", .E },
.{ "nothing", .C },
.{ "nothinz", .D },
.{ "incommon", .M },
.{ "ancommon", .N },
.{ "ab1ommon", .O },
.{ "ab2ommon", .P },
.{ "ab3ommon", .Q },
.{ "ab4ommon", .R },
.{ "ab5ommon", .S },
.{ "ab6ommon", .T },
.{ "ab7ommon", .U },
.{ "ab8ommon", .V },
.{ "ab9ommon", .W },
.{ "abAommon", .X },
.{ "abBommon", .Y },
.{ "abCommon", .FZ },
.{ "abZommon", .FA },
.{ "abEommon", .FB },
.{ "abFommon", .FC },
.{ "ab10omon", .FD },
.{ "ab11omon", .FE },
.{ "ab12omon", .FF },
.{ "ab13omon", .FG },
.{ "ab14omon", .FH },
.{ "ab15omon", .FI },
.{ "ab16omon", .FJ },
.{ "samelen", .FK },
.{ "ab16omon1", .FH },
.{ "0", .FL },
.{ "00", .FL },
});
};
pub fn compareString(input: []const u8) !void {
var str = try std.heap.page_allocator.dupe(u8, input);
if (TestEnum2.map.has(str) != TestEnum2.official.has(str)) {
std.debug.panic("{s} - TestEnum2.map.has(str) ({d}) != TestEnum2.official.has(str) ({d})", .{
str,
@intFromBool(TestEnum2.map.has(str)),
@intFromBool(TestEnum2.official.has(str)),
});
}
std.debug.print("For string: \"{s}\" (has a match? {d})\n", .{ str, @intFromBool(TestEnum2.map.has(str)) });
var i: usize = 0;
var is_eql = false;
var timer = try std.time.Timer.start();
while (i < 99999999) : (i += 1) {
is_eql = @call(.never_inline, TestEnum2.map.has, .{str});
}
const new = timer.lap();
std.debug.print("- new {}\n", .{std.fmt.fmtDuration(new)});
i = 0;
while (i < 99999999) : (i += 1) {
is_eql = @call(.never_inline, TestEnum2.official.has, .{str});
}
const _std = timer.lap();
std.debug.print("- std {}\n\n", .{std.fmt.fmtDuration(_std)});
}
pub fn main() anyerror!void {
try compareString("naaaaaa");
try compareString("nothinz");
try compareString("these");
try compareString("incommon");
try compareString("noMatch");
try compareString("0");
try compareString("00");
}