#replacement for fs.File.readToEndAlloc()

1 messages · Page 1 of 1 (latest)

austere pine
#

Is this a correct replacement now that readToEndAlloc() is gone?

    const stdin = std.fs.File.stdin();
-    const input = try stdin.readToEndAlloc(allocator, std.math.maxInt(u32));
+    var buf: [4096]u8 = undefined;
+    var freader = stdin.reader(&buf);
+    const input = try freader.interface.allocRemaining(allocator, .limited(std.math.maxInt(u32)));

I'm not really trying to limit the file size. So I guess I should use .unlimited instead of .limited().

tawdry pulsar
#

that will work.

note that if you need to do multiple reads, you might want to use an Allocating writer if you don't mind some extra code. that way you can reuse the same memory next time you want to do an read. for example, here is it being use to echo stdin:

const std = @import("std");

pub fn main() !void {
    // The length must be at least one, since `stdin.interface.streamDelimiterEnding()` calls
    // functions that assert there is such space.
    var stdin_buffer: [1024]u8 = undefined;
    var stdin = std.fs.File.stdin().reader(&stdin_buffer);

    var stdout_buffer: [1024]u8 = undefined;
    var stdout = std.fs.File.stdout().writer(&stdout_buffer);

    var input_writer: std.Io.Writer.Allocating = .init(std.heap.smp_allocator);
    defer input_writer.deinit();

    while (true) {
        // Toss any writes to stdout that would then appear in stdin.
        defer stdin.interface.tossBuffered();

        _ = try stdin.interface.streamDelimiterEnding(&input_writer.writer, '\n');

        // Read from the buffer so that we can reuse the allocated memory next loop.
        const input = input_writer.writer.buffered();
        // Discard what is in the input buffer to reuse the memory next loop.
        defer _ = input_writer.writer.consumeAll();

        try stdout.interface.writeAll(input);
        try stdout.interface.writeByte('\n');
        try stdout.interface.flush();
    }
}
austere pine
#

thanks! i've been using Allocating in a few other places. I didn't know about consumeAll(). that might be what i'm missing trying to figure out why some output seems to be missing and have been adding random flush() calls.

tawdry pulsar
#

consumeAll() sets the writer.end back to zero. if it was missing i think the buffer would just keep growing alongside the writer.seek. though, it may cause other issues based on usage around it that would be dependent on what the stuff around it was.

if you have a snippetable example, i could take a look if you want? though my reply may be delayed as i have to do something for about the next 10 minutes