0

I'm writing a library for reading/writing bits from/to Streams/Channels.

When working with Channels I use 1-byte-long ByteBuffer.

Here comes how to read/write with those ByteBuffer.

//@Override // commented for pre 5
public int readUnsignedByte() throws IOException {

    buffer.clear(); // ------------------------------------------- clear

    for (int read = -1;;) {
        read = input.read(buffer); // ----------------------------- read
        if (read == -1) {
            throw new EOFException("eof");
        }
        if (read == 1) {
            break;
        }
    }

    buffer.flip(); // --------------------------------------------- flip

    return (buffer.get() & 0xFF); // ------------------------------- get
}


//@Override // commented for pre 5
public void writeUnsignedByte(final int value) throws IOException {

    buffer.put((byte) value); // ----------------------------------- put

    buffer.flip(); // --------------------------------------------- flip

    while (output.write(buffer) != 1); // ------------------------ write

    buffer.clear(); // ------------------------------------------- clear
}

In this case, does allocateDirect(1) is always better than allocate(1)?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
  • 1
    probably, but I doubt you will notice much difference. – BevynQ May 28 '13 at 07:20
  • 1
    If you're using blocking mode the loops around `read()` and `write()` are redundant, and if you're using non-blocking mode they are a serious waste of your CPU: you should be integrating with a `Selector` and allowing a zero length read or write to occur. I also question the utility of a 1 byte buffer: the performance will be truly appalling. I would reconsider the design. – user207421 May 28 '13 at 07:40

0 Answers0