summaryrefslogtreecommitdiff
path: root/src/int.zig
blob: d5e7589c50aec686da9327c1f3406d1ad00752b7 (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
const std = @import("std");
const c = @import("c");

const zpy = @import("root.zig");

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

    data: c.PyObject,

    pub fn from(value: anytype) !*Self {
        const T = @TypeOf(value);
        const result = switch (@typeInfo(T)) {
            .int => |i| switch (i.signedness) {
                .signed => c.PyLong_FromLong(value),
                .unsigned => c.PyLong_FromUnsignedLong(value),
            },
            .comptime_int => c.PyLong_FromLong(value),
            .float => c.PyLong_FromDouble(value),
            else => @compileError("value must be numberic."),
        };

        return @ptrCast(result orelse return error.Exception);
    }

    pub fn as(self: *const Self, T: type) T {
        return switch(@typeInfo(T)) {
            .int => |i| switch (i) {
                .signed => c.PyLong_AsLong(self.object.ptr),
                .unsigned => c.PyLong_AsUnsignedLong(self.object.ptr),
            },
            .float => c.PyLong_AsDouble(self.object.ptr),
            else => @compileError("value must be numberic."),
        };
    }

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