diff --git a/src/hasFn.zig b/src/hasFn.zig new file mode 100644 index 0000000000000000000000000000000000000000..1e583d1bc98ef76c09abe6e58267932b58ef5db3 --- /dev/null +++ b/src/hasFn.zig @@ -0,0 +1,25 @@ +const std = @import("std"); +const string = []const u8; +const extras = @import("./lib.zig"); + +pub fn hasFn(comptime name: []const u8) fn (type) bool { + const Closure = struct { + pub fn trait(comptime T: type) bool { + if (!comptime extras.isContainer(T)) return false; + if (!comptime @hasDecl(T, name)) return false; + const DeclType = @TypeOf(@field(T, name)); + return @typeInfo(DeclType) == .Fn; + } + }; + return Closure.trait; +} + +test { + const TestStruct = struct { + pub fn useless() void {} + }; + + try std.testing.expect(hasFn("useless")(TestStruct)); + try std.testing.expect(!hasFn("append")(TestStruct)); + try std.testing.expect(!hasFn("useless")(u8)); +} diff --git a/src/lib.zig b/src/lib.zig index 3e34729afb6ade7b2e0e2c4c10245bc3eede9f8a..c6cc79d2ae4dcba59c3060cb722ba2c46dcf4da1 100644 --- a/src/lib.zig +++ b/src/lib.zig @@ -103,3 +103,4 @@ pub usingnamespace @import("./indexOfSlice.zig"); pub usingnamespace @import("./mapBy.zig"); pub usingnamespace @import("./lessThanBy.zig"); pub usingnamespace @import("./isContainer.zig"); +pub usingnamespace @import("./hasFn.zig");