It keeps getting better! Newest version:

private ByteBuffer xor(ByteBuffer in) {
    ByteBuffer out = in.duplicate();
    int pad = 0xAABBCCDD;

    while (in.hasRemaining()) {
        if (in.remaining() >= 4) {
            int xor = in.getInt() ^ pad;
            out.putInt(xor);
        }
        else {
            byte xor = (byte) (in.get() ^ 0xFF);
            out.put(xor);
        }
    }

    return in.flip();
}

On Thu, Oct 2, 2008 at 6:56 PM, W.B. Garvelink
<[EMAIL PROTECTED]> wrote:
> This duplicate buffer thing can be a very useful tool to avoid making
> unnecessary copies of in-memory data. The slice() and asIntBuffer(),
> asCharBuffer(), etc, methods all work in the same way. On the flip
> side, if you take a small slice from a larger buffer and never use the
> rest, you may end up holding on to more memory than you have to.
>
> Barend
>
>
>
> On Thu, Oct 2, 2008 at 11:40 PM, W.B. Garvelink
> <[EMAIL PROTECTED]> wrote:
>> Hi Andres,
>>
>>
>> Yep, there's another way, and I'll admit I was hoping you'd ask ;-).
>> Take a look at the ByteBuffer.duplicate() method:
>>
>>> Creates a new byte buffer that shares this buffer's content.
>>>
>>> The content of the new buffer will be that of this buffer. Changes
>>> to this buffer's content will be visible in the new buffer, and
>>> vice versa; the two buffers' position, limit, and mark values will
>>> be independent.
>>>
>>> The new buffer's capacity, limit, position, and mark values will
>>> be identical to those of this buffer.
>>
>> You can create a second ByteBuffer "view" on the same in-memory data, use one
>> to your reads and the other to do your writes. They both start at the
>> same position and they both have the same limit, so if you read from one and 
>> write
>> to the other within the loop body, they stay in sync.
>>
>

Reply via email to