Java Code Examples for com.google.common.primitives.UnsignedBytes

The following are top voted examples for showing how to use com.google.common.primitives.UnsignedBytes. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: minebox   File: SiaSeedServiceTest.java   View source code 6 votes vote down vote up
@Test
public void testBlakeHash() {
    Assert.assertEquals(32, TESTVECTOR_UNSIGED_SIA_BYTES.length);
    Assert.assertEquals(32, TESTVECTOR_UNSIGNED_BLAKE_HASH.length);

    byte[] signedSiaBytes = new byte[32];
    for (int i = 0; i < TESTVECTOR_UNSIGED_SIA_BYTES.length; i++) {
        signedSiaBytes[i] = UnsignedBytes.checkedCast(TESTVECTOR_UNSIGED_SIA_BYTES[i]);
    }
    final byte[] result = SiaSeedService.blakeHash(signedSiaBytes);

    for (int i = 0; i < result.length; i++) {
        byte b = result[i];
        Assert.assertEquals(UnsignedBytes.checkedCast(TESTVECTOR_UNSIGNED_BLAKE_HASH[i]), b);
    }
    final List<String> strings = SiaSeedService.buildSiaWords(signedSiaBytes);
    Assert.assertEquals(TEST_VECTOR_WODS, strings);

}
 
Example 2
Project: silent-support   File: ApiLookup.java   View source code 6 votes vote down vote up
private String dumpEntry(int offset) {
    if (DEBUG_SEARCH) {
        StringBuilder sb = new StringBuilder(200);
        for (int i = offset; i < mData.length; i++) {
            if (mData[i] == 0) {
                break;
            }
            char c = (char) UnsignedBytes.toInt(mData[i]);
            sb.append(c);
        }

        return sb.toString();
    } else {
        return "<disabled>";
    }
}
 
Example 3
Project: dremio-oss   File: RocksDBStore.java   View source code 6 votes vote down vote up
private void populateNext() {
  nextKey = null;
  nextValue = null;

  if (!iter.isValid()) {
    return;
  }

  byte[] key = iter.key();
  if (end != null) {
    int comparison = UnsignedBytes.lexicographicalComparator().compare(key, end);
    if ( !(comparison < 0 || (comparison == 0 && endInclusive))) {
      // hit end key.
      return;
    }
  }

  nextKey = key;
  nextValue = iter.value();

}
 
Example 4
Project: tools   File: SiaSeedServiceTest.java   View source code 6 votes vote down vote up
@Test
public void testBlakeHash() {
    Assert.assertEquals(32, TESTVECTOR_UNSIGED_SIA_BYTES.length);
    Assert.assertEquals(32, TESTVECTOR_UNSIGNED_BLAKE_HASH.length);

    byte[] signedSiaBytes = new byte[32];
    for (int i = 0; i < TESTVECTOR_UNSIGED_SIA_BYTES.length; i++) {
        signedSiaBytes[i] = UnsignedBytes.checkedCast(TESTVECTOR_UNSIGED_SIA_BYTES[i]);
    }
    final byte[] result = SiaSeedService.blakeHash(signedSiaBytes);

    for (int i = 0; i < result.length; i++) {
        byte b = result[i];
        Assert.assertEquals(UnsignedBytes.checkedCast(TESTVECTOR_UNSIGNED_BLAKE_HASH[i]), b);
    }
    final List<String> strings = SiaSeedService.buildSiaWords(signedSiaBytes);
    Assert.assertEquals(TEST_VECTOR_WODS, strings);

}
 
Example 5
Project: ditb   File: PrefixTreeArraySearcher.java   View source code 6 votes vote down vote up
/**
 * Compare only the bytes within the window of the current token
 * @param key
 * @return return -1 if key is lessThan (before) this, 0 if equal, and 1 if key is after
 */
protected int compareToCurrentToken(Cell key) {
  int startIndex = rowLength - currentRowNode.getTokenLength();
  int endIndexExclusive = startIndex + currentRowNode.getTokenLength();
  for (int i = startIndex; i < endIndexExclusive; ++i) {
    if (i >= key.getRowLength()) {// key was shorter, so it's first
      return -1;
    }
    byte keyByte = CellUtil.getRowByte(key, i);
    byte thisByte = rowBuffer[i];
    if (keyByte == thisByte) {
      continue;
    }
    return UnsignedBytes.compare(keyByte, thisByte);
  }
  if (!currentRowNode.hasOccurrences() && rowLength >= key.getRowLength()) { // key was shorter
      return -1;
  }
  return 0;
}
 
