RedisStreamReader implements Closeable { public String readString() throws IOException { int noOfBytesRead, newLength; byte[] bytes = new byte[0]; final byte[] tempBytes = new byte[BUFFER_SIZE]; do { noOfBytesRead = inputStream.read(tempBytes); newLength = noOfBytesRead - (noOfBytesRead > 1 && tempBytes[noOfBytesRead - 2] == RedisBytes.CARRIAGE_RETURN_BYTE ? 2 : 0) - (noOfBytesRead > 0 && tempBytes[noOfBytesRead - 1] == RedisBytes.CARRIAGE_RETURN_BYTE ? 1 : 0); byte[] newBytes = new byte[newLength + bytes.length]; System.arraycopy(bytes, 0, newBytes, 0, bytes.length); System.arraycopy(tempBytes, 0, newBytes, bytes.length, newLength); bytes = newBytes; } while (noOfBytesRead != -1 && newLength == noOfBytesRead); return new String(bytes); } RedisStreamReader(InputStream inputStream); byte readByte(); String readString(); int readInt(); byte[] read(int length); @Override void close(); static final int BUFFER_SIZE; }
@Test public void readString() throws IOException { final byte[] bytes = {'O', 'K', '\r', '\n'}; setupInputStreamRead(bytes, SIZE); String actualStatus = reader.readString(); assertEquals("OK", actualStatus); }
@Test public void readLongString() throws IOException { char theChar = '*'; final byte[] bytes = new byte[10002]; String expectedString = ""; for (int i = 0; i < bytes.length - 2; i++) { bytes[i] = (byte) theChar; expectedString += theChar; } bytes[bytes.length - 2] = '\r'; bytes[bytes.length - 1] = '\n'; setupInputStreamRead(bytes, SIZE); String actualString = reader.readString(); assertEquals(expectedString, actualString); }
@Test public void readLongStringWithoutLineFeed() throws IOException { char theChar = '*'; final byte[] bytes = new byte[SIZE]; String expectedString = ""; for (int i = 0; i < bytes.length - 1; i++) { bytes[i] = (byte) theChar; expectedString += theChar; } bytes[bytes.length - 1] = '\r'; setupInputStreamRead(bytes, SIZE); String actualString = reader.readString(); assertEquals(expectedString, actualString); }