diff --git a/Sources/HeapModule/Heap.swift b/Sources/HeapModule/Heap.swift index 698f28f4d..8f884eb03 100644 --- a/Sources/HeapModule/Heap.swift +++ b/Sources/HeapModule/Heap.swift @@ -100,6 +100,42 @@ extension Heap { Array(_storage) } + /// Creates an empty heap with preallocated space for at least the + /// specified number of elements. + /// + /// Use this initializer to avoid intermediate reallocations of a heap's + /// storage when you know in advance how many elements you'll insert into it + /// after creation. + /// + /// - Parameter minimumCapacity: The minimum number of elements that the newly + /// created heap should be able to store without reallocating its storage. + /// + /// - Complexity: O(1) allocations + @inlinable + public init(minimumCapacity: Int) { + self.init() + self.reserveCapacity(minimumCapacity) + } + + /// Reserves enough space to store the specified number of elements. + /// + /// If you are adding a known number of elements to a heap, use this method + /// to avoid multiple reallocations. This method ensures that the heap has + /// unique, mutable, contiguous storage, with space allocated for at least + /// the requested number of elements. + /// + /// For performance reasons, the size of the newly allocated storage might be + /// greater than the requested capacity. + /// + /// - Parameter minimumCapacity: The minimum number of elements that the + /// resulting heap should be able to store without reallocating its storage. + /// + /// - Complexity: O(`count`) + @inlinable + public mutating func reserveCapacity(_ minimumCapacity: Int) { + _storage.reserveCapacity(minimumCapacity) + } + /// Inserts the given element into the heap. /// /// - Complexity: O(log(`count`)) element comparisons @@ -192,6 +228,7 @@ extension Heap { /// /// - Complexity: O(log(`count`)) element comparisons @inlinable + @discardableResult public mutating func removeMin() -> Element { return popMin()! } @@ -202,6 +239,7 @@ extension Heap { /// /// - Complexity: O(log(`count`)) element comparisons @inlinable + @discardableResult public mutating func removeMax() -> Element { return popMax()! }