Merge pull request #1210 from violetagg/grow-data-buffer

* grow-data-buffer:
  DefaultDataBuffer improvements
This commit is contained in:
Arjen Poutsma
2016-10-18 13:48:08 +02:00
2 changed files with 21 additions and 1 deletions

View File

@@ -272,10 +272,13 @@ public class DefaultDataBuffer implements DataBuffer {
ByteBuffer.allocate(minCapacity));
// Explicit cast for compatibility with covariant return type on JDK 9's ByteBuffer
((Buffer) oldBuffer).position(this.readPosition);
final int remaining = readableByteCount();
((Buffer) oldBuffer).position(this.readPosition).limit(this.writePosition);
newBuffer.put(oldBuffer);
this.byteBuffer = newBuffer;
this.readPosition = 0;
this.writePosition = remaining;
oldBuffer.clear();
}

View File

@@ -20,6 +20,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.junit.Test;
@@ -266,4 +267,20 @@ public class DataBufferTests extends AbstractDataBufferAllocatingTestCase {
}
@Test
public void growDataBuffer() {
DataBuffer buffer = stringBuffer("Hello World!");
byte[] bytes = new byte[5];
buffer.read(bytes);
assertArrayEquals("Hello".getBytes(StandardCharsets.UTF_8), bytes);
buffer.write("!!".getBytes(StandardCharsets.UTF_8));
bytes = new byte[9];
buffer.read(bytes);
assertArrayEquals(" World!!!".getBytes(StandardCharsets.UTF_8), bytes);
}
}