下面列出了javax.annotation.Nonnegative#com.google.common.primitives.UnsignedBytes 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
}
@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);
}
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));
}
}
}
}
@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));
}
}
/**
* 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++;
}
}
@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]);
}
}
/**
* {@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");
}
/** 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;
}
@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();
}
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));
}
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();
}
@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);
}
}
@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);
}
}
/**
* 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);
}
}
/** 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);
}
/**
* Performs an arbitrary-precision decrement of a byte array.
*
* @param in The array to decrement.
* @return The same input array.
*/
@Nonnull
public static byte[] decrement(@Nonnull byte[] in) {
for (int i = in.length - 1; i >= 0; i--) {
if (UnsignedBytes.toInt(in[i]) > 0) {
in[i]--;
break;
}
in[i] = UnsignedBytes.MAX_VALUE;
}
return in;
}
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;
}
private static Slice sliceFromBytes(int... bytes)
{
byte[] buffer = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
buffer[i] = UnsignedBytes.checkedCast(bytes[i]);
}
return Slices.wrappedBuffer(buffer);
}
@Override
protected void toWireData(ByteBuffer buffer) {
if (toWireCompletionCode(buffer)) // 1
return;
buffer.put(deviceId); // 2
buffer.put(setBit((byte) (deviceRevision & 0xF), 7, deviceProvidesDeviceSDRs)); // 3
buffer.put(setBit((byte) (deviceFirmwareRevisionMajor & 0x7F), 7, deviceAvailable)); // 4
buffer.put(toWireBcdLE(UnsignedBytes.checkedCast(deviceFirmwareRevisionMinor))); // 5
buffer.put(toWireBcdLE(UnsignedBytes.checkedCast(deviceIpmiRevision))); // 6
buffer.put(Bits.toByte(deviceSupport)); // 7
toWireOemIanaLE3(buffer, oemEnterpriseNumber); // 8:10
toWireCharLE(buffer, productId);
if (auxiliaryFirmwareRevisionInformation != null)
buffer.putInt(auxiliaryFirmwareRevisionInformation);
}
/**
* Creates a Uint8Array value from a Uint8Array, Buffer, string or hex input.
* `null` ior `undefined` nputs returns a `[]` result, Uint8Array values returns the value, hex strings returns a Uint8Array representation.
* **example**
*
* ```java
* u8aToU8a(new Uint8Array([0x12, 0x34]); // => Uint8Array([0x12, 0x34])
* u8aToU8a(0x1234); // => Uint8Array([0x12, 0x34])
* ```
*/
//export default function u8aToU8a (value?: Array<number> | Buffer | Uint8Array | string | null): Uint8Array {
public static byte[] u8aToU8a(Object value) {
if (value == null) {
return new byte[0];
}
//if (isBuffer(value)) {
// return bufferToU8a(value);
//}
if (value instanceof String) {
String strValue = (String) value;
return isHex(strValue)
? hexToU8a(strValue)
: stringToU8a(strValue);
}
if (value instanceof byte[]) {
return (byte[]) value;
}
if (value instanceof U8a) {
return ((U8a) value).raw;
}
if (value.getClass().isArray()) {
List<Object> objects = CodecUtils.arrayLikeToList(value);
byte[] result = new byte[objects.size()];
for (int i = 0; i < objects.size(); i++) {
Number number = (Number) objects.get(i);
result[i] = UnsignedBytes.parseUnsignedByte(number.toString());
}
return result;
}
return (byte[]) value;
}
@Override
@OverridingMethodsMustInvokeSuper
public void toStringBuilder(StringBuilder buf, int depth) {
appendHeader(buf, depth, "IpmiHeader");
depth++;
appendValue(buf, depth, "IpmiPayloadType", getPayloadType());
appendValue(buf, depth, "IpmiCommand", getCommandName());
appendValue(buf, depth, "SourceAddress", "0x" + UnsignedBytes.toString(getSourceAddress(), 16));
appendValue(buf, depth, "SourceLun", getSourceLun());
appendValue(buf, depth, "TargetAddress", "0x" + UnsignedBytes.toString(getTargetAddress(), 16));
appendValue(buf, depth, "TargetLun", getTargetLun());
appendValue(buf, depth, "SequenceNumber", getSequenceNumber());
}
/**
* As {@link #compare(TInstance,ValueSource,TInstance,ValueSource)} with
* {@code null} expected to be handled already.
*/
protected int doCompare(TInstance typeA, ValueSource sourceA, TInstance typeB, ValueSource sourceB) {
if (sourceA.hasCacheValue() && sourceB.hasCacheValue()) {
Object objectA = sourceA.getObject();
if (objectA instanceof Comparable<?>) {
// assume objectA and objectB are of the same class. If it's comparable, use that
@SuppressWarnings("unchecked")
Comparable<Object> comparableA = (Comparable<Object>) objectA;
return comparableA.compareTo(sourceB.getObject());
}
}
switch (TInstance.underlyingType(typeA)) {
case BOOL:
return Boolean.compare(sourceA.getBoolean(), sourceB.getBoolean());
case INT_8:
return Integer.compare(sourceA.getInt8(), sourceB.getInt8());
case INT_16:
return Integer.compare(sourceA.getInt16(), sourceB.getInt16());
case UINT_16:
return Integer.compare(sourceA.getUInt16(), sourceB.getUInt16());
case INT_32:
return Integer.compare(sourceA.getInt32(), sourceB.getInt32());
case INT_64:
return Long.compare(sourceA.getInt64(), sourceB.getInt64());
case FLOAT:
return Float.compare(sourceA.getFloat(), sourceB.getFloat());
case DOUBLE:
return Double.compare(sourceA.getDouble(), sourceB.getDouble());
case BYTES:
return UnsignedBytes.lexicographicalComparator().compare(sourceA.getBytes(), sourceB.getBytes());
case STRING:
// Remember: TString overrides and handles collator
return sourceA.getString().compareTo(sourceB.getString());
default:
throw new AssertionError(sourceA.getType());
}
}
/**
* Creates redeem script with given public keys and threshold. Given public keys will be placed in
* redeem script in the lexicographical sorting order.
*/
public static Script createRedeemScript(int threshold, List<byte[]> pubkeys) {
pubkeys = new ArrayList<byte[]>(pubkeys);
final Comparator comparator = UnsignedBytes.lexicographicalComparator();
Collections.sort(pubkeys, new Comparator<byte[]>() {
@Override
public int compare(byte[] k1, byte[] k2) {
return comparator.compare(k1, k2);
}
});
return ScriptBuilder.createMultiSigOutputScript(threshold, pubkeys);
}
public TransactionDatabase(TransactionDatabase parent)
{
this.parent = parent;
//OPEN MAP
this.transactionMap = new TreeMap<byte[], byte[]>(UnsignedBytes.lexicographicalComparator());
}
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;
}
@Override
protected void fromWireData(ByteBuffer buffer) {
if (fromWireCompletionCode(buffer))
return;
int tmp = UnsignedBytes.toInt(buffer.get());
presentRevision = (tmp >> 4) & 0xF;
lastCompatibleRevision = (tmp >> 4) & 0xF;
parameterData = readBytes(buffer, buffer.remaining());
}
protected TypeChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
id = UnsignedBytes.toInt(buffer.get());
buffer.position(buffer.position() + 3); // Skip 3 bytes for packing
entryCount = buffer.getInt();
entriesStart = buffer.getInt();
configuration = ResourceConfiguration.create(buffer);
}
/**
* 当两个高度一致的块hash不同时,排序统一选取前面一个hash为正确的
*/
private byte[] compareHashAndGetSmall(byte[] hash1, byte[] hash2) {
Comparator<byte[]> comparator = UnsignedBytes.lexicographicalComparator();
if (comparator.compare(hash1, hash2) <= 0) {
return hash1;
}
return hash2;
}
/**
* 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;
}
@Override
protected Map<byte[], byte[]> getMap(DB database)
{
//OPEN MAP
return database.createTreeMap("children")
.keySerializer(BTreeKeySerializer.BASIC)
.comparator(UnsignedBytes.lexicographicalComparator())
.makeOrGet();
}