StringReader: allow more escapes like JSON

This commit is contained in:
Mary Strodl 2021-04-28 10:31:30 -04:00
parent cf754c4ef6
commit 134099a39d
No known key found for this signature in database
GPG key ID: 23B7FC1590D8E30E
2 changed files with 36 additions and 6 deletions

View file

@ -200,8 +200,37 @@ public class StringReader implements ImmutableStringReader {
while (canRead()) {
final char c = read();
if (escaped) {
if (c == terminator || c == SYNTAX_ESCAPE) {
result.append(c);
Character mogrified = null;
if (c == terminator) {
mogrified = terminator;
} else {
// Adapted from section 9 of ECMA-404:
switch (c) {
case SYNTAX_ESCAPE:
mogrified = SYNTAX_ESCAPE;
break;
case '/':
mogrified = '/';
break;
case 'b':
mogrified = '\b';
break;
case 'f':
mogrified = '\f';
break;
case 'n':
mogrified = '\n';
break;
case 'r':
mogrified = '\r';
break;
case 't':
mogrified = '\t';
break;
}
}
if(mogrified != null) {
result.append(mogrified);
escaped = false;
} else {
setCursor(getCursor() - 1);

View file

@ -214,9 +214,10 @@ public class StringReaderTest {
@Test
public void readQuotedString_withEscapedEscapes() throws Exception {
final StringReader reader = new StringReader("\"\\\\o/\"");
assertThat(reader.readQuotedString(), equalTo("\\o/"));
assertThat(reader.getRead(), equalTo("\"\\\\o/\""));
final String original = "\"\\n\\\\o/\"";
final StringReader reader = new StringReader(original);
assertThat(reader.readQuotedString(), equalTo("\n\\o/"));
assertThat(reader.getRead(), equalTo(original));
assertThat(reader.getRemaining(), equalTo(""));
}
@ -585,4 +586,4 @@ public class StringReaderTest {
assertThat(ex.getCursor(), is(0));
}
}
}
}