When attempting to write a byte beyond the end of a byte[], don't update the position until after we've finished the bounds checks.

Previously, we'd update position, so size left would return -1.

This is a partial roll-forward of cl/673588324.

PiperOrigin-RevId: 677587399
pull/18442/head
Mark Hansen 2 months ago committed by Copybara-Service
parent c8c232f196
commit d98f5e160d
  1. 2
      java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
  2. 6
      java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java

@ -1306,12 +1306,14 @@ public abstract class CodedOutputStream extends ByteOutput {
@Override
public final void write(byte value) throws IOException {
int position = this.position;
try {
buffer[position++] = value;
} catch (IndexOutOfBoundsException e) {
throw new OutOfSpaceException(
String.format("Pos: %d, limit: %d, len: %d", position, limit, 1), e);
}
this.position = position; // Only update position if we stayed within the array bounds.
}
@Override

@ -554,11 +554,7 @@ public class CodedOutputStreamTest {
return;
}
assertThrows(OutOfSpaceException.class, () -> coder.stream().write((byte) 1));
// For some OutputTypes, this test doesn't pass yet.
if (outputType.supportsSpaceLeft()
&& outputType != OutputType.ARRAY
&& outputType != OutputType.NIO_HEAP
&& outputType != OutputType.NIO_HEAP_WITH_INITIAL_OFFSET) {
if (outputType.supportsSpaceLeft()) {
assertThat(coder.stream().spaceLeft()).isEqualTo(0);
}
}

Loading…
Cancel
Save