protected final void ensureCapacity(final int index, final int length)
    {
        if (index < 0 || length < 0)
        {
            throw new IndexOutOfBoundsException("negative value: index=" + index + " length=" + length);
        }

        final long resultingPosition = index + (long)length;
        final int currentCapacity = capacity;
        if (resultingPosition > currentCapacity)
        {
            if (resultingPosition > MAX_BUFFER_LENGTH)
            {
                throw new IndexOutOfBoundsException(
                    "index=" + index + " length=" + length + " maxCapacity=" + MAX_BUFFER_LENGTH);
            }

            final int newCapacity = calculateExpansion(currentCapacity, resultingPosition);
            final ByteBuffer newBuffer = ByteBuffer.allocateDirect(newCapacity);
            final long newAddress = address(newBuffer);

            getBytes(0, newBuffer, 0, currentCapacity);

            byteBuffer = newBuffer;
            addressOffset = newAddress;
            capacity = newCapacity;
        }
    }
@Test
    void ensureCapacityThrowsIndexOutOfBoundsExceptionIfLengthIsNegative()
    {
        final ExpandableDirectByteBuffer buffer = new ExpandableDirectByteBuffer(1);
        final IndexOutOfBoundsException exception =
            assertThrowsExactly(IndexOutOfBoundsException.class, () -> buffer.ensureCapacity(8, -100));
        assertEquals("negative value: index=8 length=-100", exception.getMessage());
    }