defaultValue
Create a default value for a field from either default field initialization values or from struct_options
Parameters
- T:type
- type
- ContainerT:type
- type
- field_name:[]const u8
- []const u8
- struct_options:anytype
- anytype
Source
Implementation
pub fn defaultValue(T: type, ContainerT: type, comptime field_name: []const u8, struct_options: anytype) ?T {
// If the containing struct has a default value, get the field's default value from
// the corresponding field within the struct's default value.
inline for (struct_options) |option| {
if (@TypeOf(option).StructT == ContainerT and @typeInfo(ContainerT) == .@"struct") {
if (option.default_value) |default_value| {
if (@typeInfo(@FieldType(ContainerT, field_name)) == .optional) {
if (@field(default_value, field_name) != null) {
return @field(default_value, field_name);
}
} else {
return @field(default_value, field_name);
}
}
}
}
if (T == []u8 or T == []const u8) {
return "";
}
switch (@typeInfo(T)) {
inline .bool => return false,
inline .int => return 0,
inline .float => return 0.0,
inline .@"struct" => |si| {
comptime var default_found = false;
inline for (struct_options) |opt| {
if (@TypeOf(opt).StructT == T) {
default_found = true;
return opt.default_value;
}
}
if (!default_found) {
inline for (si.fields) |field| {
if (field.defaultValue() == null) {
// The struct can't be default initialized and no struct_options were supplied for this type.
return null;
}
}
}
return .{};
},
inline .@"union" => {
inline for (struct_options) |opt| {
if (@TypeOf(opt).StructT == T) {
return opt.default_value;
}
}
return null;
},
inline .@"enum" => |e| return @enumFromInt(e.fields[0].value),
inline .void => return {},
inline else => return null,
}
}