Repository navigation
Add ByteRange structure to prevent disambiguation when NSRange instead ByteRange is used - #639
Conversation
|
Thanks for your continued work on this! I hope you don't mind I pushed a few changes to your branch:
|
|
|
||
| * None. | ||
| * Replace all uses of `Int`/`Int64`/`NSRange` representing byte offsets | ||
| to use newly introduced `ByteOffset` and `ByteRange` values instead. |
| public func range(toEnd end: SourceLocation) -> NSRange { | ||
| return NSRange(location: Int(offset), length: Int(end.offset - offset)) | ||
| public func range(toEnd end: SourceLocation) -> ByteRange { | ||
| return ByteRange(location: ByteCount(Int(offset)), length: ByteCount(Int(end.offset - offset))) |
There was a problem hiding this comment.
ByteCount(Int(offset)) -> ByteCount(offset)
ByteCount can be created with Int64
There was a problem hiding this comment.
offset in this case is an Int32 and I didn't think it was worth adding a new initializer for that.
| public func substringWithSourceRange(start: SourceLocation, end: SourceLocation) -> String? { | ||
| return substringWithByteRange(start: Int(start.offset), length: Int(end.offset - start.offset)) | ||
| let byteRange = ByteRange(location: ByteCount(Int(start.offset)), | ||
| length: ByteCount(Int(end.offset - start.offset))) |
There was a problem hiding this comment.
here as well, we can use ByteCount(Int(start.offset)) -> ByteCount(start.offset)
|
Few minors with naming and unneeded casting. |
|
|
||
| - returns: An equivalent `NSRange`. | ||
| */ | ||
| public func byteRangeToNSRange(start: Int, length: Int) -> NSRange? { |
There was a problem hiding this comment.
Also, it seems, that for backward better backward compatibility it is a good ideat o leave
byteRangeToNSRange(start: ByteCount, length: ByteCount)
There was a problem hiding this comment.
In this case, since the function name hasn't changed, the compiler error should be enough to let users know how to migrate their code.
New APIs were introduced in SourceKitten to allow for a more typesafe distinction between integers meaning NSString-based distances and byte-based distances. * jpsim/SourceKitten#639 * jpsim/SourceKitten#642 This PR migrates SwiftLint's use of those APIs.
What
Add ByteRange and ByteOffset wrapper to prevent disambiguation between NSRange (byte range ) and NSRange that represents ByteOffset range
Why
While working with ranges and tokens and string in
SwiftlintI realized that it is very easy to use one range when you need totally another one. And since NSRange represents both (byte and string,) and those aren't typed, the idea was to use a type that will reprensents values when youre' working in bytes and not-character/strings world.Pros
Cons
Breaks backward compatibility
Additional
All the data that comes from SourceKit can be wrapped with ByteOffset/ByteRange. We can choose at what level we're about to stop.
Alternatives
User ByteRange<ByteOffset, ByteOffset> types. This probably will do even better.