Skip to content

Commit 22df31d

Browse files
committed
Add new empty() constructor
1 parent acfc476 commit 22df31d

File tree

4 files changed

+19
-1
lines changed

4 files changed

+19
-1
lines changed

CHANGELOG

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
* add `encodeCharsetToBytes()` feature #7
66
* add new `from(char[] charArray, Charset charset)` constructor with improved logic #8
77
* add constructor/converter from/to UUID #9
8+
* add `empty()` constructor, creating empty byte array
89

910
## v0.5.0
1011

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ Initializing **empty arrays** of arbitrary length:
139139
```java
140140
Bytes.allocate(16);
141141
Bytes.allocate(4, (byte) 1); //fill with 0x01
142+
Bytes.empty(); //creates zero length byte array
142143
```
143144

144145
Creating **random** byte arrays for e.g. testing:

src/main/java/at/favre/lib/bytes/Bytes.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,12 +92,21 @@ public static Bytes allocate(int length) {
9292
*/
9393
public static Bytes allocate(int length, byte defaultValue) {
9494
byte[] array = new byte[length];
95-
if (defaultValue != 0) {
95+
if (defaultValue != 0 && length > 0) {
9696
Arrays.fill(array, defaultValue);
9797
}
9898
return wrap(array);
9999
}
100100

101+
/**
102+
* Creates an Byte instance with an internal empty byte array. Same as calling {@link #allocate(int)} with 0.
103+
*
104+
* @return new instance
105+
*/
106+
public static Bytes empty() {
107+
return allocate(0);
108+
}
109+
101110
/**
102111
* Creates a new reference backed by the same byte array.
103112
* Inherits all attributes (readonly, etc.)

src/test/java/at/favre/lib/bytes/BytesConstructorTests.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,13 @@ public void wrapTestNullSafe() {
7676
Bytes.wrapNullSafe(null);
7777
}
7878

79+
@Test
80+
public void empty() {
81+
assertEquals(0, Bytes.empty().length());
82+
assertEquals(Bytes.allocate(0), Bytes.empty());
83+
assertArrayEquals(new byte[0], Bytes.empty().array());
84+
}
85+
7986
@Test
8087
public void allocate() {
8188
assertEquals(0, Bytes.allocate(0).length());

0 commit comments

Comments
 (0)