Example usage for io.netty.buffer ByteBuf isWritable

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

Introduction

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

Prototype

public abstract boolean isWritable(int size);

Source Link

Document

Returns true if and only if this buffer has enough room to allow writing the specified number of elements.

Usage

From source file:org.jfxvnc.net.rfb.codec.decoder.rect.CursorRectDecoder.java

License:Apache License

@Override
protected void sendRect(List<Object> out) {
    int i = 0;/* w w w  .  j  a va2 s. c  om*/
    ByteBuf pixels = aloc.buffer(capacity - bitMaskLength);
    while (pixels.isWritable(4)) {
        pixels.writeInt(framebuffer.getUnsignedByte(i * 4 + redPos) << pixelFormat.getRedShift()
                | framebuffer.getUnsignedByte(i * 4 + 1) << pixelFormat.getGreenShift()
                | framebuffer.getUnsignedByte(i * 4 + bluePos) << pixelFormat.getBlueShift() | 0xff000000);
        i++;
    }

    if (bitMaskLength > 0) {
        ByteBuf bitmask = aloc.buffer(bitMaskLength);
        framebuffer.getBytes(capacity - bitMaskLength, bitmask);
        // remove transparent pixels
        int maskBytesPerRow = Math.floorDiv((rect.getWidth() + 7), 8);
        IntStream.range(0, rect.getHeight())
                .forEach(y -> IntStream.range(0, rect.getWidth())
                        .filter(x -> (bitmask.getByte((y * maskBytesPerRow) + Math.floorDiv(x, 8))
                                & (1 << 7 - Math.floorMod(x, 8))) < 1)
                        .forEach(x -> pixels.setInt((y * rect.getWidth() + x) * 4, 0)));
        bitmask.release();
    }
    out.add(new CursorImageRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight(), pixels));
}

From source file:org.opendaylight.bgp.concepts.RouteDistinguisherUtil.java

License:Open Source License

/**
 * Serializes route distinguisher according to type and writes into ByteBuf.
 *
 * @param distinguisher/*from   w  w  w  . jav  a  2 s .co  m*/
 * @param byteAggregator
 */
public static void serializeRouteDistinquisher(final RouteDistinguisher distinguisher,
        final ByteBuf byteAggregator) {
    Preconditions.checkNotNull(distinguisher);
    Preconditions.checkState(byteAggregator != null && byteAggregator.isWritable(RD_LENGTH),
            "Cannot write Route Distinguisher to provided buffer.");
    if (distinguisher.getRdTwoOctetAs() != null) {
        final String[] values = distinguisher.getRdTwoOctetAs().getValue().split(SEPARATOR);
        byteAggregator.writeShort(RD_TYPE.AS_2BYTE.value);
        ByteBufWriteUtil.writeUnsignedShort(Integer.parseInt(values[1]), byteAggregator);
        final long assignedNumber = Integer.parseUnsignedInt(values[2]);
        ByteBufWriteUtil.writeUnsignedInt(assignedNumber, byteAggregator);
    } else if (distinguisher.getRdAs() != null) {
        final String[] values = distinguisher.getRdAs().getValue().split(SEPARATOR);
        byteAggregator.writeShort(RD_TYPE.AS_4BYTE.value);
        final long admin = Integer.parseUnsignedInt(values[0]);
        ByteBufWriteUtil.writeUnsignedInt(admin, byteAggregator);
        ByteBufWriteUtil.writeUnsignedShort(Integer.parseInt(values[1]), byteAggregator);
    } else if (distinguisher.getRdIpv4() != null) {
        final String[] values = distinguisher.getRdIpv4().getValue().split(SEPARATOR);
        final Ipv4Address ip = new Ipv4Address(values[0]);
        byteAggregator.writeShort(RD_TYPE.IPV4.value);
        ByteBufWriteUtil.writeIpv4Address(ip, byteAggregator);
        ByteBufWriteUtil.writeUnsignedShort(Integer.parseInt(values[1]), byteAggregator);
    } else {
        LOG.warn("Unable to serialize Route Distinguisher. Invalid RD value found. RD={}", distinguisher);
    }
}

From source file:qunar.tc.qmq.store.IndexLog.java

License:Apache License

private AppendMessageResult doAppendData(final LogSegment segment, final ByteBuffer data) {
    int currentPos = segment.getWrotePosition();
    final int freeSize = segment.getFileSize() - currentPos;
    if (data.remaining() <= freeSize) {
        if (!segment.appendData(data))
            throw new RuntimeException("append index data failed.");
        return new AppendMessageResult<>(SUCCESS, segment.getBaseOffset() + segment.getWrotePosition());
    }/*from  w w  w.  j av  a2s.  c  o m*/

    ByteBuf to = ByteBufAllocator.DEFAULT.ioBuffer(freeSize);
    try {
        partialCopy(data, to);
        if (to.isWritable(Long.BYTES)) {
            to.writeLong(-1);
        }
        fillZero(to);
        if (!segment.appendData(to.nioBuffer()))
            throw new RuntimeException("append index data failed.");
    } finally {
        ReferenceCountUtil.release(to);
    }
    return new AppendMessageResult(END_OF_FILE, segment.getBaseOffset() + segment.getFileSize());
}

