summaryrefslogtreecommitdiff
path: root/src/Dict.zig
blob: 89964cfcb11344eb72b91c96ebc2c43f8e63f933 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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;
}