const std = @import("std"); const c = @import("c"); const zpy = @import("root.zig"); pub const List = extern struct { const Self = @This(); data: c.PyObject, pub fn new(items: []const *zpy.Object) !*Self { var list: *Self = @ptrCast(c.PyList_New(@intCast(items.len)) orelse return error.Exception); errdefer list.asObject().decref(); for (items, 0..) |item, index| { list.setUnchecked(index, item); } return list; } pub fn size(self: *const Self) usize { return @as(usize, c.PyList_Size(@ptrCast(@constCast(self)))); } pub fn get(self: *const Self, index: usize) !*zpy.Object { return @ptrCast(c.PyList_GetItem(@ptrCast(self), @intCast(index)) orelse return error.Exception); } pub fn getUnchecked(self: *const Self, index: usize) !*zpy.Object { return @ptrCast(c.PyList_GET_ITEM(@ptrCast(self), @intCast(index)) orelse return error.Exception); } pub fn set(self: *Self, index: usize, value: *zpy.Object) !void { if (c.PyList_SetItem(@ptrCast(self), @intCast(index), @ptrCast(value)) == -1) { return error.Exception; } } /// Sets item without any error checking or releasing the resource when replacing. pub fn setUnchecked(self: *Self, index: usize, value: *zpy.Object) void { c.PyList_SET_ITEM(@ptrCast(self), @intCast(index), @ptrCast(value)); } pub fn insert(self: *Self, index: usize, value: *zpy.Object) !void { if (c.PyList_Insert(@ptrCast(self), @intCast(index), @ptrCast(value)) == -1) { return error.Exception; } } pub fn append(self: *Self, value: *zpy.Object) !void { if (c.PyList_Append(@ptrCast(self), @ptrCast(value)) == -1) { return error.Exception; } } pub fn getSlice(self: *const Self, from: usize, to: usize) !*Self { return @ptrCast(c.PyList_GetSlice( @ptrCast(@constCast(self)), @intCast(from), @intCast(to), ) orelse return error.Exception); } pub fn setSlice(self: *Self, from: usize, to: usize, itemlist: *zpy.Object) !void { if (c.PyList_SetSlice( @ptrCast(self), @intCast(from), @intCast(to), @ptrCast(itemlist), ) == -1) { return error.Exception; } } pub fn extend(self: *Self, iterable: *zpy.Object) !void { if (c.PyList_Extend( @ptrCast(self), @ptrCast(iterable), ) == -1) { return error.Exception; } } pub fn clear(self: *Self) void { c.PyList_Clear(@ptrCast(self)); } pub fn sort(self: *Self) !void { if (c.PyList_Sort(@ptrCast(self)) == -1) { return error.Exception; } } pub fn reverse(self: *Self) !void { if (c.PyList_Sort(@ptrCast(self)) == -1) { return error.Exception; } } pub fn asTuple(self: *Self) *zpy.Tuple { return @ptrCast(c.PyList_AsTuple(@ptrCast(self))); } pub fn asObject(self: *Self) *zpy.Object { return @ptrCast(self); } };