From 28aded9c2f344c95f0e2f70b67188b6ad402daef Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Tue, 5 Sep 2023 09:30:59 +0100 Subject: [PATCH 1/2] Add PyBool --- pydust/src/types.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/pydust/src/types.zig b/pydust/src/types.zig index ae43acfe..7384202f 100644 --- a/pydust/src/types.zig +++ b/pydust/src/types.zig @@ -1,3 +1,4 @@ +pub usingnamespace @import("types/bool.zig"); pub usingnamespace @import("types/dict.zig"); pub usingnamespace @import("types/error.zig"); pub usingnamespace @import("types/float.zig"); From 21493299f5a4e8059e04ab51d15f5654671709bd Mon Sep 17 00:00:00 2001 From: Nicholas Gates Date: Tue, 5 Sep 2023 09:31:05 +0100 Subject: [PATCH 2/2] Add PyBool --- pydust/src/types/bool.zig | 47 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 pydust/src/types/bool.zig diff --git a/pydust/src/types/bool.zig b/pydust/src/types/bool.zig new file mode 100644 index 00000000..5199b81e --- /dev/null +++ b/pydust/src/types/bool.zig @@ -0,0 +1,47 @@ +const std = @import("std"); +const py = @import("../pydust.zig"); +const ffi = py.ffi; +const PyError = @import("../errors.zig").PyError; + +/// Wrapper for Python PyBool. +/// +/// See: https://docs.python.org/3/c-api/bool.html +/// +/// Note: refcounting semantics apply, even for bools! +pub const PyBool = extern struct { + obj: py.PyObject, + + pub fn incref(self: PyBool) void { + self.obj.incref(); + } + + pub fn decref(self: PyBool) void { + self.obj.decref(); + } + + pub inline fn true_() PyBool { + return .{ .obj = .{ .py = ffi.PyBool_FromLong(1) } }; + } + + pub inline fn false_() PyBool { + return .{ .obj = .{ .py = ffi.PyBool_FromLong(0) } }; + } + + pub fn asbool(self: PyBool) bool { + return ffi.Py_IsTrue(self.obj.py) == 1; + } +}; + +test "PyBool" { + py.initialize(); + defer py.finalize(); + + const pytrue = PyBool.true_(); + defer pytrue.decref(); + + const pyfalse = PyBool.false_(); + defer pyfalse.decref(); + + try std.testing.expect(pytrue.asbool()); + try std.testing.expect(!pyfalse.asbool()); +}