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

The following are top voted examples for showing how to use com.google.common.primitives.Ints. 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: coherence-sql   File: PofExtractorFactory.java   View source code 7 votes vote down vote up
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);
}
 
Example 2
Project: PACE   File: GenerateEncryptionKeys.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Project: googles-monorepo-demo   File: LoadingCacheSingleThreadBenchmark.java   View source code 6 votes vote down vote up
@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);
}
 
Example 4
Project: googles-monorepo-demo   File: AbstractBaseGraph.java   View source code 6 votes vote down vote up
/**
 * 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());
    }
  };
}
 
Example 5
Project: drift   File: ApacheThriftMethodInvoker.java   View source code 6 votes vote down vote up
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");
}
 
Example 6
Project: tools   File: TransmissionPhase.java   View source code 6 votes vote down vote up
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);
        }
    };
}
 
Example 7
Project: googles-monorepo-demo   File: ImmutableRangeSet.java   View source code 6 votes vote down vote up
@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();
}
 
Example 8
Project: guava-mock   File: InetAddresses.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 9
Project: ArchUnit   File: JavaClassProcessor.java   View source code 6 votes vote down vote up
@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()));
}
 
Example 10
Project: ja-micro   File: ProtobufRpcRequest.java   View source code 6 votes vote down vote up
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;
}
 
Example 11
Project: ja-micro   File: ProtobufHandler.java   View source code 6 votes vote down vote up
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;
}
 
Example 12
Project: sstable-adaptor   File: MemoryInputStream.java   View source code 5 votes vote down vote up
@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();
}
 
Example 13
Project: tools   File: MineboxExport.java   View source code 5 votes vote down vote up
@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;
}
 
Example 14
Project: AppCoins-ethereumj   File: QuotientFilter.java   View source code 5 votes vote down vote up
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;
}
 
Example 15
Project: googles-monorepo-demo   File: QuantilesTest.java   View source code 5 votes vote down vote up
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);
}
 
Example 16
Project: googles-monorepo-demo   File: QuantilesTest.java   View source code 5 votes vote down vote up
public void testPercentiles_indexes_varargsAll_compute_doubleCollection() {
  ArrayList<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)).compute(PSEUDORANDOM_DATASET));
}
 
Example 17
Project: minebox   File: MineboxExport.java   View source code 5 votes vote down vote up
private void writeDataToBucket(Bucket bucket, long offset, int length, ByteBuffer origMessage) throws IOException {
        final long start = Math.max(offset, bucket.getBaseOffset());
        final int lengthForBucket = Ints.checkedCast(Math.min(bucket.getUpperBound() + 1, offset + length) - start);
        final int dataOffset = Ints.checkedCast(Math.max(0, bucket.getBaseOffset() - offset));
        final ByteBuffer pseudoCopy = bufferForBucket(origMessage, lengthForBucket, dataOffset);
        final long writtenBytes = bucket.putBytes(start, pseudoCopy);
//        logger.debug("wrote {} bytes to bucket {}", writtenBytes, bucket.bucketIndex);
    }
 
Example 18
Project: googles-monorepo-demo   File: Iterators.java   View source code 5 votes vote down vote up
/**
 * Returns the number of elements remaining in {@code iterator}. The iterator
 * will be left exhausted: its {@code hasNext()} method will return
 * {@code false}.
 */
public static int size(Iterator<?> iterator) {
  long count = 0L;
  while (iterator.hasNext()) {
    iterator.next();
    count++;
  }
  return Ints.saturatedCast(count);
}
 
Example 19
Project: Thermionics   File: HeatStorage.java   View source code 5 votes vote down vote up
@Override
public int receiveHeat(int amount, boolean simulate) {
	int toReceive = Ints.min(amount, max-cur, maxReceive);
	if (toReceive<minReceive) toReceive = 0;
	if (!simulate) {
		cur += toReceive;
		markDirty();
	}
	
	return toReceive;
}
 
Example 20
Project: hadoop-oss   File: MiniZKFCCluster.java   View source code 5 votes vote down vote up
/**
 * Expire the ZK session of the given service. This requires
 * (and asserts) that the given service be the current active.
 * @throws NoNodeException if no service holds the lock
 */
public void expireActiveLockHolder(int idx)
    throws NoNodeException {
  Stat stat = new Stat();
  byte[] data = zks.getZKDatabase().getData(
      DummyZKFC.LOCK_ZNODE, stat, null);
  
  assertArrayEquals(Ints.toByteArray(svcs.get(idx).index), data);
  long session = stat.getEphemeralOwner();
  LOG.info("Expiring svc " + idx + "'s zookeeper session " + session);
  zks.closeSession(session);
}
 
