Skip to content

Commit

Permalink
Fixed ByteBufferInput position getting out of sync with the buffer po…
Browse files Browse the repository at this point in the history
…sition.
  • Loading branch information
NathanSweet committed Feb 12, 2019
1 parent a570f07 commit d263639
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/com/esotericsoftware/kryo/io/ByteBufferInput.java
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ public void reset () {
byteBuffer.position(0);
}

/** Fills the buffer with more bytes. The default implementation reads from the {@link #getInputStream() InputStream}, if set.
* Can be overridden to fill the bytes from another source. */
/** Fills the buffer with more bytes. May leave the buffer position changed. The default implementation reads from the
* {@link #getInputStream() InputStream}, if set. Can be overridden to fill the bytes from another source. */
protected int fill (ByteBuffer buffer, int offset, int count) throws KryoException {
if (inputStream == null) return -1;
try {
Expand All @@ -151,7 +151,6 @@ protected int fill (ByteBuffer buffer, int offset, int count) throws KryoExcepti
count -= read;
total += read;
}
buffer.position(offset);
return total;
} catch (IOException ex) {
throw new KryoException(ex);
Expand All @@ -164,23 +163,25 @@ protected int require (int required) throws KryoException {
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(byteBuffer, limit, capacity - limit);
if (count == -1) throw new KryoException("Buffer underflow.");
byteBuffer.position(position);
remaining += count;
if (remaining >= required) {
limit += count;
return remaining;
}
}

// Compact. Position after compaction can be non-zero.
byteBuffer.position(position);
byteBuffer.compact();
// Compact.
byteBuffer.compact(); // Buffer's position is at end of compacted bytes.
total += position;
position = 0;

// Try to fill again.
while (true) {
count = fill(byteBuffer, remaining, capacity - remaining);
if (count == -1) {
Expand All @@ -206,6 +207,7 @@ protected int optional (int optional) throws KryoException {

// Try to fill the buffer.
int count = fill(byteBuffer, limit, capacity - limit);
byteBuffer.position(position);
if (count == -1) return remaining == 0 ? -1 : Math.min(remaining, optional);
remaining += count;
if (remaining >= optional) {
Expand All @@ -214,10 +216,11 @@ protected int optional (int optional) throws KryoException {
}

// Compact.
byteBuffer.compact();
byteBuffer.compact(); // Buffer's position is at end of compacted bytes.
total += position;
position = 0;

// Try to fill again.
while (true) {
count = fill(byteBuffer, remaining, capacity - remaining);
if (count == -1) break;
Expand Down

0 comments on commit d263639

Please sign in to comment.