private void addBuffer(int minCapacity)
  {
    if (this._bufferList.peekLast() != null)
    {
      this._alreadyBufferedSize += this._index;
      this._index = 0;
    }
    if (this._nextBufferSize < minCapacity)
    {
      this._nextBufferSize = nextPowerOf2(minCapacity);
    }

    // Make sure we always stay within maximum stream size.
    if (this._nextBufferSize > MAX_STREAM_SIZE - size())
    {
      this._nextBufferSize = MAX_STREAM_SIZE - size();
    }
    this._bufferList.add(new byte[this._nextBufferSize]);
    this._nextBufferSize *= 2;
  }
@Test
  @SuppressWarnings("unchecked")
  public void testAddBuffer() throws Exception
  {
    FastByteArrayOutputStream testStream = new FastByteArrayOutputStream();
    Field bufferListField = testStream.getClass().getDeclaredField("_bufferList");
    bufferListField.setAccessible(true);
    // Empty linked list until the first write.
    Assert.assertEquals(((LinkedList<byte[]>) bufferListField.get(testStream)).size(), 0);

    testStream.write(1);
    Assert.assertEquals(((LinkedList<byte[]>) bufferListField.get(testStream)).size(), 1);

    Field defaultSizeField = FastByteArrayOutputStream.class.getDeclaredField("DEFAULT_BUFFER_SIZE");
    defaultSizeField.setAccessible(true);
    int defaultSize = (int) defaultSizeField.get(null);

    byte[] testArray = new byte[defaultSize];
    testStream.write(testArray, 0, testArray.length);
    // Exceed the capacity of DEFAULT_BUFFER_SIZE and the second buffer is added.
    Assert.assertEquals(((LinkedList<byte[]>) bufferListField.get(testStream)).size(), 2);
    Assert.assertEquals(testStream.toByteArray().length, defaultSize + 1);
  }