(long a, long b)
| 641 | */ |
| 642 | // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, || |
| 643 | @SuppressWarnings("ShortCircuitBoolean") |
| 644 | public static long saturatedAdd(long a, long b) { |
| 645 | long naiveSum = a + b; |
| 646 | if ((a ^ b) < 0 | (a ^ naiveSum) >= 0) { |
| 647 | // If a and b have different signs or a has the same sign as the result then there was no |
| 648 | // overflow, return. |
| 649 | return naiveSum; |
| 650 | } |
| 651 | // we did over/under flow, if the sign is negative we should return MAX otherwise MIN |
| 652 | return Long.MAX_VALUE + ((naiveSum >>> (Long.SIZE - 1)) ^ 1); |
| 653 | } |
| 654 | |
| 655 | /** |
| 656 | * Returns the difference of {@code a} and {@code b} unless it would overflow or underflow in |
no outgoing calls