Skip to content

Commit

Permalink
fix human readable formatter for negative sizes, zero bytes, and one …
Browse files Browse the repository at this point in the history
…byte
  • Loading branch information
heuermh committed May 29, 2024
1 parent fc4a87d commit 9b4cb86
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@
<artifactId>picocli</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,20 @@ final class HumanReadableFormatter {
* Format the specified size in bytes to human readable
* binary multi-byte units.
*
* @param size, size in bytes
* @param size, size in bytes, must be at least zero
* @return the specified size in bytes formatted to human readable
* binary multi-byte units
*/
String format(final long size) {
if (size < 0L) {
throw new IllegalArgumentException("size must be at least zero");
}
if (size == 0L) {
return "0 Bytes";
}
if (size == 1L) {
return "1 Byte";
}
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return decimalFormat.format(size / Math.pow(1024, digitGroups)) + " " + UNITS[digitGroups];
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* The authors of this file license it to you under the
* Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.heuermh.cooper;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
* Unit test for HumanReadableFormatter.
*
* @author Michael Heuer
*/
public final class HumanReadableFormatterTest {

@Test(expected=IllegalArgumentException.class)
public void testFormatLessThanZero() {
new HumanReadableFormatter().format(-1L);
}

@Test
public void testFormat() {
HumanReadableFormatter formatter = new HumanReadableFormatter();
assertEquals("0 Bytes", formatter.format(0L));
assertEquals("1 Byte", formatter.format(1L));
assertEquals("113 Bytes", formatter.format(113L));
assertEquals("2.1 KiB", formatter.format(2122L));
assertEquals("377.3 MiB", formatter.format(395610342L));
assertEquals("1.7 GiB", formatter.format(1826577054L));
}
}

0 comments on commit 9b4cb86

Please sign in to comment.