|
| 1 | +import Foundation |
| 2 | + |
| 3 | +/** |
| 4 | + * Prints a string as a GraphQL StringValue literal. Replaces control characters |
| 5 | + * and excluded characters (" U+0022 and \\ U+005C) with escape sequences. |
| 6 | + */ |
| 7 | +func printString(_ str: String) -> String { |
| 8 | + let replacedString = str.unicodeScalars.map { char in |
| 9 | + if |
| 10 | + char.value <= 0x1F || // \x00-\x1f |
| 11 | + char.value == 0x22 || // \x22 |
| 12 | + char.value == 0x5C || // \x5c |
| 13 | + (char.value >= 0x7F && char.value <= 0x9F) // \x7f-\x9f |
| 14 | + { |
| 15 | + return escapeSequences[Int(char.value)] |
| 16 | + } |
| 17 | + return String(char) |
| 18 | + }.joined() |
| 19 | + return "\"\(replacedString)\"" |
| 20 | +} |
| 21 | + |
| 22 | +let escapeSequences = [ |
| 23 | + "\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", |
| 24 | + "\\b", "\\t", "\\n", "\\u000B", "\\f", "\\r", "\\u000E", "\\u000F", |
| 25 | + "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", |
| 26 | + "\\u0018", "\\u0019", "\\u001A", "\\u001B", "\\u001C", "\\u001D", "\\u001E", "\\u001F", |
| 27 | + "", "", "\\\"", "", "", "", "", "", |
| 28 | + "", "", "", "", "", "", "", "", // 2F |
| 29 | + "", "", "", "", "", "", "", "", |
| 30 | + "", "", "", "", "", "", "", "", // 3F |
| 31 | + "", "", "", "", "", "", "", "", |
| 32 | + "", "", "", "", "", "", "", "", // 4F |
| 33 | + "", "", "", "", "", "", "", "", |
| 34 | + "", "", "", "", "\\\\", "", "", "", // 5F |
| 35 | + "", "", "", "", "", "", "", "", |
| 36 | + "", "", "", "", "", "", "", "", // 6F |
| 37 | + "", "", "", "", "", "", "", "", |
| 38 | + "", "", "", "", "", "", "", "\\u007F", |
| 39 | + "\\u0080", "\\u0081", "\\u0082", "\\u0083", "\\u0084", "\\u0085", "\\u0086", "\\u0087", |
| 40 | + "\\u0088", "\\u0089", "\\u008A", "\\u008B", "\\u008C", "\\u008D", "\\u008E", "\\u008F", |
| 41 | + "\\u0090", "\\u0091", "\\u0092", "\\u0093", "\\u0094", "\\u0095", "\\u0096", "\\u0097", |
| 42 | + "\\u0098", "\\u0099", "\\u009A", "\\u009B", "\\u009C", "\\u009D", "\\u009E", "\\u009F", |
| 43 | +] |
0 commit comments