const SomeErrorType = error{NewError};
const SomeStruct = struct {
pub const variable1: type = std.io.AnyReader.Error;
pub const variable2: type = SomeErrorType;
};
say if I have something like this… i would like to turn these into a struct field… something like the following…?
fn WrappedStruct(comptime in_type: type) type {
const type_info = @typeInfo(in_type);
if (type_info != .Struct) {
@compileError("expected struct argument, found " ++ @typeName(in_type));
}
if (type_info.Struct.layout != .Auto) {
@compileError("expected the container layout to be auto, found " ++ @tagName(type_info.Struct.layout));
}
const struct_info = type_info.Struct;
const fields_info = struct_info.fields;
comptime var fields: [struct_info.decls.len + fields_info.len]std.builtin.Type.StructField = undefined;
comptime var fields_idx = 0;
inline for (fields_info) |field| {
fields[fields_idx] = field;
fields_idx += 1;
}
inline for (struct_info.decls) |decl| {
const decl_as_field = @field(in_type, decl.name);
const decl_type = @TypeOf(decl_as_field);
const decl_type_info = @typeInfo(decl_type);
if (decl_type_info == .Fn) {
/* get wrapped function */;
} else {
fields[fields_idx] = .{
.name = decl.name,
.type = decl_type,
.default_value = null, /* what should it be? */
.is_comptime = true,
.alignment = 0,
};
}
fields_idx += 1;
}
// return custom struct type
return struct {};
}
what’s the x problem? well i just wanted to wrap all the public functions of a struct type into custom functions, say if SomeStruct
has function foo(self: @This(), var: u32) void
, would like to create a new custom Struct type which will still contain all the fields and public declarations and also function called foo(self: @This(), var: u32) void
except this function’s body would be something like:
// inline if possible
pub fn foo(self: Internal, var: u32) void {
/* does something custom */
return self.instance.foor(var);
}
// `Internal` should be just a be a wrapped struct to save the instance of the provided type.
and the user should be able to call it like this:
const WrappedSomeStruct = WrappedStruct(SomeStruct);
const wrappedSomeStruct = WrappedSomeStruct{};
wrappedSomeStruct.foo(); // this should call the custom wrapper function
// I would also like to expose all the public declaration `type`s which aren't a function.
Since I couldn’t find a way to create custom declaration based on comptime
argument, so basically converting all the declaration into comptime
Struct field.