nine-lives-later / zzmq

Zig Binding for ZeroMQ
Mozilla Public License 2.0
19 stars 2 forks source link

[FYI] Using RoutingId socket option #9

Closed ritalin closed 2 months ago

ritalin commented 2 months ago

ZSocket is supported RoutingId option. When you get this option, you must provide buffer.

What is buffer size? In specification, this buffer size is defined as 255 chars + null termination char.

If you takeaway the routing id outside scope, this buffer must be heap allocation.

fn routingId(allocator: std.mem.Allocator, socket: *ZSocket) ![]const u8 {   
     const routing_id = try self.allocator.alloc(u8, 256);
     var opt: zmq.ZSocketOption = .{.RoutingId = routing_id};
     try socket.getSocketOption(&opt);

     return routing_id; // note bellow
}

where you must not return out.RoutingId because of leaking memory.

To use following:

const routing_id = try routingId(allocator, socket);
defer allocator.free(routing_id);

someMethod(
    std.mem.sliceTo(routing_id, 0) // because a size of routing_id is 256
);

If you ingest inside scope, you'll use a fixed size array.

var routing_id: [256:0]u8 = undefined;
var opt: zmq.ZSocketOption = .{.RoutingId = &routing_id};
try socket.getSocketOption(&opt);

// (snip) ingesting...
ritalin commented 2 months ago

I got stuck, so I wrote this issue as a memo.