Example 6
Project: tracingplane-java   File: UnsignedByteBuffer.java   View source code 6 votes vote down vote up
@Override
public int compare(ByteBuffer left, ByteBuffer right) {
    int initialLeftPosition = left.position();
    int initialRightPosition = right.position();
    try {
        int minLength = Math.min(left.remaining(), right.remaining());
        for (int i = 0; i < minLength; i++) {
            int result = UnsignedBytes.compare(left.get(), right.get());
            if (result != 0) {
                return result;
            }
        }
        return left.remaining() - right.remaining();
    } finally {
        left.position(initialLeftPosition);
        right.position(initialRightPosition);
    }
}
 
Example 7
Project: lmdbjava   File: CursorIteratorTest.java   View source code 6 votes vote down vote up
@Test
public void openClosedBackwardTestWithGuava() {
  final Comparator<byte[]> guava = UnsignedBytes.lexicographicalComparator();
  final Comparator<ByteBuffer> comparator = (bb1, bb2) -> {
    final byte[] array1 = new byte[bb1.remaining()];
    final byte[] array2 = new byte[bb2.remaining()];
    bb1.mark();
    bb2.mark();
    bb1.get(array1);
    bb2.get(array2);
    bb1.reset();
    bb2.reset();
    return guava.compare(array1, array2);
  };
  verify(openClosedBackward(bb(7), bb(2)), comparator, 6, 4, 2);
  verify(openClosedBackward(bb(8), bb(4)), comparator, 6, 4);
}
 
Example 8
Project: codebuff   File: BloomFilter.java   View source code 6 votes vote down vote up
/**
 * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java
 * serialization). This has been measured to save at least 400 bytes compared to regular
 * serialization.
 *
 * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter.
 */


public void writeTo(OutputStream out) throws IOException {
  // Serial form:
  // 1 signed byte for the strategy
  // 1 unsigned byte for the number of hash functions
  // 1 big endian int, the number of longs in our bitset
  // N big endian longs of our bitset
  DataOutputStream dout = new DataOutputStream(out);
  dout.writeByte(SignedBytes.checkedCast(strategy.ordinal()));
  dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor
  dout.writeInt(bits.data.length);
  for (long value : bits.data) {
    dout.writeLong(value);
  }
}
 
Example 9
Project: codebuff   File: BloomFilter.java   View source code 6 votes vote down vote up
/**
 * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java
 * serialization). This has been measured to save at least 400 bytes compared to regular
 * serialization.
 *
 * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter.
 */


public void writeTo(OutputStream out) throws IOException {
  // Serial form:
  // 1 signed byte for the strategy
  // 1 unsigned byte for the number of hash functions
  // 1 big endian int, the number of longs in our bitset
  // N big endian longs of our bitset
  DataOutputStream dout = new DataOutputStream(out);
  dout.writeByte(SignedBytes.checkedCast(strategy.ordinal()));
  dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor
  dout.writeInt(bits.data.length);
  for (long value : bits.data) {
    dout.writeLong(value);
  }
}
 
Example 10
Project: codebuff   File: BloomFilter.java   View source code 6 votes vote down vote up
/**
 * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java
 * serialization). This has been measured to save at least 400 bytes compared to regular
 * serialization.
 *
 * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter.
 */


public void writeTo(OutputStream out) throws IOException {
  // Serial form:
  // 1 signed byte for the strategy
  // 1 unsigned byte for the number of hash functions
  // 1 big endian int, the number of longs in our bitset
  // N big endian longs of our bitset
  DataOutputStream dout = new DataOutputStream(out);
  dout.writeByte(SignedBytes.checkedCast(strategy.ordinal()));
  dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor
  dout.writeInt(bits.data.length);
  for (long value : bits.data) {
    dout.writeLong(value);
  }
}
 
Example 11
Project: codebuff   File: BloomFilter.java   View source code 6 votes vote down vote up
/**
 * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java
 * serialization). This has been measured to save at least 400 bytes compared to regular
 * serialization.
 *
 * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter.
 */


public void writeTo(OutputStream out) throws IOException {
  // Serial form:
  // 1 signed byte for the strategy
  // 1 unsigned byte for the number of hash functions
  // 1 big endian int, the number of longs in our bitset
  // N big endian longs of our bitset
  DataOutputStream dout = new DataOutputStream(out);
  dout.writeByte(SignedBytes.checkedCast(strategy.ordinal()));
  dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor
  dout.writeInt(bits.data.length);
  for (long value : bits.data) {
    dout.writeLong(value);
  }
}
 
