Skip to content

Commit 6e64b26

Browse files
authored
Merge pull request #913 from bnbarham/pretty-print-perf
Optimize pretty printing performance
2 parents e82cdd7 + 3ca204b commit 6e64b26

File tree

2 files changed

+48
-11
lines changed

2 files changed

+48
-11
lines changed

Sources/SwiftFormat/PrettyPrint/PrettyPrintBuffer.swift

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -119,18 +119,21 @@ struct PrettyPrintBuffer {
119119
consecutiveNewlineCount = 0
120120
pendingSpaces = 0
121121

122-
// In case of comments, we may get a multi-line string.
123-
// To account for that case, we need to correct the lineNumber count.
124-
// The new column is only the position within the last line.
125-
let lines = text.split(separator: "\n")
126-
lineNumber += lines.count - 1
127-
if lines.count > 1 {
128-
// in case we have inserted new lines, we need to reset the column
129-
column = lines.last?.count ?? 0
122+
// In case of comments, we may get a multi-line string. To account for that case, we need to correct the
123+
// `lineNumber` count. The new `column` is the position within the last line.
124+
125+
var lastNewlineIndex: String.Index? = nil
126+
for i in text.utf8.indices {
127+
if text.utf8[i] == UInt8(ascii: "\n") {
128+
lastNewlineIndex = i
129+
lineNumber += 1
130+
}
131+
}
132+
133+
if let lastNewlineIndex {
134+
column = text.distance(from: text.utf8.index(after: lastNewlineIndex), to: text.endIndex)
130135
} else {
131-
// in case it is an end of line comment or a single line comment,
132-
// we just add to the current column
133-
column += lines.last?.count ?? 0
136+
column += text.count
134137
}
135138
}
136139

Tests/SwiftFormatTests/PrettyPrint/LineNumbersTests.swift

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,38 @@ final class LineNumbersTests: PrettyPrintTestCase {
8181
]
8282
)
8383
}
84+
85+
func testCharacterVsCodepoint() {
86+
let input =
87+
"""
88+
let fo = 1 // 🤥
89+
90+
"""
91+
92+
assertPrettyPrintEqual(
93+
input: input,
94+
expected: input,
95+
linelength: 16,
96+
whitespaceOnly: true,
97+
findings: []
98+
)
99+
}
100+
101+
func testCharacterVsCodepointMultiline() {
102+
let input =
103+
#"""
104+
/// This is a multiline
105+
/// comment that is in 🤥
106+
/// fact perfectly sized
107+
108+
"""#
109+
110+
assertPrettyPrintEqual(
111+
input: input,
112+
expected: input,
113+
linelength: 25,
114+
whitespaceOnly: true,
115+
findings: []
116+
)
117+
}
84118
}

0 commit comments

Comments
 (0)