|
36 | 36 | * A {@link ByteBank} is a self-growing buffer over arbitrary bytes. |
37 | 37 | * |
38 | 38 | * @author Gabriel Einsdorf |
| 39 | + * @author Curtis Rueden |
39 | 40 | */ |
40 | 41 | public interface ByteBank { |
41 | 42 |
|
@@ -63,6 +64,36 @@ default int getBytes(long startPos, byte[] bytes) { |
63 | 64 | */ |
64 | 65 | int getBytes(long startPos, byte[] bytes, int offset, int length); |
65 | 66 |
|
| 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 | + |
66 | 97 | /** |
67 | 98 | * Sets the bytes starting form the given position to the values form the |
68 | 99 | * provided array. |
|
0 commit comments