ByteBuffer (final ByteBuffer buffer, final int offset, final int oldGapSize, final int newGapSize) { final int oldGapEndOffset = offset + oldGapSize; final int newGapEndOffset = offset + newGapSize; final int limitBefore = buffer.limit(); if (newGapSize > oldGapSize) {//expand: final ByteBuffer enlargedBuffer = ensureLimitAndData(buffer, limitBefore + (newGapSize - oldGapSize)); enlargedBuffer.put(newGapEndOffset, buffer, oldGapEndOffset, limitBefore - oldGapEndOffset); enlargedBuffer.limit(limitBefore + newGapSize - oldGapSize); return enlargedBuffer; } else if (newGapSize < oldGapSize) {//collapse: buffer.put(newGapEndOffset, buffer, oldGapEndOffset, limitBefore - oldGapEndOffset); buffer.limit(limitBefore + (newGapSize - oldGapSize)); return buffer; } else {//nothing to move: oldGap=newGap return buffer; } }