* @return the number of bytes remaining.
* @throws KryoException if EOS is reached before required bytes are read (buffer underflow). */
final protected int require (int required) throws KryoException {
int remaining = limit - position;
if (remaining >= required) return remaining;
if (required > capacity) throw new KryoException("Buffer too small: capacity: " + capacity + ", required: " + required);
int count;
// Try to fill the buffer.
if (remaining > 0) {
count = fill(niobuffer, limit, capacity - limit);
if (count == -1) throw new KryoException("Buffer underflow.");
remaining += count;
if (remaining >= required) {
limit += count;
return remaining;
}
}
// Compact. Position after compaction can be non-zero
niobuffer.position(position);
niobuffer.compact();
total += position;
position = 0;
while (true) {
count = fill(niobuffer, remaining, capacity - remaining);
if (count == -1) {
if (remaining >= required) break;
throw new KryoException("Buffer underflow.");
}
remaining += count;
if (remaining >= required) break; // Enough has been read.
}
limit = remaining;