Help converting u8 to string

The documentation of std.io.buffered_writer.bufferedWriter(underlying_stream) shows that the bufferedWriter function returns a value of type BufferedWriter(4096, @TypeOf(underlying_stream)). Here 4096 is the buffer size used.

If you want to specify your own buffer size, you should (currently) be able to do it as follows:

pub fn main() !void {
    // This would not specify buffer size and default to 4096:
    // var stdout_bufwriter = std.io.bufferedWriter(std.io.getStdOut().writer());
    //
    // Instead we do:
    const stdout_unbuf = std.io.getStdOut().writer();
    const bufsize = 8192;
    var stdout_bufwriter = std.io.BufferedWriter(
        bufsize,
        @TypeOf(stdout_unbuf),
    ){
        .unbuffered_writer = stdout_unbuf,
    };

    var stdout = stdout_bufwriter.writer();
    try stdout.print("Hello Buffer!\n", .{});
    try stdout_bufwriter.flush();
}

As I understand, the interface is going to be changed soon when I/O is being reworked for async/await. So in the near future, it might work differently. As I learned here, there is already a demo branch in the repository for the new async/await I/O concept, but I didn’t have a look yet, and not sure what state it is in.

On my system, 4096 happens to be equivalent to the memory page size, but I think that may be platform dependent.

$ getconf PAGESIZE
4096

Note, however, that BufferedWriter(4096, _) is slightly larger than 4096 bytes, so it won’t fit in one memory page (if memory page size is 4096). On my system:

pub fn main() void {
    std.debug.print("Total size = {}\n", .{
        @sizeOf(std.io.BufferedWriter(4096, std.fs.File)),
    });
}
Total size = 4112

Yet, the mere buffer (disregarding the data for the underlying stream) would be 4096 and thus fit into one memory page for many platforms, I assume. And those 4096 bytes would then also be the amount that is written per system call, I believe.

As far as I understand, the BufferedWriter isn’t necessarily on the heap, but if you simply assign it to a variable in main, it would be on the stack. BufferedWriter does not perform further allocation.

I don’t know. I would assume that a buffer size of 8192, for example, would result in the half amount of system calls required at the expense of a larger latency and more memory use.

I personally wouldn’t worry that much and use the default values unless you want to transfer/generate really big amounts of data (maybe if you write several gigabytes in short time?). But I don’t know really.

1 Like