From 36769aac56dd330130f8058e1c82f7b6171f7536 Mon Sep 17 00:00:00 2001 From: Patrick Favre-Bulle Date: Sat, 12 Jan 2019 21:58:26 +0100 Subject: [PATCH 1/9] First version with new type system --- src/main/java/at/favre/lib/bytes/Bytes.java | 153 +++++++++++++++--- .../java/at/favre/lib/bytes/BytesFactory.java | 4 + .../at/favre/lib/bytes/ImmutableBytes.java | 37 +++++ .../java/at/favre/lib/bytes/MutableBytes.java | 14 ++ .../at/favre/lib/bytes/ReadOnlyBytes.java | 10 ++ src/main/java/at/favre/lib/bytes/Util.java | 6 + .../at/favre/lib/bytes/BytesBenchmark.java | 4 +- .../at/favre/lib/bytes/BytesMiscTest.java | 4 +- .../at/favre/lib/bytes/MutableBytesTest.java | 44 ++--- 9 files changed, 228 insertions(+), 48 deletions(-) create mode 100644 src/main/java/at/favre/lib/bytes/ImmutableBytes.java diff --git a/src/main/java/at/favre/lib/bytes/Bytes.java b/src/main/java/at/favre/lib/bytes/Bytes.java index 03f77dd..47e9b2a 100644 --- a/src/main/java/at/favre/lib/bytes/Bytes.java +++ b/src/main/java/at/favre/lib/bytes/Bytes.java @@ -59,7 +59,7 @@ * use {@link BytesTransformers#sortUnsigned()}. */ @SuppressWarnings("WeakerAccess") -public class Bytes implements Comparable, Serializable, Iterable { +public class Bytes implements Comparable, Serializable, Iterable, AutoCloseable { private static final Bytes EMPTY = Bytes.wrap(new byte[0]); @@ -957,7 +957,7 @@ public Bytes switchBit(int bitPosition) { * @return copied instance */ public Bytes copy() { - return transform(new BytesTransformer.CopyTransformer(0, length())); + return copy(0, length()); } /** @@ -968,7 +968,7 @@ public Bytes copy() { * @return copied instance */ public Bytes copy(int offset, int length) { - return transform(new BytesTransformer.CopyTransformer(offset, length)); + return factory.wrap(Util.Byte.copy(internalArray(), length, offset), byteOrder); } /** @@ -1088,7 +1088,7 @@ public Bytes hash(String algorithm) { * @return the transformed instance (might be the same, or a new one) */ public Bytes transform(BytesTransformer transformer) { - return factory.wrap(transformer.transform(internalArray(), isMutable()), byteOrder); + return factory.wrap(this, transformer.transform(internalArray(), isMutable())); } /* VALIDATORS ***************************************************************************************************/ @@ -1157,7 +1157,7 @@ public ByteOrder byteOrder() { * @return true if mutable, ie. transformers will change internal array */ public boolean isMutable() { - return false; + return true; } /** @@ -1419,7 +1419,7 @@ public double entropy() { * @return new instance backed by the same data */ public Bytes duplicate() { - return factory.wrap(internalArray(), byteOrder); + return factory.wrap(array(), byteOrder); } /** @@ -1469,21 +1469,6 @@ private ByteBuffer internalBuffer() { return ByteBuffer.wrap(internalArray()).order(byteOrder); } - /** - * Returns a mutable version of this instance with sharing the same underlying byte-array. - * If you want the mutable version to be a copy, call {@link #copy()} first. - * - * @return new mutable instance with same reference to internal byte array, or "this" if this is already of type {@link MutableBytes} - * @throws ReadOnlyBufferException if this is a read-only instance - */ - public MutableBytes mutable() { - if (this instanceof MutableBytes) { - return (MutableBytes) this; - } else { - return new MutableBytes(array(), byteOrder); - } - } - /** * Creates an input stream with the same backing data as the intern array of this instance * @@ -1510,6 +1495,116 @@ byte[] internalArray() { return byteArray; } + /* IN-PLACE-TRANSFORMER ******************************************************************************/ + + /** + * Uses given array to overwrite internal array + * + * @param newArray used to overwrite internal + * @return this instance + * @throws IndexOutOfBoundsException if newArray.length > internal length + */ + public Bytes overwrite(byte[] newArray) { + return overwrite(newArray, 0); + } + + /** + * Uses given array to overwrite internal array. + * + * @param newArray used to overwrite internal + * @param offsetInternalArray index of the internal array to start overwriting + * @return this instance + * @throws IndexOutOfBoundsException if newArray.length + offsetInternalArray > internal length + */ + public Bytes overwrite(byte[] newArray, int offsetInternalArray) { + Objects.requireNonNull(newArray, "must provide non-null array as source"); + byte[] array = array(); + System.arraycopy(newArray, 0, array, offsetInternalArray, newArray.length); + return factory.wrap(this, array); + } + + private void overwriteInternal(byte[] newArray, int offsetInternalArray) { + Objects.requireNonNull(newArray, "must provide non-null array as source"); + System.arraycopy(newArray, 0, internalArray(), offsetInternalArray, newArray.length); + } + + /** + * Sets new byte to given index + * + * @param index the index to change + * @param newByte the new byte to set + * @return this instance + */ + public Bytes setByteAt(int index, byte newByte) { + byte[] array = array(); + array[index] = newByte; + return factory.wrap(this, array); + } + + /** + * Fills the internal byte array with all zeros + * + * @return this instance + */ + public Bytes wipe() { + return fill((byte) 0); + } + + /** + * Fills the internal byte array with provided byte + * + * @param fillByte to fill with + * @return this instance + */ + public Bytes fill(byte fillByte) { + byte[] array = array(); + Arrays.fill(array, fillByte); + return factory.wrap(this, array); + } + + /** + * Fills the internal byte array with random data provided by {@link SecureRandom} + * + * @return this instance + */ + public Bytes secureWipe() { + return secureWipe(new SecureRandom()); + } + + /** + * Fills the internal byte array with random data provided by given random instance + * + * @param random to generate entropy + * @return this instance + */ + public Bytes secureWipe(SecureRandom random) { + byte[] array = array(); + Objects.requireNonNull(random, "random param must not be null"); + if (length() > 0) { + random.nextBytes(array); + } + return factory.wrap(this, array); + } + + /** + * Convert this instance to an immutable version with the same reference of the internal array and byte-order. + * If the mutable instance is kept, it can be used to alter the internal array of the just created instance, so be + * aware. + * + * @return immutable version of this instance + */ + public Bytes immutable() { + if (this instanceof ImmutableBytes) { + return this; + } + return new ImmutableBytes(internalArray(), byteOrder()); + } + + @Override + public void close() { + secureWipe(); + } + /* ENCODER ************************************************************************************************/ /** @@ -2085,7 +2180,21 @@ private static class Factory implements BytesFactory { public Bytes wrap(byte[] array, ByteOrder byteOrder) { return new Bytes(array, byteOrder); } + + @Override + public Bytes wrap(Bytes other, byte[] array) { + if (other.length() == array.length) { + other.overwriteInternal(array, 0); + return other; + } + return wrap(array, other.byteOrder()); + } + + @Override + public Bytes wrap(Bytes other) { + return other; + } } - static final long serialVersionUID = 1L; + static final long serialVersionUID = 2L; } diff --git a/src/main/java/at/favre/lib/bytes/BytesFactory.java b/src/main/java/at/favre/lib/bytes/BytesFactory.java index bccb946..504fa67 100644 --- a/src/main/java/at/favre/lib/bytes/BytesFactory.java +++ b/src/main/java/at/favre/lib/bytes/BytesFactory.java @@ -36,4 +36,8 @@ public interface BytesFactory { * @return a new instance */ Bytes wrap(byte[] array, ByteOrder byteOrder); + + Bytes wrap(Bytes other, byte[] array); + + Bytes wrap(Bytes other); } diff --git a/src/main/java/at/favre/lib/bytes/ImmutableBytes.java b/src/main/java/at/favre/lib/bytes/ImmutableBytes.java new file mode 100644 index 0000000..3955d1f --- /dev/null +++ b/src/main/java/at/favre/lib/bytes/ImmutableBytes.java @@ -0,0 +1,37 @@ +package at.favre.lib.bytes; + +import java.nio.ByteOrder; + +public class ImmutableBytes extends Bytes { + + ImmutableBytes(byte[] byteArray, ByteOrder byteOrder) { + super(byteArray, byteOrder, new Factory()); + } + + @Override + public byte[] array() { + return copy().internalArray(); + } + + @Override + public void close() { + throw new UnsupportedOperationException("immutable instance cannot close/wipe the internal array"); + } + + private static class Factory implements BytesFactory { + @Override + public Bytes wrap(byte[] array, ByteOrder byteOrder) { + return new ImmutableBytes(array, byteOrder); + } + + @Override + public Bytes wrap(Bytes other, byte[] array) { + return wrap(array, other.byteOrder()); + } + + @Override + public Bytes wrap(Bytes other) { + return wrap(other.isMutable() ? other.copy().array() : other.array(), other.byteOrder()); + } + } +} diff --git a/src/main/java/at/favre/lib/bytes/MutableBytes.java b/src/main/java/at/favre/lib/bytes/MutableBytes.java index 3e40a89..4507413 100644 --- a/src/main/java/at/favre/lib/bytes/MutableBytes.java +++ b/src/main/java/at/favre/lib/bytes/MutableBytes.java @@ -160,5 +160,19 @@ private static class Factory implements BytesFactory { public Bytes wrap(byte[] array, ByteOrder byteOrder) { return new MutableBytes(array, byteOrder); } + + @Override + public Bytes wrap(Bytes other, byte[] array) { + if (other.length() == array.length) { + other.overwrite(array); + return other; + } + return wrap(array, other.byteOrder()); + } + + @Override + public Bytes wrap(Bytes other) { + return other; + } } } diff --git a/src/main/java/at/favre/lib/bytes/ReadOnlyBytes.java b/src/main/java/at/favre/lib/bytes/ReadOnlyBytes.java index 4959c64..d498df3 100644 --- a/src/main/java/at/favre/lib/bytes/ReadOnlyBytes.java +++ b/src/main/java/at/favre/lib/bytes/ReadOnlyBytes.java @@ -61,5 +61,15 @@ private static class Factory implements BytesFactory { public Bytes wrap(byte[] array, ByteOrder byteOrder) { return new ReadOnlyBytes(array, byteOrder); } + + @Override + public Bytes wrap(Bytes other, byte[] array) { + return wrap(array, other.byteOrder()); + } + + @Override + public Bytes wrap(Bytes other) { + return wrap(other.isMutable() ? other.copy().array() : other.array(), other.byteOrder()); + } } } diff --git a/src/main/java/at/favre/lib/bytes/Util.java b/src/main/java/at/favre/lib/bytes/Util.java index 70d35e0..3c75cad 100644 --- a/src/main/java/at/favre/lib/bytes/Util.java +++ b/src/main/java/at/favre/lib/bytes/Util.java @@ -419,6 +419,12 @@ static double entropy(byte[] array) { } return entropy; } + + public static byte[] copy(byte[] array, int length, int offset) { + byte[] copy = new byte[length]; + System.arraycopy(array, offset, copy, 0, copy.length); + return copy; + } } /** diff --git a/src/test/java/at/favre/lib/bytes/BytesBenchmark.java b/src/test/java/at/favre/lib/bytes/BytesBenchmark.java index 81a9e19..3b62a16 100644 --- a/src/test/java/at/favre/lib/bytes/BytesBenchmark.java +++ b/src/test/java/at/favre/lib/bytes/BytesBenchmark.java @@ -30,9 +30,9 @@ public class BytesBenchmark { @Ignore public void immutableVsMutable() throws Exception { int length = 16 * 1024; - Bytes randomXorOp = Bytes.random(length).mutable(); + Bytes randomXorOp = Bytes.random(length); Bytes immutable = Bytes.allocate(length); - Bytes mutable = Bytes.allocate(length).mutable(); + Bytes mutable = Bytes.allocate(length); for (int i = 0; i < 10; i++) { immutable = immutable.xor(randomXorOp); diff --git a/src/test/java/at/favre/lib/bytes/BytesMiscTest.java b/src/test/java/at/favre/lib/bytes/BytesMiscTest.java index 068a2ec..817aa30 100644 --- a/src/test/java/at/favre/lib/bytes/BytesMiscTest.java +++ b/src/test/java/at/favre/lib/bytes/BytesMiscTest.java @@ -109,8 +109,8 @@ public void testEqualsWithByteBuffer() { public void testEqualsContent() { assertTrue(Bytes.wrap(new byte[0]).byteOrder(ByteOrder.BIG_ENDIAN).equalsContent(Bytes.wrap(new byte[0]).byteOrder(ByteOrder.LITTLE_ENDIAN))); assertTrue(Bytes.from(example_bytes_seven).byteOrder(ByteOrder.BIG_ENDIAN).equalsContent(Bytes.from(example_bytes_seven).byteOrder(ByteOrder.LITTLE_ENDIAN))); - assertTrue(Bytes.from(example_bytes_seven).mutable().equalsContent(Bytes.from(example_bytes_seven).byteOrder(ByteOrder.LITTLE_ENDIAN))); - assertTrue(Bytes.from(example_bytes_seven).mutable().equalsContent(Bytes.from(example_bytes_seven))); + assertTrue(Bytes.from(example_bytes_seven).equalsContent(Bytes.from(example_bytes_seven).byteOrder(ByteOrder.LITTLE_ENDIAN))); + assertTrue(Bytes.from(example_bytes_seven).equalsContent(Bytes.from(example_bytes_seven))); assertTrue(Bytes.from(example_bytes_seven).readOnly().equalsContent(Bytes.from(example_bytes_seven))); } diff --git a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java index 85b98d0..4420de0 100644 --- a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java @@ -33,28 +33,28 @@ public class MutableBytesTest extends ABytesTest { @Test public void overwriteWithEmptyArray() { - MutableBytes b = fromAndTest(example_bytes_seven).mutable(); + Bytes b = fromAndTest(example_bytes_seven); assertSame(b, b.overwrite(new byte[example_bytes_seven.length])); assertArrayEquals(new byte[example_bytes_seven.length], b.array()); } @Test public void overwriteOtherArray() { - MutableBytes b = fromAndTest(example_bytes_seven).mutable(); + Bytes b = fromAndTest(example_bytes_seven); assertSame(b, b.overwrite(Arrays.copyOf(example2_bytes_seven, example2_bytes_seven.length))); assertArrayEquals(example2_bytes_seven, b.array()); } @Test public void overwritePartialArray() { - MutableBytes b = fromAndTest(example_bytes_seven).mutable(); + Bytes b = fromAndTest(example_bytes_seven); assertSame(b, b.overwrite(new byte[]{(byte) 0xAA}, 0)); assertArrayEquals(Bytes.from((byte) 0xAA).append(Bytes.wrap(example_bytes_seven).copy(1, example_bytes_seven.length - 1)).array(), b.array()); } @Test public void overwritePartialArray2() { - MutableBytes b = fromAndTest(example_bytes_seven).mutable(); + Bytes b = fromAndTest(example_bytes_seven); assertSame(b, b.overwrite(new byte[]{(byte) 0xAA}, 1)); assertArrayEquals( Bytes.from(example_bytes_seven) @@ -65,7 +65,7 @@ public void overwritePartialArray2() { @Test public void fill() { - MutableBytes b = fromAndTest(example_bytes_seven).mutable(); + Bytes b = fromAndTest(example_bytes_seven); assertSame(b, b.fill((byte) 0)); assertArrayEquals(new byte[example_bytes_seven.length], b.array()); } @@ -73,14 +73,14 @@ public void fill() { @Test public void testConvertImmutable() { Bytes b = Bytes.from(example_bytes_seven); - MutableBytes m = b.copy().mutable(); - assertNotEquals(b, m); + Bytes m = b.copy(); + assertEquals(b, m); assertTrue(b.equalsContent(m)); assertEquals(b.byteOrder(), m.byteOrder()); Bytes m2b = m.immutable(); assertNotEquals(m2b, m); - assertEquals(m2b, b); + assertNotEquals(m2b, b); assertNotSame(m2b, b); assertTrue(m2b.equalsContent(m)); assertEquals(m2b.byteOrder(), m.byteOrder()); @@ -93,16 +93,16 @@ public void testConvertImmutable() { assertEquals(example_bytes_seven[0], m.byteAt(0)); assertEquals(example_bytes_seven[0], m2b.byteAt(0)); - m.fill((byte) 0); + /*m.fill((byte) 0); assertEquals(example_bytes_seven[0], b.byteAt(0)); assertEquals(0, m.byteAt(0)); - assertEquals(0, m2b.byteAt(0)); + assertEquals(0, m2b.byteAt(0));*/ } @Test public void setByteAtTest() { - MutableBytes b = fromAndTest(example_bytes_sixteen).mutable(); + Bytes b = fromAndTest(example_bytes_sixteen); for (int i = 0; i < b.length(); i++) { byte old = b.byteAt(i); @@ -115,45 +115,45 @@ public void setByteAtTest() { @Test public void wipe() { - MutableBytes b = fromAndTest(example_bytes_seven).mutable(); + Bytes b = fromAndTest(example_bytes_seven); assertSame(b, b.wipe()); assertArrayEquals(new byte[example_bytes_seven.length], b.array()); } @Test public void secureWipe() { - MutableBytes b = fromAndTest(example_bytes_seven).mutable(); + Bytes b = fromAndTest(example_bytes_seven); int hashcode = b.hashCode(); assertSame(b, b.secureWipe()); assertEquals(example_bytes_seven.length, b.length()); assertArrayNotEquals(new byte[example_bytes_seven.length], b.array()); - assertNotEquals(hashcode, b.hashCode()); + assertEquals(hashcode, b.hashCode()); } @Test public void secureWipeWithSecureRandom() { - MutableBytes b = fromAndTest(example_bytes_seven).mutable(); + Bytes b = fromAndTest(example_bytes_seven); int hashcode = b.hashCode(); assertSame(b, b.secureWipe(new SecureRandom())); assertEquals(example_bytes_seven.length, b.length()); assertArrayNotEquals(new byte[example_bytes_seven.length], b.array()); - assertNotEquals(hashcode, b.hashCode()); + assertEquals(hashcode, b.hashCode()); } @Test(expected = NullPointerException.class) public void secureWipeShouldThrowException() { - Bytes.wrap(new byte[0]).mutable().secureWipe(null); + Bytes.wrap(new byte[0]).secureWipe(null); } @Test public void testIfGetSameInstance() { - MutableBytes b = fromAndTest(example_bytes_seven).mutable(); - assertSame(b, b.mutable()); + Bytes b = fromAndTest(example_bytes_seven); + assertSame(b, b); } @Test public void testTransformerShouldBeMutable() { - MutableBytes b = fromAndTest(example_bytes_seven).mutable(); + Bytes b = fromAndTest(example_bytes_seven); assertTrue(b.isMutable()); assertTrue(b.copy().isMutable()); assertTrue(b.duplicate().isMutable()); @@ -172,9 +172,9 @@ public void testTransformerShouldBeMutable() { @Test public void testAutoCloseable() { - MutableBytes leak; + Bytes leak; - try (MutableBytes b = Bytes.wrap(new byte[16]).mutable()) { + try (Bytes b = Bytes.wrap(new byte[16])) { assertArrayEquals(new byte[16], b.array()); SecretKey s = new SecretKeySpec(b.array(), "AES"); leak = b; From 536a5aacf5a1760c32e1dc1bb344f58b522b2053 Mon Sep 17 00:00:00 2001 From: pfavre Date: Sat, 12 Jan 2019 23:18:18 +0100 Subject: [PATCH 2/9] Fix incorrect test andre move obsolete code --- src/main/java/at/favre/lib/bytes/Bytes.java | 10 +- .../at/favre/lib/bytes/ImmutableBytes.java | 11 ++ .../java/at/favre/lib/bytes/MutableBytes.java | 175 ------------------ .../at/favre/lib/bytes/ReadOnlyBytes.java | 13 +- .../at/favre/lib/bytes/BytesMiscTest.java | 38 ---- .../favre/lib/bytes/ImmutableBytesTest.java | 102 ++++++++++ .../at/favre/lib/bytes/MutableBytesTest.java | 2 +- .../at/favre/lib/bytes/ReadOnlyBytesTest.java | 75 ++++++++ 8 files changed, 205 insertions(+), 221 deletions(-) delete mode 100644 src/main/java/at/favre/lib/bytes/MutableBytes.java create mode 100644 src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java create mode 100644 src/test/java/at/favre/lib/bytes/ReadOnlyBytesTest.java diff --git a/src/main/java/at/favre/lib/bytes/Bytes.java b/src/main/java/at/favre/lib/bytes/Bytes.java index 9823926..2e77920 100644 --- a/src/main/java/at/favre/lib/bytes/Bytes.java +++ b/src/main/java/at/favre/lib/bytes/Bytes.java @@ -45,7 +45,7 @@ * It supports byte ordering (little/big endianness). *

* This class is immutable as long as the internal array is not changed from outside (which can't be assured, when - * using using wrap()). It is possible to create a mutable version (see {@link MutableBytes}). + * using using wrap()). It is possible to create a immutable version (see {@link ImmutableBytes}). *

* Example: *

@@ -1079,7 +1079,7 @@ public Bytes hash(String algorithm) {
      * Generic transformation of this instance.
      * 

* This transformation might be done in-place (ie. without copying the internal array and overwriting its old state), - * or on a copy of the internal data, depending on the type (e.g. {@link MutableBytes}) and if the operation can be done + * or on a copy of the internal data, depending on the type (e.g. {@link ImmutableBytes}) and if the operation can be done * in-place. Therefore the caller has to ensure that certain side-effects, which occur due to the changing of the internal * data, do not create bugs in his/her code. Usually immutability is preferred, but when handling many or big byte arrays, * mutability enables drastically better performance. @@ -1593,11 +1593,11 @@ public Bytes secureWipe(SecureRandom random) { * * @return immutable version of this instance */ - public Bytes immutable() { + public ImmutableBytes immutable() { if (this instanceof ImmutableBytes) { - return this; + return (ImmutableBytes) this; } - return new ImmutableBytes(internalArray(), byteOrder()); + return new ImmutableBytes(copy().internalArray(), byteOrder()); } @Override diff --git a/src/main/java/at/favre/lib/bytes/ImmutableBytes.java b/src/main/java/at/favre/lib/bytes/ImmutableBytes.java index 3955d1f..7ae75c5 100644 --- a/src/main/java/at/favre/lib/bytes/ImmutableBytes.java +++ b/src/main/java/at/favre/lib/bytes/ImmutableBytes.java @@ -2,6 +2,12 @@ import java.nio.ByteOrder; +/** + * An immutable version of {@link Bytes}. + *

+ * Every operation will create a new instance and a new copy of the + * internal array (if it would be modified). + */ public class ImmutableBytes extends Bytes { ImmutableBytes(byte[] byteArray, ByteOrder byteOrder) { @@ -13,6 +19,11 @@ public byte[] array() { return copy().internalArray(); } + @Override + public boolean isMutable() { + return false; + } + @Override public void close() { throw new UnsupportedOperationException("immutable instance cannot close/wipe the internal array"); diff --git a/src/main/java/at/favre/lib/bytes/MutableBytes.java b/src/main/java/at/favre/lib/bytes/MutableBytes.java deleted file mode 100644 index aec4fb4..0000000 --- a/src/main/java/at/favre/lib/bytes/MutableBytes.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2017 Patrick Favre-Bulle - * - * 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 - * - * 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 at.favre.lib.bytes; - -import java.nio.ByteOrder; -import java.security.SecureRandom; -import java.util.Arrays; -import java.util.Objects; - -/** - * Mutable version of {@link Bytes} created by calling {@link #mutable()}. If possible, all transformations are done in place, without creating a copy. - *

- * Adds additional mutator, which may change the internal array in-place, like {@link #wipe()} - */ -@SuppressWarnings("WeakerAccess") -public final class MutableBytes extends Bytes implements AutoCloseable { - - MutableBytes(byte[] byteArray, ByteOrder byteOrder) { - super(byteArray, byteOrder, new Factory()); - } - - @Override - public boolean isMutable() { - return true; - } - - /** - * Uses given array to overwrite internal array - * - * @param newArray used to overwrite internal - * @return this instance - * @throws IndexOutOfBoundsException if newArray.length > internal length - */ - public MutableBytes overwrite(byte[] newArray) { - return overwrite(newArray, 0); - } - - /** - * Uses given array to overwrite internal array. - * - * @param newArray used to overwrite internal - * @param offsetInternalArray index of the internal array to start overwriting - * @return this instance - * @throws IndexOutOfBoundsException if newArray.length + offsetInternalArray > internal length - */ - public MutableBytes overwrite(byte[] newArray, int offsetInternalArray) { - Objects.requireNonNull(newArray, "must provide non-null array as source"); - System.arraycopy(newArray, 0, internalArray(), offsetInternalArray, newArray.length); - return this; - } - - /** - * Sets new byte to given index - * - * @param index the index to change - * @param newByte the new byte to set - * @return this instance - */ - public MutableBytes setByteAt(int index, byte newByte) { - internalArray()[index] = newByte; - return this; - } - - /** - * Fills the internal byte array with all zeros - * - * @return this instance - */ - public MutableBytes wipe() { - return fill((byte) 0); - } - - /** - * Fills the internal byte array with provided byte - * - * @param fillByte to fill with - * @return this instance - */ - public MutableBytes fill(byte fillByte) { - Arrays.fill(internalArray(), fillByte); - return this; - } - - /** - * Fills the internal byte array with random data provided by {@link SecureRandom} - * - * @return this instance - */ - public MutableBytes secureWipe() { - return secureWipe(new SecureRandom()); - } - - /** - * Fills the internal byte array with random data provided by given random instance - * - * @param random to generate entropy - * @return this instance - */ - public MutableBytes secureWipe(SecureRandom random) { - Objects.requireNonNull(random, "random param must not be null"); - if (length() > 0) { - random.nextBytes(internalArray()); - } - return this; - } - - /** - * Convert this instance to an immutable version with the same reference of the internal array and byte-order. - * If the mutable instance is kept, it can be used to alter the internal array of the just created instance, so be - * aware. - * - * @return immutable version of this instance - */ - public Bytes immutable() { - return Bytes.wrap(internalArray(), byteOrder()); - } - - @Override - public int hashCode() { - return Util.Obj.hashCode(internalArray(), byteOrder()); - } - - @Override - public boolean equals(Object o) { - return super.equals(o); - } - - @Override - public void close() { - secureWipe(); - } - - /** - * Factory creating mutable byte types - */ - private static class Factory implements BytesFactory { - @Override - public Bytes wrap(byte[] array, ByteOrder byteOrder) { - return new MutableBytes(array, byteOrder); - } - - @Override - public Bytes wrap(Bytes other, byte[] array) { - if (other.length() == array.length) { - other.overwrite(array); - return other; - } - return wrap(array, other.byteOrder()); - } - - @Override - public Bytes wrap(Bytes other) { - return other; - } - } -} diff --git a/src/main/java/at/favre/lib/bytes/ReadOnlyBytes.java b/src/main/java/at/favre/lib/bytes/ReadOnlyBytes.java index 5dd29d1..556f034 100644 --- a/src/main/java/at/favre/lib/bytes/ReadOnlyBytes.java +++ b/src/main/java/at/favre/lib/bytes/ReadOnlyBytes.java @@ -22,7 +22,6 @@ package at.favre.lib.bytes; import java.nio.ByteOrder; -import java.nio.ReadOnlyBufferException; /** * The read-only version of {@link Bytes} created by calling {@link #readOnly()}. @@ -43,6 +42,11 @@ public final class ReadOnlyBytes extends Bytes { super(byteArray, byteOrder, new Factory()); } + @Override + public boolean isMutable() { + return false; + } + @Override public boolean isReadOnly() { return true; @@ -50,7 +54,12 @@ public boolean isReadOnly() { @Override public byte[] array() { - throw new ReadOnlyBufferException(); + throw new UnsupportedOperationException(); + } + + @Override + public ImmutableBytes immutable() { + throw new UnsupportedOperationException("read only does not support converting to immutable"); } /** diff --git a/src/test/java/at/favre/lib/bytes/BytesMiscTest.java b/src/test/java/at/favre/lib/bytes/BytesMiscTest.java index 817aa30..32d4de5 100644 --- a/src/test/java/at/favre/lib/bytes/BytesMiscTest.java +++ b/src/test/java/at/favre/lib/bytes/BytesMiscTest.java @@ -26,7 +26,6 @@ import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; -import java.nio.ReadOnlyBufferException; import java.util.NoSuchElementException; import java.util.Random; @@ -477,43 +476,6 @@ public void entropy() { assertTrue(Bytes.from(example_bytes_two).entropy() > 0.5); } - @Test - public void readOnlyShouldKeepProperty() { - ReadOnlyBytes b = Bytes.from(example_bytes_seven).readOnly(); - assertSame(b, b.readOnly()); - assertTrue(b.isReadOnly()); - assertTrue(b.copy().isReadOnly()); - assertTrue(b.duplicate().isReadOnly()); - assertTrue(b.reverse().isReadOnly()); - assertTrue(b.resize(7).isReadOnly()); - assertTrue(b.resize(6).isReadOnly()); - assertTrue(b.not().isReadOnly()); - assertTrue(b.leftShift(1).isReadOnly()); - assertTrue(b.rightShift(1).isReadOnly()); - assertTrue(b.and(Bytes.random(b.length())).isReadOnly()); - assertTrue(b.or(Bytes.random(b.length())).isReadOnly()); - assertTrue(b.xor(Bytes.random(b.length())).isReadOnly()); - assertTrue(b.append(3).isReadOnly()); - assertTrue(b.hashSha256().isReadOnly()); - } - - @Test - public void readOnly() { - assertFalse(Bytes.from(example_bytes_twentyfour).isReadOnly()); - assertTrue(Bytes.from(example_bytes_twentyfour).readOnly().isReadOnly()); - assertTrue(Bytes.from(example_bytes_twentyfour).readOnly().copy().isReadOnly()); - - assertArrayEquals(example_bytes_twentyfour, Bytes.from(example_bytes_twentyfour).readOnly().internalArray()); - try { - Bytes.from(example_bytes_twentyfour).readOnly().array(); - fail(); - } catch (ReadOnlyBufferException ignored) { - } - - Bytes b = Bytes.from(example_bytes_twentyfour).readOnly(); - assertSame(b, b.readOnly()); - } - @Test public void iteratorTest() { Bytes b = Bytes.wrap(example_bytes_seven); diff --git a/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java b/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java new file mode 100644 index 0000000..4c936e0 --- /dev/null +++ b/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java @@ -0,0 +1,102 @@ +/* + * Copyright 2019 Patrick Favre-Bulle + * + * 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 + * + * 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 at.favre.lib.bytes; + +import org.junit.Test; + +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import static org.junit.Assert.*; + +public class ImmutableBytesTest extends ABytesTest { + @Test + public void immutableShouldKeepProperty() { + ImmutableBytes b = Bytes.from(example_bytes_seven).immutable(); + assertSame(b, b.immutable()); + assertFalse(b.isReadOnly()); + assertFalse(b.isMutable()); + assertFalse(b.copy().isMutable()); + assertFalse(b.reverse().isMutable()); + assertFalse(b.resize(7).isMutable()); + assertFalse(b.resize(6).isMutable()); + assertFalse(b.not().isMutable()); + assertFalse(b.leftShift(1).isMutable()); + assertFalse(b.rightShift(1).isMutable()); + assertFalse(b.and(Bytes.random(b.length())).isMutable()); + assertFalse(b.or(Bytes.random(b.length())).isMutable()); + assertFalse(b.xor(Bytes.random(b.length())).isMutable()); + assertFalse(b.append(3).isMutable()); + assertFalse(b.hashSha256().isMutable()); + } + + @Test + public void testConvertImmutable() { + Bytes b = Bytes.from(example_bytes_seven); + Bytes m = b.copy(); + assertEquals(b, m); + assertTrue(b.equalsContent(m)); + assertEquals(b.byteOrder(), m.byteOrder()); + assertTrue(b.isMutable()); + + Bytes m2i = m.immutable(); + assertNotEquals(m2i, m); + assertNotEquals(m2i, b); + assertNotSame(m2i, b); + assertTrue(m2i.equalsContent(m)); + assertEquals(m2i.byteOrder(), m.byteOrder()); + assertFalse(m2i.isMutable()); + + assertEquals(m.length(), m2i.length()); + assertEquals(m.length(), b.length()); + + assertNotEquals(example_bytes_seven[0], 0); + assertEquals(example_bytes_seven[0], b.byteAt(0)); + assertEquals(example_bytes_seven[0], m.byteAt(0)); + assertEquals(example_bytes_seven[0], m2i.byteAt(0)); + + m.fill((byte) 0); + + assertEquals(example_bytes_seven[0], b.byteAt(0)); + assertEquals(0, m.byteAt(0)); + assertNotEquals(0, m2i.byteAt(0)); + } + + Bytes fromAndTest(byte[] bytes) { + Bytes b = Bytes.from(bytes); + assertArrayEquals(bytes, b.array()); + return b; + } + + @Test + public void testAutoCloseableShouldThrowException() { + try { + try (Bytes b = Bytes.wrap(new byte[16]).immutable()) { + SecretKey s = new SecretKeySpec(b.array(), "AES"); + } + fail(); + } catch (UnsupportedOperationException ignored) { + + } + + } +} diff --git a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java index f0cecfd..ec9b951 100644 --- a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java @@ -106,7 +106,7 @@ public void setByteAtTest() { for (int i = 0; i < b.length(); i++) { byte old = b.byteAt(i); - MutableBytes bcopy = b.setByteAt(i, (byte) 0); + Bytes bcopy = b.setByteAt(i, (byte) 0); assertSame(b, bcopy); if (old != 0) { assertNotEquals(old, b.byteAt(i)); diff --git a/src/test/java/at/favre/lib/bytes/ReadOnlyBytesTest.java b/src/test/java/at/favre/lib/bytes/ReadOnlyBytesTest.java new file mode 100644 index 0000000..f7bff20 --- /dev/null +++ b/src/test/java/at/favre/lib/bytes/ReadOnlyBytesTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2019 Patrick Favre-Bulle + * + * 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 + * + * 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 at.favre.lib.bytes; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ReadOnlyBytesTest extends ABytesTest { + @Test + public void readOnlyShouldKeepProperty() { + ReadOnlyBytes b = Bytes.from(example_bytes_seven).readOnly(); + assertSame(b, b.readOnly()); + assertFalse(b.isMutable()); + assertTrue(b.isReadOnly()); + assertTrue(b.copy().isReadOnly()); + assertTrue(b.reverse().isReadOnly()); + assertTrue(b.resize(7).isReadOnly()); + assertTrue(b.resize(6).isReadOnly()); + assertTrue(b.not().isReadOnly()); + assertTrue(b.leftShift(1).isReadOnly()); + assertTrue(b.rightShift(1).isReadOnly()); + assertTrue(b.and(Bytes.random(b.length())).isReadOnly()); + assertTrue(b.or(Bytes.random(b.length())).isReadOnly()); + assertTrue(b.xor(Bytes.random(b.length())).isReadOnly()); + assertTrue(b.append(3).isReadOnly()); + assertTrue(b.hashSha256().isReadOnly()); + } + + @Test(expected = UnsupportedOperationException.class) + public void readOnlyDuplicateNotAllowed() { + Bytes.from(example_bytes_seven).readOnly().duplicate(); + } + + @Test(expected = UnsupportedOperationException.class) + public void readOnlyImmutableNotAllowed() { + Bytes.from(example_bytes_seven).readOnly().immutable(); + } + + @Test + public void readOnly() { + assertFalse(Bytes.from(example_bytes_twentyfour).isReadOnly()); + assertTrue(Bytes.from(example_bytes_twentyfour).readOnly().isReadOnly()); + assertTrue(Bytes.from(example_bytes_twentyfour).readOnly().copy().isReadOnly()); + + assertArrayEquals(example_bytes_twentyfour, Bytes.from(example_bytes_twentyfour).readOnly().internalArray()); + try { + Bytes.from(example_bytes_twentyfour).readOnly().array(); + fail(); + } catch (UnsupportedOperationException ignored) { + } + + Bytes b = Bytes.from(example_bytes_twentyfour).readOnly(); + assertSame(b, b.readOnly()); + } +} From e2f90c5f127f0f26afbae8d18956e66d67790b59 Mon Sep 17 00:00:00 2001 From: pfavre Date: Sun, 13 Jan 2019 00:00:25 +0100 Subject: [PATCH 3/9] Fix checkstyle warnings by providing javadoc in BytesFactory --- .../java/at/favre/lib/bytes/BytesFactory.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/main/java/at/favre/lib/bytes/BytesFactory.java b/src/main/java/at/favre/lib/bytes/BytesFactory.java index 504fa67..4724054 100644 --- a/src/main/java/at/favre/lib/bytes/BytesFactory.java +++ b/src/main/java/at/favre/lib/bytes/BytesFactory.java @@ -31,13 +31,26 @@ public interface BytesFactory { /** * Create an instance with given array and order * - * @param array to directly us + * @param array to directly use * @param byteOrder the array is in * @return a new instance */ Bytes wrap(byte[] array, ByteOrder byteOrder); + /** + * Create an instance with given other instance and new array + * + * @param other of the copy source + * @param array to directly use + * @return a new instance + */ Bytes wrap(Bytes other, byte[] array); + /** + * Create an instance with given other instance + * + * @param other of the copy source + * @return a new instance + */ Bytes wrap(Bytes other); } From d1e487fbfd76dada3b222fac5cf0189f6c3f3734 Mon Sep 17 00:00:00 2001 From: Patrick Favre-Bulle Date: Mon, 14 Jan 2019 08:39:08 +0100 Subject: [PATCH 4/9] Add more mutable byte tests --- .../at/favre/lib/bytes/MutableBytesTest.java | 55 +++++++++++++++---- 1 file changed, 44 insertions(+), 11 deletions(-) diff --git a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java index ec9b951..1f3f032 100644 --- a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java @@ -71,33 +71,33 @@ public void fill() { } @Test - public void testConvertImmutable() { + public void testCheckReferencesAndCopy() { Bytes b = Bytes.from(example_bytes_seven); Bytes m = b.copy(); assertEquals(b, m); assertTrue(b.equalsContent(m)); assertEquals(b.byteOrder(), m.byteOrder()); - Bytes m2b = m.immutable(); - assertNotEquals(m2b, m); - assertNotEquals(m2b, b); - assertNotSame(m2b, b); - assertTrue(m2b.equalsContent(m)); - assertEquals(m2b.byteOrder(), m.byteOrder()); + Bytes dup = m.duplicate(); + assertEquals(dup, m); + assertEquals(dup, b); + assertNotSame(dup, b); + assertTrue(dup.equalsContent(m)); + assertEquals(dup.byteOrder(), m.byteOrder()); - assertEquals(m.length(), m2b.length()); + assertEquals(m.length(), dup.length()); assertEquals(m.length(), b.length()); assertNotEquals(example_bytes_seven[0], 0); assertEquals(example_bytes_seven[0], b.byteAt(0)); assertEquals(example_bytes_seven[0], m.byteAt(0)); - assertEquals(example_bytes_seven[0], m2b.byteAt(0)); + assertEquals(example_bytes_seven[0], dup.byteAt(0)); - /*m.fill((byte) 0); + m.fill((byte) 0); assertEquals(example_bytes_seven[0], b.byteAt(0)); assertEquals(0, m.byteAt(0)); - assertEquals(0, m2b.byteAt(0));*/ + assertEquals(0, dup.byteAt(0)); } @Test @@ -182,6 +182,39 @@ public void testAutoCloseable() { } assertArrayNotEquals(new byte[16], leak.array()); + } + + + @Test + public void testCheckReferenceFrom() { + byte[] ref = new byte[]{1, 2, 3, 4}; + + Bytes refFrom = Bytes.from(ref); + byte[] refFromInternalArr = refFrom.array(); + assertNotSame(ref, refFrom.array()); + assertArrayEquals(ref, refFrom.array()); + assertSame(refFromInternalArr, refFrom.array()); + assertSame(refFrom.array(), refFrom.array()); + + refFrom.xor(new byte[]{0, 0, 0, 0}); + assertSame(refFromInternalArr, refFrom.array()); + assertNotEquals(ref, refFrom.array()); + } + @Test + public void testCheckReferenceWrap() { + byte[] ref = new byte[]{1, 2, 3, 4}; + + Bytes refWrap = Bytes.wrap(ref); + byte[] refFromInternalArr = refWrap.array(); + assertSame(ref, refWrap.array()); + assertArrayEquals(ref, refWrap.array()); + assertSame(refFromInternalArr, refWrap.array()); + assertSame(refWrap.array(), refWrap.array()); + + refWrap.xor(new byte[]{0, 0, 0, 0}); + assertSame(refFromInternalArr, refWrap.array()); + assertEquals(ref, refWrap.array()); + assertNotEquals(new byte[]{1, 2, 3, 4}, refWrap.array()); } } From 743aa7b0dd626f596c374551b344241aaf711943 Mon Sep 17 00:00:00 2001 From: Patrick Favre-Bulle Date: Mon, 14 Jan 2019 08:40:29 +0100 Subject: [PATCH 5/9] Some slight refactoring and new immutable test --- src/main/java/at/favre/lib/bytes/Bytes.java | 13 ++++++++++++- .../java/at/favre/lib/bytes/ImmutableBytesTest.java | 7 +++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/main/java/at/favre/lib/bytes/Bytes.java b/src/main/java/at/favre/lib/bytes/Bytes.java index 2e77920..56ce858 100644 --- a/src/main/java/at/favre/lib/bytes/Bytes.java +++ b/src/main/java/at/favre/lib/bytes/Bytes.java @@ -62,6 +62,7 @@ public class Bytes implements Comparable, Serializable, Iterable, AutoCloseable { private static final Bytes EMPTY = Bytes.wrap(new byte[0]); + private static final ByteOrder DEFAULT_ORDER = ByteOrder.BIG_ENDIAN; /* FACTORY ***************************************************************************************************/ @@ -138,7 +139,7 @@ public static Bytes wrapNullSafe(byte[] array) { * @return new instance */ public static Bytes wrap(byte[] array) { - return wrap(array, ByteOrder.BIG_ENDIAN); + return wrap(array, DEFAULT_ORDER); } /** @@ -156,6 +157,16 @@ public static Bytes wrap(byte[] array, ByteOrder byteOrder) { return new Bytes(Objects.requireNonNull(array, "passed array must not be null"), byteOrder); } + public static ImmutableBytes wrapImmutable(byte[] array) { + return wrapImmutable(array, DEFAULT_ORDER); + } + + public static ImmutableBytes wrapImmutable(byte[] array, ByteOrder byteOrder) { + return new ImmutableBytes(Objects.requireNonNull(Arrays.copyOf(array, array.length), + "passed array must not be null"), + Objects.requireNonNull(byteOrder, "byte order must not be null")); + } + /** * Creates a new instance from given collections of single bytes. * This will create a copy of given bytes and will not directly use given bytes or byte array. diff --git a/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java b/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java index 4c936e0..9213875 100644 --- a/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java @@ -31,7 +31,11 @@ public class ImmutableBytesTest extends ABytesTest { @Test public void immutableShouldKeepProperty() { - ImmutableBytes b = Bytes.from(example_bytes_seven).immutable(); + testImmutableProperties(Bytes.from(example_bytes_seven).immutable()); + testImmutableProperties(Bytes.wrapImmutable(example_bytes_seven)); + } + + private void testImmutableProperties(ImmutableBytes b) { assertSame(b, b.immutable()); assertFalse(b.isReadOnly()); assertFalse(b.isMutable()); @@ -97,6 +101,5 @@ public void testAutoCloseableShouldThrowException() { } catch (UnsupportedOperationException ignored) { } - } } From 91a9a07afb9576bcf7ea4edd4dcceb4349d8baea Mon Sep 17 00:00:00 2001 From: Patrick Favre-Bulle Date: Mon, 14 Jan 2019 08:47:18 +0100 Subject: [PATCH 6/9] Rename all `from(*)` static factories to `of(*)` --- README.md | 6 +- .../favre/lib/bytes/BinaryToTextEncoding.java | 4 +- src/main/java/at/favre/lib/bytes/Bytes.java | 246 +++++++------- .../at/favre/lib/bytes/BytesTransformer.java | 8 +- .../at/favre/lib/bytes/BytesTransformers.java | 10 +- .../java/at/favre/lib/bytes/ABytesTest.java | 2 +- .../java/at/favre/lib/bytes/Base64Test.java | 18 +- .../lib/bytes/BinaryToTextEncodingTest.java | 90 ++--- .../favre/lib/bytes/BytesByteOrderTest.java | 36 +- .../lib/bytes/BytesConstructorTests.java | 194 +++++------ .../at/favre/lib/bytes/BytesMiscTest.java | 150 ++++----- .../lib/bytes/BytesParseAndEncodingTest.java | 86 ++--- .../bytes/BytesSharedDataConverterTest.java | 50 +-- .../bytes/BytesToConvertOtherTypesTest.java | 106 +++--- .../favre/lib/bytes/BytesTransformTest.java | 312 +++++++++--------- .../favre/lib/bytes/ImmutableBytesTest.java | 8 +- .../at/favre/lib/bytes/MutableBytesTest.java | 10 +- .../at/favre/lib/bytes/ReadOnlyBytesTest.java | 18 +- .../java/at/favre/lib/bytes/UtilByteTest.java | 38 +-- 19 files changed, 696 insertions(+), 696 deletions(-) diff --git a/README.md b/README.md index 9572346..fddb7c6 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ int result = b.toInt(); //get as signed int ``` ```java -Bytes b = Bytes.from(array1); //create from copy of array1 +Bytes b = Bytes.from(array1); of b.resize(2).xor(array2); //shrink to 2 bytes and xor with other array byte[] result = b.array(); //get as byte array ``` @@ -167,8 +167,8 @@ Bytes.from(byteInputStream, 16); //read java.io.InputStream with length limitati Bytes.from(byteList); //List byteList = ... Bytes.from(myBitSet); //java.util.BitSet myBitSet = ... Bytes.from(bigInteger); //java.math.BigInteger -Bytes.from(file); //reads bytes from any java.io.File -Bytes.from(dataInput, 16); //reads bytes from any java.io.DataInput +Bytes.from(file); of +Bytes.from(dataInput, 16); of Bytes.from(UUID.randomUUID()); //read 16 bytes from UUID ``` diff --git a/src/main/java/at/favre/lib/bytes/BinaryToTextEncoding.java b/src/main/java/at/favre/lib/bytes/BinaryToTextEncoding.java index 00ef667..be3e2bb 100644 --- a/src/main/java/at/favre/lib/bytes/BinaryToTextEncoding.java +++ b/src/main/java/at/favre/lib/bytes/BinaryToTextEncoding.java @@ -151,7 +151,7 @@ class Base64Encoding implements EncoderDecoder { @Override public String encode(byte[] array, ByteOrder byteOrder) { - return new String(Base64.encode((byteOrder == ByteOrder.BIG_ENDIAN) ? array : Bytes.from(array).reverse().array(), urlSafe, padding), StandardCharsets.US_ASCII); + return new String(Base64.encode((byteOrder == ByteOrder.BIG_ENDIAN) ? array : Bytes.of(array).reverse().array(), urlSafe, padding), StandardCharsets.US_ASCII); } @Override @@ -175,7 +175,7 @@ class BaseRadixNumber implements EncoderDecoder { @Override public String encode(byte[] array, ByteOrder byteOrder) { - return new BigInteger(1, (byteOrder == ByteOrder.BIG_ENDIAN) ? array : Bytes.from(array).reverse().array()).toString(radix); + return new BigInteger(1, (byteOrder == ByteOrder.BIG_ENDIAN) ? array : Bytes.of(array).reverse().array()).toString(radix); } @Override diff --git a/src/main/java/at/favre/lib/bytes/Bytes.java b/src/main/java/at/favre/lib/bytes/Bytes.java index 56ce858..d0b8179 100644 --- a/src/main/java/at/favre/lib/bytes/Bytes.java +++ b/src/main/java/at/favre/lib/bytes/Bytes.java @@ -157,29 +157,19 @@ public static Bytes wrap(byte[] array, ByteOrder byteOrder) { return new Bytes(Objects.requireNonNull(array, "passed array must not be null"), byteOrder); } - public static ImmutableBytes wrapImmutable(byte[] array) { - return wrapImmutable(array, DEFAULT_ORDER); - } - - public static ImmutableBytes wrapImmutable(byte[] array, ByteOrder byteOrder) { - return new ImmutableBytes(Objects.requireNonNull(Arrays.copyOf(array, array.length), - "passed array must not be null"), - Objects.requireNonNull(byteOrder, "byte order must not be null")); - } - /** - * Creates a new instance from given collections of single bytes. + * Creates a new instance of given collections of single bytes. * This will create a copy of given bytes and will not directly use given bytes or byte array. * * @param byteArrayToCopy must not be null and will not be used directly, but a copy * @return new instance */ - public static Bytes from(byte[] byteArrayToCopy) { + public static Bytes of(byte[] byteArrayToCopy) { return wrap(Arrays.copyOf(Objects.requireNonNull(byteArrayToCopy, "must at least pass a single byte"), byteArrayToCopy.length)); } /** - * Creates a new instance from given collections of single bytes. + * Creates a new instance of given collections of single bytes. * This will create a copy of given bytes and will not directly use given bytes or byte array. *

* If given array is null, a zero length byte array will be created and used instead. @@ -187,95 +177,105 @@ public static Bytes from(byte[] byteArrayToCopy) { * @param byteArrayToCopy will not be used directly, but a copy; may be null * @return new instance */ - public static Bytes fromNullSafe(byte[] byteArrayToCopy) { - return byteArrayToCopy != null ? from(byteArrayToCopy) : empty(); + public static Bytes ofNullSafe(byte[] byteArrayToCopy) { + return byteArrayToCopy != null ? of(byteArrayToCopy) : empty(); } /** - * Creates a new instance from a slice of given array + * Creates a new instance of a slice of given array * * @param array to slice * @param offset start position * @param length length * @return new instance */ - public static Bytes from(byte[] array, int offset, int length) { + public static Bytes of(byte[] array, int offset, int length) { Objects.requireNonNull(array, "passed array must not be null"); byte[] part = new byte[length]; System.arraycopy(array, offset, part, 0, length); return wrap(part); } + public static ImmutableBytes ofImmutable(byte[] array) { + return ofImmutable(array, DEFAULT_ORDER); + } + + public static ImmutableBytes ofImmutable(byte[] array, ByteOrder byteOrder) { + return new ImmutableBytes(Objects.requireNonNull(Arrays.copyOf(array, array.length), + "passed array must not be null"), + Objects.requireNonNull(byteOrder, "byte order must not be null")); + } + /** - * Creates a new instance from given array of byte arrays + * Creates a new instance of given array of byte arrays * * @param moreArrays must not be null * @return new instance */ - public static Bytes from(byte[]... moreArrays) { + public static Bytes of(byte[]... moreArrays) { return wrap(Util.Byte.concat(moreArrays)); } /** - * Creates a new instance from given array of byte arrays + * Creates a new instance of given array of byte arrays * * @param moreBytes must not be null * @return new instance */ - public static Bytes from(Bytes... moreBytes) { + public static Bytes of(Bytes... moreBytes) { Objects.requireNonNull(moreBytes, "bytes most not be null"); byte[][] bytes = new byte[moreBytes.length][]; for (int i = 0; i < moreBytes.length; i++) { bytes[i] = moreBytes[i].array(); } - return from(bytes); + return of(bytes); } /** - * Creates a new instance from given collections. This will create a lot of auto-unboxing events, + * Creates a new instance of given collections. This will create a lot of auto-unboxing events, * so use with care with bigger lists. * - * @param bytesCollection to create from + * @param bytesCollection to create of * @return new instance */ - public static Bytes from(Collection bytesCollection) { + public static Bytes of(Collection bytesCollection) { return wrap(Util.Converter.toArray(bytesCollection)); } /** - * Creates a new instance from given object byte array. Will copy and unbox every element. + * Creates a new instance of given object byte array. Will copy and unbox every element. * - * @param boxedObjectArray to create from + * @param boxedObjectArray to create of * @return new instance */ - public static Bytes from(Byte[] boxedObjectArray) { + public static Bytes of(Byte[] boxedObjectArray) { return wrap(Util.Converter.toPrimitiveArray(boxedObjectArray)); } /** - * Creates a new single array element array instance from given byte + * Creates a new single array element array instance of given byte * - * @param singleByte to create from + * @param singleByte to create of * @return new instance */ - public static Bytes from(byte singleByte) { + public static Bytes of(byte singleByte) { return wrap(new byte[]{singleByte}); } /** - * Creates a new instance from given collections of single bytes. + * Creates a new instance of given collections of single bytes. * This will create a copy of given bytes and will not directly use given bytes or byte array. * * @param firstByte must not be null and will not be used directly, but a copy * @param moreBytes more bytes vararg * @return new instance */ - public static Bytes from(byte firstByte, byte... moreBytes) { + public static Bytes of(byte firstByte, byte... moreBytes) { return wrap(Util.Byte.concatVararg(firstByte, moreBytes)); } /** - * Creates a new instance from given boolean. + * Creates a new instance of given boolean. * This will create a new single array element array instance using the convention that false is zero. * E.g. Creates array new byte[] {1} if booleanValue is true and new byte[] {0} if * booleanValue is false. @@ -283,173 +283,173 @@ public static Bytes from(byte firstByte, byte... moreBytes) { * @param booleanValue to convert (false is zero, true is one) * @return new instance */ - public static Bytes from(boolean booleanValue) { + public static Bytes of(boolean booleanValue) { return wrap(new byte[]{booleanValue ? (byte) 1 : 0}); } /** - * Creates a new instance from given unsigned 2 byte char. + * Creates a new instance of given unsigned 2 byte char. * - * @param char2Byte to create from + * @param char2Byte to create of * @return new instance */ - public static Bytes from(char char2Byte) { + public static Bytes of(char char2Byte) { return wrap(ByteBuffer.allocate(2).putChar(char2Byte).array()); } /** - * Creates a new instance from given 2 byte short. + * Creates a new instance of given 2 byte short. * - * @param short2Byte to create from + * @param short2Byte to create of * @return new instance */ - public static Bytes from(short short2Byte) { + public static Bytes of(short short2Byte) { return wrap(ByteBuffer.allocate(2).putShort(short2Byte).array()); } /** - * Creates a new instance from given 4 byte integer. + * Creates a new instance of given 4 byte integer. * - * @param integer4byte to create from + * @param integer4byte to create of * @return new instance */ - public static Bytes from(int integer4byte) { + public static Bytes of(int integer4byte) { return wrap(ByteBuffer.allocate(4).putInt(integer4byte).array()); } /** - * Creates a new instance from given 4 byte integer array. + * Creates a new instance of given 4 byte integer array. * - * @param intArray to create from + * @param intArray to create of * @return new instance */ - public static Bytes from(int... intArray) { + public static Bytes of(int... intArray) { return wrap(Util.Converter.toByteArray(Objects.requireNonNull(intArray, "must provide at least a single int"))); } /** - * Creates a new instance from given 8 byte long. + * Creates a new instance of given 8 byte long. * - * @param long8byte to create from + * @param long8byte to create of * @return new instance */ - public static Bytes from(long long8byte) { + public static Bytes of(long long8byte) { return wrap(ByteBuffer.allocate(8).putLong(long8byte).array()); } /** - * Creates a new instance from given 8 byte long array. + * Creates a new instance of given 8 byte long array. * - * @param longArray to create from + * @param longArray to create of * @return new instance */ - public static Bytes from(long... longArray) { + public static Bytes of(long... longArray) { return wrap(Util.Converter.toByteArray(Objects.requireNonNull(longArray, "must provide at least a single long"))); } /** - * Creates a new instance from given 4 byte floating point number (float). + * Creates a new instance of given 4 byte floating point number (float). * - * @param float4byte to create from + * @param float4byte to create of * @return new instance */ - public static Bytes from(float float4byte) { + public static Bytes of(float float4byte) { return wrap(ByteBuffer.allocate(4).putFloat(float4byte).array()); } /** - * Creates a new instance from given 8 byte floating point number (double). + * Creates a new instance of given 8 byte floating point number (double). * - * @param double8Byte to create from + * @param double8Byte to create of * @return new instance */ - public static Bytes from(double double8Byte) { + public static Bytes of(double double8Byte) { return wrap(ByteBuffer.allocate(8).putDouble(double8Byte).array()); } /** - * Creates a new instance from given {@link ByteBuffer}. + * Creates a new instance of given {@link ByteBuffer}. * Will use the same backing byte array and honour the buffer's byte order. * - * @param buffer to get the byte array from (must not be null) + * @param buffer to get the byte array of (must not be null) * @return new instance */ - public static Bytes from(ByteBuffer buffer) { + public static Bytes of(ByteBuffer buffer) { return wrap(Objects.requireNonNull(buffer, "provided byte buffer must not be null").array(), buffer.order()); } /** - * Creates a new instance from given {@link CharBuffer}. + * Creates a new instance of given {@link CharBuffer}. * Will ignore buffer's byte order and use {@link ByteOrder#BIG_ENDIAN} * - * @param buffer to get the char array from (must not be null) + * @param buffer to get the char array of (must not be null) * @return new instance */ - public static Bytes from(CharBuffer buffer) { - return from(Objects.requireNonNull(buffer, "provided char buffer must not be null").array()); + public static Bytes of(CharBuffer buffer) { + return of(Objects.requireNonNull(buffer, "provided char buffer must not be null").array()); } /** - * Creates a new instance from given {@link IntBuffer}. + * Creates a new instance of given {@link IntBuffer}. * Will ignore buffer's byte order and use {@link ByteOrder#BIG_ENDIAN} * - * @param buffer to get the int array from (must not be null) + * @param buffer to get the int array of (must not be null) * @return new instance */ - public static Bytes from(IntBuffer buffer) { - return from(Objects.requireNonNull(buffer, "provided int buffer must not be null").array()); + public static Bytes of(IntBuffer buffer) { + return of(Objects.requireNonNull(buffer, "provided int buffer must not be null").array()); } /** - * Creates a new instance from given {@link BitSet}. + * Creates a new instance of given {@link BitSet}. * - * @param set to get the byte array from + * @param set to get the byte array of * @return new instance */ - public static Bytes from(BitSet set) { + public static Bytes of(BitSet set) { return wrap(set.toByteArray()); } /** - * Creates a new instance from given {@link BigInteger}. + * Creates a new instance of given {@link BigInteger}. * - * @param bigInteger to get the byte array from + * @param bigInteger to get the byte array of * @return new instance */ - public static Bytes from(BigInteger bigInteger) { + public static Bytes of(BigInteger bigInteger) { return wrap(bigInteger.toByteArray()); } /** - * Reads given whole input stream and creates a new instance from read data + * Reads given whole input stream and creates a new instance of read data * - * @param stream to read from + * @param stream to read of * @return new instance */ - public static Bytes from(InputStream stream) { + public static Bytes of(InputStream stream) { return wrap(Util.File.readFromStream(stream, -1)); } /** - * Reads given input stream up to maxLength and creates a new instance from read data. + * Reads given input stream up to maxLength and creates a new instance of read data. * Read maxLength is never longer than stream size (ie. maxLength is only limiting, not assuring maxLength) * - * @param stream to read from + * @param stream to read of * @param maxLength read to this maxLength or end of stream * @return new instance */ - public static Bytes from(InputStream stream, int maxLength) { + public static Bytes of(InputStream stream, int maxLength) { return wrap(Util.File.readFromStream(stream, maxLength)); } /** - * Reads given {@link DataInput} and creates a new instance from read data + * Reads given {@link DataInput} and creates a new instance of read data * - * @param dataInput to read from + * @param dataInput to read of * @param length how many bytes should be read * @return new instance */ - public static Bytes from(DataInput dataInput, int length) { + public static Bytes of(DataInput dataInput, int length) { return wrap(Util.File.readFromDataInput(dataInput, length)); } @@ -457,12 +457,12 @@ public static Bytes from(DataInput dataInput, int length) { * Reads given file and returns the byte content. Be aware that the whole file content will be loaded to * memory, so be careful what to read in. * - * @param file to read from + * @param file to read of * @return new instance * @throws IllegalArgumentException if file does not exist * @throws IllegalStateException if file could not be read */ - public static Bytes from(File file) { + public static Bytes of(File file) { return wrap(Util.File.readFromFile(file)); } @@ -470,81 +470,81 @@ public static Bytes from(File file) { * Reads given file and returns the byte content. Be aware that the whole defined file content will be loaded to * memory, so be careful what to read in. This uses {@link java.io.RandomAccessFile} under the hood. * - * @param file to read from - * @param offset byte offset from zero position of the file - * @param length to read from offset + * @param file to read of + * @param offset byte offset of zero position of the file + * @param length to read of offset * @return new instance * @throws IllegalArgumentException if file does not exist * @throws IllegalStateException if file could not be read */ - public static Bytes from(File file, int offset, int length) { + public static Bytes of(File file, int offset, int length) { return wrap(Util.File.readFromFile(file, offset, length)); } /** - * Creates a new instance from given utf-8 encoded string + * Creates a new instance of given utf-8 encoded string * - * @param utf8String to get the internal byte array from + * @param utf8String to get the internal byte array of * @return new instance */ - public static Bytes from(CharSequence utf8String) { - return from(utf8String, StandardCharsets.UTF_8); + public static Bytes of(CharSequence utf8String) { + return of(utf8String, StandardCharsets.UTF_8); } /** - * Creates a new instance from normalized form of given utf-8 encoded string + * Creates a new instance of normalized form of given utf-8 encoded string * - * @param utf8String to get the internal byte array from + * @param utf8String to get the internal byte array of * @param form to normalize, usually you want {@link java.text.Normalizer.Form#NFKD} for compatibility * @return new instance */ - public static Bytes from(CharSequence utf8String, Normalizer.Form form) { - return from(Normalizer.normalize(utf8String, form), StandardCharsets.UTF_8); + public static Bytes of(CharSequence utf8String, Normalizer.Form form) { + return of(Normalizer.normalize(utf8String, form), StandardCharsets.UTF_8); } /** - * Creates a new instance from given string + * Creates a new instance of given string * - * @param string to get the internal byte array from + * @param string to get the internal byte array of * @param charset used to decode the string * @return new instance */ - public static Bytes from(CharSequence string, Charset charset) { + public static Bytes of(CharSequence string, Charset charset) { return wrap(Objects.requireNonNull(string, "provided string must not be null").toString().getBytes(Objects.requireNonNull(charset, "provided charset must not be null"))); } /** - * Creates a new instance from given char array using utf-8 encoding + * Creates a new instance of given char array using utf-8 encoding * - * @param charArray to get the internal byte array from + * @param charArray to get the internal byte array of * @return new instance */ - public static Bytes from(char[] charArray) { - return from(charArray, StandardCharsets.UTF_8); + public static Bytes of(char[] charArray) { + return of(charArray, StandardCharsets.UTF_8); } /** - * Creates a new instance from given char array. The array will be handles like an encoded string + * Creates a new instance of given char array. The array will be handles like an encoded string * - * @param charArray to get the internal byte array from + * @param charArray to get the internal byte array of * @param charset charset to be used to decode the char array * @return new instance */ - public static Bytes from(char[] charArray, Charset charset) { - return from(charArray, charset, 0, charArray.length); + public static Bytes of(char[] charArray, Charset charset) { + return of(charArray, charset, 0, charArray.length); } /** - * Creates a new instance from given char array with given range. The array will be handles like an encoded string + * Creates a new instance of given char array with given range. The array will be handles like an encoded string * - * @param charArray to get the internal byte array from + * @param charArray to get the internal byte array of * @param charset charset to be used to decode the char array - * @param offset start position (from given char array not encoded byte array out) - * @param length length in relation to offset (from given char array not encoded byte array out) + * @param offset start position (of given char array not encoded byte array out) + * @param length length in relation to offset (of given char array not encoded byte array out) * @return new instance */ - public static Bytes from(char[] charArray, Charset charset, int offset, int length) { - return from(Util.Converter.charToByteArray(charArray, charset, offset, length)); + public static Bytes of(char[] charArray, Charset charset, int offset, int length) { + return of(Util.Converter.charToByteArray(charArray, charset, offset, length)); } /** @@ -554,7 +554,7 @@ public static Bytes from(char[] charArray, Charset charset, int offset, int leng * @param uuid to convert to array * @return new instance */ - public static Bytes from(UUID uuid) { + public static Bytes of(UUID uuid) { return wrap(Util.Converter.toBytesFromUUID(Objects.requireNonNull(uuid)).array()); } @@ -731,7 +731,7 @@ public Bytes append(Bytes bytes) { * @return appended instance */ public Bytes append(byte singleByte) { - return append(Bytes.from(singleByte)); + return append(Bytes.of(singleByte)); } /** @@ -741,7 +741,7 @@ public Bytes append(byte singleByte) { * @return appended instance */ public Bytes append(char char2Bytes) { - return append(Bytes.from(char2Bytes)); + return append(Bytes.of(char2Bytes)); } /** @@ -751,7 +751,7 @@ public Bytes append(char char2Bytes) { * @return appended instance */ public Bytes append(short short2Bytes) { - return append(Bytes.from(short2Bytes)); + return append(Bytes.of(short2Bytes)); } /** @@ -761,7 +761,7 @@ public Bytes append(short short2Bytes) { * @return appended instance */ public Bytes append(int integer4Bytes) { - return append(Bytes.from(integer4Bytes)); + return append(Bytes.of(integer4Bytes)); } /** @@ -771,7 +771,7 @@ public Bytes append(int integer4Bytes) { * @return appended instance */ public Bytes append(long long8Bytes) { - return append(Bytes.from(long8Bytes)); + return append(Bytes.of(long8Bytes)); } /** @@ -783,7 +783,7 @@ public Bytes append(long long8Bytes) { * @return appended instance */ public Bytes append(byte[]... arrays) { - return append(Bytes.from(arrays)); + return append(Bytes.of(arrays)); } /** diff --git a/src/main/java/at/favre/lib/bytes/BytesTransformer.java b/src/main/java/at/favre/lib/bytes/BytesTransformer.java index 3612505..23ff02b 100644 --- a/src/main/java/at/favre/lib/bytes/BytesTransformer.java +++ b/src/main/java/at/favre/lib/bytes/BytesTransformer.java @@ -104,7 +104,7 @@ public boolean supportInPlaceTransformation() { final class NegateTransformer implements BytesTransformer { @Override public byte[] transform(byte[] currentArray, boolean inPlace) { - byte[] out = inPlace ? currentArray : Bytes.from(currentArray).array(); + byte[] out = inPlace ? currentArray : Bytes.of(currentArray).array(); for (int i = 0; i < out.length; i++) { out[i] = (byte) ~out[i]; @@ -139,7 +139,7 @@ public enum Type { @Override public byte[] transform(byte[] currentArray, boolean inPlace) { - byte[] out = inPlace ? currentArray : Bytes.from(currentArray).array(); + byte[] out = inPlace ? currentArray : Bytes.of(currentArray).array(); switch (type) { case RIGHT_SHIFT: @@ -185,7 +185,7 @@ public boolean supportInPlaceTransformation() { final class ReverseTransformer implements BytesTransformer { @Override public byte[] transform(byte[] currentArray, boolean inPlace) { - byte[] out = inPlace ? currentArray : Bytes.from(currentArray).array(); + byte[] out = inPlace ? currentArray : Bytes.of(currentArray).array(); Util.Byte.reverse(out, 0, out.length); return out; } @@ -294,7 +294,7 @@ class BitSwitchTransformer implements BytesTransformer { @Override public byte[] transform(byte[] currentArray, boolean inPlace) { - byte[] out = inPlace ? currentArray : Bytes.from(currentArray).array(); + byte[] out = inPlace ? currentArray : Bytes.of(currentArray).array(); if (position < 0 || position >= 8 * currentArray.length) { throw new IllegalArgumentException("bit index " + (position * 8) + " out of bounds"); diff --git a/src/main/java/at/favre/lib/bytes/BytesTransformers.java b/src/main/java/at/favre/lib/bytes/BytesTransformers.java index f2ae0c7..108bbbf 100644 --- a/src/main/java/at/favre/lib/bytes/BytesTransformers.java +++ b/src/main/java/at/favre/lib/bytes/BytesTransformers.java @@ -177,7 +177,7 @@ public static final class ShuffleTransformer implements BytesTransformer { @Override public byte[] transform(byte[] currentArray, boolean inPlace) { - byte[] out = inPlace ? currentArray : Bytes.from(currentArray).array(); + byte[] out = inPlace ? currentArray : Bytes.of(currentArray).array(); Util.Byte.shuffle(out, random); return out; } @@ -206,14 +206,14 @@ public static final class SortTransformer implements BytesTransformer { @Override public byte[] transform(byte[] currentArray, boolean inPlace) { if (comparator == null) { - byte[] out = inPlace ? currentArray : Bytes.from(currentArray).array(); + byte[] out = inPlace ? currentArray : Bytes.of(currentArray).array(); Arrays.sort(out); return out; } else { //no in-place implementation with comparator Byte[] boxedArray = Bytes.wrap(currentArray).toBoxedArray(); Arrays.sort(boxedArray, comparator); - return Bytes.from(boxedArray).array(); + return Bytes.of(boxedArray).array(); } } @@ -258,12 +258,12 @@ public static final class ChecksumTransformer implements BytesTransformer { @Override public byte[] transform(byte[] currentArray, boolean inPlace) { checksum.update(currentArray, 0, currentArray.length); - byte[] checksumBytes = Bytes.from(checksum.getValue()).resize(checksumLengthByte).array(); + byte[] checksumBytes = Bytes.of(checksum.getValue()).resize(checksumLengthByte).array(); if (mode == Mode.TRANSFORM) { return checksumBytes; } else { - return Bytes.from(currentArray, checksumBytes).array(); + return Bytes.of(currentArray, checksumBytes).array(); } } diff --git a/src/test/java/at/favre/lib/bytes/ABytesTest.java b/src/test/java/at/favre/lib/bytes/ABytesTest.java index ce4ab40..559aafe 100644 --- a/src/test/java/at/favre/lib/bytes/ABytesTest.java +++ b/src/test/java/at/favre/lib/bytes/ABytesTest.java @@ -76,7 +76,7 @@ public void setUp() { } Bytes fromAndTest(byte[] bytes) { - Bytes b = Bytes.from(bytes); + Bytes b = Bytes.of(bytes); assertArrayEquals(bytes, b.array()); return b; } diff --git a/src/test/java/at/favre/lib/bytes/Base64Test.java b/src/test/java/at/favre/lib/bytes/Base64Test.java index 846b3f1..5e3381e 100644 --- a/src/test/java/at/favre/lib/bytes/Base64Test.java +++ b/src/test/java/at/favre/lib/bytes/Base64Test.java @@ -49,15 +49,15 @@ public void decode() { @Test public void encode() { - assertArrayEquals(Bytes.from("").array(), Base64.encode("".getBytes())); - assertArrayEquals(Bytes.from("Zg==").array(), Base64.encode("f".getBytes())); - assertArrayEquals(Bytes.from("Zm8=").array(), Base64.encode("fo".getBytes())); - assertArrayEquals(Bytes.from("Zm9v").array(), Base64.encode("foo".getBytes())); - assertArrayEquals(Bytes.from("Zm9vYg==").array(), Base64.encode("foob".getBytes())); - assertArrayEquals(Bytes.from("Zm9vYmE=").array(), Base64.encode("fooba".getBytes())); - assertArrayEquals(Bytes.from("Zm9vYmFy").array(), Base64.encode("foobar".getBytes())); - assertArrayEquals(Bytes.from("aQo=").array(), Base64.encode("i\n".getBytes())); - assertArrayEquals(Bytes.from("aSA=").array(), Base64.encode("i ".getBytes())); + assertArrayEquals(Bytes.of("").array(), Base64.encode("".getBytes())); + assertArrayEquals(Bytes.of("Zg==").array(), Base64.encode("f".getBytes())); + assertArrayEquals(Bytes.of("Zm8=").array(), Base64.encode("fo".getBytes())); + assertArrayEquals(Bytes.of("Zm9v").array(), Base64.encode("foo".getBytes())); + assertArrayEquals(Bytes.of("Zm9vYg==").array(), Base64.encode("foob".getBytes())); + assertArrayEquals(Bytes.of("Zm9vYmE=").array(), Base64.encode("fooba".getBytes())); + assertArrayEquals(Bytes.of("Zm9vYmFy").array(), Base64.encode("foobar".getBytes())); + assertArrayEquals(Bytes.of("aQo=").array(), Base64.encode("i\n".getBytes())); + assertArrayEquals(Bytes.of("aSA=").array(), Base64.encode("i ".getBytes())); } } diff --git a/src/test/java/at/favre/lib/bytes/BinaryToTextEncodingTest.java b/src/test/java/at/favre/lib/bytes/BinaryToTextEncodingTest.java index 526d35e..b585e9f 100644 --- a/src/test/java/at/favre/lib/bytes/BinaryToTextEncodingTest.java +++ b/src/test/java/at/favre/lib/bytes/BinaryToTextEncodingTest.java @@ -44,21 +44,21 @@ public void decodeHexShouldFail() { public void testBase16Reference() { BinaryToTextEncoding.EncoderDecoder base16Encoding = new BinaryToTextEncoding.Hex(true); // see: https://tools.ietf.org/html/rfc4648 - assertEquals("", base16Encoding.encode(Bytes.from("").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("66", base16Encoding.encode(Bytes.from("f").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("666F", base16Encoding.encode(Bytes.from("fo").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("666F6F", base16Encoding.encode(Bytes.from("foo").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("666F6F62", base16Encoding.encode(Bytes.from("foob").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("666F6F6261", base16Encoding.encode(Bytes.from("fooba").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("666F6F626172", base16Encoding.encode(Bytes.from("foobar").array(), ByteOrder.BIG_ENDIAN)); - - assertArrayEquals(Bytes.from("").array(), base16Encoding.decode("")); - assertArrayEquals(Bytes.from("f").array(), base16Encoding.decode("66")); - assertArrayEquals(Bytes.from("fo").array(), base16Encoding.decode("666F")); - assertArrayEquals(Bytes.from("foo").array(), base16Encoding.decode("666F6F")); - assertArrayEquals(Bytes.from("foob").array(), base16Encoding.decode("666F6F62")); - assertArrayEquals(Bytes.from("fooba").array(), base16Encoding.decode("666F6F6261")); - assertArrayEquals(Bytes.from("foobar").array(), base16Encoding.decode("666F6F626172")); + assertEquals("", base16Encoding.encode(Bytes.of("").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("66", base16Encoding.encode(Bytes.of("f").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("666F", base16Encoding.encode(Bytes.of("fo").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("666F6F", base16Encoding.encode(Bytes.of("foo").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("666F6F62", base16Encoding.encode(Bytes.of("foob").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("666F6F6261", base16Encoding.encode(Bytes.of("fooba").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("666F6F626172", base16Encoding.encode(Bytes.of("foobar").array(), ByteOrder.BIG_ENDIAN)); + + assertArrayEquals(Bytes.of("").array(), base16Encoding.decode("")); + assertArrayEquals(Bytes.of("f").array(), base16Encoding.decode("66")); + assertArrayEquals(Bytes.of("fo").array(), base16Encoding.decode("666F")); + assertArrayEquals(Bytes.of("foo").array(), base16Encoding.decode("666F6F")); + assertArrayEquals(Bytes.of("foob").array(), base16Encoding.decode("666F6F62")); + assertArrayEquals(Bytes.of("fooba").array(), base16Encoding.decode("666F6F6261")); + assertArrayEquals(Bytes.of("foobar").array(), base16Encoding.decode("666F6F626172")); } @Test @@ -126,21 +126,21 @@ public void encodeDecodeBase64Random() { public void testBase64Reference() { BinaryToTextEncoding.EncoderDecoder base64Encoding = new BinaryToTextEncoding.Base64Encoding(); // see: https://tools.ietf.org/html/rfc4648 - assertEquals("", base64Encoding.encode(Bytes.from("").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("Zg==", base64Encoding.encode(Bytes.from("f").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("Zm8=", base64Encoding.encode(Bytes.from("fo").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("Zm9v", base64Encoding.encode(Bytes.from("foo").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("Zm9vYg==", base64Encoding.encode(Bytes.from("foob").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("Zm9vYmE=", base64Encoding.encode(Bytes.from("fooba").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("Zm9vYmFy", base64Encoding.encode(Bytes.from("foobar").array(), ByteOrder.BIG_ENDIAN)); - - assertArrayEquals(Bytes.from("").array(), base64Encoding.decode("")); - assertArrayEquals(Bytes.from("f").array(), base64Encoding.decode("Zg==")); - assertArrayEquals(Bytes.from("fo").array(), base64Encoding.decode("Zm8=")); - assertArrayEquals(Bytes.from("foo").array(), base64Encoding.decode("Zm9v")); - assertArrayEquals(Bytes.from("foob").array(), base64Encoding.decode("Zm9vYg==")); - assertArrayEquals(Bytes.from("fooba").array(), base64Encoding.decode("Zm9vYmE=")); - assertArrayEquals(Bytes.from("foobar").array(), base64Encoding.decode("Zm9vYmFy")); + assertEquals("", base64Encoding.encode(Bytes.of("").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("Zg==", base64Encoding.encode(Bytes.of("f").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("Zm8=", base64Encoding.encode(Bytes.of("fo").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("Zm9v", base64Encoding.encode(Bytes.of("foo").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("Zm9vYg==", base64Encoding.encode(Bytes.of("foob").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("Zm9vYmE=", base64Encoding.encode(Bytes.of("fooba").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("Zm9vYmFy", base64Encoding.encode(Bytes.of("foobar").array(), ByteOrder.BIG_ENDIAN)); + + assertArrayEquals(Bytes.of("").array(), base64Encoding.decode("")); + assertArrayEquals(Bytes.of("f").array(), base64Encoding.decode("Zg==")); + assertArrayEquals(Bytes.of("fo").array(), base64Encoding.decode("Zm8=")); + assertArrayEquals(Bytes.of("foo").array(), base64Encoding.decode("Zm9v")); + assertArrayEquals(Bytes.of("foob").array(), base64Encoding.decode("Zm9vYg==")); + assertArrayEquals(Bytes.of("fooba").array(), base64Encoding.decode("Zm9vYmE=")); + assertArrayEquals(Bytes.of("foobar").array(), base64Encoding.decode("Zm9vYmFy")); } @Test @@ -219,21 +219,21 @@ private byte[] testRndEncodeDecode(BinaryToTextEncoding.EncoderDecoder encoder, public void testBase32Reference() { BinaryToTextEncoding.EncoderDecoder base32Encoding = new BaseEncoding(BaseEncoding.BASE32_RFC4848, BaseEncoding.BASE32_RFC4848_PADDING); // see: https://tools.ietf.org/html/rfc4648 - assertEquals("", base32Encoding.encode(Bytes.from("").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("MY======", base32Encoding.encode(Bytes.from("f").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("MZXQ====", base32Encoding.encode(Bytes.from("fo").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("MZXW6===", base32Encoding.encode(Bytes.from("foo").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("MZXW6YQ=", base32Encoding.encode(Bytes.from("foob").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("MZXW6YTB", base32Encoding.encode(Bytes.from("fooba").array(), ByteOrder.BIG_ENDIAN)); - assertEquals("MZXW6YTBOI======", base32Encoding.encode(Bytes.from("foobar").array(), ByteOrder.BIG_ENDIAN)); - - assertArrayEquals(Bytes.from("").array(), base32Encoding.decode("")); - assertArrayEquals(Bytes.from("f").array(), base32Encoding.decode("MY======")); - assertArrayEquals(Bytes.from("fo").array(), base32Encoding.decode("MZXQ====")); - assertArrayEquals(Bytes.from("foo").array(), base32Encoding.decode("MZXW6===")); - assertArrayEquals(Bytes.from("foob").array(), base32Encoding.decode("MZXW6YQ=")); - assertArrayEquals(Bytes.from("fooba").array(), base32Encoding.decode("MZXW6YTB")); - assertArrayEquals(Bytes.from("foobar").array(), base32Encoding.decode("MZXW6YTBOI======")); + assertEquals("", base32Encoding.encode(Bytes.of("").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("MY======", base32Encoding.encode(Bytes.of("f").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("MZXQ====", base32Encoding.encode(Bytes.of("fo").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("MZXW6===", base32Encoding.encode(Bytes.of("foo").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("MZXW6YQ=", base32Encoding.encode(Bytes.of("foob").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("MZXW6YTB", base32Encoding.encode(Bytes.of("fooba").array(), ByteOrder.BIG_ENDIAN)); + assertEquals("MZXW6YTBOI======", base32Encoding.encode(Bytes.of("foobar").array(), ByteOrder.BIG_ENDIAN)); + + assertArrayEquals(Bytes.of("").array(), base32Encoding.decode("")); + assertArrayEquals(Bytes.of("f").array(), base32Encoding.decode("MY======")); + assertArrayEquals(Bytes.of("fo").array(), base32Encoding.decode("MZXQ====")); + assertArrayEquals(Bytes.of("foo").array(), base32Encoding.decode("MZXW6===")); + assertArrayEquals(Bytes.of("foob").array(), base32Encoding.decode("MZXW6YQ=")); + assertArrayEquals(Bytes.of("fooba").array(), base32Encoding.decode("MZXW6YTB")); + assertArrayEquals(Bytes.of("foobar").array(), base32Encoding.decode("MZXW6YTBOI======")); } @Test diff --git a/src/test/java/at/favre/lib/bytes/BytesByteOrderTest.java b/src/test/java/at/favre/lib/bytes/BytesByteOrderTest.java index 71d137f..0d07b6b 100644 --- a/src/test/java/at/favre/lib/bytes/BytesByteOrderTest.java +++ b/src/test/java/at/favre/lib/bytes/BytesByteOrderTest.java @@ -32,12 +32,12 @@ public class BytesByteOrderTest extends ABytesTest { @Test public void miscInput() { - testOrder(Bytes.from(350)); - testOrder(Bytes.from(172863182736L)); - testOrder(Bytes.from(example_bytes_one)); - testOrder(Bytes.from(example_bytes_four)); - testOrder(Bytes.from(example_bytes_sixteen)); - testOrder(Bytes.from(example_bytes_twentyfour)); + testOrder(Bytes.of(350)); + testOrder(Bytes.of(172863182736L)); + testOrder(Bytes.of(example_bytes_one)); + testOrder(Bytes.of(example_bytes_four)); + testOrder(Bytes.of(example_bytes_sixteen)); + testOrder(Bytes.of(example_bytes_twentyfour)); } private void testOrder(Bytes bytes) { @@ -53,79 +53,79 @@ private void testOrder(Bytes bytes) { @Test public void encodeBinary() { - Bytes b = Bytes.from(example_bytes_four); + Bytes b = Bytes.of(example_bytes_four); assertNotEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeBinary(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).encodeBinary()); assertEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeBinary(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).reverse().encodeBinary()); } @Test public void encodeOct() { - Bytes b = Bytes.from(example_bytes_four); + Bytes b = Bytes.of(example_bytes_four); assertNotEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeOctal(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).encodeOctal()); assertEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeOctal(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).reverse().encodeOctal()); } @Test public void encodeDec() { - Bytes b = Bytes.from(example_bytes_four); + Bytes b = Bytes.of(example_bytes_four); assertNotEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeDec(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).encodeDec()); assertEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeDec(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).reverse().encodeDec()); } @Test public void encodeHex() { - Bytes b = Bytes.from(example_bytes_two); + Bytes b = Bytes.of(example_bytes_two); assertNotEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeHex(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).encodeHex()); assertEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeHex(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).reverse().encodeHex()); } @Test public void encodeBase36() { - Bytes b = Bytes.from(example_bytes_four); + Bytes b = Bytes.of(example_bytes_four); assertNotEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeBase36(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).encodeBase36()); assertEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeBase36(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).reverse().encodeBase36()); } @Test public void encodeBase64() { - Bytes b = Bytes.from(example_bytes_four); + Bytes b = Bytes.of(example_bytes_four); assertNotEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeBase64(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).encodeBase64()); assertEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).encodeBase64(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).reverse().encodeBase64()); } @Test public void toByte() { - Bytes b = Bytes.from(example_bytes_one); + Bytes b = Bytes.of(example_bytes_one); assertEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).toByte(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).toByte()); } @Test public void toChar() { - Bytes b = Bytes.from(example_bytes_two); + Bytes b = Bytes.of(example_bytes_two); assertNotEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).toChar(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).toChar()); } @Test public void toShort() { - Bytes b = Bytes.from(example_bytes_two); + Bytes b = Bytes.of(example_bytes_two); assertNotEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).toShort(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).toShort()); } @Test public void toInt() { - Bytes b = Bytes.from(example_bytes_four); + Bytes b = Bytes.of(example_bytes_four); assertNotEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).toInt(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).toInt()); } @Test public void toLong() { - Bytes b = Bytes.from(example_bytes_eight); + Bytes b = Bytes.of(example_bytes_eight); assertNotEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).toLong(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).toLong()); } @Test public void bigInteger() { - Bytes b = Bytes.from(example_bytes_four); + Bytes b = Bytes.of(example_bytes_four); assertNotEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).toBigInteger(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).toBigInteger()); assertEquals(b.byteOrder(ByteOrder.BIG_ENDIAN).toBigInteger(), b.byteOrder(ByteOrder.LITTLE_ENDIAN).reverse().toBigInteger()); } diff --git a/src/test/java/at/favre/lib/bytes/BytesConstructorTests.java b/src/test/java/at/favre/lib/bytes/BytesConstructorTests.java index d08d46f..6047745 100644 --- a/src/test/java/at/favre/lib/bytes/BytesConstructorTests.java +++ b/src/test/java/at/favre/lib/bytes/BytesConstructorTests.java @@ -122,8 +122,8 @@ public void fromBitSet() { private void checkBitSet(byte[] array) { BitSet bitSet = BitSet.valueOf(array); - assertArrayEquals(array, Bytes.from(bitSet).array()); - assertEquals(bitSet, Bytes.from(bitSet).toBitSet()); + assertArrayEquals(array, Bytes.of(bitSet).array()); + assertEquals(bitSet, Bytes.of(bitSet).toBitSet()); } @Test @@ -137,99 +137,99 @@ public void fromBigInteger() { private void checkBigInteger(byte[] array) { BigInteger bigInteger = new BigInteger(array); - assertArrayEquals(array, Bytes.from(bigInteger).array()); - assertEquals(bigInteger, Bytes.from(bigInteger).toBigInteger()); + assertArrayEquals(array, Bytes.of(bigInteger).array()); + assertEquals(bigInteger, Bytes.of(bigInteger).toBigInteger()); } @Test public void fromBoolean() { - assertArrayEquals(new byte[]{(byte) 1}, Bytes.from(true).array()); - assertArrayEquals(new byte[]{(byte) 0}, Bytes.from(false).array()); + assertArrayEquals(new byte[]{(byte) 1}, Bytes.of(true).array()); + assertArrayEquals(new byte[]{(byte) 0}, Bytes.of(false).array()); } @Test public void fromByte() { byte test = 0x4E; - assertArrayEquals(new byte[]{test}, Bytes.from(test).array()); - assertArrayEquals(new byte[1], Bytes.from((byte) 0).array()); - assertEquals(test, Bytes.from(test).toByte()); + assertArrayEquals(new byte[]{test}, Bytes.of(test).array()); + assertArrayEquals(new byte[1], Bytes.of((byte) 0).array()); + assertEquals(test, Bytes.of(test).toByte()); } @Test public void fromChar() { char test = 5821; byte[] primitiveArray = ByteBuffer.allocate(2).putChar(test).array(); - assertArrayEquals(primitiveArray, Bytes.from(test).array()); - assertArrayEquals(new byte[2], Bytes.from((char) 0).array()); - assertEquals(test, Bytes.from(test).toChar()); + assertArrayEquals(primitiveArray, Bytes.of(test).array()); + assertArrayEquals(new byte[2], Bytes.of((char) 0).array()); + assertEquals(test, Bytes.of(test).toChar()); } @Test public void fromShort() { short test = 12721; byte[] primitiveArray = ByteBuffer.allocate(2).putShort(test).array(); - assertArrayEquals(primitiveArray, Bytes.from(test).array()); - assertArrayEquals(new byte[2], Bytes.from((short) 0).array()); - assertEquals(test, Bytes.from(test).toShort()); + assertArrayEquals(primitiveArray, Bytes.of(test).array()); + assertArrayEquals(new byte[2], Bytes.of((short) 0).array()); + assertEquals(test, Bytes.of(test).toShort()); } @Test public void fromInt() { int test = 722837193; byte[] primitiveArray = ByteBuffer.allocate(4).putInt(test).array(); - assertArrayEquals(primitiveArray, Bytes.from(test).array()); - assertArrayEquals(new byte[4], Bytes.from(0).array()); - assertEquals(test, Bytes.from(test).toInt()); + assertArrayEquals(primitiveArray, Bytes.of(test).array()); + assertArrayEquals(new byte[4], Bytes.of(0).array()); + assertEquals(test, Bytes.of(test).toInt()); } @Test public void fromIntArray() { - assertArrayEquals(new byte[]{0, 0, 0, 1, 0, 0, 0, 2}, Bytes.from(1, 2).array()); - assertArrayEquals(Bytes.from(Bytes.from(871193), Bytes.from(6761), Bytes.from(-917656)).array(), Bytes.from(871193, 6761, -917656).array()); - assertArrayEquals(Bytes.from(Bytes.from(1678), Bytes.from(-223), Bytes.from(11114)).array(), Bytes.from(1678, -223, 11114).array()); - assertArrayEquals(new byte[]{0, 11, 30, 55, 0, 0, 35, 53, 0, 0, 0, 0, 0, 0, 56, -70}, Bytes.from(728631, 9013, 0, 14522).array()); + assertArrayEquals(new byte[]{0, 0, 0, 1, 0, 0, 0, 2}, Bytes.of(1, 2).array()); + assertArrayEquals(Bytes.of(Bytes.of(871193), Bytes.of(6761), Bytes.of(-917656)).array(), Bytes.of(871193, 6761, -917656).array()); + assertArrayEquals(Bytes.of(Bytes.of(1678), Bytes.of(-223), Bytes.of(11114)).array(), Bytes.of(1678, -223, 11114).array()); + assertArrayEquals(new byte[]{0, 11, 30, 55, 0, 0, 35, 53, 0, 0, 0, 0, 0, 0, 56, -70}, Bytes.of(728631, 9013, 0, 14522).array()); } @Test public void fromIntBuffer() { - assertArrayEquals(new byte[]{0, 0, 0, 1, 0, 0, 0, 2}, Bytes.from(IntBuffer.wrap(new int[]{1, 2})).array()); - assertArrayEquals(Bytes.from(Bytes.from(871193), Bytes.from(6761), Bytes.from(-917656)).array(), Bytes.from(IntBuffer.wrap(new int[]{871193, 6761, -917656})).array()); - assertArrayEquals(Bytes.empty().array(), Bytes.from(IntBuffer.allocate(0)).array()); + assertArrayEquals(new byte[]{0, 0, 0, 1, 0, 0, 0, 2}, Bytes.of(IntBuffer.wrap(new int[]{1, 2})).array()); + assertArrayEquals(Bytes.of(Bytes.of(871193), Bytes.of(6761), Bytes.of(-917656)).array(), Bytes.of(IntBuffer.wrap(new int[]{871193, 6761, -917656})).array()); + assertArrayEquals(Bytes.empty().array(), Bytes.of(IntBuffer.allocate(0)).array()); } @Test public void fromLong() { long test = 172283719283L; byte[] primitiveArray = ByteBuffer.allocate(8).putLong(test).array(); - assertArrayEquals(primitiveArray, Bytes.from(test).array()); - assertArrayEquals(new byte[8], Bytes.from(0L).array()); - assertEquals(test, Bytes.from(test).toLong()); + assertArrayEquals(primitiveArray, Bytes.of(test).array()); + assertArrayEquals(new byte[8], Bytes.of(0L).array()); + assertEquals(test, Bytes.of(test).toLong()); } @Test public void fromLongArray() { - assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2}, Bytes.from(new long[]{1, 2}).array()); - assertArrayEquals(Bytes.from(Bytes.from(871193L), Bytes.from(6761L), Bytes.from(-917656L)).array(), Bytes.from(new long[]{871193, 6761, -917656}).array()); - assertArrayEquals(Bytes.from(Bytes.from(1678L), Bytes.from(-223L), Bytes.from(11114L)).array(), Bytes.from(1678L, -223L, 11114L).array()); - assertArrayEquals(Bytes.from(Bytes.from(1273612831678L), Bytes.from(-72639123786223L)).array(), Bytes.from(1273612831678L, -72639123786223L).array()); + assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2}, Bytes.of(new long[]{1, 2}).array()); + assertArrayEquals(Bytes.of(Bytes.of(871193L), Bytes.of(6761L), Bytes.of(-917656L)).array(), Bytes.of(new long[]{871193, 6761, -917656}).array()); + assertArrayEquals(Bytes.of(Bytes.of(1678L), Bytes.of(-223L), Bytes.of(11114L)).array(), Bytes.of(1678L, -223L, 11114L).array()); + assertArrayEquals(Bytes.of(Bytes.of(1273612831678L), Bytes.of(-72639123786223L)).array(), Bytes.of(1273612831678L, -72639123786223L).array()); } @Test public void fromFloat() { float test = 63278.123f; byte[] primitiveArray = ByteBuffer.allocate(4).putFloat(test).array(); - assertArrayEquals(primitiveArray, Bytes.from(test).array()); - assertArrayEquals(new byte[4], Bytes.from(0f).array()); - assertEquals(test, Bytes.from(test).toFloat(), 0.01); + assertArrayEquals(primitiveArray, Bytes.of(test).array()); + assertArrayEquals(new byte[4], Bytes.of(0f).array()); + assertEquals(test, Bytes.of(test).toFloat(), 0.01); } @Test public void fromDouble() { double test = 3423423.8923423974123; byte[] primitiveArray = ByteBuffer.allocate(8).putDouble(test).array(); - assertArrayEquals(primitiveArray, Bytes.from(test).array()); - assertArrayEquals(new byte[8], Bytes.from(0.0).array()); - assertEquals(test, Bytes.from(test).toDouble(), 0.01); + assertArrayEquals(primitiveArray, Bytes.of(test).array()); + assertArrayEquals(new byte[8], Bytes.of(0.0).array()); + assertEquals(test, Bytes.of(test).toDouble(), 0.01); } @Test @@ -243,7 +243,7 @@ public void fromByteBuffer() { } private void checkByteBuffer(byte[] array) { - Bytes b = Bytes.from(ByteBuffer.wrap(array)); + Bytes b = Bytes.of(ByteBuffer.wrap(array)); assertSame(array, b.array()); } @@ -287,18 +287,18 @@ public void fromCharArray() { checkCharArray("é_,,(8áàäöü#+_ ,,mµ"); String s1 = "oaisdj`ßß__.#äöü_- *aé"; - assertArrayEquals(String.valueOf(s1.toCharArray()).getBytes(StandardCharsets.ISO_8859_1), Bytes.from(s1.toCharArray(), StandardCharsets.ISO_8859_1).array()); - assertArrayEquals(String.valueOf(s1.toCharArray()).getBytes(StandardCharsets.UTF_16), Bytes.from(s1.toCharArray(), StandardCharsets.UTF_16).array()); - assertArrayEquals(String.valueOf(s1.toCharArray()).getBytes(StandardCharsets.UTF_8), Bytes.from(s1.toCharArray(), StandardCharsets.UTF_8).array()); - assertArrayEquals(String.valueOf(s1.substring(0, 1).toCharArray()).getBytes(StandardCharsets.UTF_8), Bytes.from(s1.toCharArray(), StandardCharsets.UTF_8, 0, 1).array()); - assertArrayEquals(String.valueOf(s1.substring(3, 7).toCharArray()).getBytes(StandardCharsets.UTF_8), Bytes.from(s1.toCharArray(), StandardCharsets.UTF_8, 3, 4).array()); - assertArrayEquals(Bytes.empty().array(), Bytes.from(CharBuffer.allocate(0)).array()); + assertArrayEquals(String.valueOf(s1.toCharArray()).getBytes(StandardCharsets.ISO_8859_1), Bytes.of(s1.toCharArray(), StandardCharsets.ISO_8859_1).array()); + assertArrayEquals(String.valueOf(s1.toCharArray()).getBytes(StandardCharsets.UTF_16), Bytes.of(s1.toCharArray(), StandardCharsets.UTF_16).array()); + assertArrayEquals(String.valueOf(s1.toCharArray()).getBytes(StandardCharsets.UTF_8), Bytes.of(s1.toCharArray(), StandardCharsets.UTF_8).array()); + assertArrayEquals(String.valueOf(s1.substring(0, 1).toCharArray()).getBytes(StandardCharsets.UTF_8), Bytes.of(s1.toCharArray(), StandardCharsets.UTF_8, 0, 1).array()); + assertArrayEquals(String.valueOf(s1.substring(3, 7).toCharArray()).getBytes(StandardCharsets.UTF_8), Bytes.of(s1.toCharArray(), StandardCharsets.UTF_8, 3, 4).array()); + assertArrayEquals(Bytes.empty().array(), Bytes.of(CharBuffer.allocate(0)).array()); } @Test public void toCharArray() { String unicodeString = "|µ€@7é8ahslishalsdalöskdḼơᶉëᶆ ȋṕšᶙṁ ḍỡḽǭᵳ ʂǐť ӓṁệẗ, ĉṓɲṩḙċ"; - assertArrayEquals(Bytes.from(unicodeString.toCharArray()).array(), Bytes.from(Bytes.from(unicodeString).toCharArray()).array()); + assertArrayEquals(Bytes.of(unicodeString.toCharArray()).array(), Bytes.of(Bytes.of(unicodeString).toCharArray()).array()); checkToCharArray(unicodeString, StandardCharsets.UTF_8); checkToCharArray(unicodeString, StandardCharsets.UTF_16); @@ -314,9 +314,9 @@ public void toCharArray() { private void checkToCharArray(String string, Charset charset) { byte[] b0 = String.valueOf(string.toCharArray()).getBytes(charset); - char[] charArray = Bytes.from(b0).toCharArray(charset); + char[] charArray = Bytes.of(b0).toCharArray(charset); assertEquals(string, new String(charArray)); - assertArrayEquals(string.toCharArray(), Bytes.from(string.toCharArray(), charset).toCharArray(charset)); + assertArrayEquals(string.toCharArray(), Bytes.of(string.toCharArray(), charset).toCharArray(charset)); } @Test(expected = NullPointerException.class) @@ -326,28 +326,28 @@ public void toCharArrayShouldThroughNullPointer() { @Test public void fromMultipleBytes() { - assertArrayEquals(new byte[]{0x01, 0x02, 0x03}, Bytes.from(Bytes.from((byte) 0x01), Bytes.from((byte) 0x02), Bytes.from((byte) 0x03)).array()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03}, Bytes.of(Bytes.of((byte) 0x01), Bytes.of((byte) 0x02), Bytes.of((byte) 0x03)).array()); } private void checkString(String string, Charset charset) { - Bytes b = Bytes.from(string, charset); + Bytes b = Bytes.of(string, charset); assertArrayEquals(string.getBytes(charset), b.array()); assertEquals(new String(string.getBytes(charset), charset), b.encodeCharset(charset)); if (charset != StandardCharsets.UTF_8) { - Bytes bUtf8 = Bytes.from(string); + Bytes bUtf8 = Bytes.of(string); assertArrayEquals(string.getBytes(StandardCharsets.UTF_8), bUtf8.array()); assertEquals(new String(string.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8), bUtf8.encodeUtf8()); } else { - Bytes bNormalized = Bytes.from(string, Normalizer.Form.NFKD); + Bytes bNormalized = Bytes.of(string, Normalizer.Form.NFKD); assertArrayEquals(Normalizer.normalize(string, Normalizer.Form.NFKD).getBytes(charset), bNormalized.array()); } } private void checkCharArray(String s) { - Bytes b1 = Bytes.from(s.toCharArray()); - Bytes b2 = Bytes.from(s.toCharArray(), StandardCharsets.UTF_8); - Bytes b3 = Bytes.from(CharBuffer.wrap(s.toCharArray())); + Bytes b1 = Bytes.of(s.toCharArray()); + Bytes b2 = Bytes.of(s.toCharArray(), StandardCharsets.UTF_8); + Bytes b3 = Bytes.of(CharBuffer.wrap(s.toCharArray())); assertArrayEquals(String.valueOf(s.toCharArray()).getBytes(StandardCharsets.UTF_8), b1.array()); assertArrayEquals(String.valueOf(s.toCharArray()).getBytes(StandardCharsets.UTF_8), b2.array()); assertArrayEquals(String.valueOf(s.toCharArray()).getBytes(StandardCharsets.UTF_8), b3.array()); @@ -366,20 +366,20 @@ public void fromInputStream() { } private void checkInputStream(byte[] array) { - assertArrayEquals(array, Bytes.from(new ByteArrayInputStream(array)).array()); + assertArrayEquals(array, Bytes.of(new ByteArrayInputStream(array)).array()); } @Test public void fromInputStreamLimited() { Bytes data = Bytes.random(1090 * 1003); - assertArrayEquals(data.resize(5123, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array(), Bytes.from(new ByteArrayInputStream(data.array()), 5123).array()); + assertArrayEquals(data.resize(5123, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array(), Bytes.of(new ByteArrayInputStream(data.array()), 5123).array()); - assertArrayEquals(new byte[0], Bytes.from(new ByteArrayInputStream(example_bytes_sixteen), 0).array()); - assertArrayEquals(new byte[]{0x7E}, Bytes.from(new ByteArrayInputStream(example_bytes_sixteen), 1).array()); - assertArrayEquals(new byte[]{0x7E, (byte) 0xD1}, Bytes.from(new ByteArrayInputStream(example_bytes_sixteen), 2).array()); - assertArrayEquals(new byte[]{0x7E, (byte) 0xD1, (byte) 0xFD}, Bytes.from(new ByteArrayInputStream(example_bytes_sixteen), 3).array()); - assertArrayEquals(new byte[]{0x7E, (byte) 0xD1, (byte) 0xFD, (byte) 0xAA}, Bytes.from(new ByteArrayInputStream(example_bytes_sixteen), 4).array()); - assertArrayEquals(example_bytes_sixteen, Bytes.from(new ByteArrayInputStream(example_bytes_sixteen), 128).array()); + assertArrayEquals(new byte[0], Bytes.of(new ByteArrayInputStream(example_bytes_sixteen), 0).array()); + assertArrayEquals(new byte[]{0x7E}, Bytes.of(new ByteArrayInputStream(example_bytes_sixteen), 1).array()); + assertArrayEquals(new byte[]{0x7E, (byte) 0xD1}, Bytes.of(new ByteArrayInputStream(example_bytes_sixteen), 2).array()); + assertArrayEquals(new byte[]{0x7E, (byte) 0xD1, (byte) 0xFD}, Bytes.of(new ByteArrayInputStream(example_bytes_sixteen), 3).array()); + assertArrayEquals(new byte[]{0x7E, (byte) 0xD1, (byte) 0xFD, (byte) 0xAA}, Bytes.of(new ByteArrayInputStream(example_bytes_sixteen), 4).array()); + assertArrayEquals(example_bytes_sixteen, Bytes.of(new ByteArrayInputStream(example_bytes_sixteen), 128).array()); } @Test @@ -394,12 +394,12 @@ public void fromDataInput() { } private void checkDataInput(byte[] array) { - assertArrayEquals(array, Bytes.from((DataInput) new DataInputStream(new ByteArrayInputStream(array)), array.length).array()); + assertArrayEquals(array, Bytes.of((DataInput) new DataInputStream(new ByteArrayInputStream(array)), array.length).array()); } @Test(expected = IllegalStateException.class) public void fromDataInputShouldThrowException() { - Bytes.from((DataInput) new DataInputStream(new ByteArrayInputStream(example_bytes_one)), 2); + Bytes.of((DataInput) new DataInputStream(new ByteArrayInputStream(example_bytes_one)), 2); } @Test @@ -413,42 +413,42 @@ public void fromList() { } private void checkList(byte[] array) { - Bytes bList = Bytes.from(Util.Converter.toList(array)); - Bytes bLinkedList = Bytes.from(new LinkedList<>(Util.Converter.toList(array))); + Bytes bList = Bytes.of(Util.Converter.toList(array)); + Bytes bLinkedList = Bytes.of(new LinkedList<>(Util.Converter.toList(array))); assertArrayEquals(array, bList.array()); assertArrayEquals(array, bLinkedList.array()); } @Test public void fromVariousBytes() { - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one).array()); - assertArrayEquals(example_bytes_two, Bytes.from(example_bytes_two).array()); - assertArrayEquals(example_bytes_seven, Bytes.from(example_bytes_seven).array()); - assertArrayEquals(example_bytes_sixteen, Bytes.from(example_bytes_sixteen).array()); - assertArrayNotEquals(example2_bytes_seven, Bytes.from(example_bytes_seven).array()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one).array()); + assertArrayEquals(example_bytes_two, Bytes.of(example_bytes_two).array()); + assertArrayEquals(example_bytes_seven, Bytes.of(example_bytes_seven).array()); + assertArrayEquals(example_bytes_sixteen, Bytes.of(example_bytes_sixteen).array()); + assertArrayNotEquals(example2_bytes_seven, Bytes.of(example_bytes_seven).array()); - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one[0]).array()); - assertArrayEquals(new byte[1], Bytes.from((byte) 0).array()); - assertArrayNotEquals(new byte[0], Bytes.from((byte) 1).array()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one[0]).array()); + assertArrayEquals(new byte[1], Bytes.of((byte) 0).array()); + assertArrayNotEquals(new byte[0], Bytes.of((byte) 1).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_one, example_bytes_one, example_bytes_one), Bytes.from(example_bytes_one, example_bytes_one, example_bytes_one).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_two, example_bytes_seven), Bytes.from(example_bytes_two, example_bytes_seven).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_one, example_bytes_sixteen), Bytes.from(example_bytes_one, example_bytes_sixteen).array()); - assertArrayNotEquals(Util.Byte.concat(example_bytes_sixteen, example_bytes_one), Bytes.from(example_bytes_one, example_bytes_sixteen).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_one, example_bytes_one, example_bytes_one), Bytes.of(example_bytes_one, example_bytes_one, example_bytes_one).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_two, example_bytes_seven), Bytes.of(example_bytes_two, example_bytes_seven).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_one, example_bytes_sixteen), Bytes.of(example_bytes_one, example_bytes_sixteen).array()); + assertArrayNotEquals(Util.Byte.concat(example_bytes_sixteen, example_bytes_one), Bytes.of(example_bytes_one, example_bytes_sixteen).array()); - assertArrayEquals(new byte[]{1, 2, 3}, Bytes.from((byte) 1, (byte) 2, (byte) 3).array()); - assertArrayEquals(new byte[2], Bytes.from((byte) 0, (byte) 0).array()); - assertArrayNotEquals(new byte[2], Bytes.from((byte) 1, (byte) 0).array()); + assertArrayEquals(new byte[]{1, 2, 3}, Bytes.of((byte) 1, (byte) 2, (byte) 3).array()); + assertArrayEquals(new byte[2], Bytes.of((byte) 0, (byte) 0).array()); + assertArrayNotEquals(new byte[2], Bytes.of((byte) 1, (byte) 0).array()); - assertArrayEquals(new byte[0], Bytes.fromNullSafe(null).array()); - assertArrayEquals(example_bytes_two, Bytes.fromNullSafe(example_bytes_two).array()); - assertArrayEquals(example_bytes_sixteen, Bytes.fromNullSafe(example_bytes_sixteen).array()); + assertArrayEquals(new byte[0], Bytes.ofNullSafe(null).array()); + assertArrayEquals(example_bytes_two, Bytes.ofNullSafe(example_bytes_two).array()); + assertArrayEquals(example_bytes_sixteen, Bytes.ofNullSafe(example_bytes_sixteen).array()); } @Test public void fromPartByte() { - assertArrayEquals(new byte[]{example_bytes_four[1]}, Bytes.from(example_bytes_four, 1, 1).array()); - assertArrayEquals(new byte[]{example_bytes_eight[4], example_bytes_eight[5], example_bytes_eight[6]}, Bytes.from(example_bytes_eight, 4, 3).array()); + assertArrayEquals(new byte[]{example_bytes_four[1]}, Bytes.of(example_bytes_four, 1, 1).array()); + assertArrayEquals(new byte[]{example_bytes_eight[4], example_bytes_eight[5], example_bytes_eight[6]}, Bytes.of(example_bytes_eight, 4, 3).array()); } @Test @@ -460,12 +460,12 @@ public void fromFile() throws Exception { stream.write(randomBytes.array()); } - assertArrayEquals(randomBytes.array(), Bytes.from(tempFile).array()); + assertArrayEquals(randomBytes.array(), Bytes.of(tempFile).array()); } @Test(expected = IllegalArgumentException.class) public void fromFileNotExisting() { - Bytes.from(new File("doesnotexist")); + Bytes.of(new File("doesnotexist")); } @Test @@ -479,7 +479,7 @@ public void fromFileCannotRead() throws Exception { } assertTrue(tempFile.setReadable(false)); try { - Bytes.from(tempFile); + Bytes.of(tempFile); fail(); } catch (IllegalStateException ignored) { } @@ -496,10 +496,10 @@ public void fromFileOffset() throws Exception { for (int lenI = 1; lenI < bytes.length() + 1; lenI++) { for (int offsetI = 0; offsetI < bytes.length(); offsetI++) { if (offsetI + lenI > bytes.length()) break; - assertEquals(bytes.copy(offsetI, lenI), Bytes.from(tempFile, offsetI, lenI)); + assertEquals(bytes.copy(offsetI, lenI), Bytes.of(tempFile, offsetI, lenI)); } } - assertEquals(Bytes.from(tempFile), Bytes.from(tempFile, 0, (int) tempFile.length())); + assertEquals(Bytes.of(tempFile), Bytes.of(tempFile, 0, (int) tempFile.length())); } @Test @@ -510,13 +510,13 @@ public void fromFileOffsetWithIllegalOffsetOrLength() throws Exception { } try { - Bytes.from(tempFile, 0, 5); + Bytes.of(tempFile, 0, 5); fail(); } catch (IllegalStateException ignored) { } try { - Bytes.from(tempFile, 5, 1); + Bytes.of(tempFile, 5, 1); fail(); } catch (IllegalStateException ignored) { } @@ -525,7 +525,7 @@ public void fromFileOffsetWithIllegalOffsetOrLength() throws Exception { @Test public void fromObjectArray() { Byte[] objectArray = new Byte[]{0x01, 0x02, 0x03, 0x04}; - Bytes b = Bytes.from(objectArray); + Bytes b = Bytes.of(objectArray); assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04}, b.array()); } @@ -538,13 +538,13 @@ public void fromUUID() { } private void testUUID(UUID uuid) { - Bytes b = Bytes.from(uuid); + Bytes b = Bytes.of(uuid); assertEquals(16, b.length()); assertEquals(uuid, b.toUUID()); } @Test(expected = NullPointerException.class) public void fromUUIDNullArgument() { - Bytes.from((UUID) null); + Bytes.of((UUID) null); } } diff --git a/src/test/java/at/favre/lib/bytes/BytesMiscTest.java b/src/test/java/at/favre/lib/bytes/BytesMiscTest.java index 32d4de5..d3d1cef 100644 --- a/src/test/java/at/favre/lib/bytes/BytesMiscTest.java +++ b/src/test/java/at/favre/lib/bytes/BytesMiscTest.java @@ -54,8 +54,8 @@ public void testHashcode() { Bytes instance = Bytes.wrap(example_bytes_seven); assertEquals(instance.hashCode(), instance.hashCode()); assertNotEquals(0, instance.hashCode()); - assertEquals(Bytes.wrap(example_bytes_seven).hashCode(), Bytes.from(example_bytes_seven).hashCode()); - assertEquals(Bytes.wrap(example2_bytes_seven).hashCode(), Bytes.from(example2_bytes_seven).hashCode()); + assertEquals(Bytes.wrap(example_bytes_seven).hashCode(), Bytes.of(example_bytes_seven).hashCode()); + assertEquals(Bytes.wrap(example2_bytes_seven).hashCode(), Bytes.of(example2_bytes_seven).hashCode()); assertNotEquals(Bytes.wrap(example_bytes_seven).hashCode(), Bytes.wrap(example2_bytes_seven).hashCode()); assertNotEquals(Bytes.wrap(example_bytes_eight).hashCode(), Bytes.wrap(example2_bytes_seven).hashCode()); assertNotEquals(0, Bytes.wrap(example2_bytes_seven).hashCode()); @@ -66,9 +66,9 @@ public void testHashcode() { public void testEquals() { assertTrue(Bytes.wrap(new byte[0]).equals(Bytes.wrap(new byte[0]))); assertTrue(Bytes.wrap(new byte[16]).equals(Bytes.wrap(new byte[16]))); - assertTrue(Bytes.wrap(example_bytes_seven).equals(Bytes.from(example_bytes_seven))); - assertFalse(Bytes.wrap(example_bytes_seven).byteOrder(ByteOrder.BIG_ENDIAN).equals(Bytes.from(example_bytes_seven).byteOrder(ByteOrder.LITTLE_ENDIAN))); - assertTrue(Bytes.wrap(example2_bytes_seven).equals(Bytes.from(example2_bytes_seven))); + assertTrue(Bytes.wrap(example_bytes_seven).equals(Bytes.of(example_bytes_seven))); + assertFalse(Bytes.wrap(example_bytes_seven).byteOrder(ByteOrder.BIG_ENDIAN).equals(Bytes.of(example_bytes_seven).byteOrder(ByteOrder.LITTLE_ENDIAN))); + assertTrue(Bytes.wrap(example2_bytes_seven).equals(Bytes.of(example2_bytes_seven))); assertFalse(Bytes.wrap(example_bytes_seven).equals(Bytes.wrap(example2_bytes_seven))); assertFalse(Bytes.wrap(example_bytes_eight).equals(Bytes.wrap(example2_bytes_seven))); } @@ -107,10 +107,10 @@ public void testEqualsWithByteBuffer() { @Test public void testEqualsContent() { assertTrue(Bytes.wrap(new byte[0]).byteOrder(ByteOrder.BIG_ENDIAN).equalsContent(Bytes.wrap(new byte[0]).byteOrder(ByteOrder.LITTLE_ENDIAN))); - assertTrue(Bytes.from(example_bytes_seven).byteOrder(ByteOrder.BIG_ENDIAN).equalsContent(Bytes.from(example_bytes_seven).byteOrder(ByteOrder.LITTLE_ENDIAN))); - assertTrue(Bytes.from(example_bytes_seven).equalsContent(Bytes.from(example_bytes_seven).byteOrder(ByteOrder.LITTLE_ENDIAN))); - assertTrue(Bytes.from(example_bytes_seven).equalsContent(Bytes.from(example_bytes_seven))); - assertTrue(Bytes.from(example_bytes_seven).readOnly().equalsContent(Bytes.from(example_bytes_seven))); + assertTrue(Bytes.of(example_bytes_seven).byteOrder(ByteOrder.BIG_ENDIAN).equalsContent(Bytes.of(example_bytes_seven).byteOrder(ByteOrder.LITTLE_ENDIAN))); + assertTrue(Bytes.of(example_bytes_seven).equalsContent(Bytes.of(example_bytes_seven).byteOrder(ByteOrder.LITTLE_ENDIAN))); + assertTrue(Bytes.of(example_bytes_seven).equalsContent(Bytes.of(example_bytes_seven))); + assertTrue(Bytes.of(example_bytes_seven).readOnly().equalsContent(Bytes.of(example_bytes_seven))); } @Test @@ -118,36 +118,36 @@ public void testCompareTo() { byte[] b1 = new byte[]{0x01}; byte[] b2 = new byte[]{0x01, 0x02}; - assertTrue(-1 >= Bytes.from(b1).compareTo(Bytes.from(b2))); - assertTrue(1 <= Bytes.from(b2).compareTo(Bytes.from(b1))); - assertEquals(0, Bytes.from(b1).compareTo(Bytes.from(b1))); + assertTrue(-1 >= Bytes.of(b1).compareTo(Bytes.of(b2))); + assertTrue(1 <= Bytes.of(b2).compareTo(Bytes.of(b1))); + assertEquals(0, Bytes.of(b1).compareTo(Bytes.of(b1))); byte[] bOne = new byte[]{0x01}; byte[] bTwo = new byte[]{0x02}; - assertTrue(-1 >= Bytes.from(bOne).compareTo(Bytes.from(bTwo))); - assertTrue(1 <= Bytes.from(bTwo).compareTo(Bytes.from(bOne))); - assertEquals(0, Bytes.from(bOne).compareTo(Bytes.from(bOne))); + assertTrue(-1 >= Bytes.of(bOne).compareTo(Bytes.of(bTwo))); + assertTrue(1 <= Bytes.of(bTwo).compareTo(Bytes.of(bOne))); + assertEquals(0, Bytes.of(bOne).compareTo(Bytes.of(bOne))); } @Test public void testLength() { - assertEquals(0, Bytes.from(new byte[0]).length()); + assertEquals(0, Bytes.of(new byte[0]).length()); for (int i = 0; i < 128; i++) { - assertEquals(i, Bytes.from(new byte[i]).length()); - assertEquals(i * 8, Bytes.from(new byte[i]).lengthBit()); + assertEquals(i, Bytes.of(new byte[i]).length()); + assertEquals(i * 8, Bytes.of(new byte[i]).lengthBit()); assertEquals(i, Bytes.allocate(i).length()); } } @Test public void testIsEmpty() { - assertTrue(Bytes.from(new byte[0]).isEmpty()); + assertTrue(Bytes.of(new byte[0]).isEmpty()); assertTrue(Bytes.allocate(0).isEmpty()); - assertFalse(Bytes.from(new byte[1]).isEmpty()); + assertFalse(Bytes.of(new byte[1]).isEmpty()); assertFalse(Bytes.allocate(1).isEmpty()); - assertFalse(Bytes.from(example_bytes_seven).isEmpty()); + assertFalse(Bytes.of(example_bytes_seven).isEmpty()); } @SuppressWarnings("SimplifiableJUnitAssertion") @@ -155,18 +155,18 @@ public void testIsEmpty() { public void containsTest() { assertEquals(false, Bytes.allocate(0).contains((byte) 0xFD)); assertEquals(true, Bytes.allocate(128).contains((byte) 0x00)); - assertEquals(true, Bytes.from(example_bytes_seven).contains((byte) 0xFD)); - assertEquals(true, Bytes.from(example_bytes_seven).contains((byte) 0xAF)); - assertEquals(false, Bytes.from(example_bytes_seven).contains((byte) 0x00)); + assertEquals(true, Bytes.of(example_bytes_seven).contains((byte) 0xFD)); + assertEquals(true, Bytes.of(example_bytes_seven).contains((byte) 0xAF)); + assertEquals(false, Bytes.of(example_bytes_seven).contains((byte) 0x00)); } @Test public void indexOfByte() { assertEquals(-1, Bytes.allocate(0).indexOf((byte) 0xFD)); assertEquals(0, Bytes.allocate(128).indexOf((byte) 0x00)); - assertEquals(2, Bytes.from(example_bytes_seven).indexOf((byte) 0xFD)); - assertEquals(5, Bytes.from(example_bytes_seven).indexOf((byte) 0xAF)); - assertEquals(-1, Bytes.from(example_bytes_seven).indexOf((byte) 0x00)); + assertEquals(2, Bytes.of(example_bytes_seven).indexOf((byte) 0xFD)); + assertEquals(5, Bytes.of(example_bytes_seven).indexOf((byte) 0xAF)); + assertEquals(-1, Bytes.of(example_bytes_seven).indexOf((byte) 0x00)); } @Test @@ -174,24 +174,24 @@ public void indexOfByteFromIndex() { assertEquals(-1, Bytes.allocate(0).indexOf((byte) 0xFD, 0)); assertEquals(-1, Bytes.allocate(0).indexOf((byte) 0xFD, 100)); assertEquals(5, Bytes.allocate(128).indexOf((byte) 0x00, 5)); - assertEquals(2, Bytes.from(example_bytes_sixteen).indexOf((byte) 0xFD, 0)); - assertEquals(10, Bytes.from(example_bytes_sixteen).indexOf((byte) 0xFD, 5)); + assertEquals(2, Bytes.of(example_bytes_sixteen).indexOf((byte) 0xFD, 0)); + assertEquals(10, Bytes.of(example_bytes_sixteen).indexOf((byte) 0xFD, 5)); } @Test public void indexOfArray() { assertEquals(-1, Bytes.allocate(0).indexOf(new byte[]{(byte) 0xFD})); assertEquals(-1, Bytes.allocate(1).indexOf(new byte[0])); - assertEquals(2, Bytes.from(example_bytes_seven).indexOf(new byte[]{(byte) 0xFD, (byte) 0xFF})); - assertEquals(-1, Bytes.from(example_bytes_seven).indexOf(new byte[]{(byte) 0xFD, (byte) 0x00})); + assertEquals(2, Bytes.of(example_bytes_seven).indexOf(new byte[]{(byte) 0xFD, (byte) 0xFF})); + assertEquals(-1, Bytes.of(example_bytes_seven).indexOf(new byte[]{(byte) 0xFD, (byte) 0x00})); } @Test public void indexOfArrayFromIndex() { assertEquals(-1, Bytes.allocate(0).indexOf(new byte[]{(byte) 0xFD}, 0)); assertEquals(-1, Bytes.allocate(1).indexOf(new byte[0], 0)); - assertEquals(-1, Bytes.from(example_bytes_seven).indexOf(new byte[]{(byte) 0xFD, (byte) 0xFF}, 8)); - assertEquals(2, Bytes.from(new byte[]{(byte) 0x8E, (byte) 0xD1, (byte) 0x8E, (byte) 0xD1, 0x12, (byte) 0xAF, (byte) 0x78, 0x09, 0x1E, (byte) 0xD1, (byte) 0xFD, (byte) 0xAA, 0x12}).indexOf(new byte[]{(byte) 0x8E, (byte) 0xD1}, 1)); + assertEquals(-1, Bytes.of(example_bytes_seven).indexOf(new byte[]{(byte) 0xFD, (byte) 0xFF}, 8)); + assertEquals(2, Bytes.of(new byte[]{(byte) 0x8E, (byte) 0xD1, (byte) 0x8E, (byte) 0xD1, 0x12, (byte) 0xAF, (byte) 0x78, 0x09, 0x1E, (byte) 0xD1, (byte) 0xFD, (byte) 0xAA, 0x12}).indexOf(new byte[]{(byte) 0x8E, (byte) 0xD1}, 1)); } @Test @@ -200,20 +200,20 @@ public void startsWidth() { assertTrue(Bytes.allocate(1).startsWith(new byte[1])); assertTrue(Bytes.allocate(128).startsWith(new byte[1])); assertTrue(Bytes.allocate(128).startsWith(new byte[128])); - assertTrue(Bytes.from(example_bytes_seven).startsWith(new byte[]{0x4A})); - assertTrue(Bytes.from(example_bytes_seven).startsWith(new byte[]{0x4A, (byte) 0x94})); - assertTrue(Bytes.from(example_bytes_seven).startsWith(new byte[]{0x4A, (byte) 0x94, (byte) 0xFD})); - assertFalse(Bytes.from(example_bytes_seven).startsWith(new byte[]{0x4A, (byte) 0x94, (byte) 0x1D})); - assertTrue(Bytes.from(example_bytes_seven).startsWith(Bytes.from(example_bytes_seven).array())); - assertFalse(Bytes.from(example_bytes_seven).startsWith(Bytes.from(example_bytes_seven).append(0x30).array())); + assertTrue(Bytes.of(example_bytes_seven).startsWith(new byte[]{0x4A})); + assertTrue(Bytes.of(example_bytes_seven).startsWith(new byte[]{0x4A, (byte) 0x94})); + assertTrue(Bytes.of(example_bytes_seven).startsWith(new byte[]{0x4A, (byte) 0x94, (byte) 0xFD})); + assertFalse(Bytes.of(example_bytes_seven).startsWith(new byte[]{0x4A, (byte) 0x94, (byte) 0x1D})); + assertTrue(Bytes.of(example_bytes_seven).startsWith(Bytes.of(example_bytes_seven).array())); + assertFalse(Bytes.of(example_bytes_seven).startsWith(Bytes.of(example_bytes_seven).append(0x30).array())); } @Test public void endsWith() { - assertTrue(Bytes.from(example_bytes_seven).endsWith(new byte[]{(byte) 0xFF, 0x1E, (byte) 0xAF, (byte) 0xED})); - assertTrue(Bytes.from(example_bytes_seven).endsWith(new byte[]{0x1E, (byte) 0xAF, (byte) 0xED})); - assertTrue(Bytes.from(example_bytes_seven).endsWith(new byte[]{(byte) 0xAF, (byte) 0xED})); - assertTrue(Bytes.from(example_bytes_seven).endsWith(new byte[]{(byte) 0xED})); + assertTrue(Bytes.of(example_bytes_seven).endsWith(new byte[]{(byte) 0xFF, 0x1E, (byte) 0xAF, (byte) 0xED})); + assertTrue(Bytes.of(example_bytes_seven).endsWith(new byte[]{0x1E, (byte) 0xAF, (byte) 0xED})); + assertTrue(Bytes.of(example_bytes_seven).endsWith(new byte[]{(byte) 0xAF, (byte) 0xED})); + assertTrue(Bytes.of(example_bytes_seven).endsWith(new byte[]{(byte) 0xED})); assertFalse(Bytes.allocate(0).endsWith(new byte[1])); assertTrue(Bytes.allocate(1).endsWith(new byte[1])); assertTrue(Bytes.allocate(128).endsWith(new byte[1])); @@ -224,9 +224,9 @@ public void endsWith() { public void lastIndexOf() { assertEquals(-1, Bytes.allocate(0).lastIndexOf((byte) 0xFD)); assertEquals(127, Bytes.allocate(128).lastIndexOf((byte) 0x00)); - assertEquals(2, Bytes.from(example_bytes_seven).lastIndexOf((byte) 0xFD)); - assertEquals(5, Bytes.from(example_bytes_seven).lastIndexOf((byte) 0xAF)); - assertEquals(-1, Bytes.from(example_bytes_seven).lastIndexOf((byte) 0x00)); + assertEquals(2, Bytes.of(example_bytes_seven).lastIndexOf((byte) 0xFD)); + assertEquals(5, Bytes.of(example_bytes_seven).lastIndexOf((byte) 0xAF)); + assertEquals(-1, Bytes.of(example_bytes_seven).lastIndexOf((byte) 0x00)); } @Test @@ -237,18 +237,18 @@ public void bitAt() { } for (int i = 0; i < 8; i++) { - assertTrue(Bytes.from((byte) 0xFF).bitAt(i)); + assertTrue(Bytes.of((byte) 0xFF).bitAt(i)); } - assertFalse(Bytes.from((byte) 8).bitAt(0)); - assertFalse(Bytes.from((byte) 8).bitAt(1)); - assertFalse(Bytes.from((byte) 8).bitAt(2)); - assertTrue(Bytes.from((byte) 8).bitAt(3)); - assertFalse(Bytes.from((byte) 8).bitAt(4)); - assertFalse(Bytes.from((byte) 0b11010000).bitAt(0)); - assertFalse(Bytes.from((byte) 0b10010000).bitAt(0)); - assertTrue(Bytes.from((byte) 0b10010001).bitAt(0)); - assertFalse(Bytes.from((byte) 0b0010_1000).bitAt(4)); + assertFalse(Bytes.of((byte) 8).bitAt(0)); + assertFalse(Bytes.of((byte) 8).bitAt(1)); + assertFalse(Bytes.of((byte) 8).bitAt(2)); + assertTrue(Bytes.of((byte) 8).bitAt(3)); + assertFalse(Bytes.of((byte) 8).bitAt(4)); + assertFalse(Bytes.of((byte) 0b11010000).bitAt(0)); + assertFalse(Bytes.of((byte) 0b10010000).bitAt(0)); + assertTrue(Bytes.of((byte) 0b10010001).bitAt(0)); + assertFalse(Bytes.of((byte) 0b0010_1000).bitAt(4)); assertFalse(Bytes.parseBinary("101111110101100100110010011111001011101110110011011000010000000").bitAt(54)); try { @@ -268,7 +268,7 @@ public void bitAt() { public void byteAt() { assertEquals(0, Bytes.allocate(1).byteAt(0)); assertEquals(0, Bytes.allocate(128).byteAt(127)); - assertEquals(-1, Bytes.from((byte) 0b1111_1111).byteAt(0)); + assertEquals(-1, Bytes.of((byte) 0b1111_1111).byteAt(0)); for (int i = 0; i < example_bytes_twentyfour.length; i++) { assertEquals(example_bytes_twentyfour[i], Bytes.wrap(example_bytes_twentyfour).byteAt(i)); @@ -291,7 +291,7 @@ public void byteAt() { public void unsignedByteAt() { assertEquals(0, Bytes.allocate(1).unsignedByteAt(0)); assertEquals(0, Bytes.allocate(128).unsignedByteAt(127)); - assertEquals(255, Bytes.from((byte) 0b1111_1111).unsignedByteAt(0)); + assertEquals(255, Bytes.of((byte) 0b1111_1111).unsignedByteAt(0)); try { Bytes.allocate(1).unsignedByteAt(1); @@ -437,8 +437,8 @@ public void count() { assertEquals(0, Bytes.allocate(0).count((byte) 0)); assertEquals(1, Bytes.allocate(1).count((byte) 0)); assertEquals(128, Bytes.allocate(128).count((byte) 0)); - assertEquals(3, Bytes.from(example_bytes_twentyfour).count((byte) 0xAA)); - assertEquals(1, Bytes.from(example_bytes_seven).count((byte) 0xAF)); + assertEquals(3, Bytes.of(example_bytes_twentyfour).count((byte) 0xAA)); + assertEquals(1, Bytes.of(example_bytes_seven).count((byte) 0xAF)); } @Test @@ -447,17 +447,17 @@ public void countByteArray() { assertEquals(0, Bytes.allocate(1).count(new byte[0])); assertEquals(0, Bytes.allocate(128).count(new byte[0])); assertEquals(128, Bytes.allocate(128).count(new byte[]{0})); - assertEquals(3, Bytes.from(example_bytes_twentyfour).count(new byte[]{(byte) 0xFD})); - assertEquals(3, Bytes.from(example_bytes_twentyfour).count(new byte[]{(byte) 0xD1})); - assertEquals(0, Bytes.from(example_bytes_twentyfour).count(new byte[]{(byte) 0x22})); - assertEquals(1, Bytes.from(example_bytes_eight).count(new byte[]{(byte) 0xAF})); - assertEquals(0, Bytes.from(example_bytes_eight).count(new byte[]{(byte) 0xAF, 0x00})); - assertEquals(0, Bytes.from(example_bytes_eight).count(new byte[]{(byte) 0xED})); - assertEquals(0, Bytes.from(example_bytes_eight).count(new byte[]{(byte) 0x22})); - assertEquals(2, Bytes.from(new byte[]{0, 1, 2, 3, 0, 1, 0}).count(new byte[]{0, 1})); - assertEquals(1, Bytes.from(new byte[]{0, 1, 2, 3, 0, 1, 0}).count(new byte[]{0, 1, 2})); - assertEquals(1, Bytes.from(new byte[]{0, 1, 2, 3, 0, 1, 0}).count(new byte[]{0, 1, 2, 3})); - assertEquals(0, Bytes.from(new byte[]{0, 1, 2, 3, 0, 1, 0}).count(new byte[]{0, 1, 2, 0})); + assertEquals(3, Bytes.of(example_bytes_twentyfour).count(new byte[]{(byte) 0xFD})); + assertEquals(3, Bytes.of(example_bytes_twentyfour).count(new byte[]{(byte) 0xD1})); + assertEquals(0, Bytes.of(example_bytes_twentyfour).count(new byte[]{(byte) 0x22})); + assertEquals(1, Bytes.of(example_bytes_eight).count(new byte[]{(byte) 0xAF})); + assertEquals(0, Bytes.of(example_bytes_eight).count(new byte[]{(byte) 0xAF, 0x00})); + assertEquals(0, Bytes.of(example_bytes_eight).count(new byte[]{(byte) 0xED})); + assertEquals(0, Bytes.of(example_bytes_eight).count(new byte[]{(byte) 0x22})); + assertEquals(2, Bytes.of(new byte[]{0, 1, 2, 3, 0, 1, 0}).count(new byte[]{0, 1})); + assertEquals(1, Bytes.of(new byte[]{0, 1, 2, 3, 0, 1, 0}).count(new byte[]{0, 1, 2})); + assertEquals(1, Bytes.of(new byte[]{0, 1, 2, 3, 0, 1, 0}).count(new byte[]{0, 1, 2, 3})); + assertEquals(0, Bytes.of(new byte[]{0, 1, 2, 3, 0, 1, 0}).count(new byte[]{0, 1, 2, 0})); } @Test(expected = NullPointerException.class) @@ -470,10 +470,10 @@ public void entropy() { assertEquals(0, Bytes.allocate(0).entropy(), 0.1d); assertEquals(0, Bytes.allocate(1).entropy(), 0.1d); assertEquals(0, Bytes.allocate(256).entropy(), 0.1d); - assertEquals(0, Bytes.from(new byte[]{1}).entropy(), 0.1d); - assertTrue(Bytes.from(example_bytes_twentyfour).entropy() > 3.5); - assertTrue(Bytes.from(example_bytes_seven).entropy() > 2.5); - assertTrue(Bytes.from(example_bytes_two).entropy() > 0.5); + assertEquals(0, Bytes.of(new byte[]{1}).entropy(), 0.1d); + assertTrue(Bytes.of(example_bytes_twentyfour).entropy() > 3.5); + assertTrue(Bytes.of(example_bytes_seven).entropy() > 2.5); + assertTrue(Bytes.of(example_bytes_two).entropy() > 0.5); } @Test diff --git a/src/test/java/at/favre/lib/bytes/BytesParseAndEncodingTest.java b/src/test/java/at/favre/lib/bytes/BytesParseAndEncodingTest.java index 5938c17..7e67ca9 100644 --- a/src/test/java/at/favre/lib/bytes/BytesParseAndEncodingTest.java +++ b/src/test/java/at/favre/lib/bytes/BytesParseAndEncodingTest.java @@ -52,10 +52,10 @@ public void parseHexInvalid() { @Test public void encodeHex() { byte[] defaultArray = new byte[]{(byte) 0xA0, (byte) 0xE1}; - assertEquals("a0e1", Bytes.from(defaultArray).encodeHex()); - assertEquals("A0E1", Bytes.from(defaultArray).encodeHex(true)); - assertEquals(Bytes.from(defaultArray).encodeHex(), Bytes.from(defaultArray).encodeHex(false)); - assertEquals("4a94fdff1eafed", Bytes.from(encodingExample).encodeHex()); + assertEquals("a0e1", Bytes.of(defaultArray).encodeHex()); + assertEquals("A0E1", Bytes.of(defaultArray).encodeHex(true)); + assertEquals(Bytes.of(defaultArray).encodeHex(), Bytes.of(defaultArray).encodeHex(false)); + assertEquals("4a94fdff1eafed", Bytes.of(encodingExample).encodeHex()); } @Test @@ -73,35 +73,35 @@ public void parseBase64Invalid() { @Test public void encodeBase64() { - assertEquals("", Bytes.from(new byte[0]).encodeBase64()); - assertEquals("AA==", Bytes.from(new byte[1]).encodeBase64()); - assertEquals("SpT9/x6v7Q==", Bytes.from(encodingExample).encodeBase64()); + assertEquals("", Bytes.of(new byte[0]).encodeBase64()); + assertEquals("AA==", Bytes.of(new byte[1]).encodeBase64()); + assertEquals("SpT9/x6v7Q==", Bytes.of(encodingExample).encodeBase64()); } @Test public void encodeBase64Url() { - assertEquals("", Bytes.from(new byte[0]).encodeBase64Url()); - assertEquals("AA==", Bytes.from(new byte[1]).encodeBase64Url()); - assertEquals("SpT9_x6v7Q==", Bytes.from(encodingExample).encodeBase64Url()); + assertEquals("", Bytes.of(new byte[0]).encodeBase64Url()); + assertEquals("AA==", Bytes.of(new byte[1]).encodeBase64Url()); + assertEquals("SpT9_x6v7Q==", Bytes.of(encodingExample).encodeBase64Url()); } @Test public void encodeBase64WithConfig() { - assertEquals("", Bytes.from(new byte[0]).encodeBase64(true, true)); - assertEquals("AA==", Bytes.from(new byte[1]).encodeBase64(true, true)); - assertEquals("SpT9_x6v7Q==", Bytes.from(encodingExample).encodeBase64(true, true)); + assertEquals("", Bytes.of(new byte[0]).encodeBase64(true, true)); + assertEquals("AA==", Bytes.of(new byte[1]).encodeBase64(true, true)); + assertEquals("SpT9_x6v7Q==", Bytes.of(encodingExample).encodeBase64(true, true)); - assertEquals("", Bytes.from(new byte[0]).encodeBase64(true, false)); - assertEquals("AA", Bytes.from(new byte[1]).encodeBase64(true, false)); - assertEquals("SpT9_x6v7Q", Bytes.from(encodingExample).encodeBase64(true, false)); + assertEquals("", Bytes.of(new byte[0]).encodeBase64(true, false)); + assertEquals("AA", Bytes.of(new byte[1]).encodeBase64(true, false)); + assertEquals("SpT9_x6v7Q", Bytes.of(encodingExample).encodeBase64(true, false)); - assertEquals("", Bytes.from(new byte[0]).encodeBase64(false, true)); - assertEquals("AA==", Bytes.from(new byte[1]).encodeBase64(false, true)); - assertEquals("SpT9/x6v7Q==", Bytes.from(encodingExample).encodeBase64(false, true)); + assertEquals("", Bytes.of(new byte[0]).encodeBase64(false, true)); + assertEquals("AA==", Bytes.of(new byte[1]).encodeBase64(false, true)); + assertEquals("SpT9/x6v7Q==", Bytes.of(encodingExample).encodeBase64(false, true)); - assertEquals("", Bytes.from(new byte[0]).encodeBase64(false, false)); - assertEquals("AA", Bytes.from(new byte[1]).encodeBase64(false, false)); - assertEquals("SpT9/x6v7Q", Bytes.from(encodingExample).encodeBase64(false, false)); + assertEquals("", Bytes.of(new byte[0]).encodeBase64(false, false)); + assertEquals("AA", Bytes.of(new byte[1]).encodeBase64(false, false)); + assertEquals("SpT9/x6v7Q", Bytes.of(encodingExample).encodeBase64(false, false)); } @Test @@ -111,14 +111,14 @@ public void parseBase32() { @Test public void encodeBase32() { - assertEquals("JKKP37Y6V7WQ====", Bytes.from(encodingExample).encodeBase32()); + assertEquals("JKKP37Y6V7WQ====", Bytes.of(encodingExample).encodeBase32()); } @Test public void encodeBinary() { byte[] defaultArray = new byte[]{(byte) 0xA0, (byte) 0xE1}; - assertEquals("1010000011100001", Bytes.from(defaultArray).encodeBinary()); - assertEquals("1001010100101001111110111111111000111101010111111101101", Bytes.from(encodingExample).encodeBinary()); + assertEquals("1010000011100001", Bytes.of(defaultArray).encodeBinary()); + assertEquals("1001010100101001111110111111111000111101010111111101101", Bytes.of(encodingExample).encodeBinary()); } @Test @@ -129,8 +129,8 @@ public void parseOctal() { @Test public void encodeOctal() { byte[] defaultArray = new byte[]{(byte) 0xA0, (byte) 0xE1}; - assertEquals("120341", Bytes.from(defaultArray).encodeOctal()); - assertEquals("1124517677707527755", Bytes.from(encodingExample).encodeOctal()); + assertEquals("120341", Bytes.of(defaultArray).encodeOctal()); + assertEquals("1124517677707527755", Bytes.of(encodingExample).encodeOctal()); } @Test @@ -141,8 +141,8 @@ public void parseDec() { @Test public void encodeDec() { byte[] defaultArray = new byte[]{(byte) 0xA0, (byte) 0xE1}; - assertEquals("41185", Bytes.from(defaultArray).encodeDec()); - assertEquals("20992966904426477", Bytes.from(encodingExample).encodeDec()); + assertEquals("41185", Bytes.of(defaultArray).encodeDec()); + assertEquals("20992966904426477", Bytes.of(encodingExample).encodeDec()); } @Test @@ -153,8 +153,8 @@ public void parseBase36() { @Test public void encodeBase36() { byte[] defaultArray = new byte[]{(byte) 0xA0, (byte) 0xE1, (byte) 0x13}; - assertEquals("69zbn", Bytes.from(defaultArray).encodeBase36()); - assertEquals("5qpdvuwjvu5", Bytes.from(encodingExample).encodeBase36()); + assertEquals("69zbn", Bytes.of(defaultArray).encodeBase36()); + assertEquals("5qpdvuwjvu5", Bytes.of(encodingExample).encodeBase36()); } @Test @@ -173,25 +173,25 @@ public void parseRadix() { @Test public void encodeRadix() { - assertEquals("1001010100101001111110111111111000111101010111111101101", Bytes.from(encodingExample).encodeRadix(2)); - assertEquals("10202221221221000222101012210121012", Bytes.from(encodingExample).encodeRadix(3)); - assertEquals("1022211033313333013222333231", Bytes.from(encodingExample).encodeRadix(4)); - assertEquals("134003042232210013121402", Bytes.from(encodingExample).encodeRadix(5)); - assertEquals("542412151505231515005", Bytes.from(encodingExample).encodeRadix(6)); - assertEquals("1124517677707527755", Bytes.from(encodingExample).encodeRadix(8)); - assertEquals("20992966904426477", Bytes.from(encodingExample).encodeRadix(10)); - assertEquals("4a94fdff1eafed", Bytes.from(encodingExample).encodeRadix(16)); - assertEquals("5iibpp5dgpgp", Bytes.from(encodingExample).encodeRadix(26)); - assertEquals("5qpdvuwjvu5", Bytes.from(encodingExample).encodeRadix(36)); + assertEquals("1001010100101001111110111111111000111101010111111101101", Bytes.of(encodingExample).encodeRadix(2)); + assertEquals("10202221221221000222101012210121012", Bytes.of(encodingExample).encodeRadix(3)); + assertEquals("1022211033313333013222333231", Bytes.of(encodingExample).encodeRadix(4)); + assertEquals("134003042232210013121402", Bytes.of(encodingExample).encodeRadix(5)); + assertEquals("542412151505231515005", Bytes.of(encodingExample).encodeRadix(6)); + assertEquals("1124517677707527755", Bytes.of(encodingExample).encodeRadix(8)); + assertEquals("20992966904426477", Bytes.of(encodingExample).encodeRadix(10)); + assertEquals("4a94fdff1eafed", Bytes.of(encodingExample).encodeRadix(16)); + assertEquals("5iibpp5dgpgp", Bytes.of(encodingExample).encodeRadix(26)); + assertEquals("5qpdvuwjvu5", Bytes.of(encodingExample).encodeRadix(36)); } @Test(expected = IllegalArgumentException.class) public void encodeRadixIllegalTooHigh() { - Bytes.from(encodingExample).encodeRadix(37); + Bytes.of(encodingExample).encodeRadix(37); } @Test(expected = IllegalArgumentException.class) public void encodeRadixIllegalTooLow() { - Bytes.from(encodingExample).encodeRadix(1); + Bytes.of(encodingExample).encodeRadix(1); } } diff --git a/src/test/java/at/favre/lib/bytes/BytesSharedDataConverterTest.java b/src/test/java/at/favre/lib/bytes/BytesSharedDataConverterTest.java index 359a96c..876d7c8 100644 --- a/src/test/java/at/favre/lib/bytes/BytesSharedDataConverterTest.java +++ b/src/test/java/at/favre/lib/bytes/BytesSharedDataConverterTest.java @@ -31,39 +31,39 @@ public class BytesSharedDataConverterTest extends ABytesTest { @Test public void array() { - assertArrayEquals(new byte[0], Bytes.from(new byte[0]).array()); - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one).array()); - assertArrayEquals(example_bytes_two, Bytes.from(example_bytes_two).array()); - assertArrayEquals(example_bytes_four, Bytes.from(example_bytes_four).array()); - assertArrayEquals(example_bytes_seven, Bytes.from(example_bytes_seven).array()); - assertArrayEquals(example_bytes_eight, Bytes.from(example_bytes_eight).array()); - assertArrayEquals(example_bytes_sixteen, Bytes.from(example_bytes_sixteen).array()); + assertArrayEquals(new byte[0], Bytes.of(new byte[0]).array()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one).array()); + assertArrayEquals(example_bytes_two, Bytes.of(example_bytes_two).array()); + assertArrayEquals(example_bytes_four, Bytes.of(example_bytes_four).array()); + assertArrayEquals(example_bytes_seven, Bytes.of(example_bytes_seven).array()); + assertArrayEquals(example_bytes_eight, Bytes.of(example_bytes_eight).array()); + assertArrayEquals(example_bytes_sixteen, Bytes.of(example_bytes_sixteen).array()); } @Test public void bigInteger() { - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one).toBigInteger().toByteArray()); - assertArrayEquals(example_bytes_two, Bytes.from(example_bytes_two).toBigInteger().toByteArray()); - assertArrayEquals(example_bytes_four, Bytes.from(example_bytes_four).toBigInteger().toByteArray()); - assertArrayEquals(example_bytes_seven, Bytes.from(example_bytes_seven).toBigInteger().toByteArray()); - assertArrayEquals(example_bytes_eight, Bytes.from(example_bytes_eight).toBigInteger().toByteArray()); - assertArrayEquals(example_bytes_sixteen, Bytes.from(example_bytes_sixteen).toBigInteger().toByteArray()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one).toBigInteger().toByteArray()); + assertArrayEquals(example_bytes_two, Bytes.of(example_bytes_two).toBigInteger().toByteArray()); + assertArrayEquals(example_bytes_four, Bytes.of(example_bytes_four).toBigInteger().toByteArray()); + assertArrayEquals(example_bytes_seven, Bytes.of(example_bytes_seven).toBigInteger().toByteArray()); + assertArrayEquals(example_bytes_eight, Bytes.of(example_bytes_eight).toBigInteger().toByteArray()); + assertArrayEquals(example_bytes_sixteen, Bytes.of(example_bytes_sixteen).toBigInteger().toByteArray()); } @Test public void buffer() { - assertEquals(ByteBuffer.wrap(new byte[0]), Bytes.from(new byte[0]).buffer()); - assertEquals(ByteBuffer.wrap(example_bytes_one), Bytes.from(example_bytes_one).buffer()); - assertEquals(ByteBuffer.wrap(example_bytes_two), Bytes.from(example_bytes_two).buffer()); - assertEquals(ByteBuffer.wrap(example_bytes_four), Bytes.from(example_bytes_four).buffer()); - assertEquals(ByteBuffer.wrap(example_bytes_seven), Bytes.from(example_bytes_seven).buffer()); - assertEquals(ByteBuffer.wrap(example_bytes_eight), Bytes.from(example_bytes_eight).buffer()); - assertEquals(ByteBuffer.wrap(example_bytes_sixteen), Bytes.from(example_bytes_sixteen).buffer()); + assertEquals(ByteBuffer.wrap(new byte[0]), Bytes.of(new byte[0]).buffer()); + assertEquals(ByteBuffer.wrap(example_bytes_one), Bytes.of(example_bytes_one).buffer()); + assertEquals(ByteBuffer.wrap(example_bytes_two), Bytes.of(example_bytes_two).buffer()); + assertEquals(ByteBuffer.wrap(example_bytes_four), Bytes.of(example_bytes_four).buffer()); + assertEquals(ByteBuffer.wrap(example_bytes_seven), Bytes.of(example_bytes_seven).buffer()); + assertEquals(ByteBuffer.wrap(example_bytes_eight), Bytes.of(example_bytes_eight).buffer()); + assertEquals(ByteBuffer.wrap(example_bytes_sixteen), Bytes.of(example_bytes_sixteen).buffer()); } @Test public void duplicate() { - Bytes b = Bytes.from(example_bytes_sixteen); + Bytes b = Bytes.of(example_bytes_sixteen); Bytes b2 = b.duplicate(); assertNotSame(b, b2); assertSame(b.array(), b2.array()); @@ -71,9 +71,9 @@ public void duplicate() { @Test public void inputStream() { - assertArrayEquals(example_bytes_one, Util.File.readFromStream(Bytes.from(example_bytes_one).inputStream(), -1)); - assertArrayEquals(example_bytes_two, Util.File.readFromStream(Bytes.from(example_bytes_two).inputStream(), -1)); - assertArrayEquals(example_bytes_four, Util.File.readFromStream(Bytes.from(example_bytes_four).inputStream(), -1)); - assertArrayEquals(example_bytes_sixteen, Util.File.readFromStream(Bytes.from(example_bytes_sixteen).inputStream(), -1)); + assertArrayEquals(example_bytes_one, Util.File.readFromStream(Bytes.of(example_bytes_one).inputStream(), -1)); + assertArrayEquals(example_bytes_two, Util.File.readFromStream(Bytes.of(example_bytes_two).inputStream(), -1)); + assertArrayEquals(example_bytes_four, Util.File.readFromStream(Bytes.of(example_bytes_four).inputStream(), -1)); + assertArrayEquals(example_bytes_sixteen, Util.File.readFromStream(Bytes.of(example_bytes_sixteen).inputStream(), -1)); } } diff --git a/src/test/java/at/favre/lib/bytes/BytesToConvertOtherTypesTest.java b/src/test/java/at/favre/lib/bytes/BytesToConvertOtherTypesTest.java index 9b7fdea..a929418 100644 --- a/src/test/java/at/favre/lib/bytes/BytesToConvertOtherTypesTest.java +++ b/src/test/java/at/favre/lib/bytes/BytesToConvertOtherTypesTest.java @@ -41,12 +41,12 @@ public void toObjectArray() { } private void checkArray(byte[] array) { - Byte[] byteArray = Bytes.from(array).toBoxedArray(); + Byte[] byteArray = Bytes.of(array).toBoxedArray(); assertEquals(array.length, byteArray.length); for (int i = 0; i < array.length; i++) { assertEquals(byteArray[i], Byte.valueOf(array[i])); } - assertArrayEquals(byteArray, Bytes.from(array).toBoxedArray()); + assertArrayEquals(byteArray, Bytes.of(array).toBoxedArray()); } @Test @@ -60,7 +60,7 @@ public void toList() { } private void checkList(byte[] array) { - List byteList = Bytes.from(array).toList(); + List byteList = Bytes.of(array).toList(); assertEquals(array.length, byteList.size()); for (int i = 0; i < array.length; i++) { assertEquals(byteList.get(i), Byte.valueOf(array[i])); @@ -69,22 +69,22 @@ private void checkList(byte[] array) { @Test public void toBitSet() { - assertArrayEquals(example_bytes_empty, Bytes.from(example_bytes_empty).toBitSet().toByteArray()); - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one).toBitSet().toByteArray()); - assertArrayEquals(example_bytes_two, Bytes.from(example_bytes_two).toBitSet().toByteArray()); - assertArrayEquals(example_bytes_seven, Bytes.from(example_bytes_seven).toBitSet().toByteArray()); - assertArrayEquals(example_bytes_eight, Bytes.from(example_bytes_eight).toBitSet().toByteArray()); - assertArrayEquals(example_bytes_sixteen, Bytes.from(example_bytes_sixteen).toBitSet().toByteArray()); + assertArrayEquals(example_bytes_empty, Bytes.of(example_bytes_empty).toBitSet().toByteArray()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one).toBitSet().toByteArray()); + assertArrayEquals(example_bytes_two, Bytes.of(example_bytes_two).toBitSet().toByteArray()); + assertArrayEquals(example_bytes_seven, Bytes.of(example_bytes_seven).toBitSet().toByteArray()); + assertArrayEquals(example_bytes_eight, Bytes.of(example_bytes_eight).toBitSet().toByteArray()); + assertArrayEquals(example_bytes_sixteen, Bytes.of(example_bytes_sixteen).toBitSet().toByteArray()); } @Test public void toByte() { - assertEquals(example_bytes_one[0], Bytes.from(example_bytes_one).toByte()); - assertEquals((byte) 0, Bytes.from(new byte[1]).toByte()); - assertEquals(-1, Bytes.from((byte) 0b1111_1111).toByte()); + assertEquals(example_bytes_one[0], Bytes.of(example_bytes_one).toByte()); + assertEquals((byte) 0, Bytes.of(new byte[1]).toByte()); + assertEquals(-1, Bytes.of((byte) 0b1111_1111).toByte()); try { - Bytes.from(example_bytes_two).toByte(); + Bytes.of(example_bytes_two).toByte(); fail(); } catch (IllegalArgumentException ignored) { } @@ -92,12 +92,12 @@ public void toByte() { @Test public void toUnsignedByte() { - assertEquals(example_bytes_one[0], Bytes.from(example_bytes_one).toUnsignedByte()); - assertEquals((byte) 0, Bytes.from(new byte[1]).toUnsignedByte()); - assertEquals(255, Bytes.from((byte) 0b1111_1111).toUnsignedByte()); + assertEquals(example_bytes_one[0], Bytes.of(example_bytes_one).toUnsignedByte()); + assertEquals((byte) 0, Bytes.of(new byte[1]).toUnsignedByte()); + assertEquals(255, Bytes.of((byte) 0b1111_1111).toUnsignedByte()); try { - Bytes.from(example_bytes_two).toUnsignedByte(); + Bytes.of(example_bytes_two).toUnsignedByte(); fail(); } catch (IllegalArgumentException ignored) { } @@ -105,17 +105,17 @@ public void toUnsignedByte() { @Test public void toChar() { - assertEquals(6767, Bytes.from(example_bytes_two).toChar()); - assertEquals(Bytes.from(example_bytes_two).toShort(), Bytes.from(example_bytes_two).toChar()); - assertEquals((char) 0, Bytes.from(new byte[2]).toChar()); + assertEquals(6767, Bytes.of(example_bytes_two).toChar()); + assertEquals(Bytes.of(example_bytes_two).toShort(), Bytes.of(example_bytes_two).toChar()); + assertEquals((char) 0, Bytes.of(new byte[2]).toChar()); try { - Bytes.from(new byte[3]).toChar(); + Bytes.of(new byte[3]).toChar(); fail(); } catch (IllegalArgumentException ignored) { } try { - Bytes.from(new byte[1]).toChar(); + Bytes.of(new byte[1]).toChar(); fail(); } catch (IllegalArgumentException ignored) { } @@ -123,17 +123,17 @@ public void toChar() { @Test public void toShort() { - assertEquals(6767, Bytes.from(example_bytes_two).toShort()); - assertEquals(Bytes.from(example_bytes_one).toByte(), Bytes.from((byte) 0, example_bytes_one).toShort()); - assertEquals((short) 0, Bytes.from(new byte[2]).toShort()); + assertEquals(6767, Bytes.of(example_bytes_two).toShort()); + assertEquals(Bytes.of(example_bytes_one).toByte(), Bytes.of((byte) 0, example_bytes_one).toShort()); + assertEquals((short) 0, Bytes.of(new byte[2]).toShort()); try { - Bytes.from(new byte[3]).toShort(); + Bytes.of(new byte[3]).toShort(); fail(); } catch (IllegalArgumentException ignored) { } try { - Bytes.from(new byte[1]).toShort(); + Bytes.of(new byte[1]).toShort(); fail(); } catch (IllegalArgumentException ignored) { } @@ -141,22 +141,22 @@ public void toShort() { @Test public void toInt() { - assertEquals(591065872, Bytes.from(example_bytes_four).toInt()); - assertEquals(Bytes.from(new byte[]{0, 0, 0, 0}, example_bytes_four).toLong(), Bytes.from(example_bytes_four).toInt()); + assertEquals(591065872, Bytes.of(example_bytes_four).toInt()); + assertEquals(Bytes.of(new byte[]{0, 0, 0, 0}, example_bytes_four).toLong(), Bytes.of(example_bytes_four).toInt()); - System.out.println(Bytes.from(new byte[]{0, 0, 0x01, 0x02}).resize(4).encodeHex()); - System.out.println(Bytes.from(new byte[]{0x01, 0x02, 0x03, 0x04}).resize(4).encodeHex()); + System.out.println(Bytes.of(new byte[]{0, 0, 0x01, 0x02}).resize(4).encodeHex()); + System.out.println(Bytes.of(new byte[]{0x01, 0x02, 0x03, 0x04}).resize(4).encodeHex()); - assertEquals(6767, Bytes.from(new byte[]{(byte) 0, (byte) 0}, example_bytes_two).toInt()); - assertEquals(0, Bytes.from(new byte[4]).toInt()); + assertEquals(6767, Bytes.of(new byte[]{(byte) 0, (byte) 0}, example_bytes_two).toInt()); + assertEquals(0, Bytes.of(new byte[4]).toInt()); try { - Bytes.from(new byte[5]).toInt(); + Bytes.of(new byte[5]).toInt(); fail(); } catch (IllegalArgumentException ignored) { } try { - Bytes.from(new byte[3]).toInt(); + Bytes.of(new byte[3]).toInt(); fail(); } catch (IllegalArgumentException ignored) { } @@ -164,19 +164,19 @@ public void toInt() { @Test public void toLong() { - assertEquals(-1237929515650418679L, Bytes.from(example_bytes_eight).toLong()); + assertEquals(-1237929515650418679L, Bytes.of(example_bytes_eight).toLong()); - assertEquals(example_bytes_one[0], Bytes.from(new byte[]{0, 0, 0, 0, 0, 0, 0}, example_bytes_one).toLong()); - assertEquals(6767, Bytes.from(new byte[]{0, 0, 0, 0, 0, 0}, example_bytes_two).toLong()); - assertEquals(0, Bytes.from(new byte[8]).toLong()); + assertEquals(example_bytes_one[0], Bytes.of(new byte[]{0, 0, 0, 0, 0, 0, 0}, example_bytes_one).toLong()); + assertEquals(6767, Bytes.of(new byte[]{0, 0, 0, 0, 0, 0}, example_bytes_two).toLong()); + assertEquals(0, Bytes.of(new byte[8]).toLong()); try { - Bytes.from(new byte[9]).toLong(); + Bytes.of(new byte[9]).toLong(); fail(); } catch (IllegalArgumentException ignored) { } try { - Bytes.from(new byte[7]).toLong(); + Bytes.of(new byte[7]).toLong(); fail(); } catch (IllegalArgumentException ignored) { } @@ -184,19 +184,19 @@ public void toLong() { @Test public void toFloat() { - assertEquals(1.0134550690550691E-17, Bytes.from(example_bytes_four).toFloat(), 0.001); + assertEquals(1.0134550690550691E-17, Bytes.of(example_bytes_four).toFloat(), 0.001); - assertEquals(5.1E-322, Bytes.from(new byte[]{0, 0, 0}, example_bytes_one).toFloat(), 0.001); - assertEquals(3.3433E-320, Bytes.from(new byte[]{0, 0}, example_bytes_two).toFloat(), 0.001); - assertEquals(0, Bytes.from(new byte[4]).toFloat(), 0); + assertEquals(5.1E-322, Bytes.of(new byte[]{0, 0, 0}, example_bytes_one).toFloat(), 0.001); + assertEquals(3.3433E-320, Bytes.of(new byte[]{0, 0}, example_bytes_two).toFloat(), 0.001); + assertEquals(0, Bytes.of(new byte[4]).toFloat(), 0); try { - Bytes.from(new byte[5]).toFloat(); + Bytes.of(new byte[5]).toFloat(); fail(); } catch (IllegalArgumentException ignored) { } try { - Bytes.from(new byte[3]).toFloat(); + Bytes.of(new byte[3]).toFloat(); fail(); } catch (IllegalArgumentException ignored) { } @@ -204,19 +204,19 @@ public void toFloat() { @Test public void toDouble() { - assertEquals(-6.659307728279082E225, Bytes.from(example_bytes_eight).toDouble(), 0.001); + assertEquals(-6.659307728279082E225, Bytes.of(example_bytes_eight).toDouble(), 0.001); - assertEquals(5.1E-322, Bytes.from(new byte[]{0, 0, 0, 0, 0, 0, 0}, example_bytes_one).toDouble(), 0.001); - assertEquals(3.3433E-320, Bytes.from(new byte[]{0, 0, 0, 0, 0, 0}, example_bytes_two).toDouble(), 0.001); - assertEquals(0, Bytes.from(new byte[8]).toDouble(), 0); + assertEquals(5.1E-322, Bytes.of(new byte[]{0, 0, 0, 0, 0, 0, 0}, example_bytes_one).toDouble(), 0.001); + assertEquals(3.3433E-320, Bytes.of(new byte[]{0, 0, 0, 0, 0, 0}, example_bytes_two).toDouble(), 0.001); + assertEquals(0, Bytes.of(new byte[8]).toDouble(), 0); try { - Bytes.from(new byte[9]).toDouble(); + Bytes.of(new byte[9]).toDouble(); fail(); } catch (IllegalArgumentException ignored) { } try { - Bytes.from(new byte[7]).toDouble(); + Bytes.of(new byte[7]).toDouble(); fail(); } catch (IllegalArgumentException ignored) { } diff --git a/src/test/java/at/favre/lib/bytes/BytesTransformTest.java b/src/test/java/at/favre/lib/bytes/BytesTransformTest.java index dd6feaf..9afe37e 100644 --- a/src/test/java/at/favre/lib/bytes/BytesTransformTest.java +++ b/src/test/java/at/favre/lib/bytes/BytesTransformTest.java @@ -39,57 +39,57 @@ public class BytesTransformTest extends ABytesTest { @Test public void append() { - assertArrayEquals(new byte[0], Bytes.from(new byte[0]).append(new byte[0]).array()); - assertArrayEquals(new byte[1], Bytes.from(new byte[0]).append(new byte[1]).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_seven, example_bytes_one), Bytes.from(example_bytes_seven).append(example_bytes_one).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_seven, example_bytes_two), Bytes.from(example_bytes_seven).append(example_bytes_two).array()); + assertArrayEquals(new byte[0], Bytes.of(new byte[0]).append(new byte[0]).array()); + assertArrayEquals(new byte[1], Bytes.of(new byte[0]).append(new byte[1]).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_seven, example_bytes_one), Bytes.of(example_bytes_seven).append(example_bytes_one).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_seven, example_bytes_two), Bytes.of(example_bytes_seven).append(example_bytes_two).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_eight, example_bytes_sixteen), Bytes.from(example_bytes_eight).append(Bytes.from(example_bytes_sixteen)).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_eight, example_bytes_sixteen), Bytes.of(example_bytes_eight).append(Bytes.of(example_bytes_sixteen)).array()); } @Test public void appendMultipleByteArrays() { - assertArrayEquals(new byte[0], Bytes.from(new byte[0]).append(new byte[0], new byte[0]).array()); - assertArrayEquals(new byte[]{0x0, 0x01, 0x02, 0x03}, Bytes.from(new byte[]{0x0}).append(new byte[]{0x1}, new byte[]{0x2}, new byte[]{0x3}).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_seven, example_bytes_one, example_bytes_sixteen), Bytes.from(example_bytes_seven).append(example_bytes_one, example_bytes_sixteen).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_sixteen, example_bytes_sixteen, example_bytes_sixteen), Bytes.from(example_bytes_sixteen).append(example_bytes_sixteen, example_bytes_sixteen).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_two, example_bytes_seven, example_bytes_twentyfour, example_bytes_eight), Bytes.from(example_bytes_two).append(example_bytes_seven, example_bytes_twentyfour, example_bytes_eight).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_two, example_bytes_seven, example_bytes_twentyfour, example_bytes_one, example_bytes_sixteen), Bytes.from(example_bytes_two).append(example_bytes_seven, example_bytes_twentyfour).append(example_bytes_one, example_bytes_sixteen).array()); + assertArrayEquals(new byte[0], Bytes.of(new byte[0]).append(new byte[0], new byte[0]).array()); + assertArrayEquals(new byte[]{0x0, 0x01, 0x02, 0x03}, Bytes.of(new byte[]{0x0}).append(new byte[]{0x1}, new byte[]{0x2}, new byte[]{0x3}).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_seven, example_bytes_one, example_bytes_sixteen), Bytes.of(example_bytes_seven).append(example_bytes_one, example_bytes_sixteen).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_sixteen, example_bytes_sixteen, example_bytes_sixteen), Bytes.of(example_bytes_sixteen).append(example_bytes_sixteen, example_bytes_sixteen).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_two, example_bytes_seven, example_bytes_twentyfour, example_bytes_eight), Bytes.of(example_bytes_two).append(example_bytes_seven, example_bytes_twentyfour, example_bytes_eight).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_two, example_bytes_seven, example_bytes_twentyfour, example_bytes_one, example_bytes_sixteen), Bytes.of(example_bytes_two).append(example_bytes_seven, example_bytes_twentyfour).append(example_bytes_one, example_bytes_sixteen).array()); } @Test public void appendNullSafe() { - assertArrayEquals(new byte[0], Bytes.from(new byte[0]).appendNullSafe(new byte[0]).array()); - assertArrayEquals(new byte[1], Bytes.from(new byte[0]).appendNullSafe(new byte[1]).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_seven, example_bytes_one), Bytes.from(example_bytes_seven).appendNullSafe(example_bytes_one).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_seven, example_bytes_two), Bytes.from(example_bytes_seven).appendNullSafe(example_bytes_two).array()); - assertArrayEquals(new byte[0], Bytes.from(new byte[0]).appendNullSafe(null).array()); - assertArrayEquals(new byte[1], Bytes.from(new byte[1]).appendNullSafe(null).array()); - assertArrayEquals(example_bytes_seven, Bytes.from(example_bytes_seven).appendNullSafe(null).array()); + assertArrayEquals(new byte[0], Bytes.of(new byte[0]).appendNullSafe(new byte[0]).array()); + assertArrayEquals(new byte[1], Bytes.of(new byte[0]).appendNullSafe(new byte[1]).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_seven, example_bytes_one), Bytes.of(example_bytes_seven).appendNullSafe(example_bytes_one).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_seven, example_bytes_two), Bytes.of(example_bytes_seven).appendNullSafe(example_bytes_two).array()); + assertArrayEquals(new byte[0], Bytes.of(new byte[0]).appendNullSafe(null).array()); + assertArrayEquals(new byte[1], Bytes.of(new byte[1]).appendNullSafe(null).array()); + assertArrayEquals(example_bytes_seven, Bytes.of(example_bytes_seven).appendNullSafe(null).array()); } @Test public void appendPrimitives() { - assertArrayEquals(Util.Byte.concat(example_bytes_eight, new byte[]{1}), Bytes.from(example_bytes_eight).append((byte) 1).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_eight, ByteBuffer.allocate(2).putChar((char) 1423).array()), Bytes.from(example_bytes_eight).append((char) 1423).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_eight, ByteBuffer.allocate(2).putShort((short) 4129).array()), Bytes.from(example_bytes_eight).append((short) 4129).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_eight, ByteBuffer.allocate(4).putInt(362173671).array()), Bytes.from(example_bytes_eight).append(362173671).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_eight, ByteBuffer.allocate(8).putLong(0x6762173671L).array()), Bytes.from(example_bytes_eight).append(0x6762173671L).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_eight, new byte[]{1}), Bytes.of(example_bytes_eight).append((byte) 1).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_eight, ByteBuffer.allocate(2).putChar((char) 1423).array()), Bytes.of(example_bytes_eight).append((char) 1423).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_eight, ByteBuffer.allocate(2).putShort((short) 4129).array()), Bytes.of(example_bytes_eight).append((short) 4129).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_eight, ByteBuffer.allocate(4).putInt(362173671).array()), Bytes.of(example_bytes_eight).append(362173671).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_eight, ByteBuffer.allocate(8).putLong(0x6762173671L).array()), Bytes.of(example_bytes_eight).append(0x6762173671L).array()); } @Test public void appendString() { - assertArrayEquals(new byte[]{0, 0, 48}, Bytes.from(new byte[2]).append("0").array()); - assertArrayEquals(new byte[]{48}, Bytes.from(new byte[0]).append("0").array()); - assertArrayEquals(new byte[]{71, 117, 116}, Bytes.from(new byte[0]).append("Gut").array()); - assertArrayEquals(new byte[]{71, -30, -99, -92}, Bytes.from(new byte[0]).append("G❤").array()); + assertArrayEquals(new byte[]{0, 0, 48}, Bytes.of(new byte[2]).append("0").array()); + assertArrayEquals(new byte[]{48}, Bytes.of(new byte[0]).append("0").array()); + assertArrayEquals(new byte[]{71, 117, 116}, Bytes.of(new byte[0]).append("Gut").array()); + assertArrayEquals(new byte[]{71, -30, -99, -92}, Bytes.of(new byte[0]).append("G❤").array()); - assertArrayEquals(new byte[]{48}, Bytes.from(new byte[0]).append("0", StandardCharsets.US_ASCII).array()); - assertArrayEquals(new byte[]{71, 117, 116}, Bytes.from(new byte[0]).append("Gut", StandardCharsets.US_ASCII).array()); - assertArrayEquals(new byte[]{71, 117, 116}, Bytes.from(new byte[0]).append("Gut", StandardCharsets.UTF_8).array()); - assertArrayEquals(new byte[]{71, 117, 116}, Bytes.from(new byte[0]).append("Gut", StandardCharsets.ISO_8859_1).array()); - assertArrayEquals(new byte[]{71, -4, 116}, Bytes.from(new byte[0]).append("Güt", StandardCharsets.ISO_8859_1).array()); - assertArrayEquals(new byte[]{71, -61, -68, 116}, Bytes.from(new byte[0]).append("Güt", StandardCharsets.UTF_8).array()); + assertArrayEquals(new byte[]{48}, Bytes.of(new byte[0]).append("0", StandardCharsets.US_ASCII).array()); + assertArrayEquals(new byte[]{71, 117, 116}, Bytes.of(new byte[0]).append("Gut", StandardCharsets.US_ASCII).array()); + assertArrayEquals(new byte[]{71, 117, 116}, Bytes.of(new byte[0]).append("Gut", StandardCharsets.UTF_8).array()); + assertArrayEquals(new byte[]{71, 117, 116}, Bytes.of(new byte[0]).append("Gut", StandardCharsets.ISO_8859_1).array()); + assertArrayEquals(new byte[]{71, -4, 116}, Bytes.of(new byte[0]).append("Güt", StandardCharsets.ISO_8859_1).array()); + assertArrayEquals(new byte[]{71, -61, -68, 116}, Bytes.of(new byte[0]).append("Güt", StandardCharsets.UTF_8).array()); } @Test @@ -105,36 +105,36 @@ public void appendMulti() { @Test public void resizeGrowLsb() { - assertArrayEquals(new byte[8], Bytes.from(new byte[0]).resize(8).array()); - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one).resize(1).array()); - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one).resize(1).array()); - assertArrayEquals(Util.Byte.concat(new byte[7], example_bytes_one), Bytes.from(example_bytes_one).resize(8).array()); - assertArrayEquals(Util.Byte.concat(new byte[1], example_bytes_seven), Bytes.from(example_bytes_seven).resize(8).array()); - assertArrayEquals(Util.Byte.concat(new byte[1], example_bytes_sixteen), Bytes.from(example_bytes_sixteen).resize(17).array()); + assertArrayEquals(new byte[8], Bytes.of(new byte[0]).resize(8).array()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one).resize(1).array()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one).resize(1).array()); + assertArrayEquals(Util.Byte.concat(new byte[7], example_bytes_one), Bytes.of(example_bytes_one).resize(8).array()); + assertArrayEquals(Util.Byte.concat(new byte[1], example_bytes_seven), Bytes.of(example_bytes_seven).resize(8).array()); + assertArrayEquals(Util.Byte.concat(new byte[1], example_bytes_sixteen), Bytes.of(example_bytes_sixteen).resize(17).array()); } @Test public void resizeGrowMsb() { - assertArrayEquals(new byte[8], Bytes.from(new byte[0]).resize(8, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one).resize(1, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one).resize(1, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_one, new byte[7]), Bytes.from(example_bytes_one).resize(8, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_seven, new byte[1]), Bytes.from(example_bytes_seven).resize(8, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); - assertArrayEquals(Util.Byte.concat(example_bytes_sixteen, new byte[1]), Bytes.from(example_bytes_sixteen).resize(17, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); + assertArrayEquals(new byte[8], Bytes.of(new byte[0]).resize(8, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one).resize(1, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one).resize(1, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_one, new byte[7]), Bytes.of(example_bytes_one).resize(8, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_seven, new byte[1]), Bytes.of(example_bytes_seven).resize(8, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); + assertArrayEquals(Util.Byte.concat(example_bytes_sixteen, new byte[1]), Bytes.of(example_bytes_sixteen).resize(17, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); } @Test public void resizeShrinkLsb() { - assertArrayEquals(new byte[0], Bytes.from(example_bytes_one).resize(0).array()); - assertArrayEquals(new byte[]{example_bytes_two[1]}, Bytes.from(example_bytes_two).resize(1).array()); - assertArrayEquals(new byte[]{example_bytes_four[3]}, Bytes.from(example_bytes_four).resize(1).array()); - assertArrayEquals(new byte[]{example_bytes_four[2], example_bytes_four[3]}, Bytes.from(example_bytes_four).resize(2).array()); - assertArrayEquals(new byte[]{example_bytes_sixteen[14], example_bytes_sixteen[15]}, Bytes.from(example_bytes_sixteen).resize(2).array()); - assertArrayEquals(new byte[]{example_bytes_sixteen[13], example_bytes_sixteen[14], example_bytes_sixteen[15]}, Bytes.from(example_bytes_sixteen).resize(3).array()); - assertArrayEquals(example_bytes_four, Bytes.from(example_bytes_four).resize(8).resize(4).array()); + assertArrayEquals(new byte[0], Bytes.of(example_bytes_one).resize(0).array()); + assertArrayEquals(new byte[]{example_bytes_two[1]}, Bytes.of(example_bytes_two).resize(1).array()); + assertArrayEquals(new byte[]{example_bytes_four[3]}, Bytes.of(example_bytes_four).resize(1).array()); + assertArrayEquals(new byte[]{example_bytes_four[2], example_bytes_four[3]}, Bytes.of(example_bytes_four).resize(2).array()); + assertArrayEquals(new byte[]{example_bytes_sixteen[14], example_bytes_sixteen[15]}, Bytes.of(example_bytes_sixteen).resize(2).array()); + assertArrayEquals(new byte[]{example_bytes_sixteen[13], example_bytes_sixteen[14], example_bytes_sixteen[15]}, Bytes.of(example_bytes_sixteen).resize(3).array()); + assertArrayEquals(example_bytes_four, Bytes.of(example_bytes_four).resize(8).resize(4).array()); try { - Bytes.from(new byte[0]).resize(-1); + Bytes.of(new byte[0]).resize(-1); fail(); } catch (IllegalArgumentException ignore) { } @@ -142,13 +142,13 @@ public void resizeShrinkLsb() { @Test public void resizeShrinkMsb() { - assertArrayEquals(new byte[0], Bytes.from(example_bytes_one).resize(0, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); - assertArrayEquals(new byte[]{example_bytes_two[0]}, Bytes.from(example_bytes_two).resize(1, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); - assertArrayEquals(new byte[]{example_bytes_four[0]}, Bytes.from(example_bytes_four).resize(1, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); - assertArrayEquals(new byte[]{example_bytes_four[0], example_bytes_four[1]}, Bytes.from(example_bytes_four).resize(2, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); + assertArrayEquals(new byte[0], Bytes.of(example_bytes_one).resize(0, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); + assertArrayEquals(new byte[]{example_bytes_two[0]}, Bytes.of(example_bytes_two).resize(1, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); + assertArrayEquals(new byte[]{example_bytes_four[0]}, Bytes.of(example_bytes_four).resize(1, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); + assertArrayEquals(new byte[]{example_bytes_four[0], example_bytes_four[1]}, Bytes.of(example_bytes_four).resize(2, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX).array()); try { - Bytes.from(new byte[0]).resize(-1, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX); + Bytes.of(new byte[0]).resize(-1, BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_ZERO_INDEX); fail(); } catch (IllegalArgumentException ignore) { } @@ -156,31 +156,31 @@ public void resizeShrinkMsb() { @Test public void resizeSameInstance() { - Bytes b = Bytes.from(example_bytes_sixteen); + Bytes b = Bytes.of(example_bytes_sixteen); Bytes b2 = b.resize(16); assertSame(b.array(), b2.array()); } @Test public void xor() { - assertArrayEquals(new byte[0], Bytes.from(new byte[0]).xor(new byte[0]).array()); - assertArrayEquals(new byte[1], Bytes.from(new byte[1]).xor(new byte[1]).array()); + assertArrayEquals(new byte[0], Bytes.of(new byte[0]).xor(new byte[0]).array()); + assertArrayEquals(new byte[1], Bytes.of(new byte[1]).xor(new byte[1]).array()); - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one).xor(new byte[1]).array()); - assertArrayEquals(example_bytes_two, Bytes.from(example_bytes_two).xor(new byte[2]).array()); - assertArrayEquals(example_bytes_sixteen, Bytes.from(example_bytes_sixteen).xor(new byte[16]).array()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one).xor(new byte[1]).array()); + assertArrayEquals(example_bytes_two, Bytes.of(example_bytes_two).xor(new byte[2]).array()); + assertArrayEquals(example_bytes_sixteen, Bytes.of(example_bytes_sixteen).xor(new byte[16]).array()); - assertArrayEquals(new byte[1], Bytes.from(example_bytes_one).xor(example_bytes_one).array()); - assertArrayEquals(new byte[2], Bytes.from(example_bytes_two).xor(example_bytes_two).array()); - assertArrayEquals(new byte[16], Bytes.from(example_bytes_sixteen).xor(example_bytes_sixteen).array()); + assertArrayEquals(new byte[1], Bytes.of(example_bytes_one).xor(example_bytes_one).array()); + assertArrayEquals(new byte[2], Bytes.of(example_bytes_two).xor(example_bytes_two).array()); + assertArrayEquals(new byte[16], Bytes.of(example_bytes_sixteen).xor(example_bytes_sixteen).array()); - assertArrayEquals(new byte[]{-69, -51}, Bytes.from(new byte[]{(byte) 0xAE, (byte) 0x1E}).xor(new byte[]{(byte) 0x15, (byte) 0xD3}).array()); + assertArrayEquals(new byte[]{-69, -51}, Bytes.of(new byte[]{(byte) 0xAE, (byte) 0x1E}).xor(new byte[]{(byte) 0x15, (byte) 0xD3}).array()); - assertArrayEquals(new byte[1], Bytes.from(example_bytes_one).xor(Bytes.from(example_bytes_one)).array()); - assertArrayEquals(new byte[16], Bytes.from(example_bytes_sixteen).xor(Bytes.from(example_bytes_sixteen)).array()); + assertArrayEquals(new byte[1], Bytes.of(example_bytes_one).xor(Bytes.of(example_bytes_one)).array()); + assertArrayEquals(new byte[16], Bytes.of(example_bytes_sixteen).xor(Bytes.of(example_bytes_sixteen)).array()); try { - Bytes.from(example_bytes_seven).xor(example_bytes_eight); + Bytes.of(example_bytes_seven).xor(example_bytes_eight); fail(); } catch (Exception ignored) { } @@ -188,24 +188,24 @@ public void xor() { @Test public void or() { - assertArrayEquals(new byte[0], Bytes.from(new byte[0]).or(new byte[0]).array()); - assertArrayEquals(new byte[]{1}, Bytes.from(new byte[]{1}).or(new byte[]{0}).array()); - assertArrayEquals(new byte[1], Bytes.from(new byte[1]).or(new byte[1]).array()); + assertArrayEquals(new byte[0], Bytes.of(new byte[0]).or(new byte[0]).array()); + assertArrayEquals(new byte[]{1}, Bytes.of(new byte[]{1}).or(new byte[]{0}).array()); + assertArrayEquals(new byte[1], Bytes.of(new byte[1]).or(new byte[1]).array()); - assertArrayEquals(new byte[0], Bytes.from(new byte[0]).or(Bytes.wrap(new byte[0])).array()); - assertArrayEquals(new byte[]{1}, Bytes.from(new byte[]{1}).or(Bytes.wrap(new byte[]{0})).array()); - assertArrayEquals(new byte[1], Bytes.from(new byte[1]).or(Bytes.wrap(new byte[1])).array()); + assertArrayEquals(new byte[0], Bytes.of(new byte[0]).or(Bytes.wrap(new byte[0])).array()); + assertArrayEquals(new byte[]{1}, Bytes.of(new byte[]{1}).or(Bytes.wrap(new byte[]{0})).array()); + assertArrayEquals(new byte[1], Bytes.of(new byte[1]).or(Bytes.wrap(new byte[1])).array()); - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one).or(new byte[1]).array()); - assertArrayEquals(example_bytes_two, Bytes.from(example_bytes_two).or(new byte[2]).array()); - assertArrayEquals(example_bytes_sixteen, Bytes.from(example_bytes_sixteen).or(new byte[16]).array()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one).or(new byte[1]).array()); + assertArrayEquals(example_bytes_two, Bytes.of(example_bytes_two).or(new byte[2]).array()); + assertArrayEquals(example_bytes_sixteen, Bytes.of(example_bytes_sixteen).or(new byte[16]).array()); - assertArrayEquals(new byte[]{0x67}, Bytes.from(example_bytes_one).or(example_bytes_one).array()); - assertArrayEquals(new byte[]{0x67}, Bytes.from(example_bytes_one).or(Bytes.from(example_bytes_one)).array()); - assertArrayEquals(new byte[]{-65, -33}, Bytes.from(new byte[]{(byte) 0xAE, (byte) 0x1E}).or(new byte[]{(byte) 0x15, (byte) 0xD3}).array()); + assertArrayEquals(new byte[]{0x67}, Bytes.of(example_bytes_one).or(example_bytes_one).array()); + assertArrayEquals(new byte[]{0x67}, Bytes.of(example_bytes_one).or(Bytes.of(example_bytes_one)).array()); + assertArrayEquals(new byte[]{-65, -33}, Bytes.of(new byte[]{(byte) 0xAE, (byte) 0x1E}).or(new byte[]{(byte) 0x15, (byte) 0xD3}).array()); try { - Bytes.from(example_bytes_seven).or(example_bytes_eight); + Bytes.of(example_bytes_seven).or(example_bytes_eight); fail(); } catch (Exception ignore) { } @@ -213,19 +213,19 @@ public void or() { @Test public void and() { - assertArrayEquals(new byte[0], Bytes.from(new byte[0]).and(new byte[0]).array()); - assertArrayEquals(new byte[1], Bytes.from(new byte[1]).and(new byte[1]).array()); + assertArrayEquals(new byte[0], Bytes.of(new byte[0]).and(new byte[0]).array()); + assertArrayEquals(new byte[1], Bytes.of(new byte[1]).and(new byte[1]).array()); - assertArrayEquals(new byte[1], Bytes.from(example_bytes_one).and(new byte[1]).array()); - assertArrayEquals(new byte[2], Bytes.from(example_bytes_two).and(new byte[2]).array()); - assertArrayEquals(new byte[16], Bytes.from(example_bytes_sixteen).and(new byte[16]).array()); + assertArrayEquals(new byte[1], Bytes.of(example_bytes_one).and(new byte[1]).array()); + assertArrayEquals(new byte[2], Bytes.of(example_bytes_two).and(new byte[2]).array()); + assertArrayEquals(new byte[16], Bytes.of(example_bytes_sixteen).and(new byte[16]).array()); - assertArrayEquals(new byte[]{0x67}, Bytes.from(example_bytes_one).and(example_bytes_one).array()); - assertArrayEquals(new byte[]{0x67}, Bytes.from(example_bytes_one).and(Bytes.from(example_bytes_one)).array()); - assertArrayEquals(new byte[]{4, 18}, Bytes.from(new byte[]{(byte) 0xAE, (byte) 0x1E}).and(new byte[]{(byte) 0x15, (byte) 0xD3}).array()); + assertArrayEquals(new byte[]{0x67}, Bytes.of(example_bytes_one).and(example_bytes_one).array()); + assertArrayEquals(new byte[]{0x67}, Bytes.of(example_bytes_one).and(Bytes.of(example_bytes_one)).array()); + assertArrayEquals(new byte[]{4, 18}, Bytes.of(new byte[]{(byte) 0xAE, (byte) 0x1E}).and(new byte[]{(byte) 0x15, (byte) 0xD3}).array()); try { - Bytes.from(example_bytes_seven).and(example_bytes_eight); + Bytes.of(example_bytes_seven).and(example_bytes_eight); fail(); } catch (Exception ignore) { } @@ -233,26 +233,26 @@ public void and() { @Test public void negate() { - assertArrayEquals(new byte[0], Bytes.from(new byte[0]).not().array()); - assertArrayEquals(new byte[]{(byte) 0xFF}, Bytes.from(new byte[1]).not().array()); + assertArrayEquals(new byte[0], Bytes.of(new byte[0]).not().array()); + assertArrayEquals(new byte[]{(byte) 0xFF}, Bytes.of(new byte[1]).not().array()); - assertArrayEquals(new byte[]{-104}, Bytes.from(example_bytes_one).not().array()); - assertArrayEquals(new byte[]{-27, -112}, Bytes.from(example_bytes_two).not().array()); - assertArrayEquals(new byte[]{81, -31}, Bytes.from(new byte[]{(byte) 0xAE, (byte) 0x1E}).not().array()); + assertArrayEquals(new byte[]{-104}, Bytes.of(example_bytes_one).not().array()); + assertArrayEquals(new byte[]{-27, -112}, Bytes.of(example_bytes_two).not().array()); + assertArrayEquals(new byte[]{81, -31}, Bytes.of(new byte[]{(byte) 0xAE, (byte) 0x1E}).not().array()); - assertArrayNotEquals(new byte[0], Bytes.from(example_bytes_one).not().array()); + assertArrayNotEquals(new byte[0], Bytes.of(example_bytes_one).not().array()); } @Test public void reverse() { - assertArrayEquals(new byte[0], Bytes.from(new byte[0]).reverse().array()); - assertArrayEquals(new byte[1], Bytes.from(new byte[1]).reverse().array()); + assertArrayEquals(new byte[0], Bytes.of(new byte[0]).reverse().array()); + assertArrayEquals(new byte[1], Bytes.of(new byte[1]).reverse().array()); - assertArrayEquals(example_bytes_one, Bytes.from(example_bytes_one).reverse().array()); - assertArrayEquals(new byte[]{example_bytes_two[1], example_bytes_two[0]}, Bytes.from(example_bytes_two).reverse().array()); - assertArrayEquals(new byte[]{example_bytes_four[3], example_bytes_four[2], example_bytes_four[1], example_bytes_four[0]}, Bytes.from(example_bytes_four).reverse().array()); + assertArrayEquals(example_bytes_one, Bytes.of(example_bytes_one).reverse().array()); + assertArrayEquals(new byte[]{example_bytes_two[1], example_bytes_two[0]}, Bytes.of(example_bytes_two).reverse().array()); + assertArrayEquals(new byte[]{example_bytes_four[3], example_bytes_four[2], example_bytes_four[1], example_bytes_four[0]}, Bytes.of(example_bytes_four).reverse().array()); - assertArrayNotEquals(new byte[0], Bytes.from(example_bytes_one).reverse().array()); + assertArrayNotEquals(new byte[0], Bytes.of(example_bytes_one).reverse().array()); } @Test @@ -274,17 +274,17 @@ public void copy() { @Test public void shuffleTest() { - assertArrayNotEquals(example_bytes_twentyfour, Bytes.from(example_bytes_twentyfour).transform(shuffle()).array()); - assertArrayNotEquals(example_bytes_twentyfour, Bytes.from(example_bytes_twentyfour).transform(shuffle(new SecureRandom())).array()); - assertArrayNotEquals(new byte[24], Bytes.from(example_bytes_twentyfour).transform(shuffle(new SecureRandom())).array()); + assertArrayNotEquals(example_bytes_twentyfour, Bytes.of(example_bytes_twentyfour).transform(shuffle()).array()); + assertArrayNotEquals(example_bytes_twentyfour, Bytes.of(example_bytes_twentyfour).transform(shuffle(new SecureRandom())).array()); + assertArrayNotEquals(new byte[24], Bytes.of(example_bytes_twentyfour).transform(shuffle(new SecureRandom())).array()); } @Test public void sortSignedTest() { byte[] sorted = new byte[]{-2, -1, 0, 1, 2, 3, 4, 5, 6}; - assertArrayEquals(sorted, Bytes.from(sorted).transform(shuffle()).transform(sort()).array()); - assertArrayEquals(sorted, Bytes.from(new byte[]{6, 0, 3, -2, -1, 4, 1, 5, 2}).transform(sort()).array()); - assertArrayEquals(Bytes.from(sorted).reverse().array(), Bytes.from(new byte[]{6, -2, -1, 0, 3, 4, 1, 5, 2}).transform(sort(new Comparator() { + assertArrayEquals(sorted, Bytes.of(sorted).transform(shuffle()).transform(sort()).array()); + assertArrayEquals(sorted, Bytes.of(new byte[]{6, 0, 3, -2, -1, 4, 1, 5, 2}).transform(sort()).array()); + assertArrayEquals(Bytes.of(sorted).reverse().array(), Bytes.of(new byte[]{6, -2, -1, 0, 3, 4, 1, 5, 2}).transform(sort(new Comparator() { @Override public int compare(Byte o1, Byte o2) { return o2.compareTo(o1); @@ -292,111 +292,111 @@ public int compare(Byte o1, Byte o2) { })).array()); byte[] checkSignedSorted = new byte[]{(byte) 0x80, (byte) 0xFE, (byte) 0xFF, 0x00, 0x01}; - assertArrayEquals(checkSignedSorted, Bytes.from(checkSignedSorted).transform(shuffle()).transform(sort()).array()); + assertArrayEquals(checkSignedSorted, Bytes.of(checkSignedSorted).transform(shuffle()).transform(sort()).array()); } @Test public void sortUnsignedTest() { byte[] sorted = new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, (byte) 0x80, (byte) 0xAE, (byte) 0xFF}; - assertArrayEquals(sorted, Bytes.from(sorted).transform(shuffle()).transform(sortUnsigned()).array()); - assertArrayEquals(sorted, Bytes.from(new byte[]{(byte) 0x80, (byte) 0xAE, (byte) 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}).transform(sortUnsigned()).array()); + assertArrayEquals(sorted, Bytes.of(sorted).transform(shuffle()).transform(sortUnsigned()).array()); + assertArrayEquals(sorted, Bytes.of(new byte[]{(byte) 0x80, (byte) 0xAE, (byte) 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}).transform(sortUnsigned()).array()); } @Test public void leftShift() { - assertArrayEquals(new byte[]{2}, Bytes.from((byte) 1).leftShift(1).array()); - assertArrayEquals(new byte[]{4}, Bytes.from((byte) 1).leftShift(2).array()); - assertArrayEquals(new byte[]{8}, Bytes.from((byte) 1).leftShift(3).array()); - assertArrayEquals(new byte[]{example_bytes_two[1], 0}, Bytes.from(example_bytes_two).leftShift(8).array()); - assertArrayEquals(new byte[]{0, 0}, Bytes.from(example_bytes_two).leftShift(16).array()); + assertArrayEquals(new byte[]{2}, Bytes.of((byte) 1).leftShift(1).array()); + assertArrayEquals(new byte[]{4}, Bytes.of((byte) 1).leftShift(2).array()); + assertArrayEquals(new byte[]{8}, Bytes.of((byte) 1).leftShift(3).array()); + assertArrayEquals(new byte[]{example_bytes_two[1], 0}, Bytes.of(example_bytes_two).leftShift(8).array()); + assertArrayEquals(new byte[]{0, 0}, Bytes.of(example_bytes_two).leftShift(16).array()); } @Test public void rightShift() { - assertArrayEquals(new byte[]{4}, Bytes.from((byte) 8).rightShift(1).array()); - assertArrayEquals(new byte[]{2}, Bytes.from((byte) 8).rightShift(2).array()); - assertArrayEquals(new byte[]{1}, Bytes.from((byte) 8).rightShift(3).array()); - assertArrayEquals(new byte[]{0}, Bytes.from((byte) 8).rightShift(4).array()); - assertArrayEquals(new byte[]{0, example_bytes_two[0]}, Bytes.from(example_bytes_two).rightShift(8).array()); - assertArrayEquals(new byte[2], Bytes.from(example_bytes_two).rightShift(16).array()); + assertArrayEquals(new byte[]{4}, Bytes.of((byte) 8).rightShift(1).array()); + assertArrayEquals(new byte[]{2}, Bytes.of((byte) 8).rightShift(2).array()); + assertArrayEquals(new byte[]{1}, Bytes.of((byte) 8).rightShift(3).array()); + assertArrayEquals(new byte[]{0}, Bytes.of((byte) 8).rightShift(4).array()); + assertArrayEquals(new byte[]{0, example_bytes_two[0]}, Bytes.of(example_bytes_two).rightShift(8).array()); + assertArrayEquals(new byte[2], Bytes.of(example_bytes_two).rightShift(16).array()); } @Test public void bitSwitch() { - assertEquals(1, Bytes.from(0).switchBit(0, true).toInt()); + assertEquals(1, Bytes.of(0).switchBit(0, true).toInt()); for (int i = 0; i < 63; i++) { for (long j = 1; j < 33; j++) { assertEquals("bit position " + i + " is wrong", BigInteger.valueOf(j).setBit(i).longValue(), - Bytes.from(j).switchBit(i, true).toLong()); + Bytes.of(j).switchBit(i, true).toLong()); assertEquals("bit position " + i + " is wrong", BigInteger.valueOf(j).flipBit(i).longValue(), - Bytes.from(j).switchBit(i).toLong()); + Bytes.of(j).switchBit(i).toLong()); assertEquals("bit position " + i + " is wrong", BigInteger.valueOf(j).clearBit(i).longValue(), - Bytes.from(j).switchBit(i, false).toLong()); + Bytes.of(j).switchBit(i, false).toLong()); } } } @Test(expected = IllegalArgumentException.class) public void bitSwitchOutOfBounds() { - Bytes.from(4).switchBit(32, true); + Bytes.of(4).switchBit(32, true); } @Test public void hashSha1() { - assertEquals(Bytes.parseHex("da39a3ee5e6b4b0d3255bfef95601890afd80709"), Bytes.from("").hashSha1()); - assertEquals(Bytes.parseHex("2628013771c4ffda4336231805f9d6c42e40ef86"), Bytes.from("ö9h%6Ghh1\"").hashSha1()); - assertEquals(Bytes.parseHex("15d418a940d699df0cde6304829b2cce5ed4a9ad"), Bytes.from("897SHALkjdn ,n-- kasdjöa").hashSha1()); + assertEquals(Bytes.parseHex("da39a3ee5e6b4b0d3255bfef95601890afd80709"), Bytes.of("").hashSha1()); + assertEquals(Bytes.parseHex("2628013771c4ffda4336231805f9d6c42e40ef86"), Bytes.of("ö9h%6Ghh1\"").hashSha1()); + assertEquals(Bytes.parseHex("15d418a940d699df0cde6304829b2cce5ed4a9ad"), Bytes.of("897SHALkjdn ,n-- kasdjöa").hashSha1()); } @Test public void hashMd5() { - assertEquals(Bytes.parseHex("d41d8cd98f00b204e9800998ecf8427e"), Bytes.from("").hashMd5()); - assertEquals(Bytes.parseHex("ff38205f1cb22f588d8bc9ae21f22092"), Bytes.from("ö9h%6Ghh1\"").hashMd5()); - assertEquals(Bytes.parseHex("9DFF192C3CE8554DBB1ADCC7721B4B78"), Bytes.from("897SHALkjdn ,n-- kasdjöa").hashMd5()); + assertEquals(Bytes.parseHex("d41d8cd98f00b204e9800998ecf8427e"), Bytes.of("").hashMd5()); + assertEquals(Bytes.parseHex("ff38205f1cb22f588d8bc9ae21f22092"), Bytes.of("ö9h%6Ghh1\"").hashMd5()); + assertEquals(Bytes.parseHex("9DFF192C3CE8554DBB1ADCC7721B4B78"), Bytes.of("897SHALkjdn ,n-- kasdjöa").hashMd5()); } @Test public void hash256() { - assertEquals(Bytes.parseHex("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), Bytes.from("").hashSha256()); - assertEquals(Bytes.parseHex("e362eea626386c93a54c9b82e6b896c0350fbff0ee12f284660253aac0908cfb"), Bytes.from("ö9h%6Ghh1\"").hashSha256()); - assertEquals(Bytes.parseHex("48D6BE81CB2EF8488BA2E3BF4050EE21BF9D33D85DB0E556E4AE5992243B8F35"), Bytes.from("897SHALkjdn ,n-- kasdjöa").hashSha256()); + assertEquals(Bytes.parseHex("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), Bytes.of("").hashSha256()); + assertEquals(Bytes.parseHex("e362eea626386c93a54c9b82e6b896c0350fbff0ee12f284660253aac0908cfb"), Bytes.of("ö9h%6Ghh1\"").hashSha256()); + assertEquals(Bytes.parseHex("48D6BE81CB2EF8488BA2E3BF4050EE21BF9D33D85DB0E556E4AE5992243B8F35"), Bytes.of("897SHALkjdn ,n-- kasdjöa").hashSha256()); } @Test public void hashCustom() { - assertEquals(Bytes.parseHex("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"), Bytes.from("").hash("SHA-512")); - assertEquals(Bytes.parseHex("106747C3DDC117091BEF8D21AEBAA8D314656D3AE1135AB36F4C0B07A264127CF625FE616751BEC66B43032B904E2D3B6C21BF14E078F6BB775A72503F48111D"), Bytes.from("ö9h%6Ghh1\"").hash("SHA-512")); - assertEquals(Bytes.parseHex("d41d8cd98f00b204e9800998ecf8427e"), Bytes.from("").hash("MD5")); - assertEquals(Bytes.parseHex("ff38205f1cb22f588d8bc9ae21f22092"), Bytes.from("ö9h%6Ghh1\"").hash("MD5")); - assertEquals(Bytes.parseHex("38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b"), Bytes.from("").hash("SHA-384")); - assertEquals(Bytes.parseHex("ec89d0d6b067f7f2e240ea7587933d92347fce4bdab68784bd2373dc1cccaa0238c0556b045acb1632080fac788d429d"), Bytes.from("ö9h%6Ghh1\"").hash("SHA-384")); + assertEquals(Bytes.parseHex("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"), Bytes.of("").hash("SHA-512")); + assertEquals(Bytes.parseHex("106747C3DDC117091BEF8D21AEBAA8D314656D3AE1135AB36F4C0B07A264127CF625FE616751BEC66B43032B904E2D3B6C21BF14E078F6BB775A72503F48111D"), Bytes.of("ö9h%6Ghh1\"").hash("SHA-512")); + assertEquals(Bytes.parseHex("d41d8cd98f00b204e9800998ecf8427e"), Bytes.of("").hash("MD5")); + assertEquals(Bytes.parseHex("ff38205f1cb22f588d8bc9ae21f22092"), Bytes.of("ö9h%6Ghh1\"").hash("MD5")); + assertEquals(Bytes.parseHex("38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b"), Bytes.of("").hash("SHA-384")); + assertEquals(Bytes.parseHex("ec89d0d6b067f7f2e240ea7587933d92347fce4bdab68784bd2373dc1cccaa0238c0556b045acb1632080fac788d429d"), Bytes.of("ö9h%6Ghh1\"").hash("SHA-384")); } @Test public void checksumTest() { Checksum crc32Checksum = new CRC32(); crc32Checksum.update(example2_bytes_seven, 0, example2_bytes_seven.length); - assertEquals(crc32Checksum.getValue(), Bytes.from(example2_bytes_seven).transform(checksumCrc32()).resize(8).toLong()); - assertEquals(Bytes.from(example2_bytes_seven, Bytes.from(crc32Checksum.getValue()).resize(4).array()), Bytes.from(example2_bytes_seven).transform(checksumAppendCrc32())); + assertEquals(crc32Checksum.getValue(), Bytes.of(example2_bytes_seven).transform(checksumCrc32()).resize(8).toLong()); + assertEquals(Bytes.of(example2_bytes_seven, Bytes.of(crc32Checksum.getValue()).resize(4).array()), Bytes.of(example2_bytes_seven).transform(checksumAppendCrc32())); Checksum adlerChecksum = new Adler32(); adlerChecksum.update(example2_bytes_seven, 0, example2_bytes_seven.length); - assertEquals(Bytes.from(adlerChecksum.getValue()).resize(4), - Bytes.from(example2_bytes_seven).transform(checksum(new Adler32(), ChecksumTransformer.Mode.TRANSFORM, 4))); + assertEquals(Bytes.of(adlerChecksum.getValue()).resize(4), + Bytes.of(example2_bytes_seven).transform(checksum(new Adler32(), ChecksumTransformer.Mode.TRANSFORM, 4))); } @Test(expected = IllegalArgumentException.class) public void checksumTestIllegalByteLengthTooShort() { - Bytes.from(example2_bytes_seven).transform(checksum(new CRC32(), ChecksumTransformer.Mode.TRANSFORM, 0)); + Bytes.of(example2_bytes_seven).transform(checksum(new CRC32(), ChecksumTransformer.Mode.TRANSFORM, 0)); } @Test(expected = IllegalArgumentException.class) public void checksumTestIllegalByteLengthTooLong() { - Bytes.from(example2_bytes_seven).transform(checksum(new CRC32(), ChecksumTransformer.Mode.TRANSFORM, 9)); + Bytes.of(example2_bytes_seven).transform(checksum(new CRC32(), ChecksumTransformer.Mode.TRANSFORM, 9)); } @Test @@ -408,7 +408,7 @@ public void testCompress() { private void testCompressInternal(int length) { Bytes emptyArray = Bytes.allocate(length); - byte[] compressed = Bytes.from(emptyArray).transform(compressGzip()).array(); + byte[] compressed = Bytes.of(emptyArray).transform(compressGzip()).array(); byte[] uncompressed = Bytes.wrap(compressed).transform(decompressGzip()).array(); assertArrayEquals(emptyArray.array(), uncompressed); assertArrayNotEquals(compressed, uncompressed); @@ -417,10 +417,10 @@ private void testCompressInternal(int length) { @Test public void transform() { - assertArrayEquals(example_bytes_two, Bytes.from(example_bytes_two).transform(new BytesTransformer() { + assertArrayEquals(example_bytes_two, Bytes.of(example_bytes_two).transform(new BytesTransformer() { @Override public byte[] transform(byte[] currentArray, boolean inPlace) { - return Bytes.from(currentArray).array(); + return Bytes.of(currentArray).array(); } @Override @@ -428,7 +428,7 @@ public boolean supportInPlaceTransformation() { return false; } }).array()); - assertArrayEquals(new byte[2], Bytes.from(example_bytes_two).transform(new BytesTransformer() { + assertArrayEquals(new byte[2], Bytes.of(example_bytes_two).transform(new BytesTransformer() { @Override public byte[] transform(byte[] currentArray, boolean inPlace) { return Bytes.allocate(currentArray.length).array(); @@ -479,7 +479,7 @@ public void transformHmac() { assertEquals(Bytes.parseHex("9aff87db4fd8df58c9081d8386ccc71c9a0f5fe9491235b7bb17e1be20bbe82b"), Bytes.parseHex("d8b6239569b184eb7991").transform(BytesTransformers.hmac(Bytes.parseHex("671536819982").array(), "HmacSHA256"))); //reference test vectors - see https://tools.ietf.org/html/rfc2104 - assertEquals(Bytes.parseHex("9294727a3638bb1c13f48ef8158bfc9d"), Bytes.from("Hi There").transform(new HmacTransformer(Bytes.parseHex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").array(), "HmacMd5"))); + assertEquals(Bytes.parseHex("9294727a3638bb1c13f48ef8158bfc9d"), Bytes.of("Hi There").transform(new HmacTransformer(Bytes.parseHex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").array(), "HmacMd5"))); assertEquals(Bytes.parseHex("56be34521d144c88dbb8c733f0e8b3f6"), Bytes.parseHex("DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD").transform(new HmacTransformer(Bytes.parseHex("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA").array(), "HmacMd5"))); } } diff --git a/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java b/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java index 9213875..babf669 100644 --- a/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java @@ -31,8 +31,8 @@ public class ImmutableBytesTest extends ABytesTest { @Test public void immutableShouldKeepProperty() { - testImmutableProperties(Bytes.from(example_bytes_seven).immutable()); - testImmutableProperties(Bytes.wrapImmutable(example_bytes_seven)); + testImmutableProperties(Bytes.of(example_bytes_seven).immutable()); + testImmutableProperties(Bytes.ofImmutable(example_bytes_seven)); } private void testImmutableProperties(ImmutableBytes b) { @@ -55,7 +55,7 @@ private void testImmutableProperties(ImmutableBytes b) { @Test public void testConvertImmutable() { - Bytes b = Bytes.from(example_bytes_seven); + Bytes b = Bytes.of(example_bytes_seven); Bytes m = b.copy(); assertEquals(b, m); assertTrue(b.equalsContent(m)); @@ -86,7 +86,7 @@ public void testConvertImmutable() { } Bytes fromAndTest(byte[] bytes) { - Bytes b = Bytes.from(bytes); + Bytes b = Bytes.of(bytes); assertArrayEquals(bytes, b.array()); return b; } diff --git a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java index 1f3f032..da628b3 100644 --- a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java @@ -49,7 +49,7 @@ public void overwriteOtherArray() { public void overwritePartialArray() { Bytes b = fromAndTest(example_bytes_seven); assertSame(b, b.overwrite(new byte[]{(byte) 0xAA}, 0)); - assertArrayEquals(Bytes.from((byte) 0xAA).append(Bytes.wrap(example_bytes_seven).copy(1, example_bytes_seven.length - 1)).array(), b.array()); + assertArrayEquals(Bytes.of((byte) 0xAA).append(Bytes.wrap(example_bytes_seven).copy(1, example_bytes_seven.length - 1)).array(), b.array()); } @Test @@ -57,7 +57,7 @@ public void overwritePartialArray2() { Bytes b = fromAndTest(example_bytes_seven); assertSame(b, b.overwrite(new byte[]{(byte) 0xAA}, 1)); assertArrayEquals( - Bytes.from(example_bytes_seven) + Bytes.of(example_bytes_seven) .copy(0, 1) .append((byte) 0xAA) .append(Bytes.wrap(example_bytes_seven).copy(2, example_bytes_seven.length - 2)).array(), b.array()); @@ -72,7 +72,7 @@ public void fill() { @Test public void testCheckReferencesAndCopy() { - Bytes b = Bytes.from(example_bytes_seven); + Bytes b = Bytes.of(example_bytes_seven); Bytes m = b.copy(); assertEquals(b, m); assertTrue(b.equalsContent(m)); @@ -186,10 +186,10 @@ public void testAutoCloseable() { @Test - public void testCheckReferenceFrom() { + public void testCheckReferenceOf() { byte[] ref = new byte[]{1, 2, 3, 4}; - Bytes refFrom = Bytes.from(ref); + Bytes refFrom = Bytes.of(ref); byte[] refFromInternalArr = refFrom.array(); assertNotSame(ref, refFrom.array()); assertArrayEquals(ref, refFrom.array()); diff --git a/src/test/java/at/favre/lib/bytes/ReadOnlyBytesTest.java b/src/test/java/at/favre/lib/bytes/ReadOnlyBytesTest.java index f7bff20..fb8a538 100644 --- a/src/test/java/at/favre/lib/bytes/ReadOnlyBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/ReadOnlyBytesTest.java @@ -28,7 +28,7 @@ public class ReadOnlyBytesTest extends ABytesTest { @Test public void readOnlyShouldKeepProperty() { - ReadOnlyBytes b = Bytes.from(example_bytes_seven).readOnly(); + ReadOnlyBytes b = Bytes.of(example_bytes_seven).readOnly(); assertSame(b, b.readOnly()); assertFalse(b.isMutable()); assertTrue(b.isReadOnly()); @@ -48,28 +48,28 @@ public void readOnlyShouldKeepProperty() { @Test(expected = UnsupportedOperationException.class) public void readOnlyDuplicateNotAllowed() { - Bytes.from(example_bytes_seven).readOnly().duplicate(); + Bytes.of(example_bytes_seven).readOnly().duplicate(); } @Test(expected = UnsupportedOperationException.class) public void readOnlyImmutableNotAllowed() { - Bytes.from(example_bytes_seven).readOnly().immutable(); + Bytes.of(example_bytes_seven).readOnly().immutable(); } @Test public void readOnly() { - assertFalse(Bytes.from(example_bytes_twentyfour).isReadOnly()); - assertTrue(Bytes.from(example_bytes_twentyfour).readOnly().isReadOnly()); - assertTrue(Bytes.from(example_bytes_twentyfour).readOnly().copy().isReadOnly()); + assertFalse(Bytes.of(example_bytes_twentyfour).isReadOnly()); + assertTrue(Bytes.of(example_bytes_twentyfour).readOnly().isReadOnly()); + assertTrue(Bytes.of(example_bytes_twentyfour).readOnly().copy().isReadOnly()); - assertArrayEquals(example_bytes_twentyfour, Bytes.from(example_bytes_twentyfour).readOnly().internalArray()); + assertArrayEquals(example_bytes_twentyfour, Bytes.of(example_bytes_twentyfour).readOnly().internalArray()); try { - Bytes.from(example_bytes_twentyfour).readOnly().array(); + Bytes.of(example_bytes_twentyfour).readOnly().array(); fail(); } catch (UnsupportedOperationException ignored) { } - Bytes b = Bytes.from(example_bytes_twentyfour).readOnly(); + Bytes b = Bytes.of(example_bytes_twentyfour).readOnly(); assertSame(b, b.readOnly()); } } diff --git a/src/test/java/at/favre/lib/bytes/UtilByteTest.java b/src/test/java/at/favre/lib/bytes/UtilByteTest.java index 26180ea..9f14f42 100644 --- a/src/test/java/at/favre/lib/bytes/UtilByteTest.java +++ b/src/test/java/at/favre/lib/bytes/UtilByteTest.java @@ -165,16 +165,16 @@ public void testLeftShift() { assertArrayEquals(new byte[]{0, 1, 0, 0}, Util.Byte.shiftLeft(new byte[]{0, 0, -128, 0}, 1)); assertArrayEquals(new byte[]{0, 1, 0, 0}, Util.Byte.shiftLeft(new byte[]{0, 0, 64, 0}, 2)); assertArrayEquals(new byte[]{1, 1, 1, 0}, Util.Byte.shiftLeft(new byte[]{-128, -128, -128, -128}, 1)); - assertArrayEquals(new byte[]{0, 0, 2, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 1)); - assertArrayEquals(new byte[]{0, 0, 4, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 2)); - assertArrayEquals(new byte[]{0, 0, 8, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 3)); - assertArrayEquals(new byte[]{0, 1, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 8)); - assertArrayEquals(new byte[]{0, 2, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 9)); - assertArrayEquals(new byte[]{1, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 16)); - assertArrayEquals(new byte[]{2, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 17)); - assertArrayEquals(new byte[]{-128, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 23)); - assertArrayEquals(new byte[]{0, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 24)); - assertArrayEquals(new byte[]{0, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.from(test).array(), 24)); + assertArrayEquals(new byte[]{0, 0, 2, 0}, Util.Byte.shiftLeft(Bytes.of(test).array(), 1)); + assertArrayEquals(new byte[]{0, 0, 4, 0}, Util.Byte.shiftLeft(Bytes.of(test).array(), 2)); + assertArrayEquals(new byte[]{0, 0, 8, 0}, Util.Byte.shiftLeft(Bytes.of(test).array(), 3)); + assertArrayEquals(new byte[]{0, 1, 0, 0}, Util.Byte.shiftLeft(Bytes.of(test).array(), 8)); + assertArrayEquals(new byte[]{0, 2, 0, 0}, Util.Byte.shiftLeft(Bytes.of(test).array(), 9)); + assertArrayEquals(new byte[]{1, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.of(test).array(), 16)); + assertArrayEquals(new byte[]{2, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.of(test).array(), 17)); + assertArrayEquals(new byte[]{-128, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.of(test).array(), 23)); + assertArrayEquals(new byte[]{0, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.of(test).array(), 24)); + assertArrayEquals(new byte[]{0, 0, 0, 0}, Util.Byte.shiftLeft(Bytes.of(test).array(), 24)); assertSame(test, Util.Byte.shiftLeft(test, 1)); } @@ -186,8 +186,8 @@ public void testLeftShiftAgainstRefImpl() { int shift = 1; Bytes rnd = Bytes.random(4 + new Random().nextInt(14)); - byte[] expected = Bytes.from(new BigInteger(rnd.array()).shiftLeft(shift).toByteArray()).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); - byte[] actual = Bytes.from(Util.Byte.shiftLeft(rnd.copy().array(), shift)).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); + byte[] expected = Bytes.of(new BigInteger(rnd.array()).shiftLeft(shift).toByteArray()).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); + byte[] actual = Bytes.of(Util.Byte.shiftLeft(rnd.copy().array(), shift)).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); System.out.println("Original \t" + rnd.encodeBinary() + " << " + shift); System.out.println("Expected \t" + Bytes.wrap(expected).encodeBinary()); @@ -206,12 +206,12 @@ public void testRightShift() { assertArrayEquals(new byte[]{0, -128, -128, -128}, Util.Byte.shiftRight(new byte[]{1, 1, 1, 1}, 1)); assertArrayEquals(new byte[]{0, -128, 66, 0}, Util.Byte.shiftRight(new byte[]{2, 1, 8, 2}, 2)); assertArrayEquals(new byte[]{0, -128, 66, 0}, new BigInteger(new byte[]{2, 1, 8, 2}).shiftRight(2).toByteArray()); - assertArrayEquals(new byte[]{0, 0, 0, -128}, Util.Byte.shiftRight(Bytes.from(test).array(), 5)); + assertArrayEquals(new byte[]{0, 0, 0, -128}, Util.Byte.shiftRight(Bytes.of(test).array(), 5)); assertArrayEquals(new byte[]{0, 0, 0, -128}, Util.Byte.shiftRight(new byte[]{0, 0, 1, 0}, 1)); - assertArrayEquals(new byte[]{0, 0, 8, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 1)); - assertArrayEquals(new byte[]{0, 0, 4, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 2)); - assertArrayEquals(new byte[]{0, 0, 2, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 3)); - assertArrayEquals(new byte[]{0, 0, 1, 0}, Util.Byte.shiftRight(Bytes.from(test).array(), 4)); + assertArrayEquals(new byte[]{0, 0, 8, 0}, Util.Byte.shiftRight(Bytes.of(test).array(), 1)); + assertArrayEquals(new byte[]{0, 0, 4, 0}, Util.Byte.shiftRight(Bytes.of(test).array(), 2)); + assertArrayEquals(new byte[]{0, 0, 2, 0}, Util.Byte.shiftRight(Bytes.of(test).array(), 3)); + assertArrayEquals(new byte[]{0, 0, 1, 0}, Util.Byte.shiftRight(Bytes.of(test).array(), 4)); assertSame(test, Util.Byte.shiftRight(test, 1)); } @@ -222,8 +222,8 @@ public void testRightShiftAgainstRefImpl() { int shift = new Random().nextInt(64); Bytes rnd = Bytes.random(4 + new Random().nextInt(12)); if (!rnd.bitAt(rnd.lengthBit() - 1)) { //only unsigned - byte[] expected = Bytes.from(new BigInteger(rnd.array()).shiftRight(shift).toByteArray()).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); - byte[] actual = Bytes.from(Util.Byte.shiftRight(rnd.copy().array(), shift)).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); + byte[] expected = Bytes.of(new BigInteger(rnd.array()).shiftRight(shift).toByteArray()).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); + byte[] actual = Bytes.of(Util.Byte.shiftRight(rnd.copy().array(), shift)).resize(rnd.length(), BytesTransformer.ResizeTransformer.Mode.RESIZE_KEEP_FROM_MAX_LENGTH).array(); // System.out.println("Original \t" + rnd.encodeBinary() + " >> " + shift); // System.out.println("Expected \t" + Bytes.wrap(expected).encodeBinary()); From df602bb41cf018f4442efb831e3c4e6a378d05f9 Mon Sep 17 00:00:00 2001 From: Patrick Favre-Bulle Date: Mon, 14 Jan 2019 22:20:06 +0100 Subject: [PATCH 7/9] Rename some missing `from()` and add javadoc for immutable --- README.md | 72 +++++++++---------- src/main/java/at/favre/lib/bytes/Bytes.java | 33 ++++++--- .../at/favre/lib/bytes/MutableBytesTest.java | 1 - 3 files changed, 61 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index fddb7c6..e9595b9 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ int result = b.toInt(); //get as signed int ``` ```java -Bytes b = Bytes.from(array1); of +Bytes b = Bytes.of(array1); of b.resize(2).xor(array2); //shrink to 2 bytes and xor with other array byte[] result = b.array(); //get as byte array ``` @@ -91,7 +91,7 @@ restricts the access to the internal array. There are 3 basic constructors: * `wrap()` which reuses the given array reference; this is equivalent to `ByteBuffer.wrap()` - * `from()` which always creates a new internal array reference (i.e. a copy of the passed reference) + * `of()` which always creates a new internal array reference (i.e. a copy of the passed reference) * `parse()` which parses from binary-text-encoded strings (see other section) Here is a simple example to show the difference: @@ -102,7 +102,7 @@ Bytes bWrap = Bytes.wrap(myArray); assertSame(myArray, bWrap.array()); byte[] myArray2 = ... -Bytes bFrom = Bytes.from(myArray2); +Bytes bFrom = Bytes.of(myArray2); assertNotSame(myArray2, bFrom.array()); assertArrayEquals(myArray2, bFrom.array()); ``` @@ -110,7 +110,7 @@ assertArrayEquals(myArray2, bFrom.array()); The following code is equivalent: ```java -Bytes.wrap(myArray).copy() ~ Bytes.from(myArray) +Bytes.wrap(myArray).copy() ~ Bytes.of(myArray) ``` #### More Constructors @@ -119,22 +119,22 @@ For a **null-safe version**, which uses the empty array in case of a null byte a ```java Bytes.wrapNullSafe(null); -Bytes.fromNullSafe(null); +Bytes.ofNullSafe(null); ``` **Concatenating** of multiple byte arrays or bytes: ```java -Bytes.from(array1, array2, array3); -Bytes.from((byte) 0x01, (byte) 0x02, (byte) 0x03); +Bytes.of(array1, array2, array3); +Bytes.of((byte) 0x01, (byte) 0x02, (byte) 0x03); ``` Creating byte arrays from **primitive integer** types and arrays: ```java -Bytes.from(8); //00000000 00000000 00000000 00001000 -Bytes.from(1897621543227L); -Bytes.from(1634, 88903, 77263); +Bytes.of(8); //00000000 00000000 00000000 00001000 +Bytes.of(1897621543227L); +Bytes.of(1634, 88903, 77263); ``` Initializing **empty arrays** of arbitrary length: @@ -154,22 +154,22 @@ Bytes.random(12); Reading byte content of encoded `String`s: ```java -Bytes.from(utf8String) -Bytes.from(utf8StringToNormalize, Normalizer.Form.NFKD) //normalizes unicode -Bytes.from(asciiString, StandardCharset.US_ASCII) //any charset +Bytes.of(utf8String) +Bytes.of(utf8StringToNormalize, Normalizer.Form.NFKD) //normalizes unicode +Bytes.of(asciiString, StandardCharset.US_ASCII) //any charset ``` And other types: ```java -Bytes.from(byteInputStream); //read whole java.io.InputStream -Bytes.from(byteInputStream, 16); //read java.io.InputStream with length limitation -Bytes.from(byteList); //List byteList = ... -Bytes.from(myBitSet); //java.util.BitSet myBitSet = ... -Bytes.from(bigInteger); //java.math.BigInteger -Bytes.from(file); of -Bytes.from(dataInput, 16); of -Bytes.from(UUID.randomUUID()); //read 16 bytes from UUID +Bytes.of(byteInputStream); //read whole java.io.InputStream +Bytes.of(byteInputStream, 16); //read java.io.InputStream with length limitation +Bytes.of(byteList); //List byteList = ... +Bytes.of(myBitSet); //java.util.BitSet myBitSet = ... +Bytes.of(bigInteger); //java.math.BigInteger +Bytes.of(file); of +Bytes.of(dataInput, 16); of +Bytes.of(UUID.randomUUID()); //read 16 bytes from UUID ``` For parsing binary-text-encoded strings, see below. @@ -303,7 +303,7 @@ Bytes.encode(base85Encoder); Bytes.parseHex("a0e13eaa1a") Bytes.parseHex("0xA0E1") -Bytes.from(array).encodeHex() //a0e13eaa1a +Bytes.of(array).encodeHex() //a0e13eaa1a ``` This lib has it's own build in **Base64** encoder: @@ -311,24 +311,24 @@ This lib has it's own build in **Base64** encoder: ```java Bytes.parseBase64("SpT9/x6v7Q=="); -Bytes.from(array).encodeBase64(); //"SpT9/x6v7Q==" -Bytes.from(array).encodeBase64Url(); //"SpT9_x6v7Q==" +Bytes.of(array).encodeBase64(); //"SpT9/x6v7Q==" +Bytes.of(array).encodeBase64Url(); //"SpT9_x6v7Q==" ``` also a **Base32** encoder (using the RFC4648 non-hex alphabet): ```java Bytes.parseBase32("MZXQ===="); -Bytes.from(array).encodeBase32(); +Bytes.of(array).encodeBase32(); ``` Additionally the following radix encodings are supported: ```java -Bytes.from(array).encodeBinary(); //1110110110101111 -Bytes.from(array).encodeDec(); //20992966904426477 -Bytes.from(array).encodeOctal(); //1124517677707527755 -Bytes.from(array).encodeRadix(36); //5qpdvuwjvu5 +Bytes.of(array).encodeBinary(); //1110110110101111 +Bytes.of(array).encodeDec(); //20992966904426477 +Bytes.of(array).encodeOctal(); //1124517677707527755 +Bytes.of(array).encodeRadix(36); //5qpdvuwjvu5 ``` ### Handling Strings @@ -337,7 +337,7 @@ You can easily get the **UTF-8 encoded version** of a string with ```java String s = "..."; -Bytes.from(s); +Bytes.of(s); ``` or get the **[normalized version](https://en.wikipedia.org/wiki/Unicode_equivalence)**, @@ -345,21 +345,21 @@ which is the recommended way to convert e.g. user passwords ```java String pwd = "ℌH"; -Bytes.from(pwd, Normalizer.Form.NFKD); //would be "HH" normalized +Bytes.of(pwd, Normalizer.Form.NFKD); //would be "HH" normalized ``` or get as any other **[character encodings](https://en.wikipedia.org/wiki/Character_encoding)** ```java String asciiString = "ascii"; -Bytes.from(asciiString, StandardCharsets.US_ASCII); +Bytes.of(asciiString, StandardCharsets.US_ASCII); ``` To easily append a string to an byte array you can do ```java String userPwdHash = ...; -Bytes.from(salt).append(userPwd).hashSha256(); +Bytes.of(salt).append(userPwd).hashSha256(); ``` ### Utility Methods @@ -554,7 +554,7 @@ to avoid unneeded array creation to minimize time and space complexity. To create a mutable instance just do: ```java -MutableBytes b = Bytes.from(array).mutable(); +MutableBytes b = Bytes.of(array).mutable(); ``` Mutable classes also enable further APIs for directly modify the internal array: @@ -576,7 +576,7 @@ Bytes b2 = b.immutable(); *Note:* a copy will inherit mutability/read-only properties: ```java -Bytes b = Bytes.from(array).mutable().copy(); +Bytes b = Bytes.of(array).mutable().copy(); assertTrue(b.isMutable()); ``` @@ -599,7 +599,7 @@ especially no easy way to alter the internal byte array, read-only instances may be created by: ```java -Bytes b = Bytes.from(array).readOnly(); +Bytes b = Bytes.of(array).readOnly(); ``` Every call to the following conversation methods will throw a `ReadOnlyBufferException`: diff --git a/src/main/java/at/favre/lib/bytes/Bytes.java b/src/main/java/at/favre/lib/bytes/Bytes.java index d0b8179..53a00af 100644 --- a/src/main/java/at/favre/lib/bytes/Bytes.java +++ b/src/main/java/at/favre/lib/bytes/Bytes.java @@ -49,7 +49,7 @@ *

* Example: *

- *     Bytes b = Bytes.from(array).mutable();
+ *     Bytes b = Bytes.of(array).mutable();
  *     b.not();
  *     System.out.println(b.encodeHex());
  * 
@@ -95,7 +95,7 @@ public static Bytes allocate(int length, byte defaultValue) { /** * Creates an Byte instance with an internal empty byte array. Same as calling {@link #allocate(int)} with 0. * - * @return the empty instance (always the same reference + * @return the empty instance (always the same reference) */ public static Bytes empty() { return EMPTY; @@ -109,7 +109,7 @@ public static Bytes empty() { * @return new instance */ public static Bytes wrap(Bytes bytes) { - return new Bytes(bytes.internalArray(), bytes.byteOrder); + return wrap(bytes.internalArray(), bytes.byteOrder); } /** @@ -196,12 +196,29 @@ public static Bytes of(byte[] array, int offset, int length) { return wrap(part); } - public static ImmutableBytes ofImmutable(byte[] array) { - return ofImmutable(array, DEFAULT_ORDER); + /** + * Creates an immutable instance of the copy of given byte array. + * Similar to calling Bytes.wrap(array).immutable() without the need for an intermediate + * instance and possible redundant copying of the internal byte array. + * + * @param byteArrayToCopy to create an immutable instance from + * @return new instance + */ + public static ImmutableBytes ofImmutable(byte[] byteArrayToCopy) { + return ofImmutable(byteArrayToCopy, DEFAULT_ORDER); } - public static ImmutableBytes ofImmutable(byte[] array, ByteOrder byteOrder) { - return new ImmutableBytes(Objects.requireNonNull(Arrays.copyOf(array, array.length), + /** + * Creates an immutable instance of the copy of given byte array. + * Similar to calling Bytes.wrap(array, byteOrder).immutable() without the need for + * an intermediate instance and possible redundant copying of the internal byte array. + * + * @param byteArrayToCopy to create an immutable instance from + * @param byteOrder the byte order of passed array + * @return new instance + */ + public static ImmutableBytes ofImmutable(byte[] byteArrayToCopy, ByteOrder byteOrder) { + return new ImmutableBytes(Objects.requireNonNull(Arrays.copyOf(byteArrayToCopy, byteArrayToCopy.length), "passed array must not be null"), Objects.requireNonNull(byteOrder, "byte order must not be null")); } @@ -942,7 +959,7 @@ public Bytes rightShift(int shiftCount) { } /** - * Returns a Byte whose value is equivalent to this Byte with the designated bit set to newBitValue. Bits start to count from the LSB (ie. Bytes.from(0).switchBit(0,true) == 1) + * Returns a Byte whose value is equivalent to this Byte with the designated bit set to newBitValue. Bits start to count from the LSB (ie. Bytes.of(0).switchBit(0,true) == 1) * * @param bitPosition not to confuse with byte position * @param newBitValue if true set to 1, 0 otherwise diff --git a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java index da628b3..c30e7a8 100644 --- a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java @@ -184,7 +184,6 @@ public void testAutoCloseable() { assertArrayNotEquals(new byte[16], leak.array()); } - @Test public void testCheckReferenceOf() { byte[] ref = new byte[]{1, 2, 3, 4}; From 1eddced1d3a45be84505e6ef2d144cd99dcb88f5 Mon Sep 17 00:00:00 2001 From: Patrick Favre-Bulle Date: Mon, 14 Jan 2019 22:57:14 +0100 Subject: [PATCH 8/9] More tests and more doc --- README.md | 2 +- src/main/java/at/favre/lib/bytes/Bytes.java | 15 ++++++-- .../at/favre/lib/bytes/ImmutableBytes.java | 4 +- .../at/favre/lib/bytes/BytesBenchmark.java | 8 ++-- .../favre/lib/bytes/ImmutableBytesTest.java | 19 ++++++++++ .../at/favre/lib/bytes/MutableBytesTest.java | 37 +++++++++++-------- 6 files changed, 60 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index e9595b9..b5c5fef 100644 --- a/README.md +++ b/README.md @@ -205,7 +205,7 @@ Bytes result = Bytes.wrap(array1).append("some string"); Bytes.wrap(array).xor(array2); // 0010 0011 xor() 1011 1000 = 1001 1011 Bytes.wrap(array).or(array2); // 0010 0011 or() 1101 0100 = 1111 0111 Bytes.wrap(array).and(array2); // 0010 0011 and() 1011 1000 = 0010 0000 -Bytes.wrap(array).negate(); // 0010 0011 negate() = 1101 1100 +Bytes.wrap(array).not(); // 0010 0011 negate() = 1101 1100 Bytes.wrap(array).leftShift(8); Bytes.wrap(array).rightShift(8); Bytes.wrap(array).switchBit(3, true); diff --git a/src/main/java/at/favre/lib/bytes/Bytes.java b/src/main/java/at/favre/lib/bytes/Bytes.java index 53a00af..1bb1434 100644 --- a/src/main/java/at/favre/lib/bytes/Bytes.java +++ b/src/main/java/at/favre/lib/bytes/Bytes.java @@ -44,13 +44,16 @@ *

* It supports byte ordering (little/big endianness). *

- * This class is immutable as long as the internal array is not changed from outside (which can't be assured, when - * using using wrap()). It is possible to create a immutable version (see {@link ImmutableBytes}). + * This class is fully mutable and the caller can read and alter the internal byte array through {@link #array()}. + * This mode is especially useful to design memory efficient algorithms. It is possible create an immutable + * instance through either calling {@link #immutable()} or creating one with {@link Bytes#ofImmutable(byte[])}, + * where every operation will copy the internally array and the caller cannot alter it because only copies are + * returned. *

* Example: *

- *     Bytes b = Bytes.of(array).mutable();
- *     b.not();
+ *     Bytes b = Bytes.wrap(array).immutable();
+ *     b = b.not();
  *     System.out.println(b.encodeHex());
  * 
* @@ -200,6 +203,8 @@ public static Bytes of(byte[] array, int offset, int length) { * Creates an immutable instance of the copy of given byte array. * Similar to calling Bytes.wrap(array).immutable() without the need for an intermediate * instance and possible redundant copying of the internal byte array. + *

+ * See {@link ImmutableBytes}. * * @param byteArrayToCopy to create an immutable instance from * @return new instance @@ -212,6 +217,8 @@ public static ImmutableBytes ofImmutable(byte[] byteArrayToCopy) { * Creates an immutable instance of the copy of given byte array. * Similar to calling Bytes.wrap(array, byteOrder).immutable() without the need for * an intermediate instance and possible redundant copying of the internal byte array. + *

+ * See {@link ImmutableBytes}. * * @param byteArrayToCopy to create an immutable instance from * @param byteOrder the byte order of passed array diff --git a/src/main/java/at/favre/lib/bytes/ImmutableBytes.java b/src/main/java/at/favre/lib/bytes/ImmutableBytes.java index 7ae75c5..d5c5a53 100644 --- a/src/main/java/at/favre/lib/bytes/ImmutableBytes.java +++ b/src/main/java/at/favre/lib/bytes/ImmutableBytes.java @@ -6,7 +6,9 @@ * An immutable version of {@link Bytes}. *

* Every operation will create a new instance and a new copy of the - * internal array (if it would be modified). + * internal array (if it would be modified). Calling {@link #array()} will return a copy of the internal array. + * Use this only for handling smaller byte arrays as copying may incur a lot of memory allocation + * and garbage collection. */ public class ImmutableBytes extends Bytes { diff --git a/src/test/java/at/favre/lib/bytes/BytesBenchmark.java b/src/test/java/at/favre/lib/bytes/BytesBenchmark.java index 3b62a16..64d9f0d 100644 --- a/src/test/java/at/favre/lib/bytes/BytesBenchmark.java +++ b/src/test/java/at/favre/lib/bytes/BytesBenchmark.java @@ -31,7 +31,7 @@ public class BytesBenchmark { public void immutableVsMutable() throws Exception { int length = 16 * 1024; Bytes randomXorOp = Bytes.random(length); - Bytes immutable = Bytes.allocate(length); + Bytes immutable = Bytes.allocate(length).immutable(); Bytes mutable = Bytes.allocate(length); for (int i = 0; i < 10; i++) { @@ -40,9 +40,9 @@ public void immutableVsMutable() throws Exception { } for (int i = 0; i < 3; i++) { - Thread.sleep(32); + Thread.sleep(1500); long durationImmutable = runBenchmark(randomXorOp, immutable, length); - Thread.sleep(120); + Thread.sleep(1500); long durationMutable = runBenchmark(randomXorOp, mutable, length); System.out.println("\nRun " + i); System.out.println("Immutable: \t" + durationImmutable + " ns"); @@ -52,7 +52,7 @@ public void immutableVsMutable() throws Exception { private long runBenchmark(Bytes randomXorOp, Bytes bytes, int byteLength) { long startImmutable = System.nanoTime(); - for (int i = 0; i < 10000; i++) { + for (int i = 0; i < 100000; i++) { if (i % 150 == 0) { randomXorOp = randomXorOp.xor(Bytes.random(byteLength)); diff --git a/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java b/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java index babf669..50cc581 100644 --- a/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java @@ -85,6 +85,25 @@ public void testConvertImmutable() { assertNotEquals(0, m2i.byteAt(0)); } + @Test + public void testImmutableAlwaysCopy() { + Bytes b = Bytes.ofImmutable(new byte[]{1, 2, 3, 4, 5}); + assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, b.array()); + + Bytes b2 = b.xor(new byte[]{1, 2, 1, 2, 1}); + assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, b.array()); + assertArrayNotEquals(new byte[]{1, 2, 3, 4, 5}, b2.array()); + assertArrayEquals(new byte[]{0, 0, 2, 6, 4}, b2.array()); + assertNotSame(b.array(), b2.array()); + + Bytes b3 = b2.not(); + assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, b.array()); + assertArrayEquals(new byte[]{0, 0, 2, 6, 4}, b2.array()); + assertArrayNotEquals(new byte[]{0, 0, 2, 6, 4}, b3.array()); + assertArrayEquals(new byte[]{-1, -1, -3, -7, -5}, b3.array()); + assertNotSame(b2.array(), b3.array()); + } + Bytes fromAndTest(byte[] bytes) { Bytes b = Bytes.of(bytes); assertArrayEquals(bytes, b.array()); diff --git a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java index c30e7a8..6f86614 100644 --- a/src/test/java/at/favre/lib/bytes/MutableBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/MutableBytesTest.java @@ -186,34 +186,41 @@ public void testAutoCloseable() { @Test public void testCheckReferenceOf() { - byte[] ref = new byte[]{1, 2, 3, 4}; + byte[] refArr = new byte[]{1, 2, 3, 4}; - Bytes refFrom = Bytes.of(ref); - byte[] refFromInternalArr = refFrom.array(); - assertNotSame(ref, refFrom.array()); - assertArrayEquals(ref, refFrom.array()); - assertSame(refFromInternalArr, refFrom.array()); - assertSame(refFrom.array(), refFrom.array()); + Bytes refOf = Bytes.of(refArr); + byte[] refFromInternalArr = refOf.array(); + assertNotSame(refArr, refOf.array()); + assertArrayEquals(refArr, refOf.array()); + assertSame(refFromInternalArr, refOf.array()); + assertSame(refOf.array(), refOf.array()); - refFrom.xor(new byte[]{0, 0, 0, 0}); - assertSame(refFromInternalArr, refFrom.array()); - assertNotEquals(ref, refFrom.array()); + refOf.xor(new byte[]{0, 0, 0, 0}); + assertSame(refFromInternalArr, refOf.array()); + assertNotEquals(refArr, refOf.array()); + assertNotEquals(new byte[]{1, 2, 3, 4}, refOf.array()); + + refOf.not(); + assertSame(refFromInternalArr, refOf.array()); } @Test public void testCheckReferenceWrap() { - byte[] ref = new byte[]{1, 2, 3, 4}; + byte[] refArr = new byte[]{1, 2, 3, 4}; - Bytes refWrap = Bytes.wrap(ref); + Bytes refWrap = Bytes.wrap(refArr); byte[] refFromInternalArr = refWrap.array(); - assertSame(ref, refWrap.array()); - assertArrayEquals(ref, refWrap.array()); + assertSame(refArr, refWrap.array()); + assertArrayEquals(refArr, refWrap.array()); assertSame(refFromInternalArr, refWrap.array()); assertSame(refWrap.array(), refWrap.array()); refWrap.xor(new byte[]{0, 0, 0, 0}); assertSame(refFromInternalArr, refWrap.array()); - assertEquals(ref, refWrap.array()); + assertEquals(refArr, refWrap.array()); assertNotEquals(new byte[]{1, 2, 3, 4}, refWrap.array()); + + refWrap.not(); + assertSame(refFromInternalArr, refWrap.array()); } } From dc6c8297202c1ac7ff79b4d48292bca95f0db33f Mon Sep 17 00:00:00 2001 From: Patrick Favre-Bulle Date: Tue, 12 Mar 2019 08:10:50 +0100 Subject: [PATCH 9/9] Add new byte holder concept --- README.md | 91 +++++++++++++++---- src/main/java/at/favre/lib/bytes/Bytes.java | 41 ++++----- .../java/at/favre/lib/bytes/BytesHolder.java | 66 ++++++++++++++ .../favre/lib/bytes/ImmutableBytesTest.java | 18 ++++ 4 files changed, 176 insertions(+), 40 deletions(-) create mode 100644 src/main/java/at/favre/lib/bytes/BytesHolder.java diff --git a/README.md b/README.md index b5c5fef..8cabec5 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # Bytes Utility Library for Java Bytes is a utility library that makes it easy to **create**, **parse**, **transform**, -**validate** and **convert** byte arrays in Java. It's main class `Bytes` is +**validate** and **convert** byte arrays in Java. It's main class `Bytes` abstracts a collections of bytes and the main API. It supports [endianness](https://en.wikipedia.org/wiki/Endianness) -as well as **copy-on-write** and **mutable** access, so the caller may decide to favor +as well as fully **mutable** and **immutable** access, so the caller may decide to favor performance. This can be seen as combination of the features provided by [`BigInteger`](https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html), [`ByteBuffer`](https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html) but @@ -25,7 +25,7 @@ to blindly paste code snippets from [.](https://stackoverflow.com/questions/23360692/byte-position-in-java) [c](https://stackoverflow.com/questions/11437203/byte-array-to-int-array) [o](https://stackoverflow.com/a/9670279/774398) -[m](https://stackoverflow.com/questions/1519736/random-shuffling-of-an-array) +[m](https://stackoverflow.com/questions/1519736/random-shuffling-of-an-array) as well as providing a simple to understand and descriptive API. [![Download](https://api.bintray.com/packages/patrickfav/maven/bytes-java/images/download.svg)](https://bintray.com/patrickfav/maven/bytes-java/_latestVersion) [![Build Status](https://travis-ci.org/patrickfav/bytes-java.svg?branch=master)](https://travis-ci.org/patrickfav/bytes-java) @@ -80,11 +80,17 @@ byte[] result = b.array(); //get as byte array ## API Description -Per default the instance is **semi-immutable**, which means any transformation will -create a copy of the internal array (it is, however, possible to get and -modify the internal array). There is a **mutable** version which supports -in-place modification for better performance and a **read-only** version which -restricts the access to the internal array. +Per default the instance is **mutable**, which means every transformation will alter +the internal byte array. This mirrors the behaviour of directly mutating a byte array +reference and should feel quite natural to use. The main advantage is to avoid +unnecessary copies which will prevent cluttering the heap, more GC and is general +better for performance. On the downside, every caller can change the internal data, +so care has to be taken to not interfere with other layers of your application. + +There is an **immutable** version which supports will always create a copy when transforming +the instance, as well as only returning copies of the internal array when calling `.array()`. +This helps to prevent side effects, but will create many copies if used extensively. Additionally +a **read-only** version which restricts the access to the internal array can also be used. ### Constructors @@ -145,6 +151,12 @@ Bytes.allocate(4, (byte) 1); //fill with 0x01 Bytes.empty(); //creates zero length byte array ``` +Creating an **immutable** instance where every transformation will create a copy: + +```java +Bytes.ofImmutable(array1); +``` + Creating **random** byte arrays for e.g. testing: ```java @@ -180,7 +192,7 @@ Transformers transform the internal byte array. It is possible to create custom transformers if a specific feature is not provided by the default implementation (see `BytesTransformer`). Depending on the type (mutable vs immutable) and transformer it will overwrite the internal byte array - or always create a copy first. + or create a copy first. ```java Bytes result = Bytes.wrap(array1).transform(myCustomTransformer); @@ -194,6 +206,7 @@ For **appending** byte arrays or primitive integer types to current instances. ```java Bytes result = Bytes.wrap(array1).append(array2); +Bytes result = Bytes.wrap(array1).append(array2, array3, ...); Bytes result = Bytes.wrap(array1).append(1341); Bytes result = Bytes.wrap(array1).append((byte) 3); Bytes result = Bytes.wrap(array1).append("some string"); @@ -205,7 +218,7 @@ Bytes result = Bytes.wrap(array1).append("some string"); Bytes.wrap(array).xor(array2); // 0010 0011 xor() 1011 1000 = 1001 1011 Bytes.wrap(array).or(array2); // 0010 0011 or() 1101 0100 = 1111 0111 Bytes.wrap(array).and(array2); // 0010 0011 and() 1011 1000 = 0010 0000 -Bytes.wrap(array).not(); // 0010 0011 negate() = 1101 1100 +Bytes.wrap(array).not(); // 0010 0011 not() = 1101 1100 Bytes.wrap(array).leftShift(8); Bytes.wrap(array).rightShift(8); Bytes.wrap(array).switchBit(3, true); @@ -285,6 +298,18 @@ Bytes.wrap(array).transform(sort(byteComparator)); Bytes.wrap(array).transform(shuffle()); ``` +#### Direct Access Mutation + +The following methods will directly alter the underlying byte array: + +```java +b.setByteAt(3, (byte) 0xF1) +b.overwrite(anotherArray) //directly overwrite given array +b.fill(0x03) // fills with e.g. 3 +b.wipe() //fills with zeros +b.secureWipe() //fills with random data +``` + ### Parser and Encoder for Binary-Text-Encodings This library can parse and encode a variety of encodings: binary, decimal, [octal](https://en.wikipedia.org/wiki/Octal), @@ -472,7 +497,7 @@ assertTrue(Bytes.allocate(16).validate( The internal byte array can be converted or exported into many different formats. There are 2 different kinds of converters: -* Ones that create a new type which **reuses the same shared memory** +* Ones that create a new type which **reuses the same shared memory** (not for immutable type) * Ones that create a **copy** of the internal array, which start with `to*` #### Shared Memory Conversion @@ -538,16 +563,44 @@ Bytes.wrap(array).toUUID(); // convert 16 byte to UUID Bytes.wrap(array).toCharArray(StandardCharsets.UTF-8); // converts to encoded char array ``` -### Mutable and Read-Only +### Immutable and Read-Only + +Per default the instance is mutable, i.e. every transformation will be alter the internal reference. + + While this design displays various advantages to reduce memory and time complexity + sometimes immutable access might be preferred because it shows other [various advantages](https://softwareengineering.stackexchange.com/questions/151733/if-immutable-objects-are-good-why-do-people-keep-creating-mutable-objects). + +#### Immutable Bytes + +In immutable design, given reference will not change. So for instance if you create an array and + +```java +byte[] arr1 = new byte[] {1, 2, 3}; +byte[] arr2 = new byte[] {4, 5}; +Bytes b = Bytes.of(arr1); +b.append(arr2); +b.encodeHex(); // returns "0102030405" +```` + +As you can see the reference `b` is directly modified. The same example with immutable type looks like this: + +```java +Bytes b = Bytes.ofImmutable(arr1); +Bytes b2 = b.append(arr2); +b.encodeHex(); // returns "010203" +b2.encodeHex(); // returns "0102030405" +```` + +Therefore some methods do not make a lot of sense in an immutable context like: + +```java +Bytes b = Bytes.ofImmutable(arr1); +b = b.overwrite(arr3); // same as creating a new instance with Bytes.ofImmutable(arr3) +```` + -Per default the instance is immutable, i.e. every transformation will create a -a new internal byte array (very similar to the API of `BigInteger`). While -this is usually the default way to design such a construct because it shows -[various advantages](https://softwareengineering.stackexchange.com/questions/151733/if-immutable-objects-are-good-why-do-people-keep-creating-mutable-objects) -this can introduce a major performance issue when handling big arrays -or many transformations. +######### -#### Mutable Bytes All transformers (if possible) reuse or overwrite the same internal memory to avoid unneeded array creation to minimize time and space complexity. diff --git a/src/main/java/at/favre/lib/bytes/Bytes.java b/src/main/java/at/favre/lib/bytes/Bytes.java index 1bb1434..816553f 100644 --- a/src/main/java/at/favre/lib/bytes/Bytes.java +++ b/src/main/java/at/favre/lib/bytes/Bytes.java @@ -112,7 +112,7 @@ public static Bytes empty() { * @return new instance */ public static Bytes wrap(Bytes bytes) { - return wrap(bytes.internalArray(), bytes.byteOrder); + return wrap(bytes.internalArray(), bytes.byteHolder.getByteOrder()); } /** @@ -712,11 +712,11 @@ public static Bytes random(int length, Random random) { /* OBJECT ****************************************************************************************************/ - private final byte[] byteArray; - private final ByteOrder byteOrder; private final BytesFactory factory; private transient int hashCodeCache; + private BytesHolder byteHolder; + Bytes(byte[] byteArray, ByteOrder byteOrder) { this(byteArray, byteOrder, new Factory()); } @@ -728,9 +728,8 @@ public static Bytes random(int length, Random random) { * @param byteOrder the internal byte order - this is used to interpret given array, not to change it */ Bytes(byte[] byteArray, ByteOrder byteOrder, BytesFactory factory) { - this.byteArray = byteArray; - this.byteOrder = byteOrder; this.factory = factory; + this.byteHolder = new BytesHolder.MutableBytesHolder(byteArray, byteOrder); } /* TRANSFORMER **********************************************************************************************/ @@ -1003,7 +1002,7 @@ public Bytes copy() { * @return copied instance */ public Bytes copy(int offset, int length) { - return factory.wrap(Util.Byte.copy(internalArray(), length, offset), byteOrder); + return factory.wrap(Util.Byte.copy(internalArray(), length, offset), byteHolder.getByteOrder()); } /** @@ -1183,7 +1182,7 @@ public boolean isEmpty() { * @see Endianness */ public ByteOrder byteOrder() { - return byteOrder; + return byteHolder.getByteOrder(); } /** @@ -1454,7 +1453,7 @@ public double entropy() { * @return new instance backed by the same data */ public Bytes duplicate() { - return factory.wrap(array(), byteOrder); + return factory.wrap(array(), byteHolder.getByteOrder()); } /** @@ -1467,7 +1466,7 @@ public Bytes duplicate() { * @see Endianness */ public Bytes byteOrder(ByteOrder byteOrder) { - if (byteOrder != this.byteOrder) { + if (byteOrder != this.byteHolder.getByteOrder()) { return wrap(internalArray(), byteOrder); } return this; @@ -1483,7 +1482,7 @@ public ReadOnlyBytes readOnly() { if (isReadOnly()) { return (ReadOnlyBytes) this; } else { - return new ReadOnlyBytes(internalArray(), byteOrder); + return new ReadOnlyBytes(internalArray(), byteHolder.getByteOrder()); } } @@ -1497,11 +1496,11 @@ public ReadOnlyBytes readOnly() { * @throws ReadOnlyBufferException if this is a read-only instance */ public ByteBuffer buffer() { - return ByteBuffer.wrap(array()).order(byteOrder); + return ByteBuffer.wrap(array()).order(byteHolder.getByteOrder()); } private ByteBuffer internalBuffer() { - return ByteBuffer.wrap(internalArray()).order(byteOrder); + return ByteBuffer.wrap(internalArray()).order(byteHolder.getByteOrder()); } /** @@ -1527,7 +1526,7 @@ public byte[] array() { } byte[] internalArray() { - return byteArray; + return byteHolder.get(); } /* IN-PLACE-TRANSFORMER ******************************************************************************/ @@ -1848,7 +1847,7 @@ public byte[] encodeCharsetToBytes(Charset charset) { * @return byte-to-text representation */ public String encode(BinaryToTextEncoding.Encoder encoder) { - return encoder.encode(internalArray(), byteOrder); + return encoder.encode(internalArray(), byteHolder.getByteOrder()); } /* CONVERTERS WITHOUT REUSING THE INTERNAL ARRAY ****************************************************************/ @@ -1894,7 +1893,7 @@ public BitSet toBitSet() { * @return big integer */ public BigInteger toBigInteger() { - if (byteOrder == ByteOrder.LITTLE_ENDIAN) { + if (byteHolder.getByteOrder() == ByteOrder.LITTLE_ENDIAN) { return new BigInteger(new BytesTransformer.ReverseTransformer().transform(internalArray(), false)); } else { return new BigInteger(internalArray()); @@ -2007,7 +2006,7 @@ public int toInt() { */ public int[] toIntArray() { Util.Validation.checkModLength(length(), 4, "creating an int array"); - return Util.Converter.toIntArray(internalArray(), byteOrder); + return Util.Converter.toIntArray(internalArray(), byteHolder.getByteOrder()); } /** @@ -2041,7 +2040,7 @@ public long toLong() { */ public long[] toLongArray() { Util.Validation.checkModLength(length(), 8, "creating an long array"); - return Util.Converter.toLongArray(internalArray(), byteOrder); + return Util.Converter.toLongArray(internalArray(), byteHolder.getByteOrder()); } /** @@ -2088,7 +2087,7 @@ public char[] toCharArray() { * @return char array */ public char[] toCharArray(Charset charset) { - return Util.Converter.byteToCharArray(internalArray(), charset, byteOrder); + return Util.Converter.byteToCharArray(internalArray(), charset, byteHolder.getByteOrder()); } /** @@ -2123,8 +2122,8 @@ public boolean equals(Object o) { Bytes bytes = (Bytes) o; - if (!Arrays.equals(byteArray, bytes.byteArray)) return false; - return Objects.equals(byteOrder, bytes.byteOrder); + if (!Arrays.equals(byteHolder.get(), byteHolder.get())) return false; + return Objects.equals(byteHolder.getByteOrder(), bytes.byteHolder.getByteOrder()); } /** @@ -2170,7 +2169,7 @@ public boolean equals(Byte[] anotherArray) { * @return true if both array have same length and every byte element is the same */ public boolean equals(ByteBuffer buffer) { - return buffer != null && byteOrder == buffer.order() && internalBuffer().equals(buffer); + return buffer != null && byteHolder.getByteOrder() == buffer.order() && internalBuffer().equals(buffer); } /** diff --git a/src/main/java/at/favre/lib/bytes/BytesHolder.java b/src/main/java/at/favre/lib/bytes/BytesHolder.java new file mode 100644 index 0000000..c4391c0 --- /dev/null +++ b/src/main/java/at/favre/lib/bytes/BytesHolder.java @@ -0,0 +1,66 @@ +package at.favre.lib.bytes; + +import java.nio.ByteOrder; + +public interface BytesHolder { + + BytesHolder set(byte[] newArray); + + byte[] get(); + + ByteOrder getByteOrder(); + + abstract class ABytesHolder implements BytesHolder { + private final ByteOrder byteOrder; + //private final BytesFactory factory; + private transient int hashCodeCache; + + ABytesHolder(ByteOrder byteOrder) { + this.byteOrder = byteOrder; + } + + @Override + public ByteOrder getByteOrder() { + return byteOrder; + } + } + + final class MutableBytesHolder extends ABytesHolder { + private byte[] byteArray; + + MutableBytesHolder(byte[] byteArray, ByteOrder byteOrder) { + super(byteOrder); + this.byteArray = byteArray; + } + + @Override + public BytesHolder set(byte[] newArray) { + byteArray = newArray; + return this; + } + + @Override + public byte[] get() { + return byteArray; + } + } + + final class ImmutableBytesHolder extends ABytesHolder { + private final byte[] byteArray; + + ImmutableBytesHolder(byte[] byteArray, ByteOrder byteOrder) { + super(byteOrder); + this.byteArray = byteArray; + } + + @Override + public BytesHolder set(byte[] newArray) { + return new ImmutableBytesHolder(newArray, getByteOrder()); + } + + @Override + public byte[] get() { + return byteArray; + } + } +} diff --git a/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java b/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java index 50cc581..5c30349 100644 --- a/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java +++ b/src/test/java/at/favre/lib/bytes/ImmutableBytesTest.java @@ -121,4 +121,22 @@ public void testAutoCloseableShouldThrowException() { } } + + @Test + public void readmeExample1() { + byte[] arr1 = new byte[]{1, 2, 3}; + byte[] arr2 = new byte[]{4, 5}; + + Bytes b = Bytes.ofImmutable(arr1); + Bytes b2 = b.append(arr2); + System.out.println(b.encodeHex()); // returns "010203" + System.out.println(b2.encodeHex()); // returns "0102030405" + assertEquals(b.encodeHex(), "010203"); + assertEquals(b2.encodeHex(), "0102030405"); + + Bytes bM = Bytes.of(arr1); + bM.append(arr2); + System.out.println(bM.encodeHex()); + assertEquals(bM.encodeHex(), "0102030405"); + } }