@@ -227,24 +227,10 @@ private int writeKnownLengthUncompressed(InputStream message, int messageLength)
227227 // Allocate the initial buffer chunk based on frame header + payload length.
228228 // Note that the allocator may allocate a buffer larger or smaller than this length
229229 knownLengthPendingAllocation = HEADER_LENGTH + messageLength ;
230- if (buffer == null ) {
231- buffer = allocateKnownLength ();
232- }
233230 writeRaw (headerScratch .array (), 0 , headerScratch .position ());
234231 return writeToOutputStream (message , outputStreamAdapter );
235232 }
236233
237- /**
238- * Allocate buffer according to {@link #knownLengthPendingAllocation} which is decremented after
239- * that.
240- */
241- private WritableBuffer allocateKnownLength () {
242- WritableBuffer newBuffer = bufferAllocator .allocate (knownLengthPendingAllocation );
243- knownLengthPendingAllocation -= Math .min (knownLengthPendingAllocation ,
244- newBuffer .writableBytes ());
245- return newBuffer ;
246- }
247-
248234 /**
249235 * Write a message that has been serialized to a sequence of buffers.
250236 */
@@ -304,10 +290,9 @@ private void writeRaw(byte[] b, int off, int len) {
304290 commitToSink (false , false );
305291 }
306292 if (buffer == null ) {
307- // Request a buffer allocation using the message length as a hint.
308- buffer = knownLengthPendingAllocation > 0
309- ? allocateKnownLength ()
310- : bufferAllocator .allocate (len );
293+ checkState (knownLengthPendingAllocation > 0 , "knownLengthPendingAllocation reached 0" );
294+ buffer = bufferAllocator .allocate (knownLengthPendingAllocation );
295+ knownLengthPendingAllocation -= min (knownLengthPendingAllocation , buffer .writableBytes ());
311296 }
312297 int toWrite = min (len , buffer .writableBytes ());
313298 buffer .write (b , off , toWrite );
@@ -424,11 +409,13 @@ public void write(int b) {
424409 write (singleByte , 0 , 1 );
425410 }
426411
412+ private static final int FIRST_BUFFER_SIZE = 4096 ;
413+
427414 @ Override
428415 public void write (byte [] b , int off , int len ) {
429416 if (current == null ) {
430417 // Request len bytes initially from the allocator, it may give us more.
431- current = bufferAllocator .allocate (len );
418+ current = bufferAllocator .allocate (Math . max ( FIRST_BUFFER_SIZE , len ) );
432419 bufferList .add (current );
433420 }
434421 while (len > 0 ) {
0 commit comments