diff options
Diffstat (limited to 'src/Dict.zig')
| -rw-r--r-- | src/Dict.zig | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/src/Dict.zig b/src/Dict.zig new file mode 100644 index 0000000..89964cf --- /dev/null +++ b/src/Dict.zig @@ -0,0 +1,66 @@ +const std = @import("std"); +const c = @import("c"); + +const zpy = @import("root.zig"); + +const Self = @This(); + +object: zpy.Object, + +pub const Key = union(enum) { + string: [*c]const u8, + object: zpy.Object, +}; + +pub fn new() zpy.Error!Self { + if (c.PyDict_New()) |object| { + return .{ .object = .fromPtr(object) }; + } + + return error.Exception; +} + +pub fn clear(self: *Self) void { + c.PyDict_Clear(self.object.ptr); +} + +pub fn contains(self: *const Self, key: Key) bool { + return switch (key) { + .string => |str| c.PyDict_ContainsString(self.object.ptr, str), + .object => |obj| c.PyDict_Contains(self.object.ptr, obj.ptr), + } == 1; +} + +pub fn copy(self: *const Self) Self { + return .{ .object = .fromPtr(c.PyDict_Copy(self.object.ptr)) }; +} + +pub fn set(self: *Self, key: Key, value: zpy.Object) !void { + const ret = switch (key) { + .string => |str| c.PyDict_SetItemString(self.object.ptr, str, value.ptr), + .object => |obj| c.PyDict_SetItem(self.object.ptr, obj.ptr, value.ptr), + }; + + if (ret == -1) return error.Exception; +} + +pub fn get(self: *const Self, key: Key) ?zpy.Object { + return .fromC(switch (key) { + .string => |str| c.PyDict_GetItemString(self.object.ptr, str), + .object => |obj| c.PyDict_GetItem(self.object.ptr, obj.ptr), + }); +} + +pub fn delete(self: *Self, key: Key) !void { + const ret = switch (key) { + .string => |str| c.PyDict_DelItemString(self.object.ptr, str), + .object => |obj| c.PyDict_DelItem(self.object.ptr, obj.ptr), + }; + + if (ret == -1) return error.Exception; +} + +pub fn deinit(self: *Self) void { + self.object.decref(); + self.* = undefined; +} |