Skip to content

Commit 4955d08

Browse files
committed
Use DataBuffer.write in CharSequenceEncoder
Since SPR-17558, `DataBuffer` now offers a new method to write Strings to them. This commit makes `CharSequenceEncoder` use that. Issue: SPR-17558
1 parent 6361b0c commit 4955d08

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

spring-core/src/main/java/org/springframework/core/codec/CharSequenceEncoder.java

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,8 @@
1616

1717
package org.springframework.core.codec;
1818

19-
import java.nio.ByteBuffer;
20-
import java.nio.CharBuffer;
2119
import java.nio.charset.Charset;
20+
import java.nio.charset.CoderMalfunctionError;
2221
import java.nio.charset.StandardCharsets;
2322
import java.util.Map;
2423

@@ -28,6 +27,7 @@
2827
import org.springframework.core.ResolvableType;
2928
import org.springframework.core.io.buffer.DataBuffer;
3029
import org.springframework.core.io.buffer.DataBufferFactory;
30+
import org.springframework.core.io.buffer.DataBufferUtils;
3131
import org.springframework.core.log.LogFormatUtils;
3232
import org.springframework.lang.Nullable;
3333
import org.springframework.util.MimeType;
@@ -75,9 +75,21 @@ public Flux<DataBuffer> encode(Publisher<? extends CharSequence> inputStream,
7575
return Hints.getLogPrefix(hints) + "Writing " + formatted;
7676
});
7777
}
78-
CharBuffer charBuffer = CharBuffer.wrap(charSequence);
79-
ByteBuffer byteBuffer = charset.encode(charBuffer);
80-
return bufferFactory.wrap(byteBuffer);
78+
boolean release = true;
79+
DataBuffer dataBuffer = bufferFactory.allocateBuffer();
80+
try {
81+
dataBuffer.write(charSequence, charset);
82+
release = false;
83+
}
84+
catch (CoderMalfunctionError ex) {
85+
throw new EncodingException("String encoding error: " + ex.getMessage(), ex);
86+
}
87+
finally {
88+
if (release) {
89+
DataBufferUtils.release(dataBuffer);
90+
}
91+
}
92+
return dataBuffer;
8193
});
8294
}
8395

spring-core/src/test/java/org/springframework/core/codec/CharSequenceEncoderTests.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,6 @@ public void encode() {
6363
.consumeNextWith(expectString(this.foo))
6464
.consumeNextWith(expectString(this.bar))
6565
.verifyComplete());
66-
67-
6866
}
6967

7068
}

0 commit comments

Comments
 (0)