Java Code Examples for com.google.common.math.LongMath#checkedAdd()

The following examples show how to use com.google.common.math.LongMath#checkedAdd() . 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: Sequence.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * This method checks whether there are sufficient values in the SequenceValue
 * cached on the client to allocate the requested number of slots. It handles
 * decreasing and increasing sequences as well as any overflows or underflows
 * encountered.
 */
private boolean isSequenceCacheExhaustedForBulkAllocation(final long numToAllocate, final SequenceValue value) throws SQLException {
    long targetSequenceValue;
    
    performValidationForBulkAllocation(numToAllocate, value);
    
    try {
        targetSequenceValue = LongMath.checkedAdd(value.currentValue, numToAllocate * value.incrementBy);
    } catch (ArithmeticException e) {
        // Perform a CheckedAdd to make sure if over/underflow 
        // We don't treat this as the cache being exhausted as the current value may be valid in the case
        // of no cycle, logic in increment() will take care of detecting we've hit the limit of the sequence
        return false;
    }

    if (value.incrementBy > 0) {
        return targetSequenceValue > value.nextValue;
    } else {
        return  targetSequenceValue < value.nextValue;    
    }
}
 
Example 2
Source File: SmoothRateLimiter.java    From kite with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: SequenceUtil.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
   * @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 4
Source File: RecyclingAllocator.java    From sfs with Apache License 2.0 6 votes vote down vote up
public long getBytesFree(long useableSpace) {
    synchronized (mutex) {
        useableSpace = Math.max(0, useableSpace);
        long free = 0;
        Range last = byPosition.lastEntry().getValue();
        for (Range range : byPosition.values()) {
            if (range == last) {
                long firstPosition = range.getFirst();
                long length = Rounding.down(useableSpace, blockSize);
                long lastPosition = computeLast(firstPosition, length - firstPosition);
                Range adjustedLast = new Range(firstPosition, lastPosition);
                free = LongMath.checkedAdd(free, adjustedLast.getBlockCount());
            } else {
                free = LongMath.checkedAdd(free, range.getBlockCount());
            }
        }
        return free;
    }
}
 
Example 5
Source File: BloomFilter.java    From guava-probably with Apache License 2.0 5 votes vote down vote up
/**
 * Combines {@code this} filter with another compatible filter. The mutations happen to {@code
 * this} instance. Callers must ensure {@code this} filter is appropriately sized to avoid
 * saturating it or running out of space.
 *
 * @param f filter to be combined into {@code this} filter - {@code f} is not mutated
 * @return {@code true} if the operation was successful, {@code false} otherwise
 * @throws NullPointerException     if the specified filter is null
 * @throws IllegalArgumentException if {@link #isCompatible(ProbabilisticFilter)} {@code ==
 *                                  false}
 * @see #add(Object)
 * @see #addAll(Collection)
 * @see #contains(Object)
 */
public boolean addAll(ProbabilisticFilter<E> f) {
  checkNotNull(f);
  checkArgument(this != f, "Cannot combine a " + this.getClass().getSimpleName() +
      " with itself.");
  checkArgument(f instanceof BloomFilter, "Cannot combine a " +
      this.getClass().getSimpleName() + " with a " + f.getClass().getSimpleName());
  checkArgument(this.isCompatible(f), "Cannot combine incompatible filters. " +
      this.getClass().getSimpleName() + " instances must have equivalent funnels; the same " +
      "strategy; and the same number of buckets, entries per bucket, and bits per entry.");

  delegate.putAll(((BloomFilter<E>) f).delegate);
  size = LongMath.checkedAdd(size, f.sizeLong());
  return true;
}
 
