com.google.common.math.LongMath Java Examples
The following examples show how to use
com.google.common.math.LongMath.
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: AddressRangeAddressBookEntry.java From batfish with Apache License 2.0 | 6 votes |
/** * Converts a range of {@link Ip} addresses to a minimal set of {@link Prefix prefixes} that * exactly cover the range. */ @VisibleForTesting static SortedSet<IpWildcard> rangeToWildcards(Ip low, Ip high) { checkArgument(low.valid(), "Illegal range: %s is not a valid IP", low); checkArgument(high.valid(), "Illegal range: %s is not a valid IP", high); checkArgument(low.compareTo(high) <= 0, "Illegal range: %s is larger than %s", low, high); long lo = low.asLong(); long hi = high.asLong(); ImmutableSortedSet.Builder<IpWildcard> ret = ImmutableSortedSet.naturalOrder(); long start = lo; while (start <= hi) { long numIps = hi - start + 1; int minPrefixLengthThatStartsAtStart = 32 - Math.min(Long.numberOfTrailingZeros(start), 32); int minPrefixLengthContainedInRange = 32 - LongMath.log2(numIps, RoundingMode.DOWN); int prefixLengthToUse = Math.max(minPrefixLengthThatStartsAtStart, minPrefixLengthContainedInRange); ret.add(IpWildcard.create(Prefix.create(Ip.create(start), prefixLengthToUse))); start += 1L << (32 - prefixLengthToUse); } return ret.build(); }
Example #2
Source File: MemoryBenchmark.java From caffeine with Apache License 2.0 | 6 votes |
private String[] evaluate(String label, Map<Integer, Integer> map) { long base = meter.measureDeep(map); map.putAll(workingSet); long populated = meter.measureDeep(map); long entryOverhead = 2 * FUZZY_SIZE * meter.measureDeep(workingSet.keySet().iterator().next()); long perEntry = LongMath.divide(populated - entryOverhead - base, FUZZY_SIZE, RoundingMode.HALF_EVEN); perEntry += ((perEntry & 1) == 0) ? 0 : 1; long aligned = ((perEntry % 8) == 0) ? perEntry : ((1 + perEntry / 8) * 8); return new String[] { label, String.format("%,d bytes", base), String.format("%,d bytes (%,d aligned)", perEntry, aligned) }; }
Example #3
Source File: SmoothRateLimiter.java From kite with Apache License 2.0 | 6 votes |
@Override final long reserveEarliestAvailable(int requiredPermits, long nowMicros) { resync(nowMicros); long returnValue = nextFreeTicketMicros; double storedPermitsToSpend = min(requiredPermits, this.storedPermits); double freshPermits = requiredPermits - storedPermitsToSpend; long waitMicros = storedPermitsToWaitTime(this.storedPermits, storedPermitsToSpend) + (long) (freshPermits * stableIntervalMicros); try { this.nextFreeTicketMicros = LongMath.checkedAdd(nextFreeTicketMicros, waitMicros); } catch (ArithmeticException e) { this.nextFreeTicketMicros = Long.MAX_VALUE; } this.storedPermits -= storedPermitsToSpend; return returnValue; }
Example #4
Source File: SequenceUtil.java From phoenix with Apache License 2.0 | 6 votes |
/** * @return true if we limit of a sequence has been reached. */ public static boolean checkIfLimitReached(long currentValue, long minValue, long maxValue, long incrementBy, long cacheSize, long numToAllocate) { long nextValue = 0; boolean increasingSeq = incrementBy > 0 ? true : false; // advance currentValue while checking for overflow try { long incrementValue; if (isBulkAllocation(numToAllocate)) { // For bulk allocation we increment independent of cache size incrementValue = LongMath.checkedMultiply(incrementBy, numToAllocate); } else { incrementValue = LongMath.checkedMultiply(incrementBy, cacheSize); } nextValue = LongMath.checkedAdd(currentValue, incrementValue); } catch (ArithmeticException e) { return true; } // check if limit was reached if ((increasingSeq && nextValue > maxValue) || (!increasingSeq && nextValue < minValue)) { return true; } return false; }
Example #5
Source File: CurrentTimestampFunction.java From crate with Apache License 2.0 | 6 votes |
private static long applyPrecision(long millis, int precision) { int factor; switch (precision) { case 0: factor = 1000; break; case 1: factor = 100; break; case 2: factor = 10; break; case 3: return millis; default: throw new IllegalArgumentException("Precision must be between 0 and 3"); } return LongMath.divide(millis, factor, RoundingMode.DOWN) * factor; }
Example #6
Source File: Sequence.java From phoenix with Apache License 2.0 | 5 votes |
private long increment(SequenceValue value, ValueOp op) throws SQLException { boolean increasingSeq = value.incrementBy > 0 && op != ValueOp.VALIDATE_SEQUENCE; // check if the the sequence has already reached the min/max limit if (value.limitReached && op != ValueOp.VALIDATE_SEQUENCE) { if (value.cycle) { value.limitReached=false; throw EMPTY_SEQUENCE_CACHE_EXCEPTION; } else { SQLExceptionCode code = increasingSeq ? SQLExceptionCode.SEQUENCE_VAL_REACHED_MAX_VALUE : SQLExceptionCode.SEQUENCE_VAL_REACHED_MIN_VALUE; throw SequenceUtil.getException(this.key.getSchemaName(), this.key.getSequenceName(), code); } } long returnValue = value.currentValue; if (op == ValueOp.INCREMENT_SEQUENCE) { boolean overflowOrUnderflow=false; // advance currentValue while checking for overflow try { value.currentValue = LongMath.checkedAdd(value.currentValue, value.incrementBy); } catch (ArithmeticException e) { overflowOrUnderflow = true; } // set the limitReached flag (which will be checked the next time increment is called) // if overflow or limit was reached if (overflowOrUnderflow || (increasingSeq && value.currentValue > value.maxValue) || (!increasingSeq && value.currentValue < value.minValue)) { value.limitReached=true; } } return returnValue; }
Example #7
Source File: SmoothRateLimiter.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
@Override final long reserveEarliestAvailable(int requiredPermits, long nowMicros) { resync(nowMicros); long returnValue = nextFreeTicketMicros; double storedPermitsToSpend = min(requiredPermits, this.storedPermits); double freshPermits = requiredPermits - storedPermitsToSpend; long waitMicros = storedPermitsToWaitTime(this.storedPermits, storedPermitsToSpend) + (long) (freshPermits * stableIntervalMicros); this.nextFreeTicketMicros = LongMath.saturatedAdd(nextFreeTicketMicros, waitMicros); this.storedPermits -= storedPermitsToSpend; return returnValue; }
Example #8
Source File: AkInterval.java From sql-layer with GNU Affero General Public License v3.0 | 5 votes |
@SuppressWarnings("unchecked") public long parse(String string) { // string could be a floating-point number if (units.length == 1) { try { double val = Double.parseDouble(string); return parseLong(Math.round(val), (U)units[0]); } catch (NumberFormatException e) { // does nothing. // Move on to the next step } } boolean isNegative = (string.charAt(0) == '-'); if (isNegative) string = string.substring(1); string = preParse(string); Matcher matcher = regex.matcher(string); if (!matcher.matches()) throw new AkibanInternalException("couldn't parse string as " + onBehalfOf.name() + ": " + string); long result = 0; for (int i = 0, len = matcher.groupCount(); i < len; ++i) { String group = matcher.group(i+1); @SuppressWarnings("unchecked") U unit = (U) units[i]; String preparsedGroup = preParseSegment(group, unit); Long longValue = Long.parseLong(preparsedGroup); int max = maxes[i]; if (longValue > max) throw new AkibanInternalException("out of range: " + group + " while parsing " + onBehalfOf); long parsed = parseLong(longValue, unit); result = LongMath.checkedAdd(result, parsed); } return isNegative ? -result : result; }
Example #9
Source File: SmoothRateLimiter.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
@Override final long reserveEarliestAvailable(int requiredPermits, long nowMicros) { resync(nowMicros); long returnValue = nextFreeTicketMicros; double storedPermitsToSpend = min(requiredPermits, this.storedPermits); double freshPermits = requiredPermits - storedPermitsToSpend; long waitMicros = storedPermitsToWaitTime(this.storedPermits, storedPermitsToSpend) + (long) (freshPermits * stableIntervalMicros); this.nextFreeTicketMicros = LongMath.saturatedAdd(nextFreeTicketMicros, waitMicros); this.storedPermits -= storedPermitsToSpend; return returnValue; }
Example #10
Source File: TimeoutScheduler.java From armeria with Apache License 2.0 | 5 votes |
private void setTimeoutMillis(long timeoutMillis) { checkArgument(timeoutMillis >= 0, "timeoutMillis: %s (expected: >= 0)", timeoutMillis); if (timeoutMillis == 0) { clearTimeout(); return; } if (this.timeoutMillis == 0) { setTimeoutAfterMillis(timeoutMillis); return; } final long adjustmentMillis = LongMath.saturatedSubtract(timeoutMillis, this.timeoutMillis); extendTimeoutMillis(adjustmentMillis); }
Example #11
Source File: Buffers.java From sfs with Apache License 2.0 | 5 votes |
public static Iterable<Positional<Buffer>> partition(final Positional<Buffer> input, final int size) { return () -> new Iterator<Positional<Buffer>>() { final long position = input.getPosition(); final Buffer src = input.getValue(); private long offset = position; private Iterator<Buffer> delegate = Buffers.partition(src, size).iterator(); @Override public boolean hasNext() { return delegate.hasNext(); } @Override public Positional<Buffer> next() { Buffer buffer = delegate.next(); Positional<Buffer> mapped = new Positional<>(offset, buffer); offset = LongMath.checkedAdd(offset, size); return mapped; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
Example #12
Source File: SAES256v02.java From sfs with Apache License 2.0 | 5 votes |
@Override public long encryptOutputSize(long size) { try { return LongMath.checkedAdd(size, TAG_LENGTH_BYTES); } catch (ArithmeticException e) { // do nothing } return -1; }
Example #13
Source File: Size.java From james-project with Apache License 2.0 | 5 votes |
public long asBytes() { switch (unit) { case G: return value * LongMath.pow(base, 3); case M: return value * LongMath.pow(base, 2); case K: return value * LongMath.pow(base, 1); default: return value; } }
Example #14
Source File: SendProducerBatchTask.java From aliyun-log-java-producer with Apache License 2.0 | 5 votes |
private long calculateRetryBackoffMs() { int retry = batch.getRetries(); long retryBackoffMs = producerConfig.getBaseRetryBackoffMs() * LongMath.pow(2, retry); if (retryBackoffMs <= 0) { retryBackoffMs = producerConfig.getMaxRetryBackoffMs(); } return Math.min(retryBackoffMs, producerConfig.getMaxRetryBackoffMs()); }
Example #15
Source File: DefaultTimeoutController.java From armeria with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} * * <p>Note that the {@link TimeoutTask} should be set via the {@link #setTimeoutTask(TimeoutTask)} or * the {@link #DefaultTimeoutController(TimeoutTask, EventExecutor)} before calling this method. * * @return {@code true} if the current timeout is extended by the specified {@code adjustmentMillis}. * {@code false} if no timeout was scheduled previously, the timeout has been triggered already * or the {@link TimeoutTask#canSchedule()} returned {@code false}. */ @Override public boolean extendTimeout(long adjustmentMillis) { ensureInitialized(); if (state != State.SCHEDULED || !timeoutTask.canSchedule()) { return false; } if (adjustmentMillis == 0) { return true; } // Cancel the previously scheduled timeout, if exists. cancelTimeout(); // Calculate the amount of time passed since lastStart final long currentNanoTime = System.nanoTime(); final long passedTimeMillis = TimeUnit.NANOSECONDS.toMillis(currentNanoTime - lastExecutionTimeNanos); final long newTimeoutMillis = LongMath.saturatedAdd( LongMath.saturatedSubtract(timeoutMillis, passedTimeMillis), adjustmentMillis); timeoutMillis = newTimeoutMillis; lastExecutionTimeNanos = currentNanoTime; if (newTimeoutMillis <= 0) { invokeTimeoutTask(); return true; } state = State.SCHEDULED; timeoutFuture = executor.schedule(this::invokeTimeoutTask, newTimeoutMillis, TimeUnit.MILLISECONDS); return true; }
Example #16
Source File: ArmeriaCentralDogma.java From centraldogma with Apache License 2.0 | 5 votes |
private <T> CompletableFuture<T> watch(Revision lastKnownRevision, long timeoutMillis, String path, QueryType queryType, BiFunction<AggregatedHttpResponse, QueryType, T> func) { final RequestHeadersBuilder builder = headersBuilder(HttpMethod.GET, path); builder.set(HttpHeaderNames.IF_NONE_MATCH, lastKnownRevision.text()) .set(HttpHeaderNames.PREFER, "wait=" + LongMath.saturatedAdd(timeoutMillis, 999) / 1000L); try (SafeCloseable ignored = Clients.withContextCustomizer(ctx -> { final long responseTimeoutMillis = ctx.responseTimeoutMillis(); final long adjustmentMillis = WatchTimeout.availableTimeout(timeoutMillis, responseTimeoutMillis); if (responseTimeoutMillis > 0) { ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, adjustmentMillis); } else { ctx.setResponseTimeoutMillis(adjustmentMillis); } })) { return client.execute(builder.build()).aggregate() .handle((res, cause) -> { if (cause == null) { return func.apply(res, queryType); } if ((cause instanceof ClosedStreamException) && client.options().factory().isClosing()) { // A user closed the client factory while watching. return null; } return Exceptions.throwUnsafely(cause); }); } }
Example #17
Source File: CuckooFilterTest.java From guava-probably with Apache License 2.0 | 5 votes |
@Test public void bitSize() { double fpp = 0.03; for (int i = 1; i < 10000; i++) { long numBits = CuckooFilter.calculateDataLength(i, fpp) * Long.SIZE; int arraySize = Ints.checkedCast(LongMath.divide(numBits, Long.SIZE, RoundingMode.CEILING)); assertEquals( arraySize * Long.SIZE, CuckooFilter.create(Funnels.unencodedCharsFunnel(), i, fpp).bitSize()); } }
Example #18
Source File: TpsWorkbeanch.java From saluki with Apache License 2.0 | 5 votes |
public static void run() throws Exception { Job job = new JobDetail(); // 创建Job executorService = Executors.newFixedThreadPool(N_THRESHOLDS); // 新建固定大小线程的池子 for (int i = 0; i < N_THRESHOLDS; i++) { executorService.submit(new Worker(job)); // 提交线程到池子中 } // 还需要一个线程,用于周期检查执行时间是否到达 final ScheduledExecutorService scheduledExcutor = Executors.newSingleThreadScheduledExecutor(); scheduledExcutor.scheduleAtFixedRate(new Runnable() { public void run() { if (totalTime.decrementAndGet() == 0) { // 执行时间递减到0 runnning = false; // 告诉线程,时间到了,所有线程不再执行 scheduledExcutor.shutdownNow(); } } }, 1L, 1L, TimeUnit.SECONDS); // 主线程等到所有的线程都退出,则开始统计 countDownLatch.await(); long totalExeCount = totalExecCount.get(); System.out.println(N_THRESHOLDS + " 个线程," + TIME_THRESHOLDS + " 秒内总共执行的事物数量:" + totalExeCount); long tps = LongMath.divide(totalExeCount, TIME_THRESHOLDS, RoundingMode.HALF_EVEN); System.out.println("OKHttp执行的TPS: " + tps); executorService.shutdownNow(); // 关闭线程池 }
Example #19
Source File: FilterAggStarRule.java From quark with Apache License 2.0 | 5 votes |
String bitSetToString(ImmutableBitSet bits) { long result = 0; for (Integer i : bits) { result += LongMath.checkedPow(2, i); } return String.valueOf(result); }
Example #20
Source File: MathFunctions.java From presto with Apache License 2.0 | 5 votes |
private static long roundLong(long num, long decimals) { if (decimals >= 0) { return num; } try { long factor = LongMath.checkedPow(10, toIntExact(-decimals)); return Math.multiplyExact(LongMath.divide(num, factor, RoundingMode.HALF_UP), factor); } catch (ArithmeticException e) { throw new PrestoException(NUMERIC_VALUE_OUT_OF_RANGE, "numerical overflow: " + num, e); } }
Example #21
Source File: GuavaLongMathUnitTest.java From tutorials with MIT License | 4 votes |
@Test public void whenLog2LongValues_shouldLog2ThemAndReturnTheResultForCeilingRounding() { int result = LongMath.log2(30L, RoundingMode.CEILING); assertEquals(5, result); }
Example #22
Source File: GuavaLongMathUnitTest.java From tutorials with MIT License | 4 votes |
@Test public void whenIsPrineOfLong_shouldReturnFalseeIfNotPrime() { boolean result = LongMath.isPrime(20L); assertFalse(result); }
Example #23
Source File: GuavaLongMathUnitTest.java From tutorials with MIT License | 4 votes |
@Test public void whenSaturatedMultiplyTwoLongValues_shouldMultiplyThemAndReturnIntMaxIfOverflow() { long result = LongMath.saturatedMultiply(Long.MAX_VALUE, 1000L); assertEquals(Long.MAX_VALUE, result); }
Example #24
Source File: BloomFilterStrategies.java From codebuff with BSD 2-Clause "Simplified" License | 4 votes |
BitArray(long bits) { this( new long[Ints.checkedCast(LongMath.divide(bits, 64, RoundingMode.CEILING))]); }
Example #25
Source File: IntegerSym.java From symja_android_library with GNU General Public License v3.0 | 4 votes |
/** {@inheritDoc} */ @Override public boolean isProbablePrime(int certainty) { return LongMath.isPrime(fIntValue); // return toBigNumerator().isProbablePrime(certainty); }
Example #26
Source File: Fiat.java From GreenBits with GNU General Public License v3.0 | 4 votes |
public Fiat add(final Fiat value) { checkArgument(value.currencyCode.equals(currencyCode)); return new Fiat(currencyCode, LongMath.checkedAdd(this.value, value.value)); }
Example #27
Source File: GuavaLongMathUnitTest.java From tutorials with MIT License | 4 votes |
@Test public void whenFloorPowerOfLong_shouldReturnValue() { long result = LongMath.floorPowerOfTwo(30L); assertEquals(16L, result); }
Example #28
Source File: GuavaLongMathUnitTest.java From tutorials with MIT License | 4 votes |
@Test public void whenLog10LongValues_shouldog10ThemAndReturnTheResultForFloorRounding() { int result = LongMath.log10(30L, RoundingMode.FLOOR); assertEquals(1, result); }
Example #29
Source File: GuavaLongMathUnitTest.java From tutorials with MIT License | 4 votes |
@Test public void whenFactorailLong_shouldFactorialThemAndReturnTheResultIfInIntRange() { long result = LongMath.factorial(5); assertEquals(120L, result); }
Example #30
Source File: GuavaLongMathUnitTest.java From tutorials with MIT License | 4 votes |
@Test public void whenSqrtLongValues_shouldSqrtThemAndReturnTheResultForFloorRounding() { long result = LongMath.sqrt(30L, RoundingMode.FLOOR); assertEquals(5L, result); }