FormatUtil: Fix Math#round() truncation error flagged by error-prone

Building with Bazel@HEAD: [1] is failing with this error message:

  FormatUtil.java:129: error: [MathRoundIntLong] Math.round(Integer) results in truncation
  | int p = Math.abs(Math.round(delta * 100 / size));
  | ^
  | (see https://errorprone.info/bugpattern/MathRoundIntLong)
  | Did you mean 'int p = Math.abs(Ints.saturatedCast(delta * 100 / size));'?

To rectify, replace Math.round() with Ints.saturatedCast() and borrow
this method from Guava library because Guava cannot be currently used in
GWT client code.

[1] https://github.com/bazelbuild/bazel/issues/5944
Change-Id: I1c88102d4d027796594fb7cdcde4f0ec4921d4ad
This commit is contained in:
David Ostrovsky 2018-08-22 07:32:21 +02:00
parent 6a3fa83072
commit 2a107d74a1

View File

@ -137,7 +137,25 @@ public class FormatUtil {
if (size == 0) {
return Resources.C.notAvailable();
}
int p = Math.abs(Math.round(delta * 100 / size));
int p = Math.abs(saturatedCast(delta * 100 / size));
return p + "%";
}
/**
* Returns the {@code int} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code int} if it is in the range of the {@code int} type,
* {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too
* small
*/
private static int saturatedCast(long value) {
if (value > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (value < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) value;
}
}