Skip to content

Commit e073ade

Browse files
feat: Adds isPrintableAsBlockString
1 parent 761b0b0 commit e073ade

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Sources/GraphQL/Language/BlockString.swift

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,70 @@
11
import Foundation
22

3+
func isPrintableAsBlockString(_ value: String) -> Bool {
4+
if value == "" {
5+
return true // empty string is printable
6+
}
7+
8+
var isEmptyLine = true
9+
var hasIndent = false
10+
var hasCommonIndent = true
11+
var seenNonEmptyLine = false
12+
13+
let scalars = Array(value.unicodeScalars)
14+
for i in 0 ..< scalars.count {
15+
switch scalars[i].value {
16+
case 0x0000,
17+
0x0001,
18+
0x0002,
19+
0x0003,
20+
0x0004,
21+
0x0005,
22+
0x0006,
23+
0x0007,
24+
0x0008,
25+
0x000B,
26+
0x000C,
27+
0x000E,
28+
0x000F:
29+
return false // Has non-printable characters
30+
31+
case 0x000D: // \r
32+
return false // Has \r or \r\n which will be replaced as \n
33+
34+
case 10: // \n
35+
if isEmptyLine && !seenNonEmptyLine {
36+
return false // Has leading new line
37+
}
38+
seenNonEmptyLine = true
39+
40+
isEmptyLine = true
41+
hasIndent = false
42+
43+
case 9, // \t
44+
32: // <space>
45+
if !hasIndent {
46+
hasIndent = isEmptyLine
47+
}
48+
49+
default:
50+
if hasCommonIndent {
51+
hasCommonIndent = hasIndent
52+
}
53+
isEmptyLine = false
54+
}
55+
}
56+
57+
if isEmptyLine {
58+
return false // Has trailing empty lines
59+
}
60+
61+
if hasCommonIndent && seenNonEmptyLine {
62+
return false // Has internal indent
63+
}
64+
65+
return true
66+
}
67+
368
/**
469
* Print a block string in the indented block form by adding a leading and
570
* trailing blank line. However, if a block string starts with whitespace and is

0 commit comments

Comments
 (0)