MCPcopy Create free account
hub / github.com/antlr/codebuff / saturatedPow

Method saturatedPow

output/java_guava/1.4.19/IntMath.java:590–637  ·  view source on GitHub ↗

Returns the b to the kth power, unless it would overflow or underflow in which case Integer.MAX_VALUE or Integer.MIN_VALUE is returned, respectively. @since 20.0

(int b, int k)

Source from the content-addressed store, hash-verified

588 */
589
590 @Beta
591 public static int saturatedPow(int b, int k) {
592 checkNonNegative("exponent", k);
593 switch (b) {
594 case 0:
595 return (k == 0) ? 1 : 0;
596 case 1:
597 return 1;
598 case (-1):
599 return ((k & 1) == 0) ? 1 : -1;
600 case 2:
601 if (k >= Integer.SIZE - 1) {
602 return Integer.MAX_VALUE;
603 }
604return 1 << k;
605 case (-2):
606 if (k >= Integer.SIZE) {
607 return Integer.MAX_VALUE + (k & 1);
608 }
609return ((k & 1) == 0) ? 1 << k : -1 << k;
610 default:
611 // continue below to handle the general case
612
613 }
614
615 int accum = 1;
616 // if b is negative and k is odd then the limit is MIN otherwise the limit is MAX
617 int limit = Integer.MAX_VALUE + ((b >>> Integer.SIZE - 1) & (k & 1));
618 while (true) {
619 switch (k) {
620 case 0:
621 return accum;
622 case 1:
623 return saturatedMultiply(accum, b);
624 default:
625 if ((k & 1) != 0) {
626 accum = saturatedMultiply(accum, b);
627 }
628 k >>= 1;
629 if (k > 0) {
630 if (-FLOOR_SQRT_MAX_INT > b | b > FLOOR_SQRT_MAX_INT) {
631 return limit;
632 }
633 b *= b;
634 }
635 }
636 }
637 }
638
639 @VisibleForTesting
640 static final int FLOOR_SQRT_MAX_INT = 46340;

Callers

nothing calls this directly

Calls 2

saturatedMultiplyMethod · 0.95
checkNonNegativeMethod · 0.45

Tested by

no test coverage detected