Skip to content

Commit 7e5e654

Browse files
ctruedengab1one
authored andcommitted
DataHandle: add available and ensureReadable
1 parent 995d6af commit 7e5e654

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import java.io.Closeable;
3535
import java.io.DataInput;
3636
import java.io.DataOutput;
37+
import java.io.EOFException;
3738
import java.io.IOException;
3839
import java.io.InputStreamReader;
3940
import java.nio.ByteBuffer;
@@ -73,6 +74,32 @@ public interface DataHandle<L extends Location> extends WrapperPlugin<L>,
7374
*/
7475
void setLength(long length) throws IOException;
7576

77+
/**
78+
* Verifies that the handle has sufficient bytes available to read, returning
79+
* the actual number of bytes which will be possible to read, which might
80+
* be less than the requested value.
81+
*
82+
* @param count Number of bytes to read.
83+
* @return The actual number of bytes available to be read.
84+
* @throws IOException If something goes wrong with the check.
85+
*/
86+
default long available(final long count) throws IOException {
87+
final long remain = length() - offset();
88+
return remain < count ? remain : count;
89+
}
90+
91+
/**
92+
* Ensures that the handle has sufficient bytes available to read.
93+
*
94+
* @param count Number of bytes to read.
95+
* @see #available(long)
96+
* @throws EOFException If there are insufficient bytes available.
97+
* @throws IOException If something goes wrong with the check.
98+
*/
99+
default void ensureReadable(final long count) throws IOException {
100+
if (available(count) < count) throw new EOFException();
101+
}
102+
76103
/**
77104
* Ensures that the handle has the correct length to be written to and extends
78105
* it as required.

0 commit comments

Comments
 (0)