From 3607c369677dac5583058e510d5155a40ee58198 Mon Sep 17 00:00:00 2001 From: Rylee Lyman Date: Sat, 21 Oct 2023 08:58:19 -0400 Subject: [PATCH] fix: convert `addMethod` bool to zig error --- src/class.zig | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/class.zig b/src/class.zig index d5f4ff2..0a0257f 100644 --- a/src/class.zig +++ b/src/class.zig @@ -60,10 +60,12 @@ pub const Class = struct { _ = c.class_replaceMethod(self.value, objc.sel(name).value, @ptrCast(&imp), null); } + pub const AddMethodError = error{AddMethodFailed} || std.mem.Allocator.Error; + /// allows adding new methods; returns true on success. // imp should be a function with C calling convention // whose first two arguments are a `c.id` and a `c.SEL`. - pub fn addMethod(self: Class, name: [:0]const u8, imp: anytype) !bool { + pub fn addMethod(self: Class, name: [:0]const u8, imp: anytype) AddMethodError!void { const fn_info = @typeInfo(@TypeOf(imp)).Fn; assert(fn_info.calling_convention == .C); assert(fn_info.is_var_args == false); @@ -72,7 +74,9 @@ pub const Class = struct { assert(fn_info.params[1].type == c.SEL); const str = try objc.createFnSignature(fn_info.return_type.?, fn_info.params); defer std.heap.raw_c_allocator.free(str); - return c.class_addMethod(self.value, objc.sel(name).value, @ptrCast(&imp), str.ptr); + if (!c.class_addMethod(self.value, objc.sel(name).value, @ptrCast(&imp), str.ptr)) { + return error.AddMethodFailed; + } } // only call this function between allocateClassPair and registerClassPair @@ -201,13 +205,13 @@ test "addMethod" { const My_Class = setup: { const My_Class = allocateClassPair(objc.getClass("NSObject").?, "my_class").?; defer registerClassPair(My_Class); - std.debug.assert(try My_Class.addMethod("my_addition", struct { + try My_Class.addMethod("my_addition", struct { fn imp(target: objc.c.id, sel: objc.c.SEL, a: i32, b: i32) callconv(.C) i32 { _ = sel; _ = target; return a + b; } - }.imp)); + }.imp); break :setup My_Class; }; const result = My_Class.msgSend(objc.Object, "alloc", .{})