Example usage for java.nio ByteBuffer limit

List of usage examples for java.nio ByteBuffer limit

Introduction

In this page you can find the example usage for java.nio ByteBuffer limit.

Prototype

public final Buffer limit(int newLimit) 

Source Link

Document

Sets the limit of this buffer.

Usage

From source file:org.jtrfp.trcl.core.Texture.java

public static ByteBuffer fragmentRGBA(ByteBuffer input, int quadDepth, int x, int y) {
    final int originalSideLen = (int) Math.sqrt(input.capacity() / 4);
    final int splitAmount = (int) Math.pow(2, quadDepth);
    final int newSideLen = originalSideLen / splitAmount;
    ByteBuffer result = ByteBuffer.allocateDirect((int) (Math.pow(newSideLen, 2) * 4));
    for (int row = y * newSideLen; row < (y + 1) * newSideLen; row++) {
        input.clear();/*from ww  w  .  j ava2 s .  co m*/
        input.limit((x + 1) * newSideLen * 4 + row * originalSideLen * 4);
        input.position(x * newSideLen * 4 + row * originalSideLen * 4);
        result.put(input);
    }
    return result;
}

From source file:org.apache.htrace.impl.TestPackedBuffer.java

@Test(timeout = 60000)
public void testPackSpans() throws Exception {
    Random rand = new Random(123);
    byte[] arr = new byte[16384];
    ByteBuffer bb = ByteBuffer.wrap(arr);
    bb.limit(bb.capacity());
    PackedBuffer buf = new PackedBuffer(bb);
    final int NUM_TEST_SPANS = 5;
    Span[] spans = new Span[NUM_TEST_SPANS];
    for (int i = 0; i < NUM_TEST_SPANS; i++) {
        spans[i] = TestUtil.randomSpan(rand);
    }//from  w  w  w.  j a  v a 2s .  c  o m
    for (int i = 0; i < NUM_TEST_SPANS; i++) {
        buf.writeSpan(spans[i]);
    }
    LOG.info("wrote " + buf.toHexString());
    MessagePack msgpack = new MessagePack(PackedBuffer.MSGPACK_CONF);
    MessageUnpacker unpacker = msgpack.newUnpacker(arr, 0, bb.position());
    Span[] respans = new Span[NUM_TEST_SPANS];
    for (int i = 0; i < NUM_TEST_SPANS; i++) {
        respans[i] = PackedBuffer.readSpan(unpacker);
    }
    for (int i = 0; i < NUM_TEST_SPANS; i++) {
        Assert.assertEquals("Failed to read back span " + i, spans[i].toJson(), respans[i].toJson());
    }
}

From source file:com.spotify.heroic.metric.datastax.schema.legacy.MapSerializer.java

private <T> T next(ByteBuffer buffer, TypeSerializer<T> serializer) throws IOException {
    final short segment = buffer.getShort();
    final ByteBuffer slice = buffer.slice();
    slice.limit(segment);
    final T value = serializer.deserialize(slice);

    buffer.position(buffer.position() + segment);
    return value;
}

From source file:com.linkedin.pinot.core.startree.MmapLinkedListStarTreeTable.java

private ByteBuffer getNextBuffer() {
    backingBuffer.position(documentCount * rowSize);
    checkBuffer();//from  w w  w. j ava 2s .c  o  m
    ByteBuffer buffer = backingBuffer.slice();
    buffer.limit(rowSize);
    documentCount++;
    return buffer;
}

From source file:de.csdev.ebus.command.EBusCommandUtils.java

/**
 * Build a complete telegram for master/slave, master/master and broadcasts
 *
 * @param source/*from w  w  w  .  j a v  a  2s. c  o  m*/
 * @param target
 * @param command
 * @param masterData
 * @param slaveData
 * @return
 * @throws EBusTypeException
 */
