ByteBuffer (final ByteBuffer buffer, final int requiredLimit) { if (buffer.capacity() >= requiredLimit) { return buffer.limit(Math.max(buffer.limit(), requiredLimit)); } else { return ByteBuffer.allocate(requiredLimit) .order(buffer.order()) .position(buffer.position()); } }