JsonWriter { public static <T> byte[] write(Writer<T> writer, T value) { byte[] result = new byte[writer.sizeInBytes(value)]; WriteBuffer b = WriteBuffer.wrap(result); try { writer.write(value, b); } catch (RuntimeException e) { int lengthWritten = result.length; for (int i = 0; i < result.length; i++) { if (result[i] == 0) { lengthWritten = i; break; } } String message = format( "Bug found using %s to write %s as json. Wrote %s/%s bytes: %s", writer.getClass().getSimpleName(), value.getClass().getSimpleName(), lengthWritten, result.length, new String(result, 0, lengthWritten, UTF_8)); throw Platform.get().assertionError(message, e); } return result; }  static byte[] write(Writer<T> writer, T value); static byte[] writeList(Writer<T> writer, List<T> value); static int writeList(Writer<T> writer, List<T> value, byte[] out,
      int pos); static void writeList(Writer<T> writer, List<T> value, WriteBuffer b); static final Charset UTF_8; }
@Test public void doesntStackOverflowOnToBufferWriterBug_lessThanBytes() { class FooWriter implements WriteBuffer.Writer<Object> { @Override public int sizeInBytes(Object value) { return 2; } @Override public void write(Object value, WriteBuffer buffer) { buffer.writeByte('a'); throw new RuntimeException("buggy"); } } class Foo { @Override public String toString() { return new String(JsonWriter.write(new FooWriter(), this), UTF_8); } } Foo foo = new Foo(); assertThatThrownBy(foo::toString) .isInstanceOf(AssertionError.class) .hasMessage("Bug found using FooWriter to write Foo as json. Wrote 1/2 bytes: a"); }
@Test public void doesntStackOverflowOnToBufferWriterBug_Overflow() { class FooWriter implements WriteBuffer.Writer { @Override public int sizeInBytes(Object value) { return 2; } @Override public void write(Object value, WriteBuffer buffer) { buffer.writeByte('a'); buffer.writeByte('b'); buffer.writeByte('c'); } } class Foo { @Override public String toString() { return new String(JsonWriter.write(new FooWriter(), this), UTF_8); } } Foo foo = new Foo(); assertThatThrownBy(foo::toString) .isInstanceOf(AssertionError.class) .hasMessage("Bug found using FooWriter to write Foo as json. Wrote 2/2 bytes: ab"); }