diff --git a/Package.swift b/Package.swift index 82ffb50c..fdb3aa1b 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.3 +// swift-tools-version:5.5 //===----------------------------------------------------------------------===// // // This source file is part of the Swift Collections open source project @@ -17,7 +17,7 @@ import PackageDescription // from the package manager command line: // // swift build -Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS -var settings: [SwiftSetting]? = [ +var settings: [SwiftSetting] = [ // Enables internal consistency checks at the end of initializers and // mutating operations. This can have very significant overhead, so enabling @@ -44,10 +44,6 @@ var settings: [SwiftSetting]? = [ ] -// Prevent SPM 5.3 from throwing an error on empty settings arrays. -// (This has been fixed in 5.4.) -if settings?.isEmpty == true { settings = nil } - let package = Package( name: "swift-collections", products: [ diff --git a/README.md b/README.md index c97ade3b..19d51d57 100644 --- a/README.md +++ b/README.md @@ -10,22 +10,30 @@ Read more about the package, and the intent behind it, in the [announcement on s The package currently provides the following implementations: +- [`BitSet`][BitSet] and [`BitArray`][BitArray], dynamic bit vectors. + - [`Deque`][Deque], a double-ended queue backed by a ring buffer. Deques are range-replaceable, mutable, random-access collections. +- [`Heap`][Heap], a min-max heap backed by an array, suitable for use as a priority queue. + - [`OrderedSet`][OrderedSet], a variant of the standard `Set` where the order of items is well-defined and items can be arbitrarily reordered. Uses a `ContiguousArray` as its backing store, augmented by a separate hash table of bit packed offsets into it. - [`OrderedDictionary`][OrderedDictionary], an ordered variant of the standard `Dictionary`, providing similar benefits. +- [`PersistentSet`][PersistentSet] and [`PersistentDictionary`][PersistentDictionary], persistent hashed collections implementing Compressed Hash-Array Mapped Prefix Trees (CHAMP). These work similar to the standard `Set` and `Dictionary`, but they excel at use cases that mutate shared copies, offering dramatic memory savings and radical time improvements. + +[BitSet]: Documentation/BitSet.md +[BitArray]: Documentation/BitArray.md [Deque]: Documentation/Deque.md +[Heap]: Documentation/Heap.md [OrderedSet]: Documentation/OrderedSet.md [OrderedDictionary]: Documentation/OrderedDictionary.md +[PersistentSet]: Documentation/PersistentSet.md +[PersistentDictionary]: Documentation/PersistentDictionary.md The following data structures are currently being worked on but they aren't ready for inclusion in a tagged release: -- [`Heap`][Heap] and [`PriorityQueue`](https://github.com/apple/swift-collections/pull/51), min-max heaps backed by an array. - [`SortedSet` and `SortedDictionary`](https://github.com/apple/swift-collections/pull/65), sorted collections backed by in-memory persistent b-trees. -- [`HashSet` and `HashMap`](https://github.com/apple/swift-collections/pull/31), persistent hashed collections implemented as Compressed Hash-Array Mapped Prefix-Trees (CHAMP). -- [`BitArray` and `BitSet`](https://github.com/apple/swift-collections/pull/83), dynamic bit vectors. - [`SparseSet`](https://github.com/apple/swift-collections/pull/80), a constant time set construct, trading off memory for speed. [Heap]: Documentation/Heap.md @@ -47,7 +55,7 @@ The Swift Collections package is source stable. The version numbers follow [Sema [semver]: https://semver.org -The public API of version 1.0 of the `swift-collections` package consists of non-underscored declarations that are marked `public` in the `Collections`, `DequeModule` and `OrderedCollections` modules. +The public API of version 1.1 of the `swift-collections` package consists of non-underscored declarations that are marked `public` in the `Collections`, `BitCollections`, `DequeModule`, `HeapModule`, `OrderedCollections` and `PersistentCollections` modules. Interfaces that aren't part of the public API may continue to change in any release, including patch releases. If you have a use case that requires using underscored APIs, please [submit a Feature Request][enhancement] describing it! We'd like the public interface to be as useful as possible -- although preferably without compromising safety or limiting future evolution. @@ -65,12 +73,22 @@ Future minor versions of the package may update these rules as needed. We'd like this package to quickly embrace Swift language and toolchain improvements that are relevant to its mandate. Accordingly, from time to time, we expect that new versions of this package will require clients to upgrade to a more recent Swift toolchain release. (This allows the package to make use of new language/stdlib features, build on compiler bug fixes, and adopt new package manager functionality as soon as they are available.) Requiring a new Swift release will only need a minor version bump. +The following table maps existing package releases to their minimum required Swift toolchain release: + +| Package version | Swift version | +|---|---|---| +| swift-collections 1.0.x | >= Swift 5.3 | +| swift-collections 1.1.x | >= Swift 5.5 | + +(Note: the package has no minimum deployment target, so while it does require clients to use a recent Swift toolchain to build it, the code itself is able to run on any OS release that supports running Swift code.) + + ## Using **Swift Collections** in your project To use this package in a SwiftPM project, you need to set it up as a package dependency: ```swift -// swift-tools-version:5.6 +// swift-tools-version:5.7 import PackageDescription let package = Package( @@ -78,7 +96,7 @@ let package = Package( dependencies: [ .package( url: "https://github.com/apple/swift-collections.git", - .upToNextMajor(from: "1.0.3") // or `.upToNextMinor + .upToNextMinor(from: "1.1.0") // or `.upToNextMajor ) ], targets: [ diff --git a/Sources/BitCollections/BitArray/BitArray+Copy.swift b/Sources/BitCollections/BitArray/BitArray+Copy.swift index e592e5e6..1f339c33 100644 --- a/Sources/BitCollections/BitArray/BitArray+Copy.swift +++ b/Sources/BitCollections/BitArray/BitArray+Copy.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension BitArray { internal mutating func _copy( from range: Range, diff --git a/Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift b/Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift index 9485c8f6..91357755 100644 --- a/Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift +++ b/Sources/BitCollections/BitArray/BitArray+CustomStringConvertible.swift @@ -23,7 +23,7 @@ extension BitArray: CustomStringConvertible { let b1: UInt8 = 49 // ASCII 1 var i = 0 for v in self { - target._initialize(at: i, to: v ? b1 : b0) + target.initializeElement(at: i, to: v ? b1 : b0) i &+= 1 } return i diff --git a/Sources/BitCollections/BitSet/BitSet+Initializers.swift b/Sources/BitCollections/BitSet/BitSet+Initializers.swift index bec2715d..3c23994b 100644 --- a/Sources/BitCollections/BitSet/BitSet+Initializers.swift +++ b/Sources/BitCollections/BitSet/BitSet+Initializers.swift @@ -172,16 +172,16 @@ extension BitSet { _storage = Array(unsafeUninitializedCapacity: capacity) { buffer, count in let sharedCount = Swift.min(w1.count, w2.count) for w in 0 ..< sharedCount { - buffer._initialize(at: w, to: function(w1[w], w2[w])) + buffer.initializeElement(at: w, to: function(w1[w], w2[w])) } if includingTail { if w1.count < w2.count { for w in w1.count ..< w2.count { - buffer._initialize(at: w, to: function(_Word.empty, w2[w])) + buffer.initializeElement(at: w, to: function(_Word.empty, w2[w])) } } else { for w in w2.count ..< w1.count { - buffer._initialize(at: w, to: function(w1[w], _Word.empty)) + buffer.initializeElement(at: w, to: function(w1[w], _Word.empty)) } } } diff --git a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift index ff00540a..a314d58e 100644 --- a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift +++ b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension BitSet { /// An unsafe-unowned bitset view over `UInt` storage, providing bit set /// primitives. @@ -273,7 +275,7 @@ extension BitSet._UnsafeHandle: BidirectionalCollection { internal var startIndex: Index { let word = _words.firstIndex { !$0.isEmpty } guard let word = word else { return endIndex } - return Index(word: word, bit: _words[word].firstMember) + return Index(word: word, bit: _words[word].firstMember!) } @inlinable @@ -299,7 +301,7 @@ extension BitSet._UnsafeHandle: BidirectionalCollection { } w = _words[word] } - return Index(word: word, bit: w.firstMember) + return Index(word: word, bit: w.firstMember!) } @usableFromInline @@ -318,7 +320,7 @@ extension BitSet._UnsafeHandle: BidirectionalCollection { precondition(word >= 0, "Can't advance below startIndex") w = _words[word] } - return Index(word: word, bit: w.lastMember) + return Index(word: word, bit: w.lastMember!) } @usableFromInline @@ -501,9 +503,7 @@ extension BitSet._UnsafeHandle { _mutableWords[l.word].formIntersection(_Word(upTo: l.bit).complement()) if u.word < wordCount { _mutableWords[u.word].formIntersection(_Word(upTo: u.bit)) - _mutableWords[(u.word + 1)...] - ._rebased() - .assign(repeating: .empty) + _mutableWords[(u.word + 1)...].update(repeating: .empty) } } @@ -542,9 +542,7 @@ extension BitSet._UnsafeHandle { } _mutableWords[l.word].subtract(_Word(upTo: l.bit).complement()) - _mutableWords[(l.word + 1) ..< u.word] - ._rebased() - .assign(repeating: .empty) + _mutableWords[(l.word + 1) ..< u.word].update(repeating: .empty) if u.word < wordCount { _mutableWords[u.word].subtract(_Word(upTo: u.bit)) } diff --git a/Sources/BitCollections/Shared/UInt+Tricks.swift b/Sources/BitCollections/Shared/UInt+Tricks.swift index 0b535c6f..5ef5fc72 100644 --- a/Sources/BitCollections/Shared/UInt+Tricks.swift +++ b/Sources/BitCollections/Shared/UInt+Tricks.swift @@ -9,36 +9,9 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension UInt { - @inlinable @inline(__always) - internal var _nonzeroBitCount: UInt { - Self(truncatingIfNeeded: nonzeroBitCount) - } - - internal var _reversed: UInt { - // https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel - var shift: UInt = UInt(UInt.bitWidth) - var mask: UInt = ~0; - var result = self - while true { - shift &>>= 1 - guard shift > 0 else { break } - mask ^= mask &<< shift - result = ((result &>> shift) & mask) | ((result &<< shift) & ~mask) - } - return result - } - - @inlinable @inline(__always) - internal var _lastSetBit: UInt { - UInt(truncatingIfNeeded: self.trailingZeroBitCount) - } - - @inlinable @inline(__always) - internal var _firstSetBit: UInt { - UInt(truncatingIfNeeded: UInt.bitWidth &- 1 &- self.leadingZeroBitCount) - } - /// Returns the position of the `n`th set bit in `self`. /// /// - Parameter n: The to retrieve. This value is @@ -48,52 +21,14 @@ extension UInt { /// - Returns: If this integer contains enough set bits to satisfy the /// request, then this function returns the position of the bit found. /// Otherwise it returns nil. - internal func _nthSetBit(_ n: inout UInt) -> UInt? { - // FIXME: Use bit deposit instruction when available (PDEP on Intel). - assert(UInt.bitWidth == 64 || UInt.bitWidth == 32, "Unsupported UInt bitWidth") - - var shift: UInt = 0 - - let c = self._nonzeroBitCount + internal func _rank(ofBit n: inout UInt) -> UInt? { + let c = self.nonzeroBitCount guard n < c else { - n &-= c + n &-= UInt(bitPattern: c) return nil } - - if UInt.bitWidth == 64 { - let c32 = (self & 0xFFFFFFFF)._nonzeroBitCount - if n >= c32 { - shift &+= 32 - n &-= c32 - } - } - let c16 = ((self &>> shift) & 0xFFFF)._nonzeroBitCount - if n >= c16 { - shift &+= 16 - n &-= c16 - } - let c8 = ((self &>> shift) & 0xFF)._nonzeroBitCount - if n >= c8 { - shift &+= 8 - n &-= c8 - } - let c4 = ((self &>> shift) & 0xF)._nonzeroBitCount - if n >= c4 { - shift &+= 4 - n &-= c4 - } - let c2 = ((self &>> shift) & 0x3)._nonzeroBitCount - if n >= c2 { - shift &+= 2 - n &-= c2 - } - let c1 = (self &>> shift) & 0x1 - if n >= c1 { - shift &+= 1 - n &-= c1 - } - precondition(n == 0 && (self &>> shift) & 0x1 == 1) - return shift + let m = Int(bitPattern: n) + n = 0 + return _bit(ranked: m)! } } - diff --git a/Sources/BitCollections/Shared/UnsafeMutableBufferPointer+Utilities.swift b/Sources/BitCollections/Shared/UnsafeMutableBufferPointer+Utilities.swift deleted file mode 100644 index d8fe84a5..00000000 --- a/Sources/BitCollections/Shared/UnsafeMutableBufferPointer+Utilities.swift +++ /dev/null @@ -1,36 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021-2022 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 -// -//===----------------------------------------------------------------------===// - -extension Collection { - @inlinable - @inline(__always) - internal func _rebased() -> UnsafeMutableBufferPointer - where Self == UnsafeMutableBufferPointer.SubSequence { - .init(rebasing: self) - } -} - -extension UnsafeMutableBufferPointer { - @inlinable - @inline(__always) - internal func _assign(from source: Self) { - assert(source.count == self.count) - if count > 0 { - baseAddress!.assign(from: source.baseAddress!, count: count) - } - } - - @inlinable - @inline(__always) - internal func _initialize(at index: Int, to value: Element) { - (baseAddress.unsafelyUnwrapped + index).initialize(to: value) - } -} diff --git a/Sources/BitCollections/Shared/_Word.swift b/Sources/BitCollections/Shared/_Word.swift index 09278da4..b686e677 100644 --- a/Sources/BitCollections/Shared/_Word.swift +++ b/Sources/BitCollections/Shared/_Word.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + @usableFromInline @frozen internal struct _Word { @@ -52,12 +54,12 @@ extension _Word { /// then this function returns the member found. Otherwise it returns nil. @inline(never) internal func nthElement(_ n: inout UInt) -> UInt? { - value._nthSetBit(&n) + value._rank(ofBit: &n) } @inline(never) internal func nthElementFromEnd(_ n: inout UInt) -> UInt? { - guard let i = value._reversed._nthSetBit(&n) else { return nil } + guard let i = value._reversed._rank(ofBit: &n) else { return nil } return UInt(UInt.bitWidth) &- 1 &- i } } @@ -102,13 +104,13 @@ extension _Word { @inlinable @inline(__always) - internal var firstMember: UInt { + internal var firstMember: UInt? { value._lastSetBit } @inlinable @inline(__always) - internal var lastMember: UInt { + internal var lastMember: UInt? { value._firstSetBit } diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque+Collection.swift index 8a967b47..bb4c29f7 100644 --- a/Sources/DequeModule/Deque+Collection.swift +++ b/Sources/DequeModule/Deque+Collection.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension Deque: Sequence { // Implementation note: we could also use the default `IndexingIterator` here. // This custom implementation performs direct storage access to eliminate any @@ -104,10 +106,10 @@ extension Deque: Sequence { _storage.read { source in let segments = source.segments() let c = segments.first.count - target[.. c1, let second = segments.second else { return (Iterator(_base: self, from: c1), c1) } let c2 = Swift.min(second.count, target.count - c1) - target[c1 ..< c1 + c2]._rebased()._initialize(from: second.prefix(c2)._rebased()) + target[c1 ..< c1 + c2].initializeAll(fromContentsOf: second.prefix(c2)) return (Iterator(_base: self, from: c1 + c2), c1 + c2) } } @@ -622,10 +624,10 @@ extension Deque: RangeReplaceableCollection { assert(handle.startSlot == .zero) let target = handle.mutableBuffer(for: .zero ..< _Slot(at: c)) let done: Void? = elements._withContiguousStorageIfAvailable_SR14663 { source in - target._initialize(from: source) + target.initializeAll(fromContentsOf: source) } if done == nil { - target._initialize(from: elements) + target.initializeAll(fromContentsOf: elements) } handle.count = c } diff --git a/Sources/DequeModule/Deque+Extras.swift b/Sources/DequeModule/Deque+Extras.swift index fd1c1487..93d64cc4 100644 --- a/Sources/DequeModule/Deque+Extras.swift +++ b/Sources/DequeModule/Deque+Extras.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension Deque { /// Creates a deque with the specified capacity, then calls the given /// closure with a buffer covering the array's uninitialized memory. diff --git a/Sources/DequeModule/Deque+Testing.swift b/Sources/DequeModule/Deque+Testing.swift index b9dc6d9c..2c1a0e0a 100644 --- a/Sources/DequeModule/Deque+Testing.swift +++ b/Sources/DequeModule/Deque+Testing.swift @@ -67,9 +67,9 @@ extension Deque { storage.update { target in let segments = target.mutableSegments() let c = segments.first.count - segments.first._initialize(from: source.prefix(c)._rebased()) + segments.first.initializeAll(fromContentsOf: source.prefix(c)) if let second = segments.second { - second._initialize(from: source.dropFirst(c)._rebased()) + second.initializeAll(fromContentsOf: source.dropFirst(c)) } } } diff --git a/Sources/DequeModule/UnsafeMutableBufferPointer+Utilities.swift b/Sources/DequeModule/UnsafeMutableBufferPointer+Utilities.swift deleted file mode 100644 index 95b2635a..00000000 --- a/Sources/DequeModule/UnsafeMutableBufferPointer+Utilities.swift +++ /dev/null @@ -1,65 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021 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 -// -//===----------------------------------------------------------------------===// - -extension Collection { - @inlinable - @inline(__always) - internal func _rebased() -> UnsafeBufferPointer - where Self == UnsafeBufferPointer.SubSequence { - .init(rebasing: self) - } -} - -extension Collection { - @inlinable - @inline(__always) - internal func _rebased() -> UnsafeMutableBufferPointer - where Self == UnsafeMutableBufferPointer.SubSequence { - .init(rebasing: self) - } -} - -extension UnsafeMutableBufferPointer { - @inlinable - @inline(__always) - internal func _initialize(from source: UnsafeBufferPointer) { - assert(source.count == count) - guard source.count > 0 else { return } - baseAddress!.initialize(from: source.baseAddress!, count: source.count) - } - - @inlinable - @inline(__always) - internal func _initialize( - from elements: C - ) where C.Element == Element { - assert(elements.count == count) - var (it, copied) = elements._copyContents(initializing: self) - precondition(copied == count) - precondition(it.next() == nil) - } - - @inlinable - @inline(__always) - internal func _deinitializeAll() { - guard count > 0 else { return } - baseAddress!.deinitialize(count: count) - } - - @inlinable - internal func _assign( - from replacement: C - ) where C.Element == Element { - guard self.count > 0 else { return } - self[0 ..< count]._rebased()._deinitializeAll() - _initialize(from: replacement) - } -} diff --git a/Sources/DequeModule/_UnsafeWrappedBuffer.swift b/Sources/DequeModule/_UnsafeWrappedBuffer.swift index 06a0a580..cf86b293 100644 --- a/Sources/DequeModule/_UnsafeWrappedBuffer.swift +++ b/Sources/DequeModule/_UnsafeWrappedBuffer.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + @frozen @usableFromInline internal struct _UnsafeWrappedBuffer { @@ -72,6 +74,24 @@ internal struct _UnsafeMutableWrappedBuffer { assert(first.count > 0 || second == nil) } + @inlinable + @inline(__always) + internal init( + _ first: UnsafeMutableBufferPointer.SubSequence, + _ second: UnsafeMutableBufferPointer? = nil + ) { + self.init(UnsafeMutableBufferPointer(rebasing: first), second) + } + + @inlinable + @inline(__always) + internal init( + _ first: UnsafeMutableBufferPointer, + _ second: UnsafeMutableBufferPointer.SubSequence + ) { + self.init(first, UnsafeMutableBufferPointer(rebasing: second)) + } + @inlinable @inline(__always) internal init( @@ -113,9 +133,9 @@ extension _UnsafeMutableWrappedBuffer { return self } if n <= first.count { - return Self(first.prefix(n)._rebased()) + return Self(first.prefix(n)) } - return Self(first, second!.prefix(n - first.count)._rebased()) + return Self(first, second!.prefix(n - first.count)) } @inlinable @@ -125,20 +145,20 @@ extension _UnsafeMutableWrappedBuffer { return self } guard let second = second else { - return Self(first.suffix(n)._rebased()) + return Self(first.suffix(n)) } if n <= second.count { - return Self(second.suffix(n)._rebased()) + return Self(second.suffix(n)) } - return Self(first.suffix(n - second.count)._rebased(), second) + return Self(first.suffix(n - second.count), second) } } extension _UnsafeMutableWrappedBuffer { @inlinable internal func deinitialize() { - first._deinitializeAll() - second?._deinitializeAll() + first.deinitialize() + second?.deinitialize() } @inlinable @@ -199,10 +219,10 @@ extension _UnsafeMutableWrappedBuffer { assert(self.count == elements.count) if let second = second { let wrap = elements.index(elements.startIndex, offsetBy: first.count) - first._initialize(from: elements[.. 0 else { return } - _words.baseAddress!.assign(repeating: .empty, count: _words.count) + _words.baseAddress!.update(repeating: .empty, count: _words.count) _count = 0 } diff --git a/Sources/DequeModule/Compatibility.swift b/Sources/_CollectionsUtilities/Array+WithContiguousStorage Compatibility.swift similarity index 75% rename from Sources/DequeModule/Compatibility.swift rename to Sources/_CollectionsUtilities/Array+WithContiguousStorage Compatibility.swift index 8ece8f6f..2cb6cddb 100644 --- a/Sources/DequeModule/Compatibility.swift +++ b/Sources/_CollectionsUtilities/Array+WithContiguousStorage Compatibility.swift @@ -24,19 +24,26 @@ extension Array { return false } - // SR-14663 was introduced in Swift 5.1. Check if we have a broken stdlib. + // SR-14663 was introduced in Swift 5.1, and it was resolved in Swift 5.5. + // Check if we have a broken stdlib. // The bug is caused by a bogus precondition inside a non-inlinable stdlib // method, so to determine if we're affected, we need to check the currently // running OS version. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) - guard #available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) else { - // The OS is too old to be affected by this bug. + if #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) { + // The OS is too new to be affected by this bug. (>= 5.5 stdlib) return false } - #endif - // FIXME: When a stdlib is released that contains a fix, add a check for it. +// guard #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13, *) else { +// // The OS is too old to be affected by this bug. (< 5.1 stdlib) +// return false +// } return true + #else + // Assume that other platforms aren't affected. + return false + #endif #else // Platforms that don't have an Objective-C runtime don't have verbatim @@ -49,8 +56,8 @@ extension Array { extension Sequence { // An adjusted version of the standard `withContiguousStorageIfAvailable` // method that works around https://bugs.swift.org/browse/SR-14663. - @inlinable - internal func _withContiguousStorageIfAvailable_SR14663( + @inlinable @inline(__always) + public func _withContiguousStorageIfAvailable_SR14663( _ body: (UnsafeBufferPointer) throws -> R ) rethrows -> R? { if Self.self == Array.self && Array._isWCSIABroken() { diff --git a/Sources/_CollectionsUtilities/Integer tricks/FixedWidthInteger+roundUpToPowerOfTwo.swift b/Sources/_CollectionsUtilities/Integer tricks/FixedWidthInteger+roundUpToPowerOfTwo.swift new file mode 100644 index 00000000..518e257e --- /dev/null +++ b/Sources/_CollectionsUtilities/Integer tricks/FixedWidthInteger+roundUpToPowerOfTwo.swift @@ -0,0 +1,21 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +extension FixedWidthInteger { + /// Round up `self` to the nearest power of two, assuming it's representable. + /// Returns 0 if `self` isn't positive. + @inlinable + public func _roundUpToPowerOfTwo() -> Self { + guard self > 0 else { return 0 } + let l = Self.bitWidth - (self &- 1).leadingZeroBitCount + return 1 << l + } +} diff --git a/Sources/_CollectionsUtilities/Integer tricks.swift b/Sources/_CollectionsUtilities/Integer tricks/Integer rank.swift similarity index 64% rename from Sources/_CollectionsUtilities/Integer tricks.swift rename to Sources/_CollectionsUtilities/Integer tricks/Integer rank.swift index f081a87c..bd8e638f 100644 --- a/Sources/_CollectionsUtilities/Integer tricks.swift +++ b/Sources/_CollectionsUtilities/Integer tricks/Integer rank.swift @@ -9,18 +9,8 @@ // //===----------------------------------------------------------------------===// -extension FixedWidthInteger { - /// Round up `self` to the nearest power of two, assuming it's representable. - /// Returns 0 if `self` isn't positive. - @inlinable - public func _roundUpToPowerOfTwo() -> Self { - guard self > 0 else { return 0 } - let l = Self.bitWidth - (self &- 1).leadingZeroBitCount - return 1 << l - } -} -extension UInt32 { +extension FixedWidthInteger { @inlinable @inline(__always) internal var _nonzeroBitCount: Self { Self(truncatingIfNeeded: nonzeroBitCount) @@ -32,14 +22,64 @@ extension UInt32 { let mask: Self = (1 &<< bit) &- 1 return (self & mask).nonzeroBitCount } +} +extension UInt { + @_effects(releasenone) + public func _bit(ranked n: Int) -> UInt? { + // FIXME: Use bit deposit instruction when available (PDEP on Intel). + assert(UInt.bitWidth == 64 || UInt.bitWidth == 32, + "Unsupported UInt bitWidth") + + var shift: Self = 0 + var n = Self(truncatingIfNeeded: n) + + if Self.bitWidth == 64 { + let c32 = (self & 0xFFFFFFFF)._nonzeroBitCount + if n >= c32 { + shift &+= 32 + n &-= c32 + } + } + let c16 = ((self &>> shift) & 0xFFFF)._nonzeroBitCount + if n >= c16 { + shift &+= 16 + n &-= c16 + } + let c8 = ((self &>> shift) & 0xFF)._nonzeroBitCount + if n >= c8 { + shift &+= 8 + n &-= c8 + } + let c4 = ((self &>> shift) & 0xF)._nonzeroBitCount + if n >= c4 { + shift &+= 4 + n &-= c4 + } + let c2 = ((self &>> shift) & 0x3)._nonzeroBitCount + if n >= c2 { + shift &+= 2 + n &-= c2 + } + let c1 = (self &>> shift) & 0x1 + if n >= c1 { + shift &+= 1 + n &-= c1 + } + guard n == 0 && (self &>> shift) & 0x1 == 1 else { return nil } + return shift + } +} + +extension UInt32 { // Returns the position of the `n`th set bit in `self`, i.e., the bit with // rank `n`. @_effects(releasenone) public func _bit(ranked n: Int) -> UInt? { + // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(n >= 0 && n < Self.bitWidth) var shift: Self = 0 - var n: Self = UInt32(truncatingIfNeeded: n) + var n = Self(truncatingIfNeeded: n) let c16 = (self & 0xFFFF)._nonzeroBitCount if n >= c16 { shift = 16 @@ -71,25 +111,14 @@ extension UInt32 { } extension UInt16 { - @inlinable @inline(__always) - internal var _nonzeroBitCount: Self { - Self(truncatingIfNeeded: nonzeroBitCount) - } - - @inlinable @inline(__always) - public func _rank(ofBit bit: UInt) -> Int { - assert(bit < Self.bitWidth) - let mask: Self = (1 &<< bit) &- 1 - return (self & mask).nonzeroBitCount - } - // Returns the position of the `n`th set bit in `self`, i.e., the bit with // rank `n`. @_effects(releasenone) public func _bit(ranked n: Int) -> UInt? { + // FIXME: Use bit deposit instruction when available (PDEP on Intel). assert(n >= 0 && n < Self.bitWidth) var shift: Self = 0 - var n: Self = UInt16(truncatingIfNeeded: n) + var n = Self(truncatingIfNeeded: n) let c8 = ((self &>> shift) & 0xFF)._nonzeroBitCount if n >= c8 { shift &+= 8 diff --git a/Sources/_CollectionsUtilities/Integer tricks/UInt+first and last set bit.swift b/Sources/_CollectionsUtilities/Integer tricks/UInt+first and last set bit.swift new file mode 100644 index 00000000..4a0be877 --- /dev/null +++ b/Sources/_CollectionsUtilities/Integer tricks/UInt+first and last set bit.swift @@ -0,0 +1,25 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +extension UInt { + @inlinable @inline(__always) + public var _firstSetBit: UInt? { + guard self != 0 else { return nil } + let v = UInt.bitWidth &- 1 &- self.leadingZeroBitCount + return UInt(truncatingIfNeeded: v) + } + + @inlinable @inline(__always) + public var _lastSetBit: UInt? { + guard self != 0 else { return nil } + return UInt(truncatingIfNeeded: self.trailingZeroBitCount) + } +} diff --git a/Sources/_CollectionsUtilities/Integer tricks/UInt+reversed.swift b/Sources/_CollectionsUtilities/Integer tricks/UInt+reversed.swift new file mode 100644 index 00000000..4d48c501 --- /dev/null +++ b/Sources/_CollectionsUtilities/Integer tricks/UInt+reversed.swift @@ -0,0 +1,27 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +extension UInt { + @inlinable + public var _reversed: UInt { + // https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel + var shift: UInt = UInt(UInt.bitWidth) + var mask: UInt = ~0; + var result = self + while true { + shift &>>= 1 + guard shift > 0 else { break } + mask ^= mask &<< shift + result = ((result &>> shift) & mask) | ((result &<< shift) & ~mask) + } + return result + } +} diff --git a/Sources/OrderedCollections/Utilities/RandomAccessCollection+Offsets.swift b/Sources/_CollectionsUtilities/RandomAccessCollection+Offsets.swift similarity index 68% rename from Sources/OrderedCollections/Utilities/RandomAccessCollection+Offsets.swift rename to Sources/_CollectionsUtilities/RandomAccessCollection+Offsets.swift index 54a56fa8..c82c8238 100644 --- a/Sources/OrderedCollections/Utilities/RandomAccessCollection+Offsets.swift +++ b/Sources/_CollectionsUtilities/RandomAccessCollection+Offsets.swift @@ -10,21 +10,18 @@ //===----------------------------------------------------------------------===// extension RandomAccessCollection { - @inlinable - @inline(__always) - internal func _index(at offset: Int) -> Index { + @_alwaysEmitIntoClient @inline(__always) + public func _index(at offset: Int) -> Index { index(startIndex, offsetBy: offset) } - @inlinable - @inline(__always) - internal func _offset(of index: Index) -> Int { + @_alwaysEmitIntoClient @inline(__always) + public func _offset(of index: Index) -> Int { distance(from: startIndex, to: index) } - @inlinable - @inline(__always) - internal subscript(_offset offset: Int) -> Element { + @_alwaysEmitIntoClient @inline(__always) + public subscript(_offset offset: Int) -> Element { self[_index(at: offset)] } } diff --git a/Sources/BitCollections/Shared/UnsafeBufferPointer+Utilities.swift b/Sources/_CollectionsUtilities/UnsafeBufferPointer+Extras.swift similarity index 68% rename from Sources/BitCollections/Shared/UnsafeBufferPointer+Utilities.swift rename to Sources/_CollectionsUtilities/UnsafeBufferPointer+Extras.swift index 417f14eb..f65d2aba 100644 --- a/Sources/BitCollections/Shared/UnsafeBufferPointer+Utilities.swift +++ b/Sources/_CollectionsUtilities/UnsafeBufferPointer+Extras.swift @@ -9,19 +9,10 @@ // //===----------------------------------------------------------------------===// -extension Collection { - @inlinable - @inline(__always) - internal func _rebased() -> UnsafeBufferPointer - where Self == UnsafeBufferPointer.SubSequence { - .init(rebasing: self) - } -} - extension UnsafeBufferPointer { @inlinable @inline(__always) - internal func _ptr(at index: Int) -> UnsafePointer { + public func _ptr(at index: Int) -> UnsafePointer { assert(index >= 0 && index < count) return baseAddress.unsafelyUnwrapped + index } diff --git a/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift b/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift index f79bcd03..8a85e59b 100644 --- a/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift +++ b/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift @@ -135,4 +135,3 @@ extension Slice { target.moveInitializeAll(fromContentsOf: source) } } - diff --git a/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+SE-0370.swift b/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+SE-0370.swift index e76f0af1..4b24e94c 100644 --- a/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+SE-0370.swift +++ b/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+SE-0370.swift @@ -64,7 +64,7 @@ extension UnsafeMutableBufferPointer { fromContentsOf source: C ) -> Index where C.Element == Element { - let count = source.withContiguousStorageIfAvailable { + let count = source._withContiguousStorageIfAvailable_SR14663 { guard let sourceAddress = $0.baseAddress, !$0.isEmpty else { return 0 } @@ -366,3 +366,41 @@ extension Slice { base.baseAddress.unsafelyUnwrapped.advanced(by: index).initialize(to: value) } } + +#if swift(<5.8) +extension UnsafeMutableBufferPointer { + /// Updates every element of this buffer's initialized memory. + /// + /// The buffer’s memory must be initialized or its `Element` type + /// must be a trivial type. + /// + /// - Note: All buffer elements must already be initialized. + /// + /// - Parameters: + /// - repeatedValue: The value used when updating this pointer's memory. + @_alwaysEmitIntoClient + public func update(repeating repeatedValue: Element) { + guard let dstBase = baseAddress else { return } + dstBase.update(repeating: repeatedValue, count: count) + } +} +#endif + +#if swift(<5.8) +extension Slice { + /// Updates every element of this buffer slice's initialized memory. + /// + /// The buffer slice’s memory must be initialized or its `Element` + /// must be a trivial type. + /// + /// - Note: All buffer elements must already be initialized. + /// + /// - Parameters: + /// - repeatedValue: The value used when updating this pointer's memory. + @_alwaysEmitIntoClient + public func update(repeating repeatedValue: Element) + where Base == UnsafeMutableBufferPointer { + Base(rebasing: self).update(repeating: repeatedValue) + } +} +#endif diff --git a/Sources/_CollectionsUtilities/UnsafeMutablePointer+SE-0370.swift b/Sources/_CollectionsUtilities/UnsafeMutablePointer+SE-0370.swift new file mode 100644 index 00000000..6f32ffe7 --- /dev/null +++ b/Sources/_CollectionsUtilities/UnsafeMutablePointer+SE-0370.swift @@ -0,0 +1,34 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +#if swift(<5.8) +extension UnsafeMutablePointer { + /// Update this pointer's initialized memory with the specified number of + /// consecutive copies of the given value. + /// + /// The region of memory starting at this pointer and covering `count` + /// instances of the pointer's `Pointee` type must be initialized or + /// `Pointee` must be a trivial type. After calling + /// `update(repeating:count:)`, the region is initialized. + /// + /// - Parameters: + /// - repeatedValue: The value used when updating this pointer's memory. + /// - count: The number of consecutive elements to update. + /// `count` must not be negative. + @_alwaysEmitIntoClient + public func update(repeating repeatedValue: Pointee, count: Int) { + assert(count >= 0, "UnsafeMutablePointer.update(repeating:count:) with negative count") + for i in 0 ..< count { + self[i] = repeatedValue + } + } +} +#endif diff --git a/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/CollectionsBenchmark.xcscheme b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/CollectionsBenchmark.xcscheme new file mode 100644 index 00000000..1b346b0d --- /dev/null +++ b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/CollectionsBenchmark.xcscheme @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +