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

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

    data: c.PyObject,

    pub fn from(buffer: []const u8) *Self {
        return @ptrCast(c.PyUnicode_FromStringAndSize(@ptrCast(buffer), @intCast(buffer.len)));
    }

    pub fn asUtf8(self: *Self) ![]const u8 {
        var size: c.Py_ssize_t = undefined;
        const string: [*]const u8 = c.PyUnicode_AsUTF8AndSize(@ptrCast(self), &size);

        if (size == -1) return error.Exception;

        return string[0..@as(usize, @intCast(size))];
    }

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