public static ByteBuffer buildCompleteTelegram(byte source, byte target, byte[] command, byte[] masterData,
        byte[] slaveData) throws EBusTypeException {

    boolean isMastereMaster = EBusUtils.isMasterAddress(target);
    boolean isBroadcast = target == EBusConsts.BROADCAST_ADDRESS;
    boolean isMasterSlave = !isMastereMaster && !isBroadcast;

    ByteBuffer buf = ByteBuffer.allocate(50);
    buf.put(buildPartMasterTelegram(source, target, command, masterData));

    // if used compute a complete telegram
    if (isMasterSlave && slaveData != null) {
        ByteBuffer slaveTelegramPart = buildPartSlave(slaveData);
        buf.put(slaveTelegramPart);

        buf.put(EBusConsts.ACK_OK);
        buf.put(EBusConsts.SYN);
    }

    if (isMastereMaster) {
        buf.put(EBusConsts.ACK_OK);
        buf.put(EBusConsts.SYN);
    }

    if (isBroadcast) {
        buf.put(EBusConsts.SYN);
    }

    // set limit and reset position
    buf.limit(buf.position());
    buf.position(0);

    return buf;
}

From source file:com.healthmarketscience.jackcess.UsageMap.java

/**
 * @param database database that contains this usage map
 * @param pageNum Page number that this usage map is contained in
 * @param rowNum Number of the row on the page that contains this usage map
 * @return Either an InlineUsageMap or a ReferenceUsageMap, depending on
 *         which type of map is found/*from w  w w  . jav a  2s.  co m*/
 */
public static UsageMap read(Database database, int pageNum, int rowNum, boolean assumeOutOfRangeBitsOn)
        throws IOException {
    JetFormat format = database.getFormat();
    PageChannel pageChannel = database.getPageChannel();
    ByteBuffer tableBuffer = pageChannel.createPageBuffer();
    pageChannel.readPage(tableBuffer, pageNum);
    short rowStart = Table.findRowStart(tableBuffer, rowNum, format);
    int rowEnd = Table.findRowEnd(tableBuffer, rowNum, format);
    tableBuffer.limit(rowEnd);
    byte mapType = tableBuffer.get(rowStart);
    UsageMap rtn = new UsageMap(database, tableBuffer, pageNum, rowStart);
    rtn.initHandler(mapType, assumeOutOfRangeBitsOn);
    return rtn;
}

From source file:com.linkedin.databus.core.DbusEventV2.java

public static int serializeEvent(DbusEventKey key, ByteBuffer buf, DbusEventInfo dbusEventInfo) {
    // Serialize a DbusEventV2 that has exact same contents as a DbusEventV1.
    final int start = buf.position();
    buf.put(DbusEventFactory.DBUS_EVENT_V2);
    buf.putInt(MAGIC);//from   www . jav a2  s  .c  om
    buf.putInt(0); // Header len placeholder
    buf.putInt(0); // Header crc placeholder
    buf.putInt(0); // Body CRC placeholder
    buf.putInt(0); // total length placeholder

    short attributes = 0;
    attributes = setOpCode(dbusEventInfo.getOpCode(), attributes, dbusEventInfo.getSrcId());
    attributes = setKeyType(key, attributes);
    if (dbusEventInfo.isEnableTracing()) {
        attributes |= FLAG_TRACE_ON;
    }

    if (dbusEventInfo.isReplicated()) {
        attributes |= FLAG_IS_REPLICATED;
    }

    DbusEventPart metadata = dbusEventInfo.getMetadata();
    if (shouldEncodePayloadPart(dbusEventInfo)) {
        attributes |= FLAG_HAS_PAYLOAD_PART;
    }
    if (metadata != null) {
        attributes |= FLAG_HAS_PAYLOAD_METADATA_PART;
    }
    buf.putShort(attributes);
    buf.putLong(dbusEventInfo.getTimeStampInNanos());
    buf.putInt(dbusEventInfo.getSrcId());
    buf.putShort(dbusEventInfo.getpPartitionId());
    buf.putLong(dbusEventInfo.getSequenceId());

    // Fixed part of header is done. Now for the variable header part
    setKey(buf, key);
    final int hdrEndPos = buf.position();

    if (metadata != null) {
        metadata.encode(buf);
    }

    if ((attributes & FLAG_HAS_PAYLOAD_PART) != 0) {
        ByteBuffer bb = dbusEventInfo.getValueByteBuffer();
        if (bb == null) {
            // Special case to encode when there is no data.
            bb = ByteBuffer.allocate(1).order(buf.order());
            bb.limit(0);
        }
        DbusEventPart valuePart = new DbusEventPart(SchemaDigestType.MD5, dbusEventInfo.getSchemaId(),
                dbusEventInfo.getPayloadSchemaVersion(), bb);
        valuePart.encode(buf);
    }
    final int end = buf.position();
    buf.putInt(start + HeaderLenOffset, hdrEndPos - start);
    buf.putInt(start + TotalLenOffset, end - start);

    long bodyCrc = ByteBufferCRC32.getChecksum(buf, hdrEndPos, end - hdrEndPos);
    Utils.putUnsignedInt(buf, start + BodyCrcOffset, bodyCrc);
    // Header CRC
    if (dbusEventInfo.isAutocommit()) {
        // Do the body CRC first, since that is included in the header CRC
        long hdrCrc = ByteBufferCRC32.getChecksum(buf, start + BodyCrcOffset,
                hdrEndPos - start - BodyCrcOffset);
        Utils.putUnsignedInt(buf, start + HeaderCrcOffset, hdrCrc);
    }
    return buf.position() - start;
}

