Skip to content

Commit

Permalink
Switch statement is more efficient
Browse files Browse the repository at this point in the history
  • Loading branch information
exoego committed Jan 27, 2023
1 parent fc7ed5f commit 8fabc75
Showing 1 changed file with 23 additions and 24 deletions.
47 changes: 23 additions & 24 deletions src/main/java/com/treasuredata/client/UrlPathSegmentEscaper.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand All @@ -17,7 +14,7 @@ private UrlPathSegmentEscaper()
{
}

private static String replaceWithMap(String text, Pattern pattern, Map<String, String> map)
private static String replaceAllMatched(String text, Pattern pattern)
{
Matcher matcher = pattern.matcher(text);
if (!matcher.find()) {
Expand All @@ -27,39 +24,41 @@ private static String replaceWithMap(String text, Pattern pattern, Map<String, S
int previousEnd = 0;
do {
sb.append(text.subSequence(previousEnd, matcher.start()));
sb.append(map.get(matcher.toMatchResult().group()));
sb.append(replace(matcher.group()));
previousEnd = matcher.end();
} while (matcher.find());
sb.append(text.subSequence(previousEnd, text.length()));
return sb.toString();
}

private static final Pattern GUAVA_INCOMPATIBLE = Pattern.compile("\\+|%(?:2[146789BC]|3[ABD]|7E|40)");
private static final Map<String, String> REPLACEMENT_MAP;
static {
Map<String, String> m = new HashMap<>();
m.put("+", "%20");
m.put("%21", "!");
m.put("%24", "$");
m.put("%26", "&");
m.put("%27", "'");
m.put("%28", "(");
m.put("%29", ")");
m.put("%2B", "+");
m.put("%2C", ",");
m.put("%3A", ":");
m.put("%3B", ";");
m.put("%3D", "=");
m.put("%7E", "~");
m.put("%40", "@");
REPLACEMENT_MAP = Collections.unmodifiableMap(m);

private static String replace(String token)
{
switch (token) {
case "+": return "%20";
case "%21": return "!";
case "%24": return "$";
case "%26": return "&";
case "%27": return "'";
case "%28": return "(";
case "%29": return ")";
case "%2B": return "+";
case "%2C": return ",";
case "%3A": return ":";
case "%3B": return ";";
case "%3D": return "=";
case "%7E": return "~";
case "%40": return "@";
default: throw new IllegalStateException("Unknown token: " + token);
}
}

static String escape(String s)
{
try {
String encoded = URLEncoder.encode(s, "UTF-8");
return replaceWithMap(encoded, GUAVA_INCOMPATIBLE, REPLACEMENT_MAP);
return replaceAllMatched(encoded, GUAVA_INCOMPATIBLE);
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
Expand Down

0 comments on commit 8fabc75

Please sign in to comment.