authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2025-08-23 21:25:48 -07:00
committergravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2025-08-23 21:25:48 -07:00
loga53ead2fb5378e9b09cb2f68e8a2b7cddfe086d2
treeca334895d41ad4832d756ab583facd653608a716
parent3132fef43acd717b4d22c250358a0ee4ebac7384

it's alive!


3 files changed, 59 insertions(+), 0 deletions(-)

AnyReadable.zig created+14
......@@ -0,0 +1,14 @@
1const std = @import("std");
2
3const nio = @import("./nio.zig");
4const AnyReadable = @This();
5
6readFn: *const fn (*anyopaque, []u8) anyerror!usize,
7state: *anyopaque,
8
9pub fn read(r: *AnyReadable, buffer: []u8) !usize {
10 return r.readFn(r.state, buffer);
11}
12
13pub const ReadError = anyerror;
14pub usingnamespace nio.Readable(@This());
README.md+2
......@@ -7,3 +7,5 @@
77[![Zigmod](https://img.shields.io/badge/Zigmod-latest-f7a41d)](https://github.com/nektro/zigmod)
88
99Nektro's IO, an alternative to `std.io`.
10
11Some code ported from Zig 0.14.1, via MIT Copyright (c) Zig contributors. New code MPL-2.0.
nio.zig+43
......@@ -1 +1,44 @@
11const std = @import("std");
2
3pub fn Readable(T: type) type {
4 return struct {
5 const Error = T.ReadError;
6
7 /// Returns the number of bytes read. It may be less than buffer.len.
8 /// If the number of bytes read is 0, it means end of stream.
9 /// End of stream is not an error condition.
10 // pub fn read(self: *T, buffer: []u8) Error!usize {
11 // }
12
13 /// Returns the number of bytes read. If the number read is smaller than `buffer.len`, it
14 /// means the stream reached the end. Reaching the end of a stream is not an error
15 /// condition.
16 pub fn readAll(self: *T, buffer: []u8) Error!usize {
17 return self.readAtLeast(buffer, buffer.len);
18 }
19
20 /// Returns the number of bytes read, calling the underlying read
21 /// function the minimal number of times until the buffer has at least
22 /// `len` bytes filled. If the number read is less than `len` it means
23 /// the stream reached the end. Reaching the end of the stream is not
24 /// an error condition.
25 pub fn readAtLeast(self: *T, buffer: []u8, len: usize) Error!usize {
26 std.debug.assert(len <= buffer.len);
27 var index: usize = 0;
28 while (index < len) {
29 const amt = try self.read(buffer[index..]);
30 if (amt == 0) break;
31 index += amt;
32 }
33 return index;
34 }
35
36 /// If the number read would be smaller than `buf.len`, `error.EndOfStream` is returned instead.
37 pub fn readNoEof(self: *T, buf: []u8) (Error || error{EndOfStream})!void {
38 const amt_read = try self.readAll(buf);
39 if (amt_read < buf.len) return error.EndOfStream;
40 }
41 };
42}
43
44pub const AnyReadable = @import("./AnyReadable.zig");