Skip to content

Commit 26d4ea1

Browse files
authored
[Foundation] searching in slices should index relative to the slice (swiftlang#14851)
1 parent 3214627 commit 26d4ea1

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
@@ -1425,17 +1425,17 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
14251425
let nsRange : NSRange
14261426
if let r = range {
14271427
_validateRange(r)
1428-
nsRange = NSRange(location: r.lowerBound, length: r.upperBound - r.lowerBound)
1428+
nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound)
14291429
} else {
1430-
nsRange = NSRange(location: 0, length: _backing.length)
1430+
nsRange = NSRange(location: 0, length: count)
14311431
}
14321432
let result = _backing.withInteriorPointerReference(_sliceRange) {
14331433
$0.range(of: dataToFind, options: options, in: nsRange)
14341434
}
14351435
if result.location == NSNotFound {
14361436
return nil
14371437
}
1438-
return result.location..<(result.location + result.length)
1438+
return (result.location + startIndex)..<((result.location + startIndex) + result.length)
14391439
}
14401440

14411441
/// 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)