main shar/altaica / compositor / src / objects.zig
 1const proto = @import("protocol.zig");
 2
 3extern "env" fn log_error(ptr: [*]const u8, len: u32) void;
 4
 5pub const Interface = proto.Interface;
 6
 7pub const Object = struct {
 8    id: u32,
 9    client_id: u32,
10    iface: Interface,
11};
12
13const MAX = 512;
14var pool: [MAX]?Object = [_]?Object{null} ** MAX;
15
16pub fn register(client_id: u32, id: u32, iface: Interface) ?*Object {
17    if (id == 0 or id >= MAX) {
18        const msg = "objects: object ID out of range\n";
19        log_error(msg, msg.len);
20        return null;
21    }
22    if (pool[id] != null) {
23        const msg = "objects: duplicate object ID\n";
24        log_error(msg, msg.len);
25        return null;
26    }
27    pool[id] = Object{ .id = id, .client_id = client_id, .iface = iface };
28    return &(pool[id] orelse unreachable);
29}
30
31pub fn lookup(client_id: u32, id: u32) ?*Object {
32    if (id == 0 or id >= MAX) return null;
33    const obj = pool[id] orelse return null;
34    if (obj.client_id != client_id) return null;
35    return &(pool[id] orelse unreachable);
36}
37
38pub fn remove(client_id: u32, id: u32) void {
39    if (id == 0 or id >= MAX) return;
40    const obj = pool[id] orelse return;
41    if (obj.client_id != client_id) return;
42    pool[id] = null;
43}
44
45pub fn removeAll(client_id: u32) void {
46    var i: usize = 0;
47    while (i < MAX) : (i += 1) {
48        if (pool[i]) |obj| {
49            if (obj.client_id == client_id) pool[i] = null;
50        }
51    }
52}