Skip to content

Commit 17d5fee

Browse files
authored
Base violation marker positions on bytes to avoid range conversions (#6588)
1 parent ae7ba72 commit 17d5fee

1 file changed

Lines changed: 6 additions & 27 deletions

File tree

Tests/TestHelpers/TestHelpers.swift

Lines changed: 6 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import Foundation
22
import SourceKittenFramework
3+
import SwiftSyntax
34
import XCTest
45

56
import SwiftLintFramework
@@ -198,18 +199,18 @@ public extension Collection where Element == Example {
198199
}
199200
}
200201

201-
private func cleanedContentsAndMarkerOffsets(from contents: String) -> (String, [Int]) {
202-
var markerOffsets = [Int]()
202+
private func cleanedContentsAndMarkerOffsets(from contents: String) -> (String, [AbsolutePosition]) {
203+
var markerOffsets = [AbsolutePosition]()
203204
var cleanedContents = ""
204205
cleanedContents.reserveCapacity(contents.count)
205206

206-
var offset = 0
207+
var offset = AbsolutePosition(utf8Offset: 0)
207208
for char in contents {
208209
if char == violationMarkerChar {
209210
markerOffsets.append(offset)
210211
} else {
211212
cleanedContents.append(char)
212-
offset += 1
213+
offset = offset.advanced(by: char.utf8.count)
213214
}
214215
}
215216

@@ -575,11 +576,7 @@ public extension XCTestCase {
575576
}
576577
let file = SwiftLintFile.testFile(withContents: cleanTrigger)
577578

578-
// Convert grapheme cluster indices to UTF-16 offsets
579-
let expectedLocations = markerOffsets.map { graphemeOffset -> Location in
580-
let utf16Offset = cleanTrigger.utf16OffsetFrom(graphemeOffset: graphemeOffset)
581-
return Location(file: file, characterOffset: utf16Offset)
582-
}
579+
let expectedLocations = markerOffsets.map { Location(file: file, position: $0) }
583580

584581
// Assert violations on unexpected location
585582
let violationsAtUnexpectedLocation = triggerViolations
@@ -672,21 +669,3 @@ package extension [any Rule] {
672669
first(where: { $0 is CustomRules }) as? CustomRules
673670
}
674671
}
675-
676-
private extension String {
677-
/// Converts a grapheme cluster offset to a UTF-16 code unit offset
678-
func utf16OffsetFrom(graphemeOffset: Int) -> Int {
679-
var currentGraphemeIndex = 0
680-
var utf16Offset = 0
681-
682-
for char in self {
683-
if currentGraphemeIndex == graphemeOffset {
684-
return utf16Offset
685-
}
686-
utf16Offset += char.utf16.count
687-
currentGraphemeIndex += 1
688-
}
689-
690-
return utf16Offset
691-
}
692-
}

0 commit comments

Comments
 (0)