@@ -36,7 +36,7 @@ const MAX_HTTP_REQUEST_SIZE = 4096;
3636// max message size
3737// +14 for max websocket payload overhead
3838// +140 for the max control packet that might be interleaved in a message
39- const MAX_MESSAGE_SIZE = 512 * 1024 + 14 ;
39+ const MAX_MESSAGE_SIZE = 512 * 1024 + 14 + 140 ;
4040
4141pub const Server = struct {
4242 app : * App ,
@@ -188,12 +188,15 @@ pub const Client = struct {
188188 // we expect the socket to come to us as nonblocking
189189 std .debug .assert (socket_flags & nonblocking == nonblocking );
190190
191+ var reader = try Reader (true ).init (server .allocator );
192+ errdefer reader .deinit ();
193+
191194 return .{
192195 .socket = socket ,
193196 .server = server ,
197+ .reader = reader ,
194198 .mode = .{ .http = {} },
195199 .socket_flags = socket_flags ,
196- .reader = .{ .allocator = server .allocator },
197200 .send_arena = ArenaAllocator .init (server .allocator ),
198201 };
199202 }
@@ -537,14 +540,23 @@ fn Reader(comptime EXPECT_MASK: bool) type {
537540
538541 // we add 140 to allow 1 control message (ping/pong/close) to be
539542 // fragmented into a normal message.
540- buf : [MAX_MESSAGE_SIZE + 140 ]u8 = undefined ,
543+ buf : []u8 ,
541544
542545 fragments : ? Fragments = null ,
543546
544547 const Self = @This ();
545548
549+ fn init (allocator : Allocator ) ! Self {
550+ const buf = try allocator .alloc (u8 , 32 * 1024 );
551+ return .{
552+ .buf = buf ,
553+ .allocator = allocator ,
554+ };
555+ }
556+
546557 fn deinit (self : * Self ) void {
547558 self .cleanup ();
559+ self .allocator .free (self .buf );
548560 }
549561
550562 fn cleanup (self : * Self ) void {
@@ -613,9 +625,17 @@ fn Reader(comptime EXPECT_MASK: bool) type {
613625 }
614626 } else if (message_len > MAX_MESSAGE_SIZE ) {
615627 return error .TooLarge ;
616- }
617-
618- if (buf .len < message_len ) {
628+ } 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 ];
635+ // we need more data
636+ return null ;
637+ } else if (buf .len < message_len ) {
638+ // we need more data
619639 return null ;
620640 }
621641
@@ -753,7 +773,7 @@ fn Reader(comptime EXPECT_MASK: bool) type {
753773
754774 // We're here because we either don't have enough bytes of the next
755775 // message, or we know that it won't fit in our buffer as-is.
756- std .mem .copyForwards (u8 , & self .buf , partial );
776+ std .mem .copyForwards (u8 , self .buf , partial );
757777 self .pos = 0 ;
758778 self .len = partial_bytes ;
759779 }
0 commit comments