Example 12
Project: thunder   File: Channel.java   View source code 6 votes vote down vote up
public Sha256Hash getHash () {
    if (hash != null) {
        return hash;
    }
    //TODO for now we take the two anchor hashes, this works until we have multiple anchors..
    List<byte[]> list = new ArrayList<>();

    list.add(keyServer.getPubKey());
    list.add(keyClient.getPubKey());
    list.sort(UnsignedBytes.lexicographicalComparator());
    ByteBuffer byteBuffer = ByteBuffer.allocate(list.get(0).length + list.get(1).length);
    byteBuffer.put(list.get(0));
    byteBuffer.put(list.get(1));
    hash = Sha256Hash.of(byteBuffer.array());
    return hash;
}
 
Example 13
Project: beam   File: InstantCoderTest.java   View source code 6 votes vote down vote up
@Test
public void testOrderedEncoding() throws Exception {
  List<Long> sortedTimestamps = new ArrayList<>(TEST_TIMESTAMPS);
  Collections.sort(sortedTimestamps);

  List<byte[]> encodings = new ArrayList<>(sortedTimestamps.size());
  for (long timestamp : sortedTimestamps) {
    encodings.add(CoderUtils.encodeToByteArray(TEST_CODER, new Instant(timestamp)));
  }

  // Verify that the encodings were already sorted, since they were generated
  // in the correct order.
  List<byte[]> sortedEncodings = new ArrayList<>(encodings);
  Collections.sort(sortedEncodings, UnsignedBytes.lexicographicalComparator());

  Assert.assertEquals(encodings, sortedEncodings);
}
 
Example 14
Project: intellij-ce-playground   File: ApiLookup.java   View source code 6 votes vote down vote up
private String dumpEntry(int offset) {
    if (DEBUG_SEARCH) {
        StringBuilder sb = new StringBuilder(200);
        for (int i = offset; i < mData.length; i++) {
            if (mData[i] == 0) {
                break;
            }
            char c = (char) UnsignedBytes.toInt(mData[i]);
            sb.append(c);
        }

        return sb.toString();
    } else {
        return "<disabled>"; //$NON-NLS-1$
    }
}
 
Example 15
Project: UMLS-Terminology-Server   File: ConfigUtility.java   View source code 6 votes vote down vote up
/**
 * Returns the byte comparator.
 *
 * @return the byte comparator
 */
