Skip to content

Commit

Permalink
Merge pull request #570 from jpsim/fix-crash-location=from-byte-offset
Browse files Browse the repository at this point in the history
Fix crash in NSString.location(fromByteOffset:)
  • Loading branch information
jpsim authored Nov 27, 2018
2 parents b039da6 + e6eac40 commit 59e8dea
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@

##### Bug Fixes

* None.
* Fix crash in `NSString.location(fromByteOffset:)` when using unicode
characters.
[JP Simard](https://github.com/jpsim)
[realm/SwiftLint#2276](https://github.com/realm/SwiftLint/issues/2276)

## 0.21.3

Expand Down
5 changes: 2 additions & 3 deletions Source/SourceKittenFramework/String+SourceKitten.swift
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,8 @@ extension NSString {
return NSMaxRange(line.range)
}
let utf8View = line.content.utf8
let endUTF16index = utf8View.index(utf8View.startIndex, offsetBy: diff, limitedBy: utf8View.endIndex)!
.samePosition(in: line.content.utf16)!
let utf16Diff = line.content.utf16.distance(from: line.content.utf16.startIndex, to: endUTF16index)
let endUTF8Index = utf8View.index(utf8View.startIndex, offsetBy: diff, limitedBy: utf8View.endIndex)!
let utf16Diff = line.content.utf16.distance(from: line.content.utf16.startIndex, to: endUTF8Index)
return line.range.location + utf16Diff
}

Expand Down
21 changes: 21 additions & 0 deletions Tests/SourceKittenFrameworkTests/StringTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,26 @@ class StringTests: XCTestCase {
XCTAssertEqual(string.bridge().lineAndCharacter(forByteOffset: 17), (1, 18))
}

func testByteRangeToNSRange() {
let string = """
enum Foo {
case one
case two
}
func bar(foo: Foo) -> String {
let some = "ru_RU"
switch foo {
case .one:
return "\\(some) один"
default:
return "\\(some) два"
}
}
"""
XCTAssertEqual(string.bridge().byteRangeToNSRange(start: 115, length: 42), NSRange(location: 115, length: 38))
}

func testLineAndCharacterForCharacterOffset() {
let string = "" +
"func foo() {\n" + // 12+1 characters, start=0
Expand Down Expand Up @@ -230,6 +250,7 @@ extension StringTests {
("testSubstringLinesWithByteRange", testSubstringLinesWithByteRange),
("testLineRangeWithByteRange", testLineRangeWithByteRange),
("testLineAndCharacterForByteOffset", testLineAndCharacterForByteOffset),
("testByteRangeToNSRange", testByteRangeToNSRange),
("testLineAndCharacterForCharacterOffset", testLineAndCharacterForCharacterOffset)
]
}
Expand Down

0 comments on commit 59e8dea

Please sign in to comment.