Skip to content

Commit 8dbdfeb

Browse files
authored
Makes ByteCount Comparable to make it easier to write validations. (#6156)
Signed-off-by: David Venable <dlv@amazon.com>
1 parent 0a48278 commit 8dbdfeb

2 files changed

Lines changed: 26 additions & 5 deletions

File tree

data-prepper-api/src/main/java/org/opensearch/dataprepper/model/types/ByteCount.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
*
2121
* @since 2.1
2222
*/
23-
public class ByteCount {
23+
public class ByteCount implements Comparable<ByteCount> {
2424
private static final Pattern BYTE_PATTERN = Pattern.compile("^(?<value>\\d+\\.?\\d*)(?<unit>[a-z]+)?\\z");
2525
private static final ByteCount ZERO_BYTES = new ByteCount(0);
2626
private final long bytes;
@@ -167,4 +167,9 @@ public boolean equals(final Object otherObject) {
167167
public String toString() {
168168
return bytes + Unit.BYTE.unitString;
169169
}
170+
171+
@Override
172+
public int compareTo(final ByteCount otherByteCount) {
173+
return Long.compare(this.bytes, otherByteCount.bytes);
174+
}
170175
}

data-prepper-api/src/test/java/org/opensearch/dataprepper/model/types/ByteCountTest.java

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,6 @@
1010
import org.junit.jupiter.params.provider.CsvSource;
1111
import org.junit.jupiter.params.provider.ValueSource;
1212

13-
import java.util.Random;
14-
1513
import static org.hamcrest.CoreMatchers.not;
1614
import static org.hamcrest.MatcherAssert.assertThat;
1715
import static org.hamcrest.Matchers.containsString;
@@ -21,8 +19,6 @@
2119
import static org.junit.jupiter.api.Assertions.assertThrows;
2220

2321
class ByteCountTest {
24-
private final Random random = new Random();
25-
2622
@ParameterizedTest
2723
@ValueSource(strings = {
2824
".1b",
@@ -262,4 +258,24 @@ void toString_returns_string_that_parses_to_the_same_value(final long bytes) {
262258
assertThat(parsedByteCount, equalTo(objectUnderTest));
263259
assertThat(parsedByteCount.hashCode(), equalTo(objectUnderTest.hashCode()));
264260
}
261+
262+
@ParameterizedTest
263+
@CsvSource({
264+
"0b, 0b, 0",
265+
"1b, 1b, 0",
266+
"0b, 1b, -1",
267+
"1b, 0b, 1",
268+
"1kb, 1024b, 0",
269+
"512b, 1kb, -1",
270+
"2kb, 1kb, 1",
271+
"1mb, 1kb, 1",
272+
"1kb, 1mb, -1",
273+
"1gb, 1mb, 1",
274+
"500mb, 1gb, -1"
275+
})
276+
void compareTo_returns_expected_comparison_result(final String firstByteString, final String secondByteString, final int expectedResult) {
277+
final ByteCount first = ByteCount.parse(firstByteString);
278+
final ByteCount second = ByteCount.parse(secondByteString);
279+
assertThat(first.compareTo(second), equalTo(expectedResult));
280+
}
265281
}

0 commit comments

Comments
 (0)