authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-06-01 14:50:01-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2020-06-01 14:50:01-04:00
log8f4bc772604e708a150b279ffbaff0076c4b212d
tree1215dbb4570f1fde7c1b93687925fa4c465b4dfe
parentf9b220ec2c5203fc70bab3b872cf6cd100651357
parentc91786caf3f12ec9c9ad928fc0e71d43783ea7a8
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #5449 from data-man/more_traits

Add more traits

1 files changed, 75 insertions(+), 0 deletions(-)

lib/std/meta/trait.zig+75
......@@ -341,3 +341,78 @@ test "std.meta.trait.isContainer" {
341341 testing.expect(isContainer(TestEnum));
342342 testing.expect(!isContainer(u8));
343343}
344
345pub 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
353test "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
371pub 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
379test "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
397pub 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
405test "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}