|
|
@ -117,10 +117,12 @@ public interface Words { |
|
|
|
* @return value of a plus b if no over/underflows or Long.MAX_VALUE/Long.MIN_VALUE otherwise |
|
|
|
* @return value of a plus b if no over/underflows or Long.MAX_VALUE/Long.MIN_VALUE otherwise |
|
|
|
*/ |
|
|
|
*/ |
|
|
|
static long clampedAdd(final long a, final long b) { |
|
|
|
static long clampedAdd(final long a, final long b) { |
|
|
|
try { |
|
|
|
long r = a + b; |
|
|
|
return Math.addExact(a, b); |
|
|
|
if (((a ^ r) & (b ^ r)) < 0) { |
|
|
|
} catch (final ArithmeticException ae) { |
|
|
|
// out of bounds, clamp it!
|
|
|
|
return a > 0 ? Long.MAX_VALUE : Long.MIN_VALUE; |
|
|
|
return a > 0 ? Long.MAX_VALUE : Long.MIN_VALUE; |
|
|
|
|
|
|
|
} else { |
|
|
|
|
|
|
|
return r; |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
@ -132,10 +134,15 @@ public interface Words { |
|
|
|
* @return value of a times b if no over/underflows or Long.MAX_VALUE/Long.MIN_VALUE otherwise |
|
|
|
* @return value of a times b if no over/underflows or Long.MAX_VALUE/Long.MIN_VALUE otherwise |
|
|
|
*/ |
|
|
|
*/ |
|
|
|
static long clampedMultiply(final long a, final long b) { |
|
|
|
static long clampedMultiply(final long a, final long b) { |
|
|
|
try { |
|
|
|
long r = a * b; |
|
|
|
return Math.multiplyExact(a, b); |
|
|
|
long ax = Math.abs(a); |
|
|
|
} catch (final ArithmeticException ae) { |
|
|
|
long ay = Math.abs(b); |
|
|
|
|
|
|
|
if (((ax | ay) >>> 31 != 0) |
|
|
|
|
|
|
|
&& (((b != 0) && (r / b != a)) || (a == Long.MIN_VALUE && b == -1))) { |
|
|
|
|
|
|
|
// out of bounds, clamp it!
|
|
|
|
return ((a ^ b) < 0) ? Long.MIN_VALUE : Long.MAX_VALUE; |
|
|
|
return ((a ^ b) < 0) ? Long.MIN_VALUE : Long.MAX_VALUE; |
|
|
|
|
|
|
|
} else { |
|
|
|
|
|
|
|
return r; |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
@ -148,9 +155,12 @@ public interface Words { |
|
|
|
* otherwise |
|
|
|
* otherwise |
|
|
|
*/ |
|
|
|
*/ |
|
|
|
static int clampedMultiply(final int a, final int b) { |
|
|
|
static int clampedMultiply(final int a, final int b) { |
|
|
|
try { |
|
|
|
long r = (long) a * (long) b; |
|
|
|
return Math.multiplyExact(a, b); |
|
|
|
int ri = (int) r; |
|
|
|
} catch (final ArithmeticException ae) { |
|
|
|
if (ri == r) { |
|
|
|
|
|
|
|
return ri; |
|
|
|
|
|
|
|
} else { |
|
|
|
|
|
|
|
// out of bounds, clamp it!
|
|
|
|
return ((a ^ b) < 0) ? Integer.MIN_VALUE : Integer.MAX_VALUE; |
|
|
|
return ((a ^ b) < 0) ? Integer.MIN_VALUE : Integer.MAX_VALUE; |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|