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
|
const std = @import("std");
pub const Segment = union(enum) {
literal: []const u8,
identifier: []const u8,
pub fn format(self: *const @This(), writer: *std.Io.Writer) !void {
switch (self.*) {
.literal => |l| try writer.print("{s}", .{l}),
.identifier => |l| try writer.print("{{{s}}}", .{l}),
}
}
};
segments: []const Segment,
pub const index: @This() = .{ .segments = &.{} };
pub fn fromAny(comptime route: anytype) @This() {
var segments: []const Segment = &.{};
if (route == .index) {
return index;
}
inline for (route) |r| {
const segment: []const Segment = &.{switch (@TypeOf(r)) {
@EnumLiteral() => .{ .identifier = @tagName(r) },
else => .{ .literal = r },
}};
segments = segments ++ segment;
}
return .{ .segments = segments };
}
pub fn format(self: *const @This(), writer: *std.Io.Writer) !void {
for (self.segments) |*seg| {
try writer.print("/{f}", .{seg});
}
}
pub fn isPrefixOf(self: *const @This(), other: *const @This()) bool {
if (self.segments.len > other.segments.len) {
return false;
}
for (self.segments, other.segments[0..self.segments.len]) |s, o| {
if (std.meta.activeTag(s) != std.meta.activeTag(o)) {
return false;
}
if (s == .literal) {
if (!std.mem.eql(u8, s.literal, o.literal)) {
return false;
}
}
}
return true;
}
pub fn equals(self: *const @This(), other: *const @This()) bool {
if (self.segments.len != other.segments.len) {
return false;
}
for (self.segments, other.segments) |s, o| {
if (std.meta.activeTag(s) != std.meta.activeTag(o)) {
return false;
}
if (s == .literal) {
if (!std.mem.eql(u8, s.literal, o.literal)) {
return false;
}
}
}
return true;
}
test "isPrefixOf" {
{
const parent = comptime fromAny(.{ "api", "images", .id });
const child = comptime fromAny(.{ "api", "images", .id, "metadata" });
try std.testing.expect(parent.isPrefixOf(&child));
}
{
const parent = comptime fromAny(.{ "api", "videos", .id });
const child = comptime fromAny(.{ "api", "images", .id, "metadata" });
try std.testing.expect(!parent.isPrefixOf(&child));
}
}
|