Example usage for io.netty.buffer ByteBuf nioBufferCount

List of usage examples for io.netty.buffer ByteBuf nioBufferCount

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf nioBufferCount.

Prototype

public abstract int nioBufferCount();

Source Link

Document

Returns the maximum number of NIO ByteBuffer s that consist this buffer.

Usage

From source file:io.grpc.alts.internal.BufUnwrapper.java

License:Apache License

/**
 * Optimized accessor for obtaining the underlying NIO buffers for a Netty {@link ByteBuf}. Based
 * on code from Netty's {@code SslHandler}. This method returns NIO buffers that span the readable
 * region of the {@link ByteBuf}.//from w w w  .jav  a2 s. c o m
 */
private static ByteBuffer[] nioBuffers(ByteBuf buf, ByteBuffer[] singleBuffer) {
    // As CompositeByteBuf.nioBufferCount() can be expensive (as it needs to check all composed
    // ByteBuf to calculate the count) we will just assume a CompositeByteBuf contains more than 1
    // ByteBuf. The worst that can happen is that we allocate an extra ByteBuffer[] in
    // CompositeByteBuf.nioBuffers() which is better than walking the composed ByteBuf in most
    // cases.
    if (!(buf instanceof CompositeByteBuf) && buf.nioBufferCount() == 1) {
        // We know its only backed by 1 ByteBuffer so use internalNioBuffer to keep object
        // allocation to a minimum.
        singleBuffer[0] = buf.internalNioBuffer(buf.readerIndex(), buf.readableBytes());
        return singleBuffer;
    }

    return buf.nioBuffers();
}

From source file:io.jsync.file.impl.DefaultAsyncFile.java

License:Open Source License

@Override
public AsyncFile write(Buffer buffer, long position, final Handler<AsyncResult<Void>> handler) {
    check();//from  ww w.j ava 2s.c o m
    final ByteBuf buf = buffer.getByteBuf();
    if (buf.nioBufferCount() > 1) {
        final Iterator<ByteBuffer> buffers = Arrays.asList(buf.nioBuffers()).iterator();
        doWrite(buffers, position, handler);
    } else {
        ByteBuffer bb = buf.nioBuffer();
        doWrite(bb, position, bb.limit(), handler);
    }
    return this;
}

From source file:io.jsync.file.impl.DefaultAsyncFile.java

License:Open Source License

@Override
public AsyncFile write(Buffer buffer) {
    check();// w ww .  j  a v a  2 s.com
    final int length = buffer.length();
    Handler<AsyncResult<Void>> handler = new Handler<AsyncResult<Void>>() {

        public void handle(AsyncResult<Void> deferred) {
            if (deferred.succeeded()) {
                checkContext();
                checkDrained();
                if (writesOutstanding == 0 && closedDeferred != null) {
                    closedDeferred.run();
                }
            } else {
                handleException(deferred.cause());
            }
        }
    };

    ByteBuf buf = buffer.getByteBuf();
    if (buf.nioBufferCount() > 1) {
        final Iterator<ByteBuffer> buffers = Arrays.asList(buf.nioBuffers()).iterator();
        doWrite(buffers, writePos, handler);
    } else {
        ByteBuffer bb = buf.nioBuffer();
        doWrite(bb, writePos, bb.limit(), handler);
    }
    writePos += length;
    return this;
}

From source file:io.vertx.core.file.impl.AsyncFileImpl.java

License:Open Source License

private synchronized AsyncFile doWrite(Buffer buffer, long position, Handler<AsyncResult<Void>> handler) {
    Objects.requireNonNull(buffer, "buffer");
    Arguments.require(position >= 0, "position must be >= 0");
    check();/*from  ww  w  . ja  v a 2 s. c  o  m*/
    Handler<AsyncResult<Void>> wrapped = ar -> {
        if (ar.succeeded()) {
            checkContext();
            if (writesOutstanding == 0 && closedDeferred != null) {
                closedDeferred.run();
            } else {
                checkDrained();
            }
            if (handler != null) {
                handler.handle(ar);
            }
        } else {
            if (handler != null) {
                handler.handle(ar);
            } else {
                handleException(ar.cause());
            }
        }
    };
    ByteBuf buf = buffer.getByteBuf();
    if (buf.nioBufferCount() > 1) {
        doWrite(buf.nioBuffers(), position, wrapped);
    } else {
        ByteBuffer bb = buf.nioBuffer();
        doWrite(bb, position, bb.limit(), wrapped);
    }
    return this;
}

From source file:net.tomp2p.storage.AlternativeCompositeByteBuf.java

License:Apache License

@Override
public ByteBuffer nioBuffer(int index, int length) {
    if (components.size() == 1) {
        ByteBuf buf = components.get(0).buf;
        if (buf.nioBufferCount() == 1) {
            return components.get(0).buf.nioBuffer(index, length);
        }//w  w  w  . j a  v a  2 s .com
    }
    ByteBuffer merged = ByteBuffer.allocate(length).order(order());
    ByteBuffer[] buffers = nioBuffers(index, length);

    // noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < buffers.length; i++) {
        merged.put(buffers[i]);
    }

    merged.flip();
    return merged;
}

From source file:net.tomp2p.storage.AlternativeCompositeByteBuf.java

License:Apache License

