Skip to content

Commit bb9904f

Browse files
committed
Io: fix compile error in receive and receiveTimeout
Correctly uses the `netReceive` API. If an error was returned, we propagate that error, otherwise assert we only received one message.
1 parent b2895f3 commit bb9904f

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

lib/std/Io/net.zig

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1119,7 +1119,13 @@ pub const Socket = struct {
11191119
/// * `receiveTimeout`
11201120
pub fn receive(s: *const Socket, io: Io, buffer: []u8) ReceiveError!IncomingMessage {
11211121
var message: IncomingMessage = undefined;
1122-
assert(1 == try io.vtable.netReceive(io.userdata, s.handle, (&message)[0..1], buffer, .{}, .none));
1122+
const maybe_err, const count = io.vtable.netReceive(io.userdata, s.handle, (&message)[0..1], buffer, .{}, .none);
1123+
if (maybe_err) |err| switch (err) {
1124+
// No timeout is passed to `netReceieve`, so it must not return timeout related errors.
1125+
error.Timeout, error.UnsupportedClock => unreachable,
1126+
else => |e| return e,
1127+
};
1128+
assert(1 == count);
11231129
return message;
11241130
}
11251131

@@ -1139,7 +1145,9 @@ pub const Socket = struct {
11391145
timeout: Io.Timeout,
11401146
) ReceiveTimeoutError!IncomingMessage {
11411147
var message: IncomingMessage = undefined;
1142-
assert(1 == try io.vtable.netReceive(io.userdata, s.handle, (&message)[0..1], buffer, .{}, timeout));
1148+
const maybe_err, const count = io.vtable.netReceive(io.userdata, s.handle, (&message)[0..1], buffer, .{}, timeout);
1149+
if (maybe_err) |err| return err;
1150+
assert(1 == count);
11431151
return message;
11441152
}
11451153

lib/std/Io/net/test.zig

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,24 @@ test "listen on a unix socket, send bytes, receive bytes" {
304304
try testing.expectEqualSlices(u8, "Hello world!", buf[0..n]);
305305
}
306306

307+
test "bind to socket from ip address, send bytes, receive bytes" {
308+
if (builtin.single_threaded) return error.SkipZigTest;
309+
if (!net.has_unix_sockets) return error.SkipZigTest;
310+
311+
const io = testing.io;
312+
313+
const localhost: net.IpAddress = .{ .ip4 = .loopback(8000) };
314+
315+
const socket = try localhost.bind(io, .{ .mode = .dgram });
316+
defer socket.close(io);
317+
318+
try socket.send(io, &localhost, "test");
319+
320+
var buffer: [32]u8 = undefined;
321+
const message = try socket.receive(io, &buffer);
322+
try std.testing.expectEqualSlices(u8, "test", message.data);
323+
}
324+
307325
fn generateFileName(base_name: []const u8) ![]const u8 {
308326
const random_bytes_count = 12;
309327
const sub_path_len = comptime std.fs.base64_encoder.calcSize(random_bytes_count);

0 commit comments

Comments
 (0)