Example 21
Project: hadoop-oss   File: MiniZKFCCluster.java   View source code 5 votes vote down vote up
/**
 * Wait for the given HA service to become the active lock holder.
 * If the passed svc is null, waits for there to be no active
 * lock holder.
 */
public void waitForActiveLockHolder(Integer idx)
    throws Exception {
  DummyHAService svc = idx == null ? null : svcs.get(idx);
  ActiveStandbyElectorTestUtil.waitForActiveLockData(ctx, zks,
      DummyZKFC.SCOPED_PARENT_ZNODE,
      (idx == null) ? null : Ints.toByteArray(svc.index));
}
 
Example 22
Project: andbg   File: BaseAnnotation.java   View source code 5 votes vote down vote up
@Override
public int compareTo(Annotation o) {
    int res = Ints.compare(getVisibility(), o.getVisibility());
    if (res != 0) return res;
    res = getType().compareTo(o.getType());
    if (res != 0) return res;
    return CollectionUtils.compareAsSet(getElements(), o.getElements());
}
 
Example 23
Project: ProjectAres   File: RaindropListener.java   View source code 5 votes vote down vote up
private int calculateRaindrops(MatchPlayerState player, int count, boolean scaled, double percent) {
    if(scaled) {
        final Match match = player.getMatch();
        count += (int) ((double) match.getParticipatingPlayers().size() / match.getMaxPlayers() * RaindropConstants.MATCH_FULLNESS_BONUS);

        if(player.getParty() instanceof Team) {
            count += Ints.min((int) (Math.sqrt(((Team) player.getParty()).getCumulativeParticipation(player.getPlayerId()).getSeconds()) / RaindropConstants.PLAY_TIME_BONUS), RaindropConstants.PLAY_TIME_BONUS_CUTOFF);
        }
    }

    return RaindropUtil.calculateRaindrops(player.getPlayerId(), (int) (count * percent), true);
}
 
Example 24
Project: googles-monorepo-demo   File: MapMakerInternalMap.java   View source code 5 votes vote down vote up
@Override
public int size() {
  Segment<K, V, E, S>[] segments = this.segments;
  long sum = 0;
  for (int i = 0; i < segments.length; ++i) {
    sum += segments[i].count;
  }
  return Ints.saturatedCast(sum);
}
 
Example 25
Project: talchain   File: QuotientFilter.java   View source code 5 votes vote down vote up
void setElement(long idx, long elt) {
    long bitpos = ELEMENT_BITS * idx;
    int tabpos = Ints.checkedCast(bitpos / 64);
    long slotpos = bitpos % 64;
    long spillbits = (slotpos + ELEMENT_BITS) - 64;
    elt &= ELEMENT_MASK;
    table[tabpos] &= ~(ELEMENT_MASK << slotpos);
    table[tabpos] |= elt << slotpos;
    if (spillbits > 0) {
        ++tabpos;
        table[tabpos] &= ~LOW_MASK(spillbits);
        table[tabpos] |= elt >>> (ELEMENT_BITS - spillbits);
    }
}
 
Example 26
Project: googles-monorepo-demo   File: Lists.java   View source code 5 votes vote down vote up
@VisibleForTesting
static int computeArrayListCapacity(int arraySize) {
  checkNonnegative(arraySize, "arraySize");

  // TODO(kevinb): Figure out the right behavior, and document it
  return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
}
 
Example 27
Project: drift   File: ApacheThriftMethodInvoker.java   View source code 5 votes vote down vote up
private void setSocketProperties(Socket socket)
        throws SocketException
{
    socket.setSoLinger(false, 0);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    socket.setSoTimeout(Ints.saturatedCast(requestTimeoutMillis));
}
 
Example 28
Project: ios-device-control   File: BinaryPlistSocketTest.java   View source code 5 votes vote down vote up
@Test
public void testReceiveMessage() throws IOException {
  NSDictionary inputMessage = new NSDictionary();
  inputMessage.put("goodbye", "world");
  byte[] messageBytes = BinaryPropertyListWriter.writeToArray(inputMessage);
  byte[] lengthBytes = Ints.toByteArray(messageBytes.length);
  byte[] inputBytes = new byte[messageBytes.length + 4];
  System.arraycopy(lengthBytes, 0, inputBytes, 0, 4);
  System.arraycopy(messageBytes, 0, inputBytes, 4, messageBytes.length);

  FakeSocket fakeSocket = new FakeSocket(inputBytes);
  try (InspectorSocket socket = new BinaryPlistSocket(fakeSocket)) {
    assertThat(socket.receiveMessage().get()).isEqualTo(inputMessage);
  }
}
 
