Skip to content

Commit e70139d

Browse files
committed
Add escape quote utility method.
1 parent ab93910 commit e70139d

File tree

4 files changed

+45
-41
lines changed

4 files changed

+45
-41
lines changed

.github/workflows/gradle-nightly.yml

Lines changed: 0 additions & 39 deletions
This file was deleted.

.github/workflows/gradle.yml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@ on:
55
branches:
66
- master
77
pull_request:
8-
schedule:
9-
- cron: '0 0 * * 1,4'
108

119
jobs:
1210
check:

systems.comodal.json_iterator/src/main/java/systems/comodal/jsoniter/JIUtil.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,36 @@ public static long compileReplacePattern(final byte byteToFind) {
3838
| (pattern << 48)
3939
| (pattern << 56);
4040
}
41+
42+
public static String escapeQuotes(final String str) {
43+
final char[] chars = str.toCharArray();
44+
final char[] escaped = new char[chars.length << 1];
45+
char c;
46+
for (int escapes = 0, from = 0, dest = 0, to = 0; ; to++) {
47+
if (to == chars.length) {
48+
if (from == 0) {
49+
return str;
50+
} else {
51+
final int len = to - from;
52+
System.arraycopy(chars, from, escaped, dest, len);
53+
dest += len;
54+
return new String(escaped, 0, dest);
55+
}
56+
} else {
57+
c = chars[to];
58+
if (c == '\\') {
59+
escapes++;
60+
} else if (c == '"' && (escapes & 1) == 0) {
61+
final int len = to - from;
62+
System.arraycopy(chars, from, escaped, dest, len);
63+
dest += len;
64+
escaped[dest++] = '\\';
65+
from = to;
66+
escapes = 0;
67+
} else {
68+
escapes = 0;
69+
}
70+
}
71+
}
72+
}
4173
}

systems.comodal.json_iterator/src/test/java/systems/comodal/jsoniter/TestString.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,19 @@ void test_ascii_string(final JsonIteratorFactory factory) {
3131
assertArrayEquals(world, ji.decodeBase64String());
3232
}
3333

34+
@Test
35+
void testEscapeQuotes() {
36+
var nestedJson = """
37+
{"hello": "world"}""";
38+
assertEquals("""
39+
{\\"hello\\": \\"world\\"}""", JIUtil.escapeQuotes(nestedJson));
40+
41+
nestedJson = """
42+
{"hello": "\\"world\\""}""";
43+
assertEquals("""
44+
{\\"hello\\": \\"\\"world\\"\\"}""", JIUtil.escapeQuotes(nestedJson));
45+
}
46+
3447
@ParameterizedTest
3548
@MethodSource("systems.comodal.jsoniter.TestFactories#factories")
3649
void testRandomBase64Data(final JsonIteratorFactory factory) {

0 commit comments

Comments
 (0)