Example 6
Source File: Sequence.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private long increment(SequenceValue value, ValueOp op, long numToAllocate) 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 {
            // advance by numToAllocate * the increment amount
            value.currentValue = LongMath.checkedAdd(value.currentValue, numToAllocate * 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: SAES256v02.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public long encryptOutputSize(long size) {
    try {
        return LongMath.checkedAdd(size, TAG_LENGTH_BYTES);
    } catch (ArithmeticException e) {
        // do nothing
    }
    return -1;
}
 
Example 8
Source File: SAES256v01.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public long encryptOutputSize(long size) {
    try {
        return LongMath.checkedAdd(size, MAC_SIZE_BYTES);
    } catch (ArithmeticException e) {
        // do nothing
    }
    return -1;
}
 
Example 9
Source File: Buffers.java    From sfs with Apache License 2.0 5 votes vote down vote up
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 10
Source File: AkInterval.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 11
Source File: BloomFilter.java    From guava-probably with Apache License 2.0 5 votes vote down vote up
/**
 * Combines {@code this} filter with another compatible filter. The mutations happen to {@code
 * this} instance. Callers must ensure {@code this} filter is appropriately sized to avoid
 * saturating it or running out of space.
 *
 * @param f filter to be combined into {@code this} filter - {@code f} is not mutated
 * @return {@code true} if the operation was successful, {@code false} otherwise
 * @throws NullPointerException     if the specified filter is null
 * @throws IllegalArgumentException if {@link #isCompatible(ProbabilisticFilter)} {@code ==
 *                                  false}
 * @see #add(Object)
 * @see #addAll(Collection)
 * @see #contains(Object)
 */
public boolean addAll(ProbabilisticFilter<E> f) {
  checkNotNull(f);
  checkArgument(this != f, "Cannot combine a " + this.getClass().getSimpleName() +
      " with itself.");
  checkArgument(f instanceof BloomFilter, "Cannot combine a " +
      this.getClass().getSimpleName() + " with a " + f.getClass().getSimpleName());
  checkArgument(this.isCompatible(f), "Cannot combine incompatible filters. " +
      this.getClass().getSimpleName() + " instances must have equivalent funnels; the same " +
      "strategy; and the same number of buckets, entries per bucket, and bits per entry.");

  delegate.putAll(((BloomFilter<E>) f).delegate);
  size = LongMath.checkedAdd(size, f.sizeLong());
  return true;
}
 
Example 12
Source File: Sequence.java    From phoenix with Apache License 2.0 5 votes vote down vote up
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 13
Source File: Coin.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public Coin add(final Coin value) {
    return new Coin(LongMath.checkedAdd(this.value, value.value));
}
 
Example 14
Source File: Altcoin.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public Altcoin add(final Altcoin value) {
    checkArgument(value.currencyCode.equals(currencyCode));
    return new Altcoin(currencyCode, LongMath.checkedAdd(this.value, value.value));
}
 
Example 15
Source File: Fiat.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public Fiat add(final Fiat value) {
    checkArgument(value.currencyCode.equals(currencyCode));
    return new Fiat(currencyCode, LongMath.checkedAdd(this.value, value.value));
}
 
Example 16
Source File: Altcoin.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
public Altcoin add(final Altcoin value) {
    checkArgument(value.currencyCode.equals(currencyCode));
    return new Altcoin(currencyCode, LongMath.checkedAdd(this.value, value.value));
}
 
Example 17
Source File: GuavaLongMathUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test(expected = ArithmeticException.class)
public void whenCheckedAddTwoLongValues_shouldThrowArithmeticExceptionIfOverflow() {
    LongMath.checkedAdd(Long.MAX_VALUE, 100L);
}
 
Example 18
Source File: Fiat.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public Fiat add(final Fiat value) {
    checkArgument(value.currencyCode.equals(currencyCode));
    return new Fiat(currencyCode, LongMath.checkedAdd(this.value, value.value));
}
 
Example 19
Source File: Coin.java    From GreenBits with GNU General Public License v3.0 4 votes vote down vote up
public Coin add(final Coin value) {
    return new Coin(LongMath.checkedAdd(this.value, value.value));
}
 
Example 20
Source File: BloomFilter.java    From guava-probably with Apache License 2.0 3 votes vote down vote up
/**
 * Adds the specified element to this filter. A return value of {@code true} ensures that {@link
 * #contains(Object)} given {@code e} will also return {@code true}.
 *
 * @param e element to be added to this filter
 * @return always {@code true} as {@code com.google.common.hash.BloomFilter} cannot fail to add an
 * object
 * @throws NullPointerException if the specified element is null
 * @see #contains(Object)
 * @see #addAll(Collection)
 * @see #addAll(ProbabilisticFilter)
 * @see <a target="guavadoc" href="http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/hash/BloomFilter.html#put(T)">com.google.common.hash.BloomFilter#put(T)</a>
 */
public boolean add(E e) {
  checkNotNull(e);
  delegate.put(e);
  size = LongMath.checkedAdd(size, 1L);
  return true;
}