One of the things I have done a better job of internalizing while working with zig over the last few months is that the less magic that exists, the better. In the case of parameterized functions, this means that it is much better to restrict the range of types that are permitted to be passed than to perform type manipulation. In other words, it's more confusing to see a function that is parameterized with `SomeType` taking a pointer to that type than having it be parameterized directly to take the pointer. Obviously there are exceptions to this rule, like std.mem.eql taking slices of its parameterized type. In fact, this new approach fixes some edge cases. Null userdata may now be passed in, since the user can now actually specify an optional pointer type (e.g. `?*void` may be used to provide always-null userdata). Additionally, a pointer to a constant value can now be passed in, which wasn't possible before (this could have been worked around by use of constCast and being careful, but that's an exceedingly bad option compared to having the type system work for you).
51 lines
1.5 KiB
Zig
51 lines
1.5 KiB
Zig
// This file is licensed under the CC0 1.0 license.
|
|
// See: https://creativecommons.org/publicdomain/zero/1.0/legalcode
|
|
|
|
const std = @import("std");
|
|
const nats = @import("nats");
|
|
|
|
fn onMessage(
|
|
userdata: *u32,
|
|
connection: *nats.Connection,
|
|
subscription: *nats.Subscription,
|
|
message: *nats.Message,
|
|
) void {
|
|
_ = subscription;
|
|
|
|
std.debug.print("Subject \"{s}\" received message: \"{s}\"\n", .{
|
|
message.getSubject(),
|
|
message.getData() orelse "[null]",
|
|
});
|
|
|
|
if (message.getReply()) |reply| {
|
|
connection.publish(reply, "salutations") catch @panic("HELP");
|
|
}
|
|
|
|
userdata.* += 1;
|
|
}
|
|
|
|
pub fn main() !void {
|
|
const connection = try nats.Connection.connectTo(nats.default_server_url);
|
|
defer connection.destroy();
|
|
|
|
var count: u32 = 0;
|
|
const subscription = try connection.subscribe(*u32, "channel", onMessage, &count);
|
|
defer subscription.destroy();
|
|
|
|
while (count < 10) : (nats.sleep(100)) {
|
|
const reply = try connection.request("channel", "greetings", 1000);
|
|
defer reply.destroy();
|
|
|
|
std.debug.print("Reply \"{s}\" got message: {s}\n", .{
|
|
reply.getSubject(),
|
|
reply.getData() orelse "[null]",
|
|
});
|
|
}
|
|
|
|
const stats = try connection.getStats();
|
|
std.debug.print(
|
|
"Server stats => {{\n\tmessages_in: {d} ({d} B),\n\tmessages_out: {d} ({d} B),\n\treconnects: {d}\n}}\n",
|
|
.{ stats.messages_in, stats.bytes_in, stats.messages_out, stats.bytes_out, stats.reconnects },
|
|
);
|
|
}
|