From 32aee022ce444d1fd6a1bbd5844b8720dba1e086 Mon Sep 17 00:00:00 2001 From: Nate Cook Date: Thu, 13 Jul 2023 15:17:07 -0500 Subject: [PATCH] Implements mutable merge algorithm This change implements mutable merge algorithms, both in place and using a temporary buffer. The temporary buffer is only used if the mutable collection supports accessing its storage as a contiguous unsafe buffer; if not, the in-place merge is used instead. --- Sources/Algorithms/Merge.swift | 230 ++++++++++++++++++ .../COWLoggingArray.swift | 133 ++++++++++ Tests/SwiftAlgorithmsTests/MergeTests.swift | 97 ++++++++ 3 files changed, 460 insertions(+) create mode 100644 Sources/Algorithms/Merge.swift create mode 100644 Tests/SwiftAlgorithmsTests/COWLoggingArray.swift create mode 100644 Tests/SwiftAlgorithmsTests/MergeTests.swift diff --git a/Sources/Algorithms/Merge.swift b/Sources/Algorithms/Merge.swift new file mode 100644 index 0000000..2e4c6df --- /dev/null +++ b/Sources/Algorithms/Merge.swift @@ -0,0 +1,230 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +//===----------------------------------------------------------------------===// +// merge(at:by:) / merge(subrange:at:by:) +//===----------------------------------------------------------------------===// + +extension MutableCollection where Self: BidirectionalCollection { + public mutating func merge( + at middle: Index, + by areInAscendingOrder: (Element, Element) throws -> Bool + ) rethrows { + try merge(subrange: startIndex.., + at middle: Index, + by areInAscendingOrder: (Element, Element) throws -> Bool + ) rethrows { + if subrange.lowerBound == middle || subrange.upperBound == middle { return } + + let lowerBound = distance(from: startIndex, to: subrange.lowerBound) + let rangeCount = distance(from: subrange.lowerBound, to: subrange.upperBound) + let lowerCount = distance(from: subrange.lowerBound, to: middle) + + // FIXME: Insertion sort for small counts? + + let result: Void? = try withContiguousMutableStorageIfAvailable + { selfBuffer -> Void in + let upperCount = rangeCount - lowerCount + let upperBound = lowerBound + rangeCount + let endOfLower = lowerBound + lowerCount + + try withUnsafeTemporaryAllocation( + of: Element.self, capacity: Swift.min(lowerCount, upperCount) + ) { tempBuffer in + if lowerCount < upperCount { + // Merge into lower section from start of tempBuffer and upper section, + // prioritizing tempBuffer values + + // Move elements from lower section to temporary buffer + _ = tempBuffer.moveInitialize( + fromContentsOf: selfBuffer[lowerBound..= tempLowerBound && selfSource >= selfLowerBound { + // FIXME: Figure out throwing situation + if try !areInAscendingOrder(tempSource.pointee, selfSource.pointee) { + lastUninitialized.moveInitialize(from: tempSource, count: 1) + if tempSource == tempLowerBound { + break + } + tempSource -= 1 + assert(tempSource >= tempLowerBound) + } else { + lastUninitialized.moveInitialize(from: selfSource, count: 1) + if selfSource == selfLowerBound { + // Done moving from the lower section, but there could still + // be elements in the temp buffer. + + // Note: `tempSource` points to the last element in the temp + // buffer, not the "past the end" position, hence the +1 here: + let tempCount = (tempSource + 1) - tempLowerBound + selfLowerBound.moveInitialize(from: tempLowerBound, count: tempCount) + break + } + selfSource -= 1 + assert(selfSource >= selfLowerBound) + } + lastUninitialized -= 1 + assert(lastUninitialized >= selfLowerBound) + } + } + } + } + + if result == nil { + try mergeInPlace(subrange: subrange, at: middle, by: areInAscendingOrder) + } + } +} + +extension MutableCollection where Self: BidirectionalCollection, Element: Comparable { + public mutating func merge(at middle: Index) { + merge(at: middle, by: <) + } + + public mutating func merge(subrange: Range, at middle: Index) { + merge(subrange: subrange, at: middle, by: <) + } +} + +//===----------------------------------------------------------------------===// +// mergeInPlace(at:by:) / mergeInPlace(subrange:at:by:) +//===----------------------------------------------------------------------===// + +extension MutableCollection where Self: BidirectionalCollection { + public mutating func mergeInPlace( + at middle: Index, + by areInAscendingOrder: (Element, Element) throws -> Bool + ) rethrows { + try mergeInPlace(subrange: startIndex.., + at middle: Index, + by areInAscendingOrder: (Element, Element) throws -> Bool + ) rethrows { + // If either side of `middle` is empty, there's no work to do. + if subrange.lowerBound == middle || middle == subrange.upperBound { + return + } + + let lowerCount = distance(from: subrange.lowerBound, to: middle) + let upperCount = distance(from: middle, to: subrange.upperBound) + // FIXME: Insertion sort for small counts? + guard lowerCount + upperCount > 2 else { + if try areInAscendingOrder(self[middle], self[subrange.lowerBound]) { + swapAt(subrange.lowerBound, middle) + } + return + } + + let lowerPivot: Index + let upperPivot: Index + + if lowerCount < upperCount { + // a a b b c c d e f|a b b b c d d d e e e e e f f + // ^ ^ + // lowerPivot upperPivot + // (lower pivot must be strictly greater than element at upper) + // after rotation: + // a a b b c c d|a b b b c d d/e f|d e e e e e f f + // ^ + // newMiddle + upperPivot = index(middle, offsetBy: upperCount / 2) + // FIXME: Binary search instead of linear? Require random access? + lowerPivot = try self[subrange.lowerBound.., + at middle: Index + ) { + mergeInPlace(subrange: subrange, at: middle, by: <) + } +} diff --git a/Tests/SwiftAlgorithmsTests/COWLoggingArray.swift b/Tests/SwiftAlgorithmsTests/COWLoggingArray.swift new file mode 100644 index 0000000..3f1114c --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/COWLoggingArray.swift @@ -0,0 +1,133 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest + +fileprivate var COWLoggingArray_CopyCount = 0 + +public func AssertNoCopyOnWrite( + _ elements: some Sequence, + _ message: @autoclosure () -> String = "", + file: StaticString = #file, + line: UInt = #line, + _ body: (inout COWLoggingArray) -> Void +) { + let copyCountBeforeBody = COWLoggingArray_CopyCount + var loggingArray = COWLoggingArray(elements) + body(&loggingArray) + XCTAssertEqual( + copyCountBeforeBody, + COWLoggingArray_CopyCount, + message(), file: file, line: line) +} + +public struct COWLoggingArray { + var storage: Storage + + class Storage { + var buffer: UnsafeMutableBufferPointer + var count: Int + var capacity: Int { + buffer.count + } + + init(capacity: Int) { + self.buffer = .allocate(capacity: capacity) + self.count = 0 + } + + deinit { + buffer.baseAddress!.deinitialize(count: count) + buffer.deallocate() + } + + func cloned(capacity: Int? = nil) -> Storage { + let newCapacity = Swift.max(capacity ?? self.capacity, self.capacity) + let newStorage = Storage(capacity: newCapacity) + newStorage.buffer.baseAddress! + .initialize(from: buffer.baseAddress!, count: count) + newStorage.count = count + return newStorage + } + } + + mutating func _makeUnique() { + if !isKnownUniquelyReferenced(&storage) { + storage = storage.cloned() + COWLoggingArray_CopyCount += 1 + } + } +} + +extension COWLoggingArray: RandomAccessCollection, RangeReplaceableCollection, + MutableCollection, ExpressibleByArrayLiteral +{ + public var count: Int { storage.count } + public var startIndex: Int { 0 } + public var endIndex: Int { count } + + public subscript(i: Int) -> Element { + get { + storage.buffer[i] + } + set { + _makeUnique() + storage.buffer[i] = newValue + } + } + + public init() { + storage = Storage(capacity: 10) + } + + public mutating func reserveCapacity(_ n: Int) { + if !isKnownUniquelyReferenced(&storage) { + COWLoggingArray_CopyCount += 1 + storage = storage.cloned(capacity: n) + } else if count < n { + storage = storage.cloned(capacity: n) + } + } + + public mutating func replaceSubrange(_ subrange: Range, with newElements: C) + where C : Collection, Element == C.Element + { + _makeUnique() + let newCount = (count - subrange.count) + newElements.count + if newCount > storage.capacity { + storage = storage.cloned(capacity: newCount) + } + + let startOfSubrange = storage.buffer.baseAddress! + subrange.lowerBound + let endOfSubrange = startOfSubrange + subrange.count + let endOfNewElements = startOfSubrange + newElements.count + let countAfterSubrange = count - subrange.upperBound + + // clear out old elements + startOfSubrange.deinitialize(count: subrange.count) + + // move elements above subrange + endOfNewElements.moveInitialize(from: endOfSubrange, count: countAfterSubrange) + + // assign new elements + for (pointer, element) in zip(startOfSubrange..., newElements) { + pointer.initialize(to: element) + } + + // update count + storage.count = newCount + } + + public init(arrayLiteral elements: Element...) { + storage = Storage(capacity: elements.count) + replaceSubrange(0..<0, with: elements) + } +} diff --git a/Tests/SwiftAlgorithmsTests/MergeTests.swift b/Tests/SwiftAlgorithmsTests/MergeTests.swift new file mode 100644 index 0000000..a94b580 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/MergeTests.swift @@ -0,0 +1,97 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + + +final class MergeTests: XCTestCase { + func _createInput(seed: UInt64, count: Int) -> (input: [Int], pivot: Int) { + var rng = SplitMix64(seed: seed) + // Create array of numbers with two sorted partitions + var numbers = (1...count).map { _ in Int.random(in: 1...10, using: &rng) } + let pivot = Int.random(in: 0...numbers.count, using: &rng) + numbers[..