summaryrefslogtreecommitdiff
path: root/src/Dict.zig
diff options
context:
space:
mode:
authorNathan Reiner <nathan@nathanreiner.xyz>2026-08-27 21:04:37 +0200
committerNathan Reiner <nathan@nathanreiner.xyz>2026-08-27 21:04:37 +0200
commit28f47b8399c4f3c4a64921fb16e38e44e8ce749e (patch)
tree53cde744130f2adf9c293fafde3c0a9c6a990d4b /src/Dict.zig
first commit
Diffstat (limited to 'src/Dict.zig')
-rw-r--r--src/Dict.zig66
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;
+}