From source file:com.healthmarketscience.jackcess.impl.UsageMap.java

/**
 * @param database database that contains this usage map
 * @param pageNum Page number that this usage map is contained in
 * @param rowNum Number of the row on the page that contains this usage map
 * @return Either an InlineUsageMap or a ReferenceUsageMap, depending on
 *         which type of map is found//  ww w. j  av  a  2s.c o  m
 */
public static UsageMap read(DatabaseImpl database, int pageNum, int rowNum, boolean assumeOutOfRangeBitsOn)
        throws IOException {
    if (pageNum <= 0) {
        // usage maps will never appear on page 0 (or less)
        throw new IllegalStateException("Invalid usage map page number " + pageNum);
    }

    JetFormat format = database.getFormat();
    PageChannel pageChannel = database.getPageChannel();
    ByteBuffer tableBuffer = pageChannel.createPageBuffer();
    pageChannel.readPage(tableBuffer, pageNum);
    short rowStart = TableImpl.findRowStart(tableBuffer, rowNum, format);
    int rowEnd = TableImpl.findRowEnd(tableBuffer, rowNum, format);
    tableBuffer.limit(rowEnd);
    byte mapType = tableBuffer.get(rowStart);
    UsageMap rtn = new UsageMap(database, tableBuffer, pageNum, rowStart);
    rtn.initHandler(mapType, assumeOutOfRangeBitsOn);
    return rtn;
}

From source file:de.csdev.ebus.command.EBusCommandUtils.java

/**
 * Build an escaped telegram part for a slave answer
 *
 * @param slaveData/*from  w w  w  . jav a2  s  .  c om*/
 * @return
 * @throws EBusTypeException
 */
public static ByteBuffer buildPartSlave(byte[] slaveData) throws EBusTypeException {

    ByteBuffer buf = ByteBuffer.allocate(50);

    buf.put(EBusConsts.ACK_OK); // ACK

    // if payload available
    if (slaveData != null && slaveData.length > 0) {
        buf.put((byte) slaveData.length); // NN - Length

        // add the escaped bytes
        for (byte b : slaveData) {
            buf.put(escapeSymbol(b));
        }

        // calculate crc
        byte crc8 = EBusUtils.crc8(buf.array(), buf.position());

        // add the crc, maybe escaped
        buf.put(escapeSymbol(crc8));
    } else {
        // only set len = 0
        buf.put((byte) 0x00); // NN - Length
    }

    // set limit and reset position
    buf.limit(buf.position());
    buf.position(0);

    return buf;
}

From source file:com.hazelcast.simulator.probes.xml.HistogramConverter.java

@Override
public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) {
    Histogram histogram = (Histogram) object;
    int size = histogram.getNeededByteBufferCapacity();
    ByteBuffer byteBuffer = ByteBuffer.allocate(size);
    int bytesWritten = histogram.encodeIntoCompressedByteBuffer(byteBuffer);
    byteBuffer.rewind();/*w w  w.  j a va  2 s.  c om*/
    byteBuffer.limit(bytesWritten);
    String encodedHistogram = encodeBase64String(byteBuffer.array());

    writer.setValue(encodedHistogram);
}