aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorEvan Haas <evan@lagerdata.com>2021-05-21 16:32:53 -0700
committerVeikka Tuominen <git@vexu.eu>2021-06-11 21:31:39 +0300
commit45212e3b33151b016ae4a597a898db0cc13d4e6b (patch)
treea172cfd2cd706a53d9ccb89c3df8ceecdc92bd1f /lib
parentd8b133d7339605d3cda75459bf986472a72f5bd3 (diff)
downloadzig-45212e3b33151b016ae4a597a898db0cc13d4e6b.tar.gz
zig-45212e3b33151b016ae4a597a898db0cc13d4e6b.zip
translate-c: Implement flexible arrays
Fixes #8759
Diffstat (limited to 'lib')
-rw-r--r--lib/std/meta.zig31
1 files changed, 31 insertions, 0 deletions
diff --git a/lib/std/meta.zig b/lib/std/meta.zig
index 18f761d86e..56b231eedb 100644
--- a/lib/std/meta.zig
+++ b/lib/std/meta.zig
@@ -1355,3 +1355,34 @@ test "isError" {
try std.testing.expect(isError(math.absInt(@as(i8, -128))));
try std.testing.expect(!isError(math.absInt(@as(i8, -127))));
}
+
+/// This function is for translate-c and is not intended for general use.
+/// Constructs a [*c] pointer with the const and volatile annotations
+/// from SelfType for pointing to a C flexible array of ElementType.
+pub fn FlexibleArrayType(comptime SelfType: type, ElementType: type) type {
+ switch (@typeInfo(SelfType)) {
+ .Pointer => |ptr| {
+ return @Type(TypeInfo{ .Pointer = .{
+ .size = .C,
+ .is_const = ptr.is_const,
+ .is_volatile = ptr.is_volatile,
+ .alignment = @alignOf(ElementType),
+ .child = ElementType,
+ .is_allowzero = true,
+ .sentinel = null,
+ } });
+ },
+ else => |info| @compileError("Invalid self type \"" ++ @tagName(info) ++ "\" for flexible array getter: " ++ @typeName(SelfType)),
+ }
+}
+
+test "Flexible Array Type" {
+ const Container = extern struct {
+ size: usize,
+ };
+
+ try testing.expectEqual(FlexibleArrayType(*Container, c_int), [*c]c_int);
+ try testing.expectEqual(FlexibleArrayType(*const Container, c_int), [*c]const c_int);
+ try testing.expectEqual(FlexibleArrayType(*volatile Container, c_int), [*c]volatile c_int);
+ try testing.expectEqual(FlexibleArrayType(*const volatile Container, c_int), [*c]const volatile c_int);
+}