@Override
public boolean requestCapacity(int capacity) {
- if (buffer.length > capacity) {
+ if (capacity < 0) {
+ throw new IllegalArgumentException("Capacity may not be negative (likely a previous int overflow)");
+ }
+ if (buffer.length >= capacity) {
return true;
}
// implemented in the same growing fashion as ArrayList
int oldCapacity = buffer.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
+ if (newCapacity < capacity) { // Note: this also catches newCapacity int overflow
+ newCapacity = capacity;
+ }
buffer = Arrays.copyOf(buffer, newCapacity);
return true;
}
public static void testBuilderGrowth() {
FlexBuffersBuilder builder = new FlexBuffersBuilder();
- builder.putString("This is a small string");
+ String someString = "This is a small string";
+ builder.putString(someString);
ByteBuffer b = builder.finish();
- TestEq("This is a small string", FlexBuffers.getRoot(b).asString());
+ TestEq(someString, FlexBuffers.getRoot(b).asString());
FlexBuffersBuilder failBuilder = new FlexBuffersBuilder(ByteBuffer.allocate(1));
try {
- failBuilder.putString("This is a small string");
+ failBuilder.putString(someString);
// This should never be reached, it should throw an exception
// since ByteBuffers do not grow
assert(false);
System.exit(1);
}
}
+
}