com.google.common.primitives.UnsignedBytes Java Examples

The following examples show how to use com.google.common.primitives.UnsignedBytes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AsfRAKPMessage1Data.java    From ipmi4j with Apache License 2.0 6 votes vote down vote up
@Override
protected void toWireData(ByteBuffer buffer) {
    buffer.putInt(getClientSessionId());
    buffer.put(getConsoleRandom());
    buffer.put(getConsoleUserRole().getCode());
    buffer.putShort((short) 0); // Reserved, 0

    String userName = getConsoleUserName();
    if (userName != null) {
        byte[] userNameBytes = userName.getBytes(Charsets.US_ASCII);
        buffer.put(UnsignedBytes.checkedCast(userNameBytes.length));
        buffer.put(Arrays.copyOf(userNameBytes, 16));   // XXX Wrong: It should be variable?
    } else {
        buffer.put(new byte[17]);
    }
}
 
Example #2
Source File: IpmiRAKPMessage1.java    From ipmi4j with Apache License 2.0 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 #3
Source File: Ipmi15SessionWrapper.java    From ipmi4j with Apache License 2.0 6 votes vote down vote up
/** Sequence number handling: [IPMI2] Section 6.12.8, page 58. */
@Override
public void toWireUnchecked(IpmiPacketContext context, ByteBuffer buffer) {
    // Page 133
    buffer.put(authenticationType.getCode());
    buffer.putInt(getIpmiSessionSequenceNumber());
    buffer.putInt(getIpmiSessionId());
    if (authenticationType != IpmiSessionAuthenticationType.NONE) {
        byte[] ipmiMessageAuthenticationCode = null;    // new byte 16
        buffer.put(ipmiMessageAuthenticationCode);
    }
    // Page 134
    IpmiPayload payload = getIpmiPayload();
    int payloadLength = payload.getWireLength(context);
    // LOG.info("payload=" + payload);
    // LOG.info("payloadLength=" + payloadLength);
    buffer.put(UnsignedBytes.checkedCast(payloadLength));

    payload.toWire(context, buffer);
}
 
Example #4
Source File: AddressUtils.java    From dhcp4j with Apache License 2.0 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 #5
Source File: RocksDBQueryExecution.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public int compare(final RangeReadInfo o1, final RangeReadInfo o2) {
  int comp =
      UnsignedBytes.lexicographicalComparator().compare(
          o1.sortKeyRange.getStart(),
          o2.sortKeyRange.getStart());
  if (comp != 0) {
    return comp;
  }
  comp =
      UnsignedBytes.lexicographicalComparator().compare(
          o1.sortKeyRange.getEnd(),
          o2.sortKeyRange.getEnd());
  if (comp != 0) {
    return comp;
  }
  final byte[] otherComp = o2.partitionKey == null ? new byte[0] : o2.partitionKey;
  final byte[] thisComp = o1.partitionKey == null ? new byte[0] : o1.partitionKey;

  return UnsignedBytes.lexicographicalComparator().compare(thisComp, otherComp);
}
 
Example #6
Source File: BloomFilter.java    From codebuff with BSD 2-Clause "Simplified" License 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 #7
Source File: CommitteeUtil.java    From teku with Apache License 2.0 6 votes vote down vote up
/**
 * Return from ``indices`` a random index sampled by effective balance.
 *
 * @param state
 * @param indices
 * @param seed
 * @return
 */
public static int compute_proposer_index(BeaconState state, List<Integer> indices, Bytes32 seed) {
  checkArgument(!indices.isEmpty(), "compute_proposer_index indices must not be empty");
  UnsignedLong MAX_RANDOM_BYTE = UnsignedLong.valueOf(255); // Math.pow(2, 8) - 1;
  int i = 0;
  Bytes32 hash = null;
  while (true) {
    int candidate_index =
        indices.get(compute_shuffled_index(i % indices.size(), indices.size(), seed));
    if (i % 32 == 0) {
      hash = Hash.sha2_256(Bytes.concatenate(seed, int_to_bytes(Math.floorDiv(i, 32), 8)));
    }
    int random_byte = UnsignedBytes.toInt(hash.get(i % 32));
    UnsignedLong effective_balance =
        state.getValidators().get(candidate_index).getEffective_balance();
    if (effective_balance
            .times(MAX_RANDOM_BYTE)
            .compareTo(
                UnsignedLong.valueOf(MAX_EFFECTIVE_BALANCE)
                    .times(UnsignedLong.valueOf(random_byte)))
        >= 0) {
      return candidate_index;
    }
    i++;
  }
}
 
