StringUtil.stripQuotesAroundValue optimization: avoid two substring calls

This commit is contained in:
Sergey Simonchik
2014-12-11 00:44:15 +03:00
parent c4920a28fa
commit 22a7f048e7
2 changed files with 31 additions and 2 deletions
@@ -1490,11 +1490,22 @@ public class StringUtil extends StringUtilRt {
@NotNull
@Contract(pure = true)
public static String stripQuotesAroundValue(@NotNull String text) {
if (startsWithChar(text, '\"') || startsWithChar(text, '\'')) text = text.substring(1);
if (endsWithChar(text, '\"') || endsWithChar(text, '\'')) text = text.substring(0, text.length() - 1);
final int len = text.length();
if (len > 0) {
final int from = isQuoteAt(text, 0) ? 1 : 0;
final int to = len > 1 && isQuoteAt(text, len - 1) ? len - 1 : len;
if (from > 0 || to < len) {
return text.substring(from, to);
};
}
return text;
}
private static boolean isQuoteAt(@NotNull String text, int ind) {
char ch = text.charAt(ind);
return ch == '\'' || ch == '\"';
}
@Contract(pure = true)
public static boolean isQuotedString(@NotNull String text) {
if (text.length() < 2) return false;
@@ -173,6 +173,24 @@ public class StringUtilTest extends TestCase {
assertEquals("\"foo\'", StringUtil.unquoteString("\"foo\'"));
}
public void testStripQuotesAroundValue() {
assertEquals("", StringUtil.stripQuotesAroundValue(""));
assertEquals("", StringUtil.stripQuotesAroundValue("'"));
assertEquals("", StringUtil.stripQuotesAroundValue("\""));
assertEquals("", StringUtil.stripQuotesAroundValue("''"));
assertEquals("", StringUtil.stripQuotesAroundValue("\"\""));
assertEquals("", StringUtil.stripQuotesAroundValue("'\""));
assertEquals("foo", StringUtil.stripQuotesAroundValue("'foo'"));
assertEquals("foo", StringUtil.stripQuotesAroundValue("'foo"));
assertEquals("foo", StringUtil.stripQuotesAroundValue("foo'"));
assertEquals("f'o'o", StringUtil.stripQuotesAroundValue("'f'o'o'"));
assertEquals("f\"o'o", StringUtil.stripQuotesAroundValue("\"f\"o'o'"));
assertEquals("f\"o'o", StringUtil.stripQuotesAroundValue("f\"o'o"));
assertEquals("\"'f\"o'o\"", StringUtil.stripQuotesAroundValue("\"\"'f\"o'o\"\""));
assertEquals("''f\"o'o''", StringUtil.stripQuotesAroundValue("'''f\"o'o'''"));
assertEquals("foo' 'bar", StringUtil.stripQuotesAroundValue("foo' 'bar"));
}
public void testUnqoteWithQuotationChar() {
assertEquals("", StringUtil.unquoteString("", '|'));
assertEquals("|", StringUtil.unquoteString("|", '|'));