-
- /**
- * Compacting the buffers is needed because the semantic of WriteFlusher is
- * to write the buffers and if the caller sees that the buffer is consumed,
- * then it can recycle it.
- * If we do not compact, then it is possible that we store a consumed buffer,
- * which is then recycled and refilled; when the WriteFlusher is invoked to
- * complete the write, it will write the refilled bytes, garbling the content.
- *
- * @param buffers the buffers to compact
- * @return the compacted buffers
- */
- private ByteBuffer[] compact(ByteBuffer[] buffers)
- {
- int length = buffers.length;
-
- // Just one element, no need to compact
- if (length < 2)
- return buffers;
-
- // How many still have content ?
- int consumed = 0;
- while (consumed < length && BufferUtil.isEmpty(buffers[consumed]))
- ++consumed;
-
- // All of them still have content, no need to compact
- if (consumed == 0)
- return buffers;
-
- // None has content, return empty
- if (consumed == length)
- return EMPTY_BUFFERS;
-
- return Arrays.copyOfRange(buffers,consumed,length);
- }