I have this struct, and also 14 similar:
const Config: Type.Struct = @This();
reg: Register = undefined,
reflect_rx_data_received_on_irq_pin: bool = false,
reflect_tx_data_sent_on_irq_pin: bool = false,
reflect_max_retransmit_on_irq_pin: bool = false,
crc: Crc = .@"1byte",
power: Power = .off,
operational_mode: Mode = .tx,
pub fn init() Config {
return .{};
}
I have two functions with roles of serializer and deserializer
pub fn fromRegister(self: *Config, opt_data: ?[]const u8) !void {
if (opt_data == null or opt_data.?.len == 0) {
return error.NoData;
}
const data = opt_data.?;
self.reflect_rx_data_received_on_irq_pin = (data[0] & (1 << 6)) > 0;
self.reflect_tx_data_sent_on_irq_pin = (data[0] & (1 << 5)) > 0;
self.reflect_max_retransmit_on_irq_pin = (data[0] & (1 << 4)) > 0;
self.crc = try Crc.fromInt((data[0] & (0b11 << 2)) >> 2);
self.power = try Power.formInt(data[0] & (1 << 1));
self.operational_mode = try Mode.fromInt(data[0] & 1);
}
pub fn toRegister(self: Config) ?[]const u8 {
var data: u8 = 0;
data |= @as(u8, @intFromBool(self.reflect_rx_data_received_on_irq_pin)) << 6;
data |= @as(u8, @intFromBool(self.reflect_tx_data_sent_on_irq_pin)) << 5;
data |= @as(u8, @intFromBool(self.reflect_max_retransmit_on_irq_pin)) << 4;
data |= Crc.toInt(self.crc) << 2;
data |= Power.toInt(self.power) << 1;
data |= Mode.toInt(self.operational_mode) << 1;
return &.{data};
}
I want to replace them with functions that gets Type
and some extra prepared data with all shifts etc.
Then fn gets fields, and field by field, writes it to self
or read it from self
.
Something like this
self.write(@typeInfo(Config).fields[0].name, value);
or
self[@typeInfo(Config).fields[0].name] = value;