feat: add support for init/deinit functions in Button context values

This commit is contained in:
CJ van den Berg 2025-04-23 19:46:27 +02:00
parent 9f117550fa
commit 6ae5dc5c4c
Signed by: neurocyte
GPG key ID: 8EB1E1BB660E3FB9

View file

@ -57,6 +57,7 @@ pub fn create(ctx_type: type, allocator: std.mem.Allocator, parent: Plane, opts:
.opts = opts, .opts = opts,
}; };
self.opts.label = try self.allocator.dupe(u8, opts.label); self.opts.label = try self.allocator.dupe(u8, opts.label);
try self.init();
return self; return self;
} }
@ -75,8 +76,18 @@ pub fn State(ctx_type: type) type {
const Self = @This(); const Self = @This();
pub const Context = ctx_type; pub const Context = ctx_type;
const child: type = switch (@typeInfo(Context)) {
.pointer => |p| p.child,
.@"struct" => Context,
else => struct {},
};
pub fn init(self: *Self) error{OutOfMemory}!void {
if (@hasDecl(child, "ctx_init")) return self.opts.ctx.ctx_init();
}
pub fn deinit(self: *Self, allocator: std.mem.Allocator) void { pub fn deinit(self: *Self, allocator: std.mem.Allocator) void {
if (@hasDecl(child, "ctx_deinit")) self.opts.ctx.ctx_deinit();
self.allocator.free(self.opts.label); self.allocator.free(self.opts.label);
self.plane.deinit(); self.plane.deinit();
allocator.destroy(self); allocator.destroy(self);