Skip to content
This repository was archived by the owner on Oct 31, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public String unescape(String str) {
int slashIndex = str.indexOf('\\');
if (slashIndex > -1) {
int offset = 0;
StringBuilder unescaped = new StringBuilder();
StringBuilder unescaped = new StringBuilder(str.length() - 1);
while (slashIndex > -1) {
char c = str.charAt(slashIndex + 1);
char r = (c < unescapeMap.length) ? unescapeMap[c] : NO_REPLACEMENT;
Expand All @@ -68,18 +68,24 @@ public String unescape(String str) {
}

public String escape(String str) {
StringBuilder escaped = new StringBuilder();
StringBuilder escaped = null;
int offset = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
char r = (c < escapeMap.length) ? escapeMap[c] : NO_REPLACEMENT;
if (r != NO_REPLACEMENT) {
if (escaped == null) {
escaped = new StringBuilder(str.length() + 1);
}
escaped.append(str, offset, i);
escaped.append('\\');
escaped.append(r);
offset = i + 1;
}
}
if (escaped == null) {
return str;
}
if (offset < str.length()) {
escaped.append(str, offset, str.length());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,15 @@ public void specialCharsAreEscaped() {
String escaped = escapeHelper.escape("\thello\nworld!");
assertThat(escaped, is("\\thello\\nworld\\x"));
}

@Test
public void stringWithoutSpecialCharsIsNotModified() {
StringEscapeHelper escapeHelper = new StringEscapeHelper(
'n', '\n',
't', '\t',
'x', '!'
);
String escaped = escapeHelper.escape("hello world");
assertThat(escaped, is("hello world"));
}
}