authorgravatar for thatlemon@gmail.comLemonBoy <thatlemon@gmail.com> 2021-04-25 16:49:21+02:00
committergravatar for thatlemon@gmail.comLemonBoy <thatlemon@gmail.com> 2021-04-25 16:49:21+02:00
log19cec0db1e8a9fefd8295c81edb03d631c624e62
treefa82d3cf52aca9481616b127587776904d5a4c6c
parent50a8124f45cd0994b52af3fd166dd3bda48f4b99

std: Make met.alignment work on more types

Make it return the correct value for function types and optional pointers.

1 files changed, 16 insertions(+), 3 deletions(-)

lib/std/meta.zig+16-3
......@@ -117,10 +117,21 @@ test "std.meta.bitCount" {
117117 testing.expect(bitCount(f32) == 32);
118118}
119119
120/// Returns the alignment of type T.
121/// Note that if T is a pointer or function type the result is different than
122/// the one returned by @alignOf(T).
123/// If T is a pointer type the alignment of the type it points to is returned.
124/// If T is a function type the alignment a target-dependent value is returned.
120125pub fn alignment(comptime T: type) comptime_int {
121 //@alignOf works on non-pointer types
122 const P = if (comptime trait.is(.Pointer)(T)) T else *T;
123 return @typeInfo(P).Pointer.alignment;
126 return switch (@typeInfo(T)) {
127 .Optional => |info| switch (@typeInfo(info.child)) {
128 .Pointer, .Fn => alignment(info.child),
129 else => @alignOf(T),
130 },
131 .Pointer => |info| info.alignment,
132 .Fn => |info| info.alignment,
133 else => @alignOf(T),
134 };
124135}
125136
126137test "std.meta.alignment" {
......@@ -129,6 +140,8 @@ test "std.meta.alignment" {
129140 testing.expect(alignment(*align(2) u8) == 2);
130141 testing.expect(alignment([]align(1) u8) == 1);
131142 testing.expect(alignment([]align(2) u8) == 2);
143 testing.expect(alignment(fn () void) > 0);
144 testing.expect(alignment(fn () align(128) void) == 128);
132145}
133146
134147pub fn Child(comptime T: type) type {