From source file:qunar.tc.qmq.store.IndexLog.java

License:Apache License

private void fillZero(ByteBuf buffer) {
    while (buffer.isWritable(Byte.BYTES)) {
        buffer.writeByte(0);
    }
}

From source file:qunar.tc.qmq.store.IndexLog.java

License:Apache License

private void partialCopy(ByteBuffer src, ByteBuf to) {
    while (to.isWritable(Long.BYTES)) {
        src.mark();/* ww  w . j a  va 2 s. c  o m*/
        to.markWriterIndex();
        if (!to.isWritable(Long.BYTES))
            break;
        to.writeLong(src.getLong());

        if (!to.isWritable(Long.BYTES)) {
            src.reset();
            to.resetWriterIndex();
            break;
        }
        to.writeLong(src.getLong());

        // subject
        if (!writeString(src, to))
            break;

        // msgId
        if (!writeString(src, to))
            break;
    }
}

From source file:qunar.tc.qmq.store.IndexLog.java

License:Apache License

private boolean writeString(ByteBuffer src, ByteBuf to) {
    short len = src.getShort();
    if (!to.isWritable(Short.BYTES + len)) {
        src.reset();//from  w  ww . j  a  v a 2  s.c om
        to.resetWriterIndex();
        return false;
    }
    byte[] subject = new byte[len];
    src.get(subject);
    to.writeShort(len);
    to.writeBytes(subject);
    return true;
}

From source file:qunar.tc.qmq.sync.master.MessageIndexSyncWorker.java

License:Apache License

@Override
protected SegmentBuffer getSyncLog(SyncRequest syncRequest) {
    final long originalOffset = syncRequest.getMessageLogOffset();
    long startSyncOffset = originalOffset;

    long minMessageOffset = storage.getMinMessageOffset();
    if (startSyncOffset < minMessageOffset) {
        startSyncOffset = minMessageOffset;
        LOG.info("reset message log sync offset from {} to {}", originalOffset, startSyncOffset);
    }//w w  w.ja  va2 s  .  c  om

    try (MessageLogRecordVisitor visitor = storage.newMessageLogVisitor(startSyncOffset)) {
        LogSegment logSegment = null;
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.ioBuffer(batchSize);
        long nextSyncOffset = startSyncOffset;
        try {
            for (int i = 0; i < MAX_SYNC_NUM; ++i) {
                LogVisitorRecord<MessageLogRecord> record = visitor.nextRecord();
                if (record.isNoMore()) {
                    nextSyncOffset = visitor.getStartOffset() + visitor.visitedBufferSize();
                    break;
                }

                if (!record.hasData()) {
                    nextSyncOffset = visitor.getStartOffset() + visitor.visitedBufferSize();
                    continue;
                }

                MessageLogRecord data = record.getData();
                logSegment = data.getLogSegment();

                if (!byteBuf.isWritable(Long.BYTES))
                    break;
                byteBuf.markWriterIndex();
                byteBuf.writeLong(data.getSequence());

                if (!byteBuf.isWritable(Long.BYTES)) {
                    byteBuf.resetWriterIndex();
                    break;
                }

                ByteBuffer body = data.getPayload();
                //skip flag
                body.get();
                long createTime = body.getLong();
                //skip expireTime
                body.getLong();

                //subject
                short len = body.getShort();
                byte[] subject = new byte[len];
                body.get(subject);

                //message id
                len = body.getShort();
                byte[] messageId = new byte[len];
                body.get(messageId);

                byteBuf.writeLong(createTime);

                if (!byteBuf.isWritable(Short.BYTES + subject.length)) {
                    byteBuf.resetWriterIndex();
                    break;
                }
                PayloadHolderUtils.writeString(subject, byteBuf);

                if (!byteBuf.isWritable(Short.BYTES + messageId.length)) {
                    byteBuf.resetWriterIndex();
                    break;
                }
                PayloadHolderUtils.writeString(messageId, byteBuf);

                nextSyncOffset = visitor.getStartOffset() + visitor.visitedBufferSize();
            }
        } finally {
            if (!byteBuf.isReadable()) {
                byteBuf.release();
            }
        }

        if (originalOffset == nextSyncOffset) {
            return null;
        }

        //FIXME: ????
        if (byteBuf.isReadable()) {
            return new ByteBufSegmentBuffer(nextSyncOffset, logSegment, byteBuf, byteBuf.readableBytes());
        } else {
            return new ByteBufSegmentBuffer(nextSyncOffset);
        }
    }
}