Java Code Examples for org.jboss.netty.buffer.ChannelBuffers.EMPTY_BUFFER

The following are Jave code examples for showing how to use EMPTY_BUFFER of the org.jboss.netty.buffer.ChannelBuffers class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Elasticsearch   File: PagedBytesReference.java   Source Code and License Vote up 4 votes
@Override
public ChannelBuffer toChannelBuffer() {
    // nothing to do
    if (length == 0) {
        return ChannelBuffers.EMPTY_BUFFER;
    }

    ChannelBuffer[] buffers;
    ChannelBuffer currentBuffer = null;
    BytesRef ref = new BytesRef();
    int pos = 0;

    // are we a slice?
    if (offset != 0) {
        // remaining size of page fragment at offset
        int fragmentSize = Math.min(length, PAGE_SIZE - (offset % PAGE_SIZE));
        bytearray.get(offset, fragmentSize, ref);
        currentBuffer = ChannelBuffers.wrappedBuffer(ref.bytes, ref.offset, fragmentSize);
        pos += fragmentSize;
    }

    // no need to create a composite buffer for a single page
    if (pos == length && currentBuffer != null) {
        return currentBuffer;
    }

    // a slice > pagesize will likely require extra buffers for initial/trailing fragments
    int numBuffers = countRequiredBuffers((currentBuffer != null ? 1 : 0), length - pos);

    buffers = new ChannelBuffer[numBuffers];
    int bufferSlot = 0;

    if (currentBuffer != null) {
        buffers[bufferSlot] = currentBuffer;
        bufferSlot++;
    }

    // handle remainder of pages + trailing fragment
    while (pos < length) {
        int remaining = length - pos;
        int bulkSize = (remaining > PAGE_SIZE) ? PAGE_SIZE : remaining;
        bytearray.get(offset + pos, bulkSize, ref);
        currentBuffer = ChannelBuffers.wrappedBuffer(ref.bytes, ref.offset, bulkSize);
        buffers[bufferSlot] = currentBuffer;
        bufferSlot++;
        pos += bulkSize;
    }

    // this would indicate that our numBuffer calculation is off by one.
    assert (numBuffers == bufferSlot);

    return ChannelBuffers.wrappedBuffer(NettyUtils.DEFAULT_GATHERING, buffers);
}