|
| 1 | +package io.github.json5.kotlin |
| 2 | + |
| 3 | +/** |
| 4 | + * Helper for handling escape sequences in JSON5 |
| 5 | + */ |
| 6 | +object EscapeHelper { |
| 7 | + /** |
| 8 | + * Processes a string that may contain escape sequences into their actual character representation |
| 9 | + * This is used for property names that contain escaped characters like \uXXXX |
| 10 | + */ |
| 11 | + fun processEscapedString(input: String): String { |
| 12 | + val result = StringBuilder() |
| 13 | + var i = 0 |
| 14 | + |
| 15 | + while (i < input.length) { |
| 16 | + if (input[i] == '\\' && i + 1 < input.length) { |
| 17 | + // Handle escape sequence |
| 18 | + when (val nextChar = input[i + 1]) { |
| 19 | + 'u' -> { |
| 20 | + // Unicode escape sequence \uXXXX |
| 21 | + if (i + 5 < input.length) { |
| 22 | + val hexCode = input.substring(i + 2, i + 6) |
| 23 | + try { |
| 24 | + val charCode = hexCode.toInt(16) |
| 25 | + result.append(charCode.toChar()) |
| 26 | + i += 6 |
| 27 | + } catch (e: NumberFormatException) { |
| 28 | + result.append('\\').append('u') |
| 29 | + i += 2 |
| 30 | + } |
| 31 | + } else { |
| 32 | + result.append('\\').append('u') |
| 33 | + i += 2 |
| 34 | + } |
| 35 | + } |
| 36 | + 'x' -> { |
| 37 | + // Hex escape sequence \xFF |
| 38 | + if (i + 3 < input.length) { |
| 39 | + val hexCode = input.substring(i + 2, i + 4) |
| 40 | + try { |
| 41 | + val charCode = hexCode.toInt(16) |
| 42 | + result.append(charCode.toChar()) |
| 43 | + i += 4 |
| 44 | + } catch (e: NumberFormatException) { |
| 45 | + result.append('\\').append('x') |
| 46 | + i += 2 |
| 47 | + } |
| 48 | + } else { |
| 49 | + result.append('\\').append('x') |
| 50 | + i += 2 |
| 51 | + } |
| 52 | + } |
| 53 | + 'b' -> { result.append('\b'); i += 2 } |
| 54 | + 'f' -> { result.append('\u000C'); i += 2 } |
| 55 | + 'n' -> { result.append('\n'); i += 2 } |
| 56 | + 'r' -> { result.append('\r'); i += 2 } |
| 57 | + 't' -> { result.append('\t'); i += 2 } |
| 58 | + 'v' -> { result.append('\u000B'); i += 2 } |
| 59 | + '0' -> { result.append('\u0000'); i += 2 } |
| 60 | + 'a' -> { result.append('\u0007'); i += 2 } // Bell character |
| 61 | + '\\' -> { result.append('\\'); i += 2 } |
| 62 | + '\'' -> { result.append('\''); i += 2 } |
| 63 | + '"' -> { result.append('"'); i += 2 } |
| 64 | + '\n' -> { i += 2 } // Line continuation - skip both characters |
| 65 | + '\r' -> { |
| 66 | + i += 2 |
| 67 | + // Skip following \n if present (for \r\n line endings) |
| 68 | + if (i < input.length && input[i] == '\n') { |
| 69 | + i++ |
| 70 | + } |
| 71 | + } |
| 72 | + '\u2028', '\u2029' -> { i += 2 } // Line/paragraph separator continuation |
| 73 | + else -> { |
| 74 | + result.append(nextChar) |
| 75 | + i += 2 |
| 76 | + } |
| 77 | + } |
| 78 | + } else { |
| 79 | + result.append(input[i]) |
| 80 | + i++ |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + return result.toString() |
| 85 | + } |
| 86 | +} |
0 commit comments