mirror of
https://github.com/apple/swift-collections
synced 2026-11-29 05:14:20 +00:00
Merge branch 'span-prototype' into future
This commit is contained in:
47 files changed
+2907
-5176
No files matched your search
+8
-7
@@ -55,8 +55,7 @@ var defines: [String] = [
|
||||
let _sharedSettings: [SwiftSetting] = defines.map { .define($0) } + [
|
||||
.enableExperimentalFeature("AllowUnsafeAttribute"),
|
||||
.enableExperimentalFeature("BuiltinModule"),
|
||||
.enableExperimentalFeature("NonescapableTypes"),
|
||||
.enableExperimentalFeature("RawLayout"),
|
||||
.enableExperimentalFeature("LifetimeDependence"),
|
||||
.enableExperimentalFeature("SuppressedAssociatedTypes"),
|
||||
]
|
||||
|
||||
@@ -218,13 +217,15 @@ let targets: [CustomTarget] = [
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "Future",
|
||||
name: "Span",
|
||||
dependencies: ["InternalCollectionsUtilities"],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
exclude: ["CMakeLists.txt"],
|
||||
settings: _sharedSettings + [.unsafeFlags(["-Xfrontend", "-strict-memory-safety"])],
|
||||
),
|
||||
.target(
|
||||
kind: .test,
|
||||
name: "FutureTests",
|
||||
dependencies: ["Future", "_CollectionsTestSupport"]),
|
||||
name: "SpanTests",
|
||||
dependencies: ["Span", "_CollectionsTestSupport"]),
|
||||
|
||||
.target(
|
||||
kind: .exported,
|
||||
@@ -241,7 +242,7 @@ let targets: [CustomTarget] = [
|
||||
.target(
|
||||
kind: .exported,
|
||||
name: "DequeModule",
|
||||
dependencies: ["InternalCollectionsUtilities", "Future"],
|
||||
dependencies: ["InternalCollectionsUtilities", "Span"],
|
||||
exclude: ["CMakeLists.txt"]),
|
||||
.target(
|
||||
kind: .test,
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
import InternalCollectionsUtilities
|
||||
#endif
|
||||
|
||||
import Future
|
||||
import Span
|
||||
|
||||
extension Deque {
|
||||
// Implementation note: we could also use the default `IndexingIterator` here.
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if !COLLECTIONS_SINGLE_MODULE
|
||||
import Future
|
||||
import Span
|
||||
#endif
|
||||
|
||||
extension Deque: RandomAccessContainer {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Future
|
||||
import Span
|
||||
|
||||
extension Deque: Equatable where Element: Equatable {
|
||||
/// Returns a Boolean value indicating whether two values are equal. Two
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Future
|
||||
import Span
|
||||
|
||||
/// A collection implementing a double-ended queue. `Deque` (pronounced "deck")
|
||||
/// implements an ordered random-access collection that supports efficient
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
#if !COLLECTIONS_SINGLE_MODULE
|
||||
import InternalCollectionsUtilities
|
||||
import Future
|
||||
import Span
|
||||
#endif
|
||||
|
||||
@frozen
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
#if !COLLECTIONS_SINGLE_MODULE
|
||||
import InternalCollectionsUtilities
|
||||
import Future
|
||||
import Span
|
||||
#endif
|
||||
|
||||
@frozen
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
#if !COLLECTIONS_SINGLE_MODULE
|
||||
import InternalCollectionsUtilities
|
||||
import Future
|
||||
import Span
|
||||
#endif
|
||||
|
||||
@frozen
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@frozen
|
||||
public struct Box<T: ~Copyable>: ~Copyable {
|
||||
@usableFromInline
|
||||
internal let _pointer: UnsafeMutablePointer<T>
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public init(_ value: consuming T) {
|
||||
_pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
|
||||
_pointer.initialize(to: value)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public init(_ fromInout: consuming Inout<T>) {
|
||||
_pointer = fromInout._pointer
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@inlinable
|
||||
deinit {
|
||||
_pointer.deinitialize(count: 1)
|
||||
_pointer.deallocate()
|
||||
}
|
||||
}
|
||||
|
||||
extension Box where T: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public consuming func consume() -> T {
|
||||
let result = _pointer.move()
|
||||
_pointer.deallocate()
|
||||
discard self
|
||||
return result
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@lifetime(immortal)
|
||||
public consuming func leak() -> Inout<T> {
|
||||
let result = Inout<T>(unsafeImmortalAddress: _pointer)
|
||||
discard self
|
||||
return result
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript() -> T {
|
||||
@_transparent
|
||||
unsafeAddress {
|
||||
UnsafePointer<T>(_pointer)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
nonmutating unsafeMutableAddress {
|
||||
_pointer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Box where T: Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public borrowing func copy() -> T {
|
||||
_pointer.pointee
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Builtin
|
||||
|
||||
@frozen
|
||||
@_rawLayout(like: T, movesAsLike)
|
||||
public struct Cell<T: ~Copyable>: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public var unsafeAddress: UnsafeMutablePointer<T> {
|
||||
UnsafeMutablePointer<T>(Builtin.addressOfRawLayout(self))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public init(_ value: consuming T) {
|
||||
unsafeAddress.initialize(to: value)
|
||||
}
|
||||
}
|
||||
|
||||
extension Cell where T: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public mutating func asInout() -> Inout<T> {
|
||||
Inout<T>(unsafeAddress: unsafeAddress, owner: &self)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript() -> T {
|
||||
@_transparent
|
||||
unsafeAddress {
|
||||
UnsafePointer<T>(unsafeAddress)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
nonmutating unsafeMutableAddress {
|
||||
unsafeAddress
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Cell where T: Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public borrowing func copy() -> T {
|
||||
unsafeAddress.pointee
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public protocol BorrowingIteratorProtocol: ~Escapable {
|
||||
associatedtype Element: ~Copyable
|
||||
|
||||
@lifetime(self)
|
||||
mutating func nextChunk(maximumCount: Int) -> Span<Element>
|
||||
}
|
||||
|
||||
public protocol Container: ~Copyable, ~Escapable {
|
||||
associatedtype Element: ~Copyable
|
||||
|
||||
associatedtype BorrowingIterator: BorrowingIteratorProtocol, ~Escapable
|
||||
where BorrowingIterator.Element == Element
|
||||
|
||||
borrowing func startBorrowingIteration() -> BorrowingIterator
|
||||
borrowing func startBorrowingIteration(from start: Index) -> BorrowingIterator
|
||||
|
||||
associatedtype Index: Comparable
|
||||
|
||||
var isEmpty: Bool { get }
|
||||
var count: Int { get }
|
||||
|
||||
var startIndex: Index { get }
|
||||
var endIndex: Index { get }
|
||||
|
||||
// FIXME: Replace `@_borrowed` with proper `read`/`modify` accessor requirements
|
||||
// FIXME: (Or rather, accessors with proper projection semantics.)
|
||||
@_borrowed subscript(index: Index) -> Element { get }
|
||||
|
||||
func index(after index: Index) -> Index
|
||||
func formIndex(after i: inout Index)
|
||||
|
||||
func index(at position: borrowing BorrowingIterator) -> Index
|
||||
|
||||
func distance(from start: Index, to end: Index) -> Int
|
||||
|
||||
func index(_ index: Index, offsetBy n: Int) -> Index
|
||||
|
||||
func formIndex(
|
||||
_ i: inout Index, offsetBy distance: inout Int, limitedBy limit: Index
|
||||
)
|
||||
}
|
||||
|
||||
public protocol BidirectionalContainer: Container, ~Copyable, ~Escapable {
|
||||
override associatedtype Element: ~Copyable
|
||||
|
||||
func index(before i: Index) -> Index
|
||||
func formIndex(before i: inout Index)
|
||||
|
||||
@_nonoverride func index(_ i: Index, offsetBy distance: Int) -> Index
|
||||
@_nonoverride func formIndex(
|
||||
_ i: inout Index, offsetBy distance: inout Int, limitedBy limit: Index
|
||||
)
|
||||
}
|
||||
|
||||
public protocol RandomAccessContainer: BidirectionalContainer, ~Copyable, ~Escapable {
|
||||
override associatedtype Element: ~Copyable
|
||||
}
|
||||
|
||||
extension Strideable {
|
||||
@inlinable
|
||||
public mutating func advance(by distance: inout Stride, limitedBy limit: Self) {
|
||||
if distance >= 0 {
|
||||
guard limit >= self else {
|
||||
self = self.advanced(by: distance)
|
||||
distance = 0
|
||||
return
|
||||
}
|
||||
let d = Swift.min(distance, self.distance(to: limit))
|
||||
self = self.advanced(by: d)
|
||||
distance -= d
|
||||
} else {
|
||||
guard limit <= self else {
|
||||
self = self.advanced(by: distance)
|
||||
distance = 0
|
||||
return
|
||||
}
|
||||
let d = Swift.max(distance, self.distance(to: limit))
|
||||
self = self.advanced(by: d)
|
||||
distance -= d
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension RandomAccessContainer where Index: Strideable, Index.Stride == Int, Self: ~Copyable {
|
||||
@inlinable
|
||||
public func index(after index: Index) -> Index {
|
||||
// Note: Range checks are deferred until element access.
|
||||
index.advanced(by: 1)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(before index: Index) -> Index {
|
||||
// Note: Range checks are deferred until element access.
|
||||
index.advanced(by: -1)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func formIndex(after index: inout Index) {
|
||||
// Note: Range checks are deferred until element access.
|
||||
index = index.advanced(by: 1)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func formIndex(before index: inout Index) {
|
||||
// Note: Range checks are deferred until element access.
|
||||
index = index.advanced(by: -1)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
// Note: Range checks are deferred until element access.
|
||||
start.distance(to: end)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ index: Index, offsetBy n: Int) -> Index {
|
||||
// Note: Range checks are deferred until element access.
|
||||
index.advanced(by: n)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func formIndex(
|
||||
_ index: inout Index, offsetBy distance: inout Index.Stride, limitedBy limit: Index
|
||||
) {
|
||||
// Note: Range checks are deferred until element access.
|
||||
index.advance(by: &distance, limitedBy: limit)
|
||||
}
|
||||
}
|
||||
|
||||
#if false // TODO
|
||||
public protocol Muterator: ~Copyable, ~Escapable {
|
||||
associatedtype Element: ~Copyable
|
||||
|
||||
@lifetime(self)
|
||||
mutating func nextChunk(maximumCount: Int) -> MutableSpan<Element>
|
||||
}
|
||||
|
||||
public protocol MutableContainer: Container, ~Copyable, ~Escapable {
|
||||
associatedtype MutatingIterationState: ~Copyable, ~Escapable
|
||||
|
||||
mutating func startMutatingIteration() -> MutatingIterationState
|
||||
|
||||
// FIXME: Replace `@_borrowed` with proper `read`/`modify` accessor requirements
|
||||
@_borrowed subscript(index: Index) -> Element { get set }
|
||||
|
||||
}
|
||||
#endif
|
||||
@@ -1,198 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A dynamically self-resizing, heap allocated, noncopyable array
|
||||
/// of potentially noncopyable elements.
|
||||
@frozen
|
||||
public struct DynamicArray<Element: ~Copyable>: ~Copyable {
|
||||
@usableFromInline
|
||||
internal var _storage: RigidArray<Element>
|
||||
|
||||
@inlinable
|
||||
public init() {
|
||||
_storage = .init(capacity: 0)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public init(minimumCapacity: Int) {
|
||||
_storage = .init(capacity: minimumCapacity)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public init(count: Int, initializedBy generator: (Int) -> Element) {
|
||||
_storage = .init(count: count, initializedBy: generator)
|
||||
}
|
||||
}
|
||||
|
||||
extension DynamicArray: Sendable where Element: Sendable & ~Copyable {}
|
||||
|
||||
extension DynamicArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public var capacity: Int { _storage.capacity }
|
||||
}
|
||||
|
||||
extension DynamicArray where Element: ~Copyable {
|
||||
public var storage: Span<Element> {
|
||||
_storage.storage
|
||||
}
|
||||
}
|
||||
|
||||
extension DynamicArray: RandomAccessContainer where Element: ~Copyable {
|
||||
public typealias BorrowingIterator = RigidArray<Element>.BorrowingIterator
|
||||
public typealias Index = Int
|
||||
|
||||
public func startBorrowingIteration() -> BorrowingIterator {
|
||||
BorrowingIterator(for: _storage, startOffset: 0)
|
||||
}
|
||||
|
||||
public func startBorrowingIteration(from start: Int) -> BorrowingIterator {
|
||||
BorrowingIterator(for: _storage, startOffset: start)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var isEmpty: Bool { _storage.isEmpty }
|
||||
|
||||
@inlinable
|
||||
public var count: Int { _storage.count }
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Int { 0 }
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Int { _storage.count }
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Int) -> Element {
|
||||
@inline(__always)
|
||||
_read {
|
||||
yield _storage[position]
|
||||
}
|
||||
@inline(__always)
|
||||
_modify {
|
||||
yield &_storage[position]
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(after i: Int) -> Int { i + 1 }
|
||||
|
||||
@inlinable
|
||||
public func index(before i: Int) -> Int { i - 1 }
|
||||
|
||||
@inlinable
|
||||
public func formIndex(after index: inout Int) {
|
||||
// Note: Range checks are deferred until element access.
|
||||
index += 1
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func formIndex(before index: inout Int) {
|
||||
// Note: Range checks are deferred until element access.
|
||||
index -= 1
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(at position: borrowing BorrowingIterator) -> Int {
|
||||
// Note: Range checks are deferred until element access.
|
||||
position._offset
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func distance(from start: Int, to end: Int) -> Int {
|
||||
// Note: Range checks are deferred until element access.
|
||||
end - start
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(_ index: Int, offsetBy n: Int) -> Int {
|
||||
// Note: Range checks are deferred until element access.
|
||||
index + n
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func formIndex(
|
||||
_ index: inout Int, offsetBy distance: inout Int, limitedBy limit: Int
|
||||
) {
|
||||
_storage.formIndex(&index, offsetBy: &distance, limitedBy: limit)
|
||||
}
|
||||
}
|
||||
|
||||
extension DynamicArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public func borrowElement<E: Error, R: ~Copyable> (
|
||||
at index: Int,
|
||||
by body: (borrowing Element) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
try _storage.borrowElement(at: index, by: body)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func updateElement<E: Error, R: ~Copyable> (
|
||||
at index: Int,
|
||||
by body: (inout Element) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
try _storage.updateElement(at: index, by: body)
|
||||
}
|
||||
}
|
||||
|
||||
extension DynamicArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
@discardableResult
|
||||
public mutating func remove(at index: Int) -> Element {
|
||||
_storage.remove(at: index)
|
||||
}
|
||||
}
|
||||
|
||||
extension DynamicArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public mutating func reserveCapacity(_ n: Int) {
|
||||
_storage.reserveCapacity(n)
|
||||
}
|
||||
}
|
||||
|
||||
extension DynamicArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
internal static func _grow(_ capacity: Int) -> Int {
|
||||
2 * capacity
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func _ensureFreeCapacity(_ minimumCapacity: Int) {
|
||||
guard _storage.freeCapacity < minimumCapacity else { return }
|
||||
reserveCapacity(max(count + minimumCapacity, Self._grow(capacity)))
|
||||
}
|
||||
}
|
||||
|
||||
extension DynamicArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public mutating func append(_ item: consuming Element) {
|
||||
_ensureFreeCapacity(1)
|
||||
_storage.append(item)
|
||||
}
|
||||
}
|
||||
|
||||
extension DynamicArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public mutating func insert(_ item: consuming Element, at index: Int) {
|
||||
precondition(index >= 0 && index <= count)
|
||||
_ensureFreeCapacity(1)
|
||||
_storage.insert(item, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
extension DynamicArray {
|
||||
@inlinable
|
||||
public mutating func append(contentsOf items: some Sequence<Element>) {
|
||||
for item in items {
|
||||
append(item)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// What `Array` might look like if we defined it today.
|
||||
@frozen
|
||||
public struct NewArray<Element> {
|
||||
@usableFromInline
|
||||
internal var _storage: Shared<RigidArray<Element>>
|
||||
|
||||
@inlinable
|
||||
public init(minimumCapacity: Int) {
|
||||
self._storage = Shared(RigidArray(capacity: minimumCapacity))
|
||||
}
|
||||
}
|
||||
|
||||
extension NewArray {
|
||||
public var storage: Span<Element> {
|
||||
#if false
|
||||
// FIXME: This is what I want to write; alas, lifetimes are messed up.
|
||||
return _storage.value.storage
|
||||
#else
|
||||
return Span(_unsafeElements: _storage.value._items)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
extension NewArray {
|
||||
@inlinable
|
||||
public var capacity: Int { _storage.read { $0.capacity } }
|
||||
|
||||
@inlinable
|
||||
internal mutating func _ensureUnique() {
|
||||
_storage.ensureUnique { $0._copy() }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func _ensureUnique(
|
||||
minimumCapacity: Int,
|
||||
linear: Bool = false
|
||||
) {
|
||||
if !_storage.isUnique() {
|
||||
let c = Swift.max(count, minimumCapacity)
|
||||
_storage = Shared(_storage.read { $0._copy(capacity: c) })
|
||||
} else if minimumCapacity > self.capacity {
|
||||
_storage = Shared(_storage.update { $0._move(capacity: minimumCapacity) })
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _read<E: Error, Result: ~Copyable>(
|
||||
_ body: (borrowing RigidArray<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try _storage.read(body)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func _update<E: Error, Result: ~Copyable>(
|
||||
_ body: (inout RigidArray<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
_ensureUnique()
|
||||
return try _storage.update(body)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func _update<E: Error, Result: ~Copyable>(
|
||||
minimumCapacity: Int,
|
||||
_ body: (inout RigidArray<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
_ensureUnique(minimumCapacity: minimumCapacity)
|
||||
return try _storage.update(body)
|
||||
}
|
||||
}
|
||||
|
||||
extension NewArray: RandomAccessCollection, MutableCollection {
|
||||
public typealias Index = Int
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Int { 0 }
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Int { _storage.read { $0.count } }
|
||||
|
||||
public subscript(position: Int) -> Element {
|
||||
@inlinable
|
||||
get {
|
||||
_read { $0[position] }
|
||||
}
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
_modify {
|
||||
_ensureUnique()
|
||||
yield &_storage.value[position]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension NewArray: RangeReplaceableCollection {
|
||||
public init() {
|
||||
// FIXME: Figure out if we can implement empty singletons in this setup.
|
||||
self._storage = Shared(RigidArray(capacity: 0))
|
||||
}
|
||||
|
||||
mutating public func replaceSubrange(
|
||||
_ subrange: Range<Int>,
|
||||
with newElements: some Collection<Element>
|
||||
) {
|
||||
let delta = newElements.count - subrange.count
|
||||
_ensureUnique(minimumCapacity: capacity + delta)
|
||||
}
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// A manually resizable, heap allocated, noncopyable array of
|
||||
/// potentially noncopyable elements.
|
||||
@frozen
|
||||
public struct RigidArray<Element: ~Copyable>: ~Copyable {
|
||||
@usableFromInline
|
||||
internal var _storage: UnsafeMutableBufferPointer<Element>
|
||||
|
||||
@usableFromInline
|
||||
internal var _count: Int
|
||||
|
||||
@inlinable
|
||||
public init(capacity: Int) {
|
||||
precondition(capacity >= 0)
|
||||
if capacity > 0 {
|
||||
_storage = .allocate(capacity: capacity)
|
||||
} else {
|
||||
_storage = .init(start: nil, count: 0)
|
||||
}
|
||||
_count = 0
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public init(count: Int, initializedBy generator: (Int) -> Element) {
|
||||
_storage = .allocate(capacity: count)
|
||||
for i in 0 ..< count {
|
||||
_storage.initializeElement(at: i, to: generator(i))
|
||||
}
|
||||
_count = count
|
||||
}
|
||||
|
||||
deinit {
|
||||
_storage.extracting(0 ..< count).deinitialize()
|
||||
_storage.deallocate()
|
||||
}
|
||||
}
|
||||
|
||||
extension RigidArray: @unchecked Sendable where Element: Sendable & ~Copyable {}
|
||||
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public var capacity: Int { _storage.count }
|
||||
|
||||
@inlinable
|
||||
public var freeCapacity: Int { capacity - count }
|
||||
|
||||
@inlinable
|
||||
public var isFull: Bool { freeCapacity == 0 }
|
||||
}
|
||||
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
public var storage: Span<Element> {
|
||||
Span(_unsafeElements: _items)
|
||||
}
|
||||
}
|
||||
|
||||
extension RigidArray: RandomAccessContainer where Element: ~Copyable {
|
||||
public struct BorrowingIterator: BorrowingIteratorProtocol, ~Escapable {
|
||||
@usableFromInline
|
||||
internal let _items: UnsafeBufferPointer<Element>
|
||||
|
||||
@usableFromInline
|
||||
internal var _offset: Int
|
||||
|
||||
@inlinable
|
||||
internal init(for array: borrowing RigidArray, startOffset: Int) {
|
||||
self._items = UnsafeBufferPointer(array._items)
|
||||
self._offset = startOffset
|
||||
}
|
||||
|
||||
@lifetime(self)
|
||||
public mutating func nextChunk(
|
||||
maximumCount: Int
|
||||
) -> Span<Element> {
|
||||
let end = _offset + Swift.min(maximumCount, _items.count - _offset)
|
||||
defer { _offset = end }
|
||||
let chunk = _items.extracting(Range(uncheckedBounds: (_offset, end)))
|
||||
return Span(_unsafeElements: chunk)
|
||||
}
|
||||
}
|
||||
|
||||
public func startBorrowingIteration() -> BorrowingIterator {
|
||||
BorrowingIterator(for: self, startOffset: 0)
|
||||
}
|
||||
|
||||
public func startBorrowingIteration(from start: Int) -> BorrowingIterator {
|
||||
BorrowingIterator(for: self, startOffset: start)
|
||||
}
|
||||
|
||||
public typealias Index = Int
|
||||
|
||||
@inlinable
|
||||
public var isEmpty: Bool { count == 0 }
|
||||
|
||||
@inlinable
|
||||
public var count: Int { _count }
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Int { 0 }
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Int { count }
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Int) -> Element {
|
||||
@inline(__always)
|
||||
_read {
|
||||
precondition(position >= 0 && position < _count)
|
||||
yield _storage[position]
|
||||
}
|
||||
@inline(__always)
|
||||
_modify {
|
||||
precondition(position >= 0 && position < _count)
|
||||
yield &_storage[position]
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func index(at position: borrowing BorrowingIterator) -> Int {
|
||||
precondition(position._items === UnsafeBufferPointer(self._items))
|
||||
return position._offset
|
||||
}
|
||||
}
|
||||
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
internal var _items: UnsafeMutableBufferPointer<Element> {
|
||||
_storage.extracting(Range(uncheckedBounds: (0, _count)))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var _freeSpace: UnsafeMutableBufferPointer<Element> {
|
||||
_storage.extracting(Range(uncheckedBounds: (_count, capacity)))
|
||||
}
|
||||
}
|
||||
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public mutating func resize(to newCapacity: Int) {
|
||||
precondition(newCapacity >= count)
|
||||
guard newCapacity != capacity else { return }
|
||||
let newStorage: UnsafeMutableBufferPointer<Element> = .allocate(capacity: newCapacity)
|
||||
let i = newStorage.moveInitialize(fromContentsOf: self._items)
|
||||
assert(i == count)
|
||||
_storage.deallocate()
|
||||
_storage = newStorage
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func reserveCapacity(_ n: Int) {
|
||||
guard capacity < n else { return }
|
||||
resize(to: n)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public func borrowElement<E: Error, R: ~Copyable> (
|
||||
at index: Int,
|
||||
by body: (borrowing Element) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
precondition(index >= 0 && index < _count)
|
||||
return try body(_storage[index])
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func updateElement<E: Error, R: ~Copyable> (
|
||||
at index: Int,
|
||||
by body: (inout Element) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
precondition(index >= 0 && index < _count)
|
||||
return try body(&_storage[index])
|
||||
}
|
||||
}
|
||||
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
@discardableResult
|
||||
public mutating func remove(at index: Int) -> Element {
|
||||
precondition(index >= 0 && index < count)
|
||||
let old = _storage.moveElement(from: index)
|
||||
let source = _storage.extracting(index + 1 ..< count)
|
||||
let target = _storage.extracting(index ..< count - 1)
|
||||
let i = target.moveInitialize(fromContentsOf: source)
|
||||
assert(i == target.endIndex)
|
||||
_count -= 1
|
||||
return old
|
||||
}
|
||||
}
|
||||
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public mutating func append(_ item: consuming Element) {
|
||||
precondition(!isFull)
|
||||
_storage.initializeElement(at: _count, to: item)
|
||||
_count += 1
|
||||
}
|
||||
}
|
||||
|
||||
extension RigidArray where Element: ~Copyable {
|
||||
@inlinable
|
||||
public mutating func insert(_ item: consuming Element, at index: Int) {
|
||||
precondition(index >= 0 && index <= count)
|
||||
precondition(!isFull)
|
||||
if index < count {
|
||||
let source = _storage.extracting(index ..< count)
|
||||
let target = _storage.extracting(index + 1 ..< count + 1)
|
||||
let last = target.moveInitialize(fromContentsOf: source)
|
||||
assert(last == target.endIndex)
|
||||
}
|
||||
_storage.initializeElement(at: index, to: item)
|
||||
_count += 1
|
||||
}
|
||||
}
|
||||
|
||||
extension RigidArray {
|
||||
@inlinable
|
||||
public mutating func append(contentsOf items: some Sequence<Element>) {
|
||||
for item in items {
|
||||
append(item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension RigidArray {
|
||||
@inlinable
|
||||
internal func _copy() -> Self {
|
||||
_copy(capacity: capacity)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _copy(capacity: Int) -> Self {
|
||||
precondition(capacity >= count)
|
||||
var result = RigidArray<Element>(capacity: capacity)
|
||||
let initialized = result._storage.initialize(fromContentsOf: _storage)
|
||||
precondition(initialized == count)
|
||||
result._count = count
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func _move(capacity: Int) -> Self {
|
||||
precondition(capacity >= count)
|
||||
var result = RigidArray<Element>(capacity: capacity)
|
||||
let initialized = result._storage.moveInitialize(fromContentsOf: _storage)
|
||||
precondition(initialized == count)
|
||||
result._count = count
|
||||
self._count = 0
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Builtin // For Shared.isIdentical
|
||||
|
||||
/// A utility adapter that wraps a noncopyable storage type in a copy-on-write
|
||||
/// struct, enabling efficient implementation of value semantics. The type
|
||||
/// allows safe borrowing and mutating access to its storage, with minimal fuss.
|
||||
///
|
||||
/// Like `ManagedBufferPointer`, this type is intended to be used within the
|
||||
/// internal implementation of public types. Instances of it aren't designed
|
||||
/// to be exposed as public.
|
||||
@frozen
|
||||
public struct Shared<Storage: ~Copyable> {
|
||||
@usableFromInline
|
||||
internal var _box: _Box
|
||||
|
||||
@inlinable
|
||||
public init(_ storage: consuming Storage) {
|
||||
self._box = _Box(storage)
|
||||
}
|
||||
}
|
||||
|
||||
extension Shared: @unchecked Sendable where Storage: Sendable & ~Copyable {}
|
||||
|
||||
#if true // FIXME: Silent error on class definition nested in noncopyable struct
|
||||
@usableFromInline
|
||||
internal final class _SharedBox<Storage: ~Copyable> {
|
||||
@exclusivity(unchecked)
|
||||
@usableFromInline
|
||||
internal var storage: Storage
|
||||
|
||||
@inlinable
|
||||
internal init(_ storage: consuming Storage) {
|
||||
self.storage = storage
|
||||
}
|
||||
}
|
||||
|
||||
extension Shared where Storage: ~Copyable {
|
||||
@usableFromInline
|
||||
internal typealias _Box = _SharedBox<Storage>
|
||||
}
|
||||
#else
|
||||
extension Shared where Storage: ~Copyable {
|
||||
@usableFromInline
|
||||
internal final class _Box {
|
||||
@exclusivity(unchecked)
|
||||
@usableFromInline
|
||||
internal var storage: Storage
|
||||
|
||||
@inlinable
|
||||
internal init(_ storage: consuming Storage) {
|
||||
self.storage = storage
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension Shared where Storage: ~Copyable {
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public mutating func isUnique() -> Bool {
|
||||
isKnownUniquelyReferenced(&_box)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func ensureUnique(
|
||||
cloner: (borrowing Storage) -> Storage
|
||||
) {
|
||||
if isUnique() { return }
|
||||
_box = _Box(cloner(_box.storage))
|
||||
}
|
||||
}
|
||||
|
||||
import struct SwiftShims.HeapObject
|
||||
|
||||
extension Shared where Storage: ~Copyable {
|
||||
// FIXME: Can we avoid hacks like this? If not, perhaps `_Box.storage` should be tail-allocated.
|
||||
@inlinable
|
||||
internal var _address: UnsafePointer<Storage> {
|
||||
// Adapted from _getUnsafePointerToStoredProperties
|
||||
let p = (
|
||||
UnsafeRawPointer(Builtin.bridgeToRawPointer(_box))
|
||||
+ MemoryLayout<HeapObject>.size)
|
||||
return p.alignedUp(for: Storage.self).assumingMemoryBound(to: Storage.self)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var _mutableAddress: UnsafeMutablePointer<Storage> {
|
||||
// Adapted from _getUnsafePointerToStoredProperties
|
||||
let p = (
|
||||
UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_box))
|
||||
+ MemoryLayout<HeapObject>.size)
|
||||
return p.alignedUp(for: Storage.self).assumingMemoryBound(to: Storage.self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Shared where Storage: ~Copyable {
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var value: /*FIXME: dependsOn(self)*/ Storage {
|
||||
// FIXME: This implements the wrong shape.
|
||||
// FIXME: Semantically it yields a borrow scoped to an access of this `value` variable,
|
||||
// FIXME: not the much wider borrow of `self`, which we'd actually want.
|
||||
_read {
|
||||
yield _box.storage
|
||||
}
|
||||
_modify {
|
||||
precondition(isUnique())
|
||||
yield &_box.storage
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME: This builds, but attempts to use it don't: they fail with an unexpected exclusivity violation.
|
||||
@inlinable
|
||||
@lifetime(self)
|
||||
public subscript() -> Storage {
|
||||
//@_transparent
|
||||
unsafeAddress {
|
||||
_address
|
||||
}
|
||||
|
||||
//@_transparent
|
||||
unsafeMutableAddress {
|
||||
precondition(isUnique())
|
||||
return _mutableAddress
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func read<E: Error, R: ~Copyable>(
|
||||
_ body: (borrowing Storage) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
// FIXME: This also implements the wrong shape.
|
||||
// FIXME: The borrow of `Storage` isn't tied to `self` at all, and
|
||||
// FIXME: it obviously cannot legally escape the `read` call.
|
||||
try body(_box.storage)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public mutating func update<E: Error, R: ~Copyable>(
|
||||
_ body: (inout Storage) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
precondition(isUnique())
|
||||
return try body(&_box.storage)
|
||||
}
|
||||
}
|
||||
|
||||
#if false // FIXME: Use it or lose it
|
||||
extension Shared where Storage: ~Copyable {
|
||||
// This is the actual shape we want. There is currently no way to express it.
|
||||
@inlinable
|
||||
@lifetime(borrow self)
|
||||
public borrowing func read() -> Borrow<Storage> {
|
||||
// This is gloriously (and very explicitly) unsafe, as it should be.
|
||||
// `Shared` is carefully constructed to guarantee that
|
||||
// lifetime(self) == lifetime(_box.storage); but we have not
|
||||
// (cannot) explain this to the compiler.
|
||||
Borrow(unsafeAddress: _address, owner: self)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension Shared where Storage: ~Copyable {
|
||||
@inlinable
|
||||
public func isIdentical(to other: Self) -> Bool {
|
||||
if #available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) {
|
||||
return self._box === other._box
|
||||
} else {
|
||||
// To call the standard `===`, we need to do `_SharedBox` -> AnyObject conversions
|
||||
// that are only supported in the Swift 6+ runtime.
|
||||
let a = Builtin.bridgeToRawPointer(self._box)
|
||||
let b = Builtin.bridgeToRawPointer(other._box)
|
||||
return Bool(Builtin.cmp_eq_RawPointer(a, b))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
//===--- ContiguousStorage.swift ------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public protocol ContiguousStorage<Element>: ~Copyable, ~Escapable {
|
||||
associatedtype Element/*: ~Copyable & ~Escapable*/
|
||||
|
||||
var storage: Span<Element> { borrowing get }
|
||||
}
|
||||
|
||||
extension Span: ContiguousStorage /*where Element: ~Copyable & ~Escapable*/ {
|
||||
public var storage: Self { self }
|
||||
}
|
||||
|
||||
extension Array: ContiguousStorage {
|
||||
public var storage: Span<Element> {
|
||||
_read {
|
||||
if let a = _baseAddressIfContiguous {
|
||||
yield Span(_unsafeStart: a, count: count)
|
||||
}
|
||||
else {
|
||||
let a = ContiguousArray(copy self)
|
||||
#if true
|
||||
let s = Span(
|
||||
_unsafeStart: a._baseAddressIfContiguous!, count: a.count
|
||||
)
|
||||
#else
|
||||
let s = a.storage
|
||||
#endif
|
||||
yield s
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ContiguousArray: ContiguousStorage {
|
||||
public var storage: Span<Element> {
|
||||
borrowing get {
|
||||
Span(
|
||||
_unsafeStart: _baseAddressIfContiguous!, count: count
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension CollectionOfOne: ContiguousStorage {
|
||||
public var storage: Span<Element> {
|
||||
_read {
|
||||
/* ideally: (with strawman syntax)
|
||||
@addressable let value = self._element
|
||||
yield Span(
|
||||
unsafePointer: Builtin.addressable(value), count: 1
|
||||
)
|
||||
*/
|
||||
|
||||
let a = ContiguousArray(self)
|
||||
yield Span(
|
||||
_unsafeStart: a._baseAddressIfContiguous!, count: 1
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension String.UTF8View: ContiguousStorage {
|
||||
public var storage: Span<UTF8.CodeUnit> {
|
||||
_read {
|
||||
if count < 16 { // Wrong way to know whether the String is smol
|
||||
// if _guts.isSmall {
|
||||
// let /*@addressable*/ rawStorage = _guts.asSmall._storage
|
||||
// let span = RawSpan(
|
||||
// unsafeRawPointer: UnsafeRawPointer(Builtin.adressable(rawStorage)),
|
||||
// count: MemoryLayout<_SmallString.RawBitPattern>.size,
|
||||
// owner: self
|
||||
// )
|
||||
// yield span.view(as: UTF8.CodeUnit.self)
|
||||
|
||||
let a = ContiguousArray(self)
|
||||
// yield a.storage
|
||||
yield Span(
|
||||
_unsafeStart: a._baseAddressIfContiguous!, count: 1
|
||||
)
|
||||
}
|
||||
else if let buffer = withContiguousStorageIfAvailable({ $0 }) {
|
||||
// this is totally wrong, but there is a way with stdlib-internal API
|
||||
yield Span(_unsafeElements: buffer)
|
||||
}
|
||||
else { // copy non-fast code units if we don't have eager bridging
|
||||
let a = ContiguousArray(self)
|
||||
// yield a.storage
|
||||
yield Span(
|
||||
_unsafeStart: a._baseAddressIfContiguous!, count: 1
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Builtin
|
||||
|
||||
// FIXME: A better name for the generic argument.
|
||||
|
||||
/// A safe mutable reference allowing in-place mutation to an exclusive value.
|
||||
///
|
||||
/// In order to get an instance of an `Inout<T>`, one must have exclusive access
|
||||
/// to the instance of `T`. This is achieved through the 'inout' operator, '&'.
|
||||
@frozen
|
||||
public struct Inout<T: ~Copyable>: ~Copyable, ~Escapable {
|
||||
@usableFromInline
|
||||
internal let _pointer: UnsafeMutablePointer<T>
|
||||
|
||||
/// Initializes an instance of 'Inout' extending the exclusive access of the
|
||||
/// passed instance.
|
||||
///
|
||||
/// - Parameter instance: The desired instance to get a mutable reference to.
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public init(_ instance: inout T) {
|
||||
_pointer = UnsafeMutablePointer<T>(Builtin.unprotectedAddressOf(&instance))
|
||||
}
|
||||
|
||||
/// Unsafely initializes an instance of 'Inout' using the given 'unsafeAddress'
|
||||
/// as the mutable reference based on the lifetime of the given 'owner'
|
||||
/// argument.
|
||||
///
|
||||
/// - Parameter unsafeAddress: The address to use to mutably reference an
|
||||
/// instance of type 'T'.
|
||||
/// - Parameter owner: The owning instance that this 'Inout' instance's
|
||||
/// lifetime is based on.
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
public init<Owner: ~Copyable & ~Escapable>(
|
||||
unsafeAddress: UnsafeMutablePointer<T>,
|
||||
owner: inout Owner
|
||||
) {
|
||||
_pointer = unsafeAddress
|
||||
}
|
||||
|
||||
/// Unsafely initializes an instance of 'Inout' using the given
|
||||
/// 'unsafeImmortalAddress' as the mutable reference acting as though its
|
||||
/// lifetime is immortal.
|
||||
///
|
||||
/// - Parameter unsafeImmortalAddress: The address to use to mutably reference
|
||||
/// an immortal instance of type 'T'.
|
||||
@_alwaysEmitIntoClient
|
||||
@_transparent
|
||||
@lifetime(immortal)
|
||||
public init(
|
||||
unsafeImmortalAddress: UnsafeMutablePointer<T>
|
||||
) {
|
||||
_pointer = unsafeImmortalAddress
|
||||
}
|
||||
}
|
||||
|
||||
extension Inout where T: ~Copyable {
|
||||
/// Dereferences the mutable reference allowing for in-place reads and writes
|
||||
/// to the underlying instance.
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript() -> T {
|
||||
@_transparent
|
||||
unsafeAddress {
|
||||
UnsafePointer<T>(_pointer)
|
||||
}
|
||||
|
||||
@_transparent
|
||||
nonmutating unsafeMutableAddress {
|
||||
_pointer
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Builtin
|
||||
|
||||
@_unsafeNonescapableResult
|
||||
@inlinable @inline(__always)
|
||||
@lifetime(borrow source)
|
||||
public func unsafelyOverrideLifetime<
|
||||
T: ~Copyable & ~Escapable,
|
||||
U: ~Copyable & ~Escapable
|
||||
>(
|
||||
of dependent: consuming T,
|
||||
to source: borrowing U
|
||||
) -> T {
|
||||
dependent
|
||||
}
|
||||
@@ -1,743 +0,0 @@
|
||||
//===--- MutableSpan.swift ------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Builtin
|
||||
|
||||
// A MutableSpan<Element> represents a span of memory which
|
||||
// contains initialized `Element` instances.
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@frozen
|
||||
public struct MutableSpan<Element: ~Copyable>: ~Copyable & ~Escapable {
|
||||
@usableFromInline let _pointer: UnsafeMutableRawPointer?
|
||||
|
||||
@usableFromInline let _count: Int
|
||||
|
||||
@usableFromInline @inline(__always)
|
||||
var _start: UnsafeMutableRawPointer { _pointer.unsafelyUnwrapped }
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@usableFromInline @inline(__always)
|
||||
@lifetime(borrow start)
|
||||
init(
|
||||
_unchecked start: UnsafeMutableRawPointer?,
|
||||
count: Int
|
||||
) {
|
||||
_pointer = start
|
||||
_count = count
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@available(*, unavailable)
|
||||
extension MutableSpan: Sendable {}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@usableFromInline @inline(__always)
|
||||
@lifetime(borrow elements)
|
||||
internal init(
|
||||
_unchecked elements: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
_pointer = .init(elements.baseAddress)
|
||||
_count = elements.count
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeElements buffer: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
precondition(
|
||||
((Int(bitPattern: buffer.baseAddress) &
|
||||
(MemoryLayout<Element>.alignment&-1)) == 0),
|
||||
"baseAddress must be properly aligned to access Element"
|
||||
)
|
||||
self.init(_unchecked: buffer)
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow start)
|
||||
public init(
|
||||
_unsafeStart start: UnsafeMutablePointer<Element>,
|
||||
count: Int
|
||||
) {
|
||||
precondition(count >= 0, "Count must not be negative")
|
||||
self.init(_unsafeElements: .init(start: start, count: count))
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow elements)
|
||||
public init(
|
||||
_unsafeElements elements: borrowing Slice<UnsafeMutableBufferPointer<Element>>
|
||||
) {
|
||||
self.init(_unsafeElements: UnsafeMutableBufferPointer(rebasing: elements))
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: BitwiseCopyable {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: UnsafeMutableRawBufferPointer
|
||||
) {
|
||||
precondition(
|
||||
((Int(bitPattern: buffer.baseAddress) &
|
||||
(MemoryLayout<Element>.alignment&-1)) == 0),
|
||||
"baseAddress must be properly aligned to access Element"
|
||||
)
|
||||
let (byteCount, stride) = (buffer.count, MemoryLayout<Element>.stride)
|
||||
let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride)
|
||||
precondition(remainder == 0, "Span must contain a whole number of elements")
|
||||
self.init(_unchecked: buffer.baseAddress, count: count)
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
public init(
|
||||
_unsafeStart pointer: UnsafeMutableRawPointer,
|
||||
byteCount: Int
|
||||
) {
|
||||
precondition(byteCount >= 0, "Count must not be negative")
|
||||
self.init(_unsafeBytes: .init(start: pointer, count: byteCount))
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: borrowing Slice<UnsafeMutableRawBufferPointer>
|
||||
) {
|
||||
self.init(_unsafeBytes: UnsafeMutableRawBufferPointer(rebasing: buffer))
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension Span where Element: ~Copyable {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public init(_unsafeMutableSpan mutableSpan: borrowing MutableSpan<Element>) {
|
||||
self.init(_unchecked: mutableSpan._start, count: mutableSpan.count)
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public var storage: Span<Element> { Span(_unsafeMutableSpan: self) }
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (Span<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try body(Span(_unsafeMutableSpan: self))
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension RawSpan {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public init<Element: BitwiseCopyable>(
|
||||
_unsafeMutableSpan mutableSpan: borrowing MutableSpan<Element>
|
||||
) {
|
||||
self.init(
|
||||
_unchecked: mutableSpan._start,
|
||||
byteCount: mutableSpan.count &* MemoryLayout<Element>.stride
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: Equatable {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: borrowing Self) -> Bool {
|
||||
_elementsEqual(Span(_unsafeMutableSpan: other))
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: Span<Element>) -> Bool {
|
||||
Span(_unsafeMutableSpan: self)._elementsEqual(other)
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: some Collection<Element>) -> Bool {
|
||||
Span(_unsafeMutableSpan: self)._elementsEqual(other)
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: some Sequence<Element>) -> Bool {
|
||||
Span(_unsafeMutableSpan: self)._elementsEqual(other)
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var description: String {
|
||||
let addr = String(UInt(bitPattern: _pointer), radix: 16, uppercase: false)
|
||||
return "(0x\(addr), \(_count))"
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: Collection, RandomAccessCollection
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var count: Int { _count }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var isEmpty: Bool { _count == 0 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var _indices: Range<Int> {
|
||||
Range(uncheckedBounds: (0, _count))
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: Bounds Checking
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
/// Return true if `index` is a valid offset into this `Span`
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - index: an index to validate
|
||||
/// - Returns: true if `index` is valid
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public func boundsContain(_ index: Int) -> Bool {
|
||||
0 <= index && index < _count
|
||||
}
|
||||
|
||||
/// Return true if `indices` is a valid range of indices into this `Span`
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - indices: a range of indices to validate
|
||||
/// - Returns: true if `indices` is a valid range of indices
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public func boundsContain(_ indices: Range<Int>) -> Bool {
|
||||
boundsContain(indices.lowerBound) && indices.upperBound <= _count
|
||||
}
|
||||
|
||||
/// Return true if `indices` is a valid range of indices into this `Span`
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - indices: a range of indices to validate
|
||||
/// - Returns: true if `indices` is a valid range of indices
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public func boundsContain(_ indices: ClosedRange<Int>) -> Bool {
|
||||
boundsContain(indices.lowerBound) && indices.upperBound < _count
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: BitwiseCopyable {
|
||||
|
||||
/// Construct a RawSpan over the memory represented by this span
|
||||
///
|
||||
/// - Returns: a RawSpan over the memory represented by this span
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@unsafe //FIXME: remove when the lifetime inference is fixed
|
||||
@_alwaysEmitIntoClient
|
||||
public var _unsafeRawSpan: RawSpan { RawSpan(_unsafeMutableSpan: self) }
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(_ position: Int) -> Element {
|
||||
_read {
|
||||
precondition(boundsContain(position), "index out of bounds")
|
||||
yield self[unchecked: position]
|
||||
}
|
||||
_modify {
|
||||
precondition(boundsContain(position), "index out of bounds")
|
||||
yield &self[unchecked: position]
|
||||
}
|
||||
}
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// This subscript does not validate `position`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(unchecked position: Int) -> Element {
|
||||
_read {
|
||||
let offset = position&*MemoryLayout<Element>.stride
|
||||
let p = UnsafeRawPointer(_start).advanced(by: offset)._rawValue
|
||||
let binding = Builtin.bindMemory(p, count._builtinWordValue, Element.self)
|
||||
defer { Builtin.rebindMemory(p, binding) }
|
||||
yield UnsafePointer(p).pointee
|
||||
}
|
||||
_modify {
|
||||
let offset = position&*MemoryLayout<Element>.stride
|
||||
let p = UnsafeMutableRawPointer(_start).advanced(by: offset)._rawValue
|
||||
let binding = Builtin.bindMemory(p, 1._builtinWordValue, Element.self)
|
||||
defer { Builtin.rebindMemory(p, binding) }
|
||||
yield &(UnsafeMutablePointer(p).pointee)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: BitwiseCopyable {
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(_ position: Int) -> Element {
|
||||
get {
|
||||
precondition(boundsContain(position))
|
||||
return self[unchecked: position]
|
||||
}
|
||||
set {
|
||||
precondition(boundsContain(position))
|
||||
self[unchecked: position] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// This subscript does not validate `position`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(unchecked position: Int) -> Element {
|
||||
get {
|
||||
let offset = position&*MemoryLayout<Element>.stride
|
||||
return _start.loadUnaligned(fromByteOffset: offset, as: Element.self)
|
||||
}
|
||||
set {
|
||||
let offset = position&*MemoryLayout<Element>.stride
|
||||
_start.storeBytes(of: newValue, toByteOffset: offset, as: Element.self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
//FIXME: mark closure parameter as non-escaping
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafeBufferPointer<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ buffer: UnsafeBufferPointer<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try Span(_unsafeMutableSpan: self).withUnsafeBufferPointer(body)
|
||||
}
|
||||
|
||||
//FIXME: mark closure parameter as non-escaping
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func withUnsafeMutableBufferPointer<E: Error, Result: ~Copyable>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
func executeBody(
|
||||
_ start: UnsafeMutablePointer<Element>?, _ count: Int
|
||||
) throws(E) -> Result {
|
||||
var buf = UnsafeMutableBufferPointer<Element>(start: start, count: count)
|
||||
defer {
|
||||
precondition(
|
||||
(buf.baseAddress, buf.count) == (start, count),
|
||||
"MutableSpan.withUnsafeMutableBufferPointer: replacing the buffer is not allowed"
|
||||
)
|
||||
}
|
||||
return try body(&buf)
|
||||
}
|
||||
guard let pointer = _pointer, count > 0 else {
|
||||
return try executeBody(nil, 0)
|
||||
}
|
||||
return try pointer.withMemoryRebound(to: Element.self, capacity: count) {
|
||||
pointer throws(E) -> Result in
|
||||
return try executeBody(pointer, count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: BitwiseCopyable {
|
||||
|
||||
//FIXME: mark closure parameter as non-escaping
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafeBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try RawSpan(_unsafeMutableSpan: self).withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
//FIXME: mark closure parameter as non-escaping
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func withUnsafeMutableBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ buffer: UnsafeMutableRawBufferPointer) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
let bytes = UnsafeMutableRawBufferPointer(
|
||||
start: (_count == 0) ? nil : _start,
|
||||
count: _count &* MemoryLayout<Element>.stride
|
||||
)
|
||||
return try body(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: bulk-update functions
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(repeating repeatedValue: Element) {
|
||||
_start.withMemoryRebound(to: Element.self, capacity: count) {
|
||||
$0.update(repeating: repeatedValue, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update<S: Sequence>(
|
||||
from source: S
|
||||
) -> (unwritten: S.Iterator, index: Int) where S.Element == Element {
|
||||
var iterator = source.makeIterator()
|
||||
let index = update(from: &iterator)
|
||||
return (iterator, index)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
from elements: inout some IteratorProtocol<Element>
|
||||
) -> Int {
|
||||
var index = 0
|
||||
while index < _count {
|
||||
guard let element = elements.next() else { break }
|
||||
self[unchecked: index] = element
|
||||
index &+= 1
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: some Collection<Element>
|
||||
) -> Int {
|
||||
let updated = source.withContiguousStorageIfAvailable {
|
||||
self.update(fromContentsOf: Span(_unsafeElements: $0))
|
||||
}
|
||||
if let updated {
|
||||
return 0.advanced(by: updated)
|
||||
}
|
||||
|
||||
if self.isEmpty {
|
||||
precondition(
|
||||
source.isEmpty,
|
||||
"destination buffer view cannot contain every element from source."
|
||||
)
|
||||
return 0
|
||||
}
|
||||
|
||||
var iterator = source.makeIterator()
|
||||
var index = 0
|
||||
while let value = iterator.next() {
|
||||
precondition(
|
||||
index < _count,
|
||||
"destination buffer view cannot contain every element from source."
|
||||
)
|
||||
self[unchecked: index] = value
|
||||
index &+= 1
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(fromContentsOf source: Span<Element>) -> Int {
|
||||
guard !source.isEmpty else { return 0 }
|
||||
precondition(
|
||||
source.count <= self.count,
|
||||
"destination span cannot contain every element from source."
|
||||
)
|
||||
_start.withMemoryRebound(to: Element.self, capacity: source.count) { dest in
|
||||
source._start().withMemoryRebound(to: Element.self, capacity: source.count) {
|
||||
dest.update(from: $0, count: source.count)
|
||||
}
|
||||
}
|
||||
return source.count
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: borrowing MutableSpan<Element>
|
||||
) -> Int {
|
||||
source.withSpan { self.update(fromContentsOf: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func moveUpdate(
|
||||
fromContentsOf source: consuming OutputSpan<Element>
|
||||
) -> Int {
|
||||
guard !source.isEmpty else { return 0 }
|
||||
precondition(
|
||||
source.count <= self.count,
|
||||
"destination span cannot contain every element from source."
|
||||
)
|
||||
let buffer = source.relinquishBorrowedMemory()
|
||||
// we must now deinitialize the returned UMBP
|
||||
_start.moveInitializeMemory(
|
||||
as: Element.self, from: buffer.baseAddress!, count: buffer.count
|
||||
)
|
||||
return buffer.count
|
||||
}
|
||||
|
||||
public mutating func moveUpdate(
|
||||
fromContentsOf source: UnsafeMutableBufferPointer<Element>
|
||||
) -> Int {
|
||||
#if false
|
||||
guard let sourceAddress = source.baseAddress, source.count > 0 else {
|
||||
return 0
|
||||
}
|
||||
precondition(
|
||||
source.count <= self.count,
|
||||
"destination span cannot contain every element from source."
|
||||
)
|
||||
_start.withMemoryRebound(to: Element.self, capacity: source.count) {
|
||||
$0.moveUpdate(from: sourceAddress, count: source.count)
|
||||
}
|
||||
return source.count
|
||||
#else
|
||||
let source = OutputSpan(_initializing: source, initialized: source.count)
|
||||
return self.moveUpdate(fromContentsOf: source)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan {
|
||||
|
||||
public mutating func moveUpdate(
|
||||
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
|
||||
) -> Int {
|
||||
self.moveUpdate(fromContentsOf: .init(rebasing: source))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: BitwiseCopyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
repeating repeatedValue: Element
|
||||
) where Element: BitwiseCopyable {
|
||||
guard count > 0 else { return }
|
||||
// rebind _start manually in order to avoid assumptions about alignment.
|
||||
let rp = _start._rawValue
|
||||
let binding = Builtin.bindMemory(rp, count._builtinWordValue, Element.self)
|
||||
UnsafeMutablePointer(rp).update(repeating: repeatedValue, count: count)
|
||||
Builtin.rebindMemory(rp, binding)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update<S: Sequence>(
|
||||
from source: S
|
||||
) -> (unwritten: S.Iterator, index: Int)
|
||||
where S.Element == Element, Element: BitwiseCopyable {
|
||||
var iterator = source.makeIterator()
|
||||
let index = update(from: &iterator)
|
||||
return (iterator, index)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
from elements: inout some IteratorProtocol<Element>
|
||||
) -> Int {
|
||||
var index = 0
|
||||
while index < _count {
|
||||
guard let element = elements.next() else { break }
|
||||
self[unchecked: index] = element
|
||||
index &+= 1
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: some Collection<Element>
|
||||
) -> Int where Element: BitwiseCopyable {
|
||||
let updated = source.withContiguousStorageIfAvailable {
|
||||
self.update(fromContentsOf: Span(_unsafeElements: $0))
|
||||
}
|
||||
if let updated {
|
||||
return 0.advanced(by: updated)
|
||||
}
|
||||
|
||||
if self.isEmpty {
|
||||
precondition(
|
||||
source.isEmpty,
|
||||
"destination buffer view cannot contain every element from source."
|
||||
)
|
||||
return 0
|
||||
}
|
||||
|
||||
var iterator = source.makeIterator()
|
||||
var index = 0
|
||||
while let value = iterator.next() {
|
||||
guard index < _count else {
|
||||
fatalError(
|
||||
"destination buffer view cannot contain every element from source."
|
||||
)
|
||||
}
|
||||
self[unchecked: index] = value
|
||||
index &+= 1
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: Span<Element>
|
||||
) -> Int where Element: BitwiseCopyable {
|
||||
guard !source.isEmpty else { return 0 }
|
||||
precondition(
|
||||
source.count <= self.count,
|
||||
"destination span cannot contain every element from source."
|
||||
)
|
||||
_start.copyMemory(
|
||||
from: source._start(), byteCount: source.count&*MemoryLayout<Element>.stride
|
||||
)
|
||||
return source.count
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: borrowing MutableSpan<Element>
|
||||
) -> Int where Element: BitwiseCopyable {
|
||||
self.update(fromContentsOf: source.storage)
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@unsafe
|
||||
public mutating func update(
|
||||
fromContentsOf source: RawSpan
|
||||
) -> Int where Element: BitwiseCopyable {
|
||||
self.update(fromContentsOf: source._unsafeView(as: Element.self))
|
||||
}
|
||||
|
||||
// We have to define the overloads for raw buffers and their slices,
|
||||
// otherwise they would try to use their `Collection` conformance
|
||||
// and fail due to the mismatch in `Element` type.
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: UnsafeRawBufferPointer
|
||||
) -> Int where Element: BitwiseCopyable {
|
||||
self.update(fromContentsOf: RawSpan(_unsafeBytes: source))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: UnsafeMutableRawBufferPointer
|
||||
) -> Int where Element: BitwiseCopyable {
|
||||
self.update(fromContentsOf: RawSpan(_unsafeBytes: source))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: Slice<UnsafeRawBufferPointer>
|
||||
) -> Int where Element: BitwiseCopyable {
|
||||
self.update(fromContentsOf: RawSpan(_unsafeBytes: source))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: Slice<UnsafeMutableRawBufferPointer>
|
||||
) -> Int where Element: BitwiseCopyable {
|
||||
self.update(fromContentsOf: RawSpan(_unsafeBytes: source))
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: copyMemory
|
||||
//FIXME: move these to a MutableRawSpan
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
extension MutableSpan where Element: BitwiseCopyable {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func copyMemory(
|
||||
from source: borrowing MutableSpan<Element>
|
||||
) -> Int where Element: BitwiseCopyable {
|
||||
self.update(fromContentsOf: source.storage)
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func copyMemory(
|
||||
from source: Span<Element>
|
||||
) -> Int where Element: BitwiseCopyable {
|
||||
self.update(fromContentsOf: source)
|
||||
}
|
||||
}
|
||||
@@ -1,693 +0,0 @@
|
||||
//===--- RawSpan.swift ----------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// `RawSpan` represents a contiguous region of memory
|
||||
/// which contains initialized bytes.
|
||||
///
|
||||
/// A `RawSpan` instance is a non-owning, non-escaping view into memory.
|
||||
/// When a `RawSpan` is created, it inherits the lifetime of the container
|
||||
/// owning the contiguous memory, ensuring temporal safety and avoiding
|
||||
/// use-after-free errors. Operations on `RawSpan` are bounds-checked,
|
||||
/// ensuring spcial safety and avoiding buffer overflow errors.
|
||||
@frozen
|
||||
public struct RawSpan: ~Escapable, Copyable, BitwiseCopyable {
|
||||
|
||||
/// The starting address of this `RawSpan`.
|
||||
///
|
||||
/// `_pointer` can be `nil` if and only if `_count` equals 0.
|
||||
/// Otherwise, `_pointer` must point to memory that will remain
|
||||
/// valid and not mutated as long as this `Span` exists.
|
||||
/// The memory at `_pointer` must consist of `_count` initialized bytes.
|
||||
@usableFromInline
|
||||
internal let _pointer: UnsafeRawPointer?
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _start() -> UnsafeRawPointer {
|
||||
_pointer.unsafelyUnwrapped
|
||||
}
|
||||
|
||||
/// The number of bytes in this `RawSpan`.
|
||||
///
|
||||
/// If `_count` equals 0, then `_pointer` may be either `nil` or valid.
|
||||
/// Any `_count` greater than 0 indicates a valid non-nil `_pointer`.
|
||||
/// Any `_count` less than 0 is invalid and is undefined behaviour.
|
||||
@usableFromInline
|
||||
internal let _count: Int
|
||||
|
||||
/// Unsafely create a `RawSpan` over initialized memory.
|
||||
///
|
||||
/// `pointer` must point to a region of `byteCount` initialized bytes,
|
||||
/// or may be `nil` if `count` is 0.
|
||||
///
|
||||
/// The region of `byteCount` bytes of memory starting at `pointer`
|
||||
/// must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pointer: a pointer to the first initialized byte.
|
||||
/// - byteCount: the number of initialized bytes in the span.
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
@lifetime(borrow pointer)
|
||||
internal init(
|
||||
_unchecked pointer: borrowing UnsafeRawPointer?,
|
||||
byteCount: Int
|
||||
) {
|
||||
_pointer = copy pointer
|
||||
_count = byteCount
|
||||
}
|
||||
}
|
||||
|
||||
extension RawSpan: @unchecked Sendable {}
|
||||
|
||||
extension RawSpan {
|
||||
|
||||
/// Unsafely create a `RawSpan` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `RawSpan`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: an `UnsafeRawBufferPointer` to initialized memory.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: borrowing UnsafeRawBufferPointer
|
||||
) {
|
||||
self.init(
|
||||
_unchecked: buffer.baseAddress, byteCount: buffer.count
|
||||
)
|
||||
}
|
||||
|
||||
/// Unsafely create a `RawSpan` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `RawSpan`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: an `UnsafeRawBufferPointer` to initialized memory.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: borrowing Slice<UnsafeRawBufferPointer>
|
||||
) {
|
||||
self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer))
|
||||
}
|
||||
|
||||
/// Unsafely create a `RawSpan` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `RawSpan`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: an `UnsafeRawBufferPointer` to initialized memory.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: borrowing UnsafeMutableRawBufferPointer
|
||||
) {
|
||||
self.init(_unsafeBytes: UnsafeRawBufferPointer(buffer))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: borrowing Slice<UnsafeMutableRawBufferPointer>
|
||||
) {
|
||||
self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer))
|
||||
}
|
||||
|
||||
/// Unsafely create a `RawSpan` over initialized memory.
|
||||
///
|
||||
/// The region of memory representing `byteCount` bytes starting at `pointer`
|
||||
/// must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `RawSpan`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pointer: a pointer to the first initialized byte.
|
||||
/// - byteCount: the number of initialized bytes in the span.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
public init(
|
||||
_unsafeStart pointer: borrowing UnsafeRawPointer,
|
||||
byteCount: Int
|
||||
) {
|
||||
precondition(byteCount >= 0, "Count must not be negative")
|
||||
self.init(_unchecked: copy pointer, byteCount: byteCount)
|
||||
}
|
||||
|
||||
/// Unsafely create a `RawSpan` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `RawSpan`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: an `UnsafeRawBufferPointer` to initialized memory.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init<T: BitwiseCopyable>(
|
||||
_unsafeElements buffer: borrowing UnsafeBufferPointer<T>
|
||||
) {
|
||||
self.init(_unsafeBytes: UnsafeRawBufferPointer(buffer))
|
||||
}
|
||||
|
||||
/// Unsafely create a `RawSpan` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `RawSpan`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: an `UnsafeRawBufferPointer` to initialized memory.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init<T: BitwiseCopyable>(
|
||||
_unsafeElements buffer: borrowing Slice<UnsafeBufferPointer<T>>
|
||||
) {
|
||||
self.init(
|
||||
_unsafeBytes: .init(UnsafeBufferPointer(rebasing: buffer))
|
||||
)
|
||||
}
|
||||
|
||||
/// Unsafely create a `RawSpan` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `RawSpan`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: an `UnsafeRawBufferPointer` to initialized memory.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init<T: BitwiseCopyable>(
|
||||
_unsafeElements buffer: borrowing UnsafeMutableBufferPointer<T>
|
||||
) {
|
||||
self.init(_unsafeElements: UnsafeBufferPointer(buffer))
|
||||
}
|
||||
|
||||
/// Unsafely create a `RawSpan` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `RawSpan`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: an `UnsafeRawBufferPointer` to initialized memory.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init<T: BitwiseCopyable>(
|
||||
_unsafeElements buffer: borrowing Slice<UnsafeMutableBufferPointer<T>>
|
||||
) {
|
||||
self.init(_unsafeBytes: .init(UnsafeBufferPointer(rebasing: buffer)))
|
||||
}
|
||||
|
||||
/// Unsafely create a `RawSpan` over initialized memory.
|
||||
///
|
||||
/// The region of memory representing `byteCount` bytes starting at `pointer`
|
||||
/// must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `RawSpan`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pointer: a pointer to the first initialized byte.
|
||||
/// - byteCount: the number of initialized bytes in the span.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
public init<T: BitwiseCopyable>(
|
||||
_unsafeStart pointer: borrowing UnsafePointer<T>,
|
||||
count: Int
|
||||
) {
|
||||
precondition(count >= 0, "Count must not be negative")
|
||||
self.init(
|
||||
_unchecked: copy pointer, byteCount: count * MemoryLayout<T>.stride
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a `RawSpan` over the memory represented by a `Span<T>`
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - span: An existing `Span<T>`, which will define both this
|
||||
/// `RawSpan`'s lifetime and the memory it represents.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow span)
|
||||
public init<Element: BitwiseCopyable>(
|
||||
_elements span: borrowing Span<Element>
|
||||
) {
|
||||
self.init(
|
||||
_unchecked: span._pointer,
|
||||
byteCount: span.count &* MemoryLayout<Element>.stride
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension RawSpan {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var description: String {
|
||||
let addr = String(UInt(bitPattern: _pointer), radix: 16, uppercase: false)
|
||||
return "(0x\(addr), \(_count))"
|
||||
}
|
||||
}
|
||||
|
||||
extension RawSpan {
|
||||
|
||||
/// The number of bytes in the span.
|
||||
///
|
||||
/// To check whether the span is empty, use its `isEmpty` property
|
||||
/// instead of comparing `count` to zero.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
public var byteCount: Int { _count }
|
||||
|
||||
/// A Boolean value indicating whether the span is empty.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
public var isEmpty: Bool { byteCount == 0 }
|
||||
|
||||
/// The indices that are valid for subscripting the span, in ascending
|
||||
/// order.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
public var byteOffsets: Range<Int> {
|
||||
.init(uncheckedBounds: (0, byteCount))
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: extracting sub-spans
|
||||
extension RawSpan {
|
||||
|
||||
/// Constructs a new span over the bytes within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first byte is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `RawSpan`.
|
||||
///
|
||||
/// - Returns: A span over the bytes within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(_ bounds: Range<Int>) -> Self {
|
||||
precondition(
|
||||
UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&
|
||||
UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),
|
||||
"Byte offset range out of bounds"
|
||||
)
|
||||
return _extracting(unchecked: bounds)
|
||||
}
|
||||
|
||||
/// Constructs a new span over the bytes within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first byte is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// This function does not validate `bounds`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `RawSpan`.
|
||||
///
|
||||
/// - Returns: A span over the bytes within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(unchecked bounds: Range<Int>) -> Self {
|
||||
RawSpan(
|
||||
_unchecked: _pointer?.advanced(by: bounds.lowerBound),
|
||||
byteCount: bounds.count
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructs a new span over the bytes within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first byte is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `RawSpan`.
|
||||
///
|
||||
/// - Returns: A span over the bytes within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(_ bounds: some RangeExpression<Int>) -> Self {
|
||||
_extracting(bounds.relative(to: byteOffsets))
|
||||
}
|
||||
|
||||
/// Constructs a new span over the bytes within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first byte is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// This function does not validate `bounds`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `RawSpan`.
|
||||
///
|
||||
/// - Returns: A span over the bytes within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(
|
||||
unchecked bounds: some RangeExpression<Int>
|
||||
) -> Self {
|
||||
_extracting(unchecked: bounds.relative(to: byteOffsets))
|
||||
}
|
||||
|
||||
/// Constructs a new span over all the bytes of this span.
|
||||
///
|
||||
/// The returned span's first byte is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Returns: A span over all the bytes of this span.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(_: UnboundedRange) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
extension RawSpan {
|
||||
|
||||
/// Calls the given closure with a pointer to the underlying bytes of
|
||||
/// the viewed contiguous storage.
|
||||
///
|
||||
/// The buffer pointer passed as an argument to `body` is valid only
|
||||
/// during the execution of `withUnsafeBytes(_:)`.
|
||||
/// Do not store or return the pointer for later use.
|
||||
///
|
||||
/// - Parameter body: A closure with an `UnsafeRawBufferPointer`
|
||||
/// parameter that points to the viewed contiguous storage.
|
||||
/// If `body` has a return value, that value is also
|
||||
/// used as the return value for the `withUnsafeBytes(_:)` method.
|
||||
/// The closure's parameter is valid only for the duration of
|
||||
/// its execution.
|
||||
/// - Returns: The return value of the `body` closure parameter.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafeBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try body(.init(start: _pointer, count: byteCount))
|
||||
}
|
||||
}
|
||||
|
||||
extension RawSpan {
|
||||
|
||||
/// View the bytes of this span as type `T`
|
||||
///
|
||||
/// This is the equivalent of `unsafeBitCast(_:to:)`. The
|
||||
/// underlying bytes must be initialized as type `T`, be
|
||||
/// initialized to a type that is layout-compatible with `T`,
|
||||
/// or the function mapping bit patterns of length `8*MemoryLayout<T>.size`
|
||||
/// to instances of `T` must be surjective.
|
||||
///
|
||||
/// This is an unsafe operation. Failure to meet the preconditions
|
||||
/// above may produce invalid values of `T`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - type: The type as which to view the bytes of this span.
|
||||
/// - Returns: A typed span viewing these bytes as instances of `T`.
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
consuming public func _unsafeView<T: BitwiseCopyable>(
|
||||
as type: T.Type
|
||||
) -> Span<T> {
|
||||
Span(_unsafeBytes: .init(start: _pointer, count: _count))
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: load
|
||||
extension RawSpan {
|
||||
|
||||
/// Returns a new instance of the given type, constructed from the raw memory
|
||||
/// at the specified offset.
|
||||
///
|
||||
/// The memory at this pointer plus `offset` must be properly aligned for
|
||||
/// accessing `T` and initialized to `T` or another type that is layout
|
||||
/// compatible with `T`.
|
||||
///
|
||||
/// This is an unsafe operation. Failure to meet the preconditions
|
||||
/// above may produce an invalid value of `T`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The offset from this pointer, in bytes. `offset` must be
|
||||
/// nonnegative. The default is zero.
|
||||
/// - type: The type of the instance to create.
|
||||
/// - Returns: A new instance of type `T`, read from the raw bytes at
|
||||
/// `offset`. The returned instance is memory-managed and unassociated
|
||||
/// with the value in the memory referenced by this pointer.
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public func unsafeLoad<T>(
|
||||
fromByteOffset offset: Int = 0, as: T.Type
|
||||
) -> T {
|
||||
precondition(
|
||||
UInt(bitPattern: offset) <= UInt(bitPattern: _count) &&
|
||||
MemoryLayout<T>.size <= (_count &- offset),
|
||||
"Byte offset range out of bounds"
|
||||
)
|
||||
return unsafeLoad(fromUncheckedByteOffset: offset, as: T.self)
|
||||
}
|
||||
|
||||
/// Returns a new instance of the given type, constructed from the raw memory
|
||||
/// at the specified offset.
|
||||
///
|
||||
/// The memory at this pointer plus `offset` must be properly aligned for
|
||||
/// accessing `T` and initialized to `T` or another type that is layout
|
||||
/// compatible with `T`.
|
||||
///
|
||||
/// This is an unsafe operation. This function does not validate the bounds
|
||||
/// of the memory access, and failure to meet the preconditions
|
||||
/// above may produce an invalid value of `T`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The offset from this pointer, in bytes. `offset` must be
|
||||
/// nonnegative. The default is zero.
|
||||
/// - type: The type of the instance to create.
|
||||
/// - Returns: A new instance of type `T`, read from the raw bytes at
|
||||
/// `offset`. The returned instance is memory-managed and unassociated
|
||||
/// with the value in the memory referenced by this pointer.
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public func unsafeLoad<T>(
|
||||
fromUncheckedByteOffset offset: Int, as: T.Type
|
||||
) -> T {
|
||||
_start().load(fromByteOffset: offset, as: T.self)
|
||||
}
|
||||
|
||||
/// Returns a new instance of the given type, constructed from the raw memory
|
||||
/// at the specified offset.
|
||||
///
|
||||
/// The memory at this pointer plus `offset` must be initialized to `T`
|
||||
/// or another type that is layout compatible with `T`.
|
||||
///
|
||||
/// This is an unsafe operation. Failure to meet the preconditions
|
||||
/// above may produce an invalid value of `T`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The offset from this pointer, in bytes. `offset` must be
|
||||
/// nonnegative. The default is zero.
|
||||
/// - type: The type of the instance to create.
|
||||
/// - Returns: A new instance of type `T`, read from the raw bytes at
|
||||
/// `offset`. The returned instance isn't associated
|
||||
/// with the value in the range of memory referenced by this pointer.
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public func unsafeLoadUnaligned<T: BitwiseCopyable>(
|
||||
fromByteOffset offset: Int = 0, as: T.Type
|
||||
) -> T {
|
||||
precondition(
|
||||
UInt(bitPattern: offset) <= UInt(bitPattern: _count) &&
|
||||
MemoryLayout<T>.size <= (_count &- offset),
|
||||
"Byte offset range out of bounds"
|
||||
)
|
||||
return unsafeLoadUnaligned(fromUncheckedByteOffset: offset, as: T.self)
|
||||
}
|
||||
|
||||
/// Returns a new instance of the given type, constructed from the raw memory
|
||||
/// at the specified offset.
|
||||
///
|
||||
/// The memory at this pointer plus `offset` must be initialized to `T`
|
||||
/// or another type that is layout compatible with `T`.
|
||||
///
|
||||
/// This is an unsafe operation. This function does not validate the bounds
|
||||
/// of the memory access, and failure to meet the preconditions
|
||||
/// above may produce an invalid value of `T`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The offset from this pointer, in bytes. `offset` must be
|
||||
/// nonnegative. The default is zero.
|
||||
/// - type: The type of the instance to create.
|
||||
/// - Returns: A new instance of type `T`, read from the raw bytes at
|
||||
/// `offset`. The returned instance isn't associated
|
||||
/// with the value in the range of memory referenced by this pointer.
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public func unsafeLoadUnaligned<T: BitwiseCopyable>(
|
||||
fromUncheckedByteOffset offset: Int, as: T.Type
|
||||
) -> T {
|
||||
_start().loadUnaligned(fromByteOffset: offset, as: T.self)
|
||||
}
|
||||
}
|
||||
|
||||
extension RawSpan {
|
||||
/// Returns a Boolean value indicating whether two `RawSpan` instances
|
||||
/// refer to the same region in memory.
|
||||
@_alwaysEmitIntoClient
|
||||
public func isIdentical(to other: Self) -> Bool {
|
||||
(self._pointer == other._pointer) && (self._count == other._count)
|
||||
}
|
||||
|
||||
/// Returns the offsets where the memory of `span` is located within
|
||||
/// the memory represented by `self`
|
||||
///
|
||||
/// Note: `span` must be a subrange of `self`
|
||||
///
|
||||
/// Parameters:
|
||||
/// - span: a subrange of `self`
|
||||
/// Returns: A range of offsets within `self`
|
||||
@_alwaysEmitIntoClient
|
||||
public func byteOffsets(of other: borrowing Self) -> Range<Int>? {
|
||||
if other._count > _count { return nil }
|
||||
guard let spanStart = other._pointer, _count > 0 else {
|
||||
return _pointer == other._pointer ? Range(uncheckedBounds: (0, 0)) : nil
|
||||
}
|
||||
let start = _start()
|
||||
let spanEnd = spanStart + other._count
|
||||
if spanStart < start || (start + _count) < spanEnd { return nil }
|
||||
let lower = start.distance(to: spanStart)
|
||||
return Range(uncheckedBounds: (lower, lower &+ other._count))
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: prefixes and suffixes
|
||||
extension RawSpan {
|
||||
|
||||
/// Returns a span containing the initial bytes of this span,
|
||||
/// up to the specified maximum byte count.
|
||||
///
|
||||
/// If the maximum length exceeds the length of this span,
|
||||
/// the result contains all the bytes.
|
||||
///
|
||||
/// The returned span's first byte is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of bytes to return.
|
||||
/// `maxLength` must be greater than or equal to zero.
|
||||
/// - Returns: A span with at most `maxLength` bytes.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(first maxLength: Int) -> Self {
|
||||
precondition(maxLength >= 0, "Can't have a prefix of negative length")
|
||||
let newCount = min(maxLength, byteCount)
|
||||
return Self(_unchecked: _pointer, byteCount: newCount)
|
||||
}
|
||||
|
||||
/// Returns a span over all but the given number of trailing bytes.
|
||||
///
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the span, the result is an empty span.
|
||||
///
|
||||
/// The returned span's first byte is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter k: The number of bytes to drop off the end of
|
||||
/// the span. `k` must be greater than or equal to zero.
|
||||
/// - Returns: A span leaving off the specified number of bytes at the end.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(droppingLast k: Int) -> Self {
|
||||
precondition(k >= 0, "Can't drop a negative number of elements")
|
||||
let droppedCount = min(k, byteCount)
|
||||
return Self(_unchecked: _pointer, byteCount: byteCount &- droppedCount)
|
||||
}
|
||||
|
||||
/// Returns a span containing the trailing bytes of the span,
|
||||
/// up to the given maximum length.
|
||||
///
|
||||
/// If the maximum length exceeds the length of this span,
|
||||
/// the result contains all the bytes.
|
||||
///
|
||||
/// The returned span's first byte is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of bytes to return.
|
||||
/// `maxLength` must be greater than or equal to zero.
|
||||
/// - Returns: A span with at most `maxLength` bytes.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(last maxLength: Int) -> Self {
|
||||
precondition(maxLength >= 0, "Can't have a suffix of negative length")
|
||||
let newCount = min(maxLength, byteCount)
|
||||
let newStart = _pointer?.advanced(by: byteCount &- newCount)
|
||||
return Self(_unchecked: newStart, byteCount: newCount)
|
||||
}
|
||||
|
||||
/// Returns a span over all but the given number of initial bytes.
|
||||
///
|
||||
/// If the number of elements to drop exceeds the number of bytes in
|
||||
/// the span, the result is an empty span.
|
||||
///
|
||||
/// The returned span's first byte is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter k: The number of bytes to drop from the beginning of
|
||||
/// the span. `k` must be greater than or equal to zero.
|
||||
/// - Returns: A span starting after the specified number of bytes.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(droppingFirst k: Int) -> Self {
|
||||
precondition(k >= 0, "Can't drop a negative number of elements")
|
||||
let droppedCount = min(k, byteCount)
|
||||
let newStart = _pointer?.advanced(by: droppedCount)
|
||||
return Self(_unchecked: newStart, byteCount: byteCount &- droppedCount)
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
//===--- SpanIterator.swift -----------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Span where Element: ~Copyable {
|
||||
@frozen
|
||||
public struct Iterator: Copyable, ~Escapable {
|
||||
var curPointer: UnsafeRawPointer?
|
||||
let endPointer: UnsafeRawPointer?
|
||||
|
||||
@lifetime(span)
|
||||
public init(from span: consuming Span<Element>) {
|
||||
curPointer = span._pointer
|
||||
endPointer = span._pointer?.advanced(
|
||||
by: span.count*MemoryLayout<Element>.stride
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Span.Iterator where Element: Copyable {
|
||||
|
||||
// This is the `IteratorProtocol` requirement, except that
|
||||
// Span.Iterator does not conform to `Escapable`
|
||||
public mutating func next() -> Element? {
|
||||
guard curPointer != endPointer,
|
||||
let cur = curPointer, cur < endPointer.unsafelyUnwrapped
|
||||
else { return nil }
|
||||
defer {
|
||||
curPointer = cur.advanced(by: MemoryLayout<Element>.stride)
|
||||
}
|
||||
if _isPOD(Element.self) {
|
||||
return cur.loadUnaligned(as: Element.self)
|
||||
}
|
||||
return cur.load(as: Element.self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Span.Iterator where Element: BitwiseCopyable {
|
||||
|
||||
// This is the `IteratorProtocol` requirement, except that
|
||||
// Span.Iterator does not conform to `Escapable`
|
||||
public mutating func next() -> Element? {
|
||||
guard curPointer != endPointer,
|
||||
let cur = curPointer, cur < endPointer.unsafelyUnwrapped
|
||||
else { return nil }
|
||||
defer {
|
||||
curPointer = cur.advanced(by: MemoryLayout<Element>.stride)
|
||||
}
|
||||
return cur.loadUnaligned(as: Element.self)
|
||||
}
|
||||
}
|
||||
@@ -1,830 +0,0 @@
|
||||
//===--- Span.swift -------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Builtin
|
||||
|
||||
/// `Span<Element>` represents a contiguous region of memory
|
||||
/// which contains initialized instances of `Element`.
|
||||
///
|
||||
/// A `Span` instance is a non-owning, non-escaping view into memory.
|
||||
/// When a `Span` is created, it inherits the lifetime of the container
|
||||
/// owning the contiguous memory, ensuring temporal safety and avoiding
|
||||
/// use-after-free errors. Operations on `Span` are bounds-checked,
|
||||
/// ensuring spcial safety and avoiding buffer overflow errors.
|
||||
@frozen
|
||||
public struct Span<Element: ~Copyable & ~Escapable>
|
||||
: ~Escapable, Copyable, BitwiseCopyable {
|
||||
|
||||
/// The starting address of this `Span`.
|
||||
///
|
||||
/// `_pointer` can be `nil` if and only if `_count` equals 0.
|
||||
/// Otherwise, `_pointer` must point to memory that will remain
|
||||
/// valid and not mutated as long as this `Span` exists.
|
||||
/// The memory at `_pointer` must be initialized
|
||||
/// as `_count` instances of `Element`.
|
||||
@usableFromInline
|
||||
internal let _pointer: UnsafeRawPointer?
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _start() -> UnsafeRawPointer {
|
||||
_pointer.unsafelyUnwrapped
|
||||
}
|
||||
|
||||
/// The number of elements in this `Span`.
|
||||
///
|
||||
/// If `_count` equals 0, then `_pointer` may be either `nil` or valid.
|
||||
/// Any `_count` greater than 0 indicates a valid non-nil `_pointer`.
|
||||
/// Any `_count` less than 0 is invalid and is undefined behaviour.
|
||||
@usableFromInline
|
||||
internal let _count: Int
|
||||
|
||||
/// FIXME: Remove once supported old compilers can recognize lifetime dependence
|
||||
@_unsafeNonescapableResult
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
internal init() {
|
||||
_pointer = nil
|
||||
_count = 0
|
||||
}
|
||||
|
||||
/// Unsafely create a `Span` over initialized memory.
|
||||
///
|
||||
/// `pointer` must point to a region of `count` initialized instances,
|
||||
/// or may be `nil` if `count` is 0.
|
||||
///
|
||||
/// The region of memory representing `count` instances starting at `pointer`
|
||||
/// must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pointer: a pointer to the first initialized element.
|
||||
/// - count: the number of initialized elements in the span.
|
||||
@_alwaysEmitIntoClient
|
||||
@inline(__always)
|
||||
@lifetime(borrow pointer)
|
||||
internal init(
|
||||
_unchecked pointer: borrowing UnsafeRawPointer?,
|
||||
count: Int
|
||||
) {
|
||||
_pointer = copy pointer
|
||||
_count = count
|
||||
}
|
||||
}
|
||||
|
||||
extension Span: @unchecked Sendable where Element: Sendable {}
|
||||
|
||||
extension Span where Element: ~Copyable {
|
||||
|
||||
/// Unsafely create a `Span` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: an `UnsafeBufferPointer` to initialized elements.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeElements buffer: borrowing UnsafeBufferPointer<Element>
|
||||
) {
|
||||
//FIXME: Workaround for https://github.com/swiftlang/swift/issues/77235
|
||||
let baseAddress = buffer.baseAddress
|
||||
precondition(
|
||||
((Int(bitPattern: baseAddress) &
|
||||
(MemoryLayout<Element>.alignment &- 1)) == 0),
|
||||
"baseAddress must be properly aligned to access Element"
|
||||
)
|
||||
self.init(_unchecked: baseAddress, count: buffer.count)
|
||||
}
|
||||
|
||||
/// Unsafely create a `Span` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: an `UnsafeMutableBufferPointer` to initialized elements.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeElements buffer: borrowing UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
self.init(_unsafeElements: UnsafeBufferPointer(buffer))
|
||||
}
|
||||
|
||||
/// Unsafely create a `Span` over initialized memory.
|
||||
///
|
||||
/// The region of memory representing `count` instances starting at `pointer`
|
||||
/// must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pointer: a pointer to the first initialized element.
|
||||
/// - count: the number of initialized elements in the span.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
public init(
|
||||
_unsafeStart pointer: borrowing UnsafePointer<Element>,
|
||||
count: Int
|
||||
) {
|
||||
precondition(count >= 0, "Count must not be negative")
|
||||
self.init(_unsafeElements: .init(start: copy pointer, count: count))
|
||||
}
|
||||
}
|
||||
|
||||
extension Span {
|
||||
|
||||
/// Unsafely create a `Span` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: an `UnsafeBufferPointer` to initialized elements.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeElements buffer: borrowing Slice<UnsafeBufferPointer<Element>>
|
||||
) {
|
||||
self.init(_unsafeElements: UnsafeBufferPointer(rebasing: buffer))
|
||||
}
|
||||
|
||||
/// Unsafely create a `Span` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: an `UnsafeMutableBufferPointer` to initialized elements.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeElements buffer: borrowing Slice<UnsafeMutableBufferPointer<Element>>
|
||||
) {
|
||||
self.init(_unsafeElements: UnsafeBufferPointer(rebasing: buffer))
|
||||
}
|
||||
}
|
||||
|
||||
extension Span where Element: BitwiseCopyable {
|
||||
|
||||
/// Unsafely create a `Span` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// `buffer` must be correctly aligned for accessing
|
||||
/// an element of type `Element`, and must contain a number of bytes
|
||||
/// that is an exact multiple of `Element`'s stride.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: a buffer to initialized elements.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: borrowing UnsafeRawBufferPointer
|
||||
) {
|
||||
//FIXME: Workaround for https://github.com/swiftlang/swift/issues/77235
|
||||
let baseAddress = buffer.baseAddress
|
||||
precondition(
|
||||
((Int(bitPattern: baseAddress) &
|
||||
(MemoryLayout<Element>.alignment &- 1)) == 0),
|
||||
"baseAddress must be properly aligned to access Element"
|
||||
)
|
||||
let (byteCount, stride) = (buffer.count, MemoryLayout<Element>.stride)
|
||||
let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride)
|
||||
precondition(
|
||||
remainder == 0, "Span must contain a whole number of elements"
|
||||
)
|
||||
self.init(_unchecked: baseAddress, count: count)
|
||||
}
|
||||
|
||||
/// Unsafely create a `Span` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// `buffer` must be correctly aligned for accessing
|
||||
/// an element of type `Element`, and must contain a number of bytes
|
||||
/// that is an exact multiple of `Element`'s stride.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: a buffer to initialized elements.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: borrowing UnsafeMutableRawBufferPointer
|
||||
) {
|
||||
self.init(_unsafeBytes: UnsafeRawBufferPointer(buffer))
|
||||
}
|
||||
|
||||
/// Unsafely create a `Span` over initialized memory.
|
||||
///
|
||||
/// The region of memory representing the instances starting at `pointer`
|
||||
/// must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// `pointer` must be correctly aligned for accessing
|
||||
/// an element of type `Element`, and `byteCount`
|
||||
/// must be an exact multiple of `Element`'s stride.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pointer: a pointer to the first initialized element.
|
||||
/// - byteCount: the number of initialized elements in the span.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
public init(
|
||||
_unsafeStart pointer: borrowing UnsafeRawPointer,
|
||||
byteCount: Int
|
||||
) {
|
||||
precondition(byteCount >= 0, "Count must not be negative")
|
||||
self.init(_unsafeBytes: .init(start: copy pointer, count: byteCount))
|
||||
}
|
||||
|
||||
/// Unsafely create a `Span` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// `buffer` must be correctly aligned for accessing
|
||||
/// an element of type `Element`, and must contain a number of bytes
|
||||
/// that is an exact multiple of `Element`'s stride.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: a buffer to initialized elements.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: borrowing Slice<UnsafeRawBufferPointer>
|
||||
) {
|
||||
self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer))
|
||||
}
|
||||
|
||||
/// Unsafely create a `Span` over initialized memory.
|
||||
///
|
||||
/// The memory in `buffer` must remain valid, initialized and immutable
|
||||
/// throughout the lifetime of the newly-created `Span`.
|
||||
/// Failure to maintain this invariant results in undefined behaviour.
|
||||
///
|
||||
/// `buffer` must be correctly aligned for accessing
|
||||
/// an element of type `Element`, and must contain a number of bytes
|
||||
/// that is an exact multiple of `Element`'s stride.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - buffer: a buffer to initialized elements.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: borrowing Slice<UnsafeMutableRawBufferPointer>
|
||||
) {
|
||||
self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer))
|
||||
}
|
||||
|
||||
/// Create a `Span` over the bytes represented by a `RawSpan`
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bytes: An existing `RawSpan`, which will define both this
|
||||
/// `Span`'s lifetime and the memory it represents.
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(bytes)
|
||||
public init(_bytes bytes: consuming RawSpan) {
|
||||
self.init(
|
||||
_unsafeBytes: .init(start: bytes._pointer, count: bytes.byteCount)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension Span where Element: Equatable {
|
||||
|
||||
/// Returns a Boolean value indicating whether this and another span
|
||||
/// contain equal elements in the same order.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - other: A span to compare to this one.
|
||||
/// - Returns: `true` if this sequence and `other` contain equivalent items,
|
||||
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
|
||||
///
|
||||
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
|
||||
/// sequence and the length of `other`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: Self) -> Bool {
|
||||
guard count == other.count else { return false }
|
||||
if count == 0 { return true }
|
||||
|
||||
//FIXME: This could be short-cut
|
||||
// with a layout constraint where stride equals size,
|
||||
// as long as there is at most 1 unused bit pattern.
|
||||
// if Element is BitwiseEquatable {
|
||||
// return _swift_stdlib_memcmp(lhs.baseAddress, rhs.baseAddress, count) == 0
|
||||
// }
|
||||
for o in 0..<count {
|
||||
if self[unchecked: o] != other[unchecked: o] { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Returns a Boolean value indicating whether this span and a Collection
|
||||
/// contain equal elements in the same order.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - other: A Collection to compare to this span.
|
||||
/// - Returns: `true` if this sequence and `other` contain equivalent items,
|
||||
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
|
||||
///
|
||||
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
|
||||
/// sequence and the length of `other`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: some Collection<Element>) -> Bool {
|
||||
let equal = other.withContiguousStorageIfAvailable {
|
||||
_elementsEqual(Span(_unsafeElements: $0))
|
||||
}
|
||||
if let equal { return equal }
|
||||
|
||||
guard count == other.count else { return false }
|
||||
if count == 0 { return true }
|
||||
|
||||
return _elementsEqual(AnySequence(other))
|
||||
}
|
||||
|
||||
/// Returns a Boolean value indicating whether this span and a Sequence
|
||||
/// contain equal elements in the same order.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - other: A Sequence to compare to this span.
|
||||
/// - Returns: `true` if this sequence and `other` contain equivalent items,
|
||||
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
|
||||
///
|
||||
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
|
||||
/// sequence and the length of `other`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: some Sequence<Element>) -> Bool {
|
||||
var offset = 0
|
||||
for otherElement in other {
|
||||
if offset >= count { return false }
|
||||
if self[unchecked: offset] != otherElement { return false }
|
||||
offset += 1
|
||||
}
|
||||
return offset == count
|
||||
}
|
||||
}
|
||||
|
||||
extension Span where Element: ~Copyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var description: String {
|
||||
let addr = String(UInt(bitPattern: _pointer), radix: 16, uppercase: false)
|
||||
return "(0x\(addr), \(_count))"
|
||||
}
|
||||
}
|
||||
|
||||
extension Span where Element: ~Copyable {
|
||||
|
||||
/// The number of elements in the span.
|
||||
///
|
||||
/// To check whether the span is empty, use its `isEmpty` property
|
||||
/// instead of comparing `count` to zero.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
public var count: Int { _count }
|
||||
|
||||
/// A Boolean value indicating whether the span is empty.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
public var isEmpty: Bool { _count == 0 }
|
||||
|
||||
/// The representation for a position in `Span`.
|
||||
public typealias Index = Int
|
||||
|
||||
/// The indices that are valid for subscripting the span, in ascending
|
||||
/// order.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
public var indices: Range<Index> {
|
||||
Range(uncheckedBounds: (0, _count))
|
||||
}
|
||||
}
|
||||
|
||||
extension Span where Element: ~Copyable {
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(_ position: Index) -> Element {
|
||||
//FIXME: change to unsafeRawAddress when ready
|
||||
unsafeAddress {
|
||||
precondition(indices.contains(position), "Index out of bounds")
|
||||
return _unsafeAddressOfElement(unchecked: position)
|
||||
}
|
||||
}
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// This subscript does not validate `position`. Using this subscript
|
||||
/// with an invalid `position` results in undefined behaviour.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(unchecked position: Index) -> Element {
|
||||
//FIXME: change to unsafeRawAddress when ready
|
||||
unsafeAddress {
|
||||
_unsafeAddressOfElement(unchecked: position)
|
||||
}
|
||||
}
|
||||
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _unsafeAddressOfElement(
|
||||
unchecked position: Index
|
||||
) -> UnsafePointer<Element> {
|
||||
let elementOffset = position &* MemoryLayout<Element>.stride
|
||||
let address = _start().advanced(by: elementOffset)
|
||||
return address.assumingMemoryBound(to: Element.self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Span where Element: BitwiseCopyable {
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(_ position: Index) -> Element {
|
||||
get {
|
||||
precondition(
|
||||
UInt(bitPattern: position) < UInt(bitPattern: _count),
|
||||
"Index out of bounds"
|
||||
)
|
||||
return self[unchecked: position]
|
||||
}
|
||||
}
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// This subscript does not validate `position`. Using this subscript
|
||||
/// with an invalid `position` results in undefined behaviour.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(unchecked position: Index) -> Element {
|
||||
get {
|
||||
let elementOffset = position &* MemoryLayout<Element>.stride
|
||||
let address = _start().advanced(by: elementOffset)
|
||||
return address.loadUnaligned(as: Element.self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: sub-spans
|
||||
extension Span where Element: ~Copyable {
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `Span`.
|
||||
///
|
||||
/// - Returns: A `Span` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(_ bounds: Range<Index>) -> Self {
|
||||
precondition(
|
||||
UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&
|
||||
UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),
|
||||
"Index range out of bounds"
|
||||
)
|
||||
return _extracting(unchecked: bounds)
|
||||
}
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// This function does not validate `bounds`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `Span`.
|
||||
///
|
||||
/// - Returns: A `Span` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(unchecked bounds: Range<Index>) -> Self {
|
||||
let delta = bounds.lowerBound &* MemoryLayout<Element>.stride
|
||||
return Span(_unchecked: _pointer?.advanced(by: delta), count: bounds.count)
|
||||
}
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `Span`.
|
||||
///
|
||||
/// - Returns: A `Span` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(_ bounds: some RangeExpression<Int>) -> Self {
|
||||
_extracting(bounds.relative(to: indices))
|
||||
}
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// This function does not validate `bounds`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `Span`.
|
||||
///
|
||||
/// - Returns: A `Span` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(
|
||||
unchecked bounds: some RangeExpression<Int>
|
||||
) -> Self {
|
||||
_extracting(unchecked: bounds.relative(to: indices))
|
||||
}
|
||||
|
||||
/// Constructs a new span over all the items of this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Returns: A `Span` over all the items of this span.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(_: UnboundedRange) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: UnsafeBufferPointer access hatch
|
||||
extension Span where Element: ~Copyable {
|
||||
|
||||
/// Calls a closure with a pointer to the viewed contiguous storage.
|
||||
///
|
||||
/// The buffer pointer passed as an argument to `body` is valid only
|
||||
/// during the execution of `withUnsafeBufferPointer(_:)`.
|
||||
/// Do not store or return the pointer for later use.
|
||||
///
|
||||
/// - Parameter body: A closure with an `UnsafeBufferPointer` parameter
|
||||
/// that points to the viewed contiguous storage. If `body` has
|
||||
/// a return value, that value is also used as the return value
|
||||
/// for the `withUnsafeBufferPointer(_:)` method. The closure's
|
||||
/// parameter is valid only for the duration of its execution.
|
||||
/// - Returns: The return value of the `body` closure parameter.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafeBufferPointer<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ buffer: UnsafeBufferPointer<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
guard let pointer = _pointer else {
|
||||
return try body(.init(start: nil, count: 0))
|
||||
}
|
||||
let binding = Builtin.bindMemory(
|
||||
pointer._rawValue, count._builtinWordValue, Element.self
|
||||
)
|
||||
defer { Builtin.rebindMemory(pointer._rawValue, binding) }
|
||||
return try body(.init(start: .init(pointer._rawValue), count: count))
|
||||
}
|
||||
}
|
||||
|
||||
extension Span where Element: BitwiseCopyable {
|
||||
|
||||
/// Calls the given closure with a pointer to the underlying bytes of
|
||||
/// the viewed contiguous storage.
|
||||
///
|
||||
/// The buffer pointer passed as an argument to `body` is valid only
|
||||
/// during the execution of `withUnsafeBytes(_:)`.
|
||||
/// Do not store or return the pointer for later use.
|
||||
///
|
||||
/// - Parameter body: A closure with an `UnsafeRawBufferPointer`
|
||||
/// parameter that points to the viewed contiguous storage.
|
||||
/// If `body` has a return value, that value is also
|
||||
/// used as the return value for the `withUnsafeBytes(_:)` method.
|
||||
/// The closure's parameter is valid only for the duration of
|
||||
/// its execution.
|
||||
/// - Returns: The return value of the `body` closure parameter.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafeBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try body(
|
||||
.init(start: _pointer, count: _count * MemoryLayout<Element>.stride)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// `first` and `last` can't exist where Element: ~Copyable
|
||||
// because we can't construct an Optional of a borrow
|
||||
extension Span where Element: Copyable {
|
||||
|
||||
/// The first element in the span.
|
||||
///
|
||||
/// If the span is empty, the value of this property is `nil`.
|
||||
///
|
||||
/// - Returns: The first element in the span, or `nil` if empty
|
||||
@_alwaysEmitIntoClient
|
||||
public var first: Element? {
|
||||
isEmpty ? nil : self[unchecked: 0]
|
||||
}
|
||||
|
||||
/// The last element in the span.
|
||||
///
|
||||
/// If the span is empty, the value of this property is `nil`.
|
||||
///
|
||||
/// - Returns: The last element in the span, or `nil` if empty
|
||||
@_alwaysEmitIntoClient
|
||||
public var last: Element? {
|
||||
isEmpty ? nil : self[unchecked: count &- 1]
|
||||
}
|
||||
}
|
||||
|
||||
extension Span where Element: ~Copyable {
|
||||
/// Returns a Boolean value indicating whether two `Span` instances
|
||||
/// refer to the same region in memory.
|
||||
@_alwaysEmitIntoClient
|
||||
public func isIdentical(to other: Self) -> Bool {
|
||||
(self._pointer == other._pointer) && (self._count == other._count)
|
||||
}
|
||||
|
||||
/// Returns the indices within `self` where the memory represented by `span`
|
||||
/// is located, or `nil` if `span` is not located within `self`.
|
||||
///
|
||||
/// Parameters:
|
||||
/// - span: a span that may be a subrange of `self`
|
||||
/// Returns: A range of indices within `self`, or `nil`
|
||||
@_alwaysEmitIntoClient
|
||||
public func indices(of other: borrowing Self) -> Range<Index>? {
|
||||
if other._count > _count { return nil }
|
||||
guard let spanStart = other._pointer, _count > 0 else {
|
||||
return _pointer == other._pointer ? Range(uncheckedBounds: (0, 0)) : nil
|
||||
}
|
||||
let start = _start()
|
||||
let stride = MemoryLayout<Element>.stride
|
||||
let spanEnd = spanStart + stride &* other._count
|
||||
if spanStart < start || spanEnd > (start + stride &* _count) { return nil }
|
||||
let byteOffset = start.distance(to: spanStart)
|
||||
let (lower, r) = byteOffset.quotientAndRemainder(dividingBy: stride)
|
||||
guard r == 0 else { return nil }
|
||||
return Range(uncheckedBounds: (lower, lower &+ other._count))
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: prefixes and suffixes
|
||||
extension Span where Element: ~Copyable {
|
||||
|
||||
/// Returns a span containing the initial elements of this span,
|
||||
/// up to the specified maximum length.
|
||||
///
|
||||
/// If the maximum length exceeds the length of this span,
|
||||
/// the result contains all the elements.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans 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 span with at most `maxLength` elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(first maxLength: Int) -> Self {
|
||||
precondition(maxLength >= 0, "Can't have a prefix of negative length")
|
||||
let newCount = min(maxLength, count)
|
||||
return Self(_unchecked: _pointer, count: newCount)
|
||||
}
|
||||
|
||||
/// Returns a span over all but the given number of trailing elements.
|
||||
///
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the span, the result is an empty span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter k: The number of elements to drop off the end of
|
||||
/// the span. `k` must be greater than or equal to zero.
|
||||
/// - Returns: A span leaving off the specified number of elements at the end.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(droppingLast k: Int) -> Self {
|
||||
precondition(k >= 0, "Can't drop a negative number of elements")
|
||||
let droppedCount = min(k, count)
|
||||
return Self(_unchecked: _pointer, count: count &- droppedCount)
|
||||
}
|
||||
|
||||
/// Returns a span containing the final elements of the span,
|
||||
/// up to the given maximum length.
|
||||
///
|
||||
/// If the maximum length exceeds the length of this span,
|
||||
/// the result contains all the elements.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans 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 span with at most `maxLength` elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(last maxLength: Int) -> Self {
|
||||
precondition(maxLength >= 0, "Can't have a suffix of negative length")
|
||||
let newCount = min(maxLength, count)
|
||||
let offset = (count &- newCount) * MemoryLayout<Element>.stride
|
||||
let newStart = _pointer?.advanced(by: offset)
|
||||
return Self(_unchecked: newStart, count: newCount)
|
||||
}
|
||||
|
||||
/// Returns a span over all but the given number of initial elements.
|
||||
///
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the span, the result is an empty span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter k: The number of elements to drop from the beginning of
|
||||
/// the span. `k` must be greater than or equal to zero.
|
||||
/// - Returns: A span starting after the specified number of elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(self)
|
||||
public func _extracting(droppingFirst k: Int) -> Self {
|
||||
precondition(k >= 0, "Can't drop a negative number of elements")
|
||||
let droppedCount = min(k, count)
|
||||
let offset = droppedCount * MemoryLayout<Element>.stride
|
||||
let newStart = _pointer?.advanced(by: offset)
|
||||
return Self(_unchecked: newStart, count: count &- droppedCount)
|
||||
}
|
||||
}
|
||||
@@ -1,502 +0,0 @@
|
||||
//===--- StdlibSpanExtensions.swift ---------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension UnsafeBufferPointer where Element: ~Copyable {
|
||||
public func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try body(Span(_unsafeElements: self))
|
||||
}
|
||||
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result where Element: BitwiseCopyable {
|
||||
try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(self)))
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutableBufferPointer where Element: ~Copyable {
|
||||
public func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try body(Span(_unsafeElements: self))
|
||||
}
|
||||
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result where Element: BitwiseCopyable {
|
||||
try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(self)))
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeRawBufferPointer {
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try body(RawSpan(_unsafeBytes: self))
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutableRawBufferPointer {
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try body(RawSpan(_unsafeBytes: self))
|
||||
}
|
||||
}
|
||||
|
||||
extension Slice {
|
||||
public func withSpan<Element, E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result
|
||||
where Base == UnsafeBufferPointer<Element> {
|
||||
try body(Span(_unsafeElements: UnsafeBufferPointer(rebasing: self)))
|
||||
}
|
||||
|
||||
public func withBytes<Element: BitwiseCopyable, E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result
|
||||
where Base == UnsafeBufferPointer<Element> {
|
||||
try body(RawSpan(_unsafeBytes: .init(UnsafeBufferPointer(rebasing: self))))
|
||||
}
|
||||
|
||||
public func withSpan<Element, E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result
|
||||
where Base == UnsafeMutableBufferPointer<Element> {
|
||||
try body(Span(_unsafeElements: UnsafeBufferPointer(rebasing: self)))
|
||||
}
|
||||
|
||||
public func withBytes<Element: BitwiseCopyable, E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result
|
||||
where Base == UnsafeMutableBufferPointer<Element> {
|
||||
try body(RawSpan(_unsafeBytes: .init(UnsafeBufferPointer(rebasing: self))))
|
||||
}
|
||||
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result
|
||||
where Base == UnsafeRawBufferPointer {
|
||||
try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(rebasing: self)))
|
||||
}
|
||||
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result
|
||||
where Base == UnsafeMutableRawBufferPointer {
|
||||
try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(rebasing: self)))
|
||||
}
|
||||
}
|
||||
|
||||
import struct Foundation.Data
|
||||
|
||||
extension Data {
|
||||
public func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<UInt8>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E> in
|
||||
self.withUnsafeBytes {
|
||||
bytes in
|
||||
do throws(E) {
|
||||
let result = try body(Span<UInt8>(_unsafeBytes: bytes))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return buffer.moveElement(from: 0)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ bytes: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E> in
|
||||
self.withUnsafeBytes {
|
||||
bytes in
|
||||
do throws(E) {
|
||||
let result = try body(RawSpan(_unsafeBytes: bytes))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return buffer.moveElement(from: 0)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
}
|
||||
|
||||
extension Array {
|
||||
|
||||
/// Calls a closure with a `Span` of the array's contiguous storage.
|
||||
///
|
||||
/// Often, the optimizer can eliminate bounds checks within an array
|
||||
/// algorithm, but when that fails, invoking the same algorithm on the
|
||||
/// buffer pointer passed into your closure lets you trade safety for speed.
|
||||
///
|
||||
/// The following example shows how you can iterate over the contents of the
|
||||
/// buffer pointer:
|
||||
///
|
||||
/// let numbers = [1, 2, 3, 4, 5]
|
||||
/// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in
|
||||
/// var result = 0
|
||||
/// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) {
|
||||
/// result += buffer[i]
|
||||
/// }
|
||||
/// return result
|
||||
/// }
|
||||
/// // 'sum' == 9
|
||||
///
|
||||
/// The pointer passed as an argument to `body` is valid only during the
|
||||
/// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the
|
||||
/// pointer for later use.
|
||||
///
|
||||
/// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that
|
||||
/// points to the contiguous storage for the array. If no such storage exists, it is created. If
|
||||
/// `body` has a return value, that value is also used as the return value
|
||||
/// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is
|
||||
/// valid only for the duration of the method's execution.
|
||||
/// - Returns: The return value, if any, of the `body` closure parameter.
|
||||
public func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E> in
|
||||
self.withUnsafeBufferPointer {
|
||||
elements in
|
||||
do throws(E) {
|
||||
let result = try body(Span(_unsafeElements: elements))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return buffer.moveElement(from: 0)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
// public func withSpan<E: Error, Result: ~Copyable>(
|
||||
// _ body: (_ elements: Span<Element>) throws(E) -> Result
|
||||
// ) throws(E) -> Result {
|
||||
// try withUnsafeTemporaryAllocation(of: Result.self, capacity: 1) {
|
||||
// buffer -> Result in
|
||||
// try self.withUnsafeBufferPointer {
|
||||
// let result = try body(Span(_unsafeElements: $0))
|
||||
// buffer.initializeElement(at: 0, to: result)
|
||||
// }
|
||||
// return buffer.moveElement(from: 0)
|
||||
// }
|
||||
// }
|
||||
|
||||
// public func withSpan<E: Error, Result: ~Copyable>(
|
||||
// _ body: (_ elements: Span<Element>) throws(E) -> Result
|
||||
// ) throws(E) -> Result {
|
||||
// try self.withUnsafeBufferPointer {
|
||||
// try body(Span(_unsafeElements: $0))
|
||||
// }
|
||||
// }
|
||||
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ bytes: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result where Element: BitwiseCopyable {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E> in
|
||||
self.withUnsafeBytes {
|
||||
bytes in
|
||||
do throws(E) {
|
||||
let result = try body(RawSpan(_unsafeBytes: bytes))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return buffer.moveElement(from: 0)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
}
|
||||
|
||||
extension ContiguousArray {
|
||||
public func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E> in
|
||||
self.withUnsafeBufferPointer {
|
||||
elements in
|
||||
do throws(E) {
|
||||
let result = try body(Span(_unsafeElements: elements))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return buffer.moveElement(from: 0)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
}
|
||||
|
||||
extension ContiguousArray where Element: BitwiseCopyable {
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ bytes: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result where Element: BitwiseCopyable {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E> in
|
||||
self.withUnsafeBytes {
|
||||
bytes in
|
||||
do throws(E) {
|
||||
let result = try body(RawSpan(_unsafeBytes: bytes))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return buffer.moveElement(from: 0)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
}
|
||||
|
||||
extension ArraySlice {
|
||||
public func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E> in
|
||||
self.withUnsafeBufferPointer {
|
||||
elements in
|
||||
do throws(E) {
|
||||
let result = try body(Span(_unsafeElements: elements))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return buffer.moveElement(from: 0)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
}
|
||||
|
||||
extension ArraySlice where Element: BitwiseCopyable {
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ bytes: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result where Element: BitwiseCopyable {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E> in
|
||||
self.withUnsafeBytes {
|
||||
bytes in
|
||||
do throws(E) {
|
||||
let result = try body(RawSpan(_unsafeBytes: bytes))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return buffer.moveElement(from: 0)
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
}
|
||||
|
||||
extension String.UTF8View {
|
||||
public func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<UTF8.CodeUnit>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E>? in
|
||||
let ran: Void? = self.withContiguousStorageIfAvailable {
|
||||
elements in
|
||||
do throws(E) {
|
||||
let result = try body(Span(_unsafeElements: elements))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return (ran == nil) ? nil : buffer.moveElement(from: 0)
|
||||
}
|
||||
if let result {
|
||||
return try result.get()
|
||||
}
|
||||
return try ContiguousArray(self).withSpan(body)
|
||||
}
|
||||
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ bytes: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E>? in
|
||||
let ran: Void? = self.withContiguousStorageIfAvailable {
|
||||
do throws(E) {
|
||||
let result = try body(RawSpan(_unsafeElements: $0))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return (ran == nil) ? nil : buffer.moveElement(from: 0)
|
||||
}
|
||||
if let result {
|
||||
return try result.get()
|
||||
}
|
||||
return try ContiguousArray(self).withBytes(body)
|
||||
}
|
||||
}
|
||||
|
||||
extension Substring.UTF8View {
|
||||
public func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<UTF8.CodeUnit>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E>? in
|
||||
let ran: Void? = self.withContiguousStorageIfAvailable {
|
||||
elements in
|
||||
do throws(E) {
|
||||
let result = try body(Span(_unsafeElements: elements))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return (ran == nil) ? nil : buffer.moveElement(from: 0)
|
||||
}
|
||||
if let result {
|
||||
return try result.get()
|
||||
}
|
||||
return try ContiguousArray(self).withSpan(body)
|
||||
}
|
||||
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ bytes: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
let result = withUnsafeTemporaryAllocation(
|
||||
of: Swift.Result<Result, E>.self, capacity: 1
|
||||
) {
|
||||
buffer -> Swift.Result<Result, E>? in
|
||||
let ran: Void? = self.withContiguousStorageIfAvailable {
|
||||
elements in
|
||||
do throws(E) {
|
||||
let result = try body(RawSpan(_unsafeElements: elements))
|
||||
buffer.initializeElement(at: 0, to: .success(result))
|
||||
} catch {
|
||||
buffer.initializeElement(at: 0, to: .failure(error))
|
||||
}
|
||||
}
|
||||
return (ran == nil) ? nil : buffer.moveElement(from: 0)
|
||||
}
|
||||
if let result {
|
||||
return try result.get()
|
||||
}
|
||||
return try ContiguousArray(self).withBytes(body)
|
||||
}
|
||||
}
|
||||
|
||||
extension CollectionOfOne {
|
||||
public func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
var collection = self
|
||||
return try withUnsafePointer(to: &collection) {
|
||||
pointer throws(E) -> Result in
|
||||
try pointer.withMemoryRebound(to: Element.self, capacity: 1) {
|
||||
element throws(E) -> Result in
|
||||
try body(Span(_unsafeStart: element, count: 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension CollectionOfOne where Element: BitwiseCopyable {
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ bytes: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
var collection = self
|
||||
return try Swift.withUnsafeBytes(of: &collection) {
|
||||
bytes throws(E) -> Result in
|
||||
try body(RawSpan(_unsafeBytes: bytes))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension KeyValuePairs {
|
||||
public func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (
|
||||
_ elements: Span<(key: Key, value: Value)>
|
||||
) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try ContiguousArray(self).withSpan(body)
|
||||
}
|
||||
}
|
||||
|
||||
extension KeyValuePairs where Element: BitwiseCopyable {
|
||||
public func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ bytes: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try ContiguousArray(self).withBytes(body)
|
||||
}
|
||||
}
|
||||
|
||||
extension Span where Element: ~Copyable /*& ~Escapable*/ {
|
||||
public consuming func withSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: Span<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try body(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Span where Element: BitwiseCopyable {
|
||||
public consuming func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try body(RawSpan(_elements: self))
|
||||
}
|
||||
}
|
||||
|
||||
extension RawSpan {
|
||||
public consuming func withBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ elements: RawSpan) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try body(self)
|
||||
}
|
||||
}
|
||||
|
||||
//TODO: extend SIMD vectors with `withSpan` and with `withBytes`.
|
||||
@@ -8,22 +8,14 @@ See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
add_library(Future
|
||||
"Box.swift"
|
||||
"Cell.swift"
|
||||
"ContiguousStorage.swift"
|
||||
"Inout.swift"
|
||||
"OutputSpan.swift"
|
||||
"LifetimeOverride.swift"
|
||||
"RawSpan.swift"
|
||||
"Span.swift"
|
||||
"Span+Iterator.swift"
|
||||
"MutableRawSpan.swift"
|
||||
"MutableSpan.swift"
|
||||
"MutableSpanSlicing.swift"
|
||||
"OutputSpan.swift"
|
||||
"SpanExtensions.swift"
|
||||
"StdlibOutputSpanExtensions.swift"
|
||||
"StdlibSpanExtensions.swift"
|
||||
"Containers/Shared.swift"
|
||||
"Containers/Container.swift"
|
||||
"Containers/DynamicArray.swift"
|
||||
"Containers/NewArray.swift"
|
||||
"Containers/RigidArray.swift"
|
||||
"UnsafeBufferPointer+Additions.swift"
|
||||
)
|
||||
|
||||
target_link_libraries(Future PRIVATE
|
||||
@@ -0,0 +1,67 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// 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(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(borrow 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
|
||||
}
|
||||
@@ -0,0 +1,630 @@
|
||||
//===--- MutableRawSpan.swift ---------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// A MutableRawSpan represents a span of memory which
|
||||
// contains initialized `Element` instances.
|
||||
@safe
|
||||
@frozen
|
||||
@available(macOS 9999, *)
|
||||
public struct MutableRawSpan: ~Copyable & ~Escapable {
|
||||
@usableFromInline
|
||||
internal let _pointer: UnsafeMutableRawPointer?
|
||||
|
||||
@usableFromInline
|
||||
internal let _count: Int
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _start() -> UnsafeMutableRawPointer {
|
||||
unsafe _pointer.unsafelyUnwrapped
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
internal init(
|
||||
_unchecked pointer: UnsafeMutableRawPointer?,
|
||||
byteCount: Int
|
||||
) {
|
||||
_pointer = unsafe pointer
|
||||
_count = byteCount
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableRawSpan: @unchecked Sendable {}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableRawSpan {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow bytes)
|
||||
public init(
|
||||
_unsafeBytes bytes: UnsafeMutableRawBufferPointer
|
||||
) {
|
||||
let baseAddress = bytes.baseAddress
|
||||
let span = MutableRawSpan(_unchecked: baseAddress, byteCount: bytes.count)
|
||||
self = unsafe _overrideLifetime(span, borrowing: bytes)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow bytes)
|
||||
public init(
|
||||
_unsafeBytes bytes: borrowing Slice<UnsafeMutableRawBufferPointer>
|
||||
) {
|
||||
let rebased = unsafe UnsafeMutableRawBufferPointer(rebasing: bytes)
|
||||
let span = MutableRawSpan(_unsafeBytes: rebased)
|
||||
self = unsafe _overrideLifetime(span, borrowing: bytes)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
public init(
|
||||
_unsafeStart pointer: UnsafeMutableRawPointer,
|
||||
byteCount: Int
|
||||
) {
|
||||
precondition(byteCount >= 0, "Count must not be negative")
|
||||
self.init(_unchecked: pointer, byteCount: byteCount)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow elements)
|
||||
public init<Element: BitwiseCopyable>(
|
||||
_unsafeElements elements: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
let bytes = UnsafeMutableRawBufferPointer(elements)
|
||||
let span = MutableRawSpan(_unsafeBytes: bytes)
|
||||
self = unsafe _overrideLifetime(span, borrowing: elements)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow elements)
|
||||
public init<Element: BitwiseCopyable>(
|
||||
_unsafeElements elements: borrowing Slice<UnsafeMutableBufferPointer<Element>>
|
||||
) {
|
||||
let rebased = unsafe UnsafeMutableBufferPointer(rebasing: elements)
|
||||
let span = MutableRawSpan(_unsafeElements: rebased)
|
||||
self = unsafe _overrideLifetime(span, borrowing: elements)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(elements)
|
||||
public init<Element: BitwiseCopyable>(
|
||||
_elements elements: consuming MutableSpan<Element>
|
||||
) {
|
||||
let bytes = unsafe UnsafeMutableRawBufferPointer(
|
||||
start: elements._pointer,
|
||||
count: elements.count &* MemoryLayout<Element>.stride
|
||||
)
|
||||
let span = MutableRawSpan(_unsafeBytes: bytes)
|
||||
self = unsafe _overrideLifetime(span, copying: elements)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableRawSpan {
|
||||
@_alwaysEmitIntoClient
|
||||
public var byteCount: Int { _count }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var isEmpty: Bool { byteCount == 0 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var byteOffsets: Range<Int> {
|
||||
unsafe Range(uncheckedBounds: (0, byteCount))
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableRawSpan {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafeBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
guard let pointer = _pointer, _count > 0 else {
|
||||
return try unsafe body(.init(start: nil, count: 0))
|
||||
}
|
||||
return try unsafe body(.init(start: pointer, count: _count))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func withUnsafeMutableBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (UnsafeMutableRawBufferPointer) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
guard let pointer = _pointer, _count > 0 else {
|
||||
return try unsafe body(.init(start: nil, count: 0))
|
||||
}
|
||||
return try unsafe body(.init(start: pointer, count: _count))
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension RawSpan {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow mutableSpan)
|
||||
public init(_unsafeMutableRawSpan mutableSpan: borrowing MutableRawSpan) {
|
||||
let start = mutableSpan._start()
|
||||
let span = RawSpan(_unsafeStart: start, byteCount: mutableSpan.byteCount)
|
||||
self = unsafe _overrideLifetime(span, borrowing: mutableSpan)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableRawSpan {
|
||||
|
||||
public var bytes: RawSpan {
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
borrowing get {
|
||||
return RawSpan(_unsafeMutableRawSpan: self)
|
||||
}
|
||||
}
|
||||
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
public borrowing func _unsafeView<T: BitwiseCopyable>(
|
||||
as type: T.Type
|
||||
) -> Span<T> {
|
||||
let bytes = unsafe UnsafeRawBufferPointer(start: _pointer, count: _count)
|
||||
let span = Span<T>(_unsafeBytes: bytes)
|
||||
return unsafe _overrideLifetime(span, borrowing: self)
|
||||
}
|
||||
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
public mutating func _unsafeMutableView<T: BitwiseCopyable>(
|
||||
as type: T.Type
|
||||
) -> MutableSpan<T> {
|
||||
let bytes = unsafe UnsafeMutableRawBufferPointer(
|
||||
start: _pointer, count: _count
|
||||
)
|
||||
let span = MutableSpan<T>(_unsafeBytes: bytes)
|
||||
return unsafe _overrideLifetime(span, mutating: &self)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableRawSpan {
|
||||
|
||||
/// Returns a new instance of the given type, constructed from the raw memory
|
||||
/// at the specified offset.
|
||||
///
|
||||
/// The memory at this pointer plus `offset` must be properly aligned for
|
||||
/// accessing `T` and initialized to `T` or another type that is layout
|
||||
/// compatible with `T`.
|
||||
///
|
||||
/// This is an unsafe operation. Failure to meet the preconditions
|
||||
/// above may produce an invalid value of `T`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The offset from this pointer, in bytes. `offset` must be
|
||||
/// nonnegative. The default is zero.
|
||||
/// - type: The type of the instance to create.
|
||||
/// - Returns: A new instance of type `T`, read from the raw bytes at
|
||||
/// `offset`. The returned instance is memory-managed and unassociated
|
||||
/// with the value in the memory referenced by this pointer.
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public func unsafeLoad<T>(
|
||||
fromByteOffset offset: Int = 0, as: T.Type
|
||||
) -> T {
|
||||
precondition(
|
||||
UInt(bitPattern: offset) <= UInt(bitPattern: _count) &&
|
||||
MemoryLayout<T>.size <= (_count &- offset),
|
||||
"Byte offset range out of bounds"
|
||||
)
|
||||
return unsafe unsafeLoad(fromUncheckedByteOffset: offset, as: T.self)
|
||||
}
|
||||
|
||||
/// Returns a new instance of the given type, constructed from the raw memory
|
||||
/// at the specified offset.
|
||||
///
|
||||
/// The memory at this pointer plus `offset` must be properly aligned for
|
||||
/// accessing `T` and initialized to `T` or another type that is layout
|
||||
/// compatible with `T`.
|
||||
///
|
||||
/// This is an unsafe operation. This function does not validate the bounds
|
||||
/// of the memory access, and failure to meet the preconditions
|
||||
/// above may produce an invalid value of `T`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The offset from this pointer, in bytes. `offset` must be
|
||||
/// nonnegative. The default is zero.
|
||||
/// - type: The type of the instance to create.
|
||||
/// - Returns: A new instance of type `T`, read from the raw bytes at
|
||||
/// `offset`. The returned instance is memory-managed and unassociated
|
||||
/// with the value in the memory referenced by this pointer.
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public func unsafeLoad<T>(
|
||||
fromUncheckedByteOffset offset: Int, as: T.Type
|
||||
) -> T {
|
||||
unsafe _start().load(fromByteOffset: offset, as: T.self)
|
||||
}
|
||||
|
||||
/// Returns a new instance of the given type, constructed from the raw memory
|
||||
/// at the specified offset.
|
||||
///
|
||||
/// The memory at this pointer plus `offset` must be initialized to `T`
|
||||
/// or another type that is layout compatible with `T`.
|
||||
///
|
||||
/// This is an unsafe operation. Failure to meet the preconditions
|
||||
/// above may produce an invalid value of `T`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The offset from this pointer, in bytes. `offset` must be
|
||||
/// nonnegative. The default is zero.
|
||||
/// - type: The type of the instance to create.
|
||||
/// - Returns: A new instance of type `T`, read from the raw bytes at
|
||||
/// `offset`. The returned instance isn't associated
|
||||
/// with the value in the range of memory referenced by this pointer.
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public func unsafeLoadUnaligned<T: BitwiseCopyable>(
|
||||
fromByteOffset offset: Int = 0, as: T.Type
|
||||
) -> T {
|
||||
precondition(
|
||||
UInt(bitPattern: offset) <= UInt(bitPattern: _count) &&
|
||||
MemoryLayout<T>.size <= (_count &- offset),
|
||||
"Byte offset range out of bounds"
|
||||
)
|
||||
return unsafe unsafeLoadUnaligned(fromUncheckedByteOffset: offset, as: T.self)
|
||||
}
|
||||
|
||||
/// Returns a new instance of the given type, constructed from the raw memory
|
||||
/// at the specified offset.
|
||||
///
|
||||
/// The memory at this pointer plus `offset` must be initialized to `T`
|
||||
/// or another type that is layout compatible with `T`.
|
||||
///
|
||||
/// This is an unsafe operation. This function does not validate the bounds
|
||||
/// of the memory access, and failure to meet the preconditions
|
||||
/// above may produce an invalid value of `T`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - offset: The offset from this pointer, in bytes. `offset` must be
|
||||
/// nonnegative. The default is zero.
|
||||
/// - type: The type of the instance to create.
|
||||
/// - Returns: A new instance of type `T`, read from the raw bytes at
|
||||
/// `offset`. The returned instance isn't associated
|
||||
/// with the value in the range of memory referenced by this pointer.
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public func unsafeLoadUnaligned<T: BitwiseCopyable>(
|
||||
fromUncheckedByteOffset offset: Int, as: T.Type
|
||||
) -> T {
|
||||
unsafe _start().loadUnaligned(fromByteOffset: offset, as: T.self)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func storeBytes<T: BitwiseCopyable>(
|
||||
of value: T, toByteOffset offset: Int = 0, as type: T.Type
|
||||
) {
|
||||
precondition(
|
||||
UInt(bitPattern: offset) <= UInt(bitPattern: _count) &&
|
||||
MemoryLayout<T>.size <= (_count &- offset),
|
||||
"Byte offset range out of bounds"
|
||||
)
|
||||
unsafe storeBytes(of: value, toUncheckedByteOffset: offset, as: type)
|
||||
}
|
||||
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func storeBytes<T: BitwiseCopyable>(
|
||||
of value: T, toUncheckedByteOffset offset: Int, as type: T.Type
|
||||
) {
|
||||
unsafe _start().storeBytes(of: value, toByteOffset: offset, as: type)
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: copyMemory
|
||||
@available(macOS 9999, *)
|
||||
extension MutableRawSpan {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update<S: Sequence>(
|
||||
from source: S
|
||||
) -> (unwritten: S.Iterator, byteOffset: Int) where S.Element: BitwiseCopyable {
|
||||
var iterator = source.makeIterator()
|
||||
let offset = update(from: &iterator)
|
||||
return (iterator, offset)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update<Element: BitwiseCopyable>(
|
||||
from elements: inout some IteratorProtocol<Element>
|
||||
) -> Int {
|
||||
var offset = 0
|
||||
while offset + MemoryLayout<Element>.stride <= _count {
|
||||
guard let element = elements.next() else { break }
|
||||
unsafe storeBytes(
|
||||
of: element, toUncheckedByteOffset: offset, as: Element.self
|
||||
)
|
||||
offset &+= MemoryLayout<Element>.stride
|
||||
}
|
||||
return offset
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update<C: Collection>(
|
||||
fromContentsOf source: C
|
||||
) -> Int where C.Element: BitwiseCopyable {
|
||||
let newOffset = source.withContiguousStorageIfAvailable {
|
||||
self.update(fromContentsOf: RawSpan(_unsafeElements: $0))
|
||||
}
|
||||
if let newOffset { return newOffset }
|
||||
|
||||
var elements = source.makeIterator()
|
||||
let lastOffset = update(from: &elements)
|
||||
precondition(
|
||||
elements.next() == nil,
|
||||
"destination span cannot contain every element from source."
|
||||
)
|
||||
return lastOffset
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update<Element: BitwiseCopyable>(
|
||||
fromContentsOf source: Span<Element>
|
||||
) -> Int {
|
||||
// update(from: source.bytes)
|
||||
source.withUnsafeBytes {
|
||||
update(fromContentsOf: $0)
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update<Element: BitwiseCopyable>(
|
||||
fromContentsOf source: borrowing MutableSpan<Element>
|
||||
) -> Int {
|
||||
// update(from: source.span.bytes)
|
||||
source.withUnsafeBytes {
|
||||
update(fromContentsOf: $0)
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: RawSpan
|
||||
) -> Int {
|
||||
if source.byteCount == 0 { return 0 }
|
||||
source.withUnsafeBytes {
|
||||
unsafe _start().copyMemory(from: $0.baseAddress!, byteCount: $0.count)
|
||||
}
|
||||
return source.byteCount
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: borrowing MutableRawSpan
|
||||
) -> Int {
|
||||
update(fromContentsOf: source.bytes)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: sub-spans
|
||||
@available(macOS 9999, *)
|
||||
extension MutableRawSpan {
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `MutableSpan`.
|
||||
///
|
||||
/// - Returns: A `MutableSpan` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(_ bounds: Range<Int>) -> Self {
|
||||
precondition(
|
||||
UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&
|
||||
UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),
|
||||
"Index range out of bounds"
|
||||
)
|
||||
return unsafe _extracting(unchecked: bounds)
|
||||
}
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// This function does not validate `bounds`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `MutableSpan`.
|
||||
///
|
||||
/// - Returns: A `MutableSpan` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(unchecked bounds: Range<Int>) -> Self {
|
||||
let newStart = unsafe _pointer?.advanced(by: bounds.lowerBound)
|
||||
let newSpan = Self(_unchecked: newStart, byteCount: bounds.count)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `MutableSpan`.
|
||||
///
|
||||
/// - Returns: A `MutableSpan` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(
|
||||
_ bounds: some RangeExpression<Int>
|
||||
) -> Self {
|
||||
_extracting(bounds.relative(to: byteOffsets))
|
||||
}
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// This function does not validate `bounds`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `MutableSpan`.
|
||||
///
|
||||
/// - Returns: A `MutableSpan` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(unchecked bounds: ClosedRange<Int>) -> Self {
|
||||
let range = unsafe Range(
|
||||
uncheckedBounds: (bounds.lowerBound, bounds.upperBound+1)
|
||||
)
|
||||
return unsafe _extracting(unchecked: range)
|
||||
}
|
||||
|
||||
/// Constructs a new span over all the items of this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Returns: A `MutableSpan` over all the items of this span.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(_: UnboundedRange) -> Self {
|
||||
let newSpan = Self(_unchecked: _start(), byteCount: _count)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: prefixes and suffixes
|
||||
@available(macOS 9999, *)
|
||||
extension MutableRawSpan {
|
||||
|
||||
/// Returns a span containing the initial elements of this span,
|
||||
/// up to the specified maximum length.
|
||||
///
|
||||
/// If the maximum length exceeds the length of this span,
|
||||
/// the result contains all the elements.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans 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 span with at most `maxLength` elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(first maxLength: Int) -> Self {
|
||||
precondition(maxLength >= 0, "Can't have a prefix of negative length")
|
||||
let newCount = min(maxLength, byteCount)
|
||||
let newSpan = Self(_unchecked: _pointer, byteCount: newCount)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
|
||||
/// Returns a span over all but the given number of trailing elements.
|
||||
///
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the span, the result is an empty span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter k: The number of elements to drop off the end of
|
||||
/// the span. `k` must be greater than or equal to zero.
|
||||
/// - Returns: A span leaving off the specified number of elements at the end.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(droppingLast k: Int) -> Self {
|
||||
precondition(k >= 0, "Can't drop a negative number of elements")
|
||||
let dropped = min(k, byteCount)
|
||||
let newSpan = Self(_unchecked: _pointer, byteCount: byteCount &- dropped)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
|
||||
/// Returns a span containing the final elements of the span,
|
||||
/// up to the given maximum length.
|
||||
///
|
||||
/// If the maximum length exceeds the length of this span,
|
||||
/// the result contains all the elements.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans 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 span with at most `maxLength` elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(last maxLength: Int) -> Self {
|
||||
precondition(maxLength >= 0, "Can't have a suffix of negative length")
|
||||
let newCount = min(maxLength, byteCount)
|
||||
let newStart = unsafe _pointer?.advanced(by: byteCount &- newCount)
|
||||
let newSpan = Self(_unchecked: newStart, byteCount: newCount)
|
||||
return unsafe _overrideLifetime(newSpan, copying: self)
|
||||
}
|
||||
|
||||
/// Returns a span over all but the given number of initial elements.
|
||||
///
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the span, the result is an empty span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter k: The number of elements to drop from the beginning of
|
||||
/// the span. `k` must be greater than or equal to zero.
|
||||
/// - Returns: A span starting after the specified number of elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(droppingFirst k: Int) -> Self {
|
||||
precondition(k >= 0, "Can't drop a negative number of bytes")
|
||||
let dropped = min(k, byteCount)
|
||||
let newStart = unsafe _pointer?.advanced(by: dropped)
|
||||
let newSpan = Self(_unchecked: newStart, byteCount: byteCount &- dropped)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,860 @@
|
||||
//===--- MutableSpan.swift ------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Builtin
|
||||
|
||||
// A MutableSpan<Element> represents a span of memory which
|
||||
// contains initialized `Element` instances.
|
||||
@safe
|
||||
@frozen
|
||||
@available(macOS 9999, *)
|
||||
public struct MutableSpan<Element: ~Copyable & ~Escapable>
|
||||
: ~Copyable, ~Escapable {
|
||||
@usableFromInline
|
||||
internal let _pointer: UnsafeMutableRawPointer?
|
||||
|
||||
@usableFromInline
|
||||
internal let _count: Int
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _start() -> UnsafeMutableRawPointer {
|
||||
unsafe _pointer.unsafelyUnwrapped
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow start)
|
||||
internal init(
|
||||
_unchecked start: UnsafeMutableRawPointer?,
|
||||
count: Int
|
||||
) {
|
||||
_pointer = unsafe start
|
||||
_count = count
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan: @unchecked Sendable where Element: Sendable {}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
@usableFromInline
|
||||
@lifetime(borrow elements)
|
||||
internal init(
|
||||
_unchecked elements: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
_pointer = .init(elements.baseAddress)
|
||||
_count = elements.count
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeElements buffer: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
precondition(
|
||||
((Int(bitPattern: buffer.baseAddress) &
|
||||
(MemoryLayout<Element>.alignment &- 1)) == 0),
|
||||
"baseAddress must be properly aligned to access Element"
|
||||
)
|
||||
let ms = MutableSpan<Element>(_unchecked: buffer)
|
||||
self = unsafe _overrideLifetime(ms, borrowing: buffer)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow start)
|
||||
public init(
|
||||
_unsafeStart start: UnsafeMutablePointer<Element>,
|
||||
count: Int
|
||||
) {
|
||||
precondition(count >= 0, "Count must not be negative")
|
||||
let buffer = unsafe UnsafeMutableBufferPointer(start: start, count: count)
|
||||
let ms = MutableSpan(_unsafeElements: buffer)
|
||||
self = unsafe _overrideLifetime(ms, borrowing: start)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow elements)
|
||||
public init(
|
||||
_unsafeElements elements: borrowing Slice<UnsafeMutableBufferPointer<Element>>
|
||||
) {
|
||||
let rb = unsafe UnsafeMutableBufferPointer(rebasing: elements)
|
||||
let ms = MutableSpan(_unsafeElements: rb)
|
||||
self = unsafe _overrideLifetime(ms, borrowing: elements)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: BitwiseCopyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: UnsafeMutableRawBufferPointer
|
||||
) {
|
||||
precondition(
|
||||
((Int(bitPattern: buffer.baseAddress) &
|
||||
(MemoryLayout<Element>.alignment &- 1)) == 0),
|
||||
"baseAddress must be properly aligned to access Element"
|
||||
)
|
||||
let (byteCount, stride) = (buffer.count, MemoryLayout<Element>.stride)
|
||||
let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride)
|
||||
precondition(remainder == 0, "Span must contain a whole number of elements")
|
||||
let elements = unsafe UnsafeMutableBufferPointer<Element>(
|
||||
start: buffer.baseAddress?.assumingMemoryBound(to: Element.self),
|
||||
count: count
|
||||
)
|
||||
let ms = MutableSpan(_unsafeElements: elements)
|
||||
self = unsafe _overrideLifetime(ms, borrowing: buffer)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
public init(
|
||||
_unsafeStart pointer: UnsafeMutableRawPointer,
|
||||
byteCount: Int
|
||||
) {
|
||||
precondition(byteCount >= 0, "Count must not be negative")
|
||||
let bytes = unsafe UnsafeMutableRawBufferPointer(
|
||||
start: pointer, count: byteCount
|
||||
)
|
||||
let ms = MutableSpan(_unsafeBytes: bytes)
|
||||
self = unsafe _overrideLifetime(ms, borrowing: pointer)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_unsafeBytes buffer: borrowing Slice<UnsafeMutableRawBufferPointer>
|
||||
) {
|
||||
let bytes = unsafe UnsafeMutableRawBufferPointer(rebasing: buffer)
|
||||
let ms = MutableSpan(_unsafeBytes: bytes)
|
||||
self = unsafe _overrideLifetime(ms, borrowing: buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension Span where Element: ~Copyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow mutableSpan)
|
||||
public init(_unsafeMutableSpan mutableSpan: borrowing MutableSpan<Element>) {
|
||||
let pointer =
|
||||
unsafe mutableSpan._pointer?.assumingMemoryBound(to: Element.self)
|
||||
let buffer = unsafe UnsafeBufferPointer(
|
||||
start: pointer, count: mutableSpan.count
|
||||
)
|
||||
let span = Span(_unsafeElements: buffer)
|
||||
self = unsafe _overrideLifetime(span, borrowing: mutableSpan)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var span: Span<Element> {
|
||||
@lifetime(borrow self)
|
||||
borrowing get {
|
||||
Span(_unsafeMutableSpan: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension RawSpan {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public init<Element: BitwiseCopyable>(
|
||||
_unsafeMutableSpan mutableSpan: borrowing MutableSpan<Element>
|
||||
) {
|
||||
let pointer = mutableSpan._pointer
|
||||
let byteCount = mutableSpan.count &* MemoryLayout<Element>.stride
|
||||
let buffer = unsafe UnsafeRawBufferPointer(start: pointer, count: byteCount)
|
||||
let rawSpan = RawSpan(_unsafeBytes: buffer)
|
||||
self = unsafe _overrideLifetime(rawSpan, borrowing: mutableSpan)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: Equatable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: borrowing Self) -> Bool {
|
||||
_elementsEqual(Span(_unsafeMutableSpan: other))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: Span<Element>) -> Bool {
|
||||
Span(_unsafeMutableSpan: self)._elementsEqual(other)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: some Collection<Element>) -> Bool {
|
||||
Span(_unsafeMutableSpan: self)._elementsEqual(other)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: some Sequence<Element>) -> Bool {
|
||||
Span(_unsafeMutableSpan: self)._elementsEqual(other)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var _description: String {
|
||||
let addr = String(
|
||||
UInt(bitPattern: _pointer), radix: 16, uppercase: false
|
||||
)
|
||||
return "(0x\(addr), \(_count))"
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: Collection, RandomAccessCollection
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable & ~Escapable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var count: Int { _count }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var isEmpty: Bool { _count == 0 }
|
||||
|
||||
public typealias Index = Int
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var indices: Range<Index> {
|
||||
unsafe Range(uncheckedBounds: (0, _count))
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: BitwiseCopyable {
|
||||
|
||||
/// Construct a RawSpan over the memory represented by this span
|
||||
///
|
||||
/// - Returns: a RawSpan over the memory represented by this span
|
||||
@_alwaysEmitIntoClient
|
||||
public var bytes: RawSpan {
|
||||
@lifetime(borrow self)
|
||||
borrowing get {
|
||||
RawSpan(_unsafeMutableSpan: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(_ position: Index) -> Element {
|
||||
unsafeAddress {
|
||||
precondition(indices.contains(position), "index out of bounds")
|
||||
return unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: position))
|
||||
}
|
||||
unsafeMutableAddress {
|
||||
precondition(indices.contains(position), "index out of bounds")
|
||||
return unsafe _unsafeAddressOfElement(unchecked: position)
|
||||
}
|
||||
}
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// This subscript does not validate `position`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(unchecked position: Index) -> Element {
|
||||
unsafeAddress {
|
||||
unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: position))
|
||||
}
|
||||
unsafeMutableAddress {
|
||||
unsafe _unsafeAddressOfElement(unchecked: position)
|
||||
}
|
||||
}
|
||||
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _unsafeAddressOfElement(
|
||||
unchecked position: Index
|
||||
) -> UnsafeMutablePointer<Element> {
|
||||
let elementOffset = position &* MemoryLayout<Element>.stride
|
||||
let address = unsafe _start().advanced(by: elementOffset)
|
||||
return unsafe address.assumingMemoryBound(to: Element.self)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func swapAt(_ i: Index, _ j: Index) {
|
||||
precondition(indices.contains(Index(i)))
|
||||
precondition(indices.contains(Index(j)))
|
||||
unsafe swapAt(unchecked: i, unchecked: j)
|
||||
}
|
||||
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func swapAt(unchecked i: Index, unchecked j: Index) {
|
||||
let pi = unsafe _unsafeAddressOfElement(unchecked: i)
|
||||
let pj = unsafe _unsafeAddressOfElement(unchecked: j)
|
||||
let temporary = unsafe pi.move()
|
||||
unsafe pi.initialize(to: pj.move())
|
||||
unsafe pj.initialize(to: consume temporary)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: BitwiseCopyable {
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(_ position: Index) -> Element {
|
||||
get {
|
||||
precondition(indices.contains(position), "index out of bounds")
|
||||
return unsafe self[unchecked: position]
|
||||
}
|
||||
set {
|
||||
precondition(indices.contains(position), "index out of bounds")
|
||||
unsafe self[unchecked: position] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Accesses the element at the specified position in the `Span`.
|
||||
///
|
||||
/// This subscript does not validate `position`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter position: The offset of the element to access. `position`
|
||||
/// must be greater or equal to zero, and less than `count`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public subscript(unchecked position: Index) -> Element {
|
||||
get {
|
||||
let offset = position&*MemoryLayout<Element>.stride
|
||||
return unsafe _start().loadUnaligned(
|
||||
fromByteOffset: offset, as: Element.self
|
||||
)
|
||||
}
|
||||
set {
|
||||
let offset = position&*MemoryLayout<Element>.stride
|
||||
unsafe _start().storeBytes(
|
||||
of: newValue, toByteOffset: offset, as: Element.self
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
//FIXME: mark closure parameter as non-escaping
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafeBufferPointer<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ buffer: UnsafeBufferPointer<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try Span(_unsafeMutableSpan: self).withUnsafeBufferPointer(body)
|
||||
}
|
||||
|
||||
//FIXME: mark closure parameter as non-escaping
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func withUnsafeMutableBufferPointer<
|
||||
E: Error, Result: ~Copyable
|
||||
>(
|
||||
_ body: (UnsafeMutableBufferPointer<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
guard let pointer = _pointer, count > 0 else {
|
||||
return try unsafe body(.init(start: nil, count: 0))
|
||||
}
|
||||
// bind memory by hand to sidestep alignment concerns
|
||||
let binding = Builtin.bindMemory(
|
||||
pointer._rawValue, count._builtinWordValue, Element.self
|
||||
)
|
||||
defer { Builtin.rebindMemory(pointer._rawValue, binding) }
|
||||
return try unsafe body(.init(start: .init(pointer._rawValue), count: count))
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: BitwiseCopyable {
|
||||
|
||||
//FIXME: mark closure parameter as non-escaping
|
||||
@_alwaysEmitIntoClient
|
||||
public func withUnsafeBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
try RawSpan(_unsafeMutableSpan: self).withUnsafeBytes(body)
|
||||
}
|
||||
|
||||
//FIXME: mark closure parameter as non-escaping
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func withUnsafeMutableBytes<E: Error, Result: ~Copyable>(
|
||||
_ body: (_ buffer: UnsafeMutableRawBufferPointer) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
let bytes = unsafe UnsafeMutableRawBufferPointer(
|
||||
start: (_count == 0) ? nil : _start(),
|
||||
count: _count &* MemoryLayout<Element>.stride
|
||||
)
|
||||
return try unsafe body(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: bulk-update functions
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(repeating repeatedValue: consuming Element) {
|
||||
unsafe _start().withMemoryRebound(to: Element.self, capacity: count) {
|
||||
unsafe $0.update(repeating: repeatedValue, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update<S: Sequence>(
|
||||
from source: S
|
||||
) -> (unwritten: S.Iterator, index: Index) where S.Element == Element {
|
||||
var iterator = source.makeIterator()
|
||||
let index = update(from: &iterator)
|
||||
return (iterator, index)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
from elements: inout some IteratorProtocol<Element>
|
||||
) -> Index {
|
||||
var index = 0
|
||||
while index < _count {
|
||||
guard let element = elements.next() else { break }
|
||||
unsafe self[unchecked: index] = element
|
||||
index &+= 1
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: some Collection<Element>
|
||||
) -> Index {
|
||||
let updated = source.withContiguousStorageIfAvailable {
|
||||
self.update(fromContentsOf: Span(_unsafeElements: $0))
|
||||
}
|
||||
if let updated {
|
||||
return updated
|
||||
}
|
||||
|
||||
//TODO: use _copyContents here
|
||||
|
||||
var iterator = source.makeIterator()
|
||||
let index = update(from: &iterator)
|
||||
precondition(
|
||||
iterator.next() == nil,
|
||||
"destination buffer view cannot contain every element from source."
|
||||
)
|
||||
return index
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(fromContentsOf source: Span<Element>) -> Index {
|
||||
guard !source.isEmpty else { return 0 }
|
||||
precondition(
|
||||
source.count <= self.count,
|
||||
"destination span cannot contain every element from source."
|
||||
)
|
||||
unsafe _start().withMemoryRebound(
|
||||
to: Element.self, capacity: source.count
|
||||
) { dest in
|
||||
source.withUnsafeBufferPointer {
|
||||
unsafe dest.update(from: $0.baseAddress!, count: $0.count)
|
||||
}
|
||||
}
|
||||
return source.count
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: borrowing MutableSpan<Element>
|
||||
) -> Index {
|
||||
update(fromContentsOf: source.span)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func moveUpdate(
|
||||
fromContentsOf source: consuming OutputSpan<Element>
|
||||
) -> Index {
|
||||
guard !source.isEmpty else { return 0 }
|
||||
precondition(
|
||||
source.count <= self.count,
|
||||
"destination span cannot contain every element from source."
|
||||
)
|
||||
let buffer = unsafe source.relinquishBorrowedMemory()
|
||||
// we must now deinitialize the returned UMBP
|
||||
unsafe _start().moveInitializeMemory(
|
||||
as: Element.self, from: buffer.baseAddress!, count: buffer.count
|
||||
)
|
||||
return buffer.count
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func moveUpdate(
|
||||
fromContentsOf source: UnsafeMutableBufferPointer<Element>
|
||||
) -> Index {
|
||||
let s = OutputSpan(_initializing: source, initialized: source.count)
|
||||
return self.moveUpdate(fromContentsOf: s)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func moveUpdate(
|
||||
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
|
||||
) -> Index {
|
||||
self.moveUpdate(fromContentsOf: unsafe .init(rebasing: source))
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: BitwiseCopyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
repeating repeatedValue: Element
|
||||
) where Element: BitwiseCopyable {
|
||||
guard count > 0 else { return }
|
||||
// rebind _start manually in order to avoid assumptions about alignment.
|
||||
let rp = _start()._rawValue
|
||||
let binding = Builtin.bindMemory(rp, count._builtinWordValue, Element.self)
|
||||
let rebound = unsafe UnsafeMutablePointer<Element>(rp)
|
||||
unsafe rebound.update(repeating: repeatedValue, count: count)
|
||||
Builtin.rebindMemory(rp, binding)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update<S: Sequence>(
|
||||
from source: S
|
||||
) -> (unwritten: S.Iterator, index: Index)
|
||||
where S.Element == Element, Element: BitwiseCopyable {
|
||||
var iterator = source.makeIterator()
|
||||
let index = update(from: &iterator)
|
||||
return (iterator, index)
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
from elements: inout some IteratorProtocol<Element>
|
||||
) -> Index {
|
||||
var index = 0
|
||||
while index < _count {
|
||||
guard let element = elements.next() else { break }
|
||||
unsafe self[unchecked: index] = element
|
||||
index &+= 1
|
||||
}
|
||||
return index
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: some Collection<Element>
|
||||
) -> Index where Element: BitwiseCopyable {
|
||||
let updated = source.withContiguousStorageIfAvailable {
|
||||
self.update(fromContentsOf: Span(_unsafeElements: $0))
|
||||
}
|
||||
if let updated {
|
||||
return updated
|
||||
}
|
||||
|
||||
//TODO: use _copyContents here
|
||||
|
||||
var iterator = source.makeIterator()
|
||||
let index = update(from: &iterator)
|
||||
precondition(
|
||||
iterator.next() == nil,
|
||||
"destination buffer view cannot contain every element from source."
|
||||
)
|
||||
return index
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: Span<Element>
|
||||
) -> Index where Element: BitwiseCopyable {
|
||||
guard !source.isEmpty else { return 0 }
|
||||
precondition(
|
||||
source.count <= self.count,
|
||||
"destination span cannot contain every element from source."
|
||||
)
|
||||
source.withUnsafeBufferPointer {
|
||||
unsafe _start().copyMemory(
|
||||
from: $0.baseAddress!,
|
||||
byteCount: $0.count &* MemoryLayout<Element>.stride
|
||||
)
|
||||
}
|
||||
return source.count
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func update(
|
||||
fromContentsOf source: borrowing MutableSpan<Element>
|
||||
) -> Index where Element: BitwiseCopyable {
|
||||
update(fromContentsOf: source.span)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: sub-spans
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `MutableSpan`.
|
||||
///
|
||||
/// - Returns: A `MutableSpan` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(_ bounds: Range<Index>) -> Self {
|
||||
precondition(
|
||||
UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&
|
||||
UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),
|
||||
"Index range out of bounds"
|
||||
)
|
||||
return unsafe _extracting(unchecked: bounds)
|
||||
}
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// This function does not validate `bounds`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `MutableSpan`.
|
||||
///
|
||||
/// - Returns: A `MutableSpan` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(unchecked bounds: Range<Index>) -> Self {
|
||||
let delta = bounds.lowerBound &* MemoryLayout<Element>.stride
|
||||
let newStart = unsafe _pointer?.advanced(by: delta)
|
||||
let newSpan = Self(_unchecked: newStart, count: bounds.count)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `MutableSpan`.
|
||||
///
|
||||
/// - Returns: A `MutableSpan` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(
|
||||
_ bounds: some RangeExpression<Index>
|
||||
) -> Self {
|
||||
_extracting(bounds.relative(to: indices))
|
||||
}
|
||||
|
||||
/// Constructs a new span over the items within the supplied range of
|
||||
/// positions within this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// This function does not validate `bounds`; this is an unsafe operation.
|
||||
///
|
||||
/// - Parameter bounds: A valid range of positions. Every position in
|
||||
/// this range must be within the bounds of this `MutableSpan`.
|
||||
///
|
||||
/// - Returns: A `MutableSpan` over the items within `bounds`
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(
|
||||
unchecked bounds: ClosedRange<Index>
|
||||
) -> Self {
|
||||
let range = unsafe Range(
|
||||
uncheckedBounds: (bounds.lowerBound, bounds.upperBound&+1)
|
||||
)
|
||||
return unsafe _extracting(unchecked: range)
|
||||
}
|
||||
|
||||
/// Constructs a new span over all the items of this span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Returns: A `MutableSpan` over all the items of this span.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(_: UnboundedRange) -> Self {
|
||||
let newSpan = Self(_unchecked: _start(), count: _count)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: prefixes and suffixes
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
/// Returns a span containing the initial elements of this span,
|
||||
/// up to the specified maximum length.
|
||||
///
|
||||
/// If the maximum length exceeds the length of this span,
|
||||
/// the result contains all the elements.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans 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 span with at most `maxLength` elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(first maxLength: Int) -> Self {
|
||||
precondition(maxLength >= 0, "Can't have a prefix of negative length")
|
||||
let newCount = min(maxLength, count)
|
||||
let newSpan = Self(_unchecked: _pointer, count: newCount)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
|
||||
/// Returns a span over all but the given number of trailing elements.
|
||||
///
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the span, the result is an empty span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter k: The number of elements to drop off the end of
|
||||
/// the span. `k` must be greater than or equal to zero.
|
||||
/// - Returns: A span leaving off the specified number of elements at the end.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(droppingLast k: Int) -> Self {
|
||||
precondition(k >= 0, "Can't drop a negative number of elements")
|
||||
let droppedCount = min(k, count)
|
||||
let newSpan = Self(_unchecked: _pointer, count: count &- droppedCount)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
|
||||
/// Returns a span containing the final elements of the span,
|
||||
/// up to the given maximum length.
|
||||
///
|
||||
/// If the maximum length exceeds the length of this span,
|
||||
/// the result contains all the elements.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans 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 span with at most `maxLength` elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(last maxLength: Int) -> Self {
|
||||
precondition(maxLength >= 0, "Can't have a suffix of negative length")
|
||||
let newCount = min(maxLength, count)
|
||||
let offset = (count &- newCount) * MemoryLayout<Element>.stride
|
||||
let newStart = unsafe _pointer?.advanced(by: offset)
|
||||
let newSpan = Self(_unchecked: newStart, count: newCount)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
|
||||
/// Returns a span over all but the given number of initial elements.
|
||||
///
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the span, the result is an empty span.
|
||||
///
|
||||
/// The returned span's first item is always at offset 0; unlike buffer
|
||||
/// slices, extracted spans do not share their indices with the
|
||||
/// span from which they are extracted.
|
||||
///
|
||||
/// - Parameter k: The number of elements to drop from the beginning of
|
||||
/// the span. `k` must be greater than or equal to zero.
|
||||
/// - Returns: A span starting after the specified number of elements.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow self)
|
||||
mutating public func _extracting(droppingFirst k: Int) -> Self {
|
||||
precondition(k >= 0, "Can't drop a negative number of elements")
|
||||
let droppedCount = min(k, count)
|
||||
let offset = droppedCount * MemoryLayout<Element>.stride
|
||||
let newStart = unsafe _pointer?.advanced(by: offset)
|
||||
let newSpan = Self(_unchecked: newStart, count: count &- droppedCount)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//===--- MutableSpanSlicing.swift -----------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//MARK: Option 1 extracting() function
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
@lifetime(borrow self)
|
||||
public mutating func extracting(_ bounds: Range<Index>) -> Self {
|
||||
precondition(
|
||||
UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&
|
||||
UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),
|
||||
"Index range out of bounds"
|
||||
)
|
||||
let newSpan = MutableSpan(_unchecked: _start(), uncheckedBounds: bounds)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
fileprivate init(
|
||||
_unchecked pointer: UnsafeMutableRawPointer,
|
||||
uncheckedBounds bounds: Range<Index>
|
||||
) {
|
||||
let delta = bounds.lowerBound &* MemoryLayout<Element>.stride
|
||||
let newStart = unsafe pointer.advanced(by: delta)
|
||||
let newSpan = Self(
|
||||
_unchecked: newStart, count: bounds.upperBound &- bounds.lowerBound
|
||||
)
|
||||
self = unsafe _overrideLifetime(newSpan, borrowing: pointer)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension Span where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
fileprivate init(
|
||||
_unchecked pointer: UnsafeMutableRawPointer,
|
||||
uncheckedBounds bounds: Range<Index>
|
||||
) {
|
||||
let mut = MutableSpan<Element>(_unchecked: pointer, uncheckedBounds: bounds)
|
||||
let newSpan = mut.span
|
||||
self = unsafe _overrideLifetime(newSpan, borrowing: pointer)
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: Option 2 extracting subscript
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
public subscript(extracting bounds: Range<Index>) -> Self {
|
||||
@lifetime(borrow self)
|
||||
mutating get {
|
||||
precondition(
|
||||
UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&
|
||||
UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),
|
||||
"Index range out of bounds"
|
||||
)
|
||||
let newSpan = MutableSpan(_unchecked: _start(), uncheckedBounds: bounds)
|
||||
return unsafe _overrideLifetime(newSpan, mutating: &self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: Option 3 specific slicing wrapper type
|
||||
@available(macOS 9999, *)
|
||||
public struct SubMutableSpan<Element: ~Copyable & ~Escapable>
|
||||
: ~Copyable, ~Escapable {
|
||||
public typealias Index = MutableSpan<Element>.Index
|
||||
|
||||
public fileprivate(set) var offset: MutableSpan<Element>.Index
|
||||
public /*exclusive*/ var base: MutableSpan<Element>
|
||||
|
||||
init(_ _offset: Index, _ _base: consuming MutableSpan<Element>) {
|
||||
offset = _offset
|
||||
base = _base
|
||||
}
|
||||
|
||||
public var count: Int { base.count - offset }
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension SubMutableSpan where Element: ~Copyable {
|
||||
|
||||
public subscript (index: Index) -> Element {
|
||||
unsafeAddress {
|
||||
precondition(offset <= index && index < base.count)
|
||||
return unsafe UnsafePointer(base._unsafeAddressOfElement(unchecked: index))
|
||||
}
|
||||
unsafeMutableAddress {
|
||||
precondition(offset <= index && index < base.count)
|
||||
return unsafe base._unsafeAddressOfElement(unchecked: index)
|
||||
}
|
||||
}
|
||||
|
||||
public var span: Span<Element> {
|
||||
@lifetime(borrow self)
|
||||
borrowing get {
|
||||
let newSpan = Span<Element>(
|
||||
_unchecked: base._start(), uncheckedBounds: offset..<base.count
|
||||
)
|
||||
return unsafe _overrideLifetime(newSpan, borrowing: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension SubMutableSpan {
|
||||
public mutating func update(repeating repeatedValue: consuming Element) {
|
||||
base.update(repeating: repeatedValue)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: ~Copyable {
|
||||
|
||||
public subscript(slicing bounds: Range<Index>) -> SubMutableSpan<Element> {
|
||||
@lifetime(borrow self)
|
||||
mutating get {
|
||||
precondition(
|
||||
UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&
|
||||
UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),
|
||||
"Index range out of bounds"
|
||||
)
|
||||
let prefix = Self(
|
||||
_unchecked: _start(), uncheckedBounds: 0..<bounds.upperBound
|
||||
)
|
||||
let subSpan = SubMutableSpan<Element>(bounds.lowerBound, prefix)
|
||||
return unsafe _overrideLifetime(subSpan, mutating: &self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: Option 4 range parameters to bulk mutation functions
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpan where Element: Copyable {
|
||||
|
||||
public mutating func update(
|
||||
in bounds: Range<Index>,
|
||||
repeating repeatedValue: consuming Element
|
||||
) {
|
||||
precondition(
|
||||
UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&
|
||||
UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),
|
||||
"Index range out of bounds"
|
||||
)
|
||||
let start = unsafe _start() + bounds.lowerBound &* MemoryLayout<Element>.stride
|
||||
unsafe start.withMemoryRebound(to: Element.self, capacity: bounds.count) {
|
||||
unsafe $0.update(repeating: repeatedValue, count: bounds.count)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2024 Apple Inc. and the Swift project authors
|
||||
// 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
|
||||
@@ -12,18 +12,22 @@
|
||||
|
||||
// OutputSpan<Element> represents a span of memory which contains
|
||||
// a variable number of `Element` instances, followed by uninitialized memory.
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@safe
|
||||
@frozen
|
||||
@available(macOS 9999, *)
|
||||
public struct OutputSpan<Element: ~Copyable>: ~Copyable, ~Escapable {
|
||||
@usableFromInline let _pointer: UnsafeMutableRawPointer?
|
||||
@usableFromInline
|
||||
internal let _pointer: UnsafeMutableRawPointer?
|
||||
|
||||
public let capacity: Int
|
||||
|
||||
@usableFromInline
|
||||
var _initialized: Int = 0
|
||||
internal var _initialized: Int = 0
|
||||
|
||||
@usableFromInline @inline(__always)
|
||||
var _start: UnsafeMutableRawPointer { _pointer.unsafelyUnwrapped }
|
||||
@_alwaysEmitIntoClient
|
||||
internal func _start() -> UnsafeMutableRawPointer {
|
||||
unsafe _pointer.unsafelyUnwrapped
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var available: Int { capacity &- _initialized }
|
||||
@@ -36,38 +40,38 @@ public struct OutputSpan<Element: ~Copyable>: ~Copyable, ~Escapable {
|
||||
|
||||
deinit {
|
||||
if _initialized > 0 {
|
||||
_start.withMemoryRebound(to: Element.self, capacity: _initialized) {
|
||||
unsafe _start().withMemoryRebound(
|
||||
to: Element.self, capacity: _initialized
|
||||
) {
|
||||
[ workaround = _initialized ] in
|
||||
_ = $0.deinitialize(count: workaround)
|
||||
_ = unsafe $0.deinitialize(count: workaround)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@usableFromInline @inline(__always)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow start)
|
||||
init(
|
||||
internal init(
|
||||
_unchecked start: UnsafeMutableRawPointer?,
|
||||
capacity: Int,
|
||||
initialized: Int
|
||||
) {
|
||||
_pointer = start
|
||||
_pointer = unsafe start
|
||||
self.capacity = capacity
|
||||
_initialized = initialized
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@available(macOS 9999, *)
|
||||
@available(*, unavailable)
|
||||
extension OutputSpan: Sendable {}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@available(macOS 9999, *)
|
||||
extension OutputSpan where Element: ~Copyable {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@usableFromInline @inline(__always)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
init(
|
||||
internal init(
|
||||
_unchecked buffer: UnsafeMutableBufferPointer<Element>,
|
||||
initialized: Int
|
||||
) {
|
||||
@@ -76,7 +80,6 @@ extension OutputSpan where Element: ~Copyable {
|
||||
_initialized = initialized
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
@@ -91,7 +94,6 @@ extension OutputSpan where Element: ~Copyable {
|
||||
self.init(_unchecked: buffer, initialized: initialized)
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
public init(
|
||||
@@ -100,31 +102,30 @@ extension OutputSpan where Element: ~Copyable {
|
||||
initialized: Int = 0
|
||||
) {
|
||||
precondition(capacity >= 0, "Capacity must be 0 or greater")
|
||||
self.init(
|
||||
_initializing: .init(start: pointer, count: capacity),
|
||||
initialized: initialized
|
||||
)
|
||||
let buf = unsafe UnsafeMutableBufferPointer(start: pointer, count: capacity)
|
||||
let os = OutputSpan(_initializing: buf, initialized: initialized)
|
||||
self = unsafe _overrideLifetime(os, borrowing: pointer)
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@available(macOS 9999, *)
|
||||
extension OutputSpan {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_initializing buffer: borrowing Slice<UnsafeMutableBufferPointer<Element>>,
|
||||
initialized: Int = 0
|
||||
) {
|
||||
self.init(_initializing: .init(rebasing: buffer), initialized: initialized)
|
||||
let rebased = unsafe UnsafeMutableBufferPointer(rebasing: buffer)
|
||||
let os = OutputSpan(_initializing: rebased, initialized: 0)
|
||||
self = unsafe unsafe _overrideLifetime(os, borrowing: buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@available(macOS 9999, *)
|
||||
extension OutputSpan where Element: BitwiseCopyable {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow bytes)
|
||||
public init(
|
||||
@@ -139,12 +140,13 @@ extension OutputSpan where Element: BitwiseCopyable {
|
||||
let (byteCount, stride) = (bytes.count, MemoryLayout<Element>.stride)
|
||||
let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride)
|
||||
precondition(remainder == 0, "Span must contain a whole number of elements")
|
||||
self.init(
|
||||
_unchecked: bytes.baseAddress, capacity: count, initialized: initialized
|
||||
let pointer = bytes.baseAddress
|
||||
let os = OutputSpan(
|
||||
_unchecked: pointer, capacity: count, initialized: initialized
|
||||
)
|
||||
self = unsafe _overrideLifetime(os, borrowing: bytes)
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow pointer)
|
||||
public init(
|
||||
@@ -153,56 +155,53 @@ extension OutputSpan where Element: BitwiseCopyable {
|
||||
initialized: Int = 0
|
||||
) {
|
||||
precondition(capacity >= 0, "Capacity must be 0 or greater")
|
||||
self.init(
|
||||
_initializing: .init(start: pointer, count: capacity),
|
||||
initialized: initialized
|
||||
)
|
||||
let buf = unsafe UnsafeMutableRawBufferPointer(start: pointer, count: capacity)
|
||||
let os = OutputSpan(_initializing: buf, initialized: initialized)
|
||||
self = unsafe _overrideLifetime(os, borrowing: pointer)
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
@lifetime(borrow buffer)
|
||||
public init(
|
||||
_initializing buffer: borrowing Slice<UnsafeMutableRawBufferPointer>,
|
||||
initialized: Int = 0
|
||||
) {
|
||||
self.init(
|
||||
_initializing: UnsafeMutableRawBufferPointer(rebasing: buffer),
|
||||
initialized: initialized
|
||||
)
|
||||
let rebased = unsafe UnsafeMutableRawBufferPointer(rebasing: buffer)
|
||||
let os = OutputSpan(_initializing: rebased, initialized: initialized)
|
||||
self = unsafe _overrideLifetime(os, borrowing: buffer)
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@available(macOS 9999, *)
|
||||
extension OutputSpan where Element: ~Copyable {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func appendElement(_ value: consuming Element) {
|
||||
public mutating func append(_ value: consuming Element) {
|
||||
precondition(_initialized < capacity, "Output buffer overflow")
|
||||
let p = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
p.initializeMemory(as: Element.self, to: value)
|
||||
let p = unsafe _start().advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
unsafe p.initializeMemory(as: Element.self, to: value)
|
||||
_initialized &+= 1
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func deinitializeLastElement() -> Element? {
|
||||
public mutating func removeLast() -> Element? {
|
||||
guard _initialized > 0 else { return nil }
|
||||
_initialized &-= 1
|
||||
let p = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
return p.withMemoryRebound(to: Element.self, capacity: 1, { $0.move() })
|
||||
let p = unsafe _start().advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
return unsafe p.withMemoryRebound(to: Element.self, capacity: 1, { unsafe $0.move() })
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func deinitialize() {
|
||||
_ = _start.withMemoryRebound(to: Element.self, capacity: _initialized) {
|
||||
$0.deinitialize(count: _initialized)
|
||||
public mutating func removeAll() {
|
||||
_ = unsafe _start().withMemoryRebound(to: Element.self, capacity: _initialized) {
|
||||
unsafe $0.deinitialize(count: _initialized)
|
||||
}
|
||||
_initialized = 0
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: bulk-update functions
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@available(macOS 9999, *)
|
||||
extension OutputSpan {
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -213,9 +212,9 @@ extension OutputSpan {
|
||||
"destination span cannot contain number of elements requested."
|
||||
)
|
||||
let offset = _initialized&*MemoryLayout<Element>.stride
|
||||
let p = _start.advanced(by: offset)
|
||||
p.withMemoryRebound(to: Element.self, capacity: count) {
|
||||
$0.initialize(repeating: repeatedValue, count: count)
|
||||
let p = unsafe _start().advanced(by: offset)
|
||||
unsafe p.withMemoryRebound(to: Element.self, capacity: count) {
|
||||
unsafe $0.initialize(repeating: repeatedValue, count: count)
|
||||
}
|
||||
_initialized &+= count
|
||||
}
|
||||
@@ -235,8 +234,8 @@ extension OutputSpan {
|
||||
) {
|
||||
while _initialized < capacity {
|
||||
guard let element = elements.next() else { break }
|
||||
let p = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
p.initializeMemory(as: Element.self, to: element)
|
||||
let p = unsafe _start().advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
unsafe p.initializeMemory(as: Element.self, to: element)
|
||||
_initialized &+= 1
|
||||
}
|
||||
}
|
||||
@@ -246,22 +245,18 @@ extension OutputSpan {
|
||||
fromContentsOf source: some Collection<Element>
|
||||
) {
|
||||
let void: Void? = source.withContiguousStorageIfAvailable {
|
||||
#if false
|
||||
append(fromContentsOf: Span(_unsafeElements: $0))
|
||||
#else //FIXME: remove once rdar://136838539 & rdar://136849171 are fixed
|
||||
append(fromContentsOf: $0)
|
||||
#endif
|
||||
}
|
||||
if void != nil {
|
||||
return
|
||||
}
|
||||
|
||||
let available = capacity &- _initialized
|
||||
let tail = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
let tail = unsafe _start().advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
var (iterator, copied) =
|
||||
tail.withMemoryRebound(to: Element.self, capacity: available) {
|
||||
let suffix = UnsafeMutableBufferPointer(start: $0, count: available)
|
||||
return source._copyContents(initializing: suffix)
|
||||
unsafe tail.withMemoryRebound(to: Element.self, capacity: available) {
|
||||
let suffix = unsafe UnsafeMutableBufferPointer(start: $0, count: available)
|
||||
return unsafe source._copyContents(initializing: suffix)
|
||||
}
|
||||
precondition(
|
||||
iterator.next() == nil,
|
||||
@@ -271,24 +266,6 @@ extension OutputSpan {
|
||||
_initialized &+= copied
|
||||
}
|
||||
|
||||
//FIXME: remove once rdar://136838539 & rdar://136849171 are fixed
|
||||
public mutating func append(
|
||||
fromContentsOf source: UnsafeBufferPointer<Element>
|
||||
) {
|
||||
guard !source.isEmpty else { return }
|
||||
precondition(
|
||||
source.count <= available,
|
||||
"destination span cannot contain every element from source."
|
||||
)
|
||||
let tail = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
source.baseAddress!.withMemoryRebound(to: Element.self, capacity: source.count) {
|
||||
_ = tail.initializeMemory(as: Element.self, from: $0, count: source.count)
|
||||
}
|
||||
_initialized += source.count
|
||||
}
|
||||
|
||||
//FIXME: rdar://136838539 & rdar://136849171
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func append(
|
||||
fromContentsOf source: Span<Element>
|
||||
@@ -298,24 +275,24 @@ extension OutputSpan {
|
||||
source.count <= available,
|
||||
"destination span cannot contain every element from source."
|
||||
)
|
||||
let tail = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
source._start().withMemoryRebound(to: Element.self, capacity: source.count) {
|
||||
_ = tail.initializeMemory(as: Element.self, from: $0, count: source.count)
|
||||
let tail = unsafe _start().advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
_ = source.withUnsafeBufferPointer {
|
||||
unsafe tail.initializeMemory(
|
||||
as: Element.self, from: $0.baseAddress!, count: $0.count
|
||||
)
|
||||
}
|
||||
_initialized += source.count
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func append(fromContentsOf source: borrowing MutableSpan<Element>) {
|
||||
source.withUnsafeBufferPointer { append(fromContentsOf: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@available(macOS 9999, *)
|
||||
extension OutputSpan where Element: ~Copyable {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func moveAppend(
|
||||
fromContentsOf source: consuming Self
|
||||
@@ -325,104 +302,94 @@ extension OutputSpan where Element: ~Copyable {
|
||||
source.count <= available,
|
||||
"buffer cannot contain every element from source."
|
||||
)
|
||||
let buffer = source.relinquishBorrowedMemory()
|
||||
let buffer = unsafe source.relinquishBorrowedMemory()
|
||||
// we must now deinitialize the returned UMBP
|
||||
let tail = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
tail.moveInitializeMemory(
|
||||
let tail = unsafe _start().advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
unsafe tail.moveInitializeMemory(
|
||||
as: Element.self, from: buffer.baseAddress!, count: buffer.count
|
||||
)
|
||||
_initialized &+= buffer.count
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func moveAppend(
|
||||
fromContentsOf source: UnsafeMutableBufferPointer<Element>
|
||||
) {
|
||||
#if false //FIXME: rdar://136838539 & rdar://136849171
|
||||
let source = OutputSpan(_initializing: source, initialized: source.count)
|
||||
moveAppend(fromContentsOf: source)
|
||||
#else
|
||||
guard !source.isEmpty else { return }
|
||||
precondition(
|
||||
source.count <= available,
|
||||
"buffer cannot contain every element from source."
|
||||
)
|
||||
let tail = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
|
||||
tail.moveInitializeMemory(
|
||||
as: Element.self, from: source.baseAddress!, count: source.count
|
||||
)
|
||||
_initialized &+= source.count
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension OutputSpan {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func moveAppend(
|
||||
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
|
||||
) {
|
||||
moveAppend(fromContentsOf: UnsafeMutableBufferPointer(rebasing: source))
|
||||
moveAppend(
|
||||
fromContentsOf: unsafe UnsafeMutableBufferPointer(rebasing: source)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension OutputSpan where Element: BitwiseCopyable {
|
||||
|
||||
// TODO: alternative append() implementations for BitwiseCopyable elements
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension OutputSpan where Element: ~Copyable {
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public var initializedPrefix: Span<Element> {
|
||||
get { Span(_unchecked: _pointer, count: _initialized) }
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public func withSpan<E: Error, R: ~Copyable>(
|
||||
_ body: (Span<Element>) throws(E) -> R
|
||||
) throws(E) -> R {
|
||||
try body(initializedPrefix)
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@_alwaysEmitIntoClient
|
||||
public mutating func withMutableSpan<E: Error, Result: ~Copyable>(
|
||||
_ body: (inout MutableSpan<Element>) throws(E) -> Result
|
||||
) throws(E) -> Result {
|
||||
var span = MutableSpan<Element>(_unchecked: _pointer, count: _initialized)
|
||||
defer {
|
||||
precondition(
|
||||
span.count == _initialized && span._pointer == _start,
|
||||
"Substituting the MutableSpan is unsound and unsafe."
|
||||
)
|
||||
public var span: Span<Element> {
|
||||
@lifetime(borrow self)
|
||||
borrowing get {
|
||||
let pointer = unsafe _pointer?.assumingMemoryBound(to: Element.self)
|
||||
let buffer = unsafe UnsafeBufferPointer(start: pointer, count: _initialized)
|
||||
let span = Span(_unsafeElements: buffer)
|
||||
return unsafe _overrideLifetime(span, borrowing: self)
|
||||
}
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
public var mutableSpan: MutableSpan<Element> {
|
||||
@lifetime(borrow self)
|
||||
mutating get {
|
||||
let pointer = unsafe _pointer?.assumingMemoryBound(to: Element.self)
|
||||
let buffer = unsafe UnsafeMutableBufferPointer(
|
||||
start: pointer, count: _initialized
|
||||
)
|
||||
let span = MutableSpan(_unsafeElements: buffer)
|
||||
return unsafe _overrideLifetime(span, mutating: &self)
|
||||
}
|
||||
return try body(&span)
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@available(macOS 9999, *)
|
||||
extension OutputSpan where Element: ~Copyable {
|
||||
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public consuming func relinquishBorrowedMemory() -> UnsafeMutableBufferPointer<Element> {
|
||||
public consuming func relinquishBorrowedMemory(
|
||||
) -> UnsafeMutableBufferPointer<Element> {
|
||||
let (start, count) = (self._pointer, self._initialized)
|
||||
discard self
|
||||
let typed = start?.bindMemory(to: Element.self, capacity: count)
|
||||
return .init(start: typed, count: count)
|
||||
let typed = unsafe start?.bindMemory(to: Element.self, capacity: count)
|
||||
return unsafe UnsafeMutableBufferPointer(start: typed, count: count)
|
||||
}
|
||||
}
|
||||
|
||||
@_disallowFeatureSuppression(NonescapableTypes)
|
||||
@available(macOS 9999, *)
|
||||
extension OutputSpan where Element: BitwiseCopyable {
|
||||
|
||||
@unsafe
|
||||
@_alwaysEmitIntoClient
|
||||
public consuming func relinquishBorrowedBytes() -> UnsafeMutableRawBufferPointer {
|
||||
public consuming func relinquishBorrowedBytes(
|
||||
) -> UnsafeMutableRawBufferPointer {
|
||||
let (start, count) = (self._pointer, self._initialized)
|
||||
discard self
|
||||
return .init(start: start, count: count&*MemoryLayout<Element>.stride)
|
||||
let byteCount = count&*MemoryLayout<Element>.stride
|
||||
return unsafe UnsafeMutableRawBufferPointer(start: start, count: byteCount)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//===--- SpanExtensions.swift ---------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
private let immortalThing: [Void] = []
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension Span {
|
||||
|
||||
@available(macOS 9999, *)
|
||||
public static var empty: Span {
|
||||
@lifetime(immortal)
|
||||
get {
|
||||
let empty = unsafe UnsafeBufferPointer<Element>(start: nil, count: 0)
|
||||
let span = Span(_unsafeElements: empty)
|
||||
return unsafe _overrideLifetime(span, borrowing: immortalThing)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
@lifetime(immortal)
|
||||
public init() {
|
||||
let empty = unsafe UnsafeBufferPointer<Element>(start: nil, count: 0)
|
||||
let span = Span(_unsafeElements: empty)
|
||||
self = unsafe _overrideLifetime(span, borrowing: immortalThing)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
extension Span where Element: Equatable {
|
||||
|
||||
/// Returns a Boolean value indicating whether this and another span
|
||||
/// contain equal elements in the same order.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - other: A span to compare to this one.
|
||||
/// - Returns: `true` if this sequence and `other` contain equivalent items,
|
||||
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
|
||||
///
|
||||
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
|
||||
/// sequence and the length of `other`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: Self) -> Bool {
|
||||
guard count == other.count else { return false }
|
||||
if count == 0 { return true }
|
||||
|
||||
//FIXME: This could be short-cut
|
||||
// with a layout constraint where stride equals size,
|
||||
// as long as there is at most 1 unused bit pattern.
|
||||
// if Element is BitwiseEquatable {
|
||||
// return _swift_stdlib_memcmp(lhs.baseAddress, rhs.baseAddress, count) == 0
|
||||
// }
|
||||
for o in 0..<count {
|
||||
if unsafe self[unchecked: o] != other[unchecked: o] { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Returns a Boolean value indicating whether this span and a Collection
|
||||
/// contain equal elements in the same order.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - other: A Collection to compare to this span.
|
||||
/// - Returns: `true` if this sequence and `other` contain equivalent items,
|
||||
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
|
||||
///
|
||||
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
|
||||
/// sequence and the length of `other`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: some Collection<Element>) -> Bool {
|
||||
let equal = other.withContiguousStorageIfAvailable {
|
||||
_elementsEqual(Span(_unsafeElements: $0))
|
||||
}
|
||||
if let equal { return equal }
|
||||
|
||||
guard count == other.count else { return false }
|
||||
if count == 0 { return true }
|
||||
|
||||
return _elementsEqual(AnySequence(other))
|
||||
}
|
||||
|
||||
/// Returns a Boolean value indicating whether this span and a Sequence
|
||||
/// contain equal elements in the same order.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - other: A Sequence to compare to this span.
|
||||
/// - Returns: `true` if this sequence and `other` contain equivalent items,
|
||||
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
|
||||
///
|
||||
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
|
||||
/// sequence and the length of `other`.
|
||||
@_alwaysEmitIntoClient
|
||||
public func _elementsEqual(_ other: some Sequence<Element>) -> Bool {
|
||||
var offset = 0
|
||||
for otherElement in other {
|
||||
if offset >= count { return false }
|
||||
if unsafe self[unchecked: offset] != otherElement { return false }
|
||||
offset += 1
|
||||
}
|
||||
return offset == count
|
||||
}
|
||||
}
|
||||
+24
-22
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2024 Apple Inc. and the Swift project authors
|
||||
// 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
|
||||
@@ -12,20 +12,21 @@
|
||||
|
||||
extension Array {
|
||||
|
||||
@available(macOS 9999, *)
|
||||
public init(
|
||||
capacity: Int,
|
||||
initializingWith initializer: (inout OutputSpan<Element>) throws -> Void
|
||||
) rethrows {
|
||||
try self.init(
|
||||
try unsafe self.init(
|
||||
unsafeUninitializedCapacity: capacity,
|
||||
initializingWith: { (buffer, count) in
|
||||
let pointer = unsafe buffer.baseAddress.unsafelyUnwrapped
|
||||
var output = OutputSpan<Element>(
|
||||
_initializing: buffer.baseAddress.unsafelyUnwrapped,
|
||||
capacity: buffer.count
|
||||
_initializing: pointer, capacity: buffer.count
|
||||
)
|
||||
try initializer(&output)
|
||||
let initialized = output.relinquishBorrowedMemory()
|
||||
assert(initialized.baseAddress == buffer.baseAddress)
|
||||
let initialized = unsafe output.relinquishBorrowedMemory()
|
||||
unsafe assert(initialized.baseAddress == buffer.baseAddress)
|
||||
count = initialized.count
|
||||
}
|
||||
)
|
||||
@@ -37,21 +38,21 @@ extension String {
|
||||
// also see https://github.com/apple/swift/pull/23050
|
||||
// and `final class __SharedStringStorage`
|
||||
|
||||
@available(macOS 11, *)
|
||||
@available(macOS 9999, *)
|
||||
public init(
|
||||
utf8Capacity capacity: Int,
|
||||
initializingWith initializer: (inout OutputSpan<UInt8>) throws -> Void
|
||||
initializingWith initializer: (inout OutputSpan<UTF8.CodeUnit>) throws -> Void
|
||||
) rethrows {
|
||||
try self.init(
|
||||
try unsafe self.init(
|
||||
unsafeUninitializedCapacity: capacity,
|
||||
initializingUTF8With: { buffer in
|
||||
var output = OutputSpan(
|
||||
_initializing: buffer.baseAddress.unsafelyUnwrapped,
|
||||
capacity: capacity
|
||||
let pointer = unsafe buffer.baseAddress.unsafelyUnwrapped
|
||||
var output = OutputSpan<UTF8.CodeUnit>(
|
||||
_initializing: pointer, capacity: buffer.count
|
||||
)
|
||||
try initializer(&output)
|
||||
let initialized = output.relinquishBorrowedMemory()
|
||||
assert(initialized.baseAddress == buffer.baseAddress)
|
||||
let initialized = unsafe output.relinquishBorrowedMemory()
|
||||
unsafe assert(initialized.baseAddress == buffer.baseAddress)
|
||||
return initialized.count
|
||||
}
|
||||
)
|
||||
@@ -62,21 +63,22 @@ import Foundation
|
||||
|
||||
extension Data {
|
||||
|
||||
@available(macOS 9999, *)
|
||||
public init(
|
||||
capacity: Int,
|
||||
initializingWith initializer: (inout OutputSpan<UInt8>) throws -> Void
|
||||
) rethrows {
|
||||
self = Data(count: capacity) // initialized with zeroed buffer
|
||||
let count = try self.withUnsafeMutableBytes { rawBuffer in
|
||||
try rawBuffer.withMemoryRebound(to: UInt8.self) { buffer in
|
||||
buffer.deinitialize()
|
||||
var output = OutputSpan(
|
||||
_initializing: buffer.baseAddress.unsafelyUnwrapped,
|
||||
capacity: capacity
|
||||
let count = unsafe try self.withUnsafeMutableBytes { rawBuffer in
|
||||
unsafe try rawBuffer.withMemoryRebound(to: UInt8.self) { buffer in
|
||||
unsafe buffer.deinitialize()
|
||||
let pointer = unsafe buffer.baseAddress.unsafelyUnwrapped
|
||||
var output = OutputSpan<UInt8>(
|
||||
_initializing: pointer, capacity: capacity
|
||||
)
|
||||
try initializer(&output)
|
||||
let initialized = output.relinquishBorrowedMemory()
|
||||
assert(initialized.baseAddress == buffer.baseAddress)
|
||||
let initialized = unsafe output.relinquishBorrowedMemory()
|
||||
unsafe assert(initialized.baseAddress == buffer.baseAddress)
|
||||
return initialized.count
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -1,43 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Future
|
||||
|
||||
final class FutureBoxTests: XCTestCase {
|
||||
func test_basic() {
|
||||
let intOnHeap = Box<Int>(0)
|
||||
|
||||
XCTAssertEqual(intOnHeap[], 0)
|
||||
|
||||
intOnHeap[] = 123
|
||||
|
||||
XCTAssertEqual(intOnHeap[], 123)
|
||||
|
||||
let inoutToIntOnHeap = intOnHeap.leak()
|
||||
|
||||
XCTAssertEqual(inoutToIntOnHeap[], 123)
|
||||
|
||||
inoutToIntOnHeap[] = 321
|
||||
|
||||
XCTAssertEqual(inoutToIntOnHeap[], 321)
|
||||
|
||||
let intOnHeapAgain = Box<Int>(inoutToIntOnHeap)
|
||||
|
||||
XCTAssertEqual(intOnHeapAgain[], 321)
|
||||
|
||||
XCTAssertEqual(intOnHeapAgain.copy(), 321)
|
||||
|
||||
let intInRegister = intOnHeapAgain.consume()
|
||||
|
||||
XCTAssertEqual(intInRegister, 321)
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Future
|
||||
|
||||
final class FutureCellTests: XCTestCase {
|
||||
struct IntOnStack: ~Copyable {
|
||||
var value = Cell<Int>(0)
|
||||
}
|
||||
|
||||
func test_basic() {
|
||||
var myInt = IntOnStack()
|
||||
|
||||
XCTAssertEqual(myInt.value[], 0)
|
||||
|
||||
myInt.value[] = 123
|
||||
|
||||
XCTAssertEqual(myInt.value[], 123)
|
||||
|
||||
let inoutToIntOnStack = myInt.value.asInout()
|
||||
|
||||
inoutToIntOnStack[] = 321
|
||||
|
||||
XCTAssertEqual(myInt.value[], 321)
|
||||
|
||||
XCTAssertEqual(myInt.value.copy(), 321)
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import XCTest
|
||||
import Future
|
||||
|
||||
final class ContiguousStorageTests: XCTestCase {
|
||||
|
||||
func testBorrowArrayStorage() throws {
|
||||
|
||||
let capacity = 10
|
||||
var a: [Int] = []
|
||||
a = Array(0..<capacity)
|
||||
|
||||
let span = a.storage
|
||||
XCTAssertEqual(span.count, capacity)
|
||||
|
||||
for i in span.indices {
|
||||
XCTAssertEqual(span[i], a[i])
|
||||
}
|
||||
|
||||
// This should end the borrow, and the mutation should work rdar://126298676
|
||||
// _ = consume span
|
||||
// a = []
|
||||
}
|
||||
|
||||
private struct Skipper: ~Escapable {
|
||||
private var span: Span<Int>
|
||||
|
||||
var startIndex: Int { 0 }
|
||||
var endIndex: Int { span.count }
|
||||
func index(after i: Int) -> Int { i+2 }
|
||||
|
||||
init(_ contiguous: borrowing Span<Int>) {
|
||||
span = copy contiguous
|
||||
}
|
||||
|
||||
subscript(_ p: Int) -> Int { span[p] }
|
||||
}
|
||||
|
||||
@inline(never)
|
||||
@lifetime(borrow array)
|
||||
private func skip(
|
||||
along array: borrowing Array<Int>
|
||||
) -> Skipper {
|
||||
Skipper(array.storage)
|
||||
}
|
||||
|
||||
func testSpanWrapper() {
|
||||
let capacity = 8
|
||||
let a = Array(0..<capacity)
|
||||
|
||||
let skipper = skip(along: a)
|
||||
var i = skipper.startIndex
|
||||
var s: [Int] = []
|
||||
while i < skipper.endIndex {
|
||||
s.append(skipper[i])
|
||||
i = skipper.index(after: i)
|
||||
}
|
||||
XCTAssertEqual(s, [0, 2, 4, 6])
|
||||
}
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
import XCTest
|
||||
import _CollectionsTestSupport
|
||||
import Future
|
||||
|
||||
struct Counted: ~Copyable {
|
||||
var value: Int
|
||||
nonisolated(unsafe) static var instances: Int = 0
|
||||
|
||||
init(_ value: Int) {
|
||||
self.value = value
|
||||
Counted.instances += 1
|
||||
}
|
||||
|
||||
deinit {
|
||||
Counted.instances -= 1
|
||||
expectGreaterThanOrEqual(Counted.instances, 0)
|
||||
}
|
||||
}
|
||||
|
||||
class DynamicArrayTests: CollectionTestCase {
|
||||
|
||||
func test_basics() {
|
||||
var array = DynamicArray<Counted>()
|
||||
expectTrue(array.isEmpty)
|
||||
expectEqual(array.count, 0)
|
||||
expectEqual(array.capacity, 0)
|
||||
expectEqual(Counted.instances, 0)
|
||||
|
||||
array.append(Counted(42))
|
||||
expectFalse(array.isEmpty)
|
||||
expectEqual(array.count, 1)
|
||||
expectEqual(array[0].value, 42)
|
||||
expectEqual(Counted.instances, 1)
|
||||
|
||||
array.append(Counted(23))
|
||||
expectFalse(array.isEmpty)
|
||||
expectEqual(array.count, 2)
|
||||
expectEqual(array[0].value, 42)
|
||||
expectEqual(array[1].value, 23)
|
||||
expectEqual(Counted.instances, 2)
|
||||
|
||||
let old = array.remove(at: 0)
|
||||
expectEqual(old.value, 42)
|
||||
expectFalse(array.isEmpty)
|
||||
expectEqual(array.count, 1)
|
||||
expectEqual(array[0].value, 23)
|
||||
expectEqual(Counted.instances, 2)
|
||||
_ = consume old
|
||||
expectEqual(Counted.instances, 1)
|
||||
|
||||
let old2 = array.remove(at: 0)
|
||||
expectEqual(old2.value, 23)
|
||||
expectEqual(array.count, 0)
|
||||
expectTrue(array.isEmpty)
|
||||
expectEqual(Counted.instances, 1)
|
||||
_ = consume old2
|
||||
expectEqual(Counted.instances, 0)
|
||||
}
|
||||
|
||||
func test_read_access() {
|
||||
let c = 100
|
||||
let array = DynamicArray<Counted>(count: c) { Counted($0) }
|
||||
|
||||
for i in 0 ..< c {
|
||||
expectEqual(array.borrowElement(at: i) { $0.value }, i)
|
||||
expectEqual(array[i].value, i)
|
||||
}
|
||||
}
|
||||
|
||||
func test_update_access() {
|
||||
let c = 100
|
||||
var array = DynamicArray<Counted>(count: c) { Counted($0) }
|
||||
|
||||
for i in 0 ..< c {
|
||||
array.updateElement(at: i) { $0.value += 100 }
|
||||
array[i].value += 100
|
||||
}
|
||||
|
||||
for i in 0 ..< c {
|
||||
expectEqual(array[i].value, 200 + i)
|
||||
}
|
||||
|
||||
expectEqual(Counted.instances, c)
|
||||
_ = consume array
|
||||
expectEqual(Counted.instances, 0)
|
||||
}
|
||||
|
||||
func test_append() {
|
||||
var array = DynamicArray<Counted>()
|
||||
let c = 100
|
||||
for i in 0 ..< c {
|
||||
array.append(Counted(100 + i))
|
||||
}
|
||||
expectEqual(Counted.instances, c)
|
||||
expectEqual(array.count, c)
|
||||
|
||||
for i in 0 ..< c {
|
||||
// FIXME: unexpected exclusivity violation (rdar://128441125)
|
||||
//expectEqual(array.borrowElement(at: i) { $0.value }, 100 + i)
|
||||
expectEqual(array[i].value, 100 + i)
|
||||
}
|
||||
|
||||
_ = consume array
|
||||
expectEqual(Counted.instances, 0)
|
||||
}
|
||||
|
||||
func test_insert() {
|
||||
var array = DynamicArray<Counted>()
|
||||
let c = 100
|
||||
for i in 0 ..< c {
|
||||
array.insert(Counted(100 + i), at: 0)
|
||||
}
|
||||
expectEqual(Counted.instances, c)
|
||||
expectEqual(array.count, c)
|
||||
|
||||
for i in 0 ..< c {
|
||||
// FIXME: unexpected exclusivity violation (rdar://128441125)
|
||||
//expectEqual(array.borrowElement(at: i) { $0.value }, c + 99 - i)
|
||||
expectEqual(array[i].value, c + 99 - i)
|
||||
}
|
||||
|
||||
_ = consume array
|
||||
expectEqual(Counted.instances, 0)
|
||||
}
|
||||
|
||||
func test_remove() {
|
||||
let c = 100
|
||||
var array = DynamicArray<Counted>(count: c) { Counted(100 + $0) }
|
||||
expectEqual(Counted.instances, c)
|
||||
expectEqual(array.count, c)
|
||||
|
||||
for i in 0 ..< c {
|
||||
array.remove(at: 0)
|
||||
expectEqual(array.count, c - 1 - i)
|
||||
expectEqual(Counted.instances, c - 1 - i)
|
||||
}
|
||||
|
||||
expectTrue(array.isEmpty)
|
||||
expectEqual(Counted.instances, 0)
|
||||
}
|
||||
|
||||
func test_iterate_full() {
|
||||
let c = 100
|
||||
let array = DynamicArray<Counted>(count: c) { Counted(100 + $0) }
|
||||
|
||||
var state = array.startBorrowingIteration()
|
||||
do {
|
||||
let span = state.nextChunk(maximumCount: Int.max)
|
||||
expectEqual(span.count, c)
|
||||
for i in 0 ..< span.count {
|
||||
expectEqual(span[i].value, 100 + i)
|
||||
}
|
||||
}
|
||||
do {
|
||||
let span2 = state.nextChunk(maximumCount: Int.max)
|
||||
expectEqual(span2.count, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func test_iterate_stepped() {
|
||||
let c = 100
|
||||
let array = DynamicArray<Counted>(count: c) { Counted($0) }
|
||||
|
||||
withEvery("stride", in: 1 ... c) { stride in
|
||||
var state = array.startBorrowingIteration()
|
||||
var i = 0
|
||||
while true {
|
||||
let span = state.nextChunk(maximumCount: stride)
|
||||
if span.count == 0 { break }
|
||||
expectEqual(span.count, i + stride <= c ? stride : c % stride)
|
||||
for j in 0 ..< span.count {
|
||||
expectEqual(span[j].value, i)
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
expectEqual(i, c)
|
||||
expectEqual(state.nextChunk(maximumCount: Int.max).count, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Future
|
||||
|
||||
final class FutureInoutTests: XCTestCase {
|
||||
func test_basic() {
|
||||
var x = 0
|
||||
let y = Inout(&x)
|
||||
|
||||
var v = y[]
|
||||
XCTAssertEqual(v, 0)
|
||||
|
||||
y[] += 10
|
||||
|
||||
v = y[]
|
||||
XCTAssertEqual(v, 10)
|
||||
XCTAssertEqual(x, 10)
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
//===--- StdlibSpanExtensionTests.swift -----------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Foundation
|
||||
import Future
|
||||
|
||||
enum ErrorForTesting: Error, Equatable { case error, errorToo, errorAsWell }
|
||||
|
||||
final class StdlibSpanExtensionTests: XCTestCase {
|
||||
|
||||
func testDataSpan() throws {
|
||||
let a = Data(0..<4)
|
||||
a.withSpan {
|
||||
for i in $0.indices {
|
||||
XCTAssertEqual($0[i], UInt8(i))
|
||||
}
|
||||
}
|
||||
do throws(ErrorForTesting) {
|
||||
try a.withSpan { _ throws(ErrorForTesting) in throw .error }
|
||||
} catch {
|
||||
XCTAssertEqual(error, .error)
|
||||
}
|
||||
}
|
||||
|
||||
func testDataRawSpan() throws {
|
||||
let a = Data(0..<4)
|
||||
a.withBytes {
|
||||
for i in $0.byteOffsets {
|
||||
XCTAssertEqual(
|
||||
$0.unsafeLoad(fromByteOffset: i, as: UInt8.self), UInt8(i)
|
||||
)
|
||||
}
|
||||
}
|
||||
do throws(ErrorForTesting) {
|
||||
try a.withBytes { _ throws(ErrorForTesting) in throw .error }
|
||||
} catch {
|
||||
XCTAssertEqual(error, .error)
|
||||
}
|
||||
}
|
||||
|
||||
func testArraySpan() throws {
|
||||
let a = (0..<4).map(String.init(_:))
|
||||
do throws(ErrorForTesting) {
|
||||
a.withSpan {
|
||||
for i in $0.indices {
|
||||
XCTAssertEqual($0[i], String(i))
|
||||
}
|
||||
}
|
||||
try a.withSpan { _ throws(ErrorForTesting) in throw .error }
|
||||
} catch {
|
||||
XCTAssertEqual(error, .error)
|
||||
}
|
||||
}
|
||||
|
||||
func testArrayRawSpan() throws {
|
||||
let c = 4
|
||||
let a = Array(0..<c)
|
||||
a.withBytes {
|
||||
for i in 0..<c {
|
||||
XCTAssertEqual(
|
||||
i, $0.unsafeLoad(
|
||||
fromByteOffset: i*MemoryLayout<Int>.stride, as: Int.self
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
do throws(ErrorForTesting) {
|
||||
try a.withBytes { _ throws(ErrorForTesting) in throw .error }
|
||||
} catch {
|
||||
XCTAssertEqual(error, .error)
|
||||
}
|
||||
}
|
||||
|
||||
func testContiguousArraySpan() throws {
|
||||
let a = ContiguousArray((0..<4).map(String.init(_:)))
|
||||
a.withSpan {
|
||||
for i in $0.indices {
|
||||
XCTAssertEqual($0[i], String(i))
|
||||
}
|
||||
}
|
||||
do throws(ErrorForTesting) {
|
||||
try a.withSpan { _ throws(ErrorForTesting) in throw .error }
|
||||
} catch {
|
||||
XCTAssertEqual(error, .error)
|
||||
}
|
||||
}
|
||||
|
||||
func testContiguousArrayRawSpan() throws {
|
||||
let c = 4
|
||||
let a = ContiguousArray(0..<c)
|
||||
a.withBytes {
|
||||
for i in 0..<c {
|
||||
XCTAssertEqual(
|
||||
i, $0.unsafeLoad(
|
||||
fromByteOffset: i*MemoryLayout<Int>.stride, as: Int.self
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
XCTAssertThrowsError(try a.withBytes({ _ in throw ErrorForTesting.error }))
|
||||
}
|
||||
|
||||
func testArraySliceSpan() throws {
|
||||
let a = (0..<7).map(String.init(_:)).prefix(upTo: 4)
|
||||
print(a.count)
|
||||
a.withSpan {
|
||||
for i in $0.indices {
|
||||
print(i)
|
||||
let v = $0[i]
|
||||
_ = v
|
||||
XCTAssertEqual($0[i], String(i))
|
||||
}
|
||||
}
|
||||
do throws(ErrorForTesting) {
|
||||
try a.withSpan { _ throws(ErrorForTesting) in throw .error }
|
||||
} catch {
|
||||
XCTAssertEqual(error, .error)
|
||||
}
|
||||
}
|
||||
|
||||
func testArraySliceRawSpan() throws {
|
||||
let c = 4
|
||||
let a = Array(0..<7).prefix(upTo: c)
|
||||
a.withBytes {
|
||||
for i in 0..<c {
|
||||
XCTAssertEqual(
|
||||
i, $0.unsafeLoad(
|
||||
fromByteOffset: i*MemoryLayout<Int>.stride, as: Int.self
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
XCTAssertThrowsError(try a.withBytes({ _ in throw ErrorForTesting.error }))
|
||||
}
|
||||
|
||||
func testCollectionOfOneSpan() throws {
|
||||
let a = CollectionOfOne("CollectionOfOne is an obscure Collection type.")
|
||||
a.withSpan {
|
||||
XCTAssertTrue($0._elementsEqual(a))
|
||||
}
|
||||
XCTAssertThrowsError(try a.withSpan({ _ in throw ErrorForTesting.error }))
|
||||
}
|
||||
|
||||
func testCollectionOfOneRawSpan() throws {
|
||||
let a = CollectionOfOne(Int(UInt8.random(in: 0 ..< .max)))
|
||||
a.withBytes {
|
||||
for i in $0.byteOffsets {
|
||||
let v = $0.unsafeLoad(fromByteOffset: i, as: UInt8.self)
|
||||
if v != 0 {
|
||||
XCTAssertEqual(Int(v), a.first)
|
||||
}
|
||||
}
|
||||
}
|
||||
XCTAssertThrowsError(try a.withBytes({ _ in throw ErrorForTesting.error }))
|
||||
}
|
||||
|
||||
func testUTF8ViewSpan() throws {
|
||||
let strings: [String] = [
|
||||
"small",
|
||||
"Not a small string, if I can count code units correctly.",
|
||||
NSString("legacy string if I can get it to behave.") as String
|
||||
]
|
||||
for s in strings {
|
||||
s.utf8.withSpan {
|
||||
XCTAssertEqual($0.count, s.utf8.count)
|
||||
}
|
||||
}
|
||||
let a = strings[0].utf8
|
||||
XCTAssertThrowsError(try a.withSpan({ _ in throw ErrorForTesting.error }))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
//===--- MutableSpanTests.swift -------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Span
|
||||
|
||||
@available(macOS 9999, *)
|
||||
final class MutableRawSpanTests: XCTestCase {
|
||||
|
||||
func testBasicInitializer() {
|
||||
var s = Array("\(#file)+\(#function)--\(Int.random(in: 1000...9999))".utf8)
|
||||
s.withUnsafeMutableBytes {
|
||||
let b = MutableRawSpan(_unsafeBytes: $0)
|
||||
XCTAssertEqual(b.byteCount, $0.count)
|
||||
XCTAssertFalse(b.isEmpty)
|
||||
XCTAssertEqual(b.byteOffsets, 0..<$0.count)
|
||||
}
|
||||
}
|
||||
|
||||
func testIsEmpty() {
|
||||
var array = [0, 1, 2]
|
||||
array.withUnsafeMutableBufferPointer {
|
||||
var span = MutableRawSpan(_unsafeElements: $0)
|
||||
XCTAssertFalse(span.isEmpty)
|
||||
|
||||
let e = $0.extracting(0..<0)
|
||||
span = MutableRawSpan(_unsafeElements: e)
|
||||
XCTAssertTrue(span.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
func testIndices() {
|
||||
let capacity = 4 as UInt8
|
||||
var a = Array(0..<capacity)
|
||||
a.withUnsafeMutableBytes {
|
||||
let view = MutableRawSpan(_unsafeBytes: $0)
|
||||
XCTAssertEqual(view.byteCount, view.byteOffsets.count)
|
||||
XCTAssert(view.byteOffsets.elementsEqual(0..<view.byteCount))
|
||||
}
|
||||
}
|
||||
|
||||
public func testWithUnsafeBytes() {
|
||||
let capacity: UInt8 = 64
|
||||
var a = Array(0..<capacity)
|
||||
let i = Int.random(in: a.indices)
|
||||
a.withUnsafeMutableBytes {
|
||||
var view = MutableRawSpan(_unsafeBytes: $0)
|
||||
view.withUnsafeBytes {
|
||||
XCTAssertEqual($0.load(fromByteOffset: i, as: UInt8.self), $0[i])
|
||||
}
|
||||
|
||||
let empty = UnsafeMutableRawBufferPointer(start: $0.baseAddress, count: 0)
|
||||
view = MutableRawSpan(_unsafeBytes: empty)
|
||||
view.withUnsafeBytes {
|
||||
XCTAssertEqual($0.count, 0)
|
||||
XCTAssertNil($0.baseAddress)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func testWithUnsafeMutableBytes() {
|
||||
let capacity: UInt8 = 16
|
||||
var a = Array(0..<capacity)
|
||||
let i = Int.random(in: a.indices)
|
||||
a.withUnsafeMutableBytes {
|
||||
var view = MutableRawSpan(_unsafeBytes: $0)
|
||||
let o = view.unsafeLoad(fromByteOffset: i, as: UInt8.self)
|
||||
view.withUnsafeMutableBytes {
|
||||
$0.storeBytes(of: UInt8(i+1), toByteOffset: i, as: UInt8.self)
|
||||
}
|
||||
let m = view.unsafeLoad(fromByteOffset: i, as: UInt8.self)
|
||||
XCTAssertEqual(m, o+1)
|
||||
|
||||
let empty = UnsafeMutableRawBufferPointer(start: $0.baseAddress, count: 0)
|
||||
view = MutableRawSpan(_unsafeBytes: empty)
|
||||
view.withUnsafeMutableBytes {
|
||||
XCTAssertEqual($0.count, 0)
|
||||
XCTAssertNil($0.baseAddress)
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(Int(a[i]), i+1)
|
||||
}
|
||||
|
||||
func testBytesProperty() {
|
||||
var array = [0, 1, 2]
|
||||
array.withUnsafeMutableBufferPointer {
|
||||
let mutable = MutableRawSpan(_unsafeElements: $0)
|
||||
let immutable = mutable.bytes
|
||||
XCTAssertEqual(mutable.byteCount, immutable.byteCount)
|
||||
}
|
||||
}
|
||||
|
||||
func testUnsafeView() {
|
||||
var array = [0, 1, 2]
|
||||
array.withUnsafeMutableBufferPointer {
|
||||
let mutable = MutableRawSpan(_unsafeElements: $0)
|
||||
let view = mutable._unsafeView(as: Int.self)
|
||||
XCTAssertEqual($0[1], view[1])
|
||||
}
|
||||
}
|
||||
|
||||
func testUnsafeMutableView() {
|
||||
var array = [0, 1, 2]
|
||||
let value = Int.random(in: 0..<1000)
|
||||
array.withUnsafeMutableBufferPointer {
|
||||
var mutable = MutableRawSpan(_unsafeElements: $0)
|
||||
var view = mutable._unsafeMutableView(as: Int.self)
|
||||
view[1] = value
|
||||
}
|
||||
XCTAssertEqual(array[1], value)
|
||||
}
|
||||
|
||||
func testLoad() {
|
||||
let capacity = 4
|
||||
var s = (0..<capacity).map({ "\(#file)+\(#function) #\($0)" })
|
||||
s.withUnsafeMutableBytes {
|
||||
let span = MutableRawSpan(_unsafeBytes: $0)
|
||||
let stride = MemoryLayout<String>.stride
|
||||
|
||||
let s0 = span.unsafeLoad(as: String.self)
|
||||
XCTAssertEqual(s0.contains("0"), true)
|
||||
let s1 = span.unsafeLoad(fromByteOffset: stride, as: String.self)
|
||||
XCTAssertEqual(s1.contains("1"), true)
|
||||
let s2 = span.unsafeLoad(fromUncheckedByteOffset: 2*stride, as: String.self)
|
||||
XCTAssertEqual(s2.contains("2"), true)
|
||||
}
|
||||
}
|
||||
|
||||
func testLoadUnaligned() {
|
||||
let capacity = 64
|
||||
var a = Array(0..<UInt8(capacity))
|
||||
a.withUnsafeMutableBytes {
|
||||
var span = MutableRawSpan(_unsafeBytes: $0)
|
||||
|
||||
let suffix = span._extracting(droppingFirst: 2)
|
||||
let u0 = suffix.unsafeLoadUnaligned(as: UInt64.self)
|
||||
XCTAssertEqual(u0 & 0xff, 2)
|
||||
XCTAssertEqual(u0.byteSwapped & 0xff, 9)
|
||||
let u1 = span.unsafeLoadUnaligned(fromByteOffset: 6, as: UInt64.self)
|
||||
XCTAssertEqual(u1 & 0xff, 6)
|
||||
let u3 = span.unsafeLoadUnaligned(fromUncheckedByteOffset: 7, as: UInt32.self)
|
||||
XCTAssertEqual(u3 & 0xff, 7)
|
||||
}
|
||||
}
|
||||
|
||||
func testStoreBytes() {
|
||||
let count = 4
|
||||
var a = Array(repeating: 0, count: count)
|
||||
a.withUnsafeMutableBytes {
|
||||
var span = MutableRawSpan(_unsafeBytes: $0)
|
||||
span.storeBytes(of: .max, as: UInt8.self)
|
||||
span.storeBytes(
|
||||
of: .max, toByteOffset: MemoryLayout<UInt>.stride/2, as: UInt.self
|
||||
)
|
||||
}
|
||||
XCTAssertEqual(a[0].littleEndian & 0xffff, 0xff)
|
||||
XCTAssertEqual(a[0].bigEndian & 0xffff, 0xffff)
|
||||
}
|
||||
|
||||
public func testUpdateFromSequence() {
|
||||
let capacity = 8
|
||||
var a = Array(repeating: Int.max, count: capacity)
|
||||
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
let empty = UnsafeMutableBufferPointer<Int>(start: nil, count: 0)
|
||||
var span = MutableRawSpan(_unsafeElements: empty)
|
||||
var (iterator, updated) = span.update(from: 0..<0)
|
||||
XCTAssertNil(iterator.next())
|
||||
XCTAssertEqual(updated, 0)
|
||||
|
||||
span = MutableRawSpan(_unsafeElements: $0)
|
||||
(iterator, updated) = span.update(from: 0..<0)
|
||||
XCTAssertNil(iterator.next())
|
||||
XCTAssertEqual(updated, 0)
|
||||
|
||||
(iterator, updated) = span.update(from: 0..<10000)
|
||||
XCTAssertNotNil(iterator.next())
|
||||
XCTAssertEqual(updated, capacity*MemoryLayout<Int>.stride)
|
||||
}
|
||||
XCTAssertEqual(a.elementsEqual(0..<capacity), true)
|
||||
}
|
||||
|
||||
public func testUpdateFromCollection() {
|
||||
let capacity = 8
|
||||
var a = Array(repeating: Int.max, count: capacity)
|
||||
let e = Array(EmptyCollection<UInt>())
|
||||
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
|
||||
a.withUnsafeMutableBytes {
|
||||
let emptyPrefix = $0.prefix(0)
|
||||
var span = MutableRawSpan(_unsafeBytes: emptyPrefix)
|
||||
var updated = span.update(fromContentsOf: e)
|
||||
XCTAssertEqual(updated, 0)
|
||||
|
||||
|
||||
updated = span.update(fromContentsOf: AnyCollection(e))
|
||||
XCTAssertEqual(updated, 0)
|
||||
|
||||
span = MutableRawSpan(_unsafeBytes: $0)
|
||||
updated = span.update(fromContentsOf: 0..<capacity)
|
||||
XCTAssertEqual(updated, capacity*MemoryLayout<Int>.stride)
|
||||
}
|
||||
XCTAssertEqual(a.elementsEqual(0..<capacity), true)
|
||||
}
|
||||
|
||||
public func testUpdateFromContiguousMemory() {
|
||||
let capacity = 8
|
||||
var a = Array(repeating: Int.max, count: capacity)
|
||||
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
|
||||
a.withUnsafeMutableBytes {
|
||||
var span = MutableRawSpan(_unsafeBytes: $0)
|
||||
let array = Array(0..<capacity)
|
||||
var updated = span.update(fromContentsOf: array.prefix(0))
|
||||
XCTAssertEqual(updated, 0)
|
||||
|
||||
updated = span.update(fromContentsOf: array)
|
||||
XCTAssertEqual(updated, capacity*MemoryLayout<Int>.stride)
|
||||
}
|
||||
XCTAssertEqual(a.elementsEqual(0..<capacity), true)
|
||||
|
||||
a.withUnsafeMutableBytes {
|
||||
var span = MutableRawSpan(_unsafeBytes: $0)
|
||||
var array = Array(repeating: Int.min, count: capacity)
|
||||
array.withUnsafeMutableBytes {
|
||||
let source = MutableRawSpan(_unsafeBytes: $0)
|
||||
let updated = span.update(fromContentsOf: source)
|
||||
XCTAssertEqual(updated, capacity*MemoryLayout<Int>.stride)
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(a.allSatisfy({ $0 == Int.min }), true)
|
||||
|
||||
a.withUnsafeMutableBytes {
|
||||
var span = MutableRawSpan(_unsafeBytes: $0)
|
||||
let array = Array(0..<capacity)
|
||||
array.withUnsafeBufferPointer {
|
||||
let source = Span(_unsafeElements: $0)
|
||||
let updated = span.update(fromContentsOf: source)
|
||||
XCTAssertEqual(updated, capacity*MemoryLayout<Int>.stride)
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(a.elementsEqual(0..<capacity), true)
|
||||
}
|
||||
|
||||
func testExtracting() {
|
||||
let capacity = 4
|
||||
var b = (0..<capacity).map(Int8.init)
|
||||
b.withUnsafeMutableBytes {
|
||||
var span = MutableRawSpan(_unsafeBytes: $0)
|
||||
|
||||
var sub = span._extracting(0..<2)
|
||||
XCTAssertEqual(sub.byteCount, 2)
|
||||
XCTAssertEqual(sub.unsafeLoad(as: UInt8.self), 0)
|
||||
|
||||
sub = span._extracting(..<2)
|
||||
XCTAssertEqual(sub.byteCount, 2)
|
||||
XCTAssertEqual(sub.unsafeLoad(as: UInt8.self), 0)
|
||||
|
||||
sub = span._extracting(...)
|
||||
XCTAssertEqual(sub.byteCount, 4)
|
||||
XCTAssertEqual(sub.unsafeLoad(as: UInt8.self), 0)
|
||||
|
||||
sub = span._extracting(2...)
|
||||
XCTAssertEqual(sub.byteCount, 2)
|
||||
XCTAssertEqual(sub.unsafeLoad(as: UInt8.self), 2)
|
||||
}
|
||||
}
|
||||
|
||||
func testExtractingUnchecked() {
|
||||
let capacity = 32
|
||||
var b = (0..<capacity).map(UInt8.init)
|
||||
b.withUnsafeMutableBytes {
|
||||
var span = MutableRawSpan(_unsafeBytes: $0.prefix(8))
|
||||
let beyond = span._extracting(unchecked: 16...23)
|
||||
XCTAssertEqual(beyond.byteCount, 8)
|
||||
let fromBeyond = beyond.unsafeLoad(as: UInt8.self)
|
||||
XCTAssertEqual(fromBeyond, 16)
|
||||
}
|
||||
}
|
||||
|
||||
func testPrefix() {
|
||||
let capacity = 4
|
||||
var a = Array(0..<UInt8(capacity))
|
||||
a.withUnsafeMutableBytes {
|
||||
var prefix: MutableRawSpan
|
||||
var span = MutableRawSpan(_unsafeBytes: $0)
|
||||
XCTAssertEqual(span.byteCount, capacity)
|
||||
|
||||
prefix = span._extracting(first: 1)
|
||||
XCTAssertEqual(prefix.unsafeLoad(as: UInt8.self), 0)
|
||||
|
||||
prefix = span._extracting(first: capacity)
|
||||
XCTAssertEqual(
|
||||
prefix.unsafeLoad(fromByteOffset: capacity-1, as: UInt8.self),
|
||||
UInt8(capacity-1)
|
||||
)
|
||||
|
||||
prefix = span._extracting(droppingLast: capacity)
|
||||
XCTAssertEqual(prefix.isEmpty, true)
|
||||
|
||||
prefix = span._extracting(droppingLast: 1)
|
||||
XCTAssertEqual(
|
||||
prefix.unsafeLoad(fromByteOffset: capacity-2, as: UInt8.self),
|
||||
UInt8(capacity-2)
|
||||
)
|
||||
}
|
||||
|
||||
do {
|
||||
let b = UnsafeMutableRawBufferPointer(start: nil, count: 0)
|
||||
var span = MutableRawSpan(_unsafeBytes: b)
|
||||
XCTAssertEqual(span.byteCount, b.count)
|
||||
XCTAssertEqual(span._extracting(first: 1).byteCount, b.count)
|
||||
XCTAssertEqual(span._extracting(droppingLast: 1).byteCount, b.count)
|
||||
}
|
||||
}
|
||||
|
||||
func testSuffix() {
|
||||
let capacity = 4
|
||||
var a = Array(0..<UInt8(capacity))
|
||||
a.withUnsafeMutableBytes {
|
||||
var prefix: MutableRawSpan
|
||||
var span = MutableRawSpan(_unsafeBytes: $0)
|
||||
XCTAssertEqual(span.byteCount, capacity)
|
||||
|
||||
prefix = span._extracting(last: capacity)
|
||||
XCTAssertEqual(prefix.unsafeLoad(as: UInt8.self), 0)
|
||||
|
||||
prefix = span._extracting(last: capacity-1)
|
||||
XCTAssertEqual(prefix.unsafeLoad(as: UInt8.self), 1)
|
||||
|
||||
prefix = span._extracting(last: 1)
|
||||
XCTAssertEqual(prefix.unsafeLoad(as: UInt8.self), UInt8(capacity-1))
|
||||
|
||||
prefix = span._extracting(droppingFirst: capacity)
|
||||
XCTAssertTrue(prefix.isEmpty)
|
||||
|
||||
prefix = span._extracting(droppingFirst: 1)
|
||||
XCTAssertEqual(prefix.unsafeLoad(as: UInt8.self), 1)
|
||||
}
|
||||
|
||||
do {
|
||||
let b = UnsafeMutableRawBufferPointer(start: nil, count: 0)
|
||||
var span = MutableRawSpan(_unsafeBytes: b)
|
||||
XCTAssertEqual(span.byteCount, b.count)
|
||||
XCTAssertEqual(span._extracting(last: 1).byteCount, b.count)
|
||||
XCTAssertEqual(span._extracting(droppingFirst: 1).byteCount, b.count)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//===--- MutableSpanSlicing.swift -----------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift.org 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
|
||||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Span
|
||||
|
||||
//MARK: slicing tests and examples
|
||||
@available(macOS 9999, *)
|
||||
extension MutableSpanTests {
|
||||
|
||||
private func modify(_ s: inout MutableSpan<Int>) {
|
||||
s[0] += 100
|
||||
}
|
||||
|
||||
public func testSliceAsExtractingFunction() {
|
||||
let count = 8
|
||||
let b = UnsafeMutableBufferPointer<Int>.allocate(capacity: count)
|
||||
_ = b.initialize(fromContentsOf: 0..<count)
|
||||
defer { b.deallocate() }
|
||||
|
||||
var m = MutableSpan(_unsafeElements: b)
|
||||
|
||||
let first = 5
|
||||
let range = first..<count
|
||||
var suffix = m.extracting(range)
|
||||
XCTAssertEqual(suffix.count, range.count)
|
||||
XCTAssertEqual(suffix[0], first)
|
||||
|
||||
// m[0] += 100 // exclusivity violation
|
||||
// print(m.count, m[0]) // exclusivity violation
|
||||
|
||||
modify(&suffix)
|
||||
|
||||
// print(m[5]) // exclusivity violation
|
||||
// _ = consume suffix // exclusivity violation
|
||||
|
||||
// ideally, we would like to write:
|
||||
// m.extracting(range).update(repeating: -1)
|
||||
|
||||
suffix = m.extracting(range)
|
||||
suffix.update(repeating: -1)
|
||||
|
||||
XCTAssertEqual(suffix.count, range.count)
|
||||
XCTAssertTrue(suffix._elementsEqual(repeatElement(-1, count: 3)))
|
||||
}
|
||||
|
||||
public func testSliceAsExtractingSubscript() {
|
||||
let count = 8
|
||||
let b = UnsafeMutableBufferPointer<Int>.allocate(capacity: count)
|
||||
_ = b.initialize(fromContentsOf: 0..<count)
|
||||
defer { b.deallocate() }
|
||||
|
||||
var m = MutableSpan(_unsafeElements: b)
|
||||
|
||||
let first = 5
|
||||
let range = first..<count
|
||||
var suffix = m[extracting: range]
|
||||
XCTAssertEqual(suffix.count, range.count)
|
||||
XCTAssertEqual(suffix[0], first)
|
||||
|
||||
// m[0] += 100 // exclusivity violation
|
||||
// print(m.count, m[0]) // exclusivity violation
|
||||
|
||||
modify(&suffix)
|
||||
|
||||
// print(m[5]) // exclusivity violation
|
||||
// _ = consume suffix // exclusivity violation
|
||||
|
||||
// ideally, we would like to write:
|
||||
// m[extracting: range].update(repeating: -1)
|
||||
|
||||
suffix = m[extracting: range]
|
||||
suffix.update(repeating: -1)
|
||||
|
||||
XCTAssertEqual(suffix.count, range.count)
|
||||
XCTAssertTrue(suffix._elementsEqual(repeatElement(-1, count: 3)))
|
||||
}
|
||||
|
||||
private func modify(_ s: inout SubMutableSpan<Int>) {
|
||||
s[s.offset] += 100
|
||||
}
|
||||
|
||||
public func testSliceAsWrapperType() {
|
||||
let count = 8
|
||||
let b = UnsafeMutableBufferPointer<Int>.allocate(capacity: count)
|
||||
_ = b.initialize(fromContentsOf: 0..<count)
|
||||
defer { b.deallocate() }
|
||||
|
||||
var m = MutableSpan(_unsafeElements: b)
|
||||
|
||||
let first = 5
|
||||
let range = first..<count
|
||||
var suffix = m[slicing: range]
|
||||
XCTAssertEqual(suffix.count, range.count)
|
||||
XCTAssertEqual(suffix[5], 5)
|
||||
|
||||
// m[0] += 100 // exclusivity violation
|
||||
// print(m.count, m[0]) // exclusivity violation
|
||||
|
||||
modify(&suffix)
|
||||
|
||||
// print(m[5]) // exclusivity violation
|
||||
// _ = consume suffix // exclusivity violation
|
||||
|
||||
// ideally, we would like to write:
|
||||
// m[slicing: range].update(repeating: -1)
|
||||
|
||||
suffix = m[slicing: range]
|
||||
suffix.update(repeating: -1)
|
||||
|
||||
XCTAssertEqual(suffix.count, range.count)
|
||||
let repeated = repeatElement(-1, count: range.count)
|
||||
XCTAssertTrue(suffix.span._elementsEqual(repeated))
|
||||
}
|
||||
|
||||
public func testPassRangeArgumentInsteadOfSlicing() {
|
||||
let count = 8
|
||||
let b = UnsafeMutableBufferPointer<Int>.allocate(capacity: count)
|
||||
_ = b.initialize(fromContentsOf: 0..<count)
|
||||
defer { b.deallocate() }
|
||||
|
||||
var m = MutableSpan(_unsafeElements: b)
|
||||
|
||||
let first = 5
|
||||
let range = first..<count
|
||||
m.update(in: range, repeating: -1)
|
||||
|
||||
let mutableSuffix = m[extracting: range]
|
||||
let suffix = mutableSuffix.span
|
||||
|
||||
XCTAssertEqual(suffix.count, range.count)
|
||||
let repeated = repeatElement(-1, count: range.count)
|
||||
XCTAssertTrue(suffix._elementsEqual(repeated))
|
||||
}
|
||||
}
|
||||
+222
-120
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2024 Apple Inc. and the Swift project authors
|
||||
// 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
|
||||
@@ -11,7 +11,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
@testable import Future
|
||||
import Span
|
||||
|
||||
class ID {
|
||||
let id: Int
|
||||
@@ -23,26 +23,16 @@ class ID {
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 9999, *)
|
||||
final class MutableSpanTests: XCTestCase {
|
||||
|
||||
func testOptionalStorage() {
|
||||
// XCTAssertEqual(
|
||||
// MemoryLayout<MutableSpan<UInt8>>.size, MemoryLayout<MutableSpan<UInt8>?>.size
|
||||
// )
|
||||
// XCTAssertEqual(
|
||||
// MemoryLayout<MutableSpan<UInt8>>.stride, MemoryLayout<MutableSpan<UInt8>?>.stride
|
||||
// )
|
||||
// XCTAssertEqual(
|
||||
// MemoryLayout<MutableSpan<UInt8>>.alignment, MemoryLayout<MutableSpan<UInt8>?>.alignment
|
||||
// )
|
||||
}
|
||||
|
||||
func testInitOrdinaryElement() {
|
||||
let capacity = 4
|
||||
var s = (0..<capacity).map({ "\(#file)+\(#function)--\($0)" })
|
||||
s.withUnsafeMutableBufferPointer {
|
||||
let b = MutableSpan(_unsafeElements: $0)
|
||||
XCTAssertEqual(b.count, $0.count)
|
||||
let c = b.count
|
||||
XCTAssertEqual(c, $0.count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,71 +41,39 @@ final class MutableSpanTests: XCTestCase {
|
||||
var a = Array(0..<capacity)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
let b = MutableSpan(_unsafeElements: $0)
|
||||
XCTAssertEqual(b.count, $0.count)
|
||||
let c = b.count
|
||||
XCTAssertEqual(c, $0.count)
|
||||
}
|
||||
|
||||
a.withUnsafeMutableBytes {
|
||||
let b = MutableSpan<UInt>(_unsafeBytes: $0)
|
||||
let (rp, bc) = ($0.baseAddress!, $0.count)
|
||||
let b = MutableSpan<UInt>(_unsafeStart: rp, byteCount: bc)
|
||||
XCTAssertEqual(b.count, capacity)
|
||||
|
||||
let r = MutableSpan<Int8>(_unsafeBytes: $0)
|
||||
XCTAssertEqual(r.count, capacity*MemoryLayout<Int>.stride)
|
||||
let stride = MemoryLayout<Int>.stride
|
||||
let r = MutableSpan<Int8>(_unsafeBytes: $0.dropFirst(stride))
|
||||
XCTAssertEqual(r.count, (capacity-1)*stride)
|
||||
XCTAssertEqual(r.count, bc-stride)
|
||||
}
|
||||
|
||||
// let v = UnsafeRawBufferPointer(start: nil, count: 0)
|
||||
// XCTAssertNil(MutableSpan<Int>(unsafeRawBufferPointer: v))
|
||||
let v = UnsafeMutableRawBufferPointer(start: nil, count: 0)
|
||||
let m = MutableSpan<Int>(_unsafeBytes: v)
|
||||
XCTAssertEqual(m.count, 0)
|
||||
}
|
||||
|
||||
// public func testIteratorOrdinaryElement() {
|
||||
// let capacity = 4
|
||||
// var s = (0..<capacity).map({ "\(#file)+\(#function)--\($0)" })
|
||||
// s.withUnsafeMutableBufferPointer {
|
||||
// let view = MutableSpan(_unsafeElements: $0)
|
||||
//
|
||||
// var iterator = view.makeIterator()
|
||||
// var buffered = 0
|
||||
// while let value = iterator.next() {
|
||||
// XCTAssertEqual(value.isEmpty, false)
|
||||
// buffered += 1
|
||||
// }
|
||||
// XCTAssertEqual(buffered, $0.count)
|
||||
// }
|
||||
// }
|
||||
|
||||
// public func testIteratorBitwiseCopyable() {
|
||||
// let count = 4
|
||||
// let offset = 1
|
||||
// XCTAssertLessThan(offset, MemoryLayout<UInt64>.stride)
|
||||
// let bytes = count*MemoryLayout<UInt64>.stride + offset
|
||||
// let align = MemoryLayout<UInt64>.alignment
|
||||
// let p = UnsafeMutableRawPointer.allocate(byteCount: bytes, alignment: align)
|
||||
// defer { p.deallocate() }
|
||||
// for i in 0..<bytes where i%8 == offset {
|
||||
// p.storeBytes(of: 1, toByteOffset: i, as: UInt8.self)
|
||||
// }
|
||||
//
|
||||
// let orig = p.loadUnaligned(as: Int64.self)
|
||||
// XCTAssertNotEqual(orig, 1)
|
||||
//
|
||||
// // MutableSpan doesn't need to be aligned for accessing `BitwiseCopyable` types.
|
||||
// let buffer = MutableSpan<Int64>(_unsafeStart: p+offset, byteCount: count*8)
|
||||
//
|
||||
// var buffered = 0
|
||||
// for value in 0..<buffer.count {
|
||||
// XCTAssertNotEqual(value, 1)
|
||||
// buffered += 1
|
||||
// }
|
||||
// XCTAssertEqual(buffered, count)
|
||||
// }
|
||||
|
||||
func testIsEmpty() {
|
||||
var array = [0, 1, 2]
|
||||
array.withUnsafeMutableBufferPointer {
|
||||
let span = MutableSpan(_unsafeElements: $0)
|
||||
XCTAssertFalse(span.isEmpty)
|
||||
let e = span.isEmpty
|
||||
XCTAssertFalse(e)
|
||||
}
|
||||
|
||||
let empty = MutableSpan(_unsafeElements: .init(rebasing: $0.prefix(0)))
|
||||
XCTAssertTrue(empty.isEmpty)
|
||||
array = []
|
||||
array.withUnsafeMutableBufferPointer {
|
||||
let span = MutableSpan(_unsafeElements: $0)
|
||||
let e = span.isEmpty
|
||||
XCTAssertTrue(e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,9 +90,10 @@ final class MutableSpanTests: XCTestCase {
|
||||
let count = 4
|
||||
var array = Array(0..<count)
|
||||
array.withUnsafeMutableBufferPointer {
|
||||
let span = MutableSpan(_unsafeElements: $0)
|
||||
let raw = span._unsafeRawSpan
|
||||
XCTAssertEqual(raw.byteCount, count*MemoryLayout<Int>.stride)
|
||||
let (p, c) = ($0.baseAddress!, $0.count)
|
||||
let span = MutableSpan(_unsafeStart: p, count: c)
|
||||
let bytes = span.bytes
|
||||
XCTAssertEqual(bytes.byteCount, count*MemoryLayout<Int>.stride)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,8 +102,9 @@ final class MutableSpanTests: XCTestCase {
|
||||
var a = Array(0..<capacity)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
let view = MutableSpan(_unsafeElements: $0)
|
||||
XCTAssertEqual(view.count, view._indices.count)
|
||||
XCTAssert(view._indices.elementsEqual(0..<view.count))
|
||||
XCTAssertEqual(view.count, view.indices.count)
|
||||
let equal = view.indices.elementsEqual(0..<view.count)
|
||||
XCTAssert(equal)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,10 +124,14 @@ final class MutableSpanTests: XCTestCase {
|
||||
XCTAssertEqual(v1._elementsEqual(v1), true)
|
||||
XCTAssertEqual(Span(_unsafeMutableSpan: v1)._extracting(first: 3)._elementsEqual(Span(_unsafeMutableSpan: v1)._extracting(last: 3)), false)
|
||||
|
||||
var b = v1.withUnsafeMutableBufferPointer { Array($0) }
|
||||
v1[0] = 0
|
||||
|
||||
let s = v1.span
|
||||
var b = s.withUnsafeBufferPointer { Array($0) }
|
||||
b.withUnsafeMutableBufferPointer {
|
||||
let v2 = MutableSpan(_unsafeElements: $0)
|
||||
XCTAssertEqual(v1._elementsEqual(v2), true)
|
||||
let equal = v1._elementsEqual(v2)
|
||||
XCTAssertEqual(equal, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -178,11 +142,14 @@ final class MutableSpanTests: XCTestCase {
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
let span = MutableSpan(_unsafeElements: $0)
|
||||
let a = $0.indices.randomElement()!
|
||||
let emptySpan = MutableSpan(_unsafeElements: .init(rebasing: $0[a..<a]))
|
||||
|
||||
let emptyBuffer = UnsafeMutableBufferPointer(rebasing: $0[a..<a])
|
||||
let emptySpan = MutableSpan(_unsafeElements: emptyBuffer)
|
||||
|
||||
XCTAssertEqual(span._elementsEqual($0), true)
|
||||
XCTAssertEqual(emptySpan._elementsEqual([]), true)
|
||||
XCTAssertEqual(span._elementsEqual($0.dropLast()), false)
|
||||
let e = span._elementsEqual($0.dropLast())
|
||||
XCTAssertEqual(e, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,11 +159,13 @@ final class MutableSpanTests: XCTestCase {
|
||||
let s = AnySequence(a)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
let span = MutableSpan(_unsafeElements: $0)
|
||||
let subSpan = MutableSpan(_unsafeElements: .init(rebasing: $0.dropLast()))
|
||||
let buffer = UnsafeMutableBufferPointer(rebasing: $0.dropLast())
|
||||
let subSpan = MutableSpan(_unsafeElements: buffer)
|
||||
|
||||
XCTAssertEqual(span._elementsEqual(s), true)
|
||||
XCTAssertEqual(subSpan._elementsEqual(s), false)
|
||||
XCTAssertEqual(span._elementsEqual(s.dropFirst()), false)
|
||||
let e = span._elementsEqual(s.dropFirst())
|
||||
XCTAssertEqual(e, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,18 +188,18 @@ final class MutableSpanTests: XCTestCase {
|
||||
XCTAssertEqual(v[0], first)
|
||||
|
||||
v[0].append("!")
|
||||
XCTAssertEqual(v[0], first?.appending("!"))
|
||||
XCTAssertEqual(v[0], first.map({$0+"!"}))
|
||||
}
|
||||
}
|
||||
|
||||
public func testWithUnsafeBufferPointer() {
|
||||
let capacity: UInt8 = 64
|
||||
var a = Array(0..<capacity)
|
||||
let i = Int.random(in: a.indices)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
let view = MutableSpan(_unsafeElements: $0)
|
||||
view.withUnsafeBufferPointer {
|
||||
XCTAssertEqual($0[i], $0[i])
|
||||
view.withUnsafeBufferPointer { b in
|
||||
let i = Int(capacity/2)
|
||||
XCTAssertEqual(b[i], b[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -255,12 +224,10 @@ final class MutableSpanTests: XCTestCase {
|
||||
var view = MutableSpan(_unsafeElements: $0)
|
||||
view.withUnsafeMutableBufferPointer {
|
||||
$0[i] += 1
|
||||
// $0 = .allocate(capacity: 64)
|
||||
}
|
||||
|
||||
var emptySpan = MutableSpan<UInt8>(
|
||||
_unsafeElements: .init(start: $0.baseAddress, count: 0)
|
||||
)
|
||||
let empty0 = UnsafeMutableBufferPointer(start: $0.baseAddress, count: 0)
|
||||
var emptySpan = MutableSpan(_unsafeElements: empty0)
|
||||
emptySpan.withUnsafeMutableBufferPointer {
|
||||
XCTAssertEqual($0.count, 0)
|
||||
XCTAssertNil($0.baseAddress)
|
||||
@@ -279,9 +246,8 @@ final class MutableSpanTests: XCTestCase {
|
||||
$0.storeBytes(of: UInt8(i+1), toByteOffset: i, as: UInt8.self)
|
||||
}
|
||||
|
||||
var emptySpan = MutableSpan<UInt8>(
|
||||
_unsafeElements: .init(start: $0.baseAddress, count: 0)
|
||||
)
|
||||
let empty0 = UnsafeMutableBufferPointer(start: $0.baseAddress, count: 0)
|
||||
var emptySpan = MutableSpan(_unsafeElements: empty0)
|
||||
emptySpan.withUnsafeMutableBytes {
|
||||
XCTAssertEqual($0.count, 0)
|
||||
XCTAssertNil($0.baseAddress)
|
||||
@@ -315,7 +281,8 @@ final class MutableSpanTests: XCTestCase {
|
||||
var a = Array(repeating: Int.max, count: capacity)
|
||||
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
var span = MutableSpan<Int>(_unsafeElements: .init(start: nil, count: 0))
|
||||
let empty = UnsafeMutableBufferPointer<Int>(start: nil, count: 0)
|
||||
var span = MutableSpan(_unsafeElements: empty)
|
||||
var (iterator, updated) = span.update(from: 0..<0)
|
||||
XCTAssertNil(iterator.next())
|
||||
XCTAssertEqual(updated, 0)
|
||||
@@ -337,7 +304,8 @@ final class MutableSpanTests: XCTestCase {
|
||||
var a = Array(repeating: ID(id: .max), count: capacity)
|
||||
XCTAssertEqual(a.allSatisfy({ $0.id == .max }), true)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
var span = MutableSpan(_unsafeElements: $0.prefix(0))
|
||||
let emptyPrefix = $0.prefix(0)
|
||||
var span = MutableSpan(_unsafeElements: emptyPrefix)
|
||||
var (iterator, updated) = span.update(from: [])
|
||||
XCTAssertNil(iterator.next())
|
||||
XCTAssertEqual(updated, 0)
|
||||
@@ -359,7 +327,8 @@ final class MutableSpanTests: XCTestCase {
|
||||
var a = Array(repeating: Int.max, count: capacity)
|
||||
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
var span = MutableSpan(_unsafeElements: $0.prefix(0))
|
||||
let emptyPrefix = $0.prefix(0)
|
||||
var span = MutableSpan(_unsafeElements: emptyPrefix)
|
||||
var updated = span.update(fromContentsOf: [])
|
||||
XCTAssertEqual(updated, 0)
|
||||
|
||||
@@ -379,7 +348,8 @@ final class MutableSpanTests: XCTestCase {
|
||||
var a = Array(repeating: ID(id: .max), count: capacity)
|
||||
XCTAssertEqual(a.allSatisfy({ $0.id == .max }), true)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
var span = MutableSpan(_unsafeElements: $0.prefix(0))
|
||||
let emptyPrefix = $0.prefix(0)
|
||||
var span = MutableSpan(_unsafeElements: emptyPrefix)
|
||||
var updated = span.update(fromContentsOf: [])
|
||||
XCTAssertEqual(updated, 0)
|
||||
|
||||
@@ -399,14 +369,18 @@ final class MutableSpanTests: XCTestCase {
|
||||
var a = Array(repeating: Int.max, count: capacity)
|
||||
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
var span = MutableSpan(_unsafeElements: $0.prefix(0))
|
||||
var update = span.update(fromContentsOf: [])
|
||||
let emptyPrefix = $0.prefix(0)
|
||||
var span = MutableSpan(_unsafeElements: emptyPrefix)
|
||||
let update = span.update(fromContentsOf: [])
|
||||
XCTAssertEqual(update, 0)
|
||||
|
||||
span = MutableSpan(_unsafeElements: $0)
|
||||
let array = Array(0..<capacity)
|
||||
update = span.update(fromContentsOf: array)
|
||||
XCTAssertEqual(update, capacity)
|
||||
var array = Array(0..<capacity)
|
||||
array.withUnsafeMutableBufferPointer {
|
||||
let source = MutableSpan(_unsafeElements: $0)
|
||||
let update = span.update(fromContentsOf: source)
|
||||
XCTAssertEqual(update, capacity)
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(a.elementsEqual(0..<capacity), true)
|
||||
}
|
||||
@@ -416,36 +390,24 @@ final class MutableSpanTests: XCTestCase {
|
||||
var a = Array(repeating: ID(id: .max), count: capacity)
|
||||
XCTAssertEqual(a.allSatisfy({ $0.id == .max }), true)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
var span = MutableSpan(_unsafeElements: $0.prefix(0))
|
||||
var updated = span.update(fromContentsOf: UnsafeBufferPointer(start: nil, count: 0))
|
||||
let emptyPrefix = $0.prefix(0)
|
||||
var span = MutableSpan(_unsafeElements: emptyPrefix)
|
||||
let updated = span.update(
|
||||
fromContentsOf: UnsafeBufferPointer(start: nil, count: 0)
|
||||
)
|
||||
XCTAssertEqual(updated, 0)
|
||||
|
||||
span = MutableSpan(_unsafeElements: $0)
|
||||
let elements = (0..<capacity).map(ID.init(id:))
|
||||
updated = span.update(fromContentsOf: elements)
|
||||
XCTAssertEqual(updated, capacity)
|
||||
var elements = (0..<capacity).map(ID.init(id:))
|
||||
elements.withUnsafeMutableBufferPointer {
|
||||
let source = MutableSpan(_unsafeElements: $0)
|
||||
let updated = span.update(fromContentsOf: source)
|
||||
XCTAssertEqual(updated, capacity)
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(a.map(\.id).elementsEqual(0..<capacity), true)
|
||||
}
|
||||
|
||||
public func testUpdateFromRawContiguousMemory() {
|
||||
let capacity = 8
|
||||
var a = Array(repeating: Int32.max, count: capacity)
|
||||
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
var span = MutableSpan(_unsafeElements: $0.prefix(0))
|
||||
let empty = UnsafeRawBufferPointer(start: $0.baseAddress, count: 0)
|
||||
var updated = span.update(fromContentsOf: empty)
|
||||
XCTAssertEqual(updated, 0)
|
||||
|
||||
span = MutableSpan(_unsafeElements: $0)
|
||||
let b = Array(UInt32(0)..<UInt32(capacity))
|
||||
updated = b.withUnsafeBytes { span.update(fromContentsOf: $0) }
|
||||
XCTAssertEqual(updated, capacity)
|
||||
}
|
||||
XCTAssertEqual(a.elementsEqual(0..<Int32(capacity)), true)
|
||||
}
|
||||
|
||||
public func testMoveUpdate() {
|
||||
let capacity = 8
|
||||
var a = Array(repeating: ID(id: .max), count: capacity)
|
||||
@@ -488,4 +450,144 @@ final class MutableSpanTests: XCTestCase {
|
||||
b.prefix(capacity).deinitialize()
|
||||
b.deallocate()
|
||||
}
|
||||
|
||||
public func testSpanProperty() {
|
||||
let count = 8
|
||||
let b = UnsafeMutableBufferPointer<Int>.allocate(capacity: count)
|
||||
_ = b.initialize(fromContentsOf: 0..<count)
|
||||
defer { b.deallocate() }
|
||||
let e = UnsafeBufferPointer<Int>(start: nil, count: 0)
|
||||
defer { _ = e }
|
||||
|
||||
var m = MutableSpan<Int>(_unsafeElements: b)
|
||||
m[0] = 100
|
||||
XCTAssertEqual(m.count, count)
|
||||
XCTAssertEqual(m[0], 100)
|
||||
|
||||
var s = m.span
|
||||
XCTAssertEqual(s.count, m.count)
|
||||
XCTAssertEqual(s[0], m[0])
|
||||
|
||||
// we're done using `s` before it gets reassigned
|
||||
m.update(repeating: 7)
|
||||
|
||||
s = m.span
|
||||
|
||||
// m[0] = -1 // exclusivity violation
|
||||
|
||||
XCTAssertEqual(s.count, m.count)
|
||||
XCTAssertEqual(s[0], m[0])
|
||||
}
|
||||
|
||||
public func testSwapAt() {
|
||||
let count = 8
|
||||
var array = Array(0..<count)
|
||||
array.withUnsafeMutableBufferPointer {
|
||||
var m = MutableSpan(_unsafeElements: $0)
|
||||
for i in 0..<(count/2) {
|
||||
m.swapAt(i, count - i - 1)
|
||||
}
|
||||
}
|
||||
|
||||
XCTAssertEqual(array, (0..<count).reversed())
|
||||
}
|
||||
|
||||
func testExtracting() {
|
||||
let capacity = 4
|
||||
var b = (0..<capacity).map(Int8.init)
|
||||
b.withUnsafeMutableBufferPointer {
|
||||
var span = MutableSpan(_unsafeElements: $0)
|
||||
|
||||
var sub = span._extracting(0..<2)
|
||||
XCTAssertEqual(sub.count, 2)
|
||||
XCTAssertEqual(sub[0], 0)
|
||||
|
||||
sub = span._extracting(..<2)
|
||||
XCTAssertEqual(sub.count, 2)
|
||||
XCTAssertEqual(sub[0], 0)
|
||||
|
||||
sub = span._extracting(...)
|
||||
XCTAssertEqual(sub.count, 4)
|
||||
XCTAssertEqual(sub[0], 0)
|
||||
|
||||
sub = span._extracting(2...)
|
||||
XCTAssertEqual(sub.count, 2)
|
||||
XCTAssertEqual(sub[0], 2)
|
||||
}
|
||||
}
|
||||
|
||||
func testExtractingUnchecked() {
|
||||
let capacity = 32
|
||||
var b = (0..<capacity).map(UInt8.init)
|
||||
b.withUnsafeMutableBufferPointer {
|
||||
var span = MutableSpan(_unsafeElements: $0.prefix(8))
|
||||
let beyond = span._extracting(unchecked: 16...23)
|
||||
XCTAssertEqual(beyond.count, 8)
|
||||
let fromBeyond = beyond[0]
|
||||
XCTAssertEqual(fromBeyond, 16)
|
||||
}
|
||||
}
|
||||
|
||||
func testPrefix() {
|
||||
let capacity = 4
|
||||
var a = Array(0..<UInt8(capacity))
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
var prefix: MutableSpan<UInt8>
|
||||
var span = MutableSpan(_unsafeElements: $0)
|
||||
XCTAssertEqual(span.count, capacity)
|
||||
|
||||
prefix = span._extracting(first: 1)
|
||||
XCTAssertEqual(prefix[0], 0)
|
||||
|
||||
prefix = span._extracting(first: capacity)
|
||||
XCTAssertEqual(prefix[capacity-1], UInt8(capacity-1))
|
||||
|
||||
prefix = span._extracting(droppingLast: capacity)
|
||||
XCTAssertEqual(prefix.isEmpty, true)
|
||||
|
||||
prefix = span._extracting(droppingLast: 1)
|
||||
XCTAssertEqual(prefix[capacity-2], UInt8(capacity-2))
|
||||
}
|
||||
|
||||
do {
|
||||
let b = UnsafeMutableBufferPointer<Int>(start: nil, count: 0)
|
||||
var span = MutableSpan(_unsafeElements: b)
|
||||
XCTAssertEqual(span.count, b.count)
|
||||
XCTAssertEqual(span._extracting(first: 1).count, b.count)
|
||||
XCTAssertEqual(span._extracting(droppingLast: 1).count, b.count)
|
||||
}
|
||||
}
|
||||
|
||||
func testSuffix() {
|
||||
let capacity = 4
|
||||
var a = Array(0..<UInt8(capacity))
|
||||
a.withUnsafeMutableBufferPointer {
|
||||
var suffix: MutableSpan<UInt8>
|
||||
var span = MutableSpan(_unsafeElements: $0)
|
||||
XCTAssertEqual(span.count, capacity)
|
||||
|
||||
suffix = span._extracting(last: capacity)
|
||||
XCTAssertEqual(suffix[0], 0)
|
||||
|
||||
suffix = span._extracting(last: capacity-1)
|
||||
XCTAssertEqual(suffix[0], 1)
|
||||
|
||||
suffix = span._extracting(last: 1)
|
||||
XCTAssertEqual(suffix[0], UInt8(capacity-1))
|
||||
|
||||
suffix = span._extracting(droppingFirst: capacity)
|
||||
XCTAssertTrue(suffix.isEmpty)
|
||||
|
||||
suffix = span._extracting(droppingFirst: 1)
|
||||
XCTAssertEqual(suffix[0], 1)
|
||||
}
|
||||
|
||||
do {
|
||||
let b = UnsafeMutableBufferPointer<ObjectIdentifier>(start: nil, count: 0)
|
||||
var span = MutableSpan(_unsafeElements: b)
|
||||
XCTAssertEqual(span.count, b.count)
|
||||
XCTAssertEqual(span._extracting(last: 1).count, b.count)
|
||||
XCTAssertEqual(span._extracting(droppingFirst: 1).count, b.count)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2024 Apple Inc. and the Swift project authors
|
||||
// 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
|
||||
@@ -11,8 +11,9 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import Future
|
||||
import Span
|
||||
|
||||
@available(macOS 9999, *)
|
||||
struct Allocation<T>: ~Copyable {
|
||||
let allocation: UnsafeMutablePointer<T>
|
||||
let capacity: Int
|
||||
@@ -40,7 +41,7 @@ struct Allocation<T>: ~Copyable {
|
||||
count = initialized.count
|
||||
}
|
||||
catch {
|
||||
outputBuffer.deinitialize()
|
||||
outputBuffer.removeAll()
|
||||
let empty = outputBuffer.relinquishBorrowedMemory()
|
||||
assert(empty.baseAddress == allocation)
|
||||
assert(empty.count == 0)
|
||||
@@ -64,9 +65,10 @@ struct Allocation<T>: ~Copyable {
|
||||
|
||||
enum MyTestError: Error { case error }
|
||||
|
||||
@available(macOS 9999, *)
|
||||
final class OutputSpanTests: XCTestCase {
|
||||
|
||||
func testOutputBufferInitialization() {
|
||||
func testOutputBufferCreation() {
|
||||
let c = 48
|
||||
let allocation = UnsafeMutablePointer<UInt8>.allocate(capacity: c)
|
||||
defer { allocation.deallocate() }
|
||||
@@ -77,14 +79,25 @@ final class OutputSpanTests: XCTestCase {
|
||||
XCTAssertEqual(initialized.count, 0)
|
||||
}
|
||||
|
||||
func testOutputBufferDeinitWithoutRelinquishingMemory() {
|
||||
let c = 48
|
||||
let allocation = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: c)
|
||||
defer { allocation.deallocate() }
|
||||
|
||||
var ob = OutputSpan(_initializing: Slice(base: allocation, bounds: 0..<c))
|
||||
ob.append(repeating: 65, count: 12)
|
||||
XCTAssertEqual(ob.count, 12)
|
||||
_ = ob
|
||||
}
|
||||
|
||||
func testInitializeBufferByAppendingElements() {
|
||||
var a = Allocation(of: 48, Int.self)
|
||||
let c = 10
|
||||
a.initialize {
|
||||
for i in 0...c {
|
||||
$0.appendElement(i)
|
||||
$0.append(i)
|
||||
}
|
||||
let oops = $0.deinitializeLastElement()
|
||||
let oops = $0.removeLast()
|
||||
XCTAssertEqual(oops, c)
|
||||
}
|
||||
a.withSpan {
|
||||
@@ -93,12 +106,27 @@ final class OutputSpanTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testInitializeBitwiseCopyableBuffer() {
|
||||
let c = 48
|
||||
let allocation: UnsafeMutableRawBufferPointer
|
||||
allocation = .allocate(byteCount: c, alignment: 8)
|
||||
defer { allocation.deallocate() }
|
||||
|
||||
var ob = OutputSpan<Int16>(_initializing: allocation[8...])
|
||||
let r = Int16.max>>2
|
||||
ob.append(r)
|
||||
_ = ob.relinquishBorrowedBytes()
|
||||
|
||||
let o = allocation.load(fromByteOffset: 8, as: Int16.self)
|
||||
XCTAssertEqual(o, r)
|
||||
}
|
||||
|
||||
func testInitializeBufferByAppendingRepeatedElements() {
|
||||
var a = Allocation(of: 48, Int.self)
|
||||
let c = 10
|
||||
a.initialize {
|
||||
$0.append(repeating: c, count: c)
|
||||
let oops = $0.deinitializeLastElement()
|
||||
let oops = $0.removeLast()
|
||||
XCTAssertEqual(oops, c)
|
||||
XCTAssertEqual($0.count, c-1)
|
||||
}
|
||||
@@ -126,7 +154,7 @@ final class OutputSpanTests: XCTestCase {
|
||||
a.initialize {
|
||||
$0.append(fromContentsOf: 0..<c)
|
||||
|
||||
let span = $0.initializedPrefix
|
||||
let span = $0.span
|
||||
XCTAssertEqual(span.count, c)
|
||||
XCTAssert(span._elementsEqual(0..<c))
|
||||
}
|
||||
@@ -138,7 +166,7 @@ final class OutputSpanTests: XCTestCase {
|
||||
a.initialize {
|
||||
$0.append(fromContentsOf: Array(0..<c))
|
||||
|
||||
let prefix = $0.initializedPrefix
|
||||
let prefix = $0.span
|
||||
XCTAssertEqual(prefix.count, c)
|
||||
XCTAssert(prefix._elementsEqual(0..<c))
|
||||
}
|
||||
@@ -152,16 +180,12 @@ final class OutputSpanTests: XCTestCase {
|
||||
var a = Allocation(of: 48, Int.self)
|
||||
let c = 24
|
||||
a.initialize {
|
||||
let array = Array(0..<c)
|
||||
#if false
|
||||
array.withUnsafeBufferPointer {
|
||||
// let storage = Span(_unsafeElements: $0)
|
||||
let storage = Span<Int>(_unsafeElements: .init(start: nil, count: 0))
|
||||
$0.append(fromContentsOf: storage)
|
||||
os in
|
||||
var array = Array(0..<c)
|
||||
array.withUnsafeMutableBufferPointer {
|
||||
let span = MutableSpan(_unsafeElements: $0)
|
||||
os.append(fromContentsOf: span)
|
||||
}
|
||||
#else
|
||||
$0.append(fromContentsOf: array)
|
||||
#endif
|
||||
}
|
||||
a.withSpan { span in
|
||||
XCTAssertEqual(span.count, c)
|
||||
@@ -207,8 +231,8 @@ final class OutputSpanTests: XCTestCase {
|
||||
var a = Allocation(of: 48, Int.self)
|
||||
do {
|
||||
try a.initialize {
|
||||
$0.appendElement(0)
|
||||
$0.appendElement(1)
|
||||
$0.append(0)
|
||||
$0.append(1)
|
||||
XCTAssertTrue($0.count > 0)
|
||||
throw MyTestError.error
|
||||
}
|
||||
@@ -224,23 +248,19 @@ final class OutputSpanTests: XCTestCase {
|
||||
|
||||
var span = OutputSpan(_initializing: b)
|
||||
XCTAssertEqual(span.count, 0)
|
||||
span.append(fromContentsOf: 0..<10)
|
||||
XCTAssertEqual(span.count, 10)
|
||||
span.append(fromContentsOf: 1...9)
|
||||
XCTAssertEqual(span.count, 9)
|
||||
|
||||
span.withMutableSpan {
|
||||
#if false
|
||||
let b = UnsafeMutableBufferPointer<Int>.allocate(capacity: 8)
|
||||
b.initialize(repeating: .max)
|
||||
$0 = MutableSpan(_unsafeElements: b)
|
||||
#else
|
||||
for i in 0..<$0.count {
|
||||
$0[i] *= 2
|
||||
}
|
||||
#endif
|
||||
var mutable = span.mutableSpan
|
||||
// span.append(20) // exclusivity violation
|
||||
for i in 0..<mutable.count {
|
||||
mutable[i] *= 2
|
||||
}
|
||||
|
||||
span.append(20)
|
||||
|
||||
let r = span.relinquishBorrowedMemory()
|
||||
print(Array(r))
|
||||
XCTAssert(r.elementsEqual((0..<10).map({2*(1+$0)})))
|
||||
r.deinitialize()
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2024 Apple Inc. and the Swift project authors
|
||||
// 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
|
||||
@@ -11,34 +11,28 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
@testable import Future
|
||||
@testable import Span
|
||||
|
||||
@available(macOS 9999, *)
|
||||
final class RawSpanTests: XCTestCase {
|
||||
|
||||
func testOptionalStorage() {
|
||||
// XCTAssertEqual(
|
||||
// MemoryLayout<RawSpan>.size, MemoryLayout<RawSpan?>.size
|
||||
// )
|
||||
// XCTAssertEqual(
|
||||
// MemoryLayout<RawSpan>.stride, MemoryLayout<RawSpan?>.stride
|
||||
// )
|
||||
// XCTAssertEqual(
|
||||
// MemoryLayout<RawSpan>.alignment, MemoryLayout<RawSpan?>.alignment
|
||||
// )
|
||||
}
|
||||
|
||||
func testInitWithSpanOfIntegers() {
|
||||
let capacity = 4
|
||||
let a = Array(0..<capacity)
|
||||
let span = RawSpan(_elements: a.storage)
|
||||
XCTAssertEqual(span.byteCount, capacity*MemoryLayout<Int>.stride)
|
||||
XCTAssertFalse(span.isEmpty)
|
||||
Array(0..<capacity).withUnsafeBufferPointer {
|
||||
let intSpan = Span(_unsafeElements: $0)
|
||||
let span = RawSpan(_elements: intSpan)
|
||||
XCTAssertEqual(span.byteCount, capacity*MemoryLayout<Int>.stride)
|
||||
XCTAssertFalse(span.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
func testInitWithEmptySpanOfIntegers() {
|
||||
let a: [Int] = []
|
||||
let span = RawSpan(_elements: a.storage)
|
||||
XCTAssertTrue(span.isEmpty)
|
||||
a.withUnsafeBufferPointer {
|
||||
let intSpan = Span(_unsafeElements: $0)
|
||||
let span = RawSpan(_elements: intSpan)
|
||||
XCTAssertTrue(span.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
func testInitWithRawBytes() {
|
||||
@@ -110,7 +104,7 @@ final class RawSpanTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testSubscript() {
|
||||
func testExtracting() {
|
||||
let capacity = 4
|
||||
let b = (0..<capacity).map(Int8.init)
|
||||
b.withUnsafeBytes {
|
||||
@@ -118,7 +112,7 @@ final class RawSpanTests: XCTestCase {
|
||||
let sub1 = span._extracting(0..<2)
|
||||
let sub2 = span._extracting(..<2)
|
||||
let sub3 = span._extracting(...)
|
||||
let sub4 = span._extracting(unchecked: 2...)
|
||||
let sub4 = span._extracting(2...)
|
||||
XCTAssertTrue(
|
||||
sub1._unsafeView(as: UInt8.self)._elementsEqual(sub2._unsafeView(as: UInt8.self))
|
||||
)
|
||||
@@ -131,50 +125,38 @@ final class RawSpanTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testUncheckedSubscript() {
|
||||
func testExtractingUnchecked() {
|
||||
let capacity = 32
|
||||
let b = (0..<capacity).map(UInt8.init)
|
||||
b.withUnsafeBytes {
|
||||
let span = RawSpan(_unsafeBytes: $0)
|
||||
let prefix = span._extracting(0..<8)
|
||||
let beyond = prefix._extracting(unchecked: 16..<24)
|
||||
let beyond = prefix._extracting(unchecked: 16...23)
|
||||
XCTAssertEqual(beyond.byteCount, 8)
|
||||
XCTAssertEqual(beyond.unsafeLoad(as: UInt8.self), 16)
|
||||
}
|
||||
}
|
||||
|
||||
func testUnsafeBytes() {
|
||||
func testWithUnsafeBytes() {
|
||||
let capacity = 4
|
||||
let array = Array(0..<capacity)
|
||||
let span = RawSpan(_elements: array.storage)
|
||||
array.withUnsafeBytes { b1 in
|
||||
span.withUnsafeBytes { b2 in
|
||||
XCTAssertTrue(b1.elementsEqual(b2))
|
||||
array.withUnsafeBufferPointer {
|
||||
let intSpan = Span(_unsafeElements: $0)
|
||||
let span = RawSpan(_elements: intSpan)
|
||||
array.withUnsafeBytes { b1 in
|
||||
span.withUnsafeBytes { b2 in
|
||||
XCTAssertTrue(b1.elementsEqual(b2))
|
||||
}
|
||||
}
|
||||
|
||||
let emptyBuffer = UnsafeBufferPointer(rebasing: $0[0..<0])
|
||||
XCTAssertEqual(emptyBuffer.baseAddress, $0.baseAddress)
|
||||
|
||||
let emptySpan = RawSpan(_unsafeElements: emptyBuffer)
|
||||
emptySpan.withUnsafeBytes {
|
||||
XCTAssertNil($0.baseAddress)
|
||||
}
|
||||
}
|
||||
|
||||
// Should we be able to derive a non-escapable value from a Span via unsafe pointers?
|
||||
// let copy: RawSpan = span.withUnsafeBytes { RawSpan(_unsafeBytes: $0) }
|
||||
// _ = copy
|
||||
}
|
||||
|
||||
func testStrangeBorrow() {
|
||||
let array: [String] = ["0", "1", "2", "3"]
|
||||
_ = array
|
||||
|
||||
// let rs = RawSpan(array.storage) // Initializer 'init(_:)' requires that 'String' conform to 'BitwiseCopyable'
|
||||
|
||||
// let rs1 = array.storage.withUnsafeBufferPointer {
|
||||
// RawSpan(unsafeBytes: UnsafeRawBufferPointer($0))
|
||||
// } // Lifetime-dependent value escapes its scope
|
||||
// _ = rs1
|
||||
|
||||
// let rs2 = array.storage.withUnsafeBufferPointer {
|
||||
// UnsafeRawBufferPointer($0).withMemoryRebound(to: UInt8.self) { // requires that `Span` conform to `Escapable`
|
||||
// return Span(unsafeBufferPointer: $0)
|
||||
// }
|
||||
// }
|
||||
// _ = rs2
|
||||
}
|
||||
|
||||
func testPrefix() {
|
||||
@@ -241,9 +223,8 @@ final class RawSpanTests: XCTestCase {
|
||||
let subSpan1 = span._extracting(first: 6)
|
||||
let subSpan2 = span._extracting(last: 6)
|
||||
let emptySpan = span._extracting(first: 0)
|
||||
let nilSpan = RawSpan(
|
||||
_unsafeBytes: UnsafeRawBufferPointer(start: nil, count: 0)
|
||||
)
|
||||
let nilBuffer = UnsafeRawBufferPointer(start: nil, count: 0)
|
||||
let nilSpan = RawSpan(_unsafeBytes: nilBuffer)
|
||||
|
||||
var bounds: Range<Int>?
|
||||
bounds = span.byteOffsets(of: subSpan1)
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2024 Apple Inc. and the Swift project authors
|
||||
// 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
|
||||
@@ -11,22 +11,11 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
@testable import Future
|
||||
import Span
|
||||
|
||||
@available(macOS 9999, *)
|
||||
final class SpanTests: XCTestCase {
|
||||
|
||||
func testOptionalStorage() {
|
||||
// XCTAssertEqual(
|
||||
// MemoryLayout<Span<UInt8>>.size, MemoryLayout<Span<UInt8>?>.size
|
||||
// )
|
||||
// XCTAssertEqual(
|
||||
// MemoryLayout<Span<UInt8>>.stride, MemoryLayout<Span<UInt8>?>.stride
|
||||
// )
|
||||
// XCTAssertEqual(
|
||||
// MemoryLayout<Span<UInt8>>.alignment, MemoryLayout<Span<UInt8>?>.alignment
|
||||
// )
|
||||
}
|
||||
|
||||
func testInitWithOrdinaryElement() {
|
||||
let capacity = 4
|
||||
var s = (0..<capacity).map({ "\(#file)+\(#function)--\($0)" })
|
||||
@@ -34,7 +23,8 @@ final class SpanTests: XCTestCase {
|
||||
var span = Span(_unsafeElements: $0)
|
||||
XCTAssertEqual(span.count, capacity)
|
||||
|
||||
span = Span(_unsafeStart: $0.baseAddress!, count: $0.count)
|
||||
let pointer = $0.baseAddress!
|
||||
span = Span(_unsafeStart: pointer, count: $0.count)
|
||||
XCTAssertEqual(span.count, capacity)
|
||||
}
|
||||
|
||||
@@ -55,7 +45,8 @@ final class SpanTests: XCTestCase {
|
||||
var span = Span(_unsafeElements: $0)
|
||||
XCTAssertEqual(span.count, capacity)
|
||||
|
||||
span = Span(_unsafeStart: $0.baseAddress!, count: $0.count)
|
||||
let pointer = $0.baseAddress!
|
||||
span = Span(_unsafeStart: pointer, count: $0.count)
|
||||
XCTAssertEqual(span.count, capacity)
|
||||
}
|
||||
|
||||
@@ -75,22 +66,22 @@ final class SpanTests: XCTestCase {
|
||||
let r = Span<Int8>(_unsafeBytes: $0)
|
||||
XCTAssertEqual(r.count, capacity*MemoryLayout<Int>.stride)
|
||||
|
||||
let p = Span<Int>(
|
||||
_unsafeStart: $0.baseAddress!,
|
||||
byteCount: capacity*MemoryLayout<Int>.stride
|
||||
let p = $0.baseAddress!
|
||||
let span = Span<Int>(
|
||||
_unsafeStart: p, byteCount: capacity*MemoryLayout<Int>.stride
|
||||
)
|
||||
XCTAssertEqual(p.count, capacity)
|
||||
XCTAssertEqual(span.count, capacity)
|
||||
}
|
||||
|
||||
a.withUnsafeMutableBytes {
|
||||
let b = Span<UInt>(_unsafeBytes: $0)
|
||||
XCTAssertEqual(b.count, capacity)
|
||||
|
||||
let p = Span<Int>(
|
||||
_unsafeStart: $0.baseAddress!,
|
||||
byteCount: capacity*MemoryLayout<Int>.stride
|
||||
let p = $0.baseAddress!
|
||||
let span = Span<Int>(
|
||||
_unsafeStart: p, byteCount: capacity*MemoryLayout<Int>.stride
|
||||
)
|
||||
XCTAssertEqual(p.count, capacity)
|
||||
XCTAssertEqual(span.count, capacity)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,9 +92,8 @@ final class SpanTests: XCTestCase {
|
||||
let span = Span(_unsafeElements: $0)
|
||||
XCTAssertFalse(span.isEmpty)
|
||||
|
||||
let empty = Span(
|
||||
_unsafeElements: .init(rebasing: $0.dropFirst(capacity))
|
||||
)
|
||||
let emptyBuffer = UnsafeBufferPointer(rebasing: $0.dropFirst(capacity))
|
||||
let empty = Span(_unsafeElements: emptyBuffer)
|
||||
XCTAssertTrue(empty.isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -182,33 +172,6 @@ final class SpanTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testRangeOfIndicesSubscript() {
|
||||
let capacity = 4
|
||||
let a = (0..<capacity).map(String.init)
|
||||
a.withUnsafeBufferPointer {
|
||||
let span = Span(_unsafeElements: $0)
|
||||
XCTAssertTrue(span._elementsEqual(span._extracting(0..<span.count)))
|
||||
XCTAssertTrue(span._elementsEqual(span._extracting(0...)))
|
||||
XCTAssertTrue(span._elementsEqual(span._extracting(unchecked: ..<span.count)))
|
||||
XCTAssertTrue(span._elementsEqual(span._extracting(...)))
|
||||
|
||||
let emptySpan = span._extracting(0..<0)
|
||||
_ = emptySpan._extracting(0..<0)
|
||||
}
|
||||
}
|
||||
|
||||
func testRangeOfIndicesSubscriptBitwiseCopyable() {
|
||||
let capacity = 4
|
||||
let a = Array(0..<capacity)
|
||||
a.withUnsafeBufferPointer {
|
||||
let v = Span(_unsafeElements: $0)
|
||||
XCTAssertTrue(v._elementsEqual(v._extracting(0..<v.count)))
|
||||
XCTAssertTrue(v._elementsEqual(v._extracting(0...)))
|
||||
XCTAssertTrue(v._elementsEqual(v._extracting(unchecked: ..<v.count)))
|
||||
XCTAssertTrue(v._elementsEqual(v._extracting(...)))
|
||||
}
|
||||
}
|
||||
|
||||
func testElementSubscript() {
|
||||
let capacity = 4
|
||||
let a = (0..<capacity).map(String.init)
|
||||
@@ -227,28 +190,42 @@ final class SpanTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testRangeOfOffsetsSubscript() {
|
||||
func testRangeOfIndicesSubscriptBitwiseCopyable() {
|
||||
let capacity = 4
|
||||
let a = (0..<capacity).map(String.init)
|
||||
let a = Array(0..<capacity)
|
||||
a.withUnsafeBufferPointer {
|
||||
let span = Span(_unsafeElements: $0)
|
||||
XCTAssertTrue(span._elementsEqual(span._extracting(0..<capacity)))
|
||||
XCTAssertTrue(span._elementsEqual(span._extracting(0...)))
|
||||
XCTAssertTrue(span._elementsEqual(span._extracting(unchecked: ..<capacity)))
|
||||
let v = Span(_unsafeElements: $0)
|
||||
XCTAssertTrue(v._elementsEqual(v._extracting(0..<v.count)))
|
||||
XCTAssertTrue(v._elementsEqual(v._extracting(0...)))
|
||||
XCTAssertTrue(v._elementsEqual(v._extracting(..<v.count)))
|
||||
XCTAssertTrue(v._elementsEqual(v._extracting(...)))
|
||||
}
|
||||
}
|
||||
|
||||
func testFirstAndLast() {
|
||||
let r = Int.random(in: 0..<1000)
|
||||
let a = [r]
|
||||
a.withUnsafeBufferPointer {
|
||||
func testExtracting() {
|
||||
let capacity = 4
|
||||
let b = (0..<capacity).map(String.init)
|
||||
b.withUnsafeBufferPointer {
|
||||
let span = Span(_unsafeElements: $0)
|
||||
XCTAssertEqual(span.first, r)
|
||||
XCTAssertEqual(span.last, r)
|
||||
let sub1 = span._extracting(0..<2)
|
||||
let sub2 = span._extracting(..<2)
|
||||
let sub3 = span._extracting(...)
|
||||
let sub4 = span._extracting(2...)
|
||||
XCTAssertTrue(sub1._elementsEqual(sub2))
|
||||
XCTAssertTrue(sub3._elementsEqual(span))
|
||||
XCTAssertFalse(sub4._elementsEqual(sub3))
|
||||
}
|
||||
}
|
||||
|
||||
let emptySpan = span._extracting(0..<0)
|
||||
XCTAssertEqual(emptySpan.first, nil)
|
||||
XCTAssertEqual(emptySpan.last, nil)
|
||||
func testExtractingUnchecked() {
|
||||
let capacity = 32
|
||||
let b = (0..<capacity).map(String.init)
|
||||
b.withUnsafeBufferPointer {
|
||||
let span = Span(_unsafeElements: $0)
|
||||
let prefix = span._extracting(0..<8)
|
||||
let beyond = prefix._extracting(unchecked: 16...23)
|
||||
XCTAssertEqual(beyond.count, 8)
|
||||
XCTAssertEqual(beyond[0], "16")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,10 +235,10 @@ final class SpanTests: XCTestCase {
|
||||
a.withUnsafeBufferPointer {
|
||||
let span = Span(_unsafeElements: $0)
|
||||
XCTAssertEqual(span.count, capacity)
|
||||
XCTAssertEqual(span._extracting(first: 1).last, 0)
|
||||
XCTAssertEqual(span._extracting(first: capacity).last, capacity-1)
|
||||
XCTAssertEqual(span._extracting(droppingLast: capacity).last, nil)
|
||||
XCTAssertEqual(span._extracting(droppingLast: 1).last, capacity-2)
|
||||
XCTAssertEqual(span._extracting(first: 1)[0], 0)
|
||||
XCTAssertEqual(span._extracting(first: capacity)[capacity-1], capacity-1)
|
||||
XCTAssertEqual(span._extracting(droppingLast: capacity).count, 0)
|
||||
XCTAssertEqual(span._extracting(droppingLast: 1)[capacity-2], capacity-2)
|
||||
}
|
||||
|
||||
do {
|
||||
@@ -279,11 +256,11 @@ final class SpanTests: XCTestCase {
|
||||
a.withUnsafeBufferPointer {
|
||||
let span = Span<Int>(_unsafeElements: $0)
|
||||
XCTAssertEqual(span.count, capacity)
|
||||
XCTAssertEqual(span._extracting(last: capacity).first, 0)
|
||||
XCTAssertEqual(span._extracting(last: capacity-1).first, 1)
|
||||
XCTAssertEqual(span._extracting(last: 1).first, capacity-1)
|
||||
XCTAssertEqual(span._extracting(droppingFirst: capacity).first, nil)
|
||||
XCTAssertEqual(span._extracting(droppingFirst: 1).first, 1)
|
||||
XCTAssertEqual(span._extracting(last: capacity)[0], 0)
|
||||
XCTAssertEqual(span._extracting(last: capacity-1)[0], 1)
|
||||
XCTAssertEqual(span._extracting(last: 1)[0], capacity-1)
|
||||
XCTAssertEqual(span._extracting(droppingFirst: capacity).count, 0)
|
||||
XCTAssertEqual(span._extracting(droppingFirst: 1)[0], 1)
|
||||
}
|
||||
|
||||
do {
|
||||
@@ -292,24 +269,6 @@ final class SpanTests: XCTestCase {
|
||||
XCTAssertEqual(span.count, b.count)
|
||||
XCTAssertEqual(span._extracting(last: 1).count, b.count)
|
||||
XCTAssertEqual(span._extracting(droppingFirst: 1).count, b.count)
|
||||
} }
|
||||
|
||||
public func testWithUnsafeBytes() {
|
||||
let capacity: UInt8 = 64
|
||||
let a = Array(0..<capacity)
|
||||
a.withUnsafeBufferPointer {
|
||||
ub in
|
||||
let span = Span(_unsafeElements: ub)
|
||||
|
||||
span.withUnsafeBytes {
|
||||
let i = Int.random(in: 0..<$0.count)
|
||||
XCTAssertEqual($0.load(fromByteOffset: i, as: UInt8.self), ub[i])
|
||||
}
|
||||
|
||||
span.withUnsafeBufferPointer {
|
||||
let i = Int.random(in: 0..<$0.count)
|
||||
XCTAssertEqual($0[i], ub[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,12 +278,6 @@ final class SpanTests: XCTestCase {
|
||||
a.withUnsafeBufferPointer {
|
||||
ub in
|
||||
let span = Span(_unsafeElements: ub)
|
||||
|
||||
span.withUnsafeBytes {
|
||||
let i = Int.random(in: 0..<$0.count)
|
||||
XCTAssertEqual($0[i], ub[i])
|
||||
}
|
||||
|
||||
span.withUnsafeBufferPointer {
|
||||
let i = Int.random(in: 0..<$0.count)
|
||||
XCTAssertEqual($0[i], ub[i])
|
||||
@@ -332,27 +285,34 @@ final class SpanTests: XCTestCase {
|
||||
|
||||
let emptyBuffer = UnsafeBufferPointer(rebasing: ub[0..<0])
|
||||
XCTAssertEqual(emptyBuffer.baseAddress, ub.baseAddress)
|
||||
|
||||
let emptySpan = Span(_unsafeElements: emptyBuffer)
|
||||
emptySpan.withUnsafeBufferPointer {
|
||||
XCTAssertNil($0.baseAddress)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func testBorrowing1() {
|
||||
let capacity = 8
|
||||
public func testWithUnsafeBytes() {
|
||||
let capacity: UInt8 = 64
|
||||
let a = Array(0..<capacity)
|
||||
var span = a.storage
|
||||
let prefix = span._extracting(0..<2)
|
||||
span = span._extracting(1...)
|
||||
XCTAssertEqual(span.count, capacity-1)
|
||||
XCTAssertEqual(prefix.count, 2)
|
||||
}
|
||||
a.withUnsafeBufferPointer {
|
||||
ub in
|
||||
let span = Span(_unsafeElements: ub)
|
||||
|
||||
public func testBorrowing2() {
|
||||
let capacity = 8
|
||||
let a = Array(0..<capacity)
|
||||
var span = a.storage
|
||||
let prefix = span._extracting(0..<2)
|
||||
span = span._extracting(1...)
|
||||
XCTAssertEqual(span.count, capacity-1)
|
||||
XCTAssertEqual(prefix.count, 2)
|
||||
span.withUnsafeBytes {
|
||||
let i = Int.random(in: $0.indices)
|
||||
XCTAssertEqual($0.load(fromByteOffset: i, as: UInt8.self), ub[i])
|
||||
}
|
||||
|
||||
let emptyBuffer = UnsafeBufferPointer(rebasing: ub[0..<0])
|
||||
XCTAssertEqual(emptyBuffer.baseAddress, ub.baseAddress)
|
||||
|
||||
let emptySpan = Span(_unsafeElements: emptyBuffer)
|
||||
emptySpan.withUnsafeBytes {
|
||||
XCTAssertNil($0.baseAddress)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIdentity() {
|
||||
@@ -390,9 +350,8 @@ final class SpanTests: XCTestCase {
|
||||
._extracting(droppingLast: 2)
|
||||
.unsafeView(as: Int.self)
|
||||
*/
|
||||
let nilSpan = Span<Int>(
|
||||
_unsafeElements: UnsafeBufferPointer(start: nil, count: 0)
|
||||
)
|
||||
let nilBuffer = UnsafeBufferPointer<Int>(start: nil, count: 0)
|
||||
let nilSpan = Span(_unsafeElements: nilBuffer)
|
||||
|
||||
var bounds: Range<Int>?
|
||||
bounds = span.indices(of: subSpan1)
|
||||
@@ -413,27 +372,27 @@ final class SpanTests: XCTestCase {
|
||||
XCTAssertEqual(bounds, 0..<0)
|
||||
}
|
||||
|
||||
func testSpanIterator() {
|
||||
class C {
|
||||
let id: Int
|
||||
init(id: Int) { self.id = id }
|
||||
}
|
||||
|
||||
let b = UnsafeMutableBufferPointer<C>.allocate(capacity: 8)
|
||||
_ = b.initialize(fromContentsOf: (0..<8).map(C.init(id:)))
|
||||
defer {
|
||||
b.deinitialize()
|
||||
b.deallocate()
|
||||
}
|
||||
|
||||
let span = Span(_unsafeElements: b)
|
||||
var iterator = Span.Iterator(from: span)
|
||||
var i = 0
|
||||
while let c = iterator.next() {
|
||||
XCTAssertEqual(i, c.id)
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
// func testSpanIterator() {
|
||||
// class C {
|
||||
// let id: Int
|
||||
// init(id: Int) { self.id = id }
|
||||
// }
|
||||
//
|
||||
// let b = UnsafeMutableBufferPointer<C>.allocate(capacity: 8)
|
||||
// _ = b.initialize(fromContentsOf: (0..<8).map(C.init(id:)))
|
||||
// defer {
|
||||
// b.deinitialize()
|
||||
// b.deallocate()
|
||||
// }
|
||||
//
|
||||
// let span = Span(_unsafeElements: b)
|
||||
// var iterator = Span.Iterator(from: span)
|
||||
// var i = 0
|
||||
// while let c = iterator.next() {
|
||||
// XCTAssertEqual(i, c.id)
|
||||
// i += 1
|
||||
// }
|
||||
// }
|
||||
|
||||
func testTypeErasedSpanOfBitwiseCopyable() {
|
||||
let b = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 8)
|
||||
@@ -447,7 +406,9 @@ final class SpanTests: XCTestCase {
|
||||
}
|
||||
|
||||
// let span = Span<Int32>(_unsafeBytes: b.dropFirst().dropLast(7))
|
||||
let span = Span<Int32>(_unsafeBytes: b.dropFirst(4))
|
||||
|
||||
let suffix = b.dropFirst(4)
|
||||
let span = Span<Int32>(_unsafeBytes: suffix)
|
||||
let first = test(span)
|
||||
XCTAssertEqual(first, 0x07060504)
|
||||
}
|
||||
+6
-5
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// This source file is part of the Swift.org open source project
|
||||
//
|
||||
// Copyright (c) 2024 Apple Inc. and the Swift project authors
|
||||
// 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
|
||||
@@ -12,15 +12,16 @@
|
||||
|
||||
import XCTest
|
||||
import Foundation
|
||||
import Future
|
||||
import Span
|
||||
|
||||
@available(macOS 9999, *)
|
||||
final class StdlibOutputSpanExtensionTests: XCTestCase {
|
||||
|
||||
func testArrayInitializationExample() {
|
||||
var array: [UInt8]
|
||||
array = Array(capacity: 32, initializingWith: { output in
|
||||
for i in 0..<(output.capacity/2) {
|
||||
output.appendElement(UInt8(clamping: i))
|
||||
output.append(UInt8(clamping: i))
|
||||
}
|
||||
})
|
||||
XCTAssertEqual(array.count, 16)
|
||||
@@ -32,7 +33,7 @@ final class StdlibOutputSpanExtensionTests: XCTestCase {
|
||||
var data: Data
|
||||
data = Data(capacity: 32, initializingWith: { output in
|
||||
for i in 0..<(output.capacity/2) {
|
||||
output.appendElement(UInt8(clamping: i))
|
||||
output.append(UInt8(clamping: i))
|
||||
}
|
||||
})
|
||||
XCTAssertEqual(data.count, 16)
|
||||
@@ -44,7 +45,7 @@ final class StdlibOutputSpanExtensionTests: XCTestCase {
|
||||
let c = UInt8(ascii: "A")
|
||||
string = String(utf8Capacity: 32, initializingWith: { output in
|
||||
for i in 0..<(output.capacity/2) {
|
||||
output.appendElement(c + UInt8(clamping: i))
|
||||
output.append(c + UInt8(clamping: i))
|
||||
}
|
||||
})
|
||||
XCTAssertEqual(string.utf8.count, 16)
|
||||
@@ -15,7 +15,7 @@ import XCTest
|
||||
public func expectFailure(
|
||||
_ message: @autoclosure () -> String = "",
|
||||
trapping: Bool = false,
|
||||
file: StaticString = #file,
|
||||
file: StaticString = (#file),
|
||||
line: UInt = #line
|
||||
) {
|
||||
let message = message()
|
||||
|
||||
@@ -208,7 +208,7 @@ extension TestContext {
|
||||
@inline(never)
|
||||
public func debuggerBreak(
|
||||
_ message: String,
|
||||
file: StaticString = #file,
|
||||
file: StaticString = (#file),
|
||||
line: UInt = #line
|
||||
) {
|
||||
XCTFail(message, file: file, line: line)
|
||||
|
||||
Reference in new issue
Block a user