ByteBufferInputStream extends InputStream { @Override public int read() throws IOException { pop(); if (currentBuffers.isEmpty()) { return -1; } return currentBuffers.peek().get(); } ByteBufferInputStream(ByteBuffer[] buffers); @Override int read(); @Override int read(byte[] b, int off, int len); @Override long skip(long n); @Override int available();  }
@Test public void requireThatExhaustedBufferWorks() throws IOException { ByteBuffer[] buffers = getAbcde(); buffers[2].get(); ByteBufferInputStream in = new ByteBufferInputStream(buffers); byte[] out = new byte[100]; int pos = 0; final int GUARD = 1000; int i; for (i = 0; i < GUARD; i++) { int r = in.read(); if (r == -1) { break; } out[pos] = (byte) (0xFF & r); ++pos; } assertTrue(i < GUARD); assertThat(pos, is(4)); String outString = new String(out, 0, pos, StandardCharsets.UTF_8); assertThat(outString, equalTo("abde")); }
@Test public void requireThatBulkReadWorks() throws IOException { ByteBuffer[] buffers = getAbcde(); ByteBufferInputStream in = new ByteBufferInputStream(buffers); byte[] out = new byte[100]; int pos = 0; final int GUARD = 1000; int i; for (i = 0; i < GUARD; i++) { int numReadNow; if (i == 0) { numReadNow = in.read(out); } else { numReadNow = in.read(out, pos, (out.length - pos)); } if (numReadNow == -1) { break; } pos += numReadNow; } assertTrue(i < GUARD); assertThat(pos, is(5)); String outString = new String(out, 0, pos, StandardCharsets.UTF_8); assertThat(outString, equalTo("abcde")); }
@Test public void requireThatSingleByteReadWorks() throws IOException { ByteBuffer[] buffers = getAbcde(); ByteBufferInputStream in = new ByteBufferInputStream(buffers); byte[] out = new byte[100]; int pos = 0; final int GUARD = 1000; int i; for (i = 0; i < GUARD; i++) { int r = in.read(); if (r == -1) { break; } out[pos] = (byte) (0xFF & r); ++pos; } assertTrue(i < GUARD); assertThat(pos, is(5)); String outString = new String(out, 0, pos, StandardCharsets.UTF_8); assertThat(outString, equalTo("abcde")); }