Introduce toString(Charset) in FastByteArrayOutputStream

This commit introduces a toString() overload in
FastByteArrayOutputStream that accepts a Charset in order to mirror the
method that was introduced in ByteArrayOutputStream in JDK 10,
including a special case for when a single buffer is in use internally
to avoid the need to resize.

This commit also updates getContentAsString() in
ContentCachingRequestWrapper to use this new toString(Charset) method.

Closes gh-31737
This commit is contained in:
Patrick Strawderman
2023-12-01 12:50:19 -08:00
committed by Sam Brannen
parent 0bec8125a4
commit 7cdacf3083
3 changed files with 38 additions and 2 deletions

View File

@@ -57,6 +57,24 @@ class FastByteArrayOutputStreamTests {
assertThat(this.os.size()).isEqualTo(sizeBefore);
}
@Test
void stringConversion() throws Exception {
this.os.write(this.helloBytes);
assertThat(this.os.toString()).isEqualTo("Hello World");
assertThat(this.os.toString(StandardCharsets.UTF_8)).isEqualTo("Hello World");
FastByteArrayOutputStream empty = new FastByteArrayOutputStream();
assertThat(empty.toString()).isEqualTo("");
assertThat(empty.toString(StandardCharsets.US_ASCII)).isEqualTo("");
FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream(5);
// Add bytes in multiple writes to ensure we get more than one buffer internally
outputStream.write(this.helloBytes, 0, 5);
outputStream.write(this.helloBytes, 5, 6);
assertThat(outputStream.toString(StandardCharsets.UTF_8)).isEqualTo("Hello World");
assertThat(outputStream.toString()).isEqualTo("Hello World");
}
@Test
void autoGrow() throws IOException {
this.os.resize(1);