From 08364ac773bdc95b9407974b5c761dbdab863f4d Mon Sep 17 00:00:00 2001 From: Loris Cro Date: Tue, 16 Jun 2020 23:14:05 +0200 Subject: [PATCH] read Signed-off-by: Loris Cro --- lib/std/event/loop.zig | 40 ++++++++++++++++++++++++++-------------- lib/std/fs/file.zig | 8 +++++--- lib/std/os.zig | 7 +------ 3 files changed, 32 insertions(+), 23 deletions(-) diff --git a/lib/std/event/loop.zig b/lib/std/event/loop.zig index 2dc1d5659e..7adc6e3a8f 100644 --- a/lib/std/event/loop.zig +++ b/lib/std/event/loop.zig @@ -822,23 +822,35 @@ pub const Loop = struct { /// Performs an async `os.read` using a separate thread. /// `fd` must block and not return EAGAIN. - pub fn read(self: *Loop, fd: os.fd_t, buf: []u8) os.ReadError!usize { - var req_node = Request.Node{ - .data = .{ - .msg = .{ - .read = .{ - .fd = fd, - .buf = buf, - .result = undefined, + pub fn read(self: *Loop, fd: os.fd_t, buf: []u8, simulate_evented: bool) os.ReadError!usize { + if (simulate_evented) { + var req_node = Request.Node{ + .data = .{ + .msg = .{ + .read = .{ + .fd = fd, + .buf = buf, + .result = undefined, + }, }, + .finish = .{ .TickNode = .{ .data = @frame() } }, }, - .finish = .{ .TickNode = .{ .data = @frame() } }, - }, - }; - suspend { - self.posixFsRequest(&req_node); + }; + suspend { + self.posixFsRequest(&req_node); + } + return req_node.data.msg.read.result; + } else { + while (true) { + return os.read(fd, buf) catch |err| switch (err) { + error.WouldBlock => { + self.waitUntilFdReadable(fd); + continue; + }, + else => return err, + }; + } } - return req_node.data.msg.read.result; } /// Performs an async `os.readv` using a separate thread. diff --git a/lib/std/fs/file.zig b/lib/std/fs/file.zig index 73babf5fa2..bd0b8a2943 100644 --- a/lib/std/fs/file.zig +++ b/lib/std/fs/file.zig @@ -414,10 +414,12 @@ pub const File = struct { pub fn read(self: File, buffer: []u8) ReadError!usize { if (is_windows) { return windows.ReadFile(self.handle, buffer, null, self.intended_io_mode); - } else if (self.capable_io_mode != self.intended_io_mode) { - return std.event.Loop.instance.?.read(self.handle, buffer); - } else { + } + + if (self.intended_io_mode == .blocking or !std.io.is_async) { return os.read(self.handle, buffer); + } else { + return std.event.Loop.instance.?.read(self.handle, buffer, self.capable_io_mode != self.intended_io_mode); } } diff --git a/lib/std/os.zig b/lib/std/os.zig index 023c1d5971..7db545a17c 100644 --- a/lib/std/os.zig +++ b/lib/std/os.zig @@ -366,12 +366,7 @@ pub fn read(fd: fd_t, buf: []u8) ReadError!usize { EINTR => continue, EINVAL => unreachable, EFAULT => unreachable, - EAGAIN => if (std.event.Loop.instance) |loop| { - loop.waitUntilFdReadable(fd); - continue; - } else { - return error.WouldBlock; - }, + EAGAIN => return error.WouldBlock, EBADF => return error.NotOpenForReading, // Can be a race condition. EIO => return error.InputOutput, EISDIR => return error.IsDir,