Skip to content

Instantly share code, notes, and snippets.

@dgv
Created December 11, 2025 02:52
Show Gist options
  • Select an option

  • Save dgv/4c75c1c6543843c9407295b4261c4d93 to your computer and use it in GitHub Desktop.

Select an option

Save dgv/4c75c1c6543843c9407295b4261c4d93 to your computer and use it in GitHub Desktop.
simple roundrobin in zig https://zig.fly.dev/p/KyUO8zcDG9n
const std = @import("std");
const testing = std.testing;
const RoundRobinError = error{
NotExists,
};
pub const RoundRobin = struct {
const Self = @This();
ips: []std.net.Address = undefined,
var atomic: u32 = undefined;
pub fn init(ips: []std.net.Address) RoundRobinError!RoundRobin {
if (ips.len == 0) {
return RoundRobinError.NotExists;
}
return .{ .ips = ips };
}
pub fn next(self: Self) std.net.Address {
@atomicStore(u32, &atomic, atomic + 1, .release);
const n = atomic;
return self.ips[(n - 1) % self.ips.len];
}
};
pub fn main() !void {
var ips = [_]std.net.Address{
try std.net.Address.parseIp("100.123.10.20", 0),
try std.net.Address.parseIp("100.123.30.40", 0),
try std.net.Address.parseIp("100.123.50.60", 0),
try std.net.Address.parseIp("100.123.70.80", 0),
};
const rr = try RoundRobin.init(&ips);
_ = rr.next(); // "100.123.50.60"
_ = rr.next(); // "100.123.70.80"
_ = rr.next(); // "100.123.10.20"
const lastIP = rr.next(); // "100.123.30.40"
std.debug.print("available ips {any}\n", .{ips});
std.testing.expect(std.net.Address.eql(lastIP, try std.net.Address.parseIp("100.123.30.40", 0))) catch {
std.debug.print("got unexpected ip {?}", .{lastIP});
return;
};
std.debug.print("last ip: {?}", .{lastIP});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment