Skip to content

Commit 08ee342

Browse files
authored
[Foundation] searching in slices should index relative to the slice (#14852)
1 parent 7ebaa8a commit 08ee342

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

stdlib/public/SDK/Foundation/Data.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1428,17 +1428,17 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
14281428
let nsRange : NSRange
14291429
if let r = range {
14301430
_validateRange(r)
1431-
nsRange = NSMakeRange(r.lowerBound, r.upperBound - r.lowerBound)
1431+
nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound)
14321432
} else {
1433-
nsRange = NSMakeRange(0, _backing.length)
1433+
nsRange = NSRange(location: 0, length: count)
14341434
}
14351435
let result = _backing.withInteriorPointerReference(_sliceRange) {
14361436
$0.range(of: dataToFind, options: options, in: nsRange)
14371437
}
14381438
if result.location == NSNotFound {
14391439
return nil
14401440
}
1441-
return result.location..<(result.location + result.length)
1441+
return (result.location + startIndex)..<((result.location + startIndex) + result.length)
14421442
}
14431443

14441444
/// Enumerate the contents of the data.

test/stdlib/TestData.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3741,6 +3741,14 @@ class TestData : TestDataSuper {
37413741

37423742
expectEqual(Data(bytes: [4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]), t)
37433743
}
3744+
3745+
func test_rangeOfSlice() {
3746+
let data = "FooBar".data(using: .ascii)!
3747+
let slice = data[3...] // Bar
3748+
3749+
let range = slice.range(of: "a".data(using: .ascii)!)
3750+
expectEqual(range, Range<Data.Index>(4..<5))
3751+
}
37443752
}
37453753

37463754
#if !FOUNDATION_XCTEST
@@ -4058,6 +4066,7 @@ DataTests.test("test_validateMutation_slice_mutableBacking_withUnsafeMutableByte
40584066
DataTests.test("test_validateMutation_slice_customBacking_withUnsafeMutableBytes_lengthLessThanLowerBound") { TestData().test_validateMutation_slice_customBacking_withUnsafeMutableBytes_lengthLessThanLowerBound() }
40594067
DataTests.test("test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound") { TestData().test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound() }
40604068
DataTests.test("test_byte_access_of_discontiguousData") { TestData().test_byte_access_of_discontiguousData() }
4069+
DataTests.test("test_rangeOfSlice") { TestData().test_rangeOfSlice() }
40614070

40624071
// XCTest does not have a crash detection, whereas lit does
40634072
DataTests.test("bounding failure subdata") {

0 commit comments

Comments
 (0)