ParsableByteArray { public String readNullTerminatedString(int length) { if (length == 0) { return ""; } int stringLength = length; int lastIndex = position + length - 1; if (lastIndex < limit && data[lastIndex] == 0) { stringLength--; } String result = Util.fromUtf8Bytes(data, position, stringLength); position += length; return result; } ParsableByteArray();  ParsableByteArray(int limit);  ParsableByteArray(byte[] data);  ParsableByteArray(byte[] data, int limit); void reset(); void reset(int limit); void reset(byte[] data); void reset(byte[] data, int limit); int bytesLeft(); int limit(); void setLimit(int limit); int getPosition(); int capacity(); void setPosition(int position); void skipBytes(int bytes); void readBytes(ParsableBitArray bitArray, int length); void readBytes(byte[] buffer, int offset, int length); void readBytes(ByteBuffer buffer, int length); int peekUnsignedByte(); char peekChar(); int readUnsignedByte(); int readUnsignedShort(); int readLittleEndianUnsignedShort(); short readShort(); short readLittleEndianShort(); int readUnsignedInt24(); int readInt24(); int readLittleEndianInt24(); int readLittleEndianUnsignedInt24(); long readUnsignedInt(); long readLittleEndianUnsignedInt(); int readInt(); int readLittleEndianInt(); long readLong(); long readLittleEndianLong(); int readUnsignedFixedPoint1616(); int readSynchSafeInt(); int readUnsignedIntToInt(); int readLittleEndianUnsignedIntToInt(); long readUnsignedLongToLong(); float readFloat(); double readDouble(); String readString(int length); String readString(int length, Charset charset); String readNullTerminatedString(int length); @Nullable String readNullTerminatedString(); @Nullable String readLine(); long readUtf8EncodedLong(); public byte[] data; }
@Test public void testReadNullTerminatedString() { byte[] bytes = new byte[] { 'f', 'o', 'o', 0, 'b', 'a', 'r', 0 }; ParsableByteArray parser = new ParsableByteArray(bytes); assertThat(parser.readNullTerminatedString()).isEqualTo("foo"); assertThat(parser.getPosition()).isEqualTo(4); assertThat(parser.readNullTerminatedString()).isEqualTo("bar"); assertThat(parser.getPosition()).isEqualTo(8); assertThat(parser.readNullTerminatedString()).isNull(); parser = new ParsableByteArray(bytes, 4); assertThat(parser.readNullTerminatedString()).isEqualTo("foo"); assertThat(parser.getPosition()).isEqualTo(4); assertThat(parser.readNullTerminatedString()).isNull(); parser = new ParsableByteArray(bytes, 3); assertThat(parser.readNullTerminatedString()).isEqualTo("foo"); assertThat(parser.getPosition()).isEqualTo(3); assertThat(parser.readNullTerminatedString()).isNull(); }
@Test public void testReadNullTerminatedStringWithoutEndingNull() { byte[] bytes = new byte[] { 'f', 'o', 'o', 0, 'b', 'a', 'r' }; ParsableByteArray parser = new ParsableByteArray(bytes); assertThat(parser.readNullTerminatedString()).isEqualTo("foo"); assertThat(parser.readNullTerminatedString()).isEqualTo("bar"); assertThat(parser.readNullTerminatedString()).isNull(); }