summaryrefslogtreecommitdiff
path: root/src/tuple.zig
blob: 4e53d3fa26981e8828f413cdff36ffde72332785 (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
const c = @import("c");
const zpy = @import("root.zig");

pub const Tuple = extern struct {
    const Self = @This();

    data: c.PyObject,

    pub fn new(length: usize) !*Self {
        return @ptrCast(c.PyTuple_New(@intCast(length)) orelse return error.Exception);
    }

    pub fn pack(values: []const *zpy.Object) !*Self {
        var tuple = try new(values.len);
        errdefer tuple.asObject().decref();

        for (values, 0..) |value, index| {
            try tuple.set(index, value);
        }

        return tuple;
    }

    pub fn size(self: *const Self) usize {
        return c.PyTuple_GET_SIZE(@ptrCast(self));
    }

    pub fn get(self: *const Self, index: usize) !*zpy.Object {
        return @ptrCast(
            c.PyTuple_GetItem(
                @ptrCast(self),
                @intCast(index),
            ) orelse return error.Exception,
        );
    }

    pub fn getUnchecked(self: *Self, index: usize) *zpy.Object {
        return @ptrCast(c.PyTuple.GET_ITEM(
            @ptrCast(self),
            @intCast(index),
        ));
    }

    pub fn set(self: *Self, index: usize, value: *zpy.Object) !void {
        if (c.PyTuple_SetItem(@ptrCast(self), @intCast(index), @ptrCast(value)) == -1) {
            return error.Exception;
        }
    }

    pub fn resize(self: *Self, newlen: usize) !void {
        if (c._PyTuple_Resize(@ptrCast(&self), @intCast(newlen)) == -1) {
            return error.Exception;
        }
    }

    pub fn asObject(self: *Self) *zpy.Object {
        return @ptrCast(self);
    }
};