How to exactly replicate ``.adaptToOldInterface().readAllAlloc(...);`` using new API

Hello,

I have a function that calls reader.adaptToOldInterface().readAllAlloc(allocator, std.math.maxInt(usize)); on a readerStreaming that was obtained from a stdin which is in raw mode. How to I replicate readAllAllocs behavior using purely the new API?

I posted this question already but only got the answer for something else I didn’t know and then the thread went silent. I renamed it to the question that was then answered, so that if anyone else has that other question they can find it.

1 Like

Use an allocator to allocate memory for a buffer and use std.Io.Reader.readSliceShort to read into the buffer.

I believe that std.Io.Reader.readAlloc does not work because it expects the exact read length or less, otherwise it fails with error.EndOfStream.


My questions are:

  • Why readSliceShort is not called read?
  • Why readAlloc fails with error.EndOfStream instead of filling the buffer and returning the length. It is useless this way or am I missing something?

@karlseguin on his latest post also expects a read function:

I feel a bit more confident about the weirdness of not having a read(buf: []u8) !usize function on Reader, but at this point I wouldn’t bet on me.

1 Like

So I guess that readAllAlloc no longer has a direct equivalent?

I tried to use streamRemaining and allocRemaining and stream into an allocating reader or just return the bytes but that just read once and then somehow broke the reader in the next iteration, because after the first read it would only return 0 bytes. I find this strange because I dont see just from its documentation how it would behave differently to readAllAlloc

I use a helper function if I want to read until EndOfStream, e.g.

fn readAllAlloc(alc: std.mem.Allocator, r: *std.Io.Reader) ![]u8 {
    var aw: Writer.Allocating = .init(alc);
    defer aw.deinit();
    _ = try r.streamRemaining(&aw.writer);
    return aw.toOwnedSlice();
}
2 Likes

This also does not work, it receives input once and then leaves the reader in a state that somehow always makes it return 0 bytes.

This works, but is sadly not a single function:

        var buf: [256]u8 = undefined;
        var len = buf.len;
        while (len == buf.len) {
            len = try self.stdin.readSliceShort(&buf);
            try bytes.writer.writeAll(buf[0..len]);
        }

Could you provide the full code + steps to reproduce this? Seems like a bug.

I have uploaded the broken commit here

If you feel like it id be interested in a little code review or basic opinion, because Im a student and so far havent worked professionally

This runs on 0.15.1 and just zig build run reproduces it on ghostty. The issue is that input doesnt work unless uncommenting the marked line. The interesting function is in Tty.zig