Merge pull request #196 from lorentey/require-swift-5.5

[1.1.0] Bump minimum required Swift toolchain to 5.5
This commit is contained in:
Karoy Lorentey authored and GitHub committed 2022-10-10 17:30:28 -07:00
commit f6d125e555
28 files changed
+404 -276

No files matched your search

+2 -6
View File
@@ -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: [
+24 -6
View File
@@ -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<Element>`][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<Element>`][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<Key, Value>`][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: [
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
extension BitArray {
internal mutating func _copy(
from range: Range<Int>,
@@ -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
@@ -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))
}
}
}
@@ -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))
}
@@ -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)!
}
}
@@ -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<Element>() -> UnsafeMutableBufferPointer<Element>
where Self == UnsafeMutableBufferPointer<Element>.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)
}
}
+6 -4
View File
@@ -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
}
+8 -6
View File
@@ -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[..<c]._rebased()._initialize(from: segments.first)
target[..<c].initializeAll(fromContentsOf: segments.first)
count += segments.first.count
if let second = segments.second {
target[c ..< c + second.count]._rebased()._initialize(from: second)
target[c ..< c + second.count].initializeAll(fromContentsOf: second)
count += second.count
}
assert(count == source.count)
@@ -122,12 +124,12 @@ extension Deque: Sequence {
_storage.read { source in
let segments = source.segments()
let c1 = Swift.min(segments.first.count, target.count)
target[..<c1]._rebased()._initialize(from: segments.first.prefix(c1)._rebased())
target[..<c1].initializeAll(fromContentsOf: segments.first.prefix(c1))
guard target.count > 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
}
+2
View File
@@ -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.
+2 -2
View File
@@ -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))
}
}
}
@@ -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<Element>() -> UnsafeBufferPointer<Element>
where Self == UnsafeBufferPointer<Element>.SubSequence {
.init(rebasing: self)
}
}
extension Collection {
@inlinable
@inline(__always)
internal func _rebased<Element>() -> UnsafeMutableBufferPointer<Element>
where Self == UnsafeMutableBufferPointer<Element>.SubSequence {
.init(rebasing: self)
}
}
extension UnsafeMutableBufferPointer {
@inlinable
@inline(__always)
internal func _initialize(from source: UnsafeBufferPointer<Element>) {
assert(source.count == count)
guard source.count > 0 else { return }
baseAddress!.initialize(from: source.baseAddress!, count: source.count)
}
@inlinable
@inline(__always)
internal func _initialize<C: Collection>(
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<C: Collection>(
from replacement: C
) where C.Element == Element {
guard self.count > 0 else { return }
self[0 ..< count]._rebased()._deinitializeAll()
_initialize(from: replacement)
}
}
+30 -10
View File
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
@frozen
@usableFromInline
internal struct _UnsafeWrappedBuffer<Element> {
@@ -72,6 +74,24 @@ internal struct _UnsafeMutableWrappedBuffer<Element> {
assert(first.count > 0 || second == nil)
}
@inlinable
@inline(__always)
internal init(
_ first: UnsafeMutableBufferPointer<Element>.SubSequence,
_ second: UnsafeMutableBufferPointer<Element>? = nil
) {
self.init(UnsafeMutableBufferPointer(rebasing: first), second)
}
@inlinable
@inline(__always)
internal init(
_ first: UnsafeMutableBufferPointer<Element>,
_ second: UnsafeMutableBufferPointer<Element>.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[..<wrap])
second._initialize(from: elements[wrap...])
first.initializeAll(fromContentsOf: elements[..<wrap])
second.initializeAll(fromContentsOf: elements[wrap...])
} else {
first._initialize(from: elements)
first.initializeAll(fromContentsOf: elements)
}
}
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
@usableFromInline
internal typealias _UnsafeHashTable = _HashTable.UnsafeHandle
@@ -484,7 +486,7 @@ extension _UnsafeHashTable {
@usableFromInline
internal func clear() {
assertMutable()
_buckets.assign(repeating: 0, count: wordCount)
_buckets.update(repeating: 0, count: wordCount)
}
}
@@ -11,6 +11,8 @@
// The parts of MutableCollection that OrderedSet is able to implement.
import _CollectionsUtilities
extension OrderedSet {
/// Exchanges the values at the specified indices of the set.
///
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
/// A simple bitmap of a fixed number of bits, implementing a sorted set of
/// small nonnegative `Int` values.
///
@@ -184,7 +186,7 @@ extension _UnsafeBitset {
@_effects(releasenone)
internal mutating func clear() {
guard _words.count > 0 else { return }
_words.baseAddress!.assign(repeating: .empty, count: _words.count)
_words.baseAddress!.update(repeating: .empty, count: _words.count)
_count = 0
}
@@ -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<R>(
@inlinable @inline(__always)
public func _withContiguousStorageIfAvailable_SR14663<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
if Self.self == Array<Element>.self && Array<Element>._isWCSIABroken() {
@@ -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
}
}
@@ -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
@@ -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)
}
}
@@ -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
}
}
@@ -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)]
}
}
@@ -9,19 +9,10 @@
//
//===----------------------------------------------------------------------===//
extension Collection {
@inlinable
@inline(__always)
internal func _rebased<Element>() -> UnsafeBufferPointer<Element>
where Self == UnsafeBufferPointer<Element>.SubSequence {
.init(rebasing: self)
}
}
extension UnsafeBufferPointer {
@inlinable
@inline(__always)
internal func _ptr(at index: Int) -> UnsafePointer<Element> {
public func _ptr(at index: Int) -> UnsafePointer<Element> {
assert(index >= 0 && index < count)
return baseAddress.unsafelyUnwrapped + index
}
@@ -135,4 +135,3 @@ extension Slice {
target.moveInitializeAll(fromContentsOf: source)
}
}
@@ -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<Element>(repeating repeatedValue: Element)
where Base == UnsafeMutableBufferPointer<Element> {
Base(rebasing: self).update(repeating: repeatedValue)
}
}
#endif
@@ -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
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1410"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CollectionsBenchmark"
BuildableName = "CollectionsBenchmark"
BlueprintName = "CollectionsBenchmark"
ReferencedContainer = "container:../../swift-collections-benchmark">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CollectionsBenchmarkTests"
BuildableName = "CollectionsBenchmarkTests"
BlueprintName = "CollectionsBenchmarkTests"
ReferencedContainer = "container:../../swift-collections-benchmark">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "CollectionsBenchmark"
BuildableName = "CollectionsBenchmark"
BlueprintName = "CollectionsBenchmark"
ReferencedContainer = "container:../../swift-collections-benchmark">
</BuildableReference>
</MacroExpansion>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
<InstallAction
buildConfiguration = "Release">
</InstallAction>
</Scheme>