| ... | @@ -0,0 +1,19 @@ |
| 1 | const std = @import("std"); |
| 2 | const string = []const u8; |
| 3 | const extras = @import("./lib.zig"); |
| 4 | |
| 5 | pub fn mapBy(allocator: std.mem.Allocator, slice: anytype, comptime field: std.meta.FieldEnum(std.meta.Elem(@TypeOf(slice)))) ![]std.meta.FieldType(std.meta.Elem(@TypeOf(slice)), field) { |
| 6 | const newslice = try allocator.alloc(std.meta.FieldType(std.meta.Elem(@TypeOf(slice)), field), slice.len); |
| 7 | for (newslice, slice) |*i, j| i.* = @field(j, @tagName(field)); |
| 8 | return newslice; |
| 9 | } |
| 10 | |
| 11 | test { |
| 12 | const alloc = std.testing.allocator; |
| 13 | const S = struct { x: u32 }; |
| 14 | const original: []const S = &.{ .{ .x = 53 }, .{ .x = 89 }, .{ .x = 19 }, .{ .x = 44 }, .{ .x = 29 } }; |
| 15 | const expected: []const u32 = &.{ 53, 89, 19, 44, 29 }; |
| 16 | const mapped = try mapBy(alloc, original, .x); |
| 17 | defer alloc.free(mapped); |
| 18 | try std.testing.expectEqualSlices(u32, expected, mapped); |
| 19 | } |