Skip to content

Commit

Permalink
Add helper functions for ByteSizeValues of a given unit (#63679)
Browse files Browse the repository at this point in the history
As a developer that periodically worries about absolute sizes of bytes, I love our good ByteSizeValue abstractions + and the unit sizes.

But, I find the pattern `new ByteSizeValue(<some long>, <some unit>).getBytes()` frustrating. 

This commit adds some simple convenience methods for each byte unit and constructing a ByteSizeValue of the given size for that unit.
  • Loading branch information
benwtrent authored Oct 14, 2020
1 parent b33cfa5 commit 37b261b
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,30 @@ static class DeprecationLoggerHolder {

public static final ByteSizeValue ZERO = new ByteSizeValue(0, ByteSizeUnit.BYTES);

public static ByteSizeValue ofBytes(long size) {
return new ByteSizeValue(size);
}

public static ByteSizeValue ofKb(long size) {
return new ByteSizeValue(size, ByteSizeUnit.KB);
}

public static ByteSizeValue ofMb(long size) {
return new ByteSizeValue(size, ByteSizeUnit.MB);
}

public static ByteSizeValue ofGb(long size) {
return new ByteSizeValue(size, ByteSizeUnit.GB);
}

public static ByteSizeValue ofTb(long size) {
return new ByteSizeValue(size, ByteSizeUnit.TB);
}

public static ByteSizeValue ofPb(long size) {
return new ByteSizeValue(size, ByteSizeUnit.PB);
}

private final long size;
private final ByteSizeUnit unit;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.hamcrest.MatcherAssert;

import java.io.IOException;
import java.util.function.Function;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
Expand Down Expand Up @@ -325,4 +326,37 @@ public void testGetBytesAsInt() {
}
}
}

public void testOfBytes() {
testOf(ByteSizeUnit.BYTES, ByteSizeValue::ofBytes);
}

public void testOfKb() {
testOf(ByteSizeUnit.KB, ByteSizeValue::ofKb);
}

public void testOfMb() {
testOf(ByteSizeUnit.MB, ByteSizeValue::ofMb);
}

public void testOfGb() {
testOf(ByteSizeUnit.GB, ByteSizeValue::ofGb);
}

public void testOfTb() {
testOf(ByteSizeUnit.TB, ByteSizeValue::ofTb);
}

public void testOfPb() {
testOf(ByteSizeUnit.PB, ByteSizeValue::ofPb);
}

private void testOf(ByteSizeUnit unit, Function<Long, ByteSizeValue> byteSizeValueFunction) {
for (int i = 0; i < NUMBER_OF_TEST_RUNS; i++) {
long size = randomIntBetween(1, 1000);
ByteSizeValue expected = new ByteSizeValue(size, unit);
ByteSizeValue actual = byteSizeValueFunction.apply(size);
assertThat(actual, equalTo(expected));
}
}
}

0 comments on commit 37b261b

Please sign in to comment.