summaryrefslogtreecommitdiff
path: root/src/bytes.zig
blob: f1eb258e91bae98db42f08fa826cd8472469444e (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
41
42
43
const c = @import("c");
const zpy = @import("root.zig");

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

    data: c.PyObject,

    pub fn fromString(string: []const u8) !*Self {
        return @ptrCast(c.PyBytes_FromStringAndSize(@ptrCast(string), string.len) orelse return error.Exception);
    }

    pub fn fromObject(object: *zpy.Object) !*Self {
        return @ptrCast(c.PyBytes_FromObject(@ptrCast(object)) orelse return error.Exception);
    }

    pub fn size(self: *const Self) usize {
        return @intCast(c.PyBytes_Size(@ptrCast(@constCast(self))));
    }

    pub fn toString(self: *Self) []const u8 {
        var buffer: [*]const u8 = undefined;
        var length: c.Py_ssize_t = undefined;

        if (c.PyBytes_AsStringAndSize(@ptrCast(self), &buffer, &length) == -1) {
            return error.Exception;
        }

        return buffer[0..length];
    }

    pub fn concat(self: *Self, new: *Self) !void {
        c.PyBytes_Concat(@ptrCast(&self), @ptrCast(new));
    }

    pub fn concatAndDelete(self: *Self, new: *Self) !void {
        c.PyBytes_ConcatAndDel(@ptrCast(&self), @ptrCast(new));
    }

    pub fn join(self: *Self, object: *zpy.Object) !*zpy.Object {
        return @ptrCast(c.PyBytes_Join(@ptrCast(self), @ptrCast(object)) orelse return error.Exception);
    }
};