Skip to content

Commit a3d9776

Browse files
authored
Merge pull request #78291 from hamishknight/minor-xcodegen-optimization
[xcodegen] Avoid an intermediate String
2 parents ffff34b + 1667925 commit a3d9776

File tree

1 file changed

+18
-24
lines changed

1 file changed

+18
-24
lines changed

utils/swift-xcodegen/Sources/Xcodeproj/PropertyList.swift

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -51,33 +51,12 @@ extension PropertyList {
5151
writePlistRepresentation(to: &writer)
5252
return Data(writer.bytes)
5353
}
54-
55-
/// Escapes the string for plist.
56-
/// Finds the instances of quote (") and backward slash (\) and prepends
57-
/// the escape character backward slash (\).
58-
static func escape(string: String) -> String {
59-
func needsEscape(_ char: UInt8) -> Bool {
60-
return char == UInt8(ascii: "\\") || char == UInt8(ascii: "\"")
61-
}
62-
63-
guard let pos = string.utf8.firstIndex(where: needsEscape) else {
64-
return string
65-
}
66-
var newString = String(string[..<pos])
67-
for char in string.utf8[pos...] {
68-
if needsEscape(char) {
69-
newString += "\\"
70-
}
71-
newString += String(UnicodeScalar(char))
72-
}
73-
return newString
74-
}
7554
}
7655

7756
fileprivate extension PropertyList {
7857
struct UTF8Writer {
79-
var level: Int = 0
80-
var bytes: [UInt8] = []
58+
private(set) var level: Int = 0
59+
private(set) var bytes: [UInt8] = []
8160
init() {
8261
self += "// !$*UTF8*$!\n"
8362
}
@@ -88,6 +67,10 @@ fileprivate extension PropertyList {
8867
level -= 1
8968
}
9069

70+
mutating func append(_ byte: UInt8) {
71+
bytes.append(byte)
72+
}
73+
9174
static func += (writer: inout UTF8Writer, str: StaticString) {
9275
str.withUTF8Buffer { utf8 in
9376
writer.bytes += utf8
@@ -104,6 +87,17 @@ fileprivate extension PropertyList {
10487
self += " "
10588
}
10689
}
90+
91+
/// Appends the given string, with instances of quote (") and backward slash
92+
/// (\) characters escaped with a backslash.
93+
mutating func appendEscaped(_ string: String) {
94+
for char in string.utf8 {
95+
if char == UInt8(ascii: "\\") || char == UInt8(ascii: "\"") {
96+
append(UInt8(ascii: "\\"))
97+
}
98+
append(char)
99+
}
100+
}
107101
}
108102

109103
/// Private function to generate OPENSTEP-style plist representation.
@@ -116,7 +110,7 @@ fileprivate extension PropertyList {
116110

117111
case .string(let string):
118112
writer += "\""
119-
writer += PropertyList.escape(string: string)
113+
writer.appendEscaped(string)
120114
writer += "\""
121115

122116
case .array(let array):

0 commit comments

Comments
 (0)