Adopt package access modifier and get rid of gybbing

This commit is contained in:
Karoy Lorentey committed 2025-09-29 11:56:14 -07:00
1 parent 7b847a3b70
commit bb8d566833
42 files changed
+261 -5325

No files matched your search

@@ -37,7 +37,7 @@ extension _UnsafeBitSet {
extension _UnsafeBitSet {
@inlinable
public mutating func combineSharedPrefix(
internal mutating func combineSharedPrefix(
with other: Self,
using function: (inout _Word, _Word) -> Void
) {
@@ -51,7 +51,7 @@ extension _UnsafeBitSet {
extension _UnsafeBitSet {
@_effects(releasenone)
public mutating func formUnion(_ range: Range<UInt>) {
internal mutating func formUnion(_ range: Range<UInt>) {
ensureMutable()
let l = Index(range.lowerBound)
let u = Index(range.upperBound)
@@ -73,7 +73,7 @@ extension _UnsafeBitSet {
}
@_effects(releasenone)
public mutating func formIntersection(_ range: Range<UInt>) {
internal mutating func formIntersection(_ range: Range<UInt>) {
ensureMutable()
let l = Index(Swift.min(range.lowerBound, capacity))
let u = Index(Swift.min(range.upperBound, capacity))
@@ -98,7 +98,7 @@ extension _UnsafeBitSet {
}
@_effects(releasenone)
public mutating func formSymmetricDifference(_ range: Range<UInt>) {
internal mutating func formSymmetricDifference(_ range: Range<UInt>) {
ensureMutable()
let l = Index(range.lowerBound)
let u = Index(range.upperBound)
@@ -121,7 +121,7 @@ extension _UnsafeBitSet {
}
@_effects(releasenone)
public mutating func subtract(_ range: Range<UInt>) {
internal mutating func subtract(_ range: Range<UInt>) {
ensureMutable()
let l = Index(Swift.min(range.lowerBound, capacity))
let u = Index(Swift.min(range.upperBound, capacity))
@@ -141,7 +141,7 @@ extension _UnsafeBitSet {
}
@_effects(releasenone)
public func isDisjoint(with range: Range<UInt>) -> Bool {
internal func isDisjoint(with range: Range<UInt>) -> Bool {
if self.isEmpty { return true }
let lower = Index(Swift.min(range.lowerBound, capacity))
let upper = Index(Swift.min(range.upperBound, capacity))
@@ -167,7 +167,7 @@ extension _UnsafeBitSet {
}
@_effects(releasenone)
public func isSubset(of range: Range<UInt>) -> Bool {
internal func isSubset(of range: Range<UInt>) -> Bool {
guard !range.isEmpty else { return isEmpty }
guard !_words.isEmpty else { return true }
let r = range.clamped(to: 0 ..< UInt(capacity))
@@ -193,7 +193,7 @@ extension _UnsafeBitSet {
}
@_effects(releasenone)
public func isSuperset(of range: Range<UInt>) -> Bool {
internal func isSuperset(of range: Range<UInt>) -> Bool {
guard !range.isEmpty else { return true }
let r = range.clamped(to: 0 ..< UInt(capacity))
guard r == range else { return false }
@@ -218,7 +218,7 @@ extension _UnsafeBitSet {
}
@_effects(releasenone)
public func isEqualSet(to range: Range<UInt>) -> Bool {
internal func isEqualSet(to range: Range<UInt>) -> Bool {
if range.isEmpty { return self.isEmpty }
let r = range.clamped(to: 0 ..< UInt(capacity))
guard r == range else { return false }
@@ -21,21 +21,21 @@ else()
endif()
target_sources(${module_name} PRIVATE
"autogenerated/Debugging.swift"
"autogenerated/Descriptions.swift"
"autogenerated/LifetimeOverride.swift"
"autogenerated/RandomAccessCollection+Offsets.swift"
"autogenerated/UnsafeBufferPointer+Extras.swift"
"autogenerated/UnsafeMutableBufferPointer+Extras.swift"
"autogenerated/UnsafeRawBufferPointer+Extras.swift"
"autogenerated/UnsafeMutableRawBufferPointer+Extras.swift"
"IntegerTricks/autogenerated/FixedWidthInteger+roundUpToPowerOfTwo.swift"
"IntegerTricks/autogenerated/Integer rank.swift"
"IntegerTricks/autogenerated/UInt+first and last set bit.swift"
"IntegerTricks/autogenerated/UInt+reversed.swift"
"UnsafeBitSet/autogenerated/_UnsafeBitSet+Index.swift"
"UnsafeBitSet/autogenerated/_UnsafeBitSet+_Word.swift"
"UnsafeBitSet/autogenerated/_UnsafeBitSet.swift"
"Debugging.swift"
"Descriptions.swift"
"LifetimeOverride.swift"
"RandomAccessCollection+Offsets.swift"
"UnsafeBufferPointer+Extras.swift"
"UnsafeMutableBufferPointer+Extras.swift"
"UnsafeRawBufferPointer+Extras.swift"
"UnsafeMutableRawBufferPointer+Extras.swift"
"IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift"
"IntegerTricks/Integer rank.swift"
"IntegerTricks/UInt+first and last set bit.swift"
"IntegerTricks/UInt+reversed.swift"
"UnsafeBitSet/_UnsafeBitSet+Index.swift"
"UnsafeBitSet/_UnsafeBitSet+_Word.swift"
"UnsafeBitSet/_UnsafeBitSet.swift"
"_SortedCollection.swift"
"_UniqueCollection.swift"
)
@@ -2,20 +2,13 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
// Copyright (c) 2022 - 2025 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
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
/// True if consistency checking is enabled in the implementation of the
/// Swift Collections package, false otherwise.
///
@@ -23,12 +16,10 @@ ${visibility_boilerplate(modifier)}
/// returns true -- for example, operations that are documented to take
/// O(1) time might take O(*n*) time, or worse.
@inlinable @inline(__always)
${modifier} var _isCollectionsInternalCheckingEnabled: Bool {
package var _isCollectionsInternalCheckingEnabled: Bool {
#if COLLECTIONS_INTERNAL_CHECKS
return true
#else
return false
#endif
}
% end
${visibility_boilerplate("end")}
@@ -2,40 +2,32 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
// Copyright (c) 2022 - 2025 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
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func _addressString(for pointer: UnsafeRawPointer) -> String {
@usableFromInline
package func _addressString(for pointer: UnsafeRawPointer) -> String {
let address = UInt(bitPattern: pointer)
return "0x\(String(address, radix: 16))"
}
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func _addressString(for object: AnyObject) -> String {
@usableFromInline
package func _addressString(for object: AnyObject) -> String {
_addressString(for: Unmanaged.passUnretained(object).toOpaque())
}
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func _addressString<T: AnyObject>(for object: Unmanaged<T>) -> String {
@usableFromInline
package func _addressString<T: AnyObject>(for object: Unmanaged<T>) -> String {
_addressString(for: object.toOpaque())
}
#if !$Embedded
@inlinable
${modifier} func _arrayDescription<C: Collection>(
package func _arrayDescription<C: Collection>(
for elements: C
) -> String {
var result = "["
@@ -53,7 +45,7 @@ ${modifier} func _arrayDescription<C: Collection>(
}
@inlinable
${modifier} func _dictionaryDescription<Key, Value, C: Collection>(
package func _dictionaryDescription<Key, Value, C: Collection>(
for elements: C
) -> String where C.Element == (key: Key, value: Value) {
guard !elements.isEmpty else { return "[:]" }
@@ -73,5 +65,3 @@ ${modifier} func _dictionaryDescription<Key, Value, C: Collection>(
return result
}
#endif
% end
${visibility_boilerplate("end")}
@@ -2,29 +2,20 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
// Copyright (c) 2022 - 2025 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
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension FixedWidthInteger {
/// Round up `self` to the nearest power of two, assuming it's representable.
/// Returns 0 if `self` isn't positive.
@inlinable
${modifier} func _roundUpToPowerOfTwo() -> Self {
package func _roundUpToPowerOfTwo() -> Self {
guard self > 0 else { return 0 }
let l = Self.bitWidth - (self &- 1).leadingZeroBitCount
return 1 << l
}
}
% end
${visibility_boilerplate("end")}
@@ -9,13 +9,6 @@
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension FixedWidthInteger {
@inlinable @inline(__always)
internal var _nonzeroBitCount: Self {
@@ -23,7 +16,7 @@ extension FixedWidthInteger {
}
@inlinable @inline(__always)
${modifier} func _rank(ofBit bit: UInt) -> Int {
package func _rank(ofBit bit: UInt) -> Int {
assert(bit < Self.bitWidth)
let mask: Self = (1 &<< bit) &- 1
return (self & mask).nonzeroBitCount
@@ -32,8 +25,8 @@ extension FixedWidthInteger {
extension UInt {
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func _bit(ranked n: Int) -> UInt? {
@usableFromInline
package 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")
@@ -85,8 +78,8 @@ extension UInt32 {
// Returns the position of the `n`th set bit in `self`, i.e., the bit with
// rank `n`.
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func _bit(ranked n: Int) -> UInt? {
@usableFromInline
package 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
@@ -125,8 +118,8 @@ extension UInt16 {
// Returns the position of the `n`th set bit in `self`, i.e., the bit with
// rank `n`.
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func _bit(ranked n: Int) -> UInt? {
@usableFromInline
package 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
@@ -155,5 +148,3 @@ extension UInt16 {
return UInt(truncatingIfNeeded: shift)
}
}
% end
${visibility_boilerplate("end")}
@@ -2,33 +2,24 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
// Copyright (c) 2022 - 2025 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
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension UInt {
@inlinable @inline(__always)
${modifier} var _firstSetBit: UInt? {
package var _firstSetBit: UInt? {
guard self != 0 else { return nil }
let v = UInt.bitWidth &- 1 &- self.leadingZeroBitCount
return UInt(truncatingIfNeeded: v)
}
@inlinable @inline(__always)
${modifier} var _lastSetBit: UInt? {
package var _lastSetBit: UInt? {
guard self != 0 else { return nil }
return UInt(truncatingIfNeeded: self.trailingZeroBitCount)
}
}
% end
${visibility_boilerplate("end")}
@@ -2,23 +2,16 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors
// Copyright (c) 2022 - 2025 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
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension UInt {
@inlinable
${modifier} var _reversed: UInt {
package var _reversed: UInt {
// https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
var shift: UInt = UInt(UInt.bitWidth)
var mask: UInt = ~0;
@@ -32,5 +25,3 @@ extension UInt {
return result
}
}
% end
${visibility_boilerplate("end")}
@@ -1,46 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2024 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension FixedWidthInteger {
/// Round up `self` to the nearest power of two, assuming it's representable.
/// Returns 0 if `self` isn't positive.
@inlinable
internal func _roundUpToPowerOfTwo() -> Self {
guard self > 0 else { return 0 }
let l = Self.bitWidth - (self &- 1).leadingZeroBitCount
return 1 << l
}
}
#else // !COLLECTIONS_SINGLE_MODULE
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
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -1,304 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2024 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension FixedWidthInteger {
@inlinable @inline(__always)
internal var _nonzeroBitCount: Self {
Self(truncatingIfNeeded: nonzeroBitCount)
}
@inlinable @inline(__always)
internal func _rank(ofBit bit: UInt) -> Int {
assert(bit < Self.bitWidth)
let mask: Self = (1 &<< bit) &- 1
return (self & mask).nonzeroBitCount
}
}
extension UInt {
@_effects(releasenone)
@usableFromInline
internal 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 MemoryLayout<UInt>.size == 8 {
let c32 = (self & 0xFFFFFFFF)._nonzeroBitCount
if n >= c32 {
shift &+= 32
n &-= c32
}
} else {
assert(MemoryLayout<Self>.size == 4, "Unknown platform")
}
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)
@usableFromInline
internal 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(truncatingIfNeeded: n)
let c16 = (self & 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 UInt(truncatingIfNeeded: shift)
}
}
extension UInt16 {
// Returns the position of the `n`th set bit in `self`, i.e., the bit with
// rank `n`.
@_effects(releasenone)
@usableFromInline
internal 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(truncatingIfNeeded: n)
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 UInt(truncatingIfNeeded: shift)
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension FixedWidthInteger {
@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
}
}
extension UInt {
@_effects(releasenone)
//@usableFromInline
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 MemoryLayout<UInt>.size == 8 {
let c32 = (self & 0xFFFFFFFF)._nonzeroBitCount
if n >= c32 {
shift &+= 32
n &-= c32
}
} else {
assert(MemoryLayout<Self>.size == 4, "Unknown platform")
}
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)
//@usableFromInline
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(truncatingIfNeeded: n)
let c16 = (self & 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 UInt(truncatingIfNeeded: shift)
}
}
extension UInt16 {
// Returns the position of the `n`th set bit in `self`, i.e., the bit with
// rank `n`.
@_effects(releasenone)
//@usableFromInline
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(truncatingIfNeeded: n)
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 UInt(truncatingIfNeeded: shift)
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -1,54 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2024 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension UInt {
@inlinable @inline(__always)
internal var _firstSetBit: UInt? {
guard self != 0 else { return nil }
let v = UInt.bitWidth &- 1 &- self.leadingZeroBitCount
return UInt(truncatingIfNeeded: v)
}
@inlinable @inline(__always)
internal var _lastSetBit: UInt? {
guard self != 0 else { return nil }
return UInt(truncatingIfNeeded: self.trailingZeroBitCount)
}
}
#else // !COLLECTIONS_SINGLE_MODULE
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)
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -1,58 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2024 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension UInt {
@inlinable
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
}
}
#else // !COLLECTIONS_SINGLE_MODULE
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
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -10,14 +10,7 @@
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
#if compiler(>=6.2)
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with an immortal lifetime.
@unsafe
@@ -25,7 +18,7 @@ ${visibility_boilerplate(modifier)}
@_alwaysEmitIntoClient
@_transparent
@_lifetime(immortal)
${modifier} func _unsafeImmortalize<T: ~Copyable & ~Escapable>(
package func _unsafeImmortalize<T: ~Copyable & ~Escapable>(
_ dependent: consuming T
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
@@ -41,7 +34,7 @@ ${modifier} func _unsafeImmortalize<T: ~Copyable & ~Escapable>(
@_alwaysEmitIntoClient
@_transparent
@_lifetime(borrow source)
${modifier} func _overrideLifetime<
package func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, borrowing source: borrowing U
@@ -59,7 +52,7 @@ ${modifier} func _overrideLifetime<
@_alwaysEmitIntoClient
@_transparent
@_lifetime(copy source)
${modifier} func _overrideLifetime<
package func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, copying source: borrowing U
@@ -77,7 +70,7 @@ ${modifier} func _overrideLifetime<
@_alwaysEmitIntoClient
@_transparent
@_lifetime(&source)
${modifier} func _overrideLifetime<
package func _overrideLifetime<
T: ~Copyable & ~Escapable,
U: ~Copyable & ~Escapable
>(
@@ -88,6 +81,4 @@ ${modifier} func _overrideLifetime<
// should be expressed by a builtin that is hidden within the function body.
dependent
}
% end
${visibility_boilerplate("end")}
#endif
@@ -2,35 +2,26 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
// Copyright (c) 2021 - 2025 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
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension RandomAccessCollection {
@_alwaysEmitIntoClient @inline(__always)
${modifier} func _index(at offset: Int) -> Index {
package func _index(at offset: Int) -> Index {
index(startIndex, offsetBy: offset)
}
@_alwaysEmitIntoClient @inline(__always)
${modifier} func _offset(of index: Index) -> Int {
package func _offset(of index: Index) -> Int {
distance(from: startIndex, to: index)
}
@_alwaysEmitIntoClient @inline(__always)
${modifier} subscript(_offset offset: Int) -> Element {
package subscript(_offset offset: Int) -> Element {
self[_index(at: offset)]
}
}
% end
${visibility_boilerplate("end")}
@@ -2,41 +2,35 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
// Copyright (c) 2021 - 2025 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
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension _UnsafeBitSet {
${"@frozen" if modifier == "public" else "@frozen @usableFromInline"}
${modifier} struct Index: Comparable, Hashable {
@frozen
@usableFromInline
package struct Index: Comparable, Hashable {
@usableFromInline
internal typealias _Word = _UnsafeBitSet._Word
${"@usableFromInline" if modifier != "public" else ""}
${modifier} var value: UInt
@usableFromInline
package var value: UInt
@inlinable
${modifier} init(_ value: UInt) {
package init(_ value: UInt) {
self.value = value
}
@inlinable
${modifier} init(_ value: Int) {
package init(_ value: Int) {
self.value = UInt(value)
}
@inlinable
${modifier} init(word: Int, bit: UInt) {
package init(word: Int, bit: UInt) {
assert(word >= 0 && word <= Int.max / _Word.capacity)
assert(bit < _Word.capacity)
self.value = UInt(word &* _Word.capacity) &+ bit
@@ -46,24 +40,24 @@ extension _UnsafeBitSet {
extension _UnsafeBitSet.Index {
@inlinable
${modifier} var word: Int {
package var word: Int {
// Note: We perform on UInts to get faster unsigned math (shifts).
Int(truncatingIfNeeded: value / UInt(bitPattern: _Word.capacity))
}
@inlinable
${modifier} var bit: UInt {
package var bit: UInt {
// Note: We perform on UInts to get faster unsigned math (masking).
value % UInt(bitPattern: _Word.capacity)
}
@inlinable
${modifier} var split: (word: Int, bit: UInt) {
package var split: (word: Int, bit: UInt) {
(word, bit)
}
@inlinable
${modifier} var endSplit: (word: Int, bit: UInt) {
package var endSplit: (word: Int, bit: UInt) {
let w = word
let b = bit
if w > 0, b == 0 { return (w &- 1, UInt(_Word.capacity)) }
@@ -71,17 +65,17 @@ extension _UnsafeBitSet.Index {
}
@inlinable
${modifier} static func ==(left: Self, right: Self) -> Bool {
package static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
@inlinable
${modifier} static func <(left: Self, right: Self) -> Bool {
package static func <(left: Self, right: Self) -> Bool {
left.value < right.value
}
@inlinable
${modifier} func hash(into hasher: inout Hasher) {
package func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
@@ -95,5 +89,3 @@ extension _UnsafeBitSet.Index {
Self(value - 1)
}
}
% end
${visibility_boilerplate("end")}
@@ -2,43 +2,36 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
// Copyright (c) 2021 - 2025 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
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension _UnsafeBitSet {
${"@frozen" if modifier == "public" else "@frozen @usableFromInline"}
${modifier} struct _Word {
${"@usableFromInline" if modifier != "public" else ""}
${modifier} var value: UInt
@frozen
@usableFromInline
package struct _Word {
@usableFromInline
package var value: UInt
@inlinable
@inline(__always)
${modifier} init(_ value: UInt) {
package init(_ value: UInt) {
self.value = value
}
@inlinable
@inline(__always)
${modifier} init(upTo bit: UInt) {
package init(upTo bit: UInt) {
assert(bit <= _Word.capacity)
self.init((1 << bit) &- 1)
}
@inlinable
@inline(__always)
${modifier} init(from start: UInt, to end: UInt) {
package init(from start: UInt, to end: UInt) {
assert(start <= end && end <= _Word.capacity)
self = Self(upTo: end).symmetricDifference(Self(upTo: start))
}
@@ -46,8 +39,8 @@ extension _UnsafeBitSet {
}
extension _UnsafeBitSet._Word: CustomStringConvertible {
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} var description: String {
@usableFromInline
package var description: String {
String(value, radix: 16)
}
}
@@ -89,7 +82,7 @@ extension _UnsafeBitSet._Word {
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
${modifier} static func wordCount(forBitCount count: UInt) -> Int {
package static func wordCount(forBitCount count: UInt) -> Int {
// Note: We perform on UInts to get faster unsigned math (shifts).
let width = UInt(bitPattern: Self.capacity)
return Int(bitPattern: (count + width - 1) / width)
@@ -99,51 +92,51 @@ extension _UnsafeBitSet._Word {
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
${modifier} static var capacity: Int {
package static var capacity: Int {
return UInt.bitWidth
}
@inlinable
@inline(__always)
${modifier} var count: Int {
package var count: Int {
value.nonzeroBitCount
}
@inlinable
@inline(__always)
${modifier} var isEmpty: Bool {
package var isEmpty: Bool {
value == 0
}
@inlinable
@inline(__always)
${modifier} var isFull: Bool {
package var isFull: Bool {
value == UInt.max
}
@inlinable
@inline(__always)
${modifier} func contains(_ bit: UInt) -> Bool {
package func contains(_ bit: UInt) -> Bool {
assert(bit >= 0 && bit < UInt.bitWidth)
return value & (1 &<< bit) != 0
}
@inlinable
@inline(__always)
${modifier} var firstMember: UInt? {
package var firstMember: UInt? {
value._lastSetBit
}
@inlinable
@inline(__always)
${modifier} var lastMember: UInt? {
package var lastMember: UInt? {
value._firstSetBit
}
@inlinable
@inline(__always)
@discardableResult
${modifier} mutating func insert(_ bit: UInt) -> Bool {
package mutating func insert(_ bit: UInt) -> Bool {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
let inserted = value & mask == 0
@@ -154,7 +147,7 @@ extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
@discardableResult
${modifier} mutating func remove(_ bit: UInt) -> Bool {
package mutating func remove(_ bit: UInt) -> Bool {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
let removed = (value & mask) != 0
@@ -164,7 +157,7 @@ extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
${modifier} mutating func update(_ bit: UInt, to value: Bool) {
package mutating func update(_ bit: UInt, to value: Bool) {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
if value {
@@ -213,12 +206,12 @@ extension _UnsafeBitSet._Word {
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
${modifier} static var empty: Self {
package static var empty: Self {
Self(0)
}
@inline(__always)
${modifier} static var allBits: Self {
package static var allBits: Self {
Self(UInt.max)
}
}
@@ -229,14 +222,14 @@ extension _UnsafeBitSet._Word {
// iterator, not the original word.
extension _UnsafeBitSet._Word: Sequence, IteratorProtocol {
@inlinable @inline(__always)
${modifier} var underestimatedCount: Int {
package var underestimatedCount: Int {
count
}
/// Return the index of the lowest set bit in this word,
/// and also destructively clear it.
@inlinable
${modifier} mutating func next() -> UInt? {
package mutating func next() -> UInt? {
guard value != 0 else { return nil }
let bit = UInt(truncatingIfNeeded: value.trailingZeroBitCount)
value &= value &- 1 // Clear lowest nonzero bit.
@@ -246,66 +239,66 @@ extension _UnsafeBitSet._Word: Sequence, IteratorProtocol {
extension _UnsafeBitSet._Word: Equatable {
@inlinable
${modifier} static func ==(left: Self, right: Self) -> Bool {
package static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
}
extension _UnsafeBitSet._Word: Hashable {
@inlinable
${modifier} func hash(into hasher: inout Hasher) {
package func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
extension _UnsafeBitSet._Word {
@inlinable @inline(__always)
${modifier} func complement() -> Self {
package func complement() -> Self {
Self(~self.value)
}
@inlinable @inline(__always)
${modifier} mutating func formComplement() {
package mutating func formComplement() {
self.value = ~self.value
}
@inlinable @inline(__always)
${modifier} func union(_ other: Self) -> Self {
package func union(_ other: Self) -> Self {
Self(self.value | other.value)
}
@inlinable @inline(__always)
${modifier} mutating func formUnion(_ other: Self) {
package mutating func formUnion(_ other: Self) {
self.value |= other.value
}
@inlinable @inline(__always)
${modifier} func intersection(_ other: Self) -> Self {
package func intersection(_ other: Self) -> Self {
Self(self.value & other.value)
}
@inlinable @inline(__always)
${modifier} mutating func formIntersection(_ other: Self) {
package mutating func formIntersection(_ other: Self) {
self.value &= other.value
}
@inlinable @inline(__always)
${modifier} func symmetricDifference(_ other: Self) -> Self {
package func symmetricDifference(_ other: Self) -> Self {
Self(self.value ^ other.value)
}
@inlinable @inline(__always)
${modifier} mutating func formSymmetricDifference(_ other: Self) {
package mutating func formSymmetricDifference(_ other: Self) {
self.value ^= other.value
}
@inlinable @inline(__always)
${modifier} func subtracting(_ other: Self) -> Self {
package func subtracting(_ other: Self) -> Self {
Self(self.value & ~other.value)
}
@inlinable @inline(__always)
${modifier} mutating func subtract(_ other: Self) {
package mutating func subtract(_ other: Self) {
self.value &= ~other.value
}
}
@@ -313,17 +306,15 @@ extension _UnsafeBitSet._Word {
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
${modifier} func shiftedDown(by shift: UInt) -> Self {
package func shiftedDown(by shift: UInt) -> Self {
assert(shift >= 0 && shift < Self.capacity)
return Self(self.value &>> shift)
}
@inlinable
@inline(__always)
${modifier} func shiftedUp(by shift: UInt) -> Self {
package func shiftedUp(by shift: UInt) -> Self {
assert(shift >= 0 && shift < Self.capacity)
return Self(self.value &<< shift)
}
}
% end
${visibility_boilerplate("end")}
@@ -2,27 +2,21 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
// Copyright (c) 2021 - 2025 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
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
/// An unsafe-unowned bitset view over `UInt` storage, providing bit set
/// primitives.
${"@frozen" if modifier == "public" else "@frozen @usableFromInline"}
${modifier} struct _UnsafeBitSet {
@frozen
@usableFromInline
package struct _UnsafeBitSet {
/// An unsafe-unowned storage view.
${"@usableFromInline" if modifier != "public" else ""}
${modifier} let _words: UnsafeBufferPointer<_Word>
@usableFromInline
package let _words: UnsafeBufferPointer<_Word>
#if DEBUG
/// True when this handle does not support table mutations.
@@ -33,7 +27,7 @@ ${modifier} struct _UnsafeBitSet {
@inlinable
@inline(__always)
${modifier} func ensureMutable() {
package func ensureMutable() {
#if DEBUG
assert(_mutable)
#endif
@@ -41,14 +35,14 @@ ${modifier} struct _UnsafeBitSet {
@inlinable
@inline(__always)
${modifier} var _mutableWords: UnsafeMutableBufferPointer<_Word> {
package var _mutableWords: UnsafeMutableBufferPointer<_Word> {
ensureMutable()
return UnsafeMutableBufferPointer(mutating: _words)
}
@inlinable
@inline(__always)
${modifier} init(
package init(
words: UnsafeBufferPointer<_Word>,
mutable: Bool
) {
@@ -61,7 +55,7 @@ ${modifier} struct _UnsafeBitSet {
@inlinable
@inline(__always)
${modifier} init(
package init(
words: UnsafeMutableBufferPointer<_Word>,
mutable: Bool
) {
@@ -72,7 +66,7 @@ ${modifier} struct _UnsafeBitSet {
extension _UnsafeBitSet {
@inlinable
@inline(__always)
${modifier} var wordCount: Int {
package var wordCount: Int {
_words.count
}
}
@@ -80,7 +74,7 @@ extension _UnsafeBitSet {
extension _UnsafeBitSet {
@inlinable
@inline(__always)
${modifier} static func withTemporaryBitSet<R>(
package static func withTemporaryBitSet<R>(
capacity: Int,
run body: (inout _UnsafeBitSet) throws -> R
) rethrows -> R {
@@ -90,7 +84,7 @@ extension _UnsafeBitSet {
@inlinable
@inline(__always)
${modifier} static func withTemporaryBitSet<R>(
package static func withTemporaryBitSet<R>(
wordCount: Int,
run body: (inout Self) throws -> R
) rethrows -> R {
@@ -130,12 +124,12 @@ extension _UnsafeBitSet {
extension _UnsafeBitSet {
@_effects(readnone)
@inlinable @inline(__always)
${modifier} static func wordCount(forCapacity capacity: UInt) -> Int {
package static func wordCount(forCapacity capacity: UInt) -> Int {
_Word.wordCount(forBitCount: capacity)
}
@inlinable @inline(__always)
${modifier} var capacity: UInt {
package var capacity: UInt {
UInt(wordCount &* _Word.capacity)
}
@@ -146,17 +140,17 @@ extension _UnsafeBitSet {
@_effects(releasenone)
@inline(__always)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func contains(_ element: UInt) -> Bool {
@usableFromInline
package func contains(_ element: UInt) -> Bool {
let (word, bit) = Index(element).split
guard word < wordCount else { return false }
return _words[word].contains(bit)
}
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
@usableFromInline
@discardableResult
${modifier} mutating func insert(_ element: UInt) -> Bool {
package mutating func insert(_ element: UInt) -> Bool {
ensureMutable()
assert(isWithinBounds(element))
let index = Index(element)
@@ -164,9 +158,9 @@ extension _UnsafeBitSet {
}
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
@usableFromInline
@discardableResult
${modifier} mutating func remove(_ element: UInt) -> Bool {
package mutating func remove(_ element: UInt) -> Bool {
ensureMutable()
let index = Index(element)
if index.word >= _words.count { return false }
@@ -174,8 +168,8 @@ extension _UnsafeBitSet {
}
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} mutating func update(_ member: UInt, to newValue: Bool) -> Bool {
@usableFromInline
package mutating func update(_ member: UInt, to newValue: Bool) -> Bool {
ensureMutable()
let (w, b) = Index(member).split
_mutableWords[w].update(b, to: newValue)
@@ -183,8 +177,8 @@ extension _UnsafeBitSet {
}
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} mutating func insertAll(upTo max: UInt) {
@usableFromInline
package mutating func insertAll(upTo max: UInt) {
assert(max <= capacity)
guard max > 0 else { return }
let (w, b) = Index(max).split
@@ -197,50 +191,51 @@ extension _UnsafeBitSet {
}
@_alwaysEmitIntoClient
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
@usableFromInline
@inline(__always)
@discardableResult
${modifier} mutating func insert(_ element: Int) -> Bool {
package mutating func insert(_ element: Int) -> Bool {
precondition(element >= 0)
return insert(UInt(bitPattern: element))
}
@_alwaysEmitIntoClient
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
@usableFromInline
@inline(__always)
@discardableResult
${modifier} mutating func remove(_ element: Int) -> Bool {
package mutating func remove(_ element: Int) -> Bool {
guard element >= 0 else { return false }
return remove(UInt(bitPattern: element))
}
@_alwaysEmitIntoClient
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
@usableFromInline
@inline(__always)
${modifier} mutating func insertAll(upTo max: Int) {
package mutating func insertAll(upTo max: Int) {
precondition(max >= 0)
return insertAll(upTo: UInt(bitPattern: max))
}
}
extension _UnsafeBitSet: Sequence {
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} typealias Element = UInt
@usableFromInline
package typealias Element = UInt
@inlinable
@inline(__always)
${modifier} var underestimatedCount: Int {
package var underestimatedCount: Int {
count // FIXME: really?
}
@inlinable
@inline(__always)
${modifier} func makeIterator() -> Iterator {
package func makeIterator() -> Iterator {
return Iterator(self)
}
${"@frozen" if modifier == "public" else "@usableFromInline @frozen"}
${modifier} struct Iterator: IteratorProtocol {
@frozen
@usableFromInline
package struct Iterator: IteratorProtocol {
@usableFromInline
internal let _bitset: _UnsafeBitSet
@@ -258,8 +253,8 @@ extension _UnsafeBitSet: Sequence {
}
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} mutating func next() -> UInt? {
@usableFromInline
package mutating func next() -> UInt? {
if let bit = _word.next() {
return Index(word: _index, bit: bit).value
}
@@ -278,36 +273,36 @@ extension _UnsafeBitSet: Sequence {
extension _UnsafeBitSet: BidirectionalCollection {
@inlinable
@inline(__always)
${modifier} var count: Int {
package var count: Int {
_words.reduce(0) { $0 + $1.count }
}
@inlinable
@inline(__always)
${modifier} var isEmpty: Bool {
package var isEmpty: Bool {
_words.firstIndex(where: { !$0.isEmpty }) == nil
}
@inlinable
${modifier} var startIndex: Index {
package var startIndex: Index {
let word = _words.firstIndex { !$0.isEmpty }
guard let word = word else { return endIndex }
return Index(word: word, bit: _words[word].firstMember!)
}
@inlinable
${modifier} var endIndex: Index {
package var endIndex: Index {
Index(word: wordCount, bit: 0)
}
@inlinable
${modifier} subscript(position: Index) -> UInt {
package subscript(position: Index) -> UInt {
position.value
}
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func index(after index: Index) -> Index {
@usableFromInline
package func index(after index: Index) -> Index {
precondition(index < endIndex, "Index out of bounds")
var word = index.word
var w = _words[word]
@@ -323,8 +318,8 @@ extension _UnsafeBitSet: BidirectionalCollection {
}
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func index(before index: Index) -> Index {
@usableFromInline
package func index(before index: Index) -> Index {
precondition(index <= endIndex, "Index out of bounds")
var word = index.word
var w: _Word
@@ -343,8 +338,8 @@ extension _UnsafeBitSet: BidirectionalCollection {
}
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func distance(from start: Index, to end: Index) -> Int {
@usableFromInline
package func distance(from start: Index, to end: Index) -> Int {
precondition(start <= endIndex && end <= endIndex, "Index out of bounds")
let isNegative = end < start
let (start, end) = (Swift.min(start, end), Swift.max(start, end))
@@ -375,8 +370,8 @@ extension _UnsafeBitSet: BidirectionalCollection {
}
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func index(_ i: Index, offsetBy distance: Int) -> Index {
@usableFromInline
package func index(_ i: Index, offsetBy distance: Int) -> Index {
precondition(i <= endIndex, "Index out of bounds")
precondition(i == endIndex || contains(i.value), "Invalid index")
guard distance != 0 else { return i }
@@ -416,8 +411,8 @@ extension _UnsafeBitSet: BidirectionalCollection {
}
@_effects(releasenone)
${"@usableFromInline" if modifier != "public" else "//@usableFromInline" }
${modifier} func index(
@usableFromInline
package func index(
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
) -> Index? {
precondition(i <= endIndex && limit <= endIndex, "Index out of bounds")
@@ -469,5 +464,3 @@ extension _UnsafeBitSet: BidirectionalCollection {
return nil
}
}
% end
${visibility_boilerplate("end")}
@@ -1,184 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2024 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension _UnsafeBitSet {
@frozen @usableFromInline
internal struct Index: Comparable, Hashable {
@usableFromInline
internal typealias _Word = _UnsafeBitSet._Word
@usableFromInline
internal var value: UInt
@inlinable
internal init(_ value: UInt) {
self.value = value
}
@inlinable
internal init(_ value: Int) {
self.value = UInt(value)
}
@inlinable
internal init(word: Int, bit: UInt) {
assert(word >= 0 && word <= Int.max / _Word.capacity)
assert(bit < _Word.capacity)
self.value = UInt(word &* _Word.capacity) &+ bit
}
}
}
extension _UnsafeBitSet.Index {
@inlinable
internal var word: Int {
// Note: We perform on UInts to get faster unsigned math (shifts).
Int(truncatingIfNeeded: value / UInt(bitPattern: _Word.capacity))
}
@inlinable
internal var bit: UInt {
// Note: We perform on UInts to get faster unsigned math (masking).
value % UInt(bitPattern: _Word.capacity)
}
@inlinable
internal var split: (word: Int, bit: UInt) {
(word, bit)
}
@inlinable
internal var endSplit: (word: Int, bit: UInt) {
let w = word
let b = bit
if w > 0, b == 0 { return (w &- 1, UInt(_Word.capacity)) }
return (w, b)
}
@inlinable
internal static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
@inlinable
internal static func <(left: Self, right: Self) -> Bool {
left.value < right.value
}
@inlinable
internal func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
@inlinable
internal func _successor() -> Self {
Self(value + 1)
}
@inlinable
internal func _predecessor() -> Self {
Self(value - 1)
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension _UnsafeBitSet {
@frozen
public struct Index: Comparable, Hashable {
@usableFromInline
internal typealias _Word = _UnsafeBitSet._Word
public var value: UInt
@inlinable
public init(_ value: UInt) {
self.value = value
}
@inlinable
public init(_ value: Int) {
self.value = UInt(value)
}
@inlinable
public init(word: Int, bit: UInt) {
assert(word >= 0 && word <= Int.max / _Word.capacity)
assert(bit < _Word.capacity)
self.value = UInt(word &* _Word.capacity) &+ bit
}
}
}
extension _UnsafeBitSet.Index {
@inlinable
public var word: Int {
// Note: We perform on UInts to get faster unsigned math (shifts).
Int(truncatingIfNeeded: value / UInt(bitPattern: _Word.capacity))
}
@inlinable
public var bit: UInt {
// Note: We perform on UInts to get faster unsigned math (masking).
value % UInt(bitPattern: _Word.capacity)
}
@inlinable
public var split: (word: Int, bit: UInt) {
(word, bit)
}
@inlinable
public var endSplit: (word: Int, bit: UInt) {
let w = word
let b = bit
if w > 0, b == 0 { return (w &- 1, UInt(_Word.capacity)) }
return (w, b)
}
@inlinable
public static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
@inlinable
public static func <(left: Self, right: Self) -> Bool {
left.value < right.value
}
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
@inlinable
internal func _successor() -> Self {
Self(value + 1)
}
@inlinable
internal func _predecessor() -> Self {
Self(value - 1)
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -1,643 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2024 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension _UnsafeBitSet {
@frozen @usableFromInline
internal struct _Word {
@usableFromInline
internal var value: UInt
@inlinable
@inline(__always)
internal init(_ value: UInt) {
self.value = value
}
@inlinable
@inline(__always)
internal init(upTo bit: UInt) {
assert(bit <= _Word.capacity)
self.init((1 << bit) &- 1)
}
@inlinable
@inline(__always)
internal init(from start: UInt, to end: UInt) {
assert(start <= end && end <= _Word.capacity)
self = Self(upTo: end).symmetricDifference(Self(upTo: start))
}
}
}
extension _UnsafeBitSet._Word: CustomStringConvertible {
@usableFromInline
internal var description: String {
String(value, radix: 16)
}
}
extension _UnsafeBitSet._Word {
/// Returns the `n`th member in `self`.
///
/// - Parameter n: The offset of the element to retrieve. This value is
/// decremented by the number of items found in this `self` towards the
/// value we're looking for. (If the function returns non-nil, then `n`
/// is set to `0` on return.)
/// - Returns: If this word contains enough members to satisfy the request,
/// then this function returns the member found. Otherwise it returns nil.
@inline(never)
internal func nthElement(_ n: inout UInt) -> UInt? {
let c = UInt(bitPattern: count)
guard n < c else {
n &-= c
return nil
}
let m = Int(bitPattern: n)
n = 0
return value._bit(ranked: m)!
}
@inline(never)
internal func nthElementFromEnd(_ n: inout UInt) -> UInt? {
let c = UInt(bitPattern: count)
guard n < c else {
n &-= c
return nil
}
let m = Int(bitPattern: c &- 1 &- n)
n = 0
return value._bit(ranked: m)!
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
internal static func wordCount(forBitCount count: UInt) -> Int {
// Note: We perform on UInts to get faster unsigned math (shifts).
let width = UInt(bitPattern: Self.capacity)
return Int(bitPattern: (count + width - 1) / width)
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
internal static var capacity: Int {
return UInt.bitWidth
}
@inlinable
@inline(__always)
internal var count: Int {
value.nonzeroBitCount
}
@inlinable
@inline(__always)
internal var isEmpty: Bool {
value == 0
}
@inlinable
@inline(__always)
internal var isFull: Bool {
value == UInt.max
}
@inlinable
@inline(__always)
internal func contains(_ bit: UInt) -> Bool {
assert(bit >= 0 && bit < UInt.bitWidth)
return value & (1 &<< bit) != 0
}
@inlinable
@inline(__always)
internal var firstMember: UInt? {
value._lastSetBit
}
@inlinable
@inline(__always)
internal var lastMember: UInt? {
value._firstSetBit
}
@inlinable
@inline(__always)
@discardableResult
internal mutating func insert(_ bit: UInt) -> Bool {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
let inserted = value & mask == 0
value |= mask
return inserted
}
@inlinable
@inline(__always)
@discardableResult
internal mutating func remove(_ bit: UInt) -> Bool {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
let removed = (value & mask) != 0
value &= ~mask
return removed
}
@inlinable
@inline(__always)
internal mutating func update(_ bit: UInt, to value: Bool) {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
if value {
self.value |= mask
} else {
self.value &= ~mask
}
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
internal mutating func insertAll(upTo bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask: UInt = (1 as UInt &<< bit) &- 1
value |= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(upTo bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask = UInt.max &<< bit
value &= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(through bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
var mask = UInt.max &<< bit
mask &= mask &- 1 // Clear lowest nonzero bit.
value &= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(from bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask: UInt = (1 as UInt &<< bit) &- 1
value &= mask
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
internal static var empty: Self {
Self(0)
}
@inline(__always)
internal static var allBits: Self {
Self(UInt.max)
}
}
// _Word implements Sequence by using a copy of itself as its Iterator.
// Iteration with `next()` destroys the word's value; however, this won't cause
// problems in normal use, because `next()` is usually called on a separate
// iterator, not the original word.
extension _UnsafeBitSet._Word: Sequence, IteratorProtocol {
@inlinable @inline(__always)
internal var underestimatedCount: Int {
count
}
/// Return the index of the lowest set bit in this word,
/// and also destructively clear it.
@inlinable
internal mutating func next() -> UInt? {
guard value != 0 else { return nil }
let bit = UInt(truncatingIfNeeded: value.trailingZeroBitCount)
value &= value &- 1 // Clear lowest nonzero bit.
return bit
}
}
extension _UnsafeBitSet._Word: Equatable {
@inlinable
internal static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
}
extension _UnsafeBitSet._Word: Hashable {
@inlinable
internal func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
extension _UnsafeBitSet._Word {
@inlinable @inline(__always)
internal func complement() -> Self {
Self(~self.value)
}
@inlinable @inline(__always)
internal mutating func formComplement() {
self.value = ~self.value
}
@inlinable @inline(__always)
internal func union(_ other: Self) -> Self {
Self(self.value | other.value)
}
@inlinable @inline(__always)
internal mutating func formUnion(_ other: Self) {
self.value |= other.value
}
@inlinable @inline(__always)
internal func intersection(_ other: Self) -> Self {
Self(self.value & other.value)
}
@inlinable @inline(__always)
internal mutating func formIntersection(_ other: Self) {
self.value &= other.value
}
@inlinable @inline(__always)
internal func symmetricDifference(_ other: Self) -> Self {
Self(self.value ^ other.value)
}
@inlinable @inline(__always)
internal mutating func formSymmetricDifference(_ other: Self) {
self.value ^= other.value
}
@inlinable @inline(__always)
internal func subtracting(_ other: Self) -> Self {
Self(self.value & ~other.value)
}
@inlinable @inline(__always)
internal mutating func subtract(_ other: Self) {
self.value &= ~other.value
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
internal func shiftedDown(by shift: UInt) -> Self {
assert(shift >= 0 && shift < Self.capacity)
return Self(self.value &>> shift)
}
@inlinable
@inline(__always)
internal func shiftedUp(by shift: UInt) -> Self {
assert(shift >= 0 && shift < Self.capacity)
return Self(self.value &<< shift)
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension _UnsafeBitSet {
@frozen
public struct _Word {
public var value: UInt
@inlinable
@inline(__always)
public init(_ value: UInt) {
self.value = value
}
@inlinable
@inline(__always)
public init(upTo bit: UInt) {
assert(bit <= _Word.capacity)
self.init((1 << bit) &- 1)
}
@inlinable
@inline(__always)
public init(from start: UInt, to end: UInt) {
assert(start <= end && end <= _Word.capacity)
self = Self(upTo: end).symmetricDifference(Self(upTo: start))
}
}
}
extension _UnsafeBitSet._Word: CustomStringConvertible {
//@usableFromInline
public var description: String {
String(value, radix: 16)
}
}
extension _UnsafeBitSet._Word {
/// Returns the `n`th member in `self`.
///
/// - Parameter n: The offset of the element to retrieve. This value is
/// decremented by the number of items found in this `self` towards the
/// value we're looking for. (If the function returns non-nil, then `n`
/// is set to `0` on return.)
/// - Returns: If this word contains enough members to satisfy the request,
/// then this function returns the member found. Otherwise it returns nil.
@inline(never)
internal func nthElement(_ n: inout UInt) -> UInt? {
let c = UInt(bitPattern: count)
guard n < c else {
n &-= c
return nil
}
let m = Int(bitPattern: n)
n = 0
return value._bit(ranked: m)!
}
@inline(never)
internal func nthElementFromEnd(_ n: inout UInt) -> UInt? {
let c = UInt(bitPattern: count)
guard n < c else {
n &-= c
return nil
}
let m = Int(bitPattern: c &- 1 &- n)
n = 0
return value._bit(ranked: m)!
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
public static func wordCount(forBitCount count: UInt) -> Int {
// Note: We perform on UInts to get faster unsigned math (shifts).
let width = UInt(bitPattern: Self.capacity)
return Int(bitPattern: (count + width - 1) / width)
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
public static var capacity: Int {
return UInt.bitWidth
}
@inlinable
@inline(__always)
public var count: Int {
value.nonzeroBitCount
}
@inlinable
@inline(__always)
public var isEmpty: Bool {
value == 0
}
@inlinable
@inline(__always)
public var isFull: Bool {
value == UInt.max
}
@inlinable
@inline(__always)
public func contains(_ bit: UInt) -> Bool {
assert(bit >= 0 && bit < UInt.bitWidth)
return value & (1 &<< bit) != 0
}
@inlinable
@inline(__always)
public var firstMember: UInt? {
value._lastSetBit
}
@inlinable
@inline(__always)
public var lastMember: UInt? {
value._firstSetBit
}
@inlinable
@inline(__always)
@discardableResult
public mutating func insert(_ bit: UInt) -> Bool {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
let inserted = value & mask == 0
value |= mask
return inserted
}
@inlinable
@inline(__always)
@discardableResult
public mutating func remove(_ bit: UInt) -> Bool {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
let removed = (value & mask) != 0
value &= ~mask
return removed
}
@inlinable
@inline(__always)
public mutating func update(_ bit: UInt, to value: Bool) {
assert(bit < UInt.bitWidth)
let mask: UInt = 1 &<< bit
if value {
self.value |= mask
} else {
self.value &= ~mask
}
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
internal mutating func insertAll(upTo bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask: UInt = (1 as UInt &<< bit) &- 1
value |= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(upTo bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask = UInt.max &<< bit
value &= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(through bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
var mask = UInt.max &<< bit
mask &= mask &- 1 // Clear lowest nonzero bit.
value &= mask
}
@inlinable
@inline(__always)
internal mutating func removeAll(from bit: UInt) {
assert(bit >= 0 && bit < Self.capacity)
let mask: UInt = (1 as UInt &<< bit) &- 1
value &= mask
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
public static var empty: Self {
Self(0)
}
@inline(__always)
public static var allBits: Self {
Self(UInt.max)
}
}
// _Word implements Sequence by using a copy of itself as its Iterator.
// Iteration with `next()` destroys the word's value; however, this won't cause
// problems in normal use, because `next()` is usually called on a separate
// iterator, not the original word.
extension _UnsafeBitSet._Word: Sequence, IteratorProtocol {
@inlinable @inline(__always)
public var underestimatedCount: Int {
count
}
/// Return the index of the lowest set bit in this word,
/// and also destructively clear it.
@inlinable
public mutating func next() -> UInt? {
guard value != 0 else { return nil }
let bit = UInt(truncatingIfNeeded: value.trailingZeroBitCount)
value &= value &- 1 // Clear lowest nonzero bit.
return bit
}
}
extension _UnsafeBitSet._Word: Equatable {
@inlinable
public static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
}
extension _UnsafeBitSet._Word: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
extension _UnsafeBitSet._Word {
@inlinable @inline(__always)
public func complement() -> Self {
Self(~self.value)
}
@inlinable @inline(__always)
public mutating func formComplement() {
self.value = ~self.value
}
@inlinable @inline(__always)
public func union(_ other: Self) -> Self {
Self(self.value | other.value)
}
@inlinable @inline(__always)
public mutating func formUnion(_ other: Self) {
self.value |= other.value
}
@inlinable @inline(__always)
public func intersection(_ other: Self) -> Self {
Self(self.value & other.value)
}
@inlinable @inline(__always)
public mutating func formIntersection(_ other: Self) {
self.value &= other.value
}
@inlinable @inline(__always)
public func symmetricDifference(_ other: Self) -> Self {
Self(self.value ^ other.value)
}
@inlinable @inline(__always)
public mutating func formSymmetricDifference(_ other: Self) {
self.value ^= other.value
}
@inlinable @inline(__always)
public func subtracting(_ other: Self) -> Self {
Self(self.value & ~other.value)
}
@inlinable @inline(__always)
public mutating func subtract(_ other: Self) {
self.value &= ~other.value
}
}
extension _UnsafeBitSet._Word {
@inlinable
@inline(__always)
public func shiftedDown(by shift: UInt) -> Self {
assert(shift >= 0 && shift < Self.capacity)
return Self(self.value &>> shift)
}
@inlinable
@inline(__always)
public func shiftedUp(by shift: UInt) -> Self {
assert(shift >= 0 && shift < Self.capacity)
return Self(self.value &<< shift)
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -1,932 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2024 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
/// An unsafe-unowned bitset view over `UInt` storage, providing bit set
/// primitives.
@frozen @usableFromInline
internal struct _UnsafeBitSet {
/// An unsafe-unowned storage view.
@usableFromInline
internal let _words: UnsafeBufferPointer<_Word>
#if DEBUG
/// True when this handle does not support table mutations.
/// (This is only checked in debug builds.)
@usableFromInline
internal let _mutable: Bool
#endif
@inlinable
@inline(__always)
internal func ensureMutable() {
#if DEBUG
assert(_mutable)
#endif
}
@inlinable
@inline(__always)
internal var _mutableWords: UnsafeMutableBufferPointer<_Word> {
ensureMutable()
return UnsafeMutableBufferPointer(mutating: _words)
}
@inlinable
@inline(__always)
internal init(
words: UnsafeBufferPointer<_Word>,
mutable: Bool
) {
assert(words.baseAddress != nil)
self._words = words
#if DEBUG
self._mutable = mutable
#endif
}
@inlinable
@inline(__always)
internal init(
words: UnsafeMutableBufferPointer<_Word>,
mutable: Bool
) {
self.init(words: UnsafeBufferPointer(words), mutable: mutable)
}
}
extension _UnsafeBitSet {
@inlinable
@inline(__always)
internal var wordCount: Int {
_words.count
}
}
extension _UnsafeBitSet {
@inlinable
@inline(__always)
internal static func withTemporaryBitSet<R>(
capacity: Int,
run body: (inout _UnsafeBitSet) throws -> R
) rethrows -> R {
let wordCount = _UnsafeBitSet.wordCount(forCapacity: UInt(capacity))
return try withTemporaryBitSet(wordCount: wordCount, run: body)
}
@inlinable
@inline(__always)
internal static func withTemporaryBitSet<R>(
wordCount: Int,
run body: (inout Self) throws -> R
) rethrows -> R {
var result: R?
try _withTemporaryBitSet(wordCount: wordCount) { bitset in
result = try body(&bitset)
}
return result!
}
@inline(never)
@usableFromInline
internal static func _withTemporaryBitSet(
wordCount: Int,
run body: (inout Self) throws -> Void
) rethrows {
try _withTemporaryUninitializedBitSet(wordCount: wordCount) { handle in
handle._mutableWords.initialize(repeating: .empty)
try body(&handle)
}
}
internal static func _withTemporaryUninitializedBitSet(
wordCount: Int,
run body: (inout Self) throws -> Void
) rethrows {
assert(wordCount >= 0)
return try withUnsafeTemporaryAllocation(
of: _Word.self, capacity: wordCount
) { words in
var bitset = Self(words: words, mutable: true)
return try body(&bitset)
}
}
}
extension _UnsafeBitSet {
@_effects(readnone)
@inlinable @inline(__always)
internal static func wordCount(forCapacity capacity: UInt) -> Int {
_Word.wordCount(forBitCount: capacity)
}
@inlinable @inline(__always)
internal var capacity: UInt {
UInt(wordCount &* _Word.capacity)
}
@inlinable @inline(__always)
internal func isWithinBounds(_ element: UInt) -> Bool {
element < capacity
}
@_effects(releasenone)
@inline(__always)
@usableFromInline
internal func contains(_ element: UInt) -> Bool {
let (word, bit) = Index(element).split
guard word < wordCount else { return false }
return _words[word].contains(bit)
}
@_effects(releasenone)
@usableFromInline
@discardableResult
internal mutating func insert(_ element: UInt) -> Bool {
ensureMutable()
assert(isWithinBounds(element))
let index = Index(element)
return _mutableWords[index.word].insert(index.bit)
}
@_effects(releasenone)
@usableFromInline
@discardableResult
internal mutating func remove(_ element: UInt) -> Bool {
ensureMutable()
let index = Index(element)
if index.word >= _words.count { return false }
return _mutableWords[index.word].remove(index.bit)
}
@_effects(releasenone)
@usableFromInline
internal mutating func update(_ member: UInt, to newValue: Bool) -> Bool {
ensureMutable()
let (w, b) = Index(member).split
_mutableWords[w].update(b, to: newValue)
return w == _words.count &- 1
}
@_effects(releasenone)
@usableFromInline
internal mutating func insertAll(upTo max: UInt) {
assert(max <= capacity)
guard max > 0 else { return }
let (w, b) = Index(max).split
for i in 0 ..< w {
_mutableWords[i] = .allBits
}
if b > 0 {
_mutableWords[w].insertAll(upTo: b)
}
}
@_alwaysEmitIntoClient
@usableFromInline
@inline(__always)
@discardableResult
internal mutating func insert(_ element: Int) -> Bool {
precondition(element >= 0)
return insert(UInt(bitPattern: element))
}
@_alwaysEmitIntoClient
@usableFromInline
@inline(__always)
@discardableResult
internal mutating func remove(_ element: Int) -> Bool {
guard element >= 0 else { return false }
return remove(UInt(bitPattern: element))
}
@_alwaysEmitIntoClient
@usableFromInline
@inline(__always)
internal mutating func insertAll(upTo max: Int) {
precondition(max >= 0)
return insertAll(upTo: UInt(bitPattern: max))
}
}
extension _UnsafeBitSet: Sequence {
@usableFromInline
internal typealias Element = UInt
@inlinable
@inline(__always)
internal var underestimatedCount: Int {
count // FIXME: really?
}
@inlinable
@inline(__always)
internal func makeIterator() -> Iterator {
return Iterator(self)
}
@usableFromInline @frozen
internal struct Iterator: IteratorProtocol {
@usableFromInline
internal let _bitset: _UnsafeBitSet
@usableFromInline
internal var _index: Int
@usableFromInline
internal var _word: _Word
@inlinable
internal init(_ bitset: _UnsafeBitSet) {
self._bitset = bitset
self._index = 0
self._word = bitset.wordCount > 0 ? bitset._words[0] : .empty
}
@_effects(releasenone)
@usableFromInline
internal mutating func next() -> UInt? {
if let bit = _word.next() {
return Index(word: _index, bit: bit).value
}
while (_index + 1) < _bitset.wordCount {
_index += 1
_word = _bitset._words[_index]
if let bit = _word.next() {
return Index(word: _index, bit: bit).value
}
}
return nil
}
}
}
extension _UnsafeBitSet: BidirectionalCollection {
@inlinable
@inline(__always)
internal var count: Int {
_words.reduce(0) { $0 + $1.count }
}
@inlinable
@inline(__always)
internal var isEmpty: Bool {
_words.firstIndex(where: { !$0.isEmpty }) == nil
}
@inlinable
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!)
}
@inlinable
internal var endIndex: Index {
Index(word: wordCount, bit: 0)
}
@inlinable
internal subscript(position: Index) -> UInt {
position.value
}
@_effects(releasenone)
@usableFromInline
internal func index(after index: Index) -> Index {
precondition(index < endIndex, "Index out of bounds")
var word = index.word
var w = _words[word]
w.removeAll(through: index.bit)
while w.isEmpty {
word += 1
guard word < wordCount else {
return Index(word: wordCount, bit: 0)
}
w = _words[word]
}
return Index(word: word, bit: w.firstMember!)
}
@_effects(releasenone)
@usableFromInline
internal func index(before index: Index) -> Index {
precondition(index <= endIndex, "Index out of bounds")
var word = index.word
var w: _Word
if index.bit > 0 {
w = _words[word]
w.removeAll(from: index.bit)
} else {
w = .empty
}
while w.isEmpty {
word -= 1
precondition(word >= 0, "Can't advance below startIndex")
w = _words[word]
}
return Index(word: word, bit: w.lastMember!)
}
@_effects(releasenone)
@usableFromInline
internal func distance(from start: Index, to end: Index) -> Int {
precondition(start <= endIndex && end <= endIndex, "Index out of bounds")
let isNegative = end < start
let (start, end) = (Swift.min(start, end), Swift.max(start, end))
let (w1, b1) = start.split
let (w2, b2) = end.split
if w1 == w2 {
guard w1 < wordCount else { return 0 }
let mask = _Word(from: b1, to: b2)
let c = _words[w1].intersection(mask).count
return isNegative ? -c : c
}
var c = 0
var w = w1
guard w < wordCount else { return 0 }
c &+= _words[w].subtracting(_Word(upTo: b1)).count
w &+= 1
while w < w2 {
c &+= _words[w].count
w &+= 1
}
guard w < wordCount else { return isNegative ? -c : c }
c &+= _words[w].intersection(_Word(upTo: b2)).count
return isNegative ? -c : c
}
@_effects(releasenone)
@usableFromInline
internal func index(_ i: Index, offsetBy distance: Int) -> Index {
precondition(i <= endIndex, "Index out of bounds")
precondition(i == endIndex || contains(i.value), "Invalid index")
guard distance != 0 else { return i }
var remaining = distance.magnitude
if distance > 0 {
var (w, b) = i.split
precondition(w < wordCount, "Index out of bounds")
if let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) {
return Index(word: w, bit: v)
}
while true {
w &+= 1
guard w < wordCount else { break }
if let v = _words[w].nthElement(&remaining) {
return Index(word: w, bit: v)
}
}
precondition(remaining == 0, "Index out of bounds")
return endIndex
}
// distance < 0
remaining -= 1
var (w, b) = i.endSplit
if w < wordCount {
if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) {
return Index(word: w, bit: v)
}
}
while true {
precondition(w > 0, "Index out of bounds")
w &-= 1
if let v = _words[w].nthElementFromEnd(&remaining) {
return Index(word: w, bit: v)
}
}
}
@_effects(releasenone)
@usableFromInline
internal func index(
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
) -> Index? {
precondition(i <= endIndex && limit <= endIndex, "Index out of bounds")
precondition(i == endIndex || contains(i.value), "Invalid index")
guard distance != 0 else { return i }
var remaining = distance.magnitude
if distance > 0 {
guard i <= limit else {
return self.index(i, offsetBy: distance)
}
var (w, b) = i.split
if w < wordCount,
let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining)
{
let r = Index(word: w, bit: v)
return r <= limit ? r : nil
}
let maxWord = Swift.min(wordCount - 1, limit.word)
while w < maxWord {
w &+= 1
if let v = _words[w].nthElement(&remaining) {
let r = Index(word: w, bit: v)
return r <= limit ? r : nil
}
}
return remaining == 0 && limit == endIndex ? endIndex : nil
}
// distance < 0
guard i >= limit else {
return self.index(i, offsetBy: distance)
}
remaining &-= 1
var (w, b) = i.endSplit
if w < wordCount {
if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) {
let r = Index(word: w, bit: v)
return r >= limit ? r : nil
}
}
let minWord = limit.word
while w > minWord {
w &-= 1
if let v = _words[w].nthElementFromEnd(&remaining) {
let r = Index(word: w, bit: v)
return r >= limit ? r : nil
}
}
return nil
}
}
#else // !COLLECTIONS_SINGLE_MODULE
/// An unsafe-unowned bitset view over `UInt` storage, providing bit set
/// primitives.
@frozen
public struct _UnsafeBitSet {
/// An unsafe-unowned storage view.
public let _words: UnsafeBufferPointer<_Word>
#if DEBUG
/// True when this handle does not support table mutations.
/// (This is only checked in debug builds.)
@usableFromInline
internal let _mutable: Bool
#endif
@inlinable
@inline(__always)
public func ensureMutable() {
#if DEBUG
assert(_mutable)
#endif
}
@inlinable
@inline(__always)
public var _mutableWords: UnsafeMutableBufferPointer<_Word> {
ensureMutable()
return UnsafeMutableBufferPointer(mutating: _words)
}
@inlinable
@inline(__always)
public init(
words: UnsafeBufferPointer<_Word>,
mutable: Bool
) {
assert(words.baseAddress != nil)
self._words = words
#if DEBUG
self._mutable = mutable
#endif
}
@inlinable
@inline(__always)
public init(
words: UnsafeMutableBufferPointer<_Word>,
mutable: Bool
) {
self.init(words: UnsafeBufferPointer(words), mutable: mutable)
}
}
extension _UnsafeBitSet {
@inlinable
@inline(__always)
public var wordCount: Int {
_words.count
}
}
extension _UnsafeBitSet {
@inlinable
@inline(__always)
public static func withTemporaryBitSet<R>(
capacity: Int,
run body: (inout _UnsafeBitSet) throws -> R
) rethrows -> R {
let wordCount = _UnsafeBitSet.wordCount(forCapacity: UInt(capacity))
return try withTemporaryBitSet(wordCount: wordCount, run: body)
}
@inlinable
@inline(__always)
public static func withTemporaryBitSet<R>(
wordCount: Int,
run body: (inout Self) throws -> R
) rethrows -> R {
var result: R?
try _withTemporaryBitSet(wordCount: wordCount) { bitset in
result = try body(&bitset)
}
return result!
}
@inline(never)
@usableFromInline
internal static func _withTemporaryBitSet(
wordCount: Int,
run body: (inout Self) throws -> Void
) rethrows {
try _withTemporaryUninitializedBitSet(wordCount: wordCount) { handle in
handle._mutableWords.initialize(repeating: .empty)
try body(&handle)
}
}
internal static func _withTemporaryUninitializedBitSet(
wordCount: Int,
run body: (inout Self) throws -> Void
) rethrows {
assert(wordCount >= 0)
return try withUnsafeTemporaryAllocation(
of: _Word.self, capacity: wordCount
) { words in
var bitset = Self(words: words, mutable: true)
return try body(&bitset)
}
}
}
extension _UnsafeBitSet {
@_effects(readnone)
@inlinable @inline(__always)
public static func wordCount(forCapacity capacity: UInt) -> Int {
_Word.wordCount(forBitCount: capacity)
}
@inlinable @inline(__always)
public var capacity: UInt {
UInt(wordCount &* _Word.capacity)
}
@inlinable @inline(__always)
internal func isWithinBounds(_ element: UInt) -> Bool {
element < capacity
}
@_effects(releasenone)
@inline(__always)
//@usableFromInline
public func contains(_ element: UInt) -> Bool {
let (word, bit) = Index(element).split
guard word < wordCount else { return false }
return _words[word].contains(bit)
}
@_effects(releasenone)
//@usableFromInline
@discardableResult
public mutating func insert(_ element: UInt) -> Bool {
ensureMutable()
assert(isWithinBounds(element))
let index = Index(element)
return _mutableWords[index.word].insert(index.bit)
}
@_effects(releasenone)
//@usableFromInline
@discardableResult
public mutating func remove(_ element: UInt) -> Bool {
ensureMutable()
let index = Index(element)
if index.word >= _words.count { return false }
return _mutableWords[index.word].remove(index.bit)
}
@_effects(releasenone)
//@usableFromInline
public mutating func update(_ member: UInt, to newValue: Bool) -> Bool {
ensureMutable()
let (w, b) = Index(member).split
_mutableWords[w].update(b, to: newValue)
return w == _words.count &- 1
}
@_effects(releasenone)
//@usableFromInline
public mutating func insertAll(upTo max: UInt) {
assert(max <= capacity)
guard max > 0 else { return }
let (w, b) = Index(max).split
for i in 0 ..< w {
_mutableWords[i] = .allBits
}
if b > 0 {
_mutableWords[w].insertAll(upTo: b)
}
}
@_alwaysEmitIntoClient
//@usableFromInline
@inline(__always)
@discardableResult
public mutating func insert(_ element: Int) -> Bool {
precondition(element >= 0)
return insert(UInt(bitPattern: element))
}
@_alwaysEmitIntoClient
//@usableFromInline
@inline(__always)
@discardableResult
public mutating func remove(_ element: Int) -> Bool {
guard element >= 0 else { return false }
return remove(UInt(bitPattern: element))
}
@_alwaysEmitIntoClient
//@usableFromInline
@inline(__always)
public mutating func insertAll(upTo max: Int) {
precondition(max >= 0)
return insertAll(upTo: UInt(bitPattern: max))
}
}
extension _UnsafeBitSet: Sequence {
//@usableFromInline
public typealias Element = UInt
@inlinable
@inline(__always)
public var underestimatedCount: Int {
count // FIXME: really?
}
@inlinable
@inline(__always)
public func makeIterator() -> Iterator {
return Iterator(self)
}
@frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
internal let _bitset: _UnsafeBitSet
@usableFromInline
internal var _index: Int
@usableFromInline
internal var _word: _Word
@inlinable
internal init(_ bitset: _UnsafeBitSet) {
self._bitset = bitset
self._index = 0
self._word = bitset.wordCount > 0 ? bitset._words[0] : .empty
}
@_effects(releasenone)
//@usableFromInline
public mutating func next() -> UInt? {
if let bit = _word.next() {
return Index(word: _index, bit: bit).value
}
while (_index + 1) < _bitset.wordCount {
_index += 1
_word = _bitset._words[_index]
if let bit = _word.next() {
return Index(word: _index, bit: bit).value
}
}
return nil
}
}
}
extension _UnsafeBitSet: BidirectionalCollection {
@inlinable
@inline(__always)
public var count: Int {
_words.reduce(0) { $0 + $1.count }
}
@inlinable
@inline(__always)
public var isEmpty: Bool {
_words.firstIndex(where: { !$0.isEmpty }) == nil
}
@inlinable
public var startIndex: Index {
let word = _words.firstIndex { !$0.isEmpty }
guard let word = word else { return endIndex }
return Index(word: word, bit: _words[word].firstMember!)
}
@inlinable
public var endIndex: Index {
Index(word: wordCount, bit: 0)
}
@inlinable
public subscript(position: Index) -> UInt {
position.value
}
@_effects(releasenone)
//@usableFromInline
public func index(after index: Index) -> Index {
precondition(index < endIndex, "Index out of bounds")
var word = index.word
var w = _words[word]
w.removeAll(through: index.bit)
while w.isEmpty {
word += 1
guard word < wordCount else {
return Index(word: wordCount, bit: 0)
}
w = _words[word]
}
return Index(word: word, bit: w.firstMember!)
}
@_effects(releasenone)
//@usableFromInline
public func index(before index: Index) -> Index {
precondition(index <= endIndex, "Index out of bounds")
var word = index.word
var w: _Word
if index.bit > 0 {
w = _words[word]
w.removeAll(from: index.bit)
} else {
w = .empty
}
while w.isEmpty {
word -= 1
precondition(word >= 0, "Can't advance below startIndex")
w = _words[word]
}
return Index(word: word, bit: w.lastMember!)
}
@_effects(releasenone)
//@usableFromInline
public func distance(from start: Index, to end: Index) -> Int {
precondition(start <= endIndex && end <= endIndex, "Index out of bounds")
let isNegative = end < start
let (start, end) = (Swift.min(start, end), Swift.max(start, end))
let (w1, b1) = start.split
let (w2, b2) = end.split
if w1 == w2 {
guard w1 < wordCount else { return 0 }
let mask = _Word(from: b1, to: b2)
let c = _words[w1].intersection(mask).count
return isNegative ? -c : c
}
var c = 0
var w = w1
guard w < wordCount else { return 0 }
c &+= _words[w].subtracting(_Word(upTo: b1)).count
w &+= 1
while w < w2 {
c &+= _words[w].count
w &+= 1
}
guard w < wordCount else { return isNegative ? -c : c }
c &+= _words[w].intersection(_Word(upTo: b2)).count
return isNegative ? -c : c
}
@_effects(releasenone)
//@usableFromInline
public func index(_ i: Index, offsetBy distance: Int) -> Index {
precondition(i <= endIndex, "Index out of bounds")
precondition(i == endIndex || contains(i.value), "Invalid index")
guard distance != 0 else { return i }
var remaining = distance.magnitude
if distance > 0 {
var (w, b) = i.split
precondition(w < wordCount, "Index out of bounds")
if let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) {
return Index(word: w, bit: v)
}
while true {
w &+= 1
guard w < wordCount else { break }
if let v = _words[w].nthElement(&remaining) {
return Index(word: w, bit: v)
}
}
precondition(remaining == 0, "Index out of bounds")
return endIndex
}
// distance < 0
remaining -= 1
var (w, b) = i.endSplit
if w < wordCount {
if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) {
return Index(word: w, bit: v)
}
}
while true {
precondition(w > 0, "Index out of bounds")
w &-= 1
if let v = _words[w].nthElementFromEnd(&remaining) {
return Index(word: w, bit: v)
}
}
}
@_effects(releasenone)
//@usableFromInline
public func index(
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
) -> Index? {
precondition(i <= endIndex && limit <= endIndex, "Index out of bounds")
precondition(i == endIndex || contains(i.value), "Invalid index")
guard distance != 0 else { return i }
var remaining = distance.magnitude
if distance > 0 {
guard i <= limit else {
return self.index(i, offsetBy: distance)
}
var (w, b) = i.split
if w < wordCount,
let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining)
{
let r = Index(word: w, bit: v)
return r <= limit ? r : nil
}
let maxWord = Swift.min(wordCount - 1, limit.word)
while w < maxWord {
w &+= 1
if let v = _words[w].nthElement(&remaining) {
let r = Index(word: w, bit: v)
return r <= limit ? r : nil
}
}
return remaining == 0 && limit == endIndex ? endIndex : nil
}
// distance < 0
guard i >= limit else {
return self.index(i, offsetBy: distance)
}
remaining &-= 1
var (w, b) = i.endSplit
if w < wordCount {
if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) {
let r = Index(word: w, bit: v)
return r >= limit ? r : nil
}
}
let minWord = limit.word
while w > minWord {
w &-= 1
if let v = _words[w].nthElementFromEnd(&remaining) {
let r = Index(word: w, bit: v)
return r >= limit ? r : nil
}
}
return nil
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -9,17 +9,10 @@
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension UnsafeBufferPointer {
@inlinable
@inline(__always)
${modifier} func _ptr(at index: Int) -> UnsafePointer<Element> {
package func _ptr(at index: Int) -> UnsafePointer<Element> {
assert(index >= 0 && index < count)
return baseAddress.unsafelyUnwrapped + index
}
@@ -29,7 +22,7 @@ extension UnsafeBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two `UnsafeBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
${modifier} func _isIdentical(to other: Self) -> Bool {
package func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
@@ -52,7 +45,7 @@ extension UnsafeBufferPointer where Element: ~Copyable {
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(first maxLength: Int) -> Self {
package func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = Swift.min(maxLength, count)
return Self(start: baseAddress, count: newCount)
@@ -75,12 +68,10 @@ extension UnsafeBufferPointer where Element: ~Copyable {
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(last maxLength: Int) -> Self {
package func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = Swift.min(maxLength, count)
return extracting(Range(uncheckedBounds: (count - newCount, count)))
}
}
% end
${visibility_boilerplate("end")}
@@ -9,19 +9,12 @@
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
${modifier} func _isIdentical(to other: Self) -> Bool {
package func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
@@ -76,7 +69,7 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable {
extension UnsafeMutableBufferPointer where Element: ~Copyable {
@inlinable
${modifier} func _moveInitializePrefix(
package func _moveInitializePrefix(
from source: UnsafeMutableBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
@@ -97,7 +90,7 @@ extension UnsafeMutableBufferPointer {
///
/// - Returns: The index after the last item that was initialized in this buffer.
@inlinable
${modifier} func _initializePrefix(
package func _initializePrefix(
copying source: UnsafeBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
@@ -108,7 +101,7 @@ extension UnsafeMutableBufferPointer {
}
@inlinable
${modifier} func _initializePrefix(
package func _initializePrefix(
copying source: UnsafeMutableBufferPointer<Element>
) -> Int {
_initializePrefix(copying: UnsafeBufferPointer(source))
@@ -125,7 +118,7 @@ extension UnsafeMutableBufferPointer {
/// - Returns: The index after the last item that was initialized in this buffer.
@available(SwiftStdlib 5.0, *)
@inlinable
${modifier} func _initializePrefix(copying source: Span<Element>) -> Int {
package func _initializePrefix(copying source: Span<Element>) -> Int {
source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) }
}
#endif
@@ -139,7 +132,7 @@ extension UnsafeMutableBufferPointer {
///
/// The count of `buffer` must not be greater than `self.count`.
@inlinable
${modifier} mutating func _initializeAndDropPrefix(copying source: UnsafeBufferPointer<Element>) {
package mutating func _initializeAndDropPrefix(copying source: UnsafeBufferPointer<Element>) {
let i = _initializePrefix(copying: source)
self = self.extracting(i...)
}
@@ -155,7 +148,7 @@ extension UnsafeMutableBufferPointer {
/// The count of `span` must not be greater than `self.count`.
@available(SwiftStdlib 5.0, *)
@inlinable
${modifier} mutating func _initializeAndDropPrefix(copying span: Span<Element>) {
package mutating func _initializeAndDropPrefix(copying span: Span<Element>) {
span.withUnsafeBufferPointer { buffer in
self._initializeAndDropPrefix(copying: buffer)
}
@@ -165,7 +158,7 @@ extension UnsafeMutableBufferPointer {
extension UnsafeMutableBufferPointer {
@inlinable
${modifier} func initialize(fromContentsOf source: Self) -> Index {
package func initialize(fromContentsOf source: Self) -> Index {
guard source.count > 0 else { return 0 }
precondition(
source.count <= self.count,
@@ -177,7 +170,7 @@ extension UnsafeMutableBufferPointer {
}
@inlinable
${modifier} func initialize(fromContentsOf source: Slice<Self>) -> Index {
package func initialize(fromContentsOf source: Slice<Self>) -> Index {
let sourceCount = source.count
guard sourceCount > 0 else { return 0 }
precondition(
@@ -192,7 +185,7 @@ extension UnsafeMutableBufferPointer {
extension Slice {
@inlinable @inline(__always)
${modifier} func initialize<Element>(
package func initialize<Element>(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) -> Index
where Base == UnsafeMutableBufferPointer<Element>
@@ -203,7 +196,7 @@ extension Slice {
}
@inlinable @inline(__always)
${modifier} func initialize<Element>(
package func initialize<Element>(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) -> Index
where Base == UnsafeMutableBufferPointer<Element>
@@ -216,7 +209,7 @@ extension Slice {
extension UnsafeMutableBufferPointer {
@inlinable @inline(__always)
${modifier} func initializeAll<C: Collection>(
package func initializeAll<C: Collection>(
fromContentsOf source: C
) where C.Element == Element {
let i = self.initialize(fromContentsOf: source)
@@ -224,13 +217,13 @@ extension UnsafeMutableBufferPointer {
}
@inlinable @inline(__always)
${modifier} func initializeAll(fromContentsOf source: Self) {
package func initializeAll(fromContentsOf source: Self) {
let i = self.initialize(fromContentsOf: source)
assert(i == self.endIndex)
}
@inlinable @inline(__always)
${modifier} func initializeAll(fromContentsOf source: Slice<Self>) {
package func initializeAll(fromContentsOf source: Slice<Self>) {
let i = self.initialize(fromContentsOf: source)
assert(i == self.endIndex)
}
@@ -238,7 +231,7 @@ extension UnsafeMutableBufferPointer {
extension UnsafeMutableBufferPointer where Element: ~Copyable {
@inlinable @inline(__always)
${modifier} func moveInitializeAll(fromContentsOf source: Self) {
package func moveInitializeAll(fromContentsOf source: Self) {
let i = self.moveInitialize(fromContentsOf: source)
assert(i == self.endIndex)
}
@@ -246,7 +239,7 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable {
extension UnsafeMutableBufferPointer {
@inlinable @inline(__always)
${modifier} func moveInitializeAll(fromContentsOf source: Slice<Self>) {
package func moveInitializeAll(fromContentsOf source: Slice<Self>) {
let i = self.moveInitialize(fromContentsOf: source)
assert(i == self.endIndex)
}
@@ -254,7 +247,7 @@ extension UnsafeMutableBufferPointer {
extension Slice {
@inlinable @inline(__always)
${modifier} func initializeAll<C: Collection>(
package func initializeAll<C: Collection>(
fromContentsOf source: C
) where Base == UnsafeMutableBufferPointer<C.Element> {
let i = self.initialize(fromContentsOf: source)
@@ -262,7 +255,7 @@ extension Slice {
}
@inlinable @inline(__always)
${modifier} func initializeAll<Element>(
package func initializeAll<Element>(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
@@ -270,7 +263,7 @@ extension Slice {
}
@inlinable @inline(__always)
${modifier} func initializeAll<Element>(
package func initializeAll<Element>(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
@@ -278,7 +271,7 @@ extension Slice {
}
@inlinable @inline(__always)
${modifier} func moveInitializeAll<Element>(
package func moveInitializeAll<Element>(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
@@ -286,12 +279,10 @@ extension Slice {
}
@inlinable @inline(__always)
${modifier} func moveInitializeAll<Element>(
package func moveInitializeAll<Element>(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
target.moveInitializeAll(fromContentsOf: source)
}
}
% end
${visibility_boilerplate("end")}
@@ -9,22 +9,13 @@
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension UnsafeMutableRawBufferPointer {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableRawBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
${modifier} func _isIdentical(to other: Self) -> Bool {
package func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
% end
${visibility_boilerplate("end")}
@@ -9,21 +9,11 @@
//
//===----------------------------------------------------------------------===//
%{
from gyb_utils import *
}%
${autogenerated_warning()}
% for modifier in visibility_levels:
${visibility_boilerplate(modifier)}
extension UnsafeRawBufferPointer {
/// Returns a Boolean value indicating whether two `UnsafeRawBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
${modifier} func _isIdentical(to other: Self) -> Bool {
package func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
% end
${visibility_boilerplate("end")}
@@ -1,54 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2024 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
/// True if consistency checking is enabled in the implementation of the
/// Swift Collections package, false otherwise.
///
/// Documented performance promises are null and void when this property
/// returns true -- for example, operations that are documented to take
/// O(1) time might take O(*n*) time, or worse.
@inlinable @inline(__always)
internal var _isCollectionsInternalCheckingEnabled: Bool {
#if COLLECTIONS_INTERNAL_CHECKS
return true
#else
return false
#endif
}
#else // !COLLECTIONS_SINGLE_MODULE
/// True if consistency checking is enabled in the implementation of the
/// Swift Collections package, false otherwise.
///
/// Documented performance promises are null and void when this property
/// returns true -- for example, operations that are documented to take
/// O(1) time might take O(*n*) time, or worse.
@inlinable @inline(__always)
public var _isCollectionsInternalCheckingEnabled: Bool {
#if COLLECTIONS_INTERNAL_CHECKS
return true
#else
return false
#endif
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -1,140 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2024 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
@usableFromInline
internal func _addressString(for pointer: UnsafeRawPointer) -> String {
let address = UInt(bitPattern: pointer)
return "0x\(String(address, radix: 16))"
}
@usableFromInline
internal func _addressString(for object: AnyObject) -> String {
_addressString(for: Unmanaged.passUnretained(object).toOpaque())
}
@usableFromInline
internal func _addressString<T: AnyObject>(for object: Unmanaged<T>) -> String {
_addressString(for: object.toOpaque())
}
#if !$Embedded
@inlinable
internal func _arrayDescription<C: Collection>(
for elements: C
) -> String {
var result = "["
var first = true
for item in elements {
if first {
first = false
} else {
result += ", "
}
debugPrint(item, terminator: "", to: &result)
}
result += "]"
return result
}
@inlinable
internal func _dictionaryDescription<Key, Value, C: Collection>(
for elements: C
) -> String where C.Element == (key: Key, value: Value) {
guard !elements.isEmpty else { return "[:]" }
var result = "["
var first = true
for (key, value) in elements {
if first {
first = false
} else {
result += ", "
}
debugPrint(key, terminator: "", to: &result)
result += ": "
debugPrint(value, terminator: "", to: &result)
}
result += "]"
return result
}
#endif
#else // !COLLECTIONS_SINGLE_MODULE
//@usableFromInline
public func _addressString(for pointer: UnsafeRawPointer) -> String {
let address = UInt(bitPattern: pointer)
return "0x\(String(address, radix: 16))"
}
//@usableFromInline
public func _addressString(for object: AnyObject) -> String {
_addressString(for: Unmanaged.passUnretained(object).toOpaque())
}
//@usableFromInline
public func _addressString<T: AnyObject>(for object: Unmanaged<T>) -> String {
_addressString(for: object.toOpaque())
}
#if !$Embedded
@inlinable
public func _arrayDescription<C: Collection>(
for elements: C
) -> String {
var result = "["
var first = true
for item in elements {
if first {
first = false
} else {
result += ", "
}
debugPrint(item, terminator: "", to: &result)
}
result += "]"
return result
}
@inlinable
public func _dictionaryDescription<Key, Value, C: Collection>(
for elements: C
) -> String where C.Element == (key: Key, value: Value) {
guard !elements.isEmpty else { return "[:]" }
var result = "["
var first = true
for (key, value) in elements {
if first {
first = false
} else {
result += ", "
}
debugPrint(key, terminator: "", to: &result)
result += ": "
debugPrint(value, terminator: "", to: &result)
}
result += "]"
return result
}
#endif
#endif // COLLECTIONS_SINGLE_MODULE
@@ -1,169 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 - 2025 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
#if compiler(>=6.2)
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with an immortal lifetime.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(immortal)
internal func _unsafeImmortalize<T: ~Copyable & ~Escapable>(
_ dependent: consuming T
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with a lifetime dependency
/// on the caller's borrow scope of the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(borrow source)
internal func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, borrowing source: borrowing U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` that inherits
/// all lifetime dependencies from the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(copy source)
internal func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, copying source: borrowing U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with a lifetime dependency
/// on the caller's exclusive borrow scope of the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(&source)
internal func _overrideLifetime<
T: ~Copyable & ~Escapable,
U: ~Copyable & ~Escapable
>(
_ dependent: consuming T,
mutating source: inout U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
#else // !COLLECTIONS_SINGLE_MODULE
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with an immortal lifetime.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(immortal)
public func _unsafeImmortalize<T: ~Copyable & ~Escapable>(
_ dependent: consuming T
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with a lifetime dependency
/// on the caller's borrow scope of the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(borrow source)
public func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, borrowing source: borrowing U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` that inherits
/// all lifetime dependencies from the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(copy source)
public func _overrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
>(
_ dependent: consuming T, copying source: borrowing U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
/// Unsafely discard any lifetime dependency on the `dependent` argument.
/// Return a value identical to `dependent` with a lifetime dependency
/// on the caller's exclusive borrow scope of the `source` argument.
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@_transparent
@_lifetime(&source)
public func _overrideLifetime<
T: ~Copyable & ~Escapable,
U: ~Copyable & ~Escapable
>(
_ dependent: consuming T,
mutating source: inout U
) -> T {
// TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence
// should be expressed by a builtin that is hidden within the function body.
dependent
}
#endif // COLLECTIONS_SINGLE_MODULE
#endif
@@ -1,58 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2024 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension RandomAccessCollection {
@_alwaysEmitIntoClient @inline(__always)
internal func _index(at offset: Int) -> Index {
index(startIndex, offsetBy: offset)
}
@_alwaysEmitIntoClient @inline(__always)
internal func _offset(of index: Index) -> Int {
distance(from: startIndex, to: index)
}
@_alwaysEmitIntoClient @inline(__always)
internal subscript(_offset offset: Int) -> Element {
self[_index(at: offset)]
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension RandomAccessCollection {
@_alwaysEmitIntoClient @inline(__always)
public func _index(at offset: Int) -> Index {
index(startIndex, offsetBy: offset)
}
@_alwaysEmitIntoClient @inline(__always)
public func _offset(of index: Index) -> Int {
distance(from: startIndex, to: index)
}
@_alwaysEmitIntoClient @inline(__always)
public subscript(_offset offset: Int) -> Element {
self[_index(at: offset)]
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -1,157 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2025 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension UnsafeBufferPointer {
@inlinable
@inline(__always)
internal func _ptr(at index: Int) -> UnsafePointer<Element> {
assert(index >= 0 && index < count)
return baseAddress.unsafelyUnwrapped + index
}
}
extension UnsafeBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two `UnsafeBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
internal func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
extension UnsafeBufferPointer where Element: ~Copyable {
/// Returns a buffer pointer containing the initial elements of this buffer,
/// up to the specified maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// then the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = Swift.min(maxLength, count)
return Self(start: baseAddress, count: newCount)
}
/// Returns a buffer pointer containing the final elements of this buffer,
/// up to the given maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// span from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = Swift.min(maxLength, count)
return extracting(Range(uncheckedBounds: (count - newCount, count)))
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension UnsafeBufferPointer {
@inlinable
@inline(__always)
public func _ptr(at index: Int) -> UnsafePointer<Element> {
assert(index >= 0 && index < count)
return baseAddress.unsafelyUnwrapped + index
}
}
extension UnsafeBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two `UnsafeBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
public func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
extension UnsafeBufferPointer where Element: ~Copyable {
/// Returns a buffer pointer containing the initial elements of this buffer,
/// up to the specified maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// then the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = Swift.min(maxLength, count)
return Self(start: baseAddress, count: newCount)
}
/// Returns a buffer pointer containing the final elements of this buffer,
/// up to the given maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// span from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = Swift.min(maxLength, count)
return extracting(Range(uncheckedBounds: (count - newCount, count)))
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -1,580 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 - 2025 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension UnsafeMutableBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
internal func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
/// Returns a buffer pointer containing the initial elements of this buffer,
/// up to the specified maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// then the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = Swift.min(maxLength, count)
return Self(start: baseAddress, count: newCount)
}
/// Returns a buffer pointer containing the final elements of this buffer,
/// up to the given maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = Swift.min(maxLength, count)
return extracting(Range(uncheckedBounds: (count - newCount, count)))
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
@inlinable
internal func _moveInitializePrefix(
from source: UnsafeMutableBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
precondition(source.count <= self.count)
self.baseAddress.unsafelyUnwrapped.moveInitialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
return source.count
}
}
extension UnsafeMutableBufferPointer {
/// Initialize slots at the start of this buffer by copying data from `source`.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized, while `source` must be fully initialized.
///
/// The `source` buffer must fit entirely in `self`.
///
/// - Returns: The index after the last item that was initialized in this buffer.
@inlinable
internal func _initializePrefix(
copying source: UnsafeBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
precondition(source.count <= self.count)
self.baseAddress.unsafelyUnwrapped.initialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
return source.count
}
@inlinable
internal func _initializePrefix(
copying source: UnsafeMutableBufferPointer<Element>
) -> Int {
_initializePrefix(copying: UnsafeBufferPointer(source))
}
#if compiler(>=6.2)
/// Initialize slots at the start of this buffer by copying data from `source`.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized.
///
/// The `source` span must fit entirely in `self`.
///
/// - Returns: The index after the last item that was initialized in this buffer.
@available(SwiftStdlib 5.0, *)
@inlinable
internal func _initializePrefix(copying source: Span<Element>) -> Int {
source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) }
}
#endif
/// Initialize slots at the start of this buffer by copying data from `buffer`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized, while `buffer` must be fully initialized.
///
/// The count of `buffer` must not be greater than `self.count`.
@inlinable
internal mutating func _initializeAndDropPrefix(copying source: UnsafeBufferPointer<Element>) {
let i = _initializePrefix(copying: source)
self = self.extracting(i...)
}
#if compiler(>=6.2)
/// Initialize slots at the start of this buffer by copying data from `span`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized.
///
/// The count of `span` must not be greater than `self.count`.
@available(SwiftStdlib 5.0, *)
@inlinable
internal mutating func _initializeAndDropPrefix(copying span: Span<Element>) {
span.withUnsafeBufferPointer { buffer in
self._initializeAndDropPrefix(copying: buffer)
}
}
#endif
}
extension UnsafeMutableBufferPointer {
@inlinable
internal func initialize(fromContentsOf source: Self) -> Index {
guard source.count > 0 else { return 0 }
precondition(
source.count <= self.count,
"buffer cannot contain every element from source.")
baseAddress.unsafelyUnwrapped.initialize(
from: source.baseAddress.unsafelyUnwrapped,
count: source.count)
return source.count
}
@inlinable
internal func initialize(fromContentsOf source: Slice<Self>) -> Index {
let sourceCount = source.count
guard sourceCount > 0 else { return 0 }
precondition(
sourceCount <= self.count,
"buffer cannot contain every element from source.")
baseAddress.unsafelyUnwrapped.initialize(
from: source.base.baseAddress.unsafelyUnwrapped + source.startIndex,
count: sourceCount)
return sourceCount
}
}
extension Slice {
@inlinable @inline(__always)
internal func initialize<Element>(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) -> Index
where Base == UnsafeMutableBufferPointer<Element>
{
let target = UnsafeMutableBufferPointer(rebasing: self)
let i = target.initialize(fromContentsOf: source)
return self.startIndex + i
}
@inlinable @inline(__always)
internal func initialize<Element>(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) -> Index
where Base == UnsafeMutableBufferPointer<Element>
{
let target = UnsafeMutableBufferPointer(rebasing: self)
let i = target.initialize(fromContentsOf: source)
return self.startIndex + i
}
}
extension UnsafeMutableBufferPointer {
@inlinable @inline(__always)
internal func initializeAll<C: Collection>(
fromContentsOf source: C
) where C.Element == Element {
let i = self.initialize(fromContentsOf: source)
assert(i == self.endIndex)
}
@inlinable @inline(__always)
internal func initializeAll(fromContentsOf source: Self) {
let i = self.initialize(fromContentsOf: source)
assert(i == self.endIndex)
}
@inlinable @inline(__always)
internal func initializeAll(fromContentsOf source: Slice<Self>) {
let i = self.initialize(fromContentsOf: source)
assert(i == self.endIndex)
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
@inlinable @inline(__always)
internal func moveInitializeAll(fromContentsOf source: Self) {
let i = self.moveInitialize(fromContentsOf: source)
assert(i == self.endIndex)
}
}
extension UnsafeMutableBufferPointer {
@inlinable @inline(__always)
internal func moveInitializeAll(fromContentsOf source: Slice<Self>) {
let i = self.moveInitialize(fromContentsOf: source)
assert(i == self.endIndex)
}
}
extension Slice {
@inlinable @inline(__always)
internal func initializeAll<C: Collection>(
fromContentsOf source: C
) where Base == UnsafeMutableBufferPointer<C.Element> {
let i = self.initialize(fromContentsOf: source)
assert(i == self.endIndex)
}
@inlinable @inline(__always)
internal func initializeAll<Element>(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
target.initializeAll(fromContentsOf: source)
}
@inlinable @inline(__always)
internal func initializeAll<Element>(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
target.initializeAll(fromContentsOf: source)
}
@inlinable @inline(__always)
internal func moveInitializeAll<Element>(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
target.moveInitializeAll(fromContentsOf: source)
}
@inlinable @inline(__always)
internal func moveInitializeAll<Element>(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
target.moveInitializeAll(fromContentsOf: source)
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension UnsafeMutableBufferPointer where Element: ~Copyable {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
public func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
/// Returns a buffer pointer containing the initial elements of this buffer,
/// up to the specified maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// then the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = Swift.min(maxLength, count)
return Self(start: baseAddress, count: newCount)
}
/// Returns a buffer pointer containing the final elements of this buffer,
/// up to the given maximum length.
///
/// If the maximum length exceeds the length of this buffer pointer,
/// the result contains all the elements.
///
/// The returned buffer's first item is always at offset 0; unlike buffer
/// slices, extracted buffers do not share their indices with the
/// buffer from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A buffer pointer with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@inline(__always)
public func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = Swift.min(maxLength, count)
return extracting(Range(uncheckedBounds: (count - newCount, count)))
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
@inlinable
public func _moveInitializePrefix(
from source: UnsafeMutableBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
precondition(source.count <= self.count)
self.baseAddress.unsafelyUnwrapped.moveInitialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
return source.count
}
}
extension UnsafeMutableBufferPointer {
/// Initialize slots at the start of this buffer by copying data from `source`.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized, while `source` must be fully initialized.
///
/// The `source` buffer must fit entirely in `self`.
///
/// - Returns: The index after the last item that was initialized in this buffer.
@inlinable
public func _initializePrefix(
copying source: UnsafeBufferPointer<Element>
) -> Int {
if source.isEmpty { return 0 }
precondition(source.count <= self.count)
self.baseAddress.unsafelyUnwrapped.initialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
return source.count
}
@inlinable
public func _initializePrefix(
copying source: UnsafeMutableBufferPointer<Element>
) -> Int {
_initializePrefix(copying: UnsafeBufferPointer(source))
}
#if compiler(>=6.2)
/// Initialize slots at the start of this buffer by copying data from `source`.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized.
///
/// The `source` span must fit entirely in `self`.
///
/// - Returns: The index after the last item that was initialized in this buffer.
@available(SwiftStdlib 5.0, *)
@inlinable
public func _initializePrefix(copying source: Span<Element>) -> Int {
source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) }
}
#endif
/// Initialize slots at the start of this buffer by copying data from `buffer`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized, while `buffer` must be fully initialized.
///
/// The count of `buffer` must not be greater than `self.count`.
@inlinable
public mutating func _initializeAndDropPrefix(copying source: UnsafeBufferPointer<Element>) {
let i = _initializePrefix(copying: source)
self = self.extracting(i...)
}
#if compiler(>=6.2)
/// Initialize slots at the start of this buffer by copying data from `span`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized.
///
/// The count of `span` must not be greater than `self.count`.
@available(SwiftStdlib 5.0, *)
@inlinable
public mutating func _initializeAndDropPrefix(copying span: Span<Element>) {
span.withUnsafeBufferPointer { buffer in
self._initializeAndDropPrefix(copying: buffer)
}
}
#endif
}
extension UnsafeMutableBufferPointer {
@inlinable
public func initialize(fromContentsOf source: Self) -> Index {
guard source.count > 0 else { return 0 }
precondition(
source.count <= self.count,
"buffer cannot contain every element from source.")
baseAddress.unsafelyUnwrapped.initialize(
from: source.baseAddress.unsafelyUnwrapped,
count: source.count)
return source.count
}
@inlinable
public func initialize(fromContentsOf source: Slice<Self>) -> Index {
let sourceCount = source.count
guard sourceCount > 0 else { return 0 }
precondition(
sourceCount <= self.count,
"buffer cannot contain every element from source.")
baseAddress.unsafelyUnwrapped.initialize(
from: source.base.baseAddress.unsafelyUnwrapped + source.startIndex,
count: sourceCount)
return sourceCount
}
}
extension Slice {
@inlinable @inline(__always)
public func initialize<Element>(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) -> Index
where Base == UnsafeMutableBufferPointer<Element>
{
let target = UnsafeMutableBufferPointer(rebasing: self)
let i = target.initialize(fromContentsOf: source)
return self.startIndex + i
}
@inlinable @inline(__always)
public func initialize<Element>(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) -> Index
where Base == UnsafeMutableBufferPointer<Element>
{
let target = UnsafeMutableBufferPointer(rebasing: self)
let i = target.initialize(fromContentsOf: source)
return self.startIndex + i
}
}
extension UnsafeMutableBufferPointer {
@inlinable @inline(__always)
public func initializeAll<C: Collection>(
fromContentsOf source: C
) where C.Element == Element {
let i = self.initialize(fromContentsOf: source)
assert(i == self.endIndex)
}
@inlinable @inline(__always)
public func initializeAll(fromContentsOf source: Self) {
let i = self.initialize(fromContentsOf: source)
assert(i == self.endIndex)
}
@inlinable @inline(__always)
public func initializeAll(fromContentsOf source: Slice<Self>) {
let i = self.initialize(fromContentsOf: source)
assert(i == self.endIndex)
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
@inlinable @inline(__always)
public func moveInitializeAll(fromContentsOf source: Self) {
let i = self.moveInitialize(fromContentsOf: source)
assert(i == self.endIndex)
}
}
extension UnsafeMutableBufferPointer {
@inlinable @inline(__always)
public func moveInitializeAll(fromContentsOf source: Slice<Self>) {
let i = self.moveInitialize(fromContentsOf: source)
assert(i == self.endIndex)
}
}
extension Slice {
@inlinable @inline(__always)
public func initializeAll<C: Collection>(
fromContentsOf source: C
) where Base == UnsafeMutableBufferPointer<C.Element> {
let i = self.initialize(fromContentsOf: source)
assert(i == self.endIndex)
}
@inlinable @inline(__always)
public func initializeAll<Element>(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
target.initializeAll(fromContentsOf: source)
}
@inlinable @inline(__always)
public func initializeAll<Element>(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
target.initializeAll(fromContentsOf: source)
}
@inlinable @inline(__always)
public func moveInitializeAll<Element>(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
target.moveInitializeAll(fromContentsOf: source)
}
@inlinable @inline(__always)
public func moveInitializeAll<Element>(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) where Base == UnsafeMutableBufferPointer<Element> {
let target = UnsafeMutableBufferPointer(rebasing: self)
target.moveInitializeAll(fromContentsOf: source)
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -1,45 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2025 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension UnsafeMutableRawBufferPointer {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableRawBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
internal func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension UnsafeMutableRawBufferPointer {
/// Returns a Boolean value indicating whether two
/// `UnsafeMutableRawBufferPointer` instances refer to the same region in
/// memory.
@inlinable @inline(__always)
public func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
#endif // COLLECTIONS_SINGLE_MODULE
@@ -1,43 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2025 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
//
//===----------------------------------------------------------------------===//
// #############################################################################
// # #
// # DO NOT EDIT THIS FILE; IT IS AUTOGENERATED. #
// # #
// #############################################################################
// In single module mode, we need these declarations to be internal,
// but in regular builds we want them to be public. Unfortunately
// the current best way to do this is to duplicate all definitions.
#if COLLECTIONS_SINGLE_MODULE
extension UnsafeRawBufferPointer {
/// Returns a Boolean value indicating whether two `UnsafeRawBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
internal func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
#else // !COLLECTIONS_SINGLE_MODULE
extension UnsafeRawBufferPointer {
/// Returns a Boolean value indicating whether two `UnsafeRawBufferPointer`
/// instances refer to the same region in memory.
@inlinable @inline(__always)
public func _isIdentical(to other: Self) -> Bool {
(self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
#endif // COLLECTIONS_SINGLE_MODULE