static int readDirectBuffer(InputStream f, ByteBuffer buf, byte[] temp) throws IOException {
    // copy all the bytes that return immediately, stopping at the first
    // read that doesn't return a full buffer.
    int nextReadLength = Math.min(buf.remaining(), temp.length);
    int totalBytesRead = 0;
    int bytesRead;

    while ((bytesRead = f.read(temp, 0, nextReadLength)) == temp.length) {
      buf.put(temp);
      totalBytesRead += bytesRead;
      nextReadLength = Math.min(buf.remaining(), temp.length);
    }

    if (bytesRead < 0) {
      // return -1 if nothing was read
      return totalBytesRead == 0 ? -1 : totalBytesRead;
    } else {
      // copy the last partial buffer
      buf.put(temp, 0, bytesRead);
      totalBytesRead += bytesRead;
      return totalBytesRead;
    }
  }
@Test
  public void testDirectSmallTempBufferSmallReads() throws Exception {
    byte[] temp = new byte[2]; // this will cause readDirectBuffer to loop

    ByteBuffer readBuffer = ByteBuffer.allocateDirect(10);

    MockInputStream stream = new MockInputStream(2, 3, 3);

    int len = DelegatingSeekableInputStream.readDirectBuffer(stream, readBuffer, temp);
    Assert.assertEquals(2, len);
    Assert.assertEquals(2, readBuffer.position());
    Assert.assertEquals(10, readBuffer.limit());

    len = DelegatingSeekableInputStream.readDirectBuffer(stream, readBuffer, temp);
    Assert.assertEquals(3, len);
    Assert.assertEquals(5, readBuffer.position());
    Assert.assertEquals(10, readBuffer.limit());

    len = DelegatingSeekableInputStream.readDirectBuffer(stream, readBuffer, temp);
    Assert.assertEquals(3, len);
    Assert.assertEquals(8, readBuffer.position());
    Assert.assertEquals(10, readBuffer.limit());

    len = DelegatingSeekableInputStream.readDirectBuffer(stream, readBuffer, temp);
    Assert.assertEquals(2, len);
    Assert.assertEquals(10, readBuffer.position());
    Assert.assertEquals(10, readBuffer.limit());

    len = DelegatingSeekableInputStream.readDirectBuffer(stream, readBuffer, temp);
    Assert.assertEquals(-1, len);

    readBuffer.flip();
    Assert.assertEquals("Buffer contents should match", ByteBuffer.wrap(TEST_ARRAY), readBuffer);
  }