Example 29
Project: hue   File: CostMatrix.java   View source code 5 votes vote down vote up
public void sortForDimensions(){
	sortKeys.sort((vn1,vn2) -> {
		int res =0;

		if(hints  != null){
			res = -1*Ints.compare(getRowHintCount(vn1), getRowHintCount(vn2));
		}

		if(res==0){
			res = -1*Ints.compare(getRowDimCount(vn1), getRowDimCount(vn2));
		}
		
		if(res==0){
			if(getRootSelectionCount(vn1)==0)
				res = 1;
			
			if(getRootSelectionCount(vn2)==0 && res==0)
				res = -1;
		}
		
		if(res==0){
			TableType vn1_type = vn1.getTableType();
			TableType vn2_type = vn2.getTableType();
			if(vn1_type == TableType.DIMENSION && vn2_type != TableType.DIMENSION){
				res = -1;
			}else if(vn1_type != TableType.DIMENSION && vn2_type == TableType.DIMENSION){
				res = 1;
			}
		}

		if(res==0)
			res = Double.compare(getRowCost(vn1), getRowCost(vn2));

		return res;
	});
}
 
Example 30
Project: tools   File: SingleFileBucket.java   View source code 5 votes vote down vote up
@Override
public void trim(long offset, long length) throws IOException {
    final long offsetInThisBucket = offsetInThisBucket(offset);
    final long lengthInThisBucket = calcLengthInThisBucket(offsetInThisBucket, length); //should be always equal to length since it is normalized in MineboxEport
    final FileChannel channel = getOpenChannel();
    final long fileSize = channel.size();
    if (fileSize == 0 || offsetInThisBucket >= fileSize) {
        //if the file is empty, there is nothing to trim
    } else if (lengthInThisBucket == this.bucketSize) {
        if (fileSize > 0)
        //if we are trimming the whole bucket we can truncate to 0
        {
            synchronized (this) {
                channel.truncate(0);
                channel.force(true);
            }
            needsFlush = true;
        }
    } else if (offsetInThisBucket == 0 && lengthInThisBucket >= fileSize) {
        //we are trimming the whole file, so we can truncate it.
        synchronized (this) {
            channel.truncate(0);
            channel.force(true);
        }
        needsFlush = true;
    } else if (offsetInThisBucket + lengthInThisBucket == this.bucketSize) {
        //truncating from index until end, we can shorten the file now
        synchronized (this) {
            channel.truncate(offsetInThisBucket);
            channel.force(false); //since we assume the un-truncated file was actually backed up, we don't care if this shortened file is not the one uploaded, since truncate is a "best effort" operations btrfs should tolerate those data being non-zero
        }
        needsFlush = true;
    } else {
        final int intLen = Ints.checkedCast(length); //buckets can not be bigger than 2GB right now, could be fixed
        final ByteBuffer bb = ByteBuffer.allocate(intLen);
        bb.put(new byte[intLen]);
        bb.flip();
        putBytesInternal(offset, bb, false); //sadly, this will encrypt zeroes. we need a workaround
    }
}
 
Example 31
Project: googles-monorepo-demo   File: ConcurrentHashMultisetBasherTest.java   View source code 5 votes vote down vote up
private void testAddAndRemove(ConcurrentMap<String, AtomicInteger> map)
    throws ExecutionException, InterruptedException {

  final ConcurrentHashMultiset<String> multiset = new ConcurrentHashMultiset<String>(map);
  int nThreads = 20;
  int tasksPerThread = 10;
  int nTasks = nThreads * tasksPerThread;
  ExecutorService pool = Executors.newFixedThreadPool(nThreads);
  ImmutableList<String> keys = ImmutableList.of("a", "b", "c");
  try {
    List<Future<int[]>> futures = Lists.newArrayListWithExpectedSize(nTasks);
    for (int i = 0; i < nTasks; i++) {
      futures.add(pool.submit(new MutateTask(multiset, keys)));
    }

    int[] deltas = new int[3];
    for (Future<int[]> future : futures) {
      int[] taskDeltas = future.get();
      for (int i = 0; i < deltas.length; i++) {
        deltas[i] += taskDeltas[i];
      }
    }

    List<Integer> actualCounts = Lists.transform(keys,
        new Function<String, Integer>() {
          @Override public Integer apply(String key) {
            return multiset.count(key);
          }
        });
    assertEquals("Counts not as expected", Ints.asList(deltas), actualCounts);
  } finally {
    pool.shutdownNow();
  }

  // Since we have access to the backing map, verify that there are no zeroes in the map
  for (AtomicInteger value : map.values()) {
    assertTrue("map should not contain a zero", value.get() != 0);
  }
}
 
