Skip to content

Commit 4960545

Browse files
committed
[Perf] Optimize 'SyntaxText.forEachLineLength(prefix:body:)'
Avoid incrementing 2 values per iteration.
1 parent 1d78444 commit 4960545

File tree

1 file changed

+17
-22
lines changed

1 file changed

+17
-22
lines changed

Sources/SwiftSyntax/SourceLocation.swift

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -522,38 +522,33 @@ fileprivate extension SyntaxText {
522522
prefix: SourceLength = .zero,
523523
body: (SourceLength) -> ()
524524
) -> SourceLength {
525-
// let startIndex = utf8.startIndex
526-
// let endIndex = utf8.endIndex
527525
var curIdx = startIndex
528-
var lineLength = prefix
529-
let advanceLengthByOne = { () -> () in
530-
lineLength += SourceLength(utf8Length: 1)
531-
curIdx = self.index(after: curIdx)
532-
}
526+
let endIdx = endIndex
527+
var lineStart = curIdx - prefix.utf8Length
533528

534-
while curIdx < endIndex {
535-
let char = self[curIdx]
536-
advanceLengthByOne()
529+
while curIdx != endIdx {
530+
let chr = self[curIdx]
531+
curIdx &+= 1
537532

538533
/// From https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#grammar_line-break
539534
/// * line-break → U+000A
540535
/// * line-break → U+000D
541536
/// * line-break → U+000D followed by U+000A
542-
let isNewline = { () -> Bool in
543-
if char == 10 { return true }
544-
if char == 13 {
545-
if curIdx < endIndex && self[curIdx] == 10 { advanceLengthByOne() }
546-
return true
537+
switch chr {
538+
case UInt8(ascii: "\n"):
539+
break
540+
case UInt8(ascii: "\r"):
541+
if curIdx != endIdx && self[curIdx] == UInt8(ascii: "\n") {
542+
curIdx &+= 1
547543
}
548-
return false
549-
}
550-
551-
if isNewline() {
552-
body(lineLength)
553-
lineLength = .zero
544+
break
545+
default:
546+
continue
554547
}
548+
body(SourceLength(utf8Length: curIdx - lineStart))
549+
lineStart = curIdx
555550
}
556-
return lineLength
551+
return SourceLength(utf8Length: curIdx - lineStart)
557552
}
558553

559554
func containsSwiftNewline() -> Bool {

0 commit comments

Comments
 (0)