| ... | ... | @@ -416,3 +416,71 @@ test "std.meta.trait.hasFunctions" { |
| 416 | 416 | testing.expect(!hasFunctions(TestStruct2, .{ "a", "b", "c" })); |
| 417 | 417 | testing.expect(!hasFunctions(TestStruct2, tuple)); |
| 418 | 418 | } |
| 419 | |
| 420 | /// True if every value of the type `T` has a unique bit pattern representing it. |
| 421 | /// In other words, `T` has no unused bits and no padding. |
| 422 | pub fn hasUniqueRepresentation(comptime T: type) bool { |
| 423 | switch (@typeInfo(T)) { |
| 424 | else => return false, // TODO can we know if it's true for some of these types ? |
| 425 | |
| 426 | .AnyFrame, |
| 427 | .Bool, |
| 428 | .BoundFn, |
| 429 | .Enum, |
| 430 | .ErrorSet, |
| 431 | .Fn, |
| 432 | .Int, // TODO check that it is still true |
| 433 | .Pointer, |
| 434 | => return true, |
| 435 | |
| 436 | .Array => |info| return comptime hasUniqueRepresentation(info.child), |
| 437 | |
| 438 | .Struct => |info| { |
| 439 | var sum_size = @as(usize, 0); |
| 440 | |
| 441 | inline for (info.fields) |field| { |
| 442 | const FieldType = field.field_type; |
| 443 | if (comptime !hasUniqueRepresentation(FieldType)) return false; |
| 444 | sum_size += @sizeOf(FieldType); |
| 445 | } |
| 446 | |
| 447 | return @sizeOf(T) == sum_size; |
| 448 | }, |
| 449 | |
| 450 | .Vector => |info| return comptime hasUniqueRepresentation(info.child), |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | test "std.meta.trait.hasUniqueRepresentation" { |
| 455 | const TestStruct1 = struct { |
| 456 | a: u32, |
| 457 | b: u32, |
| 458 | }; |
| 459 | |
| 460 | testing.expect(hasUniqueRepresentation(TestStruct1)); |
| 461 | |
| 462 | const TestStruct2 = struct { |
| 463 | a: u32, |
| 464 | b: u16, |
| 465 | }; |
| 466 | |
| 467 | testing.expect(!hasUniqueRepresentation(TestStruct2)); |
| 468 | |
| 469 | const TestStruct3 = struct { |
| 470 | a: u32, |
| 471 | b: u32, |
| 472 | }; |
| 473 | |
| 474 | testing.expect(hasUniqueRepresentation(TestStruct3)); |
| 475 | |
| 476 | testing.expect(hasUniqueRepresentation(i1)); |
| 477 | testing.expect(hasUniqueRepresentation(u2)); |
| 478 | testing.expect(hasUniqueRepresentation(i3)); |
| 479 | testing.expect(hasUniqueRepresentation(u4)); |
| 480 | testing.expect(hasUniqueRepresentation(i5)); |
| 481 | testing.expect(hasUniqueRepresentation(u6)); |
| 482 | testing.expect(hasUniqueRepresentation(i7)); |
| 483 | testing.expect(hasUniqueRepresentation(u8)); |
| 484 | testing.expect(hasUniqueRepresentation(i9)); |
| 485 | testing.expect(hasUniqueRepresentation(u10)); |
| 486 | } |