Skip to content

Commit

Permalink
Fix display of byte sizes (fix #2132) (#2148)
Browse files Browse the repository at this point in the history
* Fix display of byte sizes
  • Loading branch information
joerghoh authored and badvision committed Jan 6, 2020
1 parent e78b4c6 commit ee1674c
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 9 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ The format is based on [Keep a Changelog](http://keepachangelog.com)
<!-- Keep this up to date! After a release, change the tag name to the latest release -->
[unreleased changes details]: https://github.com/Adobe-Consulting-Services/acs-aem-commons/compare/acs-aem-commons-4.3.2...HEAD

### Added

### Fixed
- #2148 bugfix for displaying sizes (adresses #2132)

### Changed

## [4.4.0] - 2019-12-17

### Added
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,26 @@ public static String getHumanSize(Object val) {
return null;
}
Long bytes = (val instanceof Long) ? (Long) val : Long.parseLong(String.valueOf(val));
if (bytes < 1024) {
return bytes + " b";
return humanReadableByteCount(bytes, false);
}

// From: https://programming.guide/worlds-most-copied-so-snippet.html
public static strictfp String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
long absBytes = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes);
if (absBytes < unit) {
return bytes + " B";
}
int exp = (int) (Math.log(absBytes) / Math.log(unit));
long th = (long) (Math.pow(unit, exp) * (unit - 0.05));
if (exp < 6 && absBytes >= th - ((th & 0xfff) == 0xd00 ? 52 : 0)) {
exp++;
}
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
if (exp > 4) {
bytes /= unit;
exp -= 1;
}
int exp = (int) (Math.log(bytes) / Math.log(1024));
char pre = "kmgtpe".charAt(exp - 1);
return String.format("%.1f %cb", bytes / Math.pow(1024, exp), pre);
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,21 +51,21 @@ public void testUndefinedAnnotations() {

@Test
public void oneKb() {
assertEquals(ONE + " kb", ValueFormat.getHumanSize(1 << 10));
assertEquals(ONE + " KiB", ValueFormat.getHumanSize(1 << 10));
}

@Test
public void oneMb() {
assertEquals(ONE + " mb", ValueFormat.getHumanSize(1 << 20));
assertEquals(ONE + " MiB", ValueFormat.getHumanSize(1 << 20));
}

@Test
public void oneGb() {
assertEquals(ONE + " gb", ValueFormat.getHumanSize(1 << 30));
assertEquals(ONE + " GiB", ValueFormat.getHumanSize(1 << 30));
}

@Test
public void onetb() {
assertEquals(ONE + " tb", ValueFormat.getHumanSize(((long) (1 << 30)) * 1024L));
assertEquals(ONE + " TiB", ValueFormat.getHumanSize(((long) (1 << 30)) * 1024L));
}
}

0 comments on commit ee1674c

Please sign in to comment.