const std = @import("std"); pub const RenderError = error{ MissingVariable, InvalidHeaderValue, }; pub const ValueKind = enum { path, header, body, }; pub const VarStore = struct { allocator: std.mem.Allocator, map: std.StringHashMap([]u8), pub fn init(allocator: std.mem.Allocator) VarStore { return .{ .allocator = allocator, .map = std.StringHashMap([]u8).init(allocator), }; } pub fn deinit(self: *VarStore) void { var iterator = self.map.iterator(); while (iterator.next()) |entry| { self.allocator.free(entry.key_ptr.*); self.allocator.free(entry.value_ptr.*); } self.map.deinit(); self.* = undefined; } pub fn set(self: *VarStore, key: []const u8, value: []const u8) !void { if (self.map.fetchRemove(key)) |removed| { self.allocator.free(removed.key); self.allocator.free(removed.value); } try self.map.put(try self.allocator.dupe(u8, key), try self.allocator.dupe(u8, value)); } pub fn get(self: *const VarStore, key: []const u8) ?[]const u8 { return self.map.get(key); } pub fn cloneFrom(self: *VarStore, other: *const VarStore) !void { var iterator = other.map.iterator(); while (iterator.next()) |entry| { try self.set(entry.key_ptr.*, entry.value_ptr.*); } } pub fn clearAll(self: *VarStore) void { var iterator = self.map.iterator(); while (iterator.next()) |entry| { self.allocator.free(entry.key_ptr.*); self.allocator.free(entry.value_ptr.*); } self.map.clearRetainingCapacity(); } pub fn clearNamespace(self: *VarStore, prefix: []const u8) void { var keys = std.ArrayList([]const u8).empty; defer keys.deinit(self.allocator); var iterator = self.map.iterator(); while (iterator.next()) |entry| { if (std.mem.startsWith(u8, entry.key_ptr.*, prefix)) { keys.append(self.allocator, entry.key_ptr.*) catch return; } } for (keys.items) |key| { if (self.map.fetchRemove(key)) |removed| { self.allocator.free(removed.key); self.allocator.free(removed.value); } } } }; pub const SnapshotEntry = struct { key: []const u8, value: []const u8, }; pub fn snapshot(allocator: std.mem.Allocator, store: *const VarStore) ![]SnapshotEntry { var entries = std.ArrayList(SnapshotEntry).empty; errdefer { for (entries.items) |entry| { allocator.free(entry.key); allocator.free(entry.value); } entries.deinit(allocator); } var iterator = store.map.iterator(); while (iterator.next()) |entry| { try entries.append(allocator, .{ .key = try allocator.dupe(u8, entry.key_ptr.*), .value = try allocator.dupe(u8, entry.value_ptr.*), }); } std.sort.block(SnapshotEntry, entries.items, {}, struct { fn lessThan(_: void, left: SnapshotEntry, right: SnapshotEntry) bool { return std.mem.lessThan(u8, left.key, right.key); } }.lessThan); return try entries.toOwnedSlice(allocator); } pub fn deinitSnapshotEntries(allocator: std.mem.Allocator, entries: []SnapshotEntry) void { for (entries) |entry| { allocator.free(entry.key); allocator.free(entry.value); } allocator.free(entries); } pub fn applySnapshot(store: *VarStore, entries: []const SnapshotEntry) !void { for (entries) |entry| { try store.set(entry.key, entry.value); } } pub fn render(allocator: std.mem.Allocator, input: []const u8, store: *const VarStore, kind: ValueKind) (std.mem.Allocator.Error || RenderError)![]u8 { var output: std.ArrayList(u8) = .empty; var cursor: usize = 0; while (std.mem.indexOfPos(u8, input, cursor, "${")) |open_index| { const close_index = std.mem.indexOfScalarPos(u8, input, open_index + 2, '}') orelse return error.MissingVariable; const key = input[open_index + 2 .. close_index]; const value = store.get(key) orelse return error.MissingVariable; try output.appendSlice(allocator, input[cursor..open_index]); try appendRenderedValue(allocator, &output, value, kind); cursor = close_index + 1; } try output.appendSlice(allocator, input[cursor..]); if (kind == .header and (std.mem.indexOfScalar(u8, output.items, '\r') != null or std.mem.indexOfScalar(u8, output.items, '\n') != null)) { return error.InvalidHeaderValue; } return try output.toOwnedSlice(allocator); } fn appendRenderedValue( allocator: std.mem.Allocator, output: *std.ArrayList(u8), value: []const u8, kind: ValueKind, ) (std.mem.Allocator.Error || RenderError)!void { switch (kind) { .path => { try appendPercentEncodedPath(allocator, output, value); }, .header => { if (std.mem.indexOfScalar(u8, value, '\r') != null or std.mem.indexOfScalar(u8, value, '\n') != null) { return error.InvalidHeaderValue; } try output.appendSlice(allocator, value); }, .body => try output.appendSlice(allocator, value), } } fn appendPercentEncodedPath( allocator: std.mem.Allocator, output: *std.ArrayList(u8), value: []const u8, ) std.mem.Allocator.Error!void { for (value) |char| { const safe = std.ascii.isAlphanumeric(char) or char == '-' or char == '_' or char == '.' or char == '~' or char == '/'; if (safe) { try output.append(allocator, char); } else { try output.writer(allocator).print("%{X:0>2}", .{char}); } } } test "render replaces setup variables in paths" { var store = VarStore.init(std.testing.allocator); defer store.deinit(); try store.set("setup.USER_ID", "alice@example.com"); const rendered = try render(std.testing.allocator, "/users/${setup.USER_ID}", &store, .path); defer std.testing.allocator.free(rendered); try std.testing.expectEqualStrings("/users/alice%40example.com", rendered); } test "render rejects missing variables" { var store = VarStore.init(std.testing.allocator); defer store.deinit(); try std.testing.expectError(error.MissingVariable, render(std.testing.allocator, "/users/${setup.USER_ID}", &store, .path)); } test "var store can clone and clear namespaces" { var source = VarStore.init(std.testing.allocator); defer source.deinit(); try source.set("setup.AUTH", "token"); try source.set("iter.USER", "alice"); var cloned = VarStore.init(std.testing.allocator); defer cloned.deinit(); try cloned.cloneFrom(&source); try std.testing.expectEqualStrings("token", cloned.get("setup.AUTH").?); try std.testing.expectEqualStrings("alice", cloned.get("iter.USER").?); cloned.clearNamespace("iter."); try std.testing.expect(cloned.get("iter.USER") == null); try std.testing.expectEqualStrings("token", cloned.get("setup.AUTH").?); }