Skip to content

change std.io.BufferedReader and std.io.BufferedWriter to accept the buffer as a runtime parameter, and use AnyReader / AnyWriter #19298

Description

@andrewrk

Problem statement:

  1. BufferedReader/BufferedWriter is instantiated many times, causing code bloat.
  2. BufferedReader/BufferedWriter as a parameter requires use of anytype, and it's infectious.

Proposed solution (starting point):

--- a/lib/std/io/buffered_writer.zig
+++ b/lib/std/io/buffered_writer.zig
@@ -3,10 +3,9 @@ const std = @import("../std.zig");
 const io = std.io;
 const mem = std.mem;
 
-pub fn BufferedWriter(comptime buffer_size: usize, comptime WriterType: type) type {
-    return struct {
-        unbuffered_writer: WriterType,
-        buf: [buffer_size]u8 = undefined,
+const BufferedWriter = struct {
+    unbuffered_writer: AnyWriter,
+    user_provided_buffer: []u8,
     end: usize = 0,
 
     pub const Error = WriterType.Error;
@@ -36,8 +35,10 @@ pub fn BufferedWriter(comptime buffer_size: usize, comptime WriterType: type) ty
         return bytes.len;
     }
 };
-}
 
-pub fn bufferedWriter(underlying_stream: anytype) BufferedWriter(4096, @TypeOf(underlying_stream)) {
-    return .{ .unbuffered_writer = underlying_stream };
+pub fn bufferedWriter(buffer: []u8, unbuffered_writer: AnyWriter) BufferedWriter {
+    return .{
+        .buffer = buffer,
+        .unbuffered_writer = unbuffered_writer,
+    };
 }

Downsides:

  • async functions don't really work across function pointer boundaries
  • opportunities for the programmer to bungle the lifetime of the buffer, causing UAF

Related:

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    breakingImplementing this issue could cause existing code to no longer compile or have different behavior.proposalThis issue suggests language modifications. If it also has the "accepted" label then it is planned.standard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions