This is an automated email from the ASF dual-hosted git repository.
garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git
The following commit(s) were added to refs/heads/master by this push:
new 2ea891019 Add DataSize and DataUnit to org.apache.commons.lang3.unit
(#1901)
2ea891019 is described below
commit 2ea891019918083cc08eda21eb3a6bb2f2d5ca29
Author: Gary Gregory <[email protected]>
AuthorDate: Wed Dec 2 08:04:10 2026 -0500
Add DataSize and DataUnit to org.apache.commons.lang3.unit (#1901)
Introduce an immutable, serializable DataSize backed by a signed long
byte
count. Support explicit decimal and binary units, checked overflow, and
conversions that truncate toward zero. Parsing is not included.
---
src/changes/changes.xml | 1 +
.../org/apache/commons/lang3/unit/DataSize.java | 181 +++++++++++++
.../org/apache/commons/lang3/unit/DataUnit.java | 137 ++++++++++
.../apache/commons/lang3/unit/package-info.java | 28 ++
.../apache/commons/lang3/unit/DataSizeTest.java | 300 +++++++++++++++++++++
.../apache/commons/lang3/unit/DataUnitTest.java | 51 ++++
6 files changed, 698 insertions(+)
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 36c2f0af3..6a5b22f16 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -129,6 +129,7 @@ The <action> type attribute can be add,update,fix,remove.
<action issue="LANG-1465" type="fix" dev="ggregory" due-to="xia0c, Gary
Gregory">Javadoc: Clarify ZZ time zone parsing and the Z and XX alternatives in
DateUtils.</action>
<action type="fix" dev="ggregory" due-to="Sergi Parpal,
Gary Gregory">Javadoc: StopWatch: split() can be called more than once
(#1899).</action>
<!-- ADD -->
+ <action type="add" dev="ggregory" due-to="Gary Gregory">Add immutable
DataSize and DataUnit types in org.apache.commons.lang3.unit with explicit
decimal and binary units.</action>
<!-- UPDATE -->
</release>
<release version="3.22.0" date="2026-11-08" description="This is a feature
and maintenance release. Java 8 or later is required.">
diff --git a/src/main/java/org/apache/commons/lang3/unit/DataSize.java
b/src/main/java/org/apache/commons/lang3/unit/DataSize.java
new file mode 100644
index 000000000..c36320cc3
--- /dev/null
+++ b/src/main/java/org/apache/commons/lang3/unit/DataSize.java
@@ -0,0 +1,181 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file 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
+ *
+ * https://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 org.apache.commons.lang3.unit;
+
+import java.io.Serializable;
+import java.util.Objects;
+
+/**
+ * An immutable data size measured in bytes.
+ *
+ * <p>
+ * A data size stores a signed {@code long} byte count. Negative values can
represent differences between sizes. Equality, ordering, and hashing depend
only on
+ * the byte count, regardless of the unit used to create the instance. This
class is thread-safe.
+ * </p>
+ *
+ * <p>
+ * Decimal units use powers of 1000, while binary units use powers of 1024.
For example, one {@link DataUnit#KILOBYTES kilobyte} is 1000 bytes and one
+ * {@link DataUnit#KIBIBYTES kibibyte} is 1024 bytes. Factory methods throw
{@link ArithmeticException} if the byte count overflows a {@code long}.
Conversions
+ * to larger units truncate toward zero.
+ * </p>
+ *
+ * <pre>{@code
+ * DataSize.of(2, DataUnit.KILOBYTES).toBytes() // 2000
+ * DataSize.of(2, DataUnit.KIBIBYTES).toBytes() // 2048
+ * DataSize.ofBytes(2048).to(DataUnit.KIBIBYTES) // 2
+ * DataSize.ofBytes(-1500).to(DataUnit.KILOBYTES) // -1
+ * }</pre>
+ *
+ * @since 3.23.0
+ * @see DataUnit
+ */
+public final class DataSize implements Comparable<DataSize>, Serializable {
+
+ /**
+ * A size of zero bytes.
+ */
+ public static final DataSize ZERO = new DataSize(0);
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Creates a data size from an amount in the specified unit.
+ *
+ * @param amount The amount, positive, zero, or negative.
+ * @param unit The unit of the amount, not null.
+ * @return The data size, not null.
+ * @throws ArithmeticException if the byte count overflows a {@code long}.
+ * @throws NullPointerException if {@code unit} is null.
+ */
+ public static DataSize of(final long amount, final DataUnit unit) {
+ return ofBytes(Math.multiplyExact(amount, Objects.requireNonNull(unit,
"unit").getBytes()));
+ }
+
+ /**
+ * Creates a data size from a byte count.
+ *
+ * @param bytes The byte count, positive, zero, or negative.
+ * @return The data size, not null.
+ */
+ public static DataSize ofBytes(final long bytes) {
+ return bytes == 0 ? ZERO : new DataSize(bytes);
+ }
+
+ /**
+ * The byte count.
+ */
+ private final long bytes;
+
+ /**
+ * Constructs a data size.
+ *
+ * @param bytes The byte count.
+ */
+ private DataSize(final long bytes) {
+ this.bytes = bytes;
+ }
+
+ /**
+ * Compares this data size with another by byte count.
+ *
+ * @param other The other data size, not null.
+ * @return A negative integer, zero, or a positive integer if this size is
less than, equal to, or greater than the other size.
+ * @throws NullPointerException if {@code other} is null.
+ */
+ @Override
+ public int compareTo(final DataSize other) {
+ return Long.compare(bytes, Objects.requireNonNull(other,
"other").bytes);
+ }
+
+ /**
+ * Tests whether another object is a data size with the same byte count.
+ *
+ * @param obj The object to compare with, may be null.
+ * @return Whether the object is an equal data size.
+ */
+ @Override
+ public boolean equals(final Object obj) {
+ return this == obj || obj instanceof DataSize && bytes == ((DataSize)
obj).bytes;
+ }
+
+ /**
+ * Computes a hash code from the byte count.
+ *
+ * @return The hash code.
+ */
+ @Override
+ public int hashCode() {
+ return Long.hashCode(bytes);
+ }
+
+ /**
+ * Tests whether this data size is negative.
+ *
+ * @return Whether the byte count is less than zero.
+ */
+ public boolean isNegative() {
+ return bytes < 0;
+ }
+
+ /**
+ * Tests whether this data size is zero.
+ *
+ * @return Whether the byte count is zero.
+ */
+ public boolean isZero() {
+ return bytes == 0;
+ }
+
+ /**
+ * Converts this data size to a whole number of the specified unit.
+ *
+ * <p>
+ * Any fractional part is discarded by truncating toward zero. For
example, 1500 bytes converts to 1 kilobyte, and -1500 bytes converts to -1
kilobyte.
+ * </p>
+ *
+ * @param unit The target unit, not null.
+ * @return The number of whole units.
+ * @throws NullPointerException if {@code unit} is null.
+ */
+ public long to(final DataUnit unit) {
+ return bytes / Objects.requireNonNull(unit, "unit").getBytes();
+ }
+
+ /**
+ * Gets the byte count.
+ *
+ * @return The byte count.
+ */
+ public long toBytes() {
+ return bytes;
+ }
+
+ /**
+ * Formats this data size as its decimal byte count followed by {@code B}.
+ *
+ * <p>
+ * The result is exact and independent of the locale and the unit used to
create this instance. For example, one kibibyte is formatted as {@code 1024B}.
+ * </p>
+ *
+ * @return The byte count followed by {@code B}.
+ */
+ @Override
+ public String toString() {
+ return bytes + DataUnit.BYTES.getSymbol();
+ }
+}
diff --git a/src/main/java/org/apache/commons/lang3/unit/DataUnit.java
b/src/main/java/org/apache/commons/lang3/unit/DataUnit.java
new file mode 100644
index 000000000..5414680ca
--- /dev/null
+++ b/src/main/java/org/apache/commons/lang3/unit/DataUnit.java
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file 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
+ *
+ * https://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 org.apache.commons.lang3.unit;
+
+/**
+ * Units of data size with distinct decimal and binary prefixes.
+ *
+ * <p>
+ * Decimal prefixes denote powers of 1000, and binary prefixes denote powers
of 1024. The symbols distinguish these units, for example {@code kB} for a
+ * kilobyte and {@code KiB} for a kibibyte. All units are whole multiples of a
byte. The supported prefixes extend through exa and exbi, whose byte counts
+ * fit in a {@code long}.
+ * </p>
+ *
+ * @since 3.23.0
+ * @see DataSize
+ */
+public enum DataUnit {
+
+ /**
+ * Bytes ({@code B}).
+ */
+ BYTES(1, "B"),
+
+ /**
+ * Kilobytes ({@code kB}), each containing 10<sup>3</sup> bytes.
+ */
+ KILOBYTES(1_000L, "kB"),
+
+ /**
+ * Megabytes ({@code MB}), each containing 10<sup>6</sup> bytes.
+ */
+ MEGABYTES(1_000_000L, "MB"),
+
+ /**
+ * Gigabytes ({@code GB}), each containing 10<sup>9</sup> bytes.
+ */
+ GIGABYTES(1_000_000_000L, "GB"),
+
+ /**
+ * Terabytes ({@code TB}), each containing 10<sup>12</sup> bytes.
+ */
+ TERABYTES(1_000_000_000_000L, "TB"),
+
+ /**
+ * Petabytes ({@code PB}), each containing 10<sup>15</sup> bytes.
+ */
+ PETABYTES(1_000_000_000_000_000L, "PB"),
+
+ /**
+ * Exabytes ({@code EB}), each containing 10<sup>18</sup> bytes.
+ */
+ EXABYTES(1_000_000_000_000_000_000L, "EB"),
+
+ /**
+ * Kibibytes ({@code KiB}), each containing 2<sup>10</sup> bytes.
+ */
+ KIBIBYTES(1L << 10, "KiB"),
+
+ /**
+ * Mebibytes ({@code MiB}), each containing 2<sup>20</sup> bytes.
+ */
+ MEBIBYTES(1L << 20, "MiB"),
+
+ /**
+ * Gibibytes ({@code GiB}), each containing 2<sup>30</sup> bytes.
+ */
+ GIBIBYTES(1L << 30, "GiB"),
+
+ /**
+ * Tebibytes ({@code TiB}), each containing 2<sup>40</sup> bytes.
+ */
+ TEBIBYTES(1L << 40, "TiB"),
+
+ /**
+ * Pebibytes ({@code PiB}), each containing 2<sup>50</sup> bytes.
+ */
+ PEBIBYTES(1L << 50, "PiB"),
+
+ /**
+ * Exbibytes ({@code EiB}), each containing 2<sup>60</sup> bytes.
+ */
+ EXBIBYTES(1L << 60, "EiB");
+
+ /**
+ * The number of bytes in one unit.
+ */
+ private final long bytes;
+
+ /**
+ * The unit symbol.
+ */
+ private final String symbol;
+
+ /**
+ * Constructs a data unit.
+ *
+ * @param bytes The number of bytes in one unit.
+ * @param symbol The unit symbol.
+ */
+ DataUnit(final long bytes, final String symbol) {
+ this.bytes = bytes;
+ this.symbol = symbol;
+ }
+
+ /**
+ * Gets the number of bytes in one unit.
+ *
+ * @return The number of bytes in one unit.
+ */
+ public long getBytes() {
+ return bytes;
+ }
+
+ /**
+ * Gets the unit symbol.
+ *
+ * @return The unit symbol, for example {@code kB} or {@code KiB}.
+ */
+ public String getSymbol() {
+ return symbol;
+ }
+}
diff --git a/src/main/java/org/apache/commons/lang3/unit/package-info.java
b/src/main/java/org/apache/commons/lang3/unit/package-info.java
new file mode 100644
index 000000000..13023e32f
--- /dev/null
+++ b/src/main/java/org/apache/commons/lang3/unit/package-info.java
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file 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
+ *
+ * https://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.
+ */
+
+/**
+ * Provides value types and units for measurements.
+ *
+ * <p>
+ * {@link org.apache.commons.lang3.unit.DataSize} represents a byte count, and
{@link org.apache.commons.lang3.unit.DataUnit} distinguishes decimal units,
+ * such as kilobytes, from binary units, such as kibibytes.
+ * </p>
+ *
+ * @since 3.23.0
+ */
+package org.apache.commons.lang3.unit;
diff --git a/src/test/java/org/apache/commons/lang3/unit/DataSizeTest.java
b/src/test/java/org/apache/commons/lang3/unit/DataSizeTest.java
new file mode 100644
index 000000000..68959e67e
--- /dev/null
+++ b/src/test/java/org/apache/commons/lang3/unit/DataSizeTest.java
@@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file 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
+ *
+ * https://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 org.apache.commons.lang3.unit;
+
+import static
org.apache.commons.lang3.LangAssertions.assertNullPointerException;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.math.BigInteger;
+import java.util.Locale;
+import java.util.Random;
+import java.util.stream.LongStream;
+
+import org.apache.commons.lang3.AbstractLangTest;
+import org.apache.commons.lang3.SerializationUtils;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.EnumSource.Mode;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.junitpioneer.jupiter.WritesDefaultLocale;
+
+/**
+ * Tests {@link DataSize}.
+ */
+class DataSizeTest extends AbstractLangTest {
+
+ /**
+ * Checks factory results and overflow against arbitrary-precision
multiplication.
+ *
+ * @param amount The amount in the specified unit.
+ * @param unit The unit of the amount.
+ */
+ private static void assertOfMatchesBigInteger(final long amount, final
DataUnit unit) {
+ final BigInteger expected =
BigInteger.valueOf(amount).multiply(BigInteger.valueOf(unit.getBytes()));
+ final String message = amount + " " + unit;
+ if (expected.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0 ||
expected.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
+ assertThrows(ArithmeticException.class, () -> DataSize.of(amount,
unit), message);
+ } else {
+ final DataSize size = DataSize.of(amount, unit);
+ assertEquals(expected.longValueExact(), size.toBytes(), message);
+ assertEquals(amount, size.to(unit), message);
+ }
+ }
+
+ /**
+ * Supplies values around every representable positive power of two and
both long limits.
+ *
+ * @return The distinct boundary byte counts in ascending order.
+ */
+ private static LongStream boundaryByteCounts() {
+ final LongStream limits = LongStream.of(Long.MIN_VALUE, Long.MIN_VALUE
+ 1, Long.MIN_VALUE + 2, Long.MAX_VALUE - 2, Long.MAX_VALUE - 1,
Long.MAX_VALUE);
+ final LongStream powersOfTwo = LongStream.rangeClosed(0,
62).flatMap(exponent -> {
+ final long power = 1L << exponent;
+ return LongStream.of(-power - 1, -power, -power + 1, power - 1,
power, power + 1);
+ });
+ return LongStream.concat(limits, powersOfTwo).distinct().sorted();
+ }
+
+ @ParameterizedTest
+ @ValueSource(longs = {Long.MIN_VALUE, Long.MIN_VALUE + 1, -(1L << 53) - 1,
-(1L << 53), (1L << 53) - 1, 1L << 53,
+ Long.MAX_VALUE - 2, Long.MAX_VALUE - 1})
+ void testAdjacentPrecisionBoundaries(final long bytes) {
+ final DataSize lower = DataSize.ofBytes(bytes);
+ final DataSize upper = DataSize.ofBytes(bytes + 1);
+ assertNotEquals(lower, upper);
+ assertNotEquals(upper, lower);
+ assertEquals(-1, Integer.signum(lower.compareTo(upper)));
+ assertEquals(1, Integer.signum(upper.compareTo(lower)));
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "-9223372036854775808, 9223372036854775807, -1",
+ "9223372036854775807, -9223372036854775808, 1",
+ "-9223372036854775808, -9223372036854775808, 0",
+ "9223372036854775807, 9223372036854775807, 0",
+ "-1, 0, -1",
+ "0, 1, -1",
+ "1, 0, 1",
+ "0, -1, 1",
+ "0, 0, 0"
+ })
+ void testCompareTo(final long first, final long second, final int
expected) {
+ assertEquals(expected,
Integer.signum(DataSize.ofBytes(first).compareTo(DataSize.ofBytes(second))));
+ }
+
+ @Test
+ void testCompareToNull() {
+ assertNullPointerException(() -> DataSize.ZERO.compareTo(null));
+ }
+
+ @Test
+ void testDecimalAndBinaryUnits() {
+ assertEquals(1000, DataSize.of(1, DataUnit.KILOBYTES).toBytes());
+ assertEquals(1024, DataSize.of(1, DataUnit.KIBIBYTES).toBytes());
+ assertNotEquals(DataSize.of(1, DataUnit.KILOBYTES), DataSize.of(1,
DataUnit.KIBIBYTES));
+ assertEquals(0, DataSize.of(1,
DataUnit.KILOBYTES).to(DataUnit.KIBIBYTES));
+ assertEquals(1, DataSize.of(1,
DataUnit.KIBIBYTES).to(DataUnit.KILOBYTES));
+ }
+
+ @Test
+ void testEqualsAndHashCode() {
+ final DataSize size = DataSize.of(1, DataUnit.KIBIBYTES);
+ final DataSize equal = DataSize.ofBytes(1024);
+ assertEquals(size, size);
+ assertEquals(size, equal);
+ assertEquals(equal, size);
+ assertEquals(size.hashCode(), equal.hashCode());
+ assertEquals(0, size.compareTo(equal));
+ assertEquals(DataSize.of(128, DataUnit.KIBIBYTES),
DataSize.ofBytes(131072));
+ assertNotEquals(size, DataSize.of(1, DataUnit.KILOBYTES));
+ assertNotEquals(size, DataSize.ofBytes(-1024));
+ assertNotEquals(size, DataSize.ofBytes((1L << 32) + 1024));
+ assertNotEquals(size, null);
+ assertNotEquals(size, "1024B");
+ assertNotEquals(DataSize.ofBytes(Long.MIN_VALUE),
DataSize.ofBytes(Long.MAX_VALUE));
+ }
+
+ @ParameterizedTest
+ @MethodSource("boundaryByteCounts")
+ void testIsNegativeAndIsZero(final long bytes) {
+ final DataSize size = DataSize.ofBytes(bytes);
+ assertEquals(bytes < 0, size.isNegative());
+ assertEquals(bytes == 0, size.isZero());
+ }
+
+ @ParameterizedTest
+ @EnumSource(DataUnit.class)
+ void testOf(final DataUnit unit) {
+ final BigInteger factor = BigInteger.valueOf(unit.getBytes());
+ for (final long amount : new long[] {-7, -1, 0, 1, 7}) {
+ final DataSize size = DataSize.of(amount, unit);
+
assertEquals(factor.multiply(BigInteger.valueOf(amount)).longValueExact(),
size.toBytes());
+ assertEquals(amount, size.to(unit));
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(value = DataUnit.class, names = "BYTES", mode = Mode.EXCLUDE)
+ void testOfBoundaries(final DataUnit unit) {
+ final BigInteger factor = BigInteger.valueOf(unit.getBytes());
+ final long minimum =
BigInteger.valueOf(Long.MIN_VALUE).divide(factor).longValueExact();
+ final long maximum =
BigInteger.valueOf(Long.MAX_VALUE).divide(factor).longValueExact();
+
assertEquals(BigInteger.valueOf(minimum).multiply(factor).longValueExact(),
DataSize.of(minimum, unit).toBytes());
+
assertEquals(BigInteger.valueOf(maximum).multiply(factor).longValueExact(),
DataSize.of(maximum, unit).toBytes());
+ assertThrows(ArithmeticException.class, () -> DataSize.of(minimum - 1,
unit));
+ assertThrows(ArithmeticException.class, () -> DataSize.of(maximum + 1,
unit));
+ assertThrows(ArithmeticException.class, () ->
DataSize.of(Long.MIN_VALUE, unit));
+ assertThrows(ArithmeticException.class, () ->
DataSize.of(Long.MAX_VALUE, unit));
+ }
+
+ @ParameterizedTest
+ @MethodSource("boundaryByteCounts")
+ void testOfBytes(final long bytes) {
+ assertEquals(bytes, DataSize.ofBytes(bytes).toBytes());
+ assertEquals(bytes, DataSize.of(bytes, DataUnit.BYTES).toBytes());
+ }
+
+ @ParameterizedTest
+ @ValueSource(longs = {Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE})
+ void testOfNullUnit(final long amount) {
+ assertNullPointerException(() -> DataSize.of(amount, null));
+ }
+
+ @ParameterizedTest
+ @EnumSource(DataUnit.class)
+ void testPrecisionBoundaries(final DataUnit unit) {
+ final BigInteger factor = BigInteger.valueOf(unit.getBytes());
+ for (final long bytes : boundaryByteCounts().toArray()) {
+ assertOfMatchesBigInteger(bytes, unit);
+ final long expected =
BigInteger.valueOf(bytes).divide(factor).longValueExact();
+ assertEquals(expected, DataSize.ofBytes(bytes).to(unit), () ->
bytes + " bytes to " + unit);
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(DataUnit.class)
+ void testSamplesAgainstBigInteger(final DataUnit unit) {
+ // A fixed seed makes failures reproducible and gives every unit the
same full-width samples.
+ final Random random = new Random(0xDA7A51E);
+ final BigInteger factor = BigInteger.valueOf(unit.getBytes());
+ for (int i = 0; i < 256; i++) {
+ final long bytes = random.nextLong();
+ final long expected =
BigInteger.valueOf(bytes).divide(factor).longValueExact();
+ assertEquals(expected, DataSize.ofBytes(bytes).to(unit), () ->
bytes + " bytes to " + unit);
+ assertOfMatchesBigInteger(bytes, unit);
+ // Scale the sample into the representable range so large units
also exercise successful construction.
+ assertOfMatchesBigInteger(expected, unit);
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("boundaryByteCounts")
+ void testSerialization(final long bytes) {
+ final DataSize size = DataSize.ofBytes(bytes);
+ final DataSize copy = SerializationUtils.roundtrip(size);
+ assertEquals(size, copy);
+ assertEquals(size.hashCode(), copy.hashCode());
+ assertEquals(0, size.compareTo(copy));
+ assertEquals(bytes, copy.toBytes());
+ }
+
+ @ParameterizedTest
+ @EnumSource(DataUnit.class)
+ void testTo(final DataUnit unit) {
+ final long factor = unit.getBytes();
+ for (final long bytes : new long[] {Long.MIN_VALUE, -factor - 1,
-factor, -factor + 1, -1, 0, 1, factor - 1, factor, factor + 1,
Long.MAX_VALUE}) {
+ final long expected =
BigInteger.valueOf(bytes).divide(BigInteger.valueOf(factor)).longValueExact();
+ assertEquals(expected, DataSize.ofBytes(bytes).to(unit), () ->
bytes + " bytes to " + unit);
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(DataUnit.class)
+ void testToBetweenUnits(final DataUnit source) {
+ for (final DataUnit target : DataUnit.values()) {
+ for (final long amount : new long[] {-7, -1, 0, 1, 7}) {
+ final long expected =
BigInteger.valueOf(amount).multiply(BigInteger.valueOf(source.getBytes()))
+
.divide(BigInteger.valueOf(target.getBytes())).longValueExact();
+ assertEquals(expected, DataSize.of(amount, source).to(target),
() -> amount + " " + source + " to " + target);
+ }
+ }
+ }
+
+ @Test
+ void testToNullUnit() {
+ assertNullPointerException(() -> DataSize.ZERO.to(null));
+ assertNullPointerException(() -> DataSize.ofBytes(1).to(null));
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "-9223372036854775808, -9223372036854775808B",
+ "-1024, -1024B",
+ "0, 0B",
+ "1024, 1024B",
+ "9223372036854775807, 9223372036854775807B"
+ })
+ void testToString(final long bytes, final String expected) {
+ assertEquals(expected, DataSize.ofBytes(bytes).toString());
+ }
+
+ @Test
+ @WritesDefaultLocale
+ void testToStringIndependentOfLocale() {
+ final Locale defaultLocale = Locale.getDefault();
+ final Locale displayLocale =
Locale.getDefault(Locale.Category.DISPLAY);
+ final Locale formatLocale = Locale.getDefault(Locale.Category.FORMAT);
+ try {
+ Locale.setDefault(Locale.forLanguageTag("ar-EG"));
+ for (final long bytes : boundaryByteCounts().toArray()) {
+ assertEquals(BigInteger.valueOf(bytes).toString() + "B",
DataSize.ofBytes(bytes).toString());
+ }
+ assertEquals("1000000B", DataSize.of(1,
DataUnit.MEGABYTES).toString());
+ assertEquals("1048576B", DataSize.of(1,
DataUnit.MEBIBYTES).toString());
+ } finally {
+ // Restore the category-specific defaults after the general
default, which resets both categories.
+ Locale.setDefault(defaultLocale);
+ Locale.setDefault(Locale.Category.DISPLAY, displayLocale);
+ Locale.setDefault(Locale.Category.FORMAT, formatLocale);
+ }
+ }
+
+ @Test
+ void testToStringIndependentOfUnit() {
+ assertEquals("1000B", DataSize.of(1, DataUnit.KILOBYTES).toString());
+ assertEquals("1024B", DataSize.of(1, DataUnit.KIBIBYTES).toString());
+ assertEquals("1000000B", DataSize.of(1000,
DataUnit.KILOBYTES).toString());
+ assertEquals("1000000B", DataSize.of(1,
DataUnit.MEGABYTES).toString());
+ }
+
+ @ParameterizedTest
+ @EnumSource(DataUnit.class)
+ void testZero(final DataUnit unit) {
+ assertEquals(0, DataSize.ZERO.toBytes());
+ assertEquals(0, DataSize.ZERO.to(unit));
+ assertSame(DataSize.ZERO, DataSize.of(0, unit));
+ assertSame(DataSize.ZERO, DataSize.ofBytes(0));
+ }
+}
diff --git a/src/test/java/org/apache/commons/lang3/unit/DataUnitTest.java
b/src/test/java/org/apache/commons/lang3/unit/DataUnitTest.java
new file mode 100644
index 000000000..27db93933
--- /dev/null
+++ b/src/test/java/org/apache/commons/lang3/unit/DataUnitTest.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file 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
+ *
+ * https://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 org.apache.commons.lang3.unit;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.apache.commons.lang3.AbstractLangTest;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+/**
+ * Tests {@link DataUnit}.
+ */
+class DataUnitTest extends AbstractLangTest {
+
+ @ParameterizedTest
+ @CsvSource({
+ "BYTES, 1, B",
+ "KILOBYTES, 1000, kB",
+ "MEGABYTES, 1000000, MB",
+ "GIGABYTES, 1000000000, GB",
+ "TERABYTES, 1000000000000, TB",
+ "PETABYTES, 1000000000000000, PB",
+ "EXABYTES, 1000000000000000000, EB",
+ "KIBIBYTES, 1024, KiB",
+ "MEBIBYTES, 1048576, MiB",
+ "GIBIBYTES, 1073741824, GiB",
+ "TEBIBYTES, 1099511627776, TiB",
+ "PEBIBYTES, 1125899906842624, PiB",
+ "EXBIBYTES, 1152921504606846976, EiB"
+ })
+ void testUnits(final DataUnit unit, final long bytes, final String symbol)
{
+ assertEquals(bytes, unit.getBytes());
+ assertEquals(symbol, unit.getSymbol());
+ }
+}