Skip to content

Commit c4b9d94

Browse files
committed
Use CharsetDecoder to decode a DataBuffer into a String.
1 parent 75d006d commit c4b9d94

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

spring-web-reactive/src/main/java/org/springframework/core/codec/support/StringDecoder.java

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
package org.springframework.core.codec.support;
1818

19+
import java.nio.CharBuffer;
1920
import java.nio.charset.Charset;
2021
import java.nio.charset.StandardCharsets;
2122

@@ -38,11 +39,13 @@
3839
* @author Sebastien Deleuze
3940
* @author Brian Clozel
4041
* @author Arjen Poutsma
42+
* @author Mark Paluch
4143
* @see StringEncoder
4244
*/
4345
public class StringDecoder extends AbstractDecoder<String> {
4446

4547
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
48+
public static final String EMPTY = "";
4649

4750
private final boolean reduceToSingleBuffer;
4851

@@ -82,9 +85,13 @@ public Flux<String> decode(Publisher<DataBuffer> inputStream, ResolvableType typ
8285
}
8386
Charset charset = getCharset(mimeType);
8487
return inputFlux.map(content -> {
85-
byte[] bytes = new byte[content.readableByteCount()];
86-
content.read(bytes);
87-
return new String(bytes, charset);
88+
// fast-path exit.
89+
if(content.readableByteCount() == 0) {
90+
return EMPTY;
91+
}
92+
93+
CharBuffer charBuffer = charset.decode(content.asByteBuffer());
94+
return charBuffer.toString();
8895
});
8996
}
9097

spring-web-reactive/src/test/java/org/springframework/core/codec/support/StringDecoderTests.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
/**
3434
* @author Sebastien Deleuze
3535
* @author Brian Clozel
36+
* @author Mark Paluch
3637
*/
3738
public class StringDecoderTests extends AbstractAllocatingTestCase {
3839

@@ -92,4 +93,14 @@ public void decodeSingle() throws InterruptedException {
9293
assertEquals("foobar", result);
9394
}
9495

96+
@Test
97+
public void decodeEmpty() throws InterruptedException {
98+
Flux<DataBuffer> source = Flux.just(stringBuffer(""));
99+
Single<String> single = RxJava1SingleConverter.from(this.decoder.decode(source,
100+
ResolvableType.forClassWithGenerics(Single.class, String.class),
101+
MediaType.TEXT_PLAIN));
102+
String result = single.toBlocking().value();
103+
assertEquals("", result);
104+
}
105+
95106
}

0 commit comments

Comments
 (0)