Skip to content

[Foundation] Add initializers for NSRange<-->Range #9709

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 18, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 53 additions & 11 deletions stdlib/public/SDK/Foundation/NSRange.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,18 +105,59 @@ extension NSRange {
//===----------------------------------------------------------------------===//

extension NSRange {
public init(_ x: Range<Int>) {
location = x.lowerBound
length = x.count
}
public init<R: RangeExpression>(_ rangeExpression: R)
where R.Bound: FixedWidthInteger, R.Bound.Stride : SignedInteger {
let range = rangeExpression.relative(to: 0..<R.Bound.max)
let start: Int = numericCast(range.lowerBound)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so what happens here when you have a 32 bit host and the passed in range is a UInt64 that exceeds Int32.max?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would trap – expectedly. To construct an NSRange you need an Int. The alternative is we only allow construction from RangeExpressions of Int and push the casting onto the caller. I'm kind of ambivalent which.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eh as is seems fine; I just wanted to make sure it wasn't some funky bit truncation. Trap seems quite reasonable.

let end: Int = numericCast(range.upperBound)
self = NSRange(location: start, length: end - start)
}

public init<R: RangeExpression, S: StringProtocol>(_ rangeExpression: R, in string: S)
where R.Bound == String.Index, S.Index == String.Index {
let range = rangeExpression.relative(to: string)
let start = range.lowerBound.samePosition(in: string.utf16)
let end = range.upperBound.samePosition(in: string.utf16)
let location = string.utf16.distance(from: string.utf16.startIndex, to: start)
let length = string.utf16.distance(from: start, to: end)
self = NSRange(location: location, length: length)
}

// FIXME(ABI)#75 (Conditional Conformance): this API should be an extension on Range.
// Can't express it now because the compiler does not support conditional
// extensions with type equality constraints.
public func toRange() -> Range<Int>? {
if location == NSNotFound { return nil }
return location..<(location+length)
}
@available(swift, deprecated: 4, renamed: "Range.init(_:)")
public func toRange() -> Range<Int>? {
if location == NSNotFound { return nil }
return location..<(location+length)
}
}

extension Range where Bound: BinaryInteger {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't we also do the other range types here too?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, probably not. We don't generally encourage people to create the other range types without using the operators. Range is the currency type.

public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (numericCast(range.lowerBound), numericCast(range.upperBound)))
}
}

// This additional overload will mean Range.init(_:) defaults to Range<Int> when
// no additional type context is provided:
extension Range where Bound == Int {
public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (range.lowerBound, range.upperBound))
}
}

extension Range where Bound == String.Index {
public init?(_ range: NSRange, in string: String) {
let u = string.utf16
guard range.location != NSNotFound,
let start = u.index(u.startIndex, offsetBy: range.location, limitedBy: u.endIndex),
let end = u.index(u.startIndex, offsetBy: range.location + range.length, limitedBy: u.endIndex),
let lowerBound = String.Index(start, within: string),
let upperBound = String.Index(end, within: string)
else { return nil }

self = lowerBound..<upperBound
}
}

extension NSRange : CustomReflectable {
Expand All @@ -130,3 +171,4 @@ extension NSRange : CustomPlaygroundQuickLookable {
return .range(Int64(location), Int64(length))
}
}

44 changes: 44 additions & 0 deletions test/Interpreter/SDK/Foundation_test.swift
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,50 @@ FoundationTestSuite.test("NSRange") {
expectEqual("{1, 4}", String(NSStringFromRange(nsRange)))
}

FoundationTestSuite.test("RangeConversion") {
let i: Int8 = 10
let j: Int8 = 20

let nsrFromInt8 = NSRange(i..<j)
expectEqual(nsrFromInt8, NSRange(location: 10, length: 10))

var r = Range(nsrFromInt8)
expectNotNil(r)
expectEqual(r!.lowerBound, 10)
expectEqual(r!.upperBound, 20)
expectType(Optional<Range<Int>>.self, &r)

var r8 = Range<Int8>(nsrFromInt8)
expectNotNil(r8 != nil)
expectEqual(r8?.lowerBound, 10)
expectEqual(r8?.upperBound, 20)
expectType(Optional<Range<Int8>>.self, &r8)

var nsrFromPartial = NSRange(..<5)
expectEqual("{0, 5}", NSStringFromRange(nsrFromPartial))

let s = "Hello, 🌎!"
let b = s.index(of: ",")!
let e = s.index(of: "!")!
let nsr = NSRange(b..<e, in: s)
expectEqual(nsr.location, 5)
expectEqual(nsr.length, 4)
let rs = Range(nsr, in: s)!
expectEqual(s[rs], ", 🌎")

let nsrTo = NSRange(..<b, in: s)
expectEqual(nsrTo.location, 0)
expectEqual(nsrTo.length, 5)
let nsrFrom = NSRange(b..., in: s)
expectEqual(nsrFrom.location,5)
expectEqual(nsrFrom.length, 5)

// FIXME: enable once indices conform to RangeExpression
// let nsrFull = NSRange(s.indices, in: s)
// expectEqual(nsrFull.location, 0)
// expectEqual(nsrFull.length, 10)
}

//===----------------------------------------------------------------------===//
// URLs
//===----------------------------------------------------------------------===//
Expand Down