Convert IndexOutOfBoundsException to OutOfSpaceException in UnsafeDirectNioEncoder

When writing fixed32 and fixed64.

PiperOrigin-RevId: 677938044
pull/18445/head
Mark Hansen 5 months ago committed by Copybara-Service
parent 39824ca7bd
commit 0e75d92cce
  1. 14
      java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
  2. 18
      java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java

@ -2044,7 +2044,12 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed32NoTag(int value) throws IOException {
buffer.putInt(bufferPos(position), value);
try {
buffer.putInt(bufferPos(position), value);
} catch (IndexOutOfBoundsException e) {
throw new OutOfSpaceException(
String.format("Pos: %d, limit: %d, len: %d", position, limit, FIXED32_SIZE), e);
}
position += FIXED32_SIZE;
}
@ -2078,7 +2083,12 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public void writeFixed64NoTag(long value) throws IOException {
buffer.putLong(bufferPos(position), value);
try {
buffer.putLong(bufferPos(position), value);
} catch (IndexOutOfBoundsException e) {
throw new OutOfSpaceException(
String.format("Pos: %d, limit: %d, len: %d", position, limit, FIXED64_SIZE), e);
}
position += FIXED64_SIZE;
}

@ -291,16 +291,9 @@ public class CodedOutputStreamTest {
// Streaming's buffering masks out of bounds writes.
assume().that(outputType).isNotEqualTo(OutputType.STREAM);
Class<? extends Exception> e = OutOfSpaceException.class;
// UnsafeDirectNioEncoder is incorrectly throwing IndexOutOfBoundsException for some operations.
if (outputType == OutputType.NIO_DIRECT_UNSAFE
|| outputType == OutputType.NIO_DIRECT_UNSAFE_WITH_INITIAL_OFFSET) {
e = IndexOutOfBoundsException.class;
}
for (int i = 0; i < 4; i++) {
Coder coder = outputType.newCoder(i);
assertThrows(e, () -> coder.stream().writeFixed32NoTag(1));
assertThrows(OutOfSpaceException.class, () -> coder.stream().writeFixed32NoTag(1));
}
}
@ -309,16 +302,9 @@ public class CodedOutputStreamTest {
// Streaming's buffering masks out of bounds writes.
assume().that(outputType).isNotEqualTo(OutputType.STREAM);
Class<? extends Exception> e = OutOfSpaceException.class;
// UnsafeDirectNioEncoder is incorrectly throwing IndexOutOfBoundsException for some operations.
if (outputType == OutputType.NIO_DIRECT_UNSAFE
|| outputType == OutputType.NIO_DIRECT_UNSAFE_WITH_INITIAL_OFFSET) {
e = IndexOutOfBoundsException.class;
}
for (int i = 0; i < 8; i++) {
Coder coder = outputType.newCoder(i);
assertThrows(e, () -> coder.stream().writeFixed64NoTag(1));
assertThrows(OutOfSpaceException.class, () -> coder.stream().writeFixed64NoTag(1));
}
}

Loading…
Cancel
Save