OrderedCode { public void writeBytes(byte[] value) { int encodedLength = 2; for (byte b : value) { if ((b == ESCAPE1) || (b == ESCAPE2)) { encodedLength += 2; } else { encodedLength++; } } byte[] encodedArray = new byte[encodedLength]; int copyStart = 0; int outIndex = 0; for (int i = 0; i < value.length; i++) { byte b = value[i]; if (b == ESCAPE1) { System.arraycopy(value, copyStart, encodedArray, outIndex, i - copyStart); outIndex += i - copyStart; encodedArray[outIndex++] = ESCAPE1; encodedArray[outIndex++] = NULL_CHARACTER; copyStart = i + 1; } else if (b == ESCAPE2) { System.arraycopy(value, copyStart, encodedArray, outIndex, i - copyStart); outIndex += i - copyStart; encodedArray[outIndex++] = ESCAPE2; encodedArray[outIndex++] = FF_CHARACTER; copyStart = i + 1; } } if (copyStart < value.length) { System.arraycopy(value, copyStart, encodedArray, outIndex, value.length - copyStart); outIndex += value.length - copyStart; } encodedArray[outIndex++] = ESCAPE1; encodedArray[outIndex] = SEPARATOR; encodedArrays.add(encodedArray); } OrderedCode();  OrderedCode(byte[] encodedByteArray); void writeBytes(byte[] value); void writeNumIncreasing(long value); void writeSignedNumIncreasing(long val); void writeInfinity(); void writeTrailingBytes(byte[] value); byte[] readBytes(); long readNumIncreasing(); long readSignedNumIncreasing(); boolean readInfinity(); byte[] readTrailingBytes(); byte[] readBytes(int len); byte[] getEncodedBytes(); boolean hasRemainingEncodedBytes(); static final byte ESCAPE1; static final byte NULL_CHARACTER; static final byte SEPARATOR; static final byte ESCAPE2; static final byte INFINITY; static final byte FF_CHARACTER; static final byte[] ESCAPE1_SEPARATOR; }
@Test public void testWriteBytes() { byte[] first = {'a', 'b', 'c'}; byte[] second = {'d', 'e', 'f'}; byte[] last = {'x', 'y', 'z'}; OrderedCode orderedCode = new OrderedCode(); orderedCode.writeBytes(first); byte[] firstEncoded = orderedCode.getEncodedBytes(); assertArrayEquals(orderedCode.readBytes(), first); orderedCode.writeBytes(first); orderedCode.writeBytes(second); orderedCode.writeBytes(last); byte[] allEncoded = orderedCode.getEncodedBytes(); assertArrayEquals(orderedCode.readBytes(), first); assertArrayEquals(orderedCode.readBytes(), second); assertArrayEquals(orderedCode.readBytes(), last); orderedCode = new OrderedCode(firstEncoded); orderedCode.writeBytes(second); orderedCode.writeBytes(last); assertArrayEquals(orderedCode.getEncodedBytes(), allEncoded); assertArrayEquals(orderedCode.readBytes(), first); assertArrayEquals(orderedCode.readBytes(), second); assertArrayEquals(orderedCode.readBytes(), last); orderedCode = new OrderedCode(allEncoded); assertArrayEquals(orderedCode.readBytes(), first); assertArrayEquals(orderedCode.readBytes(), second); assertArrayEquals(orderedCode.readBytes(), last); }