Scoop API

scoop:scoop.json:0.1.0

src/parse_string.scoop

Selected production source · src/parse_string.scoop

1package scoop.json
3internal fun hexDigit(character: Char, parser: JsonParser, path: String): Int {
4 if (character >= '0' && character <= '9') { return character.code - 48 }
5 if (character >= 'a' && character <= 'f') { return character.code - 87 }
6 if (character >= 'A' && character <= 'F') { return character.code - 55 }
7 throw parser.error(path, "expected a hexadecimal digit")
8}
10internal fun readHexQuad(parser: JsonParser, path: String): Int {
11 var result: Int = 0
12 var count: Int = 0
13 while (count < 4) {
14 result = result * 16 + hexDigit(parser.take(path), parser, path)
15 count = count + 1
16 }
17 return result
20internal fun readUnicodeEscape(parser: JsonParser, path: String): Char {
21 val first = readHexQuad(parser, path)
22 if (first >= 55296 && first <= 56319) {
23 parser.expect('\\', path)
24 parser.expect('u', path)
25 val second = readHexQuad(parser, path)
26 if (second < 56320 || second > 57343) {
27 throw parser.error(path, "expected a low surrogate")
28 }
29 return (65536 + (first - 55296) * 1024 + second - 56320).toChar()
30 }
31 if (first >= 56320 && first <= 57343) {
32 throw parser.error(path, "isolated low surrogate")
33 }
34 return first.toChar()
37internal fun readJsonString(parser: JsonParser, path: String): String {
38 parser.expect('"', path)
39 val result = StringBuilder()
40 while (parser.peek() != None) {
41 val character = parser.take(path)
42 if (character == '"') { return result.toString() }
43 if (character.code < 32) { throw parser.error(path, "unescaped control character") }
44 if (character == '\\') {
45 val escaped = parser.take(path)
46 when (escaped) {
47 case '"' -> { result.append('"') }
48 case '\\' -> { result.append('\\') }
49 case '/' -> { result.append('/') }
50 case 'b' -> { result.append('\u{8}') }
51 case 'f' -> { result.append('\u{c}') }
52 case 'n' -> { result.append('\n') }
53 case 'r' -> { result.append('\r') }
54 case 't' -> { result.append('\t') }
55 case 'u' -> { result.append(readUnicodeEscape(parser, path)) }
56 else -> { throw parser.error(path, "invalid string escape") }
57 }
58 } else { result.append(character) }
59 }
60 throw parser.error(path, "unterminated string")