authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2025-02-13 12:31:47 -08:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2025-02-13 12:31:47 -08:00
logb8fec06fa26ec5ddd2b1b9cb5099de3a9df9109f
tree9d72f0ed7b48f385c924b2e9668856619655c38e
parentd9ffe3263a8d50114376b3eebaf6ab634332e2e2

add hasFn


2 files changed, 26 insertions(+), 0 deletions(-)

src/hasFn.zig created+25
......@@ -0,0 +1,25 @@
1const std = @import("std");
2const string = []const u8;
3const extras = @import("./lib.zig");
4
5pub fn hasFn(comptime name: []const u8) fn (type) bool {
6 const Closure = struct {
7 pub fn trait(comptime T: type) bool {
8 if (!comptime extras.isContainer(T)) return false;
9 if (!comptime @hasDecl(T, name)) return false;
10 const DeclType = @TypeOf(@field(T, name));
11 return @typeInfo(DeclType) == .Fn;
12 }
13 };
14 return Closure.trait;
15}
16
17test {
18 const TestStruct = struct {
19 pub fn useless() void {}
20 };
21
22 try std.testing.expect(hasFn("useless")(TestStruct));
23 try std.testing.expect(!hasFn("append")(TestStruct));
24 try std.testing.expect(!hasFn("useless")(u8));
25}
src/lib.zig+1
......@@ -103,3 +103,4 @@ pub usingnamespace @import("./indexOfSlice.zig");
103103pub usingnamespace @import("./mapBy.zig");
104104pub usingnamespace @import("./lessThanBy.zig");
105105pub usingnamespace @import("./isContainer.zig");
106pub usingnamespace @import("./hasFn.zig");