Skip to content

Commit efc983b

Browse files
committed
Start with 16K buffer (down from 32K). Use array list growth algorithm
1 parent 74d90f2 commit efc983b

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

src/server.zig

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -547,7 +547,7 @@ fn Reader(comptime EXPECT_MASK: bool) type {
547547
const Self = @This();
548548

549549
fn init(allocator: Allocator) !Self {
550-
const buf = try allocator.alloc(u8, 32 * 1024);
550+
const buf = try allocator.alloc(u8, 16 * 1024);
551551
return .{
552552
.buf = buf,
553553
.allocator = allocator,
@@ -626,12 +626,9 @@ fn Reader(comptime EXPECT_MASK: bool) type {
626626
} else if (message_len > MAX_MESSAGE_SIZE) {
627627
return error.TooLarge;
628628
} else if (message_len > self.buf.len) {
629-
const new_buf = try self.allocator.alloc(u8, message_len);
630-
@memcpy(new_buf[0..buf.len], buf);
631-
self.allocator.free(self.buf);
632-
self.buf = new_buf;
633-
self.len = buf.len;
634-
buf = new_buf[0..buf.len];
629+
const len = self.buf.len;
630+
self.buf = try growBuffer(self.allocator, self.buf, message_len);
631+
buf = self.buf[0..len];
635632
// we need more data
636633
return null;
637634
} else if (buf.len < message_len) {
@@ -780,6 +777,23 @@ fn Reader(comptime EXPECT_MASK: bool) type {
780777
};
781778
}
782779

780+
fn growBuffer(allocator: Allocator, buf: []u8, required_capacity: usize) ![]u8 {
781+
// from std.ArrayList
782+
var new_capacity = buf.len;
783+
while (true) {
784+
new_capacity +|= new_capacity / 2 + 8;
785+
if (new_capacity >= required_capacity) break;
786+
}
787+
788+
if (allocator.resize(buf, new_capacity)) {
789+
return buf.ptr[0..new_capacity];
790+
}
791+
const new_buffer = try allocator.alloc(u8, new_capacity);
792+
@memcpy(new_buffer[0..buf.len], buf);
793+
allocator.free(buf);
794+
return new_buffer;
795+
}
796+
783797
const Fragments = struct {
784798
type: Message.Type,
785799
message: std.ArrayListUnmanaged(u8),

0 commit comments

Comments
 (0)