From 35e4873c5c47aaabcd02de22316a260793eb9ebc Mon Sep 17 00:00:00 2001 From: Daryle Walker Date: Thu, 7 Oct 2021 22:47:48 -0400 Subject: [PATCH 1/8] Segregate the heap consistency testing code from the precondition code AFAIK, the previous code had no tests for itself, so the revised code doesn't either. --- .../PriorityQueueModule/Heap+Invariants.swift | 94 +++++++++++++------ 1 file changed, 64 insertions(+), 30 deletions(-) diff --git a/Sources/PriorityQueueModule/Heap+Invariants.swift b/Sources/PriorityQueueModule/Heap+Invariants.swift index 61999115..b1e0f54f 100644 --- a/Sources/PriorityQueueModule/Heap+Invariants.swift +++ b/Sources/PriorityQueueModule/Heap+Invariants.swift @@ -19,36 +19,16 @@ extension Heap { @inlinable @inline(never) internal func _checkInvariants() { - guard count > 1 else { return } - _checkInvariants(node: .root, min: nil, max: nil) - } - - @inlinable - internal func _checkInvariants(node: _Node, min: Element?, max: Element?) { - let value = _storage[node.offset] - if let min = min { - precondition(value >= min, - "Element \(value) at \(node) is less than min \(min)") - } - if let max = max { - precondition(value <= max, - "Element \(value) at \(node) is greater than max \(max)") - } - let left = node.leftChild() - let right = node.rightChild() - if node.isMinLevel { - if left.offset < count { - _checkInvariants(node: left, min: value, max: max) - } - if right.offset < count { - _checkInvariants(node: right, min: value, max: max) - } - } else { - if left.offset < count { - _checkInvariants(node: left, min: min, max: value) - } - if right.offset < count { - _checkInvariants(node: right, min: min, max: value) + if let (value, node, boundary) = _someHeapViolation() { + switch boundary { + case .lessThan(let min): + preconditionFailure( + "Element \(value) at \(node) is less than min \(min)" + ) + case .greaterThan(let max): + preconditionFailure( + "Element \(value) at \(node) is greater than max \(max)" + ) } } } @@ -57,4 +37,58 @@ extension Heap { @inline(__always) public func _checkInvariants() {} #endif // COLLECTIONS_INTERNAL_CHECKS + + /// Returns any violation of the min-max heap property. + @inlinable + internal func _someHeapViolation() + -> (value: Element, node: _Node, kind: _BoundaryViolation)? { + guard !_storage.isEmpty else { return nil } + + /// Returns any violation of the min-max heap property within the sub-heap + /// whose root is at the given node for the given value bounds. + func _someSubHeapViolation(node: _Node, min: Element?, max: Element?) + -> (value: Element, node: _Node, kind: _BoundaryViolation)? { + // Check the sub-heap's root's bounds. + let value = _storage[node.offset] + if let min = min, value < min { + return (value, node, .lessThan(min: min)) + } + if let max = max, value > max { + return (value, node, .greaterThan(max: max)) + } + + // Check the child sub-heaps. + var nextMin = min, nextMax = max + if node.isMinLevel { + nextMin = value + } else { + nextMax = value + } + + if case let leftNode = node.leftChild(), + leftNode.offset < count, + let result = _someSubHeapViolation(node: leftNode, min: nextMin, + max: nextMax) { + return result + } + if case let rightNode = node.rightChild(), + rightNode.offset < count, + let result = _someSubHeapViolation(node: rightNode, min: nextMin, + max: nextMax) { + return result + } + return nil + } + + return _someSubHeapViolation(node: .root, min: nil, max: nil) + } + + /// The manner the min-max heap property is violated. + @usableFromInline + internal enum _BoundaryViolation { + /// An element had a value less than the supplied lower bound. + case lessThan(min: Element) + /// An element had a value greater than the supplied upper bound. + case greaterThan(max: Element) + } } From c8e24c399c52e6f4165c07866fecbc7a9eab973b Mon Sep 17 00:00:00 2001 From: Daryle Walker Date: Sun, 10 Oct 2021 00:33:54 -0400 Subject: [PATCH 2/8] Add heap initializer that takes pre-arranged data --- Sources/PriorityQueueModule/Heap.swift | 36 ++++++++++++++++++++++++ Tests/PriorityQueueTests/HeapTests.swift | 27 ++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/Sources/PriorityQueueModule/Heap.swift b/Sources/PriorityQueueModule/Heap.swift index 1f6f3d83..16b10897 100644 --- a/Sources/PriorityQueueModule/Heap.swift +++ b/Sources/PriorityQueueModule/Heap.swift @@ -28,6 +28,42 @@ public struct Heap { @usableFromInline internal var _storage: ContiguousArray + /// Creates a heap from the given sequence, whether said sequence conforms to + /// an implicit data structure for a min-max heap or not. + /// + /// - Warning: This initializer is meant only as a shared implementation for + /// the public initializers. Those initializers need to either ensure the + /// input is already valid, condition the input to be valid afterwards, or + /// flag an error if the input is invalid. No other code should call this + /// initializer. + /// + /// - Precondition: `s` is finite. + /// + /// - Complexity: O(*n*), where *n* is the length of `s`. + @inlinable @inline(__always) + internal init(unchecked s: S) where S.Element == Element { + _storage = .init(s) + } + + /// Creates a heap from the given sequence, assuming said sequence is already + /// an implicit data structure for a binary min-max heap, failing otherwise. + /// + /// - Precondition: `storage` is finite. + /// + /// - Parameter storage: The elements of the heap. + /// - Postcondition: If the initializer doesn't fail: + /// `unordered.elementsEqual(s)`, where *s* is a sequence with the same + /// elements as pre-call `storage`. + /// + /// - Complexity: O(*n*), where *n* is the length of `storage`. + @inlinable + public init?(raw storage: S) where S.Element == Element { + self.init(unchecked: storage) + if _someHeapViolation() != nil { + return nil + } + } + /// Creates an empty heap. @inlinable public init() { diff --git a/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift index ca326858..72d4df3a 100644 --- a/Tests/PriorityQueueTests/HeapTests.swift +++ b/Tests/PriorityQueueTests/HeapTests.swift @@ -393,6 +393,33 @@ final class HeapTests: XCTestCase { XCTAssertEqual(heap.count, 20) } + func test_initializer_withChecking() { + XCTAssertNotNil(Heap(raw: EmptyCollection())) + XCTAssertNotNil(Heap(raw: CollectionOfOne("a"))) + XCTAssertNotNil(Heap(raw: repeatElement(2.0, count: 15))) + + // As these test non-identical multi-element sources, they may need to be + // updated whenever the internal storage format changes. + + let twoElements = Heap(raw: [1, 2]) + XCTAssertEqual(twoElements?.unordered, [1, 2]) + XCTAssertNil(Heap(raw: [2, 1])) + + let threeElements = Heap(raw: 1...3) + XCTAssertEqual(threeElements?.unordered, [1, 2, 3]) + + let otherThreeElements = Heap(raw: [1, 3, 2]) + XCTAssertEqual(otherThreeElements?.unordered, [1, 3, 2]) + XCTAssertNil(Heap(raw: [2, 1, 3])) + XCTAssertNil(Heap(raw: [2, 3, 1])) + XCTAssertNil(Heap(raw: [3, 1, 2])) + XCTAssertNil(Heap(raw: [3, 2, 1])) + + // Errors past the first two layers. + XCTAssertNil(Heap(raw: [1, 2, 3, 0, 2, 3, 2])) // 0 >= 1 is false + XCTAssertNil(Heap(raw: [1, 2, 3, 1, 4, 3, 1])) // 4 <= 2 is false + } + func test_initializer_fromArrayLiteral() { var heap: Heap = [1, 3, 5, 7, 9] XCTAssertEqual(heap.count, 5) From e55e516f114797d428ac7fe0d09f68ceddebaa8d Mon Sep 17 00:00:00 2001 From: Daryle Walker Date: Sun, 10 Oct 2021 20:15:40 -0400 Subject: [PATCH 3/8] Add methods that change the heap minimum or maximum element --- Sources/PriorityQueueModule/Heap.swift | 67 ++++++++++++++++++ Tests/PriorityQueueTests/HeapTests.swift | 87 ++++++++++++++++++++++++ 2 files changed, 154 insertions(+) diff --git a/Sources/PriorityQueueModule/Heap.swift b/Sources/PriorityQueueModule/Heap.swift index 16b10897..016743ad 100644 --- a/Sources/PriorityQueueModule/Heap.swift +++ b/Sources/PriorityQueueModule/Heap.swift @@ -205,6 +205,73 @@ extension Heap { public mutating func removeMax() -> Element { return popMax()! } + + /// Changes the element with the lowest priority to the given value, then + /// redetermines which element in the heap has the lowest priority. + /// + /// - Precondition: `!isEmpty`. + /// + /// - Parameter replacement: The value overwriting the current lowest-priority + /// element. + /// - Returns: The outgoing value of the overwritten element. + /// - Postcondition: When not equal, the multiplicity of the outgoing value + /// will decrease by one, while the multiplicity of the incoming value will + /// increase by one. If the altered element now has a priority that is + /// greater than any of the untargeted elements (if such exist), then + /// `min()` will point to a different element. + /// + /// - Complexity: O(log `count`) + @inlinable @discardableResult + public mutating func replaceMin(with replacement: Element) -> Element { + guard !isEmpty else { preconditionFailure("No element to replace") } + + var removed = replacement + _update { handle in + let minNode = _Node.root + handle.swapAt(minNode, with: &removed) + handle.trickleDownMin(minNode) + } + _checkInvariants() + return removed + } + + /// Changes the element with the highest priority to the given value, then + /// redetermines which element in the heap has the highest priority. + /// + /// - Precondition: `!isEmpty`. + /// + /// - Parameter replacement: The value overwriting the current + /// highest-priority element. + /// - Returns: The outgoing value of the overwritten element. + /// - Postcondition: When not equal, the multiplicity of the outgoing value + /// will decrease by one, while the multiplicity of the incoming value will + /// increase by one. If the altered element now has a priority that is less + /// than any of the untargeted elements (if such exist), then `max()` will + /// point to a different element. + /// + /// - Complexity: O(log `count`) + @inlinable @discardableResult + public mutating func replaceMax(with replacement: Element) -> Element { + guard !isEmpty else { preconditionFailure("No element to replace") } + + var removed = replacement + _update { handle in + switch handle.count { + case 1: + handle.swapAt(.root, with: &removed) + case 2: + handle.swapAt(.leftMax, with: &removed) + handle.bubbleUp(.leftMax) + default: + let maxNode = handle.maxValue(.leftMax, .rightMax) + handle.swapAt(maxNode, with: &removed) + handle.bubbleUp(maxNode) // This must happen first + handle.trickleDownMax(maxNode) // Either new element or dethroned min + } + } + _checkInvariants() + return removed + } } // MARK: - diff --git a/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift index 72d4df3a..2b2d9307 100644 --- a/Tests/PriorityQueueTests/HeapTests.swift +++ b/Tests/PriorityQueueTests/HeapTests.swift @@ -273,6 +273,93 @@ final class HeapTests: XCTestCase { XCTAssertEqual(heap.removeMax(), 1) } + func test_minimumReplacement() { + var heap = Heap(stride(from: 0, through: 27, by: 3).shuffled()) + XCTAssertEqual(Array(heap.ascending), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) + XCTAssertEqual(heap.min(), 0) + + // No change + heap.replaceMin(with: 0) + XCTAssertEqual(Array(heap.ascending), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) + XCTAssertEqual(heap.min(), 0) + + // Even smaller + heap.replaceMin(with: -1) + XCTAssertEqual(Array(heap.ascending), [-1, 3, 6, 9, 12, 15, 18, 21, 24, 27]) + XCTAssertEqual(heap.min(), -1) + + // Larger, but not enough to usurp + heap.replaceMin(with: 2) + XCTAssertEqual(Array(heap.ascending), [2, 3, 6, 9, 12, 15, 18, 21, 24, 27]) + XCTAssertEqual(heap.min(), 2) + + // Larger, moving another element to be the smallest + heap.replaceMin(with: 5) + XCTAssertEqual(Array(heap.ascending), [3, 5, 6, 9, 12, 15, 18, 21, 24, 27]) + XCTAssertEqual(heap.min(), 3) + } + + func test_maximumReplacement() { + var heap = Heap(stride(from: 0, through: 27, by: 3).shuffled()) + XCTAssertEqual(Array(heap.ascending), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) + XCTAssertEqual(heap.max(), 27) + + // No change + heap.replaceMax(with: 27) + XCTAssertEqual(Array(heap.ascending), [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]) + XCTAssertEqual(heap.max(), 27) + + // Even larger + heap.replaceMax(with: 28) + XCTAssertEqual(Array(heap.ascending), [0, 3, 6, 9, 12, 15, 18, 21, 24, 28]) + XCTAssertEqual(heap.max(), 28) + + // Smaller, but not enough to usurp + heap.replaceMax(with: 26) + XCTAssertEqual(Array(heap.ascending), [0, 3, 6, 9, 12, 15, 18, 21, 24, 26]) + XCTAssertEqual(heap.max(), 26) + + // Smaller, moving another element to be the largest + heap.replaceMax(with: 23) + XCTAssertEqual(Array(heap.ascending), [0, 3, 6, 9, 12, 15, 18, 21, 23, 24]) + XCTAssertEqual(heap.max(), 24) + + // Check the finer details. As these peek into the stored structure, they + // may need to be updated whenever the internal format changes. + var heap2 = Heap(raw: [1])! + XCTAssertEqual(heap2.max(), 1) + XCTAssertEqual(Array(heap2.unordered), [1]) + XCTAssertEqual(heap2.replaceMax(with: 2), 1) + XCTAssertEqual(heap2.max(), 2) + XCTAssertEqual(Array(heap2.unordered), [2]) + + heap2 = Heap(raw: [1, 2])! + XCTAssertEqual(heap2.max(), 2) + XCTAssertEqual(Array(heap2.unordered), [1, 2]) + XCTAssertEqual(heap2.replaceMax(with: 3), 2) + XCTAssertEqual(heap2.max(), 3) + XCTAssertEqual(Array(heap2.unordered), [1, 3]) + XCTAssertEqual(heap2.replaceMax(with: 0), 3) + XCTAssertEqual(heap2.max(), 1) + XCTAssertEqual(Array(heap2.unordered), [0, 1]) + + heap2 = Heap(raw: [5, 20, 31, 16, 8, 7, 18])! + XCTAssertEqual(heap2.max(), 31) + XCTAssertEqual(Array(heap2.unordered), [5, 20, 31, 16, 8, 7, 18]) + XCTAssertEqual(heap2.replaceMax(with: 29), 31) + XCTAssertEqual(Array(heap2.unordered), [5, 20, 29, 16, 8, 7, 18]) + XCTAssertEqual(heap2.max(), 29) + XCTAssertEqual(heap2.replaceMax(with: 19), 29) + XCTAssertEqual(Array(heap2.unordered), [5, 20, 19, 16, 8, 7, 18]) + XCTAssertEqual(heap2.max(), 20) + XCTAssertEqual(heap2.replaceMax(with: 15), 20) + XCTAssertEqual(Array(heap2.unordered), [5, 16, 19, 15, 8, 7, 18]) + XCTAssertEqual(heap2.max(), 19) + XCTAssertEqual(heap2.replaceMax(with: 4), 19) + XCTAssertEqual(Array(heap2.unordered), [4, 16, 18, 15, 8, 7, 5]) + XCTAssertEqual(heap2.max(), 18) + } + // MARK: - func test_min_struct() { From def8b84988413c5e71ada3cf3c2df887348d0ba0 Mon Sep 17 00:00:00 2001 From: Daryle Walker Date: Thu, 14 Oct 2021 01:27:07 -0400 Subject: [PATCH 4/8] Remove would-be common initializer --- Sources/PriorityQueueModule/Heap.swift | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/Sources/PriorityQueueModule/Heap.swift b/Sources/PriorityQueueModule/Heap.swift index 016743ad..0a7b79af 100644 --- a/Sources/PriorityQueueModule/Heap.swift +++ b/Sources/PriorityQueueModule/Heap.swift @@ -28,23 +28,6 @@ public struct Heap { @usableFromInline internal var _storage: ContiguousArray - /// Creates a heap from the given sequence, whether said sequence conforms to - /// an implicit data structure for a min-max heap or not. - /// - /// - Warning: This initializer is meant only as a shared implementation for - /// the public initializers. Those initializers need to either ensure the - /// input is already valid, condition the input to be valid afterwards, or - /// flag an error if the input is invalid. No other code should call this - /// initializer. - /// - /// - Precondition: `s` is finite. - /// - /// - Complexity: O(*n*), where *n* is the length of `s`. - @inlinable @inline(__always) - internal init(unchecked s: S) where S.Element == Element { - _storage = .init(s) - } - /// Creates a heap from the given sequence, assuming said sequence is already /// an implicit data structure for a binary min-max heap, failing otherwise. /// @@ -58,7 +41,7 @@ public struct Heap { /// - Complexity: O(*n*), where *n* is the length of `storage`. @inlinable public init?(raw storage: S) where S.Element == Element { - self.init(unchecked: storage) + _storage = .init(storage) if _someHeapViolation() != nil { return nil } From 8438c2c40821f49c42f8189dafa831d191277025 Mon Sep 17 00:00:00 2001 From: Daryle Walker Date: Thu, 14 Oct 2021 02:06:31 -0400 Subject: [PATCH 5/8] Restrict access to clear-box initializer Remove the initializer's own unit tests, assuming that it will always work instead. --- Sources/PriorityQueueModule/Heap.swift | 4 +-- Tests/PriorityQueueTests/HeapTests.swift | 33 +++--------------------- 2 files changed, 5 insertions(+), 32 deletions(-) diff --git a/Sources/PriorityQueueModule/Heap.swift b/Sources/PriorityQueueModule/Heap.swift index 0a7b79af..e22338f8 100644 --- a/Sources/PriorityQueueModule/Heap.swift +++ b/Sources/PriorityQueueModule/Heap.swift @@ -39,8 +39,8 @@ public struct Heap { /// elements as pre-call `storage`. /// /// - Complexity: O(*n*), where *n* is the length of `storage`. - @inlinable - public init?(raw storage: S) where S.Element == Element { + @_alwaysEmitIntoClient + internal init?(_raw storage: S) where S.Element == Element { _storage = .init(storage) if _someHeapViolation() != nil { return nil diff --git a/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift index 2b2d9307..b44ca359 100644 --- a/Tests/PriorityQueueTests/HeapTests.swift +++ b/Tests/PriorityQueueTests/HeapTests.swift @@ -326,14 +326,14 @@ final class HeapTests: XCTestCase { // Check the finer details. As these peek into the stored structure, they // may need to be updated whenever the internal format changes. - var heap2 = Heap(raw: [1])! + var heap2 = Heap(_raw: [1])! XCTAssertEqual(heap2.max(), 1) XCTAssertEqual(Array(heap2.unordered), [1]) XCTAssertEqual(heap2.replaceMax(with: 2), 1) XCTAssertEqual(heap2.max(), 2) XCTAssertEqual(Array(heap2.unordered), [2]) - heap2 = Heap(raw: [1, 2])! + heap2 = Heap(_raw: [1, 2])! XCTAssertEqual(heap2.max(), 2) XCTAssertEqual(Array(heap2.unordered), [1, 2]) XCTAssertEqual(heap2.replaceMax(with: 3), 2) @@ -343,7 +343,7 @@ final class HeapTests: XCTestCase { XCTAssertEqual(heap2.max(), 1) XCTAssertEqual(Array(heap2.unordered), [0, 1]) - heap2 = Heap(raw: [5, 20, 31, 16, 8, 7, 18])! + heap2 = Heap(_raw: [5, 20, 31, 16, 8, 7, 18])! XCTAssertEqual(heap2.max(), 31) XCTAssertEqual(Array(heap2.unordered), [5, 20, 31, 16, 8, 7, 18]) XCTAssertEqual(heap2.replaceMax(with: 29), 31) @@ -480,33 +480,6 @@ final class HeapTests: XCTestCase { XCTAssertEqual(heap.count, 20) } - func test_initializer_withChecking() { - XCTAssertNotNil(Heap(raw: EmptyCollection())) - XCTAssertNotNil(Heap(raw: CollectionOfOne("a"))) - XCTAssertNotNil(Heap(raw: repeatElement(2.0, count: 15))) - - // As these test non-identical multi-element sources, they may need to be - // updated whenever the internal storage format changes. - - let twoElements = Heap(raw: [1, 2]) - XCTAssertEqual(twoElements?.unordered, [1, 2]) - XCTAssertNil(Heap(raw: [2, 1])) - - let threeElements = Heap(raw: 1...3) - XCTAssertEqual(threeElements?.unordered, [1, 2, 3]) - - let otherThreeElements = Heap(raw: [1, 3, 2]) - XCTAssertEqual(otherThreeElements?.unordered, [1, 3, 2]) - XCTAssertNil(Heap(raw: [2, 1, 3])) - XCTAssertNil(Heap(raw: [2, 3, 1])) - XCTAssertNil(Heap(raw: [3, 1, 2])) - XCTAssertNil(Heap(raw: [3, 2, 1])) - - // Errors past the first two layers. - XCTAssertNil(Heap(raw: [1, 2, 3, 0, 2, 3, 2])) // 0 >= 1 is false - XCTAssertNil(Heap(raw: [1, 2, 3, 1, 4, 3, 1])) // 4 <= 2 is false - } - func test_initializer_fromArrayLiteral() { var heap: Heap = [1, 3, 5, 7, 9] XCTAssertEqual(heap.count, 5) From dec05b96fec55075372ead2ad081ceca99618341 Mon Sep 17 00:00:00 2001 From: Daryle Walker Date: Thu, 14 Oct 2021 02:14:55 -0400 Subject: [PATCH 6/8] Change the clear-box initializer to no longer be fail-able If the format of the incoming data does not match that of a heap, a precondition error is flagged instead. --- Sources/PriorityQueueModule/Heap.swift | 16 +++++++--------- Tests/PriorityQueueTests/HeapTests.swift | 6 +++--- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/Sources/PriorityQueueModule/Heap.swift b/Sources/PriorityQueueModule/Heap.swift index e22338f8..fea6d0b4 100644 --- a/Sources/PriorityQueueModule/Heap.swift +++ b/Sources/PriorityQueueModule/Heap.swift @@ -29,22 +29,20 @@ public struct Heap { internal var _storage: ContiguousArray /// Creates a heap from the given sequence, assuming said sequence is already - /// an implicit data structure for a binary min-max heap, failing otherwise. + /// an implicit data structure for a binary min-max heap. /// - /// - Precondition: `storage` is finite. + /// - Precondition: `storage` is finite, and it already matches the implicit + /// data structure for a binary min-max heap. /// /// - Parameter storage: The elements of the heap. - /// - Postcondition: If the initializer doesn't fail: - /// `unordered.elementsEqual(s)`, where *s* is a sequence with the same - /// elements as pre-call `storage`. + /// - Postcondition: `unordered.elementsEqual(s)`, where *s* is a sequence + /// with the same elements as pre-call `storage`. /// /// - Complexity: O(*n*), where *n* is the length of `storage`. @_alwaysEmitIntoClient - internal init?(_raw storage: S) where S.Element == Element { + internal init(_raw storage: S) where S.Element == Element { _storage = .init(storage) - if _someHeapViolation() != nil { - return nil - } + _checkInvariants() } /// Creates an empty heap. diff --git a/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift index b44ca359..0e2aff90 100644 --- a/Tests/PriorityQueueTests/HeapTests.swift +++ b/Tests/PriorityQueueTests/HeapTests.swift @@ -326,14 +326,14 @@ final class HeapTests: XCTestCase { // Check the finer details. As these peek into the stored structure, they // may need to be updated whenever the internal format changes. - var heap2 = Heap(_raw: [1])! + var heap2 = Heap(_raw: [1]) XCTAssertEqual(heap2.max(), 1) XCTAssertEqual(Array(heap2.unordered), [1]) XCTAssertEqual(heap2.replaceMax(with: 2), 1) XCTAssertEqual(heap2.max(), 2) XCTAssertEqual(Array(heap2.unordered), [2]) - heap2 = Heap(_raw: [1, 2])! + heap2 = Heap(_raw: [1, 2]) XCTAssertEqual(heap2.max(), 2) XCTAssertEqual(Array(heap2.unordered), [1, 2]) XCTAssertEqual(heap2.replaceMax(with: 3), 2) @@ -343,7 +343,7 @@ final class HeapTests: XCTestCase { XCTAssertEqual(heap2.max(), 1) XCTAssertEqual(Array(heap2.unordered), [0, 1]) - heap2 = Heap(_raw: [5, 20, 31, 16, 8, 7, 18])! + heap2 = Heap(_raw: [5, 20, 31, 16, 8, 7, 18]) XCTAssertEqual(heap2.max(), 31) XCTAssertEqual(Array(heap2.unordered), [5, 20, 31, 16, 8, 7, 18]) XCTAssertEqual(heap2.replaceMax(with: 29), 31) From 43e880b49c89a1ef58e671c88d55bddda18c97d1 Mon Sep 17 00:00:00 2001 From: Daryle Walker Date: Thu, 14 Oct 2021 18:49:30 -0400 Subject: [PATCH 7/8] Change the expression of preconditions --- Sources/PriorityQueueModule/Heap.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/PriorityQueueModule/Heap.swift b/Sources/PriorityQueueModule/Heap.swift index fea6d0b4..dba85310 100644 --- a/Sources/PriorityQueueModule/Heap.swift +++ b/Sources/PriorityQueueModule/Heap.swift @@ -204,7 +204,7 @@ extension Heap { /// - Complexity: O(log `count`) @inlinable @discardableResult public mutating func replaceMin(with replacement: Element) -> Element { - guard !isEmpty else { preconditionFailure("No element to replace") } + precondition(!isEmpty, "No element to replace") var removed = replacement _update { handle in @@ -233,7 +233,7 @@ extension Heap { /// - Complexity: O(log `count`) @inlinable @discardableResult public mutating func replaceMax(with replacement: Element) -> Element { - guard !isEmpty else { preconditionFailure("No element to replace") } + precondition(!isEmpty, "No element to replace") var removed = replacement _update { handle in From 8be0f192e8f120969427cb2645aabe6f5fdf15a1 Mon Sep 17 00:00:00 2001 From: Daryle Walker Date: Thu, 14 Oct 2021 19:01:36 -0400 Subject: [PATCH 8/8] Undo segregation of heap consistency tests from precondition code --- .../PriorityQueueModule/Heap+Invariants.swift | 94 ++++++------------- 1 file changed, 30 insertions(+), 64 deletions(-) diff --git a/Sources/PriorityQueueModule/Heap+Invariants.swift b/Sources/PriorityQueueModule/Heap+Invariants.swift index b1e0f54f..61999115 100644 --- a/Sources/PriorityQueueModule/Heap+Invariants.swift +++ b/Sources/PriorityQueueModule/Heap+Invariants.swift @@ -19,16 +19,36 @@ extension Heap { @inlinable @inline(never) internal func _checkInvariants() { - if let (value, node, boundary) = _someHeapViolation() { - switch boundary { - case .lessThan(let min): - preconditionFailure( - "Element \(value) at \(node) is less than min \(min)" - ) - case .greaterThan(let max): - preconditionFailure( - "Element \(value) at \(node) is greater than max \(max)" - ) + guard count > 1 else { return } + _checkInvariants(node: .root, min: nil, max: nil) + } + + @inlinable + internal func _checkInvariants(node: _Node, min: Element?, max: Element?) { + let value = _storage[node.offset] + if let min = min { + precondition(value >= min, + "Element \(value) at \(node) is less than min \(min)") + } + if let max = max { + precondition(value <= max, + "Element \(value) at \(node) is greater than max \(max)") + } + let left = node.leftChild() + let right = node.rightChild() + if node.isMinLevel { + if left.offset < count { + _checkInvariants(node: left, min: value, max: max) + } + if right.offset < count { + _checkInvariants(node: right, min: value, max: max) + } + } else { + if left.offset < count { + _checkInvariants(node: left, min: min, max: value) + } + if right.offset < count { + _checkInvariants(node: right, min: min, max: value) } } } @@ -37,58 +57,4 @@ extension Heap { @inline(__always) public func _checkInvariants() {} #endif // COLLECTIONS_INTERNAL_CHECKS - - /// Returns any violation of the min-max heap property. - @inlinable - internal func _someHeapViolation() - -> (value: Element, node: _Node, kind: _BoundaryViolation)? { - guard !_storage.isEmpty else { return nil } - - /// Returns any violation of the min-max heap property within the sub-heap - /// whose root is at the given node for the given value bounds. - func _someSubHeapViolation(node: _Node, min: Element?, max: Element?) - -> (value: Element, node: _Node, kind: _BoundaryViolation)? { - // Check the sub-heap's root's bounds. - let value = _storage[node.offset] - if let min = min, value < min { - return (value, node, .lessThan(min: min)) - } - if let max = max, value > max { - return (value, node, .greaterThan(max: max)) - } - - // Check the child sub-heaps. - var nextMin = min, nextMax = max - if node.isMinLevel { - nextMin = value - } else { - nextMax = value - } - - if case let leftNode = node.leftChild(), - leftNode.offset < count, - let result = _someSubHeapViolation(node: leftNode, min: nextMin, - max: nextMax) { - return result - } - if case let rightNode = node.rightChild(), - rightNode.offset < count, - let result = _someSubHeapViolation(node: rightNode, min: nextMin, - max: nextMax) { - return result - } - return nil - } - - return _someSubHeapViolation(node: .root, min: nil, max: nil) - } - - /// The manner the min-max heap property is violated. - @usableFromInline - internal enum _BoundaryViolation { - /// An element had a value less than the supplied lower bound. - case lessThan(min: Element) - /// An element had a value greater than the supplied upper bound. - case greaterThan(max: Element) - } }