Skip to content

Commit 5e90165

Browse files
committed
ByteBank: add toByteArray methods
These copy the data (in whole or part) into a newly allocated byte[]. Just a convenience, but it's nice to have.
1 parent bb8f791 commit 5e90165

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/main/java/org/scijava/io/ByteBank.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
* A {@link ByteBank} is a self-growing buffer over arbitrary bytes.
3737
*
3838
* @author Gabriel Einsdorf
39+
* @author Curtis Rueden
3940
*/
4041
public interface ByteBank {
4142

@@ -63,6 +64,36 @@ default int getBytes(long startPos, byte[] bytes) {
6364
*/
6465
int getBytes(long startPos, byte[] bytes, int offset, int length);
6566

67+
/**
68+
* Copies part of this buffer into a newly allocated byte array.
69+
*
70+
* @param offset the initial position in the buffer
71+
* @param len the number of bytes to copy
72+
* @return The newly allocated byte array containing the data.
73+
*/
74+
default byte[] toByteArray(final long offset, final int len) {
75+
if (offset < 0 || len < 0 || offset + len > size()) {
76+
throw new IllegalArgumentException("Invalid range");
77+
}
78+
final byte[] bytes = new byte[len];
79+
getBytes(offset, bytes);
80+
return bytes;
81+
}
82+
83+
/**
84+
* Copies this entire buffer into a newly allocated byte array.
85+
*
86+
* @return The newly allocated byte array containing the data.
87+
*/
88+
default byte[] toByteArray() {
89+
long max = size();
90+
if (max > Integer.MAX_VALUE) {
91+
throw new IllegalStateException(
92+
"Byte bank is too large to store into a single byte[]");
93+
}
94+
return toByteArray(0, (int) max);
95+
}
96+
6697
/**
6798
* Sets the bytes starting form the given position to the values form the
6899
* provided array.

0 commit comments

Comments
 (0)