Skip to content

Commit

Permalink
better bounds checking for replaceSubrange
Browse files Browse the repository at this point in the history
  • Loading branch information
mattmassicotte committed Dec 22, 2023
1 parent 803b61c commit b8b1cf9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
8 changes: 6 additions & 2 deletions Sources/RelativeCollections/RelativeArray.swift
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,6 @@ extension RelativeArray {
_ range: Range<Index>,
with newElements: Elements
) where WeightedValue == Elements.Element, Elements : Sequence {
let upperRecord = storage[range.upperBound]
let previousWeight = findDependency(for: range.lowerBound)

// create the new records and insert them
Expand All @@ -276,8 +275,13 @@ extension RelativeArray {

storage.replaceSubrange(range, with: newRecords)

if range.upperBound >= storage.endIndex {
return
}

// and now, we have to adjust everything past the insertion
let delta = configuration.subtract(upperRecord.dependency, dependency)
let upperDependency = storage[range.upperBound].dependency
let delta = configuration.subtract(upperDependency, dependency)

applyDelta(delta, after: range.upperBound)
}
Expand Down
17 changes: 17 additions & 0 deletions Tests/RelativeCollectionsTests/RelativeArrayTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -183,4 +183,21 @@ extension RelativeArrayTests {

XCTAssertEqual(array.map { $0.value }, expected)
}

func testRangeReplacementEntireArray() throws {
var array = TestArray()

for length in [1, 2, 3, 4] {
array.append(.init(weight: length))
}

array.replaceSubrange(0..<4, with: [
TestArray.WeightedValue(weight: 8),
TestArray.WeightedValue(weight: 9)
])

let expected = [8, 9]

XCTAssertEqual(array.map { $0.value }, expected)
}
}

0 comments on commit b8b1cf9

Please sign in to comment.