From Apple's documentation:
Return Value A range describing the intersection of range1 and range2—that is, a range containing the indices that exist in both ranges.
Discussion If the returned range’s length field is 0, then the two ranges don’t intersect, and the value of the location field is undefined.
Okay, so let's say I have two ranges:
(lldb) p rangeOne
(NSRange) $3 = location=11, length=4
(lldb) p rangeTwo
(NSRange) $4 = location=14, length=0
And I calculate the intersection:
NSRange intersection = NSIntersectionRange(rangeOne, rangeTwo);
The result is:
(lldb) p intersection
(NSRange) $5 = location=14, length=0
What am I supposed to do with that? Length is zero, so the location is undefined? But in this case, the result is what I would expect; can I trust it? Is calculating the intersection of ranges where one range has a length of zero invalid?
I'd interpret that to mean that when
length
is 0, the ranges are not intersecting.Agreed with Tommy – they could have set it to NSNotFound – but instead they say the result is undefined. Furthermore, I agree that the location of a zero-length range is meaningless. The position in
rangeTwo
doesn't mean anything. Nor canrangeTwo
intersect with anything.You're right. You have to go with the documentation. The value is unusable. What a hole in the API!
As a quick thought, similar to Tommy's answer, here is a version with a stronger promise
The returned value is the correct answer. You have a range starting at a location of 14 which has a length of 0. A length of 0 does not mean the range is invalid.Here is an example using a length of 0.
results in
In this example, the length of 0 means the location is an insertion point and is not removing any of the existing string.
If you need a different answer, then calculate it yourself.
That's not a bug.. Your range two has 0 length so it is same as none existent... So when you do NSRange intersection = NSIntersectionRange(rangeOne, rangeTwo), of course intersection has length of 0, because you cannot intersect with something that has 0 length!!
"What am I supposed to do with that?"
NSIntersectionRange is doing its job as intended. If it does not meet your needs, you can write your own.
"Is calculating the intersection of ranges where one range has a length of zero invalid?"
It is not invalid but is it obvious: they don't because they can't.
I don't think
NSIntersectionRange
exposes that information, which is absurd as they could have setlocation
toNSNotFound
or something. So you'd have to do it manually. I doubt you need the exposition, but e.g.:(probably with a more appropriate method name prefix than
NS
)