Example 32
Project: guava-mock   File: Multisets.java   View source code 5 votes vote down vote up
/**
 * An implementation of {@link Multiset#size}.
 */
static int sizeImpl(Multiset<?> multiset) {
  long size = 0;
  for (Entry<?> entry : multiset.entrySet()) {
    size += entry.getCount();
  }
  return Ints.saturatedCast(size);
}
 
Example 33
Project: andbg   File: CollectionUtils.java   View source code 5 votes vote down vote up
public static <T extends Comparable<? super T>> int compareAsList(@Nonnull Collection<? extends T> list1,
                                                                  @Nonnull Collection<? extends T> list2) {
    int res = Ints.compare(list1.size(), list2.size());
    if (res != 0) return res;
    Iterator<? extends T> elements2 = list2.iterator();
    for (T element1: list1) {
        res = element1.compareTo(elements2.next());
        if (res != 0) return res;
    }
    return 0;
}
 
Example 34
Project: guava-mock   File: ConcurrentHashMultiset.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <p>If the data in the multiset is modified by any other threads during this method,
 * it is undefined which (if any) of these modifications will be reflected in the result.
 */
@Override
public int size() {
  long sum = 0L;
  for (AtomicInteger value : countMap.values()) {
    sum += value.get();
  }
  return Ints.saturatedCast(sum);
}
 
Example 35
Project: Vanilla-Injection   File: InjectionConnection.java   View source code 5 votes vote down vote up
/**
 * Load the value of {@link #structureId} from {@link #dataFile}.
 *
 * @return the value for {@link #structureId}
 * @throws IOException if an I/O error occurs while reading {@link #dataFile}
 */
private int loadStructureId() throws IOException {
  ByteBuffer buffer = ByteBuffer.allocate(Ints.checkedCast(dataFileChannel.size()));
  dataFileChannel.read(buffer);
  String fileContent = new String(buffer.array(), Charsets.UTF_8);
  return Integers.parseInt(fileContent);
}
 
Example 36
Project: guava-mock   File: Maps.java   View source code 5 votes vote down vote up
/**
 * Returns a capacity that is sufficient to keep the map from being resized as long as it grows no
 * larger than expectedSize and the load factor is ≥ its default (0.75).
 */
static int capacity(int expectedSize) {
  if (expectedSize < 3) {
    checkNonnegative(expectedSize, "expectedSize");
    return expectedSize + 1;
  }
  if (expectedSize < Ints.MAX_POWER_OF_TWO) {
    // This is the calculation used in JDK8 to resize when a putAll
    // happens; it seems to be the most conservative calculation we
    // can make.  0.75 is the default load factor.
    return (int) ((float) expectedSize / 0.75F + 1.0F);
  }
  return Integer.MAX_VALUE; // any large value
}
 
Example 37
Project: ios-device-control   File: BinaryPlistSocket.java   View source code 5 votes vote down vote up
@Override
public void sendMessage(NSDictionary message) throws IOException {
  byte[] messageBytes = BinaryPropertyListWriter.writeToArray(message);
  byte[] lengthBytes = Ints.toByteArray(messageBytes.length);
  socketOut.write(lengthBytes);
  socketOut.write(messageBytes);
}
 
Example 38
Project: guava-mock   File: Murmur3_32HashFunction.java   View source code 5 votes vote down vote up
@Override
public HashCode hashInt(int input) {
  int k1 = mixK1(input);
  int h1 = mixH1(seed, k1);

  return fmix(h1, Ints.BYTES);
}
 
Example 39
Project: googles-monorepo-demo   File: BloomFilterTest.java   View source code 5 votes vote down vote up
@AndroidIncompatible // slow
public void testBitSize() {
  double fpp = 0.03;
  for (int i = 1; i < 10000; i++) {
    long numBits = BloomFilter.optimalNumOfBits(i, fpp);
    int arraySize = Ints.checkedCast(LongMath.divide(numBits, 64, RoundingMode.CEILING));
    assertEquals(
        arraySize * Long.SIZE,
        BloomFilter.create(Funnels.unencodedCharsFunnel(), i, fpp).bitSize());
  }
}
 
Example 40
Project: azure-libraries-for-java   File: Utils.java   View source code 5 votes vote down vote up
/**
 * Converts an object Long to a primitive int.
 *
 * @param value the <tt>Long</tt> value
 * @return <tt>0</tt> if the given Long value is null else <tt>integer value</tt>
 */
public static int toPrimitiveInt(Long value) {
    if (value == null) {
        return 0;
    }
    // throws IllegalArgumentException - if value is greater than Integer.MAX_VALUE
    // or less than Integer.MIN_VALUE
    return Ints.checkedCast(value);
}