Skip to content

Commit e36a8fa

Browse files
committed
DataHandle: add available and ensureReadable
1 parent efec596 commit e36a8fa

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/main/java/org/scijava/io/handle/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;
@@ -74,6 +75,32 @@ public interface DataHandle<L extends Location> extends WrapperPlugin<L>,
7475
*/
7576
void setLength(long length) throws IOException;
7677

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

0 commit comments

Comments
 (0)