public static Comparator<String> getByteComparator() {
  return new Comparator<String>() {

    /* see superclass */
    @Override
    public int compare(String o1, String o2) {
      try {
        return UnsignedBytes.lexicographicalComparator()
            .compare(o1.getBytes("UTF-8"), o2.getBytes("UTF-8"));
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }

  };
}
 
Example 16
Project: guava-libraries   File: BloomFilter.java   View source code 6 votes vote down vote up
/**
 * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java
 * serialization). This has been measured to save at least 400 bytes compared to regular
 * serialization.
 *
 * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter.
 */
public void writeTo(OutputStream out) throws IOException {
  /*
   * Serial form:
   * 1 signed byte for the strategy
   * 1 unsigned byte for the number of hash functions
   * 1 big endian int, the number of longs in our bitset
   * N big endian longs of our bitset
   */
  DataOutputStream dout = new DataOutputStream(out);
  dout.writeByte(SignedBytes.checkedCast(strategy.ordinal()));
  dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor
  dout.writeInt(bits.data.length);
  for (long value : bits.data) {
    dout.writeLong(value);
  }
}
 
Example 17
Project: simple-xml-serializers   File: PersisterUtils.java   View source code 6 votes vote down vote up
@Nonnull
public static String toString(@Nonnull byte[] data, @Nonnegative int start, @Nonnegative int len) {
    StringBuilder buf = new StringBuilder();
    buf.append("Array(start=").append(start).append(", len=").append(len).append(", data=[");
    int count = Math.min(32, len);
    for (int i = 0; i < count; i++) {
        if (i > 0)
            buf.append(", ");
        int idx = start + i;
        if (idx >= data.length) {
            buf.append("OOBE!");
            break;
        }
        buf.append(UnsignedBytes.toString(data[i], 16));
    }
    if (len > 32)
        buf.append(", ...");
    buf.append("])");
    return buf.toString();
}
 
Example 18
Project: pbase   File: PrefixTreeArraySearcher.java   View source code 6 votes vote down vote up
/**
 * Compare only the bytes within the window of the current token
 * @param key
 * @return return -1 if key is lessThan (before) this, 0 if equal, and 1 if key is after
 */
protected int compareToCurrentToken(Cell key) {
  int startIndex = rowLength - currentRowNode.getTokenLength();
  int endIndexExclusive = startIndex + currentRowNode.getTokenLength();
  for (int i = startIndex; i < endIndexExclusive; ++i) {
    if (i >= key.getRowLength()) {// key was shorter, so it's first
      return -1;
    }
    byte keyByte = CellUtil.getRowByte(key, i);
    byte thisByte = rowBuffer[i];
    if (keyByte == thisByte) {
      continue;
    }
    return UnsignedBytes.compare(keyByte, thisByte);
  }
  if (!currentRowNode.hasOccurrences() && rowLength >= key.getRowLength()) { // key was shorter
      return -1;
  }
  return 0;
}
 
Example 19
Project: HIndex   File: PrefixTreeArraySearcher.java   View source code 6 votes vote down vote up
/**
 * Compare only the bytes within the window of the current token
 * @param key
 * @return return -1 if key is lessThan (before) this, 0 if equal, and 1 if key is after
 */
protected int compareToCurrentToken(Cell key) {
  int startIndex = rowLength - currentRowNode.getTokenLength();
  int endIndexExclusive = startIndex + currentRowNode.getTokenLength();
  for (int i = startIndex; i < endIndexExclusive; ++i) {
    if (i >= key.getRowLength()) {// key was shorter, so it's first
      return -1;
    }
    byte keyByte = CellUtil.getRowByte(key, i);
    byte thisByte = rowBuffer[i];
    if (keyByte == thisByte) {
      continue;
    }
    return UnsignedBytes.compare(keyByte, thisByte);
  }
  return 0;
}
 
Example 20
Project: ipmi4j   File: IpmiRAKPMessage1.java   View source code 6 votes vote down vote up
@Override
protected void toWireUnchecked(IpmiPacketContext context, ByteBuffer buffer) {
    buffer.put(messageTag);
    buffer.put(new byte[3]);    // reserved
    toWireIntLE(buffer, systemSessionId);
    buffer.put(consoleRandom);
    buffer.put(Bits.toByte(requestedMaximumPrivilegeLevel, privilegeLookupMode));
    buffer.putChar((char) 0); // reserved
    if (username != null) {
        byte[] usernameBytes = username.getBytes(Charsets.ISO_8859_1);
        buffer.put(UnsignedBytes.checkedCast(usernameBytes.length));    // Max is 0x10.
        buffer.put(usernameBytes);
    } else {
        buffer.put((byte) 0);
    }
}
 
Example 21
Project: ipmi4j   File: Ipmi15SessionWrapper.java   View source code 6 votes vote down vote up
@Override
public void fromWireUnchecked(IpmiPacketContext context, ByteBuffer buffer) {
    IpmiSessionAuthenticationType authenticationType = Code.fromBuffer(IpmiSessionAuthenticationType.class, buffer);
    setIpmiSessionSequenceNumber(buffer.getInt());
    setIpmiSessionId(buffer.getInt());

    if (authenticationType != IpmiSessionAuthenticationType.NONE) {
        byte[] ipmiMessageAuthenticationCode = AbstractWireable.readBytes(buffer, 16);
    }
    byte payloadLength = buffer.get();

    ByteBuffer payloadBuffer = buffer.duplicate();
    payloadBuffer.limit(payloadBuffer.position() + UnsignedBytes.toInt(payloadLength));
    buffer.position(payloadBuffer.limit());

    IpmiPayload payload = newPayload(payloadBuffer, IpmiPayloadType.IPMI);
    payload.fromWire(context, payloadBuffer);
    setIpmiPayload(payload);

    // assert payloadLength == header.getWireLength() + payload.getWireLength();
}
 
Example 22
Project: Qora   File: TransactionMap.java   View source code 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void createIndexes(DB database)
{
	//TIMESTAMP INDEX
	Tuple2Comparator<Long, byte[]> comparator = new Fun.Tuple2Comparator<Long, byte[]>(Fun.COMPARATOR, UnsignedBytes.lexicographicalComparator());
	NavigableSet<Tuple2<Integer, byte[]>> heightIndex = database.createTreeSet("transactions_index_timestamp")
			.comparator(comparator)
			.makeOrGet();
			
	NavigableSet<Tuple2<Integer, byte[]>> descendingHeightIndex = database.createTreeSet("transactions_index_timestamp_descending")
			.comparator(new ReverseComparator(comparator))
			.makeOrGet();
			
	createIndex(TIMESTAMP_INDEX, heightIndex, descendingHeightIndex, new Fun.Function2<Long, byte[], Transaction>() {
	   	@Override
	    public Long run(byte[] key, Transaction value) {
	   		return value.getTimestamp();
	    }
	});
}
 
Example 23
Project: RuneCraftery   File: ModIdMapPacket.java   View source code 6 votes vote down vote up
@Override
public FMLPacket consumePacket(byte[] data)
{
    ByteArrayDataInput bdi = ByteStreams.newDataInput(data);
    int chunkIdx = UnsignedBytes.toInt(bdi.readByte());
    int chunkTotal = UnsignedBytes.toInt(bdi.readByte());
    int chunkLength = bdi.readInt();
    if (partials == null)
    {
        partials = new byte[chunkTotal][];
    }
    partials[chunkIdx] = new byte[chunkLength];
    bdi.readFully(partials[chunkIdx]);
    for (int i = 0; i < partials.length; i++)
    {
        if (partials[i] == null)
        {
            return null;
        }
    }
    return this;
}
 
Example 24
Project: SolderCraft   File: CapeConfigManager.java   View source code 6 votes vote down vote up
public static int claimId(int id) {
	if(id <= 0){
		DevCapes.logger.error("The config ID can NOT be negative or 0!");
		return id;
	}
    try {
        UnsignedBytes.checkedCast(id);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }

    boolean isRegistered = availableIds.get(id);
    if (isRegistered) {
        DevCapes.logger.error(String.format("The config ID %d is already claimed.", id));
    }

    availableIds.set(id);
    return id;
}
 
Example 25
Project: mongowp   File: ParsingTools.java   View source code 6 votes vote down vote up
protected static BinarySubtype getBinarySubtype(byte readByte) {
  switch (readByte) {
    case 0x00:
      return BinarySubtype.GENERIC;
    case 0x01:
      return BinarySubtype.FUNCTION;
    case 0x02:
      return BinarySubtype.OLD_BINARY;
    case 0x03:
      return BinarySubtype.OLD_UUID;
    case 0x04:
      return BinarySubtype.UUID;
    case 0x05:
      return BinarySubtype.MD5;
    default: {
      if (UnsignedBytes.compare(readByte, FIRST_USER_DEFINED) >= 0) {
        return BinarySubtype.USER_DEFINED;
      } else {
        throw new AssertionError(
            "Unrecognized binary type 0x" + UnsignedBytes.toString(readByte, 16));
      }
    }
  }
}
 
Example 26
Project: mongowp   File: MongoBsonTranslator.java   View source code 6 votes vote down vote up
protected static BinarySubtype getBinarySubtype(byte readByte) {
  switch (readByte) {
    case 0x00:
      return BinarySubtype.GENERIC;
    case 0x01:
      return BinarySubtype.FUNCTION;
    case 0x02:
      return BinarySubtype.OLD_BINARY;
    case 0x03:
      return BinarySubtype.OLD_UUID;
    case 0x04:
      return BinarySubtype.UUID;
    case 0x05:
      return BinarySubtype.MD5;
    default:
    {
      if (UnsignedBytes.compare(readByte, FIRST_USER_DEFINED) >= 0) {
        return BinarySubtype.USER_DEFINED;
      } else {
        throw new AssertionError(
                "Unrecognized binary type 0x" + UnsignedBytes.toString(readByte, 16));
      }
    }
  }
}
 
Example 27
Project: RuneCraftery   File: ForgePacket.java   View source code 6 votes vote down vote up
public static ForgePacket readPacket(INetworkManager network, byte[] payload)
{
    boolean multipart = UnsignedBytes.toInt(payload[0]) == 1;
    int type = UnsignedBytes.toInt(payload[1]);
    Type eType = Type.values()[type];
    byte[] data = Arrays.copyOfRange(payload, 2, payload.length);

    if (multipart)
    {
        ForgePacket pkt = eType.consumePart(network, data);
        if (pkt != null)
        {
            return pkt.consumePacket(Bytes.concat(pkt.partials));
        }
        return null;
    }
    else
    {
        return eType.make().consumePacket(data);
    }
}
 
Example 28
Project: CaracalDB   File: CustomSerialisers.java   View source code 6 votes vote down vote up
public static void serialiseKey(Key key, ByteBuf w) {
    byte[] id = key.getArray();
    BitBuffer bbuf = BitBuffer.create((key instanceof Key.Inf), (id == null));
    boolean byteFlag = (id != null) && (id.length <= Key.BYTE_KEY_SIZE);
    bbuf.write(byteFlag);
    byte[] flags = bbuf.finalise();
    w.writeBytes(flags);
    if (id != null) {
        if (byteFlag) {
            w.writeByte(UnsignedBytes.checkedCast(id.length));
        } else {
            w.writeInt(id.length);
        }
        w.writeBytes(id);
    }
}
 
Example 29
Project: CaracalDB   File: CustomSerialisers.java   View source code 6 votes vote down vote up
public static Key deserialiseKey(ByteBuf r) {
    byte[] flagBytes = new byte[1];
    r.readBytes(flagBytes);
    boolean[] flags = BitBuffer.extract(3, flagBytes);
    boolean infFlag = flags[0];
    boolean nullFlag = flags[1];
    boolean byteFlag = flags[2];
    if (infFlag) {
        return Key.INF;
    }
    if (nullFlag) {
        return new Key((byte[]) null);
    }
    int keySize;
    if (byteFlag) {
        keySize = UnsignedBytes.toInt(r.readByte());
    } else {
        keySize = r.readInt();
    }
    byte[] id;
    id = new byte[keySize];
    r.readBytes(id);
    return new Key(id);
}
 
Example 30
Project: bgpcep   File: Stateful07LspObjectParser.java   View source code 6 votes vote down vote up
@Override
public void serializeObject(final Object object, final ByteBuf buffer) {
    Preconditions.checkArgument(object instanceof Lsp, "Wrong instance of PCEPObject. Passed %s . Needed LspObject.", object.getClass());
    final Lsp specObj = (Lsp) object;
    final ByteBuf body = Unpooled.buffer();
    Preconditions.checkArgument(specObj.getPlspId() != null, "PLSP-ID not present");
    writeMedium(specObj.getPlspId().getValue().intValue() << FOUR_BITS_SHIFT, body);
    final BitArray flags = serializeFlags(specObj);
    byte op = 0;
    if (specObj.getOperational() != null) {
        op = UnsignedBytes.checkedCast(specObj.getOperational().getIntValue());
        op = (byte) (op << FOUR_BITS_SHIFT);
    }
    final byte[] res = flags.array();
    res[res.length -1] = (byte) (res[res.length -1] | op);
    body.writeByte(res[res.length -1]);
    serializeTlvs(specObj.getTlvs(), body);
    ObjectUtil.formatSubobject(TYPE, CLASS, object.isProcessingRule(), object.isIgnore(), body, buffer);
}
 
Example 31
Project: bgpcep   File: AbstractXROWithSubobjectsParser.java   View source code 6 votes vote down vote up
protected List<Subobject> parseSubobjects(final ByteBuf buffer) throws PCEPDeserializerException {
    Preconditions.checkArgument(buffer != null && buffer.isReadable(), "Array of bytes is mandatory. Can't be null or empty.");
    final List<Subobject> subs = new ArrayList<>();
    while (buffer.isReadable()) {
        final boolean mandatory = ((buffer.getUnsignedByte(buffer.readerIndex()) & (1 << Values.FIRST_BIT_OFFSET)) != 0) ? true : false;
        final int type = UnsignedBytes.checkedCast((buffer.readUnsignedByte() & Values.BYTE_MAX_VALUE_BYTES) & ~(1 << Values.FIRST_BIT_OFFSET));
        final int length = buffer.readUnsignedByte() - HEADER_LENGTH;
        if (length > buffer.readableBytes()) {
            throw new PCEPDeserializerException("Wrong length specified. Passed: " + length + "; Expected: <= "
                    + buffer.readableBytes());
        }
        LOG.debug("Attempt to parse subobject from bytes: {}", ByteBufUtil.hexDump(buffer));
        final Subobject sub = this.subobjReg.parseSubobject(type, buffer.readSlice(length), mandatory);
        if (sub == null) {
            LOG.warn("Unknown subobject type: {}. Ignoring subobject.", type);
        } else {
            LOG.debug("Subobject was parsed. {}", sub);
            subs.add(sub);
        }
    }
    return subs;
}
 
Example 32
Project: RuneCraftery   File: ForgePacket.java   View source code 6 votes vote down vote up
public static ForgePacket readPacket(INetworkManager network, byte[] payload)
{
    boolean multipart = UnsignedBytes.toInt(payload[0]) == 1;
    int type = UnsignedBytes.toInt(payload[1]);
    Type eType = Type.values()[type];
    byte[] data = Arrays.copyOfRange(payload, 2, payload.length);

    if (multipart)
    {
        ForgePacket pkt = eType.consumePart(network, data);
        if (pkt != null)
        {
            return pkt.consumePacket(Bytes.concat(pkt.partials));
        }
        return null;
    }
    else
    {
        return eType.make().consumePacket(data);
    }
}
 
Example 33
Project: RuneCraftery   File: ModIdMapPacket.java   View source code 6 votes vote down vote up
@Override
public FMLPacket consumePacket(byte[] data)
{
    ByteArrayDataInput bdi = ByteStreams.newDataInput(data);
    int chunkIdx = UnsignedBytes.toInt(bdi.readByte());
    int chunkTotal = UnsignedBytes.toInt(bdi.readByte());
    int chunkLength = bdi.readInt();
    if (partials == null)
    {
        partials = new byte[chunkTotal][];
    }
    partials[chunkIdx] = new byte[chunkLength];
    bdi.readFully(partials[chunkIdx]);
    for (int i = 0; i < partials.length; i++)
    {
        if (partials[i] == null)
        {
            return null;
        }
    }
    return this;
}
 
Example 34
Project: ipmi4j   File: IpmiRAKPMessage1.java   View source code 6 votes vote down vote up
@Override
protected void fromWireUnchecked(IpmiPacketContext context, ByteBuffer buffer) {
    messageTag = buffer.get();
    assertWireBytesZero(buffer, 3);
    systemSessionId = fromWireIntLE(buffer);
    consoleRandom = readBytes(buffer, 16);
    byte requestedMaximumPrivilegeLevelByte = buffer.get();
    requestedMaximumPrivilegeLevel = Code.fromByte(RequestedMaximumPrivilegeLevel.class, (byte) (requestedMaximumPrivilegeLevelByte & RequestedMaximumPrivilegeLevel.MASK));
    privilegeLookupMode = Code.fromByte(PrivilegeLookupMode.class, (byte) (requestedMaximumPrivilegeLevelByte & PrivilegeLookupMode.MASK));
    assertWireBytesZero(buffer, 2);
    int usernameLength = UnsignedBytes.toInt(buffer.get());
    if (usernameLength > 0) {
        byte[] usernameBytes = readBytes(buffer, usernameLength);
        username = new String(usernameBytes, Charsets.ISO_8859_1);
    } else {
        username = null;
    }
}
 
Example 35
Project: bgpcep   File: Ipv4Util.java   View source code 6 votes vote down vote up
/**
 * Creates a list of Ipv4 Prefixes from given byte array.
 *
 * @param bytes to be converted to List of Ipv4Prefixes.
 * @return A list of Ipv4Prefixes
 */
public static List<Ipv4Prefix> prefixListForBytes(final byte[] bytes) {
    if (bytes.length == 0) {
        return Collections.emptyList();
    }
    final List<Ipv4Prefix> list = new ArrayList<>();
    int byteOffset = 0;
    while (byteOffset < bytes.length) {
        final int bitLength = UnsignedBytes.toInt(bytes[byteOffset]);
        byteOffset += 1;
        // if length == 0, default route will be added
        if (bitLength == 0) {
            list.add(EMPTY_PREFIX);
            continue;
        }

        list.add(IetfInetUtil.INSTANCE.ipv4PrefixForShort(bytes, byteOffset, bitLength));
        byteOffset += bitLength / Byte.SIZE;
        if (bitLength % Byte.SIZE != 0) {
            byteOffset++;
        }

    }
    return list;
}
 
Example 36
Project: bgpcep   File: Ipv6Util.java   View source code 6 votes vote down vote up
/**
 * Creates a list of Ipv6 Prefixes from given byte array.
 *
 * @param bytes to be converted to List of Ipv6Prefixes.
 * @return A List of Ipv6Prefixes
 */
public static List<Ipv6Prefix> prefixListForBytes(final byte[] bytes) {
    if (bytes.length == 0) {
        return Collections.emptyList();
    }
    final List<Ipv6Prefix> list = new ArrayList<>();
    int byteOffset = 0;
    while (byteOffset < bytes.length) {
        final int bitLength = UnsignedBytes.toInt(bytes[byteOffset]);
        byteOffset += 1;
        // if length == 0, default route will be added
        if (bitLength == 0) {
            list.add(EMPTY_PREFIX);
            continue;
        }
        list.add(IetfInetUtil.INSTANCE.ipv6PrefixForShort(bytes, byteOffset, bitLength));
        byteOffset += bitLength / Byte.SIZE;
        if (bitLength % Byte.SIZE != 0) {
            byteOffset++;
        }
    }
    return list;
}
 
Example 37
Project: bgpcep   File: XROSubobjectListParser.java   View source code 6 votes vote down vote up
public List<SubobjectContainer> parseList(final ByteBuf byteBuf) throws RSVPParsingException {
    final List<SubobjectContainer> subs = new ArrayList<>();
    while (byteBuf.isReadable()) {
        final boolean mandatory = (byteBuf.getUnsignedByte(byteBuf.readerIndex()) & (1 << Values
            .FIRST_BIT_OFFSET)) != 0;
        final int type = UnsignedBytes.checkedCast((byteBuf.readUnsignedByte() & Values.BYTE_MAX_VALUE_BYTES) & ~
            (1 << Values.FIRST_BIT_OFFSET));
        final int length = byteBuf.readUnsignedByte() - HEADER_LENGHT;
        if (length > byteBuf.readableBytes()) {
            throw new RSVPParsingException("Wrong length specified. Passed: " + length
                + "; Expected: <= " + byteBuf.readableBytes());
        }
        LOG.debug("Attempt to parse subobject from bytes: {}", ByteBufUtil.hexDump(byteBuf));
        final SubobjectContainer sub = this.subobjReg.parseSubobject(type, byteBuf.readSlice(length), mandatory);

        if (sub == null) {
            LOG.warn("Unknown subobject type: {}. Ignoring subobject.", type);
        } else {
            LOG.debug("Subobject was parsed. {}", sub);
            subs.add(sub);
        }
    }
    return subs;
}
 
Example 38
Project: dhcp4j   File: NetworkSet.java   View source code 6 votes vote down vote up
private static void _add_bit(@Nonnull byte[] data, @Nonnegative int bitIndex) {
    // LOG.info("  +: Add " + bitIndex + " to " + UnsignedBytes.join(" ", data));
    // LOG.info(bitIndex + " -> " + (bitIndex / 8) + "[" + (bitIndex % 8) + "] & " + byteValue);

    int byteValue = 1 << (7 - (bitIndex % 8));
    // This is actually an arbitrary precision arithmetic routine computing
    // data + (1 e bitIndex)
    for (int byteIndex = bitIndex / 8; byteIndex >= 0; byteIndex--) {
        if (byteValue == 0)
            break;
        byteValue += UnsignedBytes.toInt(data[byteIndex]);
        data[byteIndex] = (byte) (byteValue & 0xFF);
        byteValue >>= Byte.SIZE;
    }
    // LOG.info("  +: Result is " + UnsignedBytes.join(" ", data));
}
 
Example 39
Project: dhcp4j   File: AddressUtils.java   View source code 6 votes vote down vote up
/** Big-endian. */
@Nonnull
public static byte[] add(@Nonnull byte[] in, @Nonnull byte[] value) {
    Preconditions.checkArgument(in.length == value.length,
            "Illegal addend of length %s for array of length %s", value.length, in.length);
    // return new BigInteger(in).add(new BigInteger(Longs.toByteArray(value))).toByteArray();
    int carry = 0;
    for (int i = in.length - 1; i >= 0; i--) {
        int sum = UnsignedBytes.toInt(in[i]) + UnsignedBytes.toInt(value[i]) + carry;
        in[i] = (byte) (sum & 0xFF);
        carry = sum >> Byte.SIZE;
    }

    // Preconditions.checkArgument(carry == 0, "Carry overflow after addition.");
    return in;
}
 
Example 40
Project: ipmi4j   File: GetChannelInfoResponse.java   View source code 6 votes vote down vote up
@Override
protected void fromWireData(ByteBuffer buffer) {
    if (fromWireCompletionCode(buffer))
        return;
    channelNumber = Code.fromBuffer(IpmiChannelNumber.class, buffer);
    channelMedium = Code.fromBuffer(IpmiChannelMedium.class, buffer);
    channelProtocol = Code.fromBuffer(IpmiChannelProtocol.class, buffer);

    int tmp = UnsignedBytes.toInt(buffer.get());
    channelSessionSupport = Code.fromInt(ChannelSessionSupport.class, tmp >> 6);
    channelSessionCount = tmp & 0x3F;

    oemEnterpriseNumber = fromWireOemIanaLE3(buffer);
    if (IpmiChannelNumber.CF.equals(channelNumber)) {
        smsInterruptType = Code.fromBuffer(ChannelInterruptType.class, buffer);
        eventMessageBufferInterruptType = Code.fromBuffer(ChannelInterruptType.class, buffer);
    } else if (oemEnterpriseNumber != IanaEnterpriseNumber.Intelligent_Platform_Management_Interface_forum.getNumber()) {
        oem0 = buffer.get();
        oem1 = buffer.get();
    } else {
        assertWireBytesZero(buffer, 2);
    }
}