@Override
public ByteBuffer[] nioBuffers(int index, int length) {
    checkIndex(index, length);//from   w  w  w .  j  a v  a2  s  .c o m
    if (length == 0) {
        return EmptyArrays.EMPTY_BYTE_BUFFERS;
    }

    List<ByteBuffer> buffers = new ArrayList<ByteBuffer>(components.size());
    int i = findIndex(index);
    while (length > 0) {
        Component c = components.get(i);
        ByteBuf s = c.buf;
        int adjustment = c.offset;
        int localLength = Math.min(length, s.readableBytes() - (index - adjustment));
        switch (s.nioBufferCount()) {
        case 0:
            throw new UnsupportedOperationException();
        case 1:
            buffers.add(s.nioBuffer(index - adjustment, localLength));
            break;
        default:
            Collections.addAll(buffers, s.nioBuffers(index - adjustment, localLength));
        }

        index += localLength;
        length -= localLength;
        i++;
    }

    return buffers.toArray(new ByteBuffer[buffers.size()]);
}

From source file:org.asynchttpclient.netty.util.Utf8ByteBufCharsetDecoder.java

License:Open Source License

public String decode(ByteBuf buf) throws CharacterCodingException {
    if (buf.isDirect()) {
        return buf.toString(UTF_8);
    }//w w  w  .  j a  v  a 2 s .c o m

    int length = buf.readableBytes();
    ensureCapacity(length);

    if (buf.nioBufferCount() == 1) {
        decodeSingleNioBuffer(buf.internalNioBuffer(buf.readerIndex(), length).duplicate(), length);
    } else {
        decode(buf.nioBuffers(), buf.readableBytes());
    }

    return charBuffer.flip().toString();
}

From source file:org.asynchttpclient.netty.util.Utf8ByteBufCharsetDecoder.java

License:Open Source License

public String decode(ByteBuf... bufs) throws CharacterCodingException {
    if (bufs.length == 1) {
        return decode(bufs[0]);
    }//ww  w .  j  a  v a2  s  .c  o  m

    int totalSize = 0;
    int totalNioBuffers = 0;
    boolean direct = false;
    for (ByteBuf buf : bufs) {
        if (buf.isDirect()) {
            direct = true;
            break;
        }
        totalSize += buf.readableBytes();
        totalNioBuffers += buf.nioBufferCount();
    }

    if (direct) {
        ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(bufs);
        try {
            return wrappedBuffer.toString(UTF_8);
        } finally {
            wrappedBuffer.release();
        }

    } else {
        ByteBuffer[] nioBuffers = new ByteBuffer[totalNioBuffers];
        int i = 0;
        for (ByteBuf buf : bufs) {
            for (ByteBuffer nioBuffer : buf.nioBuffers()) {
                nioBuffers[i++] = nioBuffer;
            }
        }

        ensureCapacity(totalSize);
        decode(nioBuffers, totalSize);

        return charBuffer.flip().toString();
    }
}

From source file:org.sfs.io.AsyncFileWriterImpl.java

License:Apache License

private AsyncFileWriterImpl doWrite(Buffer buffer, long position, Handler<AsyncResult<Void>> handler) {
    Preconditions.checkNotNull(buffer, "buffer");
    Preconditions.checkArgument(position >= 0, "position must be >= 0");
    Handler<AsyncResult<Void>> wrapped = ar -> {
        if (ar.succeeded()) {
            if (handler != null) {
                handler.handle(ar);/* www .j  ava  2  s. com*/
            }
        } else {
            if (handler != null) {
                handler.handle(ar);
            } else {
                handleException(ar.cause());
            }
        }
    };
    ByteBuf buf = buffer.getByteBuf();
    if (buf.nioBufferCount() > 1) {
        doWrite(buf.nioBuffers(), position, wrapped);
    } else {
        ByteBuffer bb = buf.nioBuffer();
        doWrite(bb, position, bb.limit(), wrapped);
    }
    return this;
}

From source file:qunar.tc.qmq.backup.service.impl.ActionSyncLogIterator.java

License:Apache License

@Override
public LogVisitorRecord<Action> next(ByteBuf buf) {
    final int magic = buf.readInt();
    if (magic != MagicCode.ACTION_LOG_MAGIC_V1) {
        return LogVisitorRecord.noMore();
    }//ww  w .  j  a va2  s  .c  om

    final byte attributes = buf.readByte();
    if (attributes == ATTR_BLANK_RECORD) {
        if (buf.readableBytes() < Integer.BYTES) {
            return LogVisitorRecord.noMore();
        }
        final int blankSize = buf.readInt();
        buf.readerIndex(buf.readerIndex() + blankSize);
        return LogVisitorRecord.data(BLANK_ACTION);
    } else if (attributes == ATTR_EMPTY_RECORD) {
        buf.readerIndex(buf.readerIndex() + buf.readableBytes());
        return LogVisitorRecord.empty();
    } else if (attributes == ATTR_ACTION_RECORD) {
        if (buf.readableBytes() < Integer.BYTES + Byte.BYTES) {
            return LogVisitorRecord.noMore();
        }
        final ActionType payloadType = ActionType.fromCode(buf.readByte());
        final int payloadSize = buf.readInt();
        if (buf.readableBytes() < payloadSize) {
            return LogVisitorRecord.noMore();
        }

        if (buf.nioBufferCount() > 0) {
            final int payloadIndex = buf.readerIndex();
            final Action action = payloadType.getReaderWriter().read(buf.nioBuffer(payloadIndex, payloadSize));
            buf.readerIndex(buf.readerIndex() + payloadSize);
            return LogVisitorRecord.data(action);
        } else {
            return LogVisitorRecord.data(BLANK_ACTION);
        }
    } else {
        throw new RuntimeException("Unknown record type");
    }
}