Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support iterator protocol #42

Merged
merged 7 commits into from
Sep 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions example/iterators.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const std = @import("std");
const py = @import("pydust");

pub const Range = py.class("Range", struct {
pub const __doc__ = "An example of iterable class";

const Self = @This();

lower: i64,
upper: i64,
step: i64,

pub fn __new__(args: struct { lower: i64, upper: i64, step: i64 }) !Self {
return .{ .lower = args.lower, .upper = args.upper, .step = args.step };
}

pub fn __iter__(self: *const Self) !*RangeIterator {
return try py.init(RangeIterator, .{ .next = self.lower, .stop = self.upper, .step = self.step });
}
});

pub const RangeIterator = py.class("RangeIterator", struct {
pub const __doc__ = "Range iterator";

const Self = @This();

next: i64,
stop: i64,
step: i64,

pub fn __new__(args: struct { next: i64, stop: i64, step: i64 }) !Self {
return .{ .next = args.next, .stop = args.stop, .step = args.step };
}

pub fn __next__(self: *Self) !?i64 {
if (self.next >= self.stop) {
return null;
}
defer self.next += self.step;
return self.next;
}
});

comptime {
py.module(@This());
}
2 changes: 2 additions & 0 deletions pydust/src/functions.zig
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ const reservedNames = .{
"__del__",
"__buffer__",
"__release_buffer__",
"__iter__",
"__next__",
};

/// Parse the arguments of a Zig function into a Pydust function siganture.
Expand Down
34 changes: 33 additions & 1 deletion pydust/src/pytypes.zig
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,20 @@ fn Slots(comptime definition: type, comptime Instance: type) type {
}};
}

if (@hasDecl(definition, "__iter__")) {
slots_ = slots_ ++ .{ffi.PyType_Slot{
.slot = ffi.Py_tp_iter,
.pfunc = @ptrCast(@constCast(&tp_iter)),
}};
}

if (@hasDecl(definition, "__next__")) {
slots_ = slots_ ++ .{ffi.PyType_Slot{
.slot = ffi.Py_tp_iternext,
.pfunc = @ptrCast(@constCast(&tp_iternext)),
}};
}

slots_ = slots_ ++ .{ffi.PyType_Slot{
.slot = ffi.Py_tp_methods,
.pfunc = @ptrCast(@constCast(&methods.pydefs)),
Expand Down Expand Up @@ -179,14 +193,32 @@ fn Slots(comptime definition: type, comptime Instance: type) type {
}

fn mp_length(pyself: *ffi.PyObject) callconv(.C) isize {
const lenFunc = @field(definition, "__len__");
const lenFunc = definition.__len__;
const self: *const Instance = @ptrCast(pyself);
const result = @as(isize, @intCast(lenFunc(&self.state)));
if (@typeInfo(@typeInfo(@TypeOf(lenFunc)).Fn.return_type.?) == .ErrorUnion) {
return result catch return -1;
}
return result;
}

fn tp_iter(pyself: *ffi.PyObject) callconv(.C) ?*ffi.PyObject {
const iterFunc = definition.__iter__;
const trampoline = tramp.Trampoline(@typeInfo(@TypeOf(iterFunc)).Fn.return_type.?);
const self: *const Instance = @ptrCast(pyself);
const result = iterFunc(&self.state) catch return null;
const obj = trampoline.wrap(result) catch return null;
return obj.py;
}

fn tp_iternext(pyself: *ffi.PyObject) callconv(.C) ?*ffi.PyObject {
const iterFunc = definition.__next__;
const trampoline = tramp.Trampoline(@typeInfo(@TypeOf(iterFunc)).Fn.return_type.?);
const self: *Instance = @constCast(@ptrCast(pyself));
const result = iterFunc(&self.state) catch return null;
const obj = trampoline.wrap(result orelse return null) catch return null;
return obj.py;
}
};
}

Expand Down
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ line-length = 120
[tool.ruff]
line-length = 120
select = ["F", "E", "W", "UP", "I001", "I002"]
target-version = "py310"

[build-system]
requires = ["poetry-core"]
Expand Down Expand Up @@ -85,3 +84,7 @@ root = "example/classes.zig"
[[tool.pydust.ext_module]]
name = "example.buffers"
root = "example/buffers.zig"

[[tool.pydust.ext_module]]
name = "example.iterators"
root = "example/iterators.zig"
11 changes: 11 additions & 0 deletions test/test_iterator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import pytest

from example import iterators


def test_range_iterator():
range_iterator = iter(iterators.Range(0, 10, 1))
for i in range(10):
assert next(range_iterator) == i
with pytest.raises(StopIteration):
next(range_iterator)