Zig utility library
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

add `Config` module

IamPyu 865c80fd 17e5bf66

+85
+69
src/config.zig
··· 1 + const std = @import("std"); 2 + const mem = std.mem; 3 + const Allocator = mem.Allocator; 4 + 5 + // TODO: maybe revamp to work like `flag` module 6 + 7 + pub const Error = error{ 8 + EmptyKey, 9 + NoSplit, 10 + } || Allocator.Error; 11 + 12 + pub const Map = std.StringArrayHashMap([]const u8); 13 + 14 + map: Map, 15 + 16 + const Self = @This(); 17 + 18 + pub fn init(alloc: Allocator) Self { 19 + return .{ .map = .init(alloc) }; 20 + } 21 + 22 + pub fn deinit(self: *Self) void { 23 + self.map.deinit(); 24 + } 25 + 26 + fn evalLine(self: *Self, line: []const u8) Error!void { 27 + const trim = " \n\r\t"; 28 + const trimmed_line = mem.trim(u8, line, trim); 29 + 30 + if (trimmed_line.len == 0) { 31 + return; 32 + } else if (trimmed_line[0] == '#') { 33 + return; 34 + } 35 + 36 + const split = @import("./mem.zig").splitOnceScalar(u8, trimmed_line, '=') orelse { 37 + return error.NoSplit; 38 + }; 39 + 40 + const key = mem.trim(u8, split[0], trim); 41 + if (key.len == 0) { 42 + return error.EmptyKey; 43 + } 44 + 45 + try self.map.put(key, split[1]); 46 + } 47 + 48 + pub fn read(self: *Self, contents: []const u8) Error!void { 49 + var iter = mem.tokenizeAny(u8, contents, "\n"); 50 + while (iter.next()) |line| { 51 + try self.evalLine(line); 52 + } 53 + } 54 + 55 + pub fn get(self: *const Self, key: []const u8) ?[]const u8 { 56 + return self.map.get(key); 57 + } 58 + 59 + test "basic" { 60 + var cfg = Self.init(std.testing.allocator); 61 + defer cfg.deinit(); 62 + 63 + try cfg.read( 64 + \\name=World 65 + \\age=est. 4.54 billion years 66 + ); 67 + 68 + try std.testing.expectEqualStrings("World", cfg.get("name").?); 69 + }
+16
src/root.zig
··· 15 15 16 16 pub const flag = @import("./flag.zig"); 17 17 18 + pub const Config = @import("./config.zig"); 19 + 20 + /// Return whether lowercased `s` matches `true`, `yes`, or `y` 21 + pub fn isTruthy(s: []const u8) bool { 22 + if (std.mem.eql(u8, s, "true")) { 23 + return true; 24 + } else if (std.mem.eql(u8, s, "yes")) { 25 + return true; 26 + } else if (std.mem.eql(u8, s, "y")) { 27 + return true; 28 + } 29 + 30 + return false; 31 + } 32 + 18 33 test { 19 34 _ = math; 20 35 _ = mem; ··· 26 41 _ = gamedev; 27 42 28 43 _ = flag; 44 + _ = Config; 29 45 }