Skip to content

Commit aa1b0b6

Browse files
committed
refactor(appsec): avoid toLowerCase allocation in MultipartContentDecoder.extractCharset
Replace toLowerCase(Locale.ROOT).indexOf with an inline ASCII case-insensitive scan to avoid allocating a full lowercase copy of the Content-Type string. Also use the already-computed end variable as the loop bound.
1 parent 228e1c4 commit aa1b0b6

1 file changed

Lines changed: 17 additions & 3 deletions

File tree

internal-api/src/main/java/datadog/trace/api/http/MultipartContentDecoder.java

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import java.nio.charset.CharacterCodingException;
55
import java.nio.charset.Charset;
66
import java.nio.charset.CodingErrorAction;
7-
import java.util.Locale;
87

98
/** Decodes multipart file content bytes to String using the per-part Content-Type charset. */
109
public final class MultipartContentDecoder {
@@ -26,11 +25,11 @@ public static String decodeBytes(byte[] buf, int length, String contentType) {
2625

2726
public static Charset extractCharset(String contentType) {
2827
if (contentType == null) return null;
29-
int idx = contentType.toLowerCase(Locale.ROOT).indexOf("charset=");
28+
int idx = indexOfIgnoreAsciiCase(contentType, "charset=");
3029
if (idx < 0) return null;
3130
int nameStart = idx + 8;
3231
int end = contentType.length();
33-
for (int i = nameStart; i < contentType.length(); i++) {
32+
for (int i = nameStart; i < end; i++) {
3433
char c = contentType.charAt(i);
3534
if (c == ';' || c == ',' || c == ' ') {
3635
end = i;
@@ -48,5 +47,20 @@ public static Charset extractCharset(String contentType) {
4847
}
4948
}
5049

50+
private static int indexOfIgnoreAsciiCase(String s, String needle) {
51+
int sLen = s.length();
52+
int nLen = needle.length();
53+
outer:
54+
for (int i = 0, max = sLen - nLen; i <= max; i++) {
55+
for (int j = 0; j < nLen; j++) {
56+
if (Character.toLowerCase(s.charAt(i + j)) != needle.charAt(j)) {
57+
continue outer;
58+
}
59+
}
60+
return i;
61+
}
62+
return -1;
63+
}
64+
5165
private MultipartContentDecoder() {}
5266
}

0 commit comments

Comments
 (0)