本文整理匯總了Java中com.google.common.primitives.Ints類的典型用法代碼示例。如果您正苦於以下問題:Java Ints類的具體用法?Java Ints怎麽用?Java Ints使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Ints類屬於com.google.common.primitives包,在下文中一共展示了Ints類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: provideExtractorForValue
import com.google.common.primitives.Ints; //導入依賴的package包/類
private <T> ValueExtractor provideExtractorForValue(Class<T> clazz, int target, List<String> chainOfProperties) {
Class<?> propertyClass = clazz;
List<Integer> indices = Lists.newArrayList();
for (String property : chainOfProperties) {
Field field;
try {
field = clazz.getDeclaredField(property);
} catch (NoSuchFieldException e) {
throw new InvalidQueryException(e);
}
PortableProperty portablePropertyAnnotation = field.getAnnotation(PortableProperty.class);
if (portablePropertyAnnotation == null) {
throw new InvalidQueryException("");
}
// TODO add support for customs codecs some day ;)
int index = portablePropertyAnnotation.value();
indices.add(index);
propertyClass = field.getDeclaringClass();
}
return new PofExtractor<>(propertyClass, new SimplePofPath(Ints.toArray(indices)), target);
}
示例2: generateKey
import com.google.common.primitives.Ints; //導入依賴的package包/類
/**
* Generate a key from the given data.
*
* @param attribute
* Attribute of the key to generate.
* @param id
* Id of the key to generate.
* @param version
* Version of the key to generate.
* @param length
* Length of the key to generate.
* @return Generated key.
*/
private static byte[] generateKey(byte[] masterSecret, String attribute, String id, int version, int length) {
ByteArrayOutputStream metadata = new ByteArrayOutputStream();
try {
if (attribute != null) {
metadata.write(Ints.toByteArray(attribute.length()));
metadata.write(attribute.getBytes(ENCODING_CHARSET));
}
metadata.write(Ints.toByteArray(version));
metadata.write(Ints.toByteArray(length));
} catch (IOException e) { /* won't be thrown */}
hkdf.init(new HKDFParameters(masterSecret, id.getBytes(ENCODING_CHARSET), metadata.toByteArray()));
byte[] key = new byte[length];
hkdf.generateBytes(key, 0, key.length);
return key;
}
示例3: setUp
import com.google.common.primitives.Ints; //導入依賴的package包/類
@BeforeExperiment void setUp() {
// random integers will be generated in this range, then raised to the
// power of (1/concentration) and floor()ed
max = Ints.checkedCast((long) Math.pow(distinctKeys, concentration));
cache = CacheBuilder.newBuilder()
.concurrencyLevel(segments)
.maximumSize(maximumSize)
.build(
new CacheLoader<Integer, Integer>() {
@Override public Integer load(Integer from) {
return (int) misses.incrementAndGet();
}
});
// To start, fill up the cache.
// Each miss both increments the counter and causes the map to grow by one,
// so until evictions begin, the size of the map is the greatest return
// value seen so far
while (cache.getUnchecked(nextRandomKey()) < maximumSize) {}
requests.set(0);
misses.set(0);
}
示例4: edges
import com.google.common.primitives.Ints; //導入依賴的package包/類
/**
* An implementation of {@link BaseGraph#edges()} defined in terms of {@link #nodes()} and {@link
* #successors(Object)}.
*/
@Override
public Set<EndpointPair<N>> edges() {
return new AbstractSet<EndpointPair<N>>() {
@Override
public UnmodifiableIterator<EndpointPair<N>> iterator() {
return EndpointPairIterator.of(AbstractBaseGraph.this);
}
@Override
public int size() {
return Ints.saturatedCast(edgeCount());
}
@Override
public boolean contains(@Nullable Object obj) {
if (!(obj instanceof EndpointPair)) {
return false;
}
EndpointPair<?> endpointPair = (EndpointPair<?>) obj;
return isDirected() == endpointPair.isOrdered()
&& nodes().contains(endpointPair.nodeU())
&& successors(endpointPair.nodeU()).contains(endpointPair.nodeV());
}
};
}
示例5: ApacheThriftMethodInvoker
import com.google.common.primitives.Ints; //導入依賴的package包/類
public ApacheThriftMethodInvoker(
ListeningExecutorService executorService,
ListeningScheduledExecutorService delayService,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory,
Duration connectTimeout,
Duration requestTimeout,
Optional<HostAndPort> socksProxy,
Optional<SSLContext> sslContext)
{
this.executorService = requireNonNull(executorService, "executorService is null");
this.delayService = requireNonNull(delayService, "delayService is null");
this.transportFactory = requireNonNull(transportFactory, "transportFactory is null");
this.protocolFactory = requireNonNull(protocolFactory, "protocolFactory is null");
this.connectTimeoutMillis = Ints.saturatedCast(requireNonNull(connectTimeout, "connectTimeout is null").toMillis());
this.requestTimeoutMillis = Ints.saturatedCast(requireNonNull(requestTimeout, "requestTimeout is null").toMillis());
this.socksProxy = requireNonNull(socksProxy, "socksProxy is null");
this.sslContext = requireNonNull(sslContext, "sslContext is null");
}
示例6: createReadOperation
import com.google.common.primitives.Ints; //導入依賴的package包/類
private Runnable createReadOperation(ChannelHandlerContext ctx, OperationParameters operationParameters) {
return () -> {
ByteBuf data = null;
int err = 0;
try {
//FIXME: use FUA/sync flag correctly
ByteBuffer bb = exportProvider.read(operationParameters.cmdOffset, Ints.checkedCast(operationParameters.cmdLength));
data = Unpooled.wrappedBuffer(bb);
checkReadLength(operationParameters, data);
} catch (Exception e) {
LOGGER.error("error during read", e);
err = Protocol.EIO_ERROR;
} finally {
sendTransmissionSimpleReply(ctx, err, operationParameters.cmdHandle, data);
}
};
}
示例7: size
import com.google.common.primitives.Ints; //導入依賴的package包/類
@Override
public int size() {
// racy single-check idiom
Integer result = size;
if (result == null) {
long total = 0;
for (Range<C> range : ranges) {
total += ContiguousSet.create(range, domain).size();
if (total >= Integer.MAX_VALUE) {
break;
}
}
result = size = Ints.saturatedCast(total);
}
return result.intValue();
}
示例8: toAddrString
import com.google.common.primitives.Ints; //導入依賴的package包/類
/**
* Returns the string representation of an {@link InetAddress}.
*
* <p>For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6
* addresses, the output follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a> section
* 4. The main difference is that this method uses "::" for zero compression, while Java's version
* uses the uncompressed form.
*
* <p>This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses
* such as "::c000:201". The output does not include a Scope ID.
*
* @param ip {@link InetAddress} to be converted to an address string
* @return {@code String} containing the text-formatted IP address
* @since 10.0
*/
public static String toAddrString(InetAddress ip) {
checkNotNull(ip);
if (ip instanceof Inet4Address) {
// For IPv4, Java's formatting is good enough.
return ip.getHostAddress();
}
checkArgument(ip instanceof Inet6Address);
byte[] bytes = ip.getAddress();
int[] hextets = new int[IPV6_PART_COUNT];
for (int i = 0; i < hextets.length; i++) {
hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]);
}
compressLongestRunOfZeroes(hextets);
return hextetsToIPv6String(hextets);
}
示例9: toArray
import com.google.common.primitives.Ints; //導入依賴的package包/類
@SuppressWarnings({"unchecked", "rawtypes"}) // NOTE: We assume the component type matches the list
private Object toArray(Class<?> componentType, List<Object> values) {
if (componentType == boolean.class) {
return Booleans.toArray((Collection) values);
} else if (componentType == byte.class) {
return Bytes.toArray((Collection) values);
} else if (componentType == short.class) {
return Shorts.toArray((Collection) values);
} else if (componentType == int.class) {
return Ints.toArray((Collection) values);
} else if (componentType == long.class) {
return Longs.toArray((Collection) values);
} else if (componentType == float.class) {
return Floats.toArray((Collection) values);
} else if (componentType == double.class) {
return Doubles.toArray((Collection) values);
} else if (componentType == char.class) {
return Chars.toArray((Collection) values);
}
return values.toArray((Object[]) Array.newInstance(componentType, values.size()));
}
示例10: getProtobufData
import com.google.common.primitives.Ints; //導入依賴的package包/類
public byte[] getProtobufData() {
byte[] envelopeData = getEnvelope().toByteArray();
byte[] payloadData = getPayload().toByteArray();
int size = envelopeData.length + payloadData.length + 8;
byte[] retval = new byte[size];
int offset = 0;
System.arraycopy(Ints.toByteArray(envelopeData.length), 0, retval, offset, 4);
offset += 4;
System.arraycopy(envelopeData, 0, retval, offset, envelopeData.length);
offset += envelopeData.length;
System.arraycopy(Ints.toByteArray(payloadData.length), 0, retval, offset, 4);
offset += 4;
System.arraycopy(payloadData, 0, retval, offset, payloadData.length);
return retval;
}
示例11: readRpcBody
import com.google.common.primitives.Ints; //導入依賴的package包/類
private Message readRpcBody(ServletInputStream in,
Class<? extends Message> requestClass) throws Exception {
byte chunkSize[] = new byte[4];
in.read(chunkSize);
int size = Ints.fromByteArray(chunkSize);
if (size == 0) {
return ProtobufUtil.newEmptyMessage(requestClass);
}
if (size > ProtobufUtil.MAX_BODY_CHUNK_SIZE) {
String message = "Invalid body chunk size: " + size;
throw new RpcReadException(chunkSize, in, message);
}
byte bodyData[] = readyFully(in, size);
Message pbRequest = ProtobufUtil.byteArrayToProtobuf(bodyData, requestClass);
return pbRequest;
}
示例12: reBuffer
import com.google.common.primitives.Ints; //導入依賴的package包/類
@Override
protected void reBuffer() throws IOException
{
if (offset - mem.peer >= mem.size())
return;
buffer = getByteBuffer(offset, Math.min(bufferSize, Ints.saturatedCast(memRemaining())));
offset += buffer.capacity();
}
示例13: read
import com.google.common.primitives.Ints; //導入依賴的package包/類
@Override
public ByteBuffer read(final long offset, final int length) throws IOException {
read.mark(length);
final ByteBuffer origMessage = ByteBuffer.allocate(length);
for (Integer bucketIndex : getBuckets(offset, length)) { //eventually make parallel
Bucket bucket = getBucketFromIndex(bucketIndex);
final long absoluteOffsetForThisBucket = Math.max(offset, bucket.getBaseOffset());
final int lengthForBucket = Ints.checkedCast(Math.min(bucket.getUpperBound() + 1, offset + length) - absoluteOffsetForThisBucket); //todo this threw an exception
final int dataOffset = Ints.checkedCast(Math.max(0, bucket.getBaseOffset() - offset));
final ByteBuffer pseudoCopy = bufferForBucket(origMessage, lengthForBucket, dataOffset);
bucket.getBytes(pseudoCopy, absoluteOffsetForThisBucket, lengthForBucket);
}
return origMessage;
}
示例14: getElement
import com.google.common.primitives.Ints; //導入依賴的package包/類
long getElement(long idx) {
long elt = 0;
long bitpos = ELEMENT_BITS * idx;
int tabpos = Ints.checkedCast(bitpos / 64);
long slotpos = bitpos % 64;
long spillbits = (slotpos + ELEMENT_BITS) - 64;
elt = (table[tabpos] >>> slotpos) & ELEMENT_MASK;
if (spillbits > 0) {
++tabpos;
long x = table[tabpos] & LOW_MASK(spillbits);
elt |= x << (ELEMENT_BITS - spillbits);
}
return elt;
}
示例15: testPercentiles_indexes_varargsAll_computeInPlace
import com.google.common.primitives.Ints; //導入依賴的package包/類
public void testPercentiles_indexes_varargsAll_computeInPlace() {
double[] dataset = Doubles.toArray(PSEUDORANDOM_DATASET);
List<Integer> indexes = new ArrayList<Integer>();
ImmutableMap.Builder<Integer, Double> expectedBuilder = ImmutableMap.builder();
for (int index = 0; index <= 100; index++) {
indexes.add(index);
expectedBuilder.put(index, expectedLargeDatasetPercentile(index));
}
Random random = new Random(770683168895677741L);
Collections.shuffle(indexes, random);
assertQuantilesMap(expectedBuilder.build(),
percentiles().indexes(Ints.toArray(indexes)).computeInPlace(dataset));
assertDatasetAnyOrder(PSEUDORANDOM_DATASET, dataset);
}