Example #8
Source File: NetworkSet.java    From dhcp4j with Apache License 2.0 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 #9
Source File: RocksDBStore.java    From dremio-oss with Apache License 2.0 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 #10
Source File: GetChannelInfoResponse.java    From ipmi4j with Apache License 2.0 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);
    }
}
 
Example #11
Source File: AsfRsspSessionAuthentication.java    From ipmi4j with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Payload fromWire(@Nonnull ByteBuffer buffer) {
    if (!buffer.hasRemaining())
        return EndOfList.INSTANCE;

    byte type = buffer.get();
    AbstractWireable.assertWireByte(buffer, (byte) 0, "reserved byte");
    short length = buffer.getShort();
    byte[] data = new byte[length - 4];
    buffer.get(data);

    switch (buffer.get()) {
        case 0:
            return EndOfList.INSTANCE;
        case 1:
            return Code.fromByte(AuthenticationAlgorithm.class, data[0]);
        case 2:
            return Code.fromByte(IntegrityAlgorithm.class, data[0]);
        default:
            throw new IllegalArgumentException("Unknown algorithm type 0x" + UnsignedBytes.toString(type, 16));
    }
}
 
Example #12
Source File: Ipmi15SessionWrapper.java    From ipmi4j with Apache License 2.0 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 #13
Source File: ParsingTools.java    From mongowp with Apache License 2.0 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 #14
Source File: AbstractIpmiCommand.java    From ipmi4j with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * This implementation must be called with a buffer of exactly decodeable
 * length, as some packet types require consumption of "optional" or
 * "remaining" data without an auxiliary embedded length field.
 *
 * @see AbstractIpmiSessionWrapper#newPayload(ByteBuffer, IpmiPayloadType)
 */
@Override
protected void fromWireUnchecked(IpmiPacketContext context, ByteBuffer buffer) {
    int chk1Start = buffer.position();
    int tmp;
    targetAddress = buffer.get();
    tmp = UnsignedBytes.toInt(buffer.get());
    IpmiNetworkFunction networkFunction = Code.fromInt(IpmiNetworkFunction.class, (tmp >>> 2) & ~1);
    targetLun = Code.fromInt(IpmiLun.class, tmp & IpmiLun.MASK);
    fromWireChecksum(buffer, chk1Start, "IPMI header checksum");
    int chk2Start = buffer.position();
    sourceAddress = buffer.get();
    tmp = UnsignedBytes.toInt(buffer.get());
    sequenceNumber = (byte) ((tmp >>> 2) & SEQUENCE_NUMBER_MASK);
    sourceLun = Code.fromInt(IpmiLun.class, tmp & IpmiLun.MASK);
    IpmiCommandName commandName = IpmiCommandName.fromByte(networkFunction, buffer.get());
    buffer.limit(buffer.limit() - 1);   // Represent an accurate data length to the packet data decoder.
    fromWireData(buffer);
    buffer.limit(buffer.limit() + 1);   // And let us get the checksum out.
    fromWireChecksum(buffer, chk2Start, "IPMI data checksum");
}
 
Example #15
Source File: AddressUtilsTest.java    From dhcp4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdd() {
    testAdd(A(1, 2), A(0, 4), 0xFEL);
    testAdd(A(0, 0), A(UnsignedBytes.MAX_VALUE, UnsignedBytes.MAX_VALUE), 0x1L);

    Random r = new Random();
    for (int i = 0; i < 10; i++) {
        int len = r.nextInt(4) + 2;
        byte[] b = new byte[len];
        r.nextBytes(b);
        int value = r.nextInt(65532);
        byte[] s = C(b);
        for (int j = 0; j < value; j++)
            AddressUtils.increment(s);
        testAdd(s, b, value);
    }
}
 
Example #16
Source File: AbstractAsfData.java    From ipmi4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void toWireUnchecked(IpmiPacketContext context, ByteBuffer buffer) {
    buffer.putInt(IANA_ENTERPRISE_NUMBER.getNumber());
    buffer.put(getMessageType().getCode());
    buffer.put(getMessageTag());
    buffer.put((byte) 0);   // reserved
    buffer.put(UnsignedBytes.checkedCast(getDataWireLength()));
    toWireData(buffer);
}
 
Example #17
Source File: PacketChunker.java    From OpenModsLib with MIT License 5 votes vote down vote up
/***
 * Get the bytes from the packet. If the total packet is not yet complete
 * (and we're waiting for more to complete the sequence), we return null.
 * Otherwise we return the full byte array
 *
 * @param payload
 *            one of the chunks
 * @return the full byte array or null if not complete
 */
