1const std = @import("std");
2const string = []const u8;
3const extras = @import("./lib.zig");
4const expectSimilarType = extras.expectSimilarType;
5
6/// Creates a new version of struct T where all fields are optional.
7/// Name inspried by https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype.
8pub fn Partial(comptime T: type) type {
9 const fields = std.meta.fields(T);
10 var names: [fields.len][]const u8 = undefined;
11 var types: [fields.len]type = undefined;
12 var attrs: [fields.len]std.builtin.Type.StructField.Attributes = undefined;
13 for (fields, 0..) |item, i| {
14 names[i] = item.name;
15 types[i] = ?item.type;
16 attrs[i] = .{ .default_value_ptr = &@as(?item.type, null) };
17 }
18 return @Struct(.auto, null, &names, &types, &attrs);
19}
20
21test {
22 try expectSimilarType(
23 Partial(struct {
24 a: u32,
25 b: u8,
26 c: u16,
27 }),
28 struct {
29 a: ?u32,
30 b: ?u8,
31 c: ?u16,
32 },
33 );
34}
35
36test {
37 try expectSimilarType(
38 Partial(struct {
39 a: ?u8,
40 }),
41 struct {
42 a: ??u8,
43 },
44 );
45}