Skip to content

Commit

Permalink
Avoid ByteArrayOutputStream for source values without the need to be …
Browse files Browse the repository at this point in the history
…encoded

Closes gh-24152
  • Loading branch information
jhoeller committed Dec 9, 2019
1 parent ebbb562 commit 119dd04
Showing 1 changed file with 16 additions and 6 deletions.
Expand Up @@ -335,8 +335,21 @@ static String encodeUriComponent(String source, Charset charset, Type type) {
Assert.notNull(type, "Type must not be null");

byte[] bytes = source.getBytes(charset);
boolean original = true;
for (byte b : bytes) {
if (b < 0) {
b += 256;
}
if (!type.isAllowed(b)) {
original = false;
break;
}
}
if (original) {
return source;
}

ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
boolean changed = false;
for (byte b : bytes) {
if (b < 0) {
b += 256;
Expand All @@ -350,10 +363,9 @@ static String encodeUriComponent(String source, Charset charset, Type type) {
char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));
bos.write(hex1);
bos.write(hex2);
changed = true;
}
}
return (changed ? new String(bos.toByteArray(), charset) : source);
return new String(bos.toByteArray(), charset);
}

private Type getHostType() {
Expand Down Expand Up @@ -416,12 +428,10 @@ else if (!type.isAllowed(ch)) {

@Override
protected HierarchicalUriComponents expandInternal(UriTemplateVariables uriVariables) {

Assert.state(!this.encodeState.equals(EncodeState.FULLY_ENCODED),
"URI components already encoded, and could not possibly contain '{' or '}'.");

// Array-based vars rely on the below order..

// Array-based vars rely on the order below...
String schemeTo = expandUriComponent(getScheme(), uriVariables, this.variableEncoder);
String userInfoTo = expandUriComponent(this.userInfo, uriVariables, this.variableEncoder);
String hostTo = expandUriComponent(this.host, uriVariables, this.variableEncoder);
Expand Down

0 comments on commit 119dd04

Please sign in to comment.