This is an automated email from the ASF dual-hosted git repository.
squah-confluent pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/kafka.git
The following commit(s) were added to refs/heads/trunk by this push:
new 26e8df61e31 MINOR: Fix formatBytes to return "0 B" for zero bytes
(#22921)
26e8df61e31 is described below
commit 26e8df61e31bd71777f24d28bce6071ac8c70a08
Author: Nikolaus Schuetz <[email protected]>
AuthorDate: Mon Aug 3 15:52:26 2026 -0700
MINOR: Fix formatBytes to return "0 B" for zero bytes (#22921)
`Utils.formatBytes(0)` returned `"0.0"` instead of `"0 B"`: for `bytes
== 0`, `Math.log(0)` is `-Infinity`, so the scale index underflows, the
suffix lookup throws `ArrayIndexOutOfBoundsException`, and the catch
falls back to `String.valueOf(0.0)`. `formatBytes` is used by
`SimpleMemoryPool`/`GarbageCollectedMemoryPool` `toString()`, so an
empty pool rendered `0.0` in operator-facing output.
Handle zero explicitly and add a `UtilsTest.testFormatBytes` case for it
(fails before the fix with `expected: <0 B> but was: <0.0>`, passes
after).
Reviewers: Sean Quah <[email protected]>
---------
Signed-off-by: Nikolaus Schuetz <[email protected]>
---
clients/src/main/java/org/apache/kafka/common/utils/Utils.java | 3 +++
clients/src/test/java/org/apache/kafka/common/utils/UtilsTest.java | 1 +
2 files changed, 4 insertions(+)
diff --git a/clients/src/main/java/org/apache/kafka/common/utils/Utils.java
b/clients/src/main/java/org/apache/kafka/common/utils/Utils.java
index 9ee0d7c9d2e..5fa1b1b83b5 100644
--- a/clients/src/main/java/org/apache/kafka/common/utils/Utils.java
+++ b/clients/src/main/java/org/apache/kafka/common/utils/Utils.java
@@ -595,6 +595,9 @@ public final class Utils {
if (bytes < 0) {
return String.valueOf(bytes);
}
+ if (bytes == 0) {
+ return "0 " + BYTE_SCALE_SUFFIXES[0];
+ }
double asDouble = (double) bytes;
int ordinal = (int) Math.floor(Math.log(asDouble) / Math.log(1024.0));
double scale = Math.pow(1024.0, ordinal);
diff --git a/clients/src/test/java/org/apache/kafka/common/utils/UtilsTest.java
b/clients/src/test/java/org/apache/kafka/common/utils/UtilsTest.java
index 470d4846ca7..59dcad1ca0d 100755
--- a/clients/src/test/java/org/apache/kafka/common/utils/UtilsTest.java
+++ b/clients/src/test/java/org/apache/kafka/common/utils/UtilsTest.java
@@ -218,6 +218,7 @@ public class UtilsTest {
@Test
public void testFormatBytes() {
assertEquals("-1", formatBytes(-1));
+ assertEquals("0 B", formatBytes(0));
assertEquals("1023 B", formatBytes(1023));
assertEquals("1 KB", formatBytes(1024));
assertEquals("1024 KB", formatBytes((1024 * 1024) - 1));