Skip to content

Commit 8f4bc77

Browse files
authored
Merge pull request #5449 from data-man/more_traits
Add more traits
2 parents f9b220e + c91786c commit 8f4bc77

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

lib/std/meta/trait.zig

+75
Original file line numberDiff line numberDiff line change
@@ -341,3 +341,78 @@ test "std.meta.trait.isContainer" {
341341
testing.expect(isContainer(TestEnum));
342342
testing.expect(!isContainer(u8));
343343
}
344+
345+
pub fn hasDecls(comptime T: type, comptime names: var) bool {
346+
inline for (names) |name| {
347+
if (!@hasDecl(T, name))
348+
return false;
349+
}
350+
return true;
351+
}
352+
353+
test "std.meta.trait.hasDecls" {
354+
const TestStruct1 = struct {};
355+
const TestStruct2 = struct {
356+
pub var a: u32;
357+
pub var b: u32;
358+
c: bool,
359+
pub fn useless() void {}
360+
};
361+
362+
const tuple = .{ "a", "b", "c" };
363+
364+
testing.expect(!hasDecls(TestStruct1, .{"a"}));
365+
testing.expect(hasDecls(TestStruct2, .{ "a", "b" }));
366+
testing.expect(hasDecls(TestStruct2, .{ "a", "b", "useless" }));
367+
testing.expect(!hasDecls(TestStruct2, .{ "a", "b", "c" }));
368+
testing.expect(!hasDecls(TestStruct2, tuple));
369+
}
370+
371+
pub fn hasFields(comptime T: type, comptime names: var) bool {
372+
inline for (names) |name| {
373+
if (!@hasField(T, name))
374+
return false;
375+
}
376+
return true;
377+
}
378+
379+
test "std.meta.trait.hasFields" {
380+
const TestStruct1 = struct {};
381+
const TestStruct2 = struct {
382+
a: u32,
383+
b: u32,
384+
c: bool,
385+
pub fn useless() void {}
386+
};
387+
388+
const tuple = .{ "a", "b", "c" };
389+
390+
testing.expect(!hasFields(TestStruct1, .{"a"}));
391+
testing.expect(hasFields(TestStruct2, .{ "a", "b" }));
392+
testing.expect(hasFields(TestStruct2, .{ "a", "b", "c" }));
393+
testing.expect(hasFields(TestStruct2, tuple));
394+
testing.expect(!hasFields(TestStruct2, .{ "a", "b", "useless" }));
395+
}
396+
397+
pub fn hasFunctions(comptime T: type, comptime names: var) bool {
398+
inline for (names) |name| {
399+
if (!hasFn(name)(T))
400+
return false;
401+
}
402+
return true;
403+
}
404+
405+
test "std.meta.trait.hasFunctions" {
406+
const TestStruct1 = struct {};
407+
const TestStruct2 = struct {
408+
pub fn a() void {}
409+
fn b() void {}
410+
};
411+
412+
const tuple = .{ "a", "b", "c" };
413+
414+
testing.expect(!hasFunctions(TestStruct1, .{"a"}));
415+
testing.expect(hasFunctions(TestStruct2, .{ "a", "b" }));
416+
testing.expect(!hasFunctions(TestStruct2, .{ "a", "b", "c" }));
417+
testing.expect(!hasFunctions(TestStruct2, tuple));
418+
}

0 commit comments

Comments
 (0)