public synchronized byte[] consumeChunk(DataInput input, int payloadLength) throws IOException {
	int numChunks = UnsignedBytes.toInt(input.readByte());

	if (numChunks == 1) {
		byte[] payload = new byte[payloadLength - 1];
		input.readFully(payload);
		return payload;
	}

	int chunkIndex = UnsignedBytes.toInt(input.readByte());
	byte incomingPacketId = input.readByte();

	byte[][] alreadyReceived = chunks.get(incomingPacketId);

	if (alreadyReceived == null) {
		alreadyReceived = new byte[numChunks][];
		chunks.put(incomingPacketId, alreadyReceived);
	}

	byte[] chunkBytes = new byte[payloadLength - 3];
	input.readFully(chunkBytes);

	alreadyReceived[chunkIndex] = chunkBytes;

	for (byte[] s : alreadyReceived)
		if (s == null) return null; // not completed yet

	ByteArrayDataOutput fullPacket = ByteStreams.newDataOutput();

	for (short i = 0; i < numChunks; i++) {
		byte[] chunkPart = alreadyReceived[i];
		fullPacket.write(chunkPart);
	}

	chunks.remove(incomingPacketId);

	return fullPacket.toByteArray();
}
 
Example #18
Source File: IpmiRAKPMessage2.java    From ipmi4j with Apache License 2.0 5 votes vote down vote up
@Override
public void toStringBuilder(StringBuilder buf, int depth) {
    appendHeader(buf, depth, getClass().getSimpleName());
    depth++;
    appendValue(buf, depth, "MessageTag", "0x" + UnsignedBytes.toString(messageTag, 16));
    appendValue(buf, depth, "ConsoleSessionId", "0x" + Integer.toHexString(consoleSessionId));
    appendValue(buf, depth, "SystemRandom", toHexString(systemRandom));
    appendValue(buf, depth, "SystemGUID", systemGuid);
    appendValue(buf, depth, "KeyExchangeAuthenticationCode", toHexString(keyExchangeAuthenticationCode));
}
 
Example #19
Source File: ResourceString.java    From android-arscblamer with Apache License 2.0 5 votes vote down vote up
private static int decodeLengthUTF8(ByteBuffer buffer, int offset) {
  // UTF-8 strings use a clever variant of the 7-bit integer for packing the string length.
  // If the first byte is >= 0x80, then a second byte follows. For these values, the length
  // is WORD-length in big-endian & 0x7FFF.
  int length = UnsignedBytes.toInt(buffer.get(offset));
  if ((length & 0x80) != 0) {
    length = ((length & 0x7F) << 8) | UnsignedBytes.toInt(buffer.get(offset + 1));
  }
  return length;
}
 
Example #20
Source File: GetSDRRequest.java    From ipmi4j with Apache License 2.0 5 votes vote down vote up
@Override
public void toStringBuilder(StringBuilder buf, int depth) {
    super.toStringBuilder(buf, depth);
    appendValue(buf, depth, "ReservationId", "0x" + Integer.toHexString(reservationId));
    appendValue(buf, depth, "RecordId", "0x" + Integer.toHexString(recordId));
    appendValue(buf, depth, "RecordOffset", "0x" + UnsignedBytes.toString(recordOffset, 16));
    appendValue(buf, depth, "RecordLength", "0x" + UnsignedBytes.toString(recordLength, 16));
}
 
Example #21
Source File: BatchedRangeRead.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(final RangeReadInfo o1, final RangeReadInfo o2) {
  int comp = Double.compare(o1.startScore, o2.startScore);
  if (comp != 0) {
    return comp;
  }
  comp = Double.compare(o1.endScore, o2.endScore);
  if (comp != 0) {
    return comp;
  }
  final byte[] otherComp = o2.partitionKey == null ? new byte[0] : o2.partitionKey;
  final byte[] thisComp = o1.partitionKey == null ? new byte[0] : o1.partitionKey;

  return UnsignedBytes.lexicographicalComparator().compare(thisComp, otherComp);
}
 
Example #22
Source File: ForkChainProcess.java    From nuls with MIT License 5 votes vote down vote up
/**
 * 当两个高度一致的块hash不同时,排序统一选取前面一个hash为正确的
 */
private byte[] compareHashAndGetSmall(byte[] hash1, byte[] hash2) {
    Comparator<byte[]> comparator = UnsignedBytes.lexicographicalComparator();
    if (comparator.compare(hash1, hash2) <= 0) {
        return hash1;
    }
    return hash2;
}
 
Example #23
Source File: CancelOrderMap.java    From Qora with MIT License 5 votes vote down vote up
@Override
protected Map<byte[], Order> getMap(DB database) 
{
	//OPEN MAP
	return database.createTreeMap("cancelOrderOrphanData")
			.keySerializer(BTreeKeySerializer.BASIC)
			.valueSerializer(new OrderSerializer())
			.comparator(UnsignedBytes.lexicographicalComparator())
			.makeOrGet();
}
 
