diff --git a/Package.swift b/Package.swift index ccd8a07a..540dbfc3 100644 --- a/Package.swift +++ b/Package.swift @@ -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, diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque+Collection.swift index adb896a8..0e308724 100644 --- a/Sources/DequeModule/Deque+Collection.swift +++ b/Sources/DequeModule/Deque+Collection.swift @@ -13,7 +13,7 @@ import InternalCollectionsUtilities #endif -import Future +import Span extension Deque { // Implementation note: we could also use the default `IndexingIterator` here. diff --git a/Sources/DequeModule/Deque+Container.swift b/Sources/DequeModule/Deque+Container.swift index f0e2fb65..0b714a24 100644 --- a/Sources/DequeModule/Deque+Container.swift +++ b/Sources/DequeModule/Deque+Container.swift @@ -10,7 +10,7 @@ //===----------------------------------------------------------------------===// #if !COLLECTIONS_SINGLE_MODULE -import Future +import Span #endif extension Deque: RandomAccessContainer { diff --git a/Sources/DequeModule/Deque+Equatable.swift b/Sources/DequeModule/Deque+Equatable.swift index eb0f4709..0c64445e 100644 --- a/Sources/DequeModule/Deque+Equatable.swift +++ b/Sources/DequeModule/Deque+Equatable.swift @@ -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 diff --git a/Sources/DequeModule/Deque.swift b/Sources/DequeModule/Deque.swift index 034bb806..c52bbc0a 100644 --- a/Sources/DequeModule/Deque.swift +++ b/Sources/DequeModule/Deque.swift @@ -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 diff --git a/Sources/DequeModule/DynamicDeque.swift b/Sources/DequeModule/DynamicDeque.swift index 4e6156b2..58eb4303 100644 --- a/Sources/DequeModule/DynamicDeque.swift +++ b/Sources/DequeModule/DynamicDeque.swift @@ -11,7 +11,7 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities -import Future +import Span #endif @frozen diff --git a/Sources/DequeModule/RigidDeque.swift b/Sources/DequeModule/RigidDeque.swift index 118a4290..cdf3f3f4 100644 --- a/Sources/DequeModule/RigidDeque.swift +++ b/Sources/DequeModule/RigidDeque.swift @@ -11,7 +11,7 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities -import Future +import Span #endif @frozen diff --git a/Sources/DequeModule/_UnsafeDequeSegments.swift b/Sources/DequeModule/_UnsafeDequeSegments.swift index 7ca03a59..49d5592f 100644 --- a/Sources/DequeModule/_UnsafeDequeSegments.swift +++ b/Sources/DequeModule/_UnsafeDequeSegments.swift @@ -11,7 +11,7 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities -import Future +import Span #endif @frozen diff --git a/Sources/Future/Box.swift b/Sources/Future/Box.swift deleted file mode 100644 index 42f7f95f..00000000 --- a/Sources/Future/Box.swift +++ /dev/null @@ -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: ~Copyable { - @usableFromInline - internal let _pointer: UnsafeMutablePointer - - @_alwaysEmitIntoClient - @_transparent - public init(_ value: consuming T) { - _pointer = UnsafeMutablePointer.allocate(capacity: 1) - _pointer.initialize(to: value) - } - - @_alwaysEmitIntoClient - @_transparent - public init(_ fromInout: consuming Inout) { - _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 { - let result = Inout(unsafeImmortalAddress: _pointer) - discard self - return result - } - - @_alwaysEmitIntoClient - public subscript() -> T { - @_transparent - unsafeAddress { - UnsafePointer(_pointer) - } - - @_transparent - nonmutating unsafeMutableAddress { - _pointer - } - } -} - -extension Box where T: Copyable { - @_alwaysEmitIntoClient - @_transparent - public borrowing func copy() -> T { - _pointer.pointee - } -} diff --git a/Sources/Future/Cell.swift b/Sources/Future/Cell.swift deleted file mode 100644 index f712836d..00000000 --- a/Sources/Future/Cell.swift +++ /dev/null @@ -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: ~Copyable { - @_alwaysEmitIntoClient - @_transparent - public var unsafeAddress: UnsafeMutablePointer { - UnsafeMutablePointer(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 { - Inout(unsafeAddress: unsafeAddress, owner: &self) - } - - @_alwaysEmitIntoClient - public subscript() -> T { - @_transparent - unsafeAddress { - UnsafePointer(unsafeAddress) - } - - @_transparent - nonmutating unsafeMutableAddress { - unsafeAddress - } - } -} - -extension Cell where T: Copyable { - @_alwaysEmitIntoClient - @_transparent - public borrowing func copy() -> T { - unsafeAddress.pointee - } -} diff --git a/Sources/Future/Containers/Container.swift b/Sources/Future/Containers/Container.swift deleted file mode 100644 index 4df0f6b8..00000000 --- a/Sources/Future/Containers/Container.swift +++ /dev/null @@ -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 -} - -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 -} - -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 diff --git a/Sources/Future/Containers/DynamicArray.swift b/Sources/Future/Containers/DynamicArray.swift deleted file mode 100644 index 0da61708..00000000 --- a/Sources/Future/Containers/DynamicArray.swift +++ /dev/null @@ -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: ~Copyable { - @usableFromInline - internal var _storage: RigidArray - - @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 { - _storage.storage - } -} - -extension DynamicArray: RandomAccessContainer where Element: ~Copyable { - public typealias BorrowingIterator = RigidArray.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 ( - 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 ( - 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) { - for item in items { - append(item) - } - } -} diff --git a/Sources/Future/Containers/NewArray.swift b/Sources/Future/Containers/NewArray.swift deleted file mode 100644 index 423fb565..00000000 --- a/Sources/Future/Containers/NewArray.swift +++ /dev/null @@ -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 { - @usableFromInline - internal var _storage: Shared> - - @inlinable - public init(minimumCapacity: Int) { - self._storage = Shared(RigidArray(capacity: minimumCapacity)) - } -} - -extension NewArray { - public var storage: Span { -#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( - _ body: (borrowing RigidArray) throws(E) -> Result - ) throws(E) -> Result { - try _storage.read(body) - } - - @inlinable - internal mutating func _update( - _ body: (inout RigidArray) throws(E) -> Result - ) throws(E) -> Result { - _ensureUnique() - return try _storage.update(body) - } - - @inlinable - internal mutating func _update( - minimumCapacity: Int, - _ body: (inout RigidArray) 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, - with newElements: some Collection - ) { - let delta = newElements.count - subrange.count - _ensureUnique(minimumCapacity: capacity + delta) - } -} diff --git a/Sources/Future/Containers/RigidArray.swift b/Sources/Future/Containers/RigidArray.swift deleted file mode 100644 index eda928f7..00000000 --- a/Sources/Future/Containers/RigidArray.swift +++ /dev/null @@ -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: ~Copyable { - @usableFromInline - internal var _storage: UnsafeMutableBufferPointer - - @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 { - Span(_unsafeElements: _items) - } -} - -extension RigidArray: RandomAccessContainer where Element: ~Copyable { - public struct BorrowingIterator: BorrowingIteratorProtocol, ~Escapable { - @usableFromInline - internal let _items: UnsafeBufferPointer - - @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 { - 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 { - _storage.extracting(Range(uncheckedBounds: (0, _count))) - } - - @inlinable - internal var _freeSpace: UnsafeMutableBufferPointer { - _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 = .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 ( - 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 ( - 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) { - 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(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(capacity: capacity) - let initialized = result._storage.moveInitialize(fromContentsOf: _storage) - precondition(initialized == count) - result._count = count - self._count = 0 - return result - } -} diff --git a/Sources/Future/Containers/Shared.swift b/Sources/Future/Containers/Shared.swift deleted file mode 100644 index 1ebcc284..00000000 --- a/Sources/Future/Containers/Shared.swift +++ /dev/null @@ -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 { - @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 { - @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 -} -#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 { - // Adapted from _getUnsafePointerToStoredProperties - let p = ( - UnsafeRawPointer(Builtin.bridgeToRawPointer(_box)) - + MemoryLayout.size) - return p.alignedUp(for: Storage.self).assumingMemoryBound(to: Storage.self) - } - - @inlinable - internal var _mutableAddress: UnsafeMutablePointer { - // Adapted from _getUnsafePointerToStoredProperties - let p = ( - UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_box)) - + MemoryLayout.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( - _ 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( - _ 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 { - // 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)) - } - } -} - diff --git a/Sources/Future/ContiguousStorage.swift b/Sources/Future/ContiguousStorage.swift deleted file mode 100644 index 27a4f00f..00000000 --- a/Sources/Future/ContiguousStorage.swift +++ /dev/null @@ -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: ~Copyable, ~Escapable { - associatedtype Element/*: ~Copyable & ~Escapable*/ - - var storage: Span { borrowing get } -} - -extension Span: ContiguousStorage /*where Element: ~Copyable & ~Escapable*/ { - public var storage: Self { self } -} - -extension Array: ContiguousStorage { - public var storage: Span { - _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 { - borrowing get { - Span( - _unsafeStart: _baseAddressIfContiguous!, count: count - ) - } - } -} - -extension CollectionOfOne: ContiguousStorage { - public var storage: Span { - _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 { - _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 - ) - } - } - } -} diff --git a/Sources/Future/Inout.swift b/Sources/Future/Inout.swift deleted file mode 100644 index deb06ce5..00000000 --- a/Sources/Future/Inout.swift +++ /dev/null @@ -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`, one must have exclusive access -/// to the instance of `T`. This is achieved through the 'inout' operator, '&'. -@frozen -public struct Inout: ~Copyable, ~Escapable { - @usableFromInline - internal let _pointer: UnsafeMutablePointer - - /// 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(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( - unsafeAddress: UnsafeMutablePointer, - 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 - ) { - _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(_pointer) - } - - @_transparent - nonmutating unsafeMutableAddress { - _pointer - } - } -} diff --git a/Sources/Future/LifetimeOverride.swift b/Sources/Future/LifetimeOverride.swift deleted file mode 100644 index 4b32cb6e..00000000 --- a/Sources/Future/LifetimeOverride.swift +++ /dev/null @@ -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 -} diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift deleted file mode 100644 index 75da72b7..00000000 --- a/Sources/Future/MutableSpan.swift +++ /dev/null @@ -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 represents a span of memory which -// contains initialized `Element` instances. -@_disallowFeatureSuppression(NonescapableTypes) -@frozen -public struct MutableSpan: ~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 - ) { - _pointer = .init(elements.baseAddress) - _count = elements.count - } - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - @lifetime(borrow buffer) - public init( - _unsafeElements buffer: UnsafeMutableBufferPointer - ) { - precondition( - ((Int(bitPattern: buffer.baseAddress) & - (MemoryLayout.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, - 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> - ) { - 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.alignment&-1)) == 0), - "baseAddress must be properly aligned to access Element" - ) - let (byteCount, stride) = (buffer.count, MemoryLayout.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 - ) { - self.init(_unsafeBytes: UnsafeMutableRawBufferPointer(rebasing: buffer)) - } -} - -@_disallowFeatureSuppression(NonescapableTypes) -extension Span where Element: ~Copyable { - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public init(_unsafeMutableSpan mutableSpan: borrowing MutableSpan) { - self.init(_unchecked: mutableSpan._start, count: mutableSpan.count) - } -} - -@_disallowFeatureSuppression(NonescapableTypes) -extension MutableSpan where Element: ~Copyable { - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public var storage: Span { Span(_unsafeMutableSpan: self) } - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public func withSpan( - _ body: (Span) throws(E) -> Result - ) throws(E) -> Result { - try body(Span(_unsafeMutableSpan: self)) - } -} - -@_disallowFeatureSuppression(NonescapableTypes) -extension RawSpan { - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public init( - _unsafeMutableSpan mutableSpan: borrowing MutableSpan - ) { - self.init( - _unchecked: mutableSpan._start, - byteCount: mutableSpan.count &* MemoryLayout.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) -> Bool { - Span(_unsafeMutableSpan: self)._elementsEqual(other) - } - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public func _elementsEqual(_ other: some Collection) -> Bool { - Span(_unsafeMutableSpan: self)._elementsEqual(other) - } - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public func _elementsEqual(_ other: some Sequence) -> 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 { - 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) -> 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) -> 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.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.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.stride - return _start.loadUnaligned(fromByteOffset: offset, as: Element.self) - } - set { - let offset = position&*MemoryLayout.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( - _ body: (_ buffer: UnsafeBufferPointer) 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( - _ body: (inout UnsafeMutableBufferPointer) throws(E) -> Result - ) throws(E) -> Result { - func executeBody( - _ start: UnsafeMutablePointer?, _ count: Int - ) throws(E) -> Result { - var buf = UnsafeMutableBufferPointer(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( - _ 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( - _ body: (_ buffer: UnsafeMutableRawBufferPointer) throws(E) -> Result - ) throws(E) -> Result { - let bytes = UnsafeMutableRawBufferPointer( - start: (_count == 0) ? nil : _start, - count: _count &* MemoryLayout.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( - 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 - ) -> 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 - ) -> 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) -> 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 - ) -> 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 - ) -> 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 - ) -> 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> - ) -> 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( - 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 - ) -> 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 - ) -> 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 - ) -> 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.stride - ) - return source.count - } - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public mutating func update( - fromContentsOf source: borrowing MutableSpan - ) -> 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 - ) -> Int where Element: BitwiseCopyable { - self.update(fromContentsOf: RawSpan(_unsafeBytes: source)) - } - - @_alwaysEmitIntoClient - public mutating func update( - fromContentsOf source: Slice - ) -> 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 - ) -> Int where Element: BitwiseCopyable { - self.update(fromContentsOf: source.storage) - } - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public mutating func copyMemory( - from source: Span - ) -> Int where Element: BitwiseCopyable { - self.update(fromContentsOf: source) - } -} diff --git a/Sources/Future/RawSpan.swift b/Sources/Future/RawSpan.swift deleted file mode 100644 index 343b9fba..00000000 --- a/Sources/Future/RawSpan.swift +++ /dev/null @@ -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 - ) { - 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 - ) { - 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( - _unsafeElements buffer: borrowing UnsafeBufferPointer - ) { - 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( - _unsafeElements buffer: borrowing Slice> - ) { - 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( - _unsafeElements buffer: borrowing UnsafeMutableBufferPointer - ) { - 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( - _unsafeElements buffer: borrowing Slice> - ) { - 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( - _unsafeStart pointer: borrowing UnsafePointer, - count: Int - ) { - precondition(count >= 0, "Count must not be negative") - self.init( - _unchecked: copy pointer, byteCount: count * MemoryLayout.stride - ) - } - - /// Create a `RawSpan` over the memory represented by a `Span` - /// - /// - Parameters: - /// - span: An existing `Span`, which will define both this - /// `RawSpan`'s lifetime and the memory it represents. - @_alwaysEmitIntoClient - @lifetime(borrow span) - public init( - _elements span: borrowing Span - ) { - self.init( - _unchecked: span._pointer, - byteCount: span.count &* MemoryLayout.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 { - .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) -> 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) -> 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) -> 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 - ) -> 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( - _ 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.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( - as type: T.Type - ) -> Span { - 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( - fromByteOffset offset: Int = 0, as: T.Type - ) -> T { - precondition( - UInt(bitPattern: offset) <= UInt(bitPattern: _count) && - MemoryLayout.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( - 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( - fromByteOffset offset: Int = 0, as: T.Type - ) -> T { - precondition( - UInt(bitPattern: offset) <= UInt(bitPattern: _count) && - MemoryLayout.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( - 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? { - 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) - } -} diff --git a/Sources/Future/Span+Iterator.swift b/Sources/Future/Span+Iterator.swift deleted file mode 100644 index 4db0f891..00000000 --- a/Sources/Future/Span+Iterator.swift +++ /dev/null @@ -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) { - curPointer = span._pointer - endPointer = span._pointer?.advanced( - by: span.count*MemoryLayout.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.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.stride) - } - return cur.loadUnaligned(as: Element.self) - } -} diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift deleted file mode 100644 index affe5643..00000000 --- a/Sources/Future/Span.swift +++ /dev/null @@ -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` 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 -: ~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 - ) { - //FIXME: Workaround for https://github.com/swiftlang/swift/issues/77235 - let baseAddress = buffer.baseAddress - precondition( - ((Int(bitPattern: baseAddress) & - (MemoryLayout.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 - ) { - 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, - 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> - ) { - 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> - ) { - 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.alignment &- 1)) == 0), - "baseAddress must be properly aligned to access Element" - ) - let (byteCount, stride) = (buffer.count, MemoryLayout.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 - ) { - 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 - ) { - 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..) -> 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) -> 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 { - 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 { - let elementOffset = position &* MemoryLayout.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.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) -> 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) -> Self { - let delta = bounds.lowerBound &* MemoryLayout.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) -> 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 - ) -> 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( - _ body: (_ buffer: UnsafeBufferPointer) 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( - _ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result - ) throws(E) -> Result { - try body( - .init(start: _pointer, count: _count * MemoryLayout.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? { - 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.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.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.stride - let newStart = _pointer?.advanced(by: offset) - return Self(_unchecked: newStart, count: count &- droppedCount) - } -} diff --git a/Sources/Future/StdlibSpanExtensions.swift b/Sources/Future/StdlibSpanExtensions.swift deleted file mode 100644 index cc6f4a05..00000000 --- a/Sources/Future/StdlibSpanExtensions.swift +++ /dev/null @@ -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( - _ body: (_ elements: Span) throws(E) -> Result - ) throws(E) -> Result { - try body(Span(_unsafeElements: self)) - } - - public func withBytes( - _ 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( - _ body: (_ elements: Span) throws(E) -> Result - ) throws(E) -> Result { - try body(Span(_unsafeElements: self)) - } - - public func withBytes( - _ body: (_ elements: RawSpan) throws(E) -> Result - ) throws(E) -> Result where Element: BitwiseCopyable { - try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(self))) - } -} - -extension UnsafeRawBufferPointer { - public func withBytes( - _ body: (_ elements: RawSpan) throws(E) -> Result - ) throws(E) -> Result { - try body(RawSpan(_unsafeBytes: self)) - } -} - -extension UnsafeMutableRawBufferPointer { - public func withBytes( - _ body: (_ elements: RawSpan) throws(E) -> Result - ) throws(E) -> Result { - try body(RawSpan(_unsafeBytes: self)) - } -} - -extension Slice { - public func withSpan( - _ body: (_ elements: Span) throws(E) -> Result - ) throws(E) -> Result - where Base == UnsafeBufferPointer { - try body(Span(_unsafeElements: UnsafeBufferPointer(rebasing: self))) - } - - public func withBytes( - _ body: (_ elements: RawSpan) throws(E) -> Result - ) throws(E) -> Result - where Base == UnsafeBufferPointer { - try body(RawSpan(_unsafeBytes: .init(UnsafeBufferPointer(rebasing: self)))) - } - - public func withSpan( - _ body: (_ elements: Span) throws(E) -> Result - ) throws(E) -> Result - where Base == UnsafeMutableBufferPointer { - try body(Span(_unsafeElements: UnsafeBufferPointer(rebasing: self))) - } - - public func withBytes( - _ body: (_ elements: RawSpan) throws(E) -> Result - ) throws(E) -> Result - where Base == UnsafeMutableBufferPointer { - try body(RawSpan(_unsafeBytes: .init(UnsafeBufferPointer(rebasing: self)))) - } - - public func withBytes( - _ body: (_ elements: RawSpan) throws(E) -> Result - ) throws(E) -> Result - where Base == UnsafeRawBufferPointer { - try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(rebasing: self))) - } - - public func withBytes( - _ 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( - _ body: (_ elements: Span) throws(E) -> Result - ) throws(E) -> Result { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result in - self.withUnsafeBytes { - bytes in - do throws(E) { - let result = try body(Span(_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( - _ body: (_ bytes: RawSpan) throws(E) -> Result - ) throws(E) -> Result { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result 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( - _ body: (_ elements: Span) throws(E) -> Result - ) throws(E) -> Result { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result 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( -// _ body: (_ elements: Span) 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( -// _ body: (_ elements: Span) throws(E) -> Result -// ) throws(E) -> Result { -// try self.withUnsafeBufferPointer { -// try body(Span(_unsafeElements: $0)) -// } -// } - - public func withBytes( - _ body: (_ bytes: RawSpan) throws(E) -> Result - ) throws(E) -> Result where Element: BitwiseCopyable { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result 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( - _ body: (_ elements: Span) throws(E) -> Result - ) throws(E) -> Result { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result 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( - _ body: (_ bytes: RawSpan) throws(E) -> Result - ) throws(E) -> Result where Element: BitwiseCopyable { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result 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( - _ body: (_ elements: Span) throws(E) -> Result - ) throws(E) -> Result { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result 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( - _ body: (_ bytes: RawSpan) throws(E) -> Result - ) throws(E) -> Result where Element: BitwiseCopyable { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result 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( - _ body: (_ elements: Span) throws(E) -> Result - ) throws(E) -> Result { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result? 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( - _ body: (_ bytes: RawSpan) throws(E) -> Result - ) throws(E) -> Result { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result? 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( - _ body: (_ elements: Span) throws(E) -> Result - ) throws(E) -> Result { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result? 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( - _ body: (_ bytes: RawSpan) throws(E) -> Result - ) throws(E) -> Result { - let result = withUnsafeTemporaryAllocation( - of: Swift.Result.self, capacity: 1 - ) { - buffer -> Swift.Result? 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( - _ body: (_ elements: Span) 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( - _ 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( - _ 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( - _ body: (_ bytes: RawSpan) throws(E) -> Result - ) throws(E) -> Result { - try ContiguousArray(self).withBytes(body) - } -} - -extension Span where Element: ~Copyable /*& ~Escapable*/ { - public consuming func withSpan( - _ body: (_ elements: Span) throws(E) -> Result - ) throws(E) -> Result { - try body(self) - } -} - -extension Span where Element: BitwiseCopyable { - public consuming func withBytes( - _ body: (_ elements: RawSpan) throws(E) -> Result - ) throws(E) -> Result { - try body(RawSpan(_elements: self)) - } -} - -extension RawSpan { - public consuming func withBytes( - _ body: (_ elements: RawSpan) throws(E) -> Result - ) throws(E) -> Result { - try body(self) - } -} - -//TODO: extend SIMD vectors with `withSpan` and with `withBytes`. diff --git a/Sources/Future/CMakeLists.txt b/Sources/Span/CMakeLists.txt similarity index 66% rename from Sources/Future/CMakeLists.txt rename to Sources/Span/CMakeLists.txt index f9ef82e0..b85b0b5e 100644 --- a/Sources/Future/CMakeLists.txt +++ b/Sources/Span/CMakeLists.txt @@ -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 diff --git a/Sources/Span/LifetimeOverride.swift b/Sources/Span/LifetimeOverride.swift new file mode 100644 index 00000000..ed416cfa --- /dev/null +++ b/Sources/Span/LifetimeOverride.swift @@ -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 +} diff --git a/Sources/Span/MutableRawSpan.swift b/Sources/Span/MutableRawSpan.swift new file mode 100644 index 00000000..3a2770a1 --- /dev/null +++ b/Sources/Span/MutableRawSpan.swift @@ -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 + ) { + 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( + _unsafeElements elements: UnsafeMutableBufferPointer + ) { + let bytes = UnsafeMutableRawBufferPointer(elements) + let span = MutableRawSpan(_unsafeBytes: bytes) + self = unsafe _overrideLifetime(span, borrowing: elements) + } + + @_alwaysEmitIntoClient + @lifetime(borrow elements) + public init( + _unsafeElements elements: borrowing Slice> + ) { + let rebased = unsafe UnsafeMutableBufferPointer(rebasing: elements) + let span = MutableRawSpan(_unsafeElements: rebased) + self = unsafe _overrideLifetime(span, borrowing: elements) + } + + @_alwaysEmitIntoClient + @lifetime(elements) + public init( + _elements elements: consuming MutableSpan + ) { + let bytes = unsafe UnsafeMutableRawBufferPointer( + start: elements._pointer, + count: elements.count &* MemoryLayout.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 { + unsafe Range(uncheckedBounds: (0, byteCount)) + } +} + +@available(macOS 9999, *) +extension MutableRawSpan { + + @_alwaysEmitIntoClient + public func withUnsafeBytes( + _ 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( + _ 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( + as type: T.Type + ) -> Span { + let bytes = unsafe UnsafeRawBufferPointer(start: _pointer, count: _count) + let span = Span(_unsafeBytes: bytes) + return unsafe _overrideLifetime(span, borrowing: self) + } + + @unsafe + @_alwaysEmitIntoClient + @lifetime(borrow self) + public mutating func _unsafeMutableView( + as type: T.Type + ) -> MutableSpan { + let bytes = unsafe UnsafeMutableRawBufferPointer( + start: _pointer, count: _count + ) + let span = MutableSpan(_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( + fromByteOffset offset: Int = 0, as: T.Type + ) -> T { + precondition( + UInt(bitPattern: offset) <= UInt(bitPattern: _count) && + MemoryLayout.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( + 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( + fromByteOffset offset: Int = 0, as: T.Type + ) -> T { + precondition( + UInt(bitPattern: offset) <= UInt(bitPattern: _count) && + MemoryLayout.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( + fromUncheckedByteOffset offset: Int, as: T.Type + ) -> T { + unsafe _start().loadUnaligned(fromByteOffset: offset, as: T.self) + } + + @_alwaysEmitIntoClient + public mutating func storeBytes( + of value: T, toByteOffset offset: Int = 0, as type: T.Type + ) { + precondition( + UInt(bitPattern: offset) <= UInt(bitPattern: _count) && + MemoryLayout.size <= (_count &- offset), + "Byte offset range out of bounds" + ) + unsafe storeBytes(of: value, toUncheckedByteOffset: offset, as: type) + } + + @unsafe + @_alwaysEmitIntoClient + public mutating func storeBytes( + 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( + 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( + from elements: inout some IteratorProtocol + ) -> Int { + var offset = 0 + while offset + MemoryLayout.stride <= _count { + guard let element = elements.next() else { break } + unsafe storeBytes( + of: element, toUncheckedByteOffset: offset, as: Element.self + ) + offset &+= MemoryLayout.stride + } + return offset + } + + @_alwaysEmitIntoClient + public mutating func update( + 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( + fromContentsOf source: Span + ) -> Int { +// update(from: source.bytes) + source.withUnsafeBytes { + update(fromContentsOf: $0) + } + } + + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: borrowing MutableSpan + ) -> 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) -> 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) -> 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 + ) -> 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) -> 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) + } +} diff --git a/Sources/Span/MutableSpan.swift b/Sources/Span/MutableSpan.swift new file mode 100644 index 00000000..d552a93f --- /dev/null +++ b/Sources/Span/MutableSpan.swift @@ -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 represents a span of memory which +// contains initialized `Element` instances. +@safe +@frozen +@available(macOS 9999, *) +public struct MutableSpan +: ~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 + ) { + _pointer = .init(elements.baseAddress) + _count = elements.count + } + + @_alwaysEmitIntoClient + @lifetime(borrow buffer) + public init( + _unsafeElements buffer: UnsafeMutableBufferPointer + ) { + precondition( + ((Int(bitPattern: buffer.baseAddress) & + (MemoryLayout.alignment &- 1)) == 0), + "baseAddress must be properly aligned to access Element" + ) + let ms = MutableSpan(_unchecked: buffer) + self = unsafe _overrideLifetime(ms, borrowing: buffer) + } + + @_alwaysEmitIntoClient + @lifetime(borrow start) + public init( + _unsafeStart start: UnsafeMutablePointer, + 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> + ) { + 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.alignment &- 1)) == 0), + "baseAddress must be properly aligned to access Element" + ) + let (byteCount, stride) = (buffer.count, MemoryLayout.stride) + let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride) + precondition(remainder == 0, "Span must contain a whole number of elements") + let elements = unsafe UnsafeMutableBufferPointer( + 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 + ) { + 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) { + 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 { + @lifetime(borrow self) + borrowing get { + Span(_unsafeMutableSpan: self) + } + } +} + +@available(macOS 9999, *) +extension RawSpan { + + @_alwaysEmitIntoClient + public init( + _unsafeMutableSpan mutableSpan: borrowing MutableSpan + ) { + let pointer = mutableSpan._pointer + let byteCount = mutableSpan.count &* MemoryLayout.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) -> Bool { + Span(_unsafeMutableSpan: self)._elementsEqual(other) + } + + @_alwaysEmitIntoClient + public func _elementsEqual(_ other: some Collection) -> Bool { + Span(_unsafeMutableSpan: self)._elementsEqual(other) + } + + @_alwaysEmitIntoClient + public func _elementsEqual(_ other: some Sequence) -> 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 { + 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 { + let elementOffset = position &* MemoryLayout.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.stride + return unsafe _start().loadUnaligned( + fromByteOffset: offset, as: Element.self + ) + } + set { + let offset = position&*MemoryLayout.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( + _ body: (_ buffer: UnsafeBufferPointer) 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) 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( + _ 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( + _ body: (_ buffer: UnsafeMutableRawBufferPointer) throws(E) -> Result + ) throws(E) -> Result { + let bytes = unsafe UnsafeMutableRawBufferPointer( + start: (_count == 0) ? nil : _start(), + count: _count &* MemoryLayout.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( + 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 + ) -> 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 + ) -> 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) -> 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 + ) -> Index { + update(fromContentsOf: source.span) + } +} + +@available(macOS 9999, *) +extension MutableSpan where Element: ~Copyable { + + @_alwaysEmitIntoClient + public mutating func moveUpdate( + fromContentsOf source: consuming OutputSpan + ) -> 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 + ) -> 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> + ) -> 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(rp) + unsafe rebound.update(repeating: repeatedValue, count: count) + Builtin.rebindMemory(rp, binding) + } + + @_alwaysEmitIntoClient + public mutating func update( + 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 + ) -> 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 + ) -> 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 + ) -> 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.stride + ) + } + return source.count + } + + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: borrowing MutableSpan + ) -> 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) -> 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) -> Self { + let delta = bounds.lowerBound &* MemoryLayout.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 + ) -> 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 + ) -> 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.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.stride + let newStart = unsafe _pointer?.advanced(by: offset) + let newSpan = Self(_unchecked: newStart, count: count &- droppedCount) + return unsafe _overrideLifetime(newSpan, mutating: &self) + } +} diff --git a/Sources/Span/MutableSpanSlicing.swift b/Sources/Span/MutableSpanSlicing.swift new file mode 100644 index 00000000..7db6229b --- /dev/null +++ b/Sources/Span/MutableSpanSlicing.swift @@ -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) -> 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 + ) { + let delta = bounds.lowerBound &* MemoryLayout.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 + ) { + let mut = MutableSpan(_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) -> 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 +: ~Copyable, ~Escapable { + public typealias Index = MutableSpan.Index + + public fileprivate(set) var offset: MutableSpan.Index + public /*exclusive*/ var base: MutableSpan + + init(_ _offset: Index, _ _base: consuming MutableSpan) { + 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 { + @lifetime(borrow self) + borrowing get { + let newSpan = Span( + _unchecked: base._start(), uncheckedBounds: offset..) -> SubMutableSpan { + @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.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, + 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.stride + unsafe start.withMemoryRebound(to: Element.self, capacity: bounds.count) { + unsafe $0.update(repeating: repeatedValue, count: bounds.count) + } + } +} diff --git a/Sources/Future/OutputSpan.swift b/Sources/Span/OutputSpan.swift similarity index 54% rename from Sources/Future/OutputSpan.swift rename to Sources/Span/OutputSpan.swift index f8ed7f07..4df8661b 100644 --- a/Sources/Future/OutputSpan.swift +++ b/Sources/Span/OutputSpan.swift @@ -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 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: ~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: ~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, 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>, 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.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, 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.stride) - p.initializeMemory(as: Element.self, to: value) + let p = unsafe _start().advanced(by: _initialized&*MemoryLayout.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.stride) - return p.withMemoryRebound(to: Element.self, capacity: 1, { $0.move() }) + let p = unsafe _start().advanced(by: _initialized&*MemoryLayout.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.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.stride) - p.initializeMemory(as: Element.self, to: element) + let p = unsafe _start().advanced(by: _initialized&*MemoryLayout.stride) + unsafe p.initializeMemory(as: Element.self, to: element) _initialized &+= 1 } } @@ -246,22 +245,18 @@ extension OutputSpan { fromContentsOf source: some Collection ) { 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.stride) + let tail = unsafe _start().advanced(by: _initialized&*MemoryLayout.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 - ) { - guard !source.isEmpty else { return } - precondition( - source.count <= available, - "destination span cannot contain every element from source." - ) - let tail = _start.advanced(by: _initialized&*MemoryLayout.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 @@ -298,24 +275,24 @@ extension OutputSpan { source.count <= available, "destination span cannot contain every element from source." ) - let tail = _start.advanced(by: _initialized&*MemoryLayout.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.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) { 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.stride) - tail.moveInitializeMemory( + let tail = unsafe _start().advanced(by: _initialized&*MemoryLayout.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 ) { -#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.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> ) { - 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 { - get { Span(_unchecked: _pointer, count: _initialized) } - } - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public func withSpan( - _ body: (Span) throws(E) -> R - ) throws(E) -> R { - try body(initializedPrefix) - } - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public mutating func withMutableSpan( - _ body: (inout MutableSpan) throws(E) -> Result - ) throws(E) -> Result { - var span = MutableSpan(_unchecked: _pointer, count: _initialized) - defer { - precondition( - span.count == _initialized && span._pointer == _start, - "Substituting the MutableSpan is unsound and unsafe." - ) + public var span: Span { + @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 { + @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 { + public consuming func relinquishBorrowedMemory( + ) -> UnsafeMutableBufferPointer { 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.stride) + let byteCount = count&*MemoryLayout.stride + return unsafe UnsafeMutableRawBufferPointer(start: start, count: byteCount) } } diff --git a/Sources/Span/SpanExtensions.swift b/Sources/Span/SpanExtensions.swift new file mode 100644 index 00000000..c0806547 --- /dev/null +++ b/Sources/Span/SpanExtensions.swift @@ -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(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(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..) -> 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) -> 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 + } +} diff --git a/Sources/Future/StdlibOutputSpanExtensions.swift b/Sources/Span/StdlibOutputSpanExtensions.swift similarity index 54% rename from Sources/Future/StdlibOutputSpanExtensions.swift rename to Sources/Span/StdlibOutputSpanExtensions.swift index cc392a3c..fce41a04 100644 --- a/Sources/Future/StdlibOutputSpanExtensions.swift +++ b/Sources/Span/StdlibOutputSpanExtensions.swift @@ -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) 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( - _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) throws -> Void + initializingWith initializer: (inout OutputSpan) 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( + _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) 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( + _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 } } diff --git a/Sources/Future/UnsafeBufferPointer+Additions.swift b/Sources/Span/UnsafeBufferPointer+Additions.swift similarity index 100% rename from Sources/Future/UnsafeBufferPointer+Additions.swift rename to Sources/Span/UnsafeBufferPointer+Additions.swift diff --git a/Tests/FutureTests/BoxTests.swift b/Tests/FutureTests/BoxTests.swift deleted file mode 100644 index 9f1075e8..00000000 --- a/Tests/FutureTests/BoxTests.swift +++ /dev/null @@ -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(0) - - XCTAssertEqual(intOnHeap[], 0) - - intOnHeap[] = 123 - - XCTAssertEqual(intOnHeap[], 123) - - let inoutToIntOnHeap = intOnHeap.leak() - - XCTAssertEqual(inoutToIntOnHeap[], 123) - - inoutToIntOnHeap[] = 321 - - XCTAssertEqual(inoutToIntOnHeap[], 321) - - let intOnHeapAgain = Box(inoutToIntOnHeap) - - XCTAssertEqual(intOnHeapAgain[], 321) - - XCTAssertEqual(intOnHeapAgain.copy(), 321) - - let intInRegister = intOnHeapAgain.consume() - - XCTAssertEqual(intInRegister, 321) - } -} diff --git a/Tests/FutureTests/CellTests.swift b/Tests/FutureTests/CellTests.swift deleted file mode 100644 index 7588e164..00000000 --- a/Tests/FutureTests/CellTests.swift +++ /dev/null @@ -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(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) - } -} diff --git a/Tests/FutureTests/ContiguousStorageTests.swift b/Tests/FutureTests/ContiguousStorageTests.swift deleted file mode 100644 index b0fa7a06..00000000 --- a/Tests/FutureTests/ContiguousStorageTests.swift +++ /dev/null @@ -1,59 +0,0 @@ -import XCTest -import Future - -final class ContiguousStorageTests: XCTestCase { - - func testBorrowArrayStorage() throws { - - let capacity = 10 - var a: [Int] = [] - a = Array(0.. - - var startIndex: Int { 0 } - var endIndex: Int { span.count } - func index(after i: Int) -> Int { i+2 } - - init(_ contiguous: borrowing Span) { - span = copy contiguous - } - - subscript(_ p: Int) -> Int { span[p] } - } - - @inline(never) - @lifetime(borrow array) - private func skip( - along array: borrowing Array - ) -> Skipper { - Skipper(array.storage) - } - - func testSpanWrapper() { - let capacity = 8 - let a = Array(0..() - 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(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(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() - 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() - 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(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(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(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) - } - } -} diff --git a/Tests/FutureTests/Inout.swift b/Tests/FutureTests/Inout.swift deleted file mode 100644 index 8ef1a100..00000000 --- a/Tests/FutureTests/Inout.swift +++ /dev/null @@ -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) - } -} diff --git a/Tests/FutureTests/StdlibSpanExtensionTests.swift b/Tests/FutureTests/StdlibSpanExtensionTests.swift deleted file mode 100644 index 006c1066..00000000 --- a/Tests/FutureTests/StdlibSpanExtensionTests.swift +++ /dev/null @@ -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...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...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...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 })) - } -} diff --git a/Tests/SpanTests/MutableRawSpanTests.swift b/Tests/SpanTests/MutableRawSpanTests.swift new file mode 100644 index 00000000..2dd1a436 --- /dev/null +++ b/Tests/SpanTests/MutableRawSpanTests.swift @@ -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...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...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(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.stride) + } + XCTAssertEqual(a.elementsEqual(0..()) + 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...stride) + } + XCTAssertEqual(a.elementsEqual(0...stride) + } + XCTAssertEqual(a.elementsEqual(0...stride) + } + } + XCTAssertEqual(a.allSatisfy({ $0 == Int.min }), true) + + a.withUnsafeMutableBytes { + var span = MutableRawSpan(_unsafeBytes: $0) + let array = Array(0...stride) + } + } + XCTAssertEqual(a.elementsEqual(0..) { + s[0] += 100 + } + + public func testSliceAsExtractingFunction() { + let count = 8 + let b = UnsafeMutableBufferPointer.allocate(capacity: count) + _ = b.initialize(fromContentsOf: 0...allocate(capacity: count) + _ = b.initialize(fromContentsOf: 0..) { + s[s.offset] += 100 + } + + public func testSliceAsWrapperType() { + let count = 8 + let b = UnsafeMutableBufferPointer.allocate(capacity: count) + _ = b.initialize(fromContentsOf: 0...allocate(capacity: count) + _ = b.initialize(fromContentsOf: 0..>.size, MemoryLayout?>.size -// ) -// XCTAssertEqual( -// MemoryLayout>.stride, MemoryLayout?>.stride -// ) -// XCTAssertEqual( -// MemoryLayout>.alignment, MemoryLayout?>.alignment -// ) - } - func testInitOrdinaryElement() { let capacity = 4 var s = (0..(_unsafeBytes: $0) + let (rp, bc) = ($0.baseAddress!, $0.count) + let b = MutableSpan(_unsafeStart: rp, byteCount: bc) XCTAssertEqual(b.count, capacity) - let r = MutableSpan(_unsafeBytes: $0) - XCTAssertEqual(r.count, capacity*MemoryLayout.stride) + let stride = MemoryLayout.stride + let r = MutableSpan(_unsafeBytes: $0.dropFirst(stride)) + XCTAssertEqual(r.count, (capacity-1)*stride) + XCTAssertEqual(r.count, bc-stride) } -// let v = UnsafeRawBufferPointer(start: nil, count: 0) -// XCTAssertNil(MutableSpan(unsafeRawBufferPointer: v)) + let v = UnsafeMutableRawBufferPointer(start: nil, count: 0) + let m = MutableSpan(_unsafeBytes: v) + XCTAssertEqual(m.count, 0) } -// public func testIteratorOrdinaryElement() { -// let capacity = 4 -// var s = (0...stride) -// let bytes = count*MemoryLayout.stride + offset -// let align = MemoryLayout.alignment -// let p = UnsafeMutableRawPointer.allocate(byteCount: bytes, alignment: align) -// defer { p.deallocate() } -// for i in 0..(_unsafeStart: p+offset, byteCount: count*8) -// -// var buffered = 0 -// for value in 0...stride) + let (p, c) = ($0.baseAddress!, $0.count) + let span = MutableSpan(_unsafeStart: p, count: c) + let bytes = span.bytes + XCTAssertEqual(bytes.byteCount, count*MemoryLayout.stride) } } @@ -143,8 +102,9 @@ final class MutableSpanTests: XCTestCase { var a = Array(0..( - _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( - _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(_unsafeElements: .init(start: nil, count: 0)) + let empty = UnsafeMutableBufferPointer(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...allocate(capacity: count) + _ = b.initialize(fromContentsOf: 0..(start: nil, count: 0) + defer { _ = e } + + var m = MutableSpan(_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.. + 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(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.. + 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(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) + } + } } diff --git a/Tests/FutureTests/OutputSpanTests.swift b/Tests/SpanTests/OutputSpanTests.swift similarity index 76% rename from Tests/FutureTests/OutputSpanTests.swift rename to Tests/SpanTests/OutputSpanTests.swift index 91aa91e6..fcac8ce0 100644 --- a/Tests/FutureTests/OutputSpanTests.swift +++ b/Tests/SpanTests/OutputSpanTests.swift @@ -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: ~Copyable { let allocation: UnsafeMutablePointer let capacity: Int @@ -40,7 +41,7 @@ struct Allocation: ~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: ~Copyable { enum MyTestError: Error { case error } +@available(macOS 9999, *) final class OutputSpanTests: XCTestCase { - func testOutputBufferInitialization() { + func testOutputBufferCreation() { let c = 48 let allocation = UnsafeMutablePointer.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.allocate(capacity: c) + defer { allocation.deallocate() } + + var ob = OutputSpan(_initializing: Slice(base: allocation, bounds: 0..(_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..(_unsafeElements: .init(start: nil, count: 0)) - $0.append(fromContentsOf: storage) + os in + var array = Array(0.. 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.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...size, MemoryLayout.size -// ) -// XCTAssertEqual( -// MemoryLayout.stride, MemoryLayout.stride -// ) -// XCTAssertEqual( -// MemoryLayout.alignment, MemoryLayout.alignment -// ) - } - func testInitWithSpanOfIntegers() { let capacity = 4 - let a = Array(0...stride) - XCTAssertFalse(span.isEmpty) + Array(0...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..? bounds = span.byteOffsets(of: subSpan1) diff --git a/Tests/FutureTests/SpanTests.swift b/Tests/SpanTests/SpanTests.swift similarity index 68% rename from Tests/FutureTests/SpanTests.swift rename to Tests/SpanTests/SpanTests.swift index ae006dfa..59654711 100644 --- a/Tests/FutureTests/SpanTests.swift +++ b/Tests/SpanTests/SpanTests.swift @@ -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>.size, MemoryLayout?>.size -// ) -// XCTAssertEqual( -// MemoryLayout>.stride, MemoryLayout?>.stride -// ) -// XCTAssertEqual( -// MemoryLayout>.alignment, MemoryLayout?>.alignment -// ) - } - func testInitWithOrdinaryElement() { let capacity = 4 var s = (0..(_unsafeBytes: $0) XCTAssertEqual(r.count, capacity*MemoryLayout.stride) - let p = Span( - _unsafeStart: $0.baseAddress!, - byteCount: capacity*MemoryLayout.stride + let p = $0.baseAddress! + let span = Span( + _unsafeStart: p, byteCount: capacity*MemoryLayout.stride ) - XCTAssertEqual(p.count, capacity) + XCTAssertEqual(span.count, capacity) } a.withUnsafeMutableBytes { let b = Span(_unsafeBytes: $0) XCTAssertEqual(b.count, capacity) - let p = Span( - _unsafeStart: $0.baseAddress!, - byteCount: capacity*MemoryLayout.stride + let p = $0.baseAddress! + let span = Span( + _unsafeStart: p, byteCount: capacity*MemoryLayout.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..(_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..( - _unsafeElements: UnsafeBufferPointer(start: nil, count: 0) - ) + let nilBuffer = UnsafeBufferPointer(start: nil, count: 0) + let nilSpan = Span(_unsafeElements: nilBuffer) var bounds: Range? 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.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.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(_unsafeBytes: b.dropFirst().dropLast(7)) - let span = Span(_unsafeBytes: b.dropFirst(4)) + + let suffix = b.dropFirst(4) + let span = Span(_unsafeBytes: suffix) let first = test(span) XCTAssertEqual(first, 0x07060504) } diff --git a/Tests/FutureTests/StdlibOutputSpanExtensionTests.swift b/Tests/SpanTests/StdlibOutputSpanExtensionTests.swift similarity index 85% rename from Tests/FutureTests/StdlibOutputSpanExtensionTests.swift rename to Tests/SpanTests/StdlibOutputSpanExtensionTests.swift index 25d40d8a..a8f88322 100644 --- a/Tests/FutureTests/StdlibOutputSpanExtensionTests.swift +++ b/Tests/SpanTests/StdlibOutputSpanExtensionTests.swift @@ -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) diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift index 7224be07..554a4c93 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift @@ -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() diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift b/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift index 59816e67..d5eaef55 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift @@ -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)