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
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/FormatUtil.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/FormatUtil.java
index 7307264..878abd25 100644
--- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/FormatUtil.java
+++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/FormatUtil.java
@@ -137,7 +137,25 @@
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;
+ }
}