authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2025-04-15 03:14:30 -07:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2025-04-15 03:14:30 -07:00
log9af9dd24bed9a6b351beae3b6414e807faeeaeb3
treebe331cbdd837eff839654e237f848551ea5ee9cc
parent9abeb2ac150728409877a3d0003e9a009acfc176

add StructOfArrays


2 files changed, 40 insertions(+), 0 deletions(-)

src/StructOfArrays.zig created+39
......@@ -0,0 +1,39 @@
1const std = @import("std");
2const string = []const u8;
3const extras = @import("./lib.zig");
4const expectSimilarType = extras.expectSimilarType;
5
6pub fn StructOfArrays(len: usize, T: type) type {
7 const fields = std.meta.fields(T);
8 var new_fields: [fields.len]std.builtin.Type.StructField = undefined;
9 for (fields, 0..) |item, i| {
10 new_fields[i] = .{
11 .name = item.name,
12 .type = [len]item.type,
13 .default_value = null,
14 .is_comptime = false,
15 .alignment = @alignOf([len]item.type),
16 };
17 }
18 const result = new_fields[0..fields.len];
19 return @Type(@unionInit(std.builtin.Type, "Struct", .{
20 .layout = .auto,
21 .backing_integer = null,
22 .fields = result,
23 .decls = &.{},
24 .is_tuple = false,
25 }));
26}
27
28test {
29 try expectSimilarType(
30 StructOfArrays(10, struct {
31 x: u8,
32 y: u16,
33 }),
34 struct {
35 x: [10]u8,
36 y: [10]u16,
37 },
38 );
39}
src/lib.zig+1
......@@ -106,3 +106,4 @@ pub usingnamespace @import("./isContainer.zig");
106106pub usingnamespace @import("./hasFn.zig");
107107pub usingnamespace @import("./hasFields.zig");
108108pub usingnamespace @import("./StructOfSlices.zig");
109pub usingnamespace @import("./StructOfArrays.zig");