Skip to content

Commit 5dbd3b0

Browse files
committed
Avoid ByteArrayOutputStream for source values without the need to be encoded
Closes gh-24154
1 parent 197dbff commit 5dbd3b0

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -335,8 +335,21 @@ static String encodeUriComponent(String source, Charset charset, Type type) {
335335
Assert.notNull(type, "Type must not be null");
336336

337337
byte[] bytes = source.getBytes(charset);
338+
boolean original = true;
339+
for (byte b : bytes) {
340+
if (b < 0) {
341+
b += 256;
342+
}
343+
if (!type.isAllowed(b)) {
344+
original = false;
345+
break;
346+
}
347+
}
348+
if (original) {
349+
return source;
350+
}
351+
338352
ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
339-
boolean changed = false;
340353
for (byte b : bytes) {
341354
if (b < 0) {
342355
b += 256;
@@ -350,10 +363,9 @@ static String encodeUriComponent(String source, Charset charset, Type type) {
350363
char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));
351364
bos.write(hex1);
352365
bos.write(hex2);
353-
changed = true;
354366
}
355367
}
356-
return (changed ? new String(bos.toByteArray(), charset) : source);
368+
return new String(bos.toByteArray(), charset);
357369
}
358370

359371
private Type getHostType() {
@@ -416,7 +428,6 @@ else if (!type.isAllowed(ch)) {
416428

417429
@Override
418430
protected HierarchicalUriComponents expandInternal(UriTemplateVariables uriVariables) {
419-
420431
Assert.state(!this.encodeState.equals(EncodeState.FULLY_ENCODED),
421432
"URI components already encoded, and could not possibly contain '{' or '}'.");
422433

0 commit comments

Comments
 (0)