Example #24
Source File: OriginAttributeParser.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void parseAttribute(final ByteBuf buffer, final AttributesBuilder builder,
        final RevisedErrorHandling errorHandling, final PeerSpecificParserConstraint constraint)
                throws BGPDocumentedException, BGPTreatAsWithdrawException {
    final int readable = buffer.readableBytes();
    if (readable != 1) {
        throw errorHandling.reportError(BGPError.ATTR_LENGTH_ERROR,
            "ORIGIN attribute is expected to have size 1, but has %s", readable);
    }

    final byte rawOrigin = buffer.readByte();
    final BgpOrigin borigin = BgpOrigin.forValue(UnsignedBytes.toInt(rawOrigin));
    if (borigin == null) {
        throw errorHandling.reportError(BGPError.ORIGIN_ATTR_NOT_VALID, "Unknown ORIGIN type %s", rawOrigin);
    }
    switch (borigin) {
        case Egp:
            builder.setOrigin(EGP);
            return;
        case Igp:
            builder.setOrigin(IGP);
            return;
        case Incomplete:
            builder.setOrigin(INC);
            return;
        default:
    }
}
 
Example #25
Source File: Comparables.java    From tikv-client-lib-java with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(@Nonnull ComparableByteString other) {
  requireNonNull(other, "other is null");
  ByteString otherBytes = other.bytes;
  int n = Math.min(bytes.size(), otherBytes.size());
  for (int i = 0, j = 0; i < n; i++, j++) {
    int cmp = UnsignedBytes.compare(bytes.byteAt(i), otherBytes.byteAt(j));
    if (cmp != 0) return cmp;
  }
  // one is the prefix of other then the longer is larger
  return bytes.size() - otherBytes.size();
}
 
Example #26
Source File: KeyUtil.java    From antsdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static byte[] min(byte[] value1, byte[] value2) {
    if (value1 == null) {
        return value2;
    }
    else if (value2 == null) {
        return value1;
    }
    else {
        int result = UnsignedBytes.lexicographicalComparator().compare(value1, value2);
        return (result <= 0) ? value1 : value2;
    }
}
 
Example #27
Source File: IpmiRAKPMessage4.java    From ipmi4j with Apache License 2.0 5 votes vote down vote up
@Override
public void toStringBuilder(StringBuilder buf, int depth) {
    appendHeader(buf, depth, getClass().getSimpleName());
    depth++;
    appendValue(buf, depth, "MessageTag", "0x" + UnsignedBytes.toString(messageTag, 16));
    appendValue(buf, depth, "StatusCode", statusCode);
    appendValue(buf, depth, "ConsoleSessionId", "0x" + Integer.toHexString(consoleSessionId));
    appendValue(buf, depth, "IntegrityCheckValue", toHexString(integrityCheckValue));
}
 
Example #28
Source File: TransactionParentMap.java    From Qora with MIT License 5 votes vote down vote up
@Override
protected Map<byte[], byte[]> getMap(DB database) 
{
	//OPEN MAP
	return database.createTreeMap("children")
			.keySerializer(BTreeKeySerializer.BASIC)
			.comparator(UnsignedBytes.lexicographicalComparator())
			.makeOrGet();
}
 
Example #29
Source File: ApiLookup.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the API version required by the given class reference,
 * or -1 if this is not a known API class. Note that it may return -1
 * for classes introduced in version 1; internally the database only
 * stores version data for version 2 and up.
 *
 * @param className the internal name of the class, e.g. its
 *            fully qualified name (as returned by Class.getName(), but with
 *            '.' replaced by '/'.
 * @return the minimum API version the method is supported for, or -1 if
 *         it's unknown <b>or version 1</b>.
 */
public int getClassVersion(@NonNull String className) {
    if (!isRelevantClass(className)) {
        return -1;
    }

    if (mData != null) {
        int classNumber = findClass(className);
        if (classNumber != -1) {
            int offset = mIndices[classNumber];
            while (mData[offset] != 0) {
                offset++;
            }
            offset++;
            return UnsignedBytes.toInt(mData[offset]);
        }
    }  else {
       ApiClass clz = mInfo.getClass(className);
        if (clz != null) {
            int since = clz.getSince();
            if (since == Integer.MAX_VALUE) {
                since = -1;
            }
            return since;
        }
    }

    return -1;
}
 
Example #30
Source File: TestPrestoThriftId.java    From presto with Apache License 2.0 5 votes vote down vote up
private static byte[] bytes(int... values)
{
    int length = values.length;
    byte[] result = new byte[length];
    for (int i = 0; i < length; i++) {
        result[i] = UnsignedBytes.checkedCast(values[i]);
    }
    return result;
}