From efc983b009e5188e3a762c5cffd026a0544bbc6d Mon Sep 17 00:00:00 2001 From: Karl Seguin Date: Fri, 29 Aug 2025 10:33:27 +0800 Subject: [PATCH] Start with 16K buffer (down from 32K). Use array list growth algorithm --- src/server.zig | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/src/server.zig b/src/server.zig index 1d4b9ec5..fdcd5f95 100644 --- a/src/server.zig +++ b/src/server.zig @@ -547,7 +547,7 @@ fn Reader(comptime EXPECT_MASK: bool) type { const Self = @This(); fn init(allocator: Allocator) !Self { - const buf = try allocator.alloc(u8, 32 * 1024); + const buf = try allocator.alloc(u8, 16 * 1024); return .{ .buf = buf, .allocator = allocator, @@ -626,12 +626,9 @@ fn Reader(comptime EXPECT_MASK: bool) type { } else if (message_len > MAX_MESSAGE_SIZE) { return error.TooLarge; } else if (message_len > self.buf.len) { - const new_buf = try self.allocator.alloc(u8, message_len); - @memcpy(new_buf[0..buf.len], buf); - self.allocator.free(self.buf); - self.buf = new_buf; - self.len = buf.len; - buf = new_buf[0..buf.len]; + const len = self.buf.len; + self.buf = try growBuffer(self.allocator, self.buf, message_len); + buf = self.buf[0..len]; // we need more data return null; } else if (buf.len < message_len) { @@ -780,6 +777,23 @@ fn Reader(comptime EXPECT_MASK: bool) type { }; } +fn growBuffer(allocator: Allocator, buf: []u8, required_capacity: usize) ![]u8 { + // from std.ArrayList + var new_capacity = buf.len; + while (true) { + new_capacity +|= new_capacity / 2 + 8; + if (new_capacity >= required_capacity) break; + } + + if (allocator.resize(buf, new_capacity)) { + return buf.ptr[0..new_capacity]; + } + const new_buffer = try allocator.alloc(u8, new_capacity); + @memcpy(new_buffer[0..buf.len], buf); + allocator.free(buf); + return new_buffer; +} + const Fragments = struct { type: Message.Type, message: std.ArrayListUnmanaged(u8),