From 6732dd7e58e3adaf217f20f227e6ff7e72cb6b22 Mon Sep 17 00:00:00 2001 From: Charles Munger Date: Tue, 21 Apr 2015 14:35:46 -0700 Subject: Throw OutOfSpaceException instead of IllegalArgumentException. When a MessageNano containing a String is serialized into a buffer that is too small to contain it, and the buffer's boundary happens to be where the string field's length delimiting varint is serialized, and the string's length and 3*length have the same length when encoded as a varint, an IllegalArgumentException is thrown rather than an OutOfSpaceException. Github issue: https://github.com/google/protobuf/issues/292 Change-Id: If478d68cf15bfd0662252d008e42b2bf1ff1c75e --- .../com/google/protobuf/nano/CodedOutputByteBufferNano.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'javanano/src/main/java') diff --git a/javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java b/javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java index 91fa3353..b1b0c53a 100644 --- a/javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java +++ b/javanano/src/main/java/com/google/protobuf/nano/CodedOutputByteBufferNano.java @@ -300,6 +300,12 @@ public final class CodedOutputByteBufferNano { final int maxLengthVarIntSize = computeRawVarint32Size(value.length() * MAX_UTF8_EXPANSION); if (minLengthVarIntSize == maxLengthVarIntSize) { int oldPosition = buffer.position(); + // Buffer.position, when passed a position that is past its limit, throws + // IllegalArgumentException, and this class is documented to throw + // OutOfSpaceException instead. + if (buffer.remaining() < minLengthVarIntSize) { + throw new OutOfSpaceException(oldPosition + minLengthVarIntSize, buffer.limit()); + } buffer.position(oldPosition + minLengthVarIntSize); encode(value, buffer); int newPosition = buffer.position(); @@ -311,7 +317,10 @@ public final class CodedOutputByteBufferNano { encode(value, buffer); } } catch (BufferOverflowException e) { - throw new OutOfSpaceException(buffer.position(), buffer.limit()); + final OutOfSpaceException outOfSpaceException = new OutOfSpaceException(buffer.position(), + buffer.limit()); + outOfSpaceException.initCause(e); + throw outOfSpaceException; } } -- cgit v1.2.3