From 1d8147baf9c87be7ba17f87ceb52f85d15b07199 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 18 Dec 2024 14:01:07 -0800 Subject: [PATCH 01/30] Update MutableSpan and MutableRawSpan --- Package.swift | 3 +- Sources/Future/Box.swift | 77 -- Sources/Future/CMakeLists.txt | 17 +- Sources/Future/Cell.swift | 57 -- Sources/Future/Containers/Container.swift | 158 ---- Sources/Future/Containers/DynamicArray.swift | 198 ----- Sources/Future/Containers/NewArray.swift | 118 --- Sources/Future/Containers/RigidArray.swift | 262 ------ Sources/Future/Containers/Shared.swift | 188 ---- Sources/Future/ContiguousStorage.swift | 104 --- Sources/Future/Inout.swift | 83 -- Sources/Future/LifetimeOverride.swift | 55 +- Sources/Future/MutableRawSpan.swift | 392 +++++++++ Sources/Future/MutableSpan.swift | 472 ++++------ Sources/Future/MutableSpanSlicing.swift | 142 +++ Sources/Future/OutputSpan.swift | 120 ++- Sources/Future/RawSpan.swift | 693 --------------- Sources/Future/Span+Iterator.swift | 60 -- Sources/Future/Span.swift | 830 ------------------ Sources/Future/SpanExtensions.swift | 110 +++ .../Future/StdlibOutputSpanExtensions.swift | 22 +- Sources/Future/StdlibSpanExtensions.swift | 502 ----------- Tests/FutureTests/BoxTests.swift | 43 - Tests/FutureTests/CellTests.swift | 37 - .../FutureTests/ContiguousStorageTests.swift | 59 -- Tests/FutureTests/DynamicArrayTests.swift | 180 ---- Tests/FutureTests/Inout.swift | 29 - Tests/FutureTests/MutableSpanTests.swift | 293 +++++-- Tests/FutureTests/OutputSpanTests.swift | 34 +- Tests/FutureTests/RawSpanTests.swift | 46 +- Tests/FutureTests/SpanTests.swift | 166 ++-- .../StdlibOutputSpanExtensionTests.swift | 7 +- .../StdlibSpanExtensionTests.swift | 181 ---- .../AssertionContexts/Assertions.swift | 2 +- .../AssertionContexts/TestContext.swift | 2 +- 35 files changed, 1284 insertions(+), 4458 deletions(-) delete mode 100644 Sources/Future/Box.swift delete mode 100644 Sources/Future/Cell.swift delete mode 100644 Sources/Future/Containers/Container.swift delete mode 100644 Sources/Future/Containers/DynamicArray.swift delete mode 100644 Sources/Future/Containers/NewArray.swift delete mode 100644 Sources/Future/Containers/RigidArray.swift delete mode 100644 Sources/Future/Containers/Shared.swift delete mode 100644 Sources/Future/ContiguousStorage.swift delete mode 100644 Sources/Future/Inout.swift create mode 100644 Sources/Future/MutableRawSpan.swift create mode 100644 Sources/Future/MutableSpanSlicing.swift delete mode 100644 Sources/Future/RawSpan.swift delete mode 100644 Sources/Future/Span+Iterator.swift delete mode 100644 Sources/Future/Span.swift create mode 100644 Sources/Future/SpanExtensions.swift delete mode 100644 Sources/Future/StdlibSpanExtensions.swift delete mode 100644 Tests/FutureTests/BoxTests.swift delete mode 100644 Tests/FutureTests/CellTests.swift delete mode 100644 Tests/FutureTests/ContiguousStorageTests.swift delete mode 100644 Tests/FutureTests/DynamicArrayTests.swift delete mode 100644 Tests/FutureTests/Inout.swift delete mode 100644 Tests/FutureTests/StdlibSpanExtensionTests.swift diff --git a/Package.swift b/Package.swift index ccd8a07a..ccd0adf2 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"), ] 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/CMakeLists.txt b/Sources/Future/CMakeLists.txt index f9ef82e0..9761e885 100644 --- a/Sources/Future/CMakeLists.txt +++ b/Sources/Future/CMakeLists.txt @@ -8,22 +8,13 @@ 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" + "MutableSpan.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/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 index 4b32cb6e..ed416cfa 100644 --- a/Sources/Future/LifetimeOverride.swift +++ b/Sources/Future/LifetimeOverride.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 @@ -10,17 +10,58 @@ // //===----------------------------------------------------------------------===// -import Builtin - +/// 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 -@inlinable @inline(__always) +@_alwaysEmitIntoClient +@_transparent @lifetime(borrow source) -public func unsafelyOverrideLifetime< +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 >( - of dependent: consuming T, - to source: borrowing U + _ 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/Future/MutableRawSpan.swift b/Sources/Future/MutableRawSpan.swift new file mode 100644 index 00000000..7b38f535 --- /dev/null +++ b/Sources/Future/MutableRawSpan.swift @@ -0,0 +1,392 @@ +//===--- 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. +@frozen +@available(macOS 9999, *) +public struct MutableRawSpan: ~Copyable & ~Escapable { + @usableFromInline + internal let _pointer: UnsafeMutableRawPointer? + + @usableFromInline + internal let _count: Int + + @_alwaysEmitIntoClient + internal func _start() -> UnsafeMutableRawPointer { + _pointer.unsafelyUnwrapped + } + + @usableFromInline @inline(__always) + @lifetime(borrow pointer) + init( + _unchecked pointer: UnsafeMutableRawPointer?, + count: Int + ) { + _pointer = pointer + _count = count + } +} + +@available(macOS 9999, *) +extension MutableRawSpan: @unchecked Sendable {} + +@available(macOS 9999, *) +extension MutableRawSpan { + + @lifetime(borrow bytes) + public init( + _unsafeBytes bytes: UnsafeMutableRawBufferPointer + ) { + let baseAddress = bytes.baseAddress + let span = MutableRawSpan(_unchecked: baseAddress, count: bytes.count) + self = _overrideLifetime(span, borrowing: bytes) + } + + @lifetime(borrow bytes) + public init( + _unsafeBytes bytes: borrowing Slice + ) { + let rebased = UnsafeMutableRawBufferPointer(rebasing: bytes) + let span = MutableRawSpan(_unsafeBytes: rebased) + self = _overrideLifetime(span, borrowing: bytes) + } + + @lifetime(borrow pointer) + public init( + _unsafeStart pointer: UnsafeMutableRawPointer, + byteCount: Int + ) { + precondition(byteCount >= 0, "Count must not be negative") + self.init(_unchecked: pointer, count: byteCount) + } + + @lifetime(borrow elements) + public init( + _unsafeElements elements: UnsafeMutableBufferPointer + ) { + let bytes = UnsafeMutableRawBufferPointer(elements) + let span = MutableRawSpan(_unsafeBytes: bytes) + self = _overrideLifetime(span, borrowing: elements) + } + + @lifetime(borrow elements) + public init( + _unsafeElements elements: borrowing Slice> + ) { + let rebased = UnsafeMutableBufferPointer(rebasing: elements) + let span = MutableRawSpan(_unsafeElements: rebased) + self = _overrideLifetime(span, borrowing: elements) + } + + @lifetime(elements) + public init( + _elements elements: consuming MutableSpan + ) { + let bytes = UnsafeMutableRawBufferPointer( + start: elements._pointer, + count: elements.count &* MemoryLayout.stride + ) + let span = MutableRawSpan(_unsafeBytes: bytes) + self = _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 { + .init(uncheckedBounds: (0, byteCount)) + } +} + +@available(macOS 9999, *) +extension MutableRawSpan { + + public func withUnsafeBytes( + _ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result + ) throws(E) -> Result { + guard let pointer = _pointer, _count > 0 else { + return try body(.init(start: nil, count: 0)) + } + return try body(.init(start: pointer, count: _count)) + } + + public mutating func withUnsafeMutableBytes( + _ body: (UnsafeMutableRawBufferPointer) throws(E) -> Result + ) throws(E) -> Result { + guard let pointer = _pointer, _count > 0 else { + return try body(.init(start: nil, count: 0)) + } + return try body(.init(start: pointer, count: _count)) + } +} + +@available(macOS 9999, *) +extension MutableRawSpan { + + public var bytes: RawSpan { + @lifetime(borrow self) + borrowing get { + let start = _start() + let span = RawSpan(_unsafeStart: start, byteCount: byteCount) + return _overrideLifetime(span, borrowing: self) + } + } + + @unsafe + @lifetime(borrow self) + public borrowing func _unsafeView( + as type: T.Type + ) -> Span { + let bytes = UnsafeRawBufferPointer(start: _pointer, count: _count) + let span = Span(_unsafeBytes: bytes) + return _overrideLifetime(span, borrowing: self) + } + + @unsafe + @lifetime(borrow self) + public mutating func _unsafeMutableView( + as type: T.Type + ) -> MutableSpan { + let bytes = UnsafeMutableRawBufferPointer(start: _pointer, count: _count) + let span = MutableSpan(_unsafeBytes: bytes) + return _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 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) + } + + @_alwaysEmitIntoClient + public 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" + ) + storeBytes(of: value, toUncheckedByteOffset: offset, as: type) + } + + @unsafe + @_alwaysEmitIntoClient + public func storeBytes( + of value: T, toUncheckedByteOffset offset: Int, as type: T.Type + ) { + _start().storeBytes(of: value, toByteOffset: offset, as: type) + } +} + +//MARK: copyMemory +@available(macOS 9999, *) +extension MutableRawSpan { + + public mutating func update( + startingAt byteOffset: Int = 0, + from source: S + ) -> (unwritten: S.Iterator, byteOffset: Int) where S.Element: BitwiseCopyable { + var iterator = source.makeIterator() + let offset = update(startingAt: byteOffset, from: &iterator) + return (iterator, offset) + } + + public mutating func update( + startingAt byteOffset: Int = 0, + from elements: inout some IteratorProtocol + ) -> Int { + var offset = byteOffset + while offset + MemoryLayout.stride <= _count { + guard let element = elements.next() else { break } + storeBytes(of: element, toUncheckedByteOffset: offset, as: Element.self) + offset &+= MemoryLayout.stride + } + return offset + } + + public mutating func update( + startingAt byteOffset: Int = 0, + fromContentsOf source: C + ) -> Int where C.Element: BitwiseCopyable { + let newOffset = source.withContiguousStorageIfAvailable { + self.update( + startingAt: byteOffset, fromContentsOf: Span(_unsafeElements: $0) + ) + } + if let newOffset { return newOffset } + + var elements = source.makeIterator() + let lastOffset = update(startingAt: byteOffset, from: &elements) + precondition( + elements.next() == nil, + "destination span cannot contain every element from source." + ) + return lastOffset + } + + public mutating func update( + startingAt byteOffset: Int = 0, + fromContentsOf source: Span + ) -> Int { +// update(startingAt: byteOffset, from: source.bytes) + source.withUnsafeBytes { + update(startingAt: byteOffset, fromContentsOf: $0) + } + } + + public mutating func update( + startingAt byteOffset: Int = 0, + fromContentsOf source: borrowing MutableSpan + ) -> Int { +// update(startingAt: byteOffset, from: source.storage.bytes) + source.withUnsafeBytes { + update(startingAt: byteOffset, fromContentsOf: $0) + } + } + + public mutating func update( + startingAt byteOffset: Int = 0, + from source: RawSpan + ) -> Int { + if source.byteCount == 0 { return byteOffset } + source.withUnsafeBytes { + _start().advanced(by: byteOffset) + .copyMemory(from: $0.baseAddress!, byteCount: $0.count) + } + return byteOffset &+ source.byteCount + } + + public mutating func update( + startingAt byteOffset: Int = 0, + from source: borrowing MutableRawSpan + ) -> Int { + update(startingAt: byteOffset, from: source.bytes) + } +} diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift index 75da72b7..dfa709cb 100644 --- a/Sources/Future/MutableSpan.swift +++ b/Sources/Future/MutableSpan.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 @@ -14,17 +14,19 @@ import Builtin // A MutableSpan represents a span of memory which // contains initialized `Element` instances. -@_disallowFeatureSuppression(NonescapableTypes) @frozen -public struct MutableSpan: ~Copyable & ~Escapable { +@available(macOS 9999, *) +public struct MutableSpan +: ~Copyable, ~Escapable { @usableFromInline let _pointer: UnsafeMutableRawPointer? @usableFromInline let _count: Int - @usableFromInline @inline(__always) - var _start: UnsafeMutableRawPointer { _pointer.unsafelyUnwrapped } + @_alwaysEmitIntoClient + internal func _start() -> UnsafeMutableRawPointer { + _pointer.unsafelyUnwrapped + } - @_disallowFeatureSuppression(NonescapableTypes) @usableFromInline @inline(__always) @lifetime(borrow start) init( @@ -36,14 +38,12 @@ public struct MutableSpan: ~Copyable & ~Escapable { } } -@_disallowFeatureSuppression(NonescapableTypes) -@available(*, unavailable) -extension MutableSpan: Sendable {} +@available(macOS 9999, *) +extension MutableSpan: @unchecked Sendable where Element: Sendable {} -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension MutableSpan where Element: ~Copyable { - @_disallowFeatureSuppression(NonescapableTypes) @usableFromInline @inline(__always) @lifetime(borrow elements) internal init( @@ -53,7 +53,6 @@ extension MutableSpan where Element: ~Copyable { _count = elements.count } - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient @lifetime(borrow buffer) public init( @@ -64,10 +63,10 @@ extension MutableSpan where Element: ~Copyable { (MemoryLayout.alignment&-1)) == 0), "baseAddress must be properly aligned to access Element" ) - self.init(_unchecked: buffer) + let ms = MutableSpan(_unchecked: buffer) + self = _overrideLifetime(ms, borrowing: buffer) } - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient @lifetime(borrow start) public init( @@ -75,27 +74,29 @@ extension MutableSpan where Element: ~Copyable { count: Int ) { precondition(count >= 0, "Count must not be negative") - self.init(_unsafeElements: .init(start: start, count: count)) + let buffer = UnsafeMutableBufferPointer(start: start, count: count) + let ms = MutableSpan(_unsafeElements: buffer) + self = _overrideLifetime(ms, borrowing: start) } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension MutableSpan { - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient @lifetime(borrow elements) public init( _unsafeElements elements: borrowing Slice> ) { - self.init(_unsafeElements: UnsafeMutableBufferPointer(rebasing: elements)) + let rb = UnsafeMutableBufferPointer(rebasing: elements) + let ms = MutableSpan(_unsafeElements: rb) + self = _overrideLifetime(ms, borrowing: elements) } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension MutableSpan where Element: BitwiseCopyable { - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient @lifetime(borrow buffer) public init( @@ -109,10 +110,14 @@ extension MutableSpan where Element: BitwiseCopyable { 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) + let elements = UnsafeMutableBufferPointer( + start: buffer.baseAddress?.assumingMemoryBound(to: Element.self), + count: count + ) + let ms = MutableSpan(_unsafeElements: elements) + self = _overrideLifetime(ms, borrowing: buffer) } - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient @lifetime(borrow pointer) public init( @@ -120,101 +125,98 @@ extension MutableSpan where Element: BitwiseCopyable { byteCount: Int ) { precondition(byteCount >= 0, "Count must not be negative") - self.init(_unsafeBytes: .init(start: pointer, count: byteCount)) + let bytes = UnsafeMutableRawBufferPointer(start: pointer, count: byteCount) + let ms = MutableSpan(_unsafeBytes: bytes) + self = _overrideLifetime(ms, borrowing: pointer) } - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient @lifetime(borrow buffer) public init( _unsafeBytes buffer: borrowing Slice ) { - self.init(_unsafeBytes: UnsafeMutableRawBufferPointer(rebasing: buffer)) + let bytes = UnsafeMutableRawBufferPointer(rebasing: buffer) + let ms = MutableSpan(_unsafeBytes: bytes) + self = _overrideLifetime(ms, borrowing: buffer) } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension Span where Element: ~Copyable { - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public init(_unsafeMutableSpan mutableSpan: borrowing MutableSpan) { - self.init(_unchecked: mutableSpan._start, count: mutableSpan.count) + let pointer = mutableSpan._pointer?.assumingMemoryBound(to: Element.self) + let buffer = UnsafeBufferPointer(start: pointer, count: mutableSpan.count) + let span = Span(_unsafeElements: buffer) + self = _overrideLifetime(span, borrowing: mutableSpan) } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) 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)) + public var span: Span { + @lifetime(borrow self) + borrowing get { + Span(_unsafeMutableSpan: self) + } } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension RawSpan { - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public init( _unsafeMutableSpan mutableSpan: borrowing MutableSpan ) { - self.init( - _unchecked: mutableSpan._start, - byteCount: mutableSpan.count &* MemoryLayout.stride - ) + let pointer = mutableSpan._pointer + let byteCount = mutableSpan.count &* MemoryLayout.stride + let buffer = UnsafeRawBufferPointer(start: pointer, count: byteCount) + let rawSpan = RawSpan(_unsafeBytes: buffer) + self = _overrideLifetime(rawSpan, borrowing: mutableSpan) } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) 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) +@available(macOS 9999, *) extension MutableSpan where Element: ~Copyable { @_alwaysEmitIntoClient - public var description: String { + 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 { +@available(macOS 9999, *) +extension MutableSpan where Element: ~Copyable & ~Escapable { @_alwaysEmitIntoClient public var count: Int { _count } @@ -222,82 +224,47 @@ extension MutableSpan where Element: ~Copyable { @_alwaysEmitIntoClient public var isEmpty: Bool { _count == 0 } + public typealias Index = Int + @_alwaysEmitIntoClient - public var _indices: Range { + 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) +@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 - @_disallowFeatureSuppression(NonescapableTypes) - @unsafe //FIXME: remove when the lifetime inference is fixed @_alwaysEmitIntoClient - public var _unsafeRawSpan: RawSpan { RawSpan(_unsafeMutableSpan: self) } + public var bytes: RawSpan { + @lifetime(borrow self) + borrowing get { + RawSpan(_unsafeMutableSpan: self) + } + } } -@_disallowFeatureSuppression(NonescapableTypes) +@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) - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public subscript(_ position: Int) -> Element { - _read { - precondition(boundsContain(position), "index out of bounds") - yield self[unchecked: position] + public subscript(_ position: Index) -> Element { + unsafeAddress { + precondition(indices.contains(position), "index out of bounds") + return UnsafePointer(_unsafeAddressOfElement(unchecked: position)) } - _modify { - precondition(boundsContain(position), "index out of bounds") - yield &self[unchecked: position] + unsafeMutableAddress { + precondition(indices.contains(position), "index out of bounds") + return _unsafeAddressOfElement(unchecked: position) } } @@ -309,27 +276,48 @@ extension MutableSpan where Element: ~Copyable { /// 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 + public subscript(unchecked position: Index) -> Element { + unsafeAddress { + UnsafePointer(_unsafeAddressOfElement(unchecked: position)) } - _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) + unsafeMutableAddress { + _unsafeAddressOfElement(unchecked: position) } } + + @unsafe + @_alwaysEmitIntoClient + internal func _unsafeAddressOfElement( + unchecked position: Index + ) -> UnsafeMutablePointer { + let elementOffset = position &* MemoryLayout.stride + let address = _start().advanced(by: elementOffset) + return address.assumingMemoryBound(to: Element.self) + } } -@_disallowFeatureSuppression(NonescapableTypes) +@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))) + swapAt(unchecked: i, unchecked: j) + } + + @_alwaysEmitIntoClient + public mutating func swapAt(unchecked i: Index, unchecked j: Index) { + let pi = _unsafeAddressOfElement(unchecked: i) + let pj = _unsafeAddressOfElement(unchecked: j) + let temporary = pi.move() + pi.initialize(to: pj.move()) + pj.initialize(to: consume temporary) + } +} + +@available(macOS 9999, *) extension MutableSpan where Element: BitwiseCopyable { /// Accesses the element at the specified position in the `Span`. @@ -338,15 +326,14 @@ extension MutableSpan where Element: BitwiseCopyable { /// must be greater or equal to zero, and less than `count`. /// /// - Complexity: O(1) - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public subscript(_ position: Int) -> Element { + public subscript(_ position: Index) -> Element { get { - precondition(boundsContain(position)) + precondition(indices.contains(position), "index out of bounds") return self[unchecked: position] } set { - precondition(boundsContain(position)) + precondition(indices.contains(position), "index out of bounds") self[unchecked: position] = newValue } } @@ -359,25 +346,23 @@ extension MutableSpan where Element: BitwiseCopyable { /// must be greater or equal to zero, and less than `count`. /// /// - Complexity: O(1) - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public subscript(unchecked position: Int) -> Element { + public subscript(unchecked position: Index) -> Element { get { let offset = position&*MemoryLayout.stride - return _start.loadUnaligned(fromByteOffset: offset, as: Element.self) + return _start().loadUnaligned(fromByteOffset: offset, as: Element.self) } set { let offset = position&*MemoryLayout.stride - _start.storeBytes(of: newValue, toByteOffset: offset, as: Element.self) + _start().storeBytes(of: newValue, toByteOffset: offset, as: Element.self) } } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension MutableSpan where Element: ~Copyable { //FIXME: mark closure parameter as non-escaping - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public func withUnsafeBufferPointer( _ body: (_ buffer: UnsafeBufferPointer) throws(E) -> Result @@ -386,38 +371,26 @@ extension MutableSpan where Element: ~Copyable { } //FIXME: mark closure parameter as non-escaping - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func withUnsafeMutableBufferPointer( - _ body: (inout UnsafeMutableBufferPointer) throws(E) -> Result + _ body: (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) + return try 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 body(.init(start: .init(pointer._rawValue), count: count)) } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension MutableSpan where Element: BitwiseCopyable { //FIXME: mark closure parameter as non-escaping - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public func withUnsafeBytes( _ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result @@ -426,13 +399,12 @@ extension MutableSpan where Element: BitwiseCopyable { } //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, + start: (_count == 0) ? nil : _start(), count: _count &* MemoryLayout.stride ) return try body(bytes) @@ -440,12 +412,12 @@ extension MutableSpan where Element: BitwiseCopyable { } //MARK: bulk-update functions -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension MutableSpan { @_alwaysEmitIntoClient - public mutating func update(repeating repeatedValue: Element) { - _start.withMemoryRebound(to: Element.self, capacity: count) { + public mutating func update(repeating repeatedValue: consuming Element) { + _start().withMemoryRebound(to: Element.self, capacity: count) { $0.update(repeating: repeatedValue, count: count) } } @@ -453,7 +425,7 @@ extension MutableSpan { @_alwaysEmitIntoClient public mutating func update( from source: S - ) -> (unwritten: S.Iterator, index: Int) where S.Element == Element { + ) -> (unwritten: S.Iterator, index: Index) where S.Element == Element { var iterator = source.makeIterator() let index = update(from: &iterator) return (iterator, index) @@ -462,7 +434,7 @@ extension MutableSpan { @_alwaysEmitIntoClient public mutating func update( from elements: inout some IteratorProtocol - ) -> Int { + ) -> Index { var index = 0 while index < _count { guard let element = elements.next() else { break } @@ -475,68 +447,55 @@ extension MutableSpan { @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: some Collection - ) -> Int { + ) -> Index { let updated = source.withContiguousStorageIfAvailable { self.update(fromContentsOf: Span(_unsafeElements: $0)) } if let updated { - return 0.advanced(by: updated) + return updated } - if self.isEmpty { - precondition( - source.isEmpty, - "destination buffer view cannot contain every element from source." - ) - return 0 - } + //TODO: use _copyContents here 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 - } + let index = update(from: &iterator) + precondition( + iterator.next() == nil, + "destination buffer view cannot contain every element from source." + ) return index } - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public mutating func update(fromContentsOf source: Span) -> Int { + 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." ) - _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) + _start().withMemoryRebound(to: Element.self, capacity: source.count) { dest in + source.withUnsafeBufferPointer { + dest.update(from: $0.baseAddress!, count: $0.count) } } return source.count } - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: borrowing MutableSpan - ) -> Int { - source.withSpan { self.update(fromContentsOf: $0) } + ) -> Index { + update(fromContentsOf: source.span) } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension MutableSpan where Element: ~Copyable { - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func moveUpdate( fromContentsOf source: consuming OutputSpan - ) -> Int { + ) -> Index { guard !source.isEmpty else { return 0 } precondition( source.count <= self.count, @@ -544,7 +503,7 @@ extension MutableSpan where Element: ~Copyable { ) let buffer = source.relinquishBorrowedMemory() // we must now deinitialize the returned UMBP - _start.moveInitializeMemory( + _start().moveInitializeMemory( as: Element.self, from: buffer.baseAddress!, count: buffer.count ) return buffer.count @@ -552,38 +511,23 @@ extension MutableSpan where Element: ~Copyable { 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 + ) -> Index { let source = OutputSpan(_initializing: source, initialized: source.count) return self.moveUpdate(fromContentsOf: source) -#endif } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension MutableSpan { public mutating func moveUpdate( fromContentsOf source: Slice> - ) -> Int { + ) -> Index { self.moveUpdate(fromContentsOf: .init(rebasing: source)) } } - -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension MutableSpan where Element: BitwiseCopyable { @_alwaysEmitIntoClient @@ -592,7 +536,7 @@ extension MutableSpan where Element: BitwiseCopyable { ) where Element: BitwiseCopyable { guard count > 0 else { return } // rebind _start manually in order to avoid assumptions about alignment. - let rp = _start._rawValue + let rp = _start()._rawValue let binding = Builtin.bindMemory(rp, count._builtinWordValue, Element.self) UnsafeMutablePointer(rp).update(repeating: repeatedValue, count: count) Builtin.rebindMemory(rp, binding) @@ -601,7 +545,7 @@ extension MutableSpan where Element: BitwiseCopyable { @_alwaysEmitIntoClient public mutating func update( from source: S - ) -> (unwritten: S.Iterator, index: Int) + ) -> (unwritten: S.Iterator, index: Index) where S.Element == Element, Element: BitwiseCopyable { var iterator = source.makeIterator() let index = update(from: &iterator) @@ -611,7 +555,7 @@ extension MutableSpan where Element: BitwiseCopyable { @_alwaysEmitIntoClient public mutating func update( from elements: inout some IteratorProtocol - ) -> Int { + ) -> Index { var index = 0 while index < _count { guard let element = elements.next() else { break } @@ -624,120 +568,46 @@ extension MutableSpan where Element: BitwiseCopyable { @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: some Collection - ) -> Int where Element: BitwiseCopyable { + ) -> Index where Element: BitwiseCopyable { let updated = source.withContiguousStorageIfAvailable { self.update(fromContentsOf: Span(_unsafeElements: $0)) } if let updated { - return 0.advanced(by: updated) + return updated } - if self.isEmpty { - precondition( - source.isEmpty, - "destination buffer view cannot contain every element from source." - ) - return 0 - } + //TODO: use _copyContents here 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 - } + let index = update(from: &iterator) + precondition( + iterator.next() == nil, + "destination buffer view cannot contain every element from source." + ) return index } - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: Span - ) -> Int where Element: BitwiseCopyable { + ) -> Index 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 - ) + source.withUnsafeBufferPointer { + _start().copyMemory( + from: $0.baseAddress!, byteCount: $0.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) + ) -> Index where Element: BitwiseCopyable { + update(fromContentsOf: source.span) } } diff --git a/Sources/Future/MutableSpanSlicing.swift b/Sources/Future/MutableSpanSlicing.swift new file mode 100644 index 00000000..dbd6c809 --- /dev/null +++ b/Sources/Future/MutableSpanSlicing.swift @@ -0,0 +1,142 @@ +//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" + ) + return extracting(unchecked: bounds) + } + + @lifetime(borrow self) + public mutating func extracting(unchecked bounds: Range) -> Self { + let delta = bounds.lowerBound &* MemoryLayout.stride + let newStart = _pointer?.advanced(by: delta) + let newSpan = MutableSpan(_unchecked: newStart, count: bounds.count) + return _overrideLifetime(newSpan, mutating: &self) + } +} + +//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" + ) + return self[extractingUnchecked: bounds] + } + } + + public subscript(extractingUnchecked bounds: Range) -> Self { + @lifetime(borrow self) + mutating get { + let delta = bounds.lowerBound &* MemoryLayout.stride + let newStart = _pointer?.advanced(by: delta) + let newSpan = MutableSpan(_unchecked: newStart, count: bounds.count) + return _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 UnsafePointer(base._unsafeAddressOfElement(unchecked: index)) + } + unsafeMutableAddress { + precondition(offset <= index && index < base.count) + return base._unsafeAddressOfElement(unchecked: index) + } + } + + public var span: Span { + @lifetime(borrow self) + borrowing get { + let delta = offset &* MemoryLayout.stride + let newStart = base._pointer?.advanced(by: delta).assumingMemoryBound(to: Element.self) + let buffer = UnsafeBufferPointer(start: newStart, count: count) + let newSpan = Span(_unsafeElements: buffer) + return _overrideLifetime(newSpan, borrowing: self) + } + } +} + +@available(macOS 9999, *) +extension SubMutableSpan { + public mutating func update(repeating repeatedValue: consuming Element) { + base.update(repeating: repeatedValue) + } +} + +@available(macOS 9999, *) +extension MutableSpan where Element: ~Copyable { + + public subscript(slicing bounds: Range) -> 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 prefixBuffer = UnsafeMutableBufferPointer( + start: _start().assumingMemoryBound(to: Element.self), + count: bounds.upperBound + ) + let prefix = MutableSpan(_unsafeElements: prefixBuffer) + var subSpan = SubMutableSpan(bounds.lowerBound, prefix) + subSpan.offset = bounds.lowerBound + return _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 = _start().advanced(by: bounds.lowerBound &* MemoryLayout.stride) + start.withMemoryRebound(to: Element.self, capacity: bounds.count) { + $0.update(repeating: repeatedValue, count: bounds.count) + } + } +} diff --git a/Sources/Future/OutputSpan.swift b/Sources/Future/OutputSpan.swift index f8ed7f07..413a4c49 100644 --- a/Sources/Future/OutputSpan.swift +++ b/Sources/Future/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,8 +12,8 @@ // OutputSpan represents a span of memory which contains // a variable number of `Element` instances, followed by uninitialized memory. -@_disallowFeatureSuppression(NonescapableTypes) @frozen +@available(macOS 9999, *) public struct OutputSpan: ~Copyable, ~Escapable { @usableFromInline let _pointer: UnsafeMutableRawPointer? @@ -43,7 +43,6 @@ public struct OutputSpan: ~Copyable, ~Escapable { } } - @_disallowFeatureSuppression(NonescapableTypes) @usableFromInline @inline(__always) @lifetime(borrow start) init( @@ -57,14 +56,13 @@ public struct OutputSpan: ~Copyable, ~Escapable { } } -@_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) @lifetime(borrow buffer) init( @@ -76,7 +74,6 @@ extension OutputSpan where Element: ~Copyable { _initialized = initialized } - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient @lifetime(borrow buffer) public init( @@ -91,7 +88,6 @@ extension OutputSpan where Element: ~Copyable { self.init(_unchecked: buffer, initialized: initialized) } - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient @lifetime(borrow pointer) public init( @@ -100,31 +96,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 buffer = UnsafeMutableBufferPointer(start: pointer, count: capacity) + let os = OutputSpan(_initializing: buffer, initialized: initialized) + self = _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 = UnsafeMutableBufferPointer(rebasing: buffer) + let os = OutputSpan(_initializing: rebased, initialized: 0) + self = _overrideLifetime(os, borrowing: buffer) } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension OutputSpan where Element: BitwiseCopyable { - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient @lifetime(borrow bytes) public init( @@ -139,12 +134,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 = _overrideLifetime(os, borrowing: bytes) } - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient @lifetime(borrow pointer) public init( @@ -153,31 +149,28 @@ 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 buffer = UnsafeMutableRawBufferPointer(start: pointer, count: capacity) + let os = OutputSpan(_initializing: buffer, initialized: initialized) + self = _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 = UnsafeMutableRawBufferPointer(rebasing: buffer) + let os = OutputSpan(_initializing: rebased, initialized: initialized) + self = _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) @@ -202,7 +195,7 @@ extension OutputSpan where Element: ~Copyable { } //MARK: bulk-update functions -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension OutputSpan { @_alwaysEmitIntoClient @@ -288,7 +281,6 @@ extension OutputSpan { } //FIXME: rdar://136838539 & rdar://136849171 - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func append( fromContentsOf source: Span @@ -299,23 +291,23 @@ extension OutputSpan { "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) + _ = source.withUnsafeBufferPointer { + 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 @@ -334,7 +326,6 @@ extension OutputSpan where Element: ~Copyable { _initialized &+= buffer.count } - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func moveAppend( fromContentsOf source: UnsafeMutableBufferPointer @@ -357,9 +348,9 @@ extension OutputSpan where Element: ~Copyable { } } +@available(macOS 9999, *) extension OutputSpan { - @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func moveAppend( fromContentsOf source: Slice> @@ -368,43 +359,38 @@ extension OutputSpan { } } +@available(macOS 9999, *) extension OutputSpan where Element: BitwiseCopyable { } +@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 = _pointer?.assumingMemoryBound(to: Element.self) + let buffer = UnsafeBufferPointer(start: pointer, count: _initialized) + let span = Span(_unsafeElements: buffer) + return _overrideLifetime(span, borrowing: self) + } + } + + @_alwaysEmitIntoClient + public var mutableSpan: MutableSpan { + @lifetime(borrow self) + mutating get { + let pointer = _pointer?.assumingMemoryBound(to: Element.self) + let buffer = UnsafeMutableBufferPointer(start: pointer, count: _initialized) + let span = MutableSpan(_unsafeElements: buffer) + return _overrideLifetime(span, mutating: &self) } - return try body(&span) } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension OutputSpan where Element: ~Copyable { @_alwaysEmitIntoClient @@ -416,7 +402,7 @@ extension OutputSpan where Element: ~Copyable { } } -@_disallowFeatureSuppression(NonescapableTypes) +@available(macOS 9999, *) extension OutputSpan where Element: BitwiseCopyable { @_alwaysEmitIntoClient 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/SpanExtensions.swift b/Sources/Future/SpanExtensions.swift new file mode 100644 index 00000000..87546bea --- /dev/null +++ b/Sources/Future/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 nilBasedBuffer = UnsafeBufferPointer(start: nil, count: 0) + let span = Span(_unsafeElements: nilBasedBuffer) + return _overrideLifetime(span, borrowing: immortalThing) + } + } + + @available(macOS 9999, *) + @lifetime(immortal) + public init() { + let nilBasedBuffer = UnsafeBufferPointer(start: nil, count: 0) + let span = Span(_unsafeElements: nilBasedBuffer) + self = _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 self[unchecked: offset] != otherElement { return false } + offset += 1 + } + return offset == count + } +} diff --git a/Sources/Future/StdlibOutputSpanExtensions.swift b/Sources/Future/StdlibOutputSpanExtensions.swift index cc392a3c..decf5d29 100644 --- a/Sources/Future/StdlibOutputSpanExtensions.swift +++ b/Sources/Future/StdlibOutputSpanExtensions.swift @@ -12,6 +12,7 @@ extension Array { + @available(macOS 9999, *) public init( capacity: Int, initializingWith initializer: (inout OutputSpan) throws -> Void @@ -19,9 +20,9 @@ extension Array { try self.init( unsafeUninitializedCapacity: capacity, initializingWith: { (buffer, count) in + let pointer = 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() @@ -37,17 +38,17 @@ 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( unsafeUninitializedCapacity: capacity, initializingUTF8With: { buffer in - var output = OutputSpan( - _initializing: buffer.baseAddress.unsafelyUnwrapped, - capacity: capacity + let pointer = buffer.baseAddress.unsafelyUnwrapped + var output = OutputSpan( + _initializing: pointer, capacity: buffer.count ) try initializer(&output) let initialized = output.relinquishBorrowedMemory() @@ -62,6 +63,7 @@ import Foundation extension Data { + @available(macOS 9999, *) public init( capacity: Int, initializingWith initializer: (inout OutputSpan) throws -> Void @@ -70,9 +72,9 @@ extension Data { 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 pointer = buffer.baseAddress.unsafelyUnwrapped + var output = OutputSpan( + _initializing: pointer, capacity: capacity ) try initializer(&output) let initialized = output.relinquishBorrowedMemory() 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/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/MutableSpanTests.swift b/Tests/FutureTests/MutableSpanTests.swift index 8fa98487..9b351bae 100644 --- a/Tests/FutureTests/MutableSpanTests.swift +++ b/Tests/FutureTests/MutableSpanTests.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// import XCTest -@testable import Future +import Future class ID { let id: Int @@ -23,26 +23,16 @@ class ID { } } +@available(macOS 9999, *) final class MutableSpanTests: XCTestCase { - func testOptionalStorage() { -// XCTAssertEqual( -// MemoryLayout>.size, MemoryLayout?>.size -// ) -// XCTAssertEqual( -// MemoryLayout>.stride, MemoryLayout?>.stride -// ) -// XCTAssertEqual( -// MemoryLayout>.alignment, MemoryLayout?>.alignment -// ) - } - func testInitOrdinaryElement() { let capacity = 4 var s = (0...stride) + let bytes = span.bytes + XCTAssertEqual(bytes.byteCount, count*MemoryLayout.stride) } } @@ -143,8 +139,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 +283,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 +318,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 +341,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 +364,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 +385,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,7 +406,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 update = span.update(fromContentsOf: []) XCTAssertEqual(update, 0) @@ -416,7 +424,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: UnsafeBufferPointer(start: nil, count: 0)) XCTAssertEqual(updated, 0) @@ -428,24 +437,6 @@ final class MutableSpanTests: XCTestCase { XCTAssertEqual(a.map(\.id).elementsEqual(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 + let b = UnsafeMutableBufferPointer.allocate(capacity: count) + _ = b.initialize(fromContentsOf: 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..: ~Copyable { let allocation: UnsafeMutablePointer let capacity: Int @@ -64,6 +65,7 @@ struct Allocation: ~Copyable { enum MyTestError: Error { case error } +@available(macOS 9999, *) final class OutputSpanTests: XCTestCase { func testOutputBufferInitialization() { @@ -82,7 +84,7 @@ final class OutputSpanTests: XCTestCase { let c = 10 a.initialize { for i in 0...c { - $0.appendElement(i) + $0.append(i) } let oops = $0.deinitializeLastElement() XCTAssertEqual(oops, c) @@ -126,7 +128,7 @@ final class OutputSpanTests: XCTestCase { a.initialize { $0.append(fromContentsOf: 0.. 0) throw MyTestError.error } @@ -224,23 +226,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() { @@ -146,10 +140,13 @@ final class RawSpanTests: XCTestCase { func testUnsafeBytes() { let capacity = 4 let array = Array(0..? bounds = span.byteOffsets(of: subSpan1) diff --git a/Tests/FutureTests/SpanTests.swift b/Tests/FutureTests/SpanTests.swift index ae006dfa..805ba1cc 100644 --- a/Tests/FutureTests/SpanTests.swift +++ b/Tests/FutureTests/SpanTests.swift @@ -11,22 +11,11 @@ //===----------------------------------------------------------------------===// import XCTest -@testable import Future +import Future +@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) } } @@ -238,19 +228,19 @@ final class SpanTests: XCTestCase { } } - func testFirstAndLast() { - let r = Int.random(in: 0..<1000) - let a = [r] - a.withUnsafeBufferPointer { - let span = Span(_unsafeElements: $0) - XCTAssertEqual(span.first, r) - XCTAssertEqual(span.last, r) - - let emptySpan = span._extracting(0..<0) - XCTAssertEqual(emptySpan.first, nil) - XCTAssertEqual(emptySpan.last, nil) - } - } +// func testFirstAndLast() { +// let r = Int.random(in: 0..<1000) +// let a = [r] +// a.withUnsafeBufferPointer { +// let span = Span(_unsafeElements: $0) +// XCTAssertEqual(span.first, r) +// XCTAssertEqual(span.last, r) +// +// let emptySpan = span._extracting(0..<0) +// XCTAssertEqual(emptySpan.first, nil) +// XCTAssertEqual(emptySpan.last, nil) +// } +// } func testPrefix() { let capacity = 4 @@ -258,10 +248,10 @@ final class SpanTests: XCTestCase { a.withUnsafeBufferPointer { let span = Span(_unsafeElements: $0) XCTAssertEqual(span.count, capacity) - XCTAssertEqual(span._extracting(first: 1).last, 0) - XCTAssertEqual(span._extracting(first: capacity).last, capacity-1) - XCTAssertEqual(span._extracting(droppingLast: capacity).last, nil) - XCTAssertEqual(span._extracting(droppingLast: 1).last, capacity-2) + XCTAssertEqual(span._extracting(first: 1)[0], 0) + XCTAssertEqual(span._extracting(first: capacity)[capacity-1], capacity-1) + XCTAssertEqual(span._extracting(droppingLast: capacity).count, 0) + XCTAssertEqual(span._extracting(droppingLast: 1)[capacity-2], capacity-2) } do { @@ -279,11 +269,11 @@ final class SpanTests: XCTestCase { a.withUnsafeBufferPointer { let span = Span(_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,7 +282,8 @@ 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 @@ -337,22 +328,24 @@ final class SpanTests: XCTestCase { public func testBorrowing1() { let capacity = 8 - 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 +405,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 +439,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/FutureTests/StdlibOutputSpanExtensionTests.swift index 25d40d8a..9dc8e8e9 100644 --- a/Tests/FutureTests/StdlibOutputSpanExtensionTests.swift +++ b/Tests/FutureTests/StdlibOutputSpanExtensionTests.swift @@ -14,13 +14,14 @@ import XCTest import Foundation import Future +@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/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/_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) From 8cb5b628ae5d33c33dbe8b71a813bcdb095560f6 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 21 Feb 2025 19:13:29 -0800 Subject: [PATCH 02/30] Rename module to Span --- Package.swift | 8 ++++---- Sources/DequeModule/Deque+Collection.swift | 2 +- Sources/DequeModule/Deque+Container.swift | 2 +- Sources/DequeModule/Deque+Equatable.swift | 2 +- Sources/DequeModule/Deque.swift | 2 +- Sources/DequeModule/DynamicDeque.swift | 2 +- Sources/DequeModule/RigidDeque.swift | 2 +- Sources/DequeModule/_UnsafeDequeSegments.swift | 2 +- Sources/{Future => Span}/CMakeLists.txt | 3 ++- Sources/{Future => Span}/LifetimeOverride.swift | 0 Sources/{Future => Span}/MutableRawSpan.swift | 0 Sources/{Future => Span}/MutableSpan.swift | 0 Sources/{Future => Span}/MutableSpanSlicing.swift | 0 Sources/{Future => Span}/OutputSpan.swift | 0 Sources/{Future => Span}/SpanExtensions.swift | 0 Sources/{Future => Span}/StdlibOutputSpanExtensions.swift | 0 .../{Future => Span}/UnsafeBufferPointer+Additions.swift | 0 Tests/{FutureTests => SpanTests}/MutableSpanTests.swift | 2 +- Tests/{FutureTests => SpanTests}/OutputSpanTests.swift | 2 +- Tests/{FutureTests => SpanTests}/RawSpanTests.swift | 2 +- Tests/{FutureTests => SpanTests}/SpanTests.swift | 2 +- .../StdlibOutputSpanExtensionTests.swift | 2 +- 22 files changed, 18 insertions(+), 17 deletions(-) rename Sources/{Future => Span}/CMakeLists.txt (93%) rename Sources/{Future => Span}/LifetimeOverride.swift (100%) rename Sources/{Future => Span}/MutableRawSpan.swift (100%) rename Sources/{Future => Span}/MutableSpan.swift (100%) rename Sources/{Future => Span}/MutableSpanSlicing.swift (100%) rename Sources/{Future => Span}/OutputSpan.swift (100%) rename Sources/{Future => Span}/SpanExtensions.swift (100%) rename Sources/{Future => Span}/StdlibOutputSpanExtensions.swift (100%) rename Sources/{Future => Span}/UnsafeBufferPointer+Additions.swift (100%) rename Tests/{FutureTests => SpanTests}/MutableSpanTests.swift (99%) rename Tests/{FutureTests => SpanTests}/OutputSpanTests.swift (99%) rename Tests/{FutureTests => SpanTests}/RawSpanTests.swift (99%) rename Tests/{FutureTests => SpanTests}/SpanTests.swift (99%) rename Tests/{FutureTests => SpanTests}/StdlibOutputSpanExtensionTests.swift (99%) diff --git a/Package.swift b/Package.swift index ccd0adf2..f3de148f 100644 --- a/Package.swift +++ b/Package.swift @@ -217,13 +217,13 @@ let targets: [CustomTarget] = [ .target( kind: .exported, - name: "Future", + name: "Span", dependencies: ["InternalCollectionsUtilities"], exclude: ["CMakeLists.txt"]), .target( kind: .test, - name: "FutureTests", - dependencies: ["Future", "_CollectionsTestSupport"]), + name: "SpanTests", + dependencies: ["Span", "_CollectionsTestSupport"]), .target( kind: .exported, @@ -240,7 +240,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/CMakeLists.txt b/Sources/Span/CMakeLists.txt similarity index 93% rename from Sources/Future/CMakeLists.txt rename to Sources/Span/CMakeLists.txt index 9761e885..b85b0b5e 100644 --- a/Sources/Future/CMakeLists.txt +++ b/Sources/Span/CMakeLists.txt @@ -9,11 +9,12 @@ See https://swift.org/LICENSE.txt for license information add_library(Future "LifetimeOverride.swift" + "MutableRawSpan.swift" "MutableSpan.swift" + "MutableSpanSlicing.swift" "OutputSpan.swift" "SpanExtensions.swift" "StdlibOutputSpanExtensions.swift" - "StdlibSpanExtensions.swift" "UnsafeBufferPointer+Additions.swift" ) diff --git a/Sources/Future/LifetimeOverride.swift b/Sources/Span/LifetimeOverride.swift similarity index 100% rename from Sources/Future/LifetimeOverride.swift rename to Sources/Span/LifetimeOverride.swift diff --git a/Sources/Future/MutableRawSpan.swift b/Sources/Span/MutableRawSpan.swift similarity index 100% rename from Sources/Future/MutableRawSpan.swift rename to Sources/Span/MutableRawSpan.swift diff --git a/Sources/Future/MutableSpan.swift b/Sources/Span/MutableSpan.swift similarity index 100% rename from Sources/Future/MutableSpan.swift rename to Sources/Span/MutableSpan.swift diff --git a/Sources/Future/MutableSpanSlicing.swift b/Sources/Span/MutableSpanSlicing.swift similarity index 100% rename from Sources/Future/MutableSpanSlicing.swift rename to Sources/Span/MutableSpanSlicing.swift diff --git a/Sources/Future/OutputSpan.swift b/Sources/Span/OutputSpan.swift similarity index 100% rename from Sources/Future/OutputSpan.swift rename to Sources/Span/OutputSpan.swift diff --git a/Sources/Future/SpanExtensions.swift b/Sources/Span/SpanExtensions.swift similarity index 100% rename from Sources/Future/SpanExtensions.swift rename to Sources/Span/SpanExtensions.swift diff --git a/Sources/Future/StdlibOutputSpanExtensions.swift b/Sources/Span/StdlibOutputSpanExtensions.swift similarity index 100% rename from Sources/Future/StdlibOutputSpanExtensions.swift rename to Sources/Span/StdlibOutputSpanExtensions.swift 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/MutableSpanTests.swift b/Tests/SpanTests/MutableSpanTests.swift similarity index 99% rename from Tests/FutureTests/MutableSpanTests.swift rename to Tests/SpanTests/MutableSpanTests.swift index 9b351bae..a0e47e5e 100644 --- a/Tests/FutureTests/MutableSpanTests.swift +++ b/Tests/SpanTests/MutableSpanTests.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// import XCTest -import Future +import Span class ID { let id: Int diff --git a/Tests/FutureTests/OutputSpanTests.swift b/Tests/SpanTests/OutputSpanTests.swift similarity index 99% rename from Tests/FutureTests/OutputSpanTests.swift rename to Tests/SpanTests/OutputSpanTests.swift index 547037ac..c14bd0e5 100644 --- a/Tests/FutureTests/OutputSpanTests.swift +++ b/Tests/SpanTests/OutputSpanTests.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// import XCTest -import Future +import Span @available(macOS 9999, *) struct Allocation: ~Copyable { diff --git a/Tests/FutureTests/RawSpanTests.swift b/Tests/SpanTests/RawSpanTests.swift similarity index 99% rename from Tests/FutureTests/RawSpanTests.swift rename to Tests/SpanTests/RawSpanTests.swift index d5edf381..83425126 100644 --- a/Tests/FutureTests/RawSpanTests.swift +++ b/Tests/SpanTests/RawSpanTests.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// import XCTest -@testable import Future +@testable import Span @available(macOS 9999, *) final class RawSpanTests: XCTestCase { diff --git a/Tests/FutureTests/SpanTests.swift b/Tests/SpanTests/SpanTests.swift similarity index 99% rename from Tests/FutureTests/SpanTests.swift rename to Tests/SpanTests/SpanTests.swift index 805ba1cc..853602bf 100644 --- a/Tests/FutureTests/SpanTests.swift +++ b/Tests/SpanTests/SpanTests.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// import XCTest -import Future +import Span @available(macOS 9999, *) final class SpanTests: XCTestCase { diff --git a/Tests/FutureTests/StdlibOutputSpanExtensionTests.swift b/Tests/SpanTests/StdlibOutputSpanExtensionTests.swift similarity index 99% rename from Tests/FutureTests/StdlibOutputSpanExtensionTests.swift rename to Tests/SpanTests/StdlibOutputSpanExtensionTests.swift index 9dc8e8e9..b8508e7d 100644 --- a/Tests/FutureTests/StdlibOutputSpanExtensionTests.swift +++ b/Tests/SpanTests/StdlibOutputSpanExtensionTests.swift @@ -12,7 +12,7 @@ import XCTest import Foundation -import Future +import Span @available(macOS 9999, *) final class StdlibOutputSpanExtensionTests: XCTestCase { From 0131e7aae225f48fdd23ba60643bcac09dede810 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 24 Feb 2025 09:03:59 -0800 Subject: [PATCH 03/30] small fixes --- Sources/Span/MutableRawSpan.swift | 16 +++++++++++++--- Sources/Span/MutableSpan.swift | 1 + 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Sources/Span/MutableRawSpan.swift b/Sources/Span/MutableRawSpan.swift index 7b38f535..245a96f8 100644 --- a/Sources/Span/MutableRawSpan.swift +++ b/Sources/Span/MutableRawSpan.swift @@ -137,15 +137,25 @@ extension MutableRawSpan { } } +@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 = _overrideLifetime(span, borrowing: mutableSpan) + } +} + @available(macOS 9999, *) extension MutableRawSpan { public var bytes: RawSpan { @lifetime(borrow self) borrowing get { - let start = _start() - let span = RawSpan(_unsafeStart: start, byteCount: byteCount) - return _overrideLifetime(span, borrowing: self) + return RawSpan(_unsafeMutableRawSpan: self) } } diff --git a/Sources/Span/MutableSpan.swift b/Sources/Span/MutableSpan.swift index dfa709cb..c0001eb1 100644 --- a/Sources/Span/MutableSpan.swift +++ b/Sources/Span/MutableSpan.swift @@ -145,6 +145,7 @@ extension MutableSpan where Element: BitwiseCopyable { extension Span where Element: ~Copyable { @_alwaysEmitIntoClient + @lifetime(borrow mutableSpan) public init(_unsafeMutableSpan mutableSpan: borrowing MutableSpan) { let pointer = mutableSpan._pointer?.assumingMemoryBound(to: Element.self) let buffer = UnsafeBufferPointer(start: pointer, count: mutableSpan.count) From e352bf057cca4152c26898a87c04a30c90fdfed2 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 24 Feb 2025 09:11:03 -0800 Subject: [PATCH 04/30] adjust copyright years --- Sources/Span/MutableSpanSlicing.swift | 12 ++++++++++++ Sources/Span/StdlibOutputSpanExtensions.swift | 2 +- Tests/SpanTests/MutableSpanTests.swift | 2 +- Tests/SpanTests/OutputSpanTests.swift | 2 +- Tests/SpanTests/RawSpanTests.swift | 2 +- Tests/SpanTests/SpanTests.swift | 2 +- Tests/SpanTests/StdlibOutputSpanExtensionTests.swift | 2 +- 7 files changed, 18 insertions(+), 6 deletions(-) diff --git a/Sources/Span/MutableSpanSlicing.swift b/Sources/Span/MutableSpanSlicing.swift index dbd6c809..17ed2415 100644 --- a/Sources/Span/MutableSpanSlicing.swift +++ b/Sources/Span/MutableSpanSlicing.swift @@ -1,3 +1,15 @@ +//===--- 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 { diff --git a/Sources/Span/StdlibOutputSpanExtensions.swift b/Sources/Span/StdlibOutputSpanExtensions.swift index decf5d29..35a6e4ce 100644 --- a/Sources/Span/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 diff --git a/Tests/SpanTests/MutableSpanTests.swift b/Tests/SpanTests/MutableSpanTests.swift index a0e47e5e..8c76c2c7 100644 --- a/Tests/SpanTests/MutableSpanTests.swift +++ b/Tests/SpanTests/MutableSpanTests.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 diff --git a/Tests/SpanTests/OutputSpanTests.swift b/Tests/SpanTests/OutputSpanTests.swift index c14bd0e5..b24a0986 100644 --- a/Tests/SpanTests/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 diff --git a/Tests/SpanTests/RawSpanTests.swift b/Tests/SpanTests/RawSpanTests.swift index 83425126..51be5871 100644 --- a/Tests/SpanTests/RawSpanTests.swift +++ b/Tests/SpanTests/RawSpanTests.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 diff --git a/Tests/SpanTests/SpanTests.swift b/Tests/SpanTests/SpanTests.swift index 853602bf..bacc5630 100644 --- a/Tests/SpanTests/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 diff --git a/Tests/SpanTests/StdlibOutputSpanExtensionTests.swift b/Tests/SpanTests/StdlibOutputSpanExtensionTests.swift index b8508e7d..a8f88322 100644 --- a/Tests/SpanTests/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 From 5b81ead26c8ee6728c4b81938ec4e55d652c7997 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sat, 22 Feb 2025 05:37:49 -0800 Subject: [PATCH 05/30] simpler slicing --- Sources/Span/MutableSpanSlicing.swift | 67 ++++++++++++++++----------- 1 file changed, 39 insertions(+), 28 deletions(-) diff --git a/Sources/Span/MutableSpanSlicing.swift b/Sources/Span/MutableSpanSlicing.swift index 17ed2415..e6e4fb33 100644 --- a/Sources/Span/MutableSpanSlicing.swift +++ b/Sources/Span/MutableSpanSlicing.swift @@ -21,18 +21,42 @@ extension MutableSpan where Element: ~Copyable { UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count), "Index range out of bounds" ) - return extracting(unchecked: bounds) - } - - @lifetime(borrow self) - public mutating func extracting(unchecked bounds: Range) -> Self { - let delta = bounds.lowerBound &* MemoryLayout.stride - let newStart = _pointer?.advanced(by: delta) - let newSpan = MutableSpan(_unchecked: newStart, count: bounds.count) + let newSpan = MutableSpan(_unchecked: _start(), uncheckedBounds: bounds) return _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 = pointer.advanced(by: delta) + let newSpan = Self( + _unchecked: newStart, count: bounds.upperBound &- bounds.lowerBound + ) + self = _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 = _overrideLifetime(newSpan, borrowing: pointer) + } +} + //MARK: Option 2 extracting subscript @available(macOS 9999, *) extension MutableSpan where Element: ~Copyable { @@ -45,16 +69,7 @@ extension MutableSpan where Element: ~Copyable { UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count), "Index range out of bounds" ) - return self[extractingUnchecked: bounds] - } - } - - public subscript(extractingUnchecked bounds: Range) -> Self { - @lifetime(borrow self) - mutating get { - let delta = bounds.lowerBound &* MemoryLayout.stride - let newStart = _pointer?.advanced(by: delta) - let newSpan = MutableSpan(_unchecked: newStart, count: bounds.count) + let newSpan = MutableSpan(_unchecked: _start(), uncheckedBounds: bounds) return _overrideLifetime(newSpan, mutating: &self) } } @@ -94,10 +109,9 @@ extension SubMutableSpan where Element: ~Copyable { public var span: Span { @lifetime(borrow self) borrowing get { - let delta = offset &* MemoryLayout.stride - let newStart = base._pointer?.advanced(by: delta).assumingMemoryBound(to: Element.self) - let buffer = UnsafeBufferPointer(start: newStart, count: count) - let newSpan = Span(_unsafeElements: buffer) + let newSpan = Span( + _unchecked: base._start(), uncheckedBounds: offset..( - start: _start().assumingMemoryBound(to: Element.self), - count: bounds.upperBound + let prefix = Self( + _unchecked: _start(), uncheckedBounds: 0..(_unsafeElements: prefixBuffer) - var subSpan = SubMutableSpan(bounds.lowerBound, prefix) - subSpan.offset = bounds.lowerBound + let subSpan = SubMutableSpan(bounds.lowerBound, prefix) return _overrideLifetime(subSpan, mutating: &self) } } From f2aea0f8e6eff0e0a6bbc352ecd945acea911786 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 24 Feb 2025 09:11:13 -0800 Subject: [PATCH 06/30] separate slicing tests --- Tests/SpanTests/MutableSpanSlicing.swift | 144 +++++++++++++++++++++++ Tests/SpanTests/MutableSpanTests.swift | 130 -------------------- 2 files changed, 144 insertions(+), 130 deletions(-) create mode 100644 Tests/SpanTests/MutableSpanSlicing.swift diff --git a/Tests/SpanTests/MutableSpanSlicing.swift b/Tests/SpanTests/MutableSpanSlicing.swift new file mode 100644 index 00000000..60cfe4bd --- /dev/null +++ b/Tests/SpanTests/MutableSpanSlicing.swift @@ -0,0 +1,144 @@ +//===--- MutableSpanSlicing.swift -----------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import XCTest +import Span + +//MARK: slicing tests and examples +@available(macOS 9999, *) +extension MutableSpanTests { + + private func modify(_ s: inout MutableSpan) { + 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..) { - 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.. Date: Wed, 26 Feb 2025 16:31:33 -0800 Subject: [PATCH 07/30] update MutableSpan tests --- Tests/SpanTests/MutableSpanTests.swift | 101 +++++++++---------------- 1 file changed, 36 insertions(+), 65 deletions(-) diff --git a/Tests/SpanTests/MutableSpanTests.swift b/Tests/SpanTests/MutableSpanTests.swift index 2e413eab..eadfb81a 100644 --- a/Tests/SpanTests/MutableSpanTests.swift +++ b/Tests/SpanTests/MutableSpanTests.swift @@ -46,59 +46,21 @@ final class MutableSpanTests: XCTestCase { } a.withUnsafeMutableBytes { - let b = MutableSpan(_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) } @@ -162,14 +125,14 @@ final class MutableSpanTests: XCTestCase { XCTAssertEqual(Span(_unsafeMutableSpan: v1)._extracting(first: 3)._elementsEqual(Span(_unsafeMutableSpan: v1)._extracting(last: 3)), false) v1[0] = 0 -// -// let s = v1.storage -// var b = s.withUnsafeBufferPointer { Array($0) } -// b.withUnsafeMutableBufferPointer { -// let v2 = MutableSpan(_unsafeElements: $0) -// let equal = v1._elementsEqual(v2) -// XCTAssertEqual(equal, true) -// } + + let s = v1.span + var b = s.withUnsafeBufferPointer { Array($0) } + b.withUnsafeMutableBufferPointer { + let v2 = MutableSpan(_unsafeElements: $0) + let equal = v1._elementsEqual(v2) + XCTAssertEqual(equal, true) + } } } @@ -225,7 +188,7 @@ final class MutableSpanTests: XCTestCase { XCTAssertEqual(v[0], first) v[0].append("!") - XCTAssertEqual(v[0], first?.appending("!")) + XCTAssertEqual(v[0], first.map({$0+"!"})) } } @@ -408,13 +371,16 @@ final class MutableSpanTests: XCTestCase { a.withUnsafeMutableBufferPointer { let emptyPrefix = $0.prefix(0) var span = MutableSpan(_unsafeElements: emptyPrefix) - var update = span.update(fromContentsOf: []) + let update = span.update(fromContentsOf: []) XCTAssertEqual(update, 0) span = MutableSpan(_unsafeElements: $0) - let array = Array(0.. Date: Wed, 26 Feb 2025 16:31:43 -0800 Subject: [PATCH 08/30] add missing annotations --- Sources/Span/MutableSpan.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Sources/Span/MutableSpan.swift b/Sources/Span/MutableSpan.swift index c0001eb1..f890227f 100644 --- a/Sources/Span/MutableSpan.swift +++ b/Sources/Span/MutableSpan.swift @@ -510,6 +510,7 @@ extension MutableSpan where Element: ~Copyable { return buffer.count } + @_alwaysEmitIntoClient public mutating func moveUpdate( fromContentsOf source: UnsafeMutableBufferPointer ) -> Index { @@ -521,6 +522,7 @@ extension MutableSpan where Element: ~Copyable { @available(macOS 9999, *) extension MutableSpan { + @_alwaysEmitIntoClient public mutating func moveUpdate( fromContentsOf source: Slice> ) -> Index { From a9fdaef1ad25a27847a331da3cab9831cea89be1 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 26 Feb 2025 16:48:54 -0800 Subject: [PATCH 09/30] update test of swapAt() --- Tests/SpanTests/MutableSpanTests.swift | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/Tests/SpanTests/MutableSpanTests.swift b/Tests/SpanTests/MutableSpanTests.swift index eadfb81a..bcab9470 100644 --- a/Tests/SpanTests/MutableSpanTests.swift +++ b/Tests/SpanTests/MutableSpanTests.swift @@ -481,15 +481,14 @@ final class MutableSpanTests: XCTestCase { public func testSwapAt() { let count = 8 - let b = UnsafeMutableBufferPointer.allocate(capacity: count) - _ = b.initialize(fromContentsOf: 0.. Date: Thu, 27 Feb 2025 03:02:58 -0800 Subject: [PATCH 10/30] fix a parameter name --- Sources/Span/MutableRawSpan.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Sources/Span/MutableRawSpan.swift b/Sources/Span/MutableRawSpan.swift index 245a96f8..c78d39a8 100644 --- a/Sources/Span/MutableRawSpan.swift +++ b/Sources/Span/MutableRawSpan.swift @@ -30,10 +30,10 @@ public struct MutableRawSpan: ~Copyable & ~Escapable { @lifetime(borrow pointer) init( _unchecked pointer: UnsafeMutableRawPointer?, - count: Int + byteCount: Int ) { _pointer = pointer - _count = count + _count = byteCount } } @@ -48,7 +48,7 @@ extension MutableRawSpan { _unsafeBytes bytes: UnsafeMutableRawBufferPointer ) { let baseAddress = bytes.baseAddress - let span = MutableRawSpan(_unchecked: baseAddress, count: bytes.count) + let span = MutableRawSpan(_unchecked: baseAddress, byteCount: bytes.count) self = _overrideLifetime(span, borrowing: bytes) } @@ -67,7 +67,7 @@ extension MutableRawSpan { byteCount: Int ) { precondition(byteCount >= 0, "Count must not be negative") - self.init(_unchecked: pointer, count: byteCount) + self.init(_unchecked: pointer, byteCount: byteCount) } @lifetime(borrow elements) From 6808d4f0b51478716cb2ea9a4a82e9a4482fb261 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 27 Feb 2025 03:03:32 -0800 Subject: [PATCH 11/30] add extracting functions to MutableSpan and MutableRawSpan --- Sources/Span/MutableRawSpan.swift | 229 +++++++++++++++++++++++++++++ Sources/Span/MutableSpan.swift | 234 ++++++++++++++++++++++++++++++ 2 files changed, 463 insertions(+) diff --git a/Sources/Span/MutableRawSpan.swift b/Sources/Span/MutableRawSpan.swift index c78d39a8..c3291a5d 100644 --- a/Sources/Span/MutableRawSpan.swift +++ b/Sources/Span/MutableRawSpan.swift @@ -400,3 +400,232 @@ extension MutableRawSpan { update(startingAt: byteOffset, from: 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 _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 = _pointer?.advanced(by: bounds.lowerBound) + let newSpan = Self(_unchecked: newStart, byteCount: bounds.count) + return _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).clamped(to: byteOffsets)) + } + + @_alwaysEmitIntoClient + @lifetime(borrow self) + mutating public func _extracting(_ bounds: ClosedRange) -> Self { + let range = Range(uncheckedBounds: (bounds.lowerBound, bounds.upperBound+1)) + return _extracting(range) + } + + /// 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: some RangeExpression + ) -> Self { + _extracting( + unchecked: bounds.relative(to: byteOffsets).clamped(to: byteOffsets) + ) + } + + @_alwaysEmitIntoClient + @lifetime(borrow self) + mutating public func _extracting(unchecked bounds: ClosedRange) -> Self { + let range = Range(uncheckedBounds: (bounds.lowerBound, bounds.upperBound+1)) + return _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 _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 _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 _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 = _pointer?.advanced(by: byteCount &- newCount) + let newSpan = Self(_unchecked: newStart, byteCount: newCount) + return _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 = _pointer?.advanced(by: dropped) + let newSpan = Self(_unchecked: newStart, byteCount: byteCount &- dropped) + return _overrideLifetime(newSpan, mutating: &self) + } +} diff --git a/Sources/Span/MutableSpan.swift b/Sources/Span/MutableSpan.swift index f890227f..99834aae 100644 --- a/Sources/Span/MutableSpan.swift +++ b/Sources/Span/MutableSpan.swift @@ -614,3 +614,237 @@ extension MutableSpan 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 _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 = _pointer?.advanced(by: delta) + let newSpan = Self(_unchecked: newStart, count: bounds.count) + return _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).clamped(to: indices)) + } + + @_alwaysEmitIntoClient + @lifetime(borrow self) + mutating public func _extracting(_ bounds: ClosedRange) -> Self { + let range = Range(uncheckedBounds: (bounds.lowerBound, bounds.upperBound+1)) + return _extracting(range) + } + + /// 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: some RangeExpression + ) -> Self { + _extracting(unchecked: bounds.relative(to: indices).clamped(to: indices)) + } + + @_alwaysEmitIntoClient + @lifetime(borrow self) + mutating public func _extracting( + unchecked bounds: ClosedRange + ) -> Self { + let range = Range(uncheckedBounds: (bounds.lowerBound, bounds.upperBound+1)) + return _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 _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 _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 _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 = _pointer?.advanced(by: offset) + let newSpan = Self(_unchecked: newStart, count: newCount) + return _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 = _pointer?.advanced(by: offset) + let newSpan = Self(_unchecked: newStart, count: count &- droppedCount) + return _overrideLifetime(newSpan, mutating: &self) + } +} From f6eff9d7f7541cee398b9a079683d00ec78ac392 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 27 Feb 2025 21:09:22 -0800 Subject: [PATCH 12/30] Update OutputSpan --- Sources/Span/OutputSpan.swift | 69 ++++++++++------------------------- 1 file changed, 19 insertions(+), 50 deletions(-) diff --git a/Sources/Span/OutputSpan.swift b/Sources/Span/OutputSpan.swift index 413a4c49..9bb2a8b6 100644 --- a/Sources/Span/OutputSpan.swift +++ b/Sources/Span/OutputSpan.swift @@ -15,15 +15,18 @@ @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 { + _pointer.unsafelyUnwrapped + } @_alwaysEmitIntoClient public var available: Int { capacity &- _initialized } @@ -36,16 +39,16 @@ public struct OutputSpan: ~Copyable, ~Escapable { deinit { if _initialized > 0 { - _start.withMemoryRebound(to: Element.self, capacity: _initialized) { + _start().withMemoryRebound(to: Element.self, capacity: _initialized) { [ workaround = _initialized ] in _ = $0.deinitialize(count: workaround) } } } - @usableFromInline @inline(__always) @lifetime(borrow start) - init( + @_alwaysEmitIntoClient + internal init( _unchecked start: UnsafeMutableRawPointer?, capacity: Int, initialized: Int @@ -65,7 +68,7 @@ extension OutputSpan where Element: ~Copyable { @usableFromInline @inline(__always) @lifetime(borrow buffer) - init( + internal init( _unchecked buffer: UnsafeMutableBufferPointer, initialized: Int ) { @@ -172,7 +175,7 @@ extension OutputSpan where Element: ~Copyable { @_alwaysEmitIntoClient public mutating func append(_ value: consuming Element) { precondition(_initialized < capacity, "Output buffer overflow") - let p = _start.advanced(by: _initialized&*MemoryLayout.stride) + let p = _start().advanced(by: _initialized&*MemoryLayout.stride) p.initializeMemory(as: Element.self, to: value) _initialized &+= 1 } @@ -181,13 +184,13 @@ extension OutputSpan where Element: ~Copyable { public mutating func deinitializeLastElement() -> Element? { guard _initialized > 0 else { return nil } _initialized &-= 1 - let p = _start.advanced(by: _initialized&*MemoryLayout.stride) + let p = _start().advanced(by: _initialized&*MemoryLayout.stride) return p.withMemoryRebound(to: Element.self, capacity: 1, { $0.move() }) } @_alwaysEmitIntoClient public mutating func deinitialize() { - _ = _start.withMemoryRebound(to: Element.self, capacity: _initialized) { + _ = _start().withMemoryRebound(to: Element.self, capacity: _initialized) { $0.deinitialize(count: _initialized) } _initialized = 0 @@ -206,7 +209,7 @@ extension OutputSpan { "destination span cannot contain number of elements requested." ) let offset = _initialized&*MemoryLayout.stride - let p = _start.advanced(by: offset) + let p = _start().advanced(by: offset) p.withMemoryRebound(to: Element.self, capacity: count) { $0.initialize(repeating: repeatedValue, count: count) } @@ -228,7 +231,7 @@ extension OutputSpan { ) { while _initialized < capacity { guard let element = elements.next() else { break } - let p = _start.advanced(by: _initialized&*MemoryLayout.stride) + let p = _start().advanced(by: _initialized&*MemoryLayout.stride) p.initializeMemory(as: Element.self, to: element) _initialized &+= 1 } @@ -239,18 +242,14 @@ 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 = _start().advanced(by: _initialized&*MemoryLayout.stride) var (iterator, copied) = tail.withMemoryRebound(to: Element.self, capacity: available) { let suffix = UnsafeMutableBufferPointer(start: $0, count: available) @@ -264,23 +263,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 @_alwaysEmitIntoClient public mutating func append( fromContentsOf source: Span @@ -290,7 +272,7 @@ extension OutputSpan { source.count <= available, "destination span cannot contain every element from source." ) - let tail = _start.advanced(by: _initialized&*MemoryLayout.stride) + let tail = _start().advanced(by: _initialized&*MemoryLayout.stride) _ = source.withUnsafeBufferPointer { tail.initializeMemory( as: Element.self, from: $0.baseAddress!, count: $0.count @@ -319,7 +301,7 @@ extension OutputSpan where Element: ~Copyable { ) let buffer = source.relinquishBorrowedMemory() // we must now deinitialize the returned UMBP - let tail = _start.advanced(by: _initialized&*MemoryLayout.stride) + let tail = _start().advanced(by: _initialized&*MemoryLayout.stride) tail.moveInitializeMemory( as: Element.self, from: buffer.baseAddress!, count: buffer.count ) @@ -330,21 +312,8 @@ extension OutputSpan where Element: ~Copyable { 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 } } From 5d5384c4620abd3dafc80a893ea403bed9b911a5 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 27 Feb 2025 21:09:38 -0800 Subject: [PATCH 13/30] update OutputSpanTests --- Tests/SpanTests/OutputSpanTests.swift | 42 ++++++++++++++++++++------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/Tests/SpanTests/OutputSpanTests.swift b/Tests/SpanTests/OutputSpanTests.swift index b24a0986..883fc6c3 100644 --- a/Tests/SpanTests/OutputSpanTests.swift +++ b/Tests/SpanTests/OutputSpanTests.swift @@ -68,7 +68,7 @@ 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() } @@ -79,6 +79,17 @@ 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 @@ -154,16 +180,12 @@ final class OutputSpanTests: XCTestCase { var a = Allocation(of: 48, Int.self) let c = 24 a.initialize { - let array = Array(0..(_unsafeElements: .init(start: nil, count: 0)) - $0.append(fromContentsOf: storage) + os in + var array = Array(0.. Date: Thu, 27 Feb 2025 21:10:43 -0800 Subject: [PATCH 14/30] add a note --- Sources/Span/OutputSpan.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/Span/OutputSpan.swift b/Sources/Span/OutputSpan.swift index 9bb2a8b6..6b8420b7 100644 --- a/Sources/Span/OutputSpan.swift +++ b/Sources/Span/OutputSpan.swift @@ -330,7 +330,7 @@ extension OutputSpan { @available(macOS 9999, *) extension OutputSpan where Element: BitwiseCopyable { - +// TODO: alternative append() implementations for BitwiseCopyable elements } @available(macOS 9999, *) From 4334415fc0f7d1f5594e60661d7d3d27af4559e9 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 28 Feb 2025 09:12:24 -0800 Subject: [PATCH 15/30] annotation cleanup --- Sources/Span/OutputSpan.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/Span/OutputSpan.swift b/Sources/Span/OutputSpan.swift index 6b8420b7..61251abc 100644 --- a/Sources/Span/OutputSpan.swift +++ b/Sources/Span/OutputSpan.swift @@ -46,8 +46,8 @@ public struct OutputSpan: ~Copyable, ~Escapable { } } - @lifetime(borrow start) @_alwaysEmitIntoClient + @lifetime(borrow start) internal init( _unchecked start: UnsafeMutableRawPointer?, capacity: Int, @@ -66,7 +66,7 @@ extension OutputSpan: Sendable {} @available(macOS 9999, *) extension OutputSpan where Element: ~Copyable { - @usableFromInline @inline(__always) + @_alwaysEmitIntoClient @lifetime(borrow buffer) internal init( _unchecked buffer: UnsafeMutableBufferPointer, From 81699ed60f30c9e8524ed52463154d2f2d8af497 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 28 Feb 2025 10:54:22 -0800 Subject: [PATCH 16/30] test tweaks --- Tests/SpanTests/RawSpanTests.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/SpanTests/RawSpanTests.swift b/Tests/SpanTests/RawSpanTests.swift index 51be5871..874af754 100644 --- a/Tests/SpanTests/RawSpanTests.swift +++ b/Tests/SpanTests/RawSpanTests.swift @@ -104,7 +104,7 @@ final class RawSpanTests: XCTestCase { } } - func testSubscript() { + func testExtracting() { let capacity = 4 let b = (0.. Date: Tue, 4 Mar 2025 16:39:35 -0800 Subject: [PATCH 17/30] `storeBytes()` must be `mutating` --- Sources/Span/MutableRawSpan.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/Span/MutableRawSpan.swift b/Sources/Span/MutableRawSpan.swift index c3291a5d..f3bc49f7 100644 --- a/Sources/Span/MutableRawSpan.swift +++ b/Sources/Span/MutableRawSpan.swift @@ -295,7 +295,7 @@ extension MutableRawSpan { } @_alwaysEmitIntoClient - public func storeBytes( + public mutating func storeBytes( of value: T, toByteOffset offset: Int = 0, as type: T.Type ) { precondition( @@ -308,7 +308,7 @@ extension MutableRawSpan { @unsafe @_alwaysEmitIntoClient - public func storeBytes( + public mutating func storeBytes( of value: T, toUncheckedByteOffset offset: Int, as type: T.Type ) { _start().storeBytes(of: value, toByteOffset: offset, as: type) From 91526b4e513742ee42a623b5ec55c491cb347807 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 4 Mar 2025 16:40:30 -0800 Subject: [PATCH 18/30] update bulk-copy operations for MutableRawSpan --- Sources/Span/MutableRawSpan.swift | 45 +++++++++++++++---------------- 1 file changed, 21 insertions(+), 24 deletions(-) diff --git a/Sources/Span/MutableRawSpan.swift b/Sources/Span/MutableRawSpan.swift index f3bc49f7..a50b7a0a 100644 --- a/Sources/Span/MutableRawSpan.swift +++ b/Sources/Span/MutableRawSpan.swift @@ -319,20 +319,20 @@ extension MutableRawSpan { @available(macOS 9999, *) extension MutableRawSpan { + @_alwaysEmitIntoClient public mutating func update( - startingAt byteOffset: Int = 0, from source: S ) -> (unwritten: S.Iterator, byteOffset: Int) where S.Element: BitwiseCopyable { var iterator = source.makeIterator() - let offset = update(startingAt: byteOffset, from: &iterator) + let offset = update(from: &iterator) return (iterator, offset) } + @_alwaysEmitIntoClient public mutating func update( - startingAt byteOffset: Int = 0, from elements: inout some IteratorProtocol ) -> Int { - var offset = byteOffset + var offset = 0 while offset + MemoryLayout.stride <= _count { guard let element = elements.next() else { break } storeBytes(of: element, toUncheckedByteOffset: offset, as: Element.self) @@ -341,19 +341,17 @@ extension MutableRawSpan { return offset } + @_alwaysEmitIntoClient public mutating func update( - startingAt byteOffset: Int = 0, fromContentsOf source: C ) -> Int where C.Element: BitwiseCopyable { let newOffset = source.withContiguousStorageIfAvailable { - self.update( - startingAt: byteOffset, fromContentsOf: Span(_unsafeElements: $0) - ) + self.update(fromContentsOf: RawSpan(_unsafeElements: $0)) } if let newOffset { return newOffset } var elements = source.makeIterator() - let lastOffset = update(startingAt: byteOffset, from: &elements) + let lastOffset = update(from: &elements) precondition( elements.next() == nil, "destination span cannot contain every element from source." @@ -361,43 +359,42 @@ extension MutableRawSpan { return lastOffset } + @_alwaysEmitIntoClient public mutating func update( - startingAt byteOffset: Int = 0, fromContentsOf source: Span ) -> Int { -// update(startingAt: byteOffset, from: source.bytes) +// update(from: source.bytes) source.withUnsafeBytes { - update(startingAt: byteOffset, fromContentsOf: $0) + update(fromContentsOf: $0) } } + @_alwaysEmitIntoClient public mutating func update( - startingAt byteOffset: Int = 0, fromContentsOf source: borrowing MutableSpan ) -> Int { -// update(startingAt: byteOffset, from: source.storage.bytes) +// update(from: source.span.bytes) source.withUnsafeBytes { - update(startingAt: byteOffset, fromContentsOf: $0) + update(fromContentsOf: $0) } } + @_alwaysEmitIntoClient public mutating func update( - startingAt byteOffset: Int = 0, - from source: RawSpan + fromContentsOf source: RawSpan ) -> Int { - if source.byteCount == 0 { return byteOffset } + if source.byteCount == 0 { return 0 } source.withUnsafeBytes { - _start().advanced(by: byteOffset) - .copyMemory(from: $0.baseAddress!, byteCount: $0.count) + _start().copyMemory(from: $0.baseAddress!, byteCount: $0.count) } - return byteOffset &+ source.byteCount + return source.byteCount } + @_alwaysEmitIntoClient public mutating func update( - startingAt byteOffset: Int = 0, - from source: borrowing MutableRawSpan + fromContentsOf source: borrowing MutableRawSpan ) -> Int { - update(startingAt: byteOffset, from: source.bytes) + update(fromContentsOf: source.bytes) } } From e299604433ac5385559a53b68ecd21f9c8100881 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 4 Mar 2025 16:40:46 -0800 Subject: [PATCH 19/30] trim the set of `extracting()` functions --- Sources/Span/MutableRawSpan.swift | 17 ----------------- Sources/Span/MutableSpan.swift | 15 --------------- 2 files changed, 32 deletions(-) diff --git a/Sources/Span/MutableRawSpan.swift b/Sources/Span/MutableRawSpan.swift index a50b7a0a..e626be83 100644 --- a/Sources/Span/MutableRawSpan.swift +++ b/Sources/Span/MutableRawSpan.swift @@ -469,13 +469,6 @@ extension MutableRawSpan { _extracting(bounds.relative(to: byteOffsets).clamped(to: byteOffsets)) } - @_alwaysEmitIntoClient - @lifetime(borrow self) - mutating public func _extracting(_ bounds: ClosedRange) -> Self { - let range = Range(uncheckedBounds: (bounds.lowerBound, bounds.upperBound+1)) - return _extracting(range) - } - /// Constructs a new span over the items within the supplied range of /// positions within this span. /// @@ -492,16 +485,6 @@ extension MutableRawSpan { /// /// - Complexity: O(1) @unsafe - @_alwaysEmitIntoClient - @lifetime(borrow self) - mutating public func _extracting( - unchecked bounds: some RangeExpression - ) -> Self { - _extracting( - unchecked: bounds.relative(to: byteOffsets).clamped(to: byteOffsets) - ) - } - @_alwaysEmitIntoClient @lifetime(borrow self) mutating public func _extracting(unchecked bounds: ClosedRange) -> Self { diff --git a/Sources/Span/MutableSpan.swift b/Sources/Span/MutableSpan.swift index 99834aae..5c9ca4c6 100644 --- a/Sources/Span/MutableSpan.swift +++ b/Sources/Span/MutableSpan.swift @@ -689,13 +689,6 @@ extension MutableSpan where Element: ~Copyable { _extracting(bounds.relative(to: indices).clamped(to: indices)) } - @_alwaysEmitIntoClient - @lifetime(borrow self) - mutating public func _extracting(_ bounds: ClosedRange) -> Self { - let range = Range(uncheckedBounds: (bounds.lowerBound, bounds.upperBound+1)) - return _extracting(range) - } - /// Constructs a new span over the items within the supplied range of /// positions within this span. /// @@ -712,14 +705,6 @@ extension MutableSpan where Element: ~Copyable { /// /// - Complexity: O(1) @unsafe - @_alwaysEmitIntoClient - @lifetime(borrow self) - mutating public func _extracting( - unchecked bounds: some RangeExpression - ) -> Self { - _extracting(unchecked: bounds.relative(to: indices).clamped(to: indices)) - } - @_alwaysEmitIntoClient @lifetime(borrow self) mutating public func _extracting( From 0b4c812e0f42f1299bb1c632e3210377fa8e268e Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 24 Feb 2025 09:04:46 -0800 Subject: [PATCH 20/30] add `MutableRawSpan` tests --- Tests/SpanTests/MutableRawSpanTests.swift | 356 ++++++++++++++++++++++ 1 file changed, 356 insertions(+) create mode 100644 Tests/SpanTests/MutableRawSpanTests.swift 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.. Date: Tue, 4 Mar 2025 17:00:34 -0800 Subject: [PATCH 21/30] complete `MutableSpan` tests --- Tests/SpanTests/MutableSpanTests.swift | 99 ++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/Tests/SpanTests/MutableSpanTests.swift b/Tests/SpanTests/MutableSpanTests.swift index bcab9470..a830fcdd 100644 --- a/Tests/SpanTests/MutableSpanTests.swift +++ b/Tests/SpanTests/MutableSpanTests.swift @@ -491,4 +491,103 @@ final class MutableSpanTests: XCTestCase { XCTAssertEqual(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) + } + } } From c37a48dff1b2d1eb801fd84aabfcb4c0462971ff Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 4 Mar 2025 17:41:55 -0800 Subject: [PATCH 22/30] enable strict memory safety --- Package.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index f3de148f..540dbfc3 100644 --- a/Package.swift +++ b/Package.swift @@ -219,7 +219,9 @@ let targets: [CustomTarget] = [ kind: .exported, name: "Span", dependencies: ["InternalCollectionsUtilities"], - exclude: ["CMakeLists.txt"]), + exclude: ["CMakeLists.txt"], + settings: _sharedSettings + [.unsafeFlags(["-Xfrontend", "-strict-memory-safety"])], + ), .target( kind: .test, name: "SpanTests", From cd48e83c46e2f1e4f73143443ae831692fed3292 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 4 Mar 2025 17:42:17 -0800 Subject: [PATCH 23/30] add required unsafe annotations to `MutableSpan` --- Sources/Span/MutableSpan.swift | 179 +++++++++++++++++++-------------- 1 file changed, 102 insertions(+), 77 deletions(-) diff --git a/Sources/Span/MutableSpan.swift b/Sources/Span/MutableSpan.swift index 5c9ca4c6..9e0ba01a 100644 --- a/Sources/Span/MutableSpan.swift +++ b/Sources/Span/MutableSpan.swift @@ -14,26 +14,29 @@ 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 let _pointer: UnsafeMutableRawPointer? + @usableFromInline + internal let _pointer: UnsafeMutableRawPointer? - @usableFromInline let _count: Int + @usableFromInline + internal let _count: Int @_alwaysEmitIntoClient internal func _start() -> UnsafeMutableRawPointer { - _pointer.unsafelyUnwrapped + unsafe _pointer.unsafelyUnwrapped } - @usableFromInline @inline(__always) + @_alwaysEmitIntoClient @lifetime(borrow start) - init( + internal init( _unchecked start: UnsafeMutableRawPointer?, count: Int ) { - _pointer = start + _pointer = unsafe start _count = count } } @@ -44,7 +47,7 @@ extension MutableSpan: @unchecked Sendable where Element: Sendable {} @available(macOS 9999, *) extension MutableSpan where Element: ~Copyable { - @usableFromInline @inline(__always) + @usableFromInline @lifetime(borrow elements) internal init( _unchecked elements: UnsafeMutableBufferPointer @@ -58,13 +61,13 @@ extension MutableSpan where Element: ~Copyable { public init( _unsafeElements buffer: UnsafeMutableBufferPointer ) { - precondition( + unsafe precondition( ((Int(bitPattern: buffer.baseAddress) & - (MemoryLayout.alignment&-1)) == 0), + (MemoryLayout.alignment &- 1)) == 0), "baseAddress must be properly aligned to access Element" ) let ms = MutableSpan(_unchecked: buffer) - self = _overrideLifetime(ms, borrowing: buffer) + self = unsafe _overrideLifetime(ms, borrowing: buffer) } @_alwaysEmitIntoClient @@ -74,9 +77,9 @@ extension MutableSpan where Element: ~Copyable { count: Int ) { precondition(count >= 0, "Count must not be negative") - let buffer = UnsafeMutableBufferPointer(start: start, count: count) + let buffer = unsafe UnsafeMutableBufferPointer(start: start, count: count) let ms = MutableSpan(_unsafeElements: buffer) - self = _overrideLifetime(ms, borrowing: start) + self = unsafe _overrideLifetime(ms, borrowing: start) } } @@ -88,9 +91,9 @@ extension MutableSpan { public init( _unsafeElements elements: borrowing Slice> ) { - let rb = UnsafeMutableBufferPointer(rebasing: elements) + let rb = unsafe UnsafeMutableBufferPointer(rebasing: elements) let ms = MutableSpan(_unsafeElements: rb) - self = _overrideLifetime(ms, borrowing: elements) + self = unsafe _overrideLifetime(ms, borrowing: elements) } } @@ -102,20 +105,20 @@ extension MutableSpan where Element: BitwiseCopyable { public init( _unsafeBytes buffer: UnsafeMutableRawBufferPointer ) { - precondition( + unsafe precondition( ((Int(bitPattern: buffer.baseAddress) & - (MemoryLayout.alignment&-1)) == 0), + (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 = UnsafeMutableBufferPointer( + let elements = unsafe UnsafeMutableBufferPointer( start: buffer.baseAddress?.assumingMemoryBound(to: Element.self), count: count ) let ms = MutableSpan(_unsafeElements: elements) - self = _overrideLifetime(ms, borrowing: buffer) + self = unsafe _overrideLifetime(ms, borrowing: buffer) } @_alwaysEmitIntoClient @@ -125,9 +128,11 @@ extension MutableSpan where Element: BitwiseCopyable { byteCount: Int ) { precondition(byteCount >= 0, "Count must not be negative") - let bytes = UnsafeMutableRawBufferPointer(start: pointer, count: byteCount) + let bytes = unsafe UnsafeMutableRawBufferPointer( + start: pointer, count: byteCount + ) let ms = MutableSpan(_unsafeBytes: bytes) - self = _overrideLifetime(ms, borrowing: pointer) + self = unsafe _overrideLifetime(ms, borrowing: pointer) } @_alwaysEmitIntoClient @@ -135,9 +140,9 @@ extension MutableSpan where Element: BitwiseCopyable { public init( _unsafeBytes buffer: borrowing Slice ) { - let bytes = UnsafeMutableRawBufferPointer(rebasing: buffer) + let bytes = unsafe UnsafeMutableRawBufferPointer(rebasing: buffer) let ms = MutableSpan(_unsafeBytes: bytes) - self = _overrideLifetime(ms, borrowing: buffer) + self = unsafe _overrideLifetime(ms, borrowing: buffer) } } @@ -147,10 +152,13 @@ extension Span where Element: ~Copyable { @_alwaysEmitIntoClient @lifetime(borrow mutableSpan) public init(_unsafeMutableSpan mutableSpan: borrowing MutableSpan) { - let pointer = mutableSpan._pointer?.assumingMemoryBound(to: Element.self) - let buffer = UnsafeBufferPointer(start: pointer, count: mutableSpan.count) + let pointer = + unsafe mutableSpan._pointer?.assumingMemoryBound(to: Element.self) + let buffer = unsafe UnsafeBufferPointer( + start: pointer, count: mutableSpan.count + ) let span = Span(_unsafeElements: buffer) - self = _overrideLifetime(span, borrowing: mutableSpan) + self = unsafe _overrideLifetime(span, borrowing: mutableSpan) } } @@ -175,9 +183,9 @@ extension RawSpan { ) { let pointer = mutableSpan._pointer let byteCount = mutableSpan.count &* MemoryLayout.stride - let buffer = UnsafeRawBufferPointer(start: pointer, count: byteCount) + let buffer = unsafe UnsafeRawBufferPointer(start: pointer, count: byteCount) let rawSpan = RawSpan(_unsafeBytes: buffer) - self = _overrideLifetime(rawSpan, borrowing: mutableSpan) + self = unsafe _overrideLifetime(rawSpan, borrowing: mutableSpan) } } @@ -210,7 +218,9 @@ extension MutableSpan where Element: ~Copyable { @_alwaysEmitIntoClient public var _description: String { - let addr = String(UInt(bitPattern: _pointer), radix: 16, uppercase: false) + let addr = String( + unsafe UInt(bitPattern: _pointer), radix: 16, uppercase: false + ) return "(0x\(addr), \(_count))" } } @@ -229,7 +239,7 @@ extension MutableSpan where Element: ~Copyable & ~Escapable { @_alwaysEmitIntoClient public var indices: Range { - Range(uncheckedBounds: (0, _count)) + unsafe Range(uncheckedBounds: (0, _count)) } } @@ -261,11 +271,11 @@ extension MutableSpan where Element: ~Copyable { public subscript(_ position: Index) -> Element { unsafeAddress { precondition(indices.contains(position), "index out of bounds") - return UnsafePointer(_unsafeAddressOfElement(unchecked: position)) + return unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: position)) } unsafeMutableAddress { precondition(indices.contains(position), "index out of bounds") - return _unsafeAddressOfElement(unchecked: position) + return unsafe _unsafeAddressOfElement(unchecked: position) } } @@ -277,13 +287,14 @@ extension MutableSpan where Element: ~Copyable { /// must be greater or equal to zero, and less than `count`. /// /// - Complexity: O(1) + @unsafe @_alwaysEmitIntoClient public subscript(unchecked position: Index) -> Element { unsafeAddress { - UnsafePointer(_unsafeAddressOfElement(unchecked: position)) + unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: position)) } unsafeMutableAddress { - _unsafeAddressOfElement(unchecked: position) + unsafe _unsafeAddressOfElement(unchecked: position) } } @@ -293,8 +304,8 @@ extension MutableSpan where Element: ~Copyable { unchecked position: Index ) -> UnsafeMutablePointer { let elementOffset = position &* MemoryLayout.stride - let address = _start().advanced(by: elementOffset) - return address.assumingMemoryBound(to: Element.self) + let address = unsafe _start().advanced(by: elementOffset) + return unsafe address.assumingMemoryBound(to: Element.self) } } @@ -305,16 +316,17 @@ extension MutableSpan where Element: ~Copyable { public mutating func swapAt(_ i: Index, _ j: Index) { precondition(indices.contains(Index(i))) precondition(indices.contains(Index(j))) - swapAt(unchecked: i, unchecked: j) + unsafe swapAt(unchecked: i, unchecked: j) } + @unsafe @_alwaysEmitIntoClient public mutating func swapAt(unchecked i: Index, unchecked j: Index) { - let pi = _unsafeAddressOfElement(unchecked: i) - let pj = _unsafeAddressOfElement(unchecked: j) - let temporary = pi.move() - pi.initialize(to: pj.move()) - pj.initialize(to: consume temporary) + 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) } } @@ -331,11 +343,11 @@ extension MutableSpan where Element: BitwiseCopyable { public subscript(_ position: Index) -> Element { get { precondition(indices.contains(position), "index out of bounds") - return self[unchecked: position] + return unsafe self[unchecked: position] } set { precondition(indices.contains(position), "index out of bounds") - self[unchecked: position] = newValue + unsafe self[unchecked: position] = newValue } } @@ -347,15 +359,20 @@ extension MutableSpan where Element: BitwiseCopyable { /// 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 _start().loadUnaligned(fromByteOffset: offset, as: Element.self) + return unsafe _start().loadUnaligned( + fromByteOffset: offset, as: Element.self + ) } set { let offset = position&*MemoryLayout.stride - _start().storeBytes(of: newValue, toByteOffset: offset, as: Element.self) + unsafe _start().storeBytes( + of: newValue, toByteOffset: offset, as: Element.self + ) } } } @@ -373,18 +390,20 @@ extension MutableSpan where Element: ~Copyable { //FIXME: mark closure parameter as non-escaping @_alwaysEmitIntoClient - public mutating func withUnsafeMutableBufferPointer( + 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 body(.init(start: nil, count: 0)) + 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 body(.init(start: .init(pointer._rawValue), count: count)) + return try unsafe body(.init(start: .init(pointer._rawValue), count: count)) } } @@ -404,11 +423,11 @@ extension MutableSpan where Element: BitwiseCopyable { public mutating func withUnsafeMutableBytes( _ body: (_ buffer: UnsafeMutableRawBufferPointer) throws(E) -> Result ) throws(E) -> Result { - let bytes = UnsafeMutableRawBufferPointer( + let bytes = unsafe UnsafeMutableRawBufferPointer( start: (_count == 0) ? nil : _start(), count: _count &* MemoryLayout.stride ) - return try body(bytes) + return try unsafe body(bytes) } } @@ -418,8 +437,8 @@ extension MutableSpan { @_alwaysEmitIntoClient public mutating func update(repeating repeatedValue: consuming Element) { - _start().withMemoryRebound(to: Element.self, capacity: count) { - $0.update(repeating: repeatedValue, count: count) + unsafe _start().withMemoryRebound(to: Element.self, capacity: count) { + unsafe $0.update(repeating: repeatedValue, count: count) } } @@ -439,7 +458,7 @@ extension MutableSpan { var index = 0 while index < _count { guard let element = elements.next() else { break } - self[unchecked: index] = element + unsafe self[unchecked: index] = element index &+= 1 } return index @@ -474,9 +493,11 @@ extension MutableSpan { source.count <= self.count, "destination span cannot contain every element from source." ) - _start().withMemoryRebound(to: Element.self, capacity: source.count) { dest in + unsafe _start().withMemoryRebound( + to: Element.self, capacity: source.count + ) { dest in source.withUnsafeBufferPointer { - dest.update(from: $0.baseAddress!, count: $0.count) + unsafe dest.update(from: $0.baseAddress!, count: $0.count) } } return source.count @@ -502,9 +523,9 @@ extension MutableSpan where Element: ~Copyable { source.count <= self.count, "destination span cannot contain every element from source." ) - let buffer = source.relinquishBorrowedMemory() + let buffer = unsafe source.relinquishBorrowedMemory() // we must now deinitialize the returned UMBP - _start().moveInitializeMemory( + unsafe _start().moveInitializeMemory( as: Element.self, from: buffer.baseAddress!, count: buffer.count ) return buffer.count @@ -514,8 +535,8 @@ extension MutableSpan where Element: ~Copyable { public mutating func moveUpdate( fromContentsOf source: UnsafeMutableBufferPointer ) -> Index { - let source = OutputSpan(_initializing: source, initialized: source.count) - return self.moveUpdate(fromContentsOf: source) + let s = unsafe OutputSpan(_initializing: source, initialized: source.count) + return self.moveUpdate(fromContentsOf: s) } } @@ -526,7 +547,7 @@ extension MutableSpan { public mutating func moveUpdate( fromContentsOf source: Slice> ) -> Index { - self.moveUpdate(fromContentsOf: .init(rebasing: source)) + self.moveUpdate(fromContentsOf: unsafe .init(rebasing: source)) } } @@ -541,7 +562,8 @@ extension MutableSpan where Element: BitwiseCopyable { // 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) + let rebound = unsafe UnsafeMutablePointer(rp) + unsafe rebound.update(repeating: repeatedValue, count: count) Builtin.rebindMemory(rp, binding) } @@ -562,7 +584,7 @@ extension MutableSpan where Element: BitwiseCopyable { var index = 0 while index < _count { guard let element = elements.next() else { break } - self[unchecked: index] = element + unsafe self[unchecked: index] = element index &+= 1 } return index @@ -600,8 +622,9 @@ extension MutableSpan where Element: BitwiseCopyable { "destination span cannot contain every element from source." ) source.withUnsafeBufferPointer { - _start().copyMemory( - from: $0.baseAddress!, byteCount: $0.count&*MemoryLayout.stride + unsafe _start().copyMemory( + from: $0.baseAddress!, + byteCount: $0.count &* MemoryLayout.stride ) } return source.count @@ -640,7 +663,7 @@ extension MutableSpan where Element: ~Copyable { UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count), "Index range out of bounds" ) - return _extracting(unchecked: bounds) + return unsafe _extracting(unchecked: bounds) } /// Constructs a new span over the items within the supplied range of @@ -663,9 +686,9 @@ extension MutableSpan where Element: ~Copyable { @lifetime(borrow self) mutating public func _extracting(unchecked bounds: Range) -> Self { let delta = bounds.lowerBound &* MemoryLayout.stride - let newStart = _pointer?.advanced(by: delta) + let newStart = unsafe _pointer?.advanced(by: delta) let newSpan = Self(_unchecked: newStart, count: bounds.count) - return _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } /// Constructs a new span over the items within the supplied range of @@ -686,7 +709,7 @@ extension MutableSpan where Element: ~Copyable { mutating public func _extracting( _ bounds: some RangeExpression ) -> Self { - _extracting(bounds.relative(to: indices).clamped(to: indices)) + _extracting(bounds.relative(to: indices)) } /// Constructs a new span over the items within the supplied range of @@ -710,8 +733,10 @@ extension MutableSpan where Element: ~Copyable { mutating public func _extracting( unchecked bounds: ClosedRange ) -> Self { - let range = Range(uncheckedBounds: (bounds.lowerBound, bounds.upperBound+1)) - return _extracting(unchecked: range) + 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. @@ -727,7 +752,7 @@ extension MutableSpan where Element: ~Copyable { @lifetime(borrow self) mutating public func _extracting(_: UnboundedRange) -> Self { let newSpan = Self(_unchecked: _start(), count: _count) - return _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } } @@ -756,7 +781,7 @@ extension MutableSpan where Element: ~Copyable { precondition(maxLength >= 0, "Can't have a prefix of negative length") let newCount = min(maxLength, count) let newSpan = Self(_unchecked: _pointer, count: newCount) - return _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } /// Returns a span over all but the given number of trailing elements. @@ -779,7 +804,7 @@ extension MutableSpan where Element: ~Copyable { 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 _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } /// Returns a span containing the final elements of the span, @@ -803,9 +828,9 @@ extension MutableSpan where Element: ~Copyable { 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) + let newStart = unsafe _pointer?.advanced(by: offset) let newSpan = Self(_unchecked: newStart, count: newCount) - return _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } /// Returns a span over all but the given number of initial elements. @@ -828,8 +853,8 @@ extension MutableSpan where Element: ~Copyable { 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) + let newStart = unsafe _pointer?.advanced(by: offset) let newSpan = Self(_unchecked: newStart, count: count &- droppedCount) - return _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } } From eaecf56fbe8a32a911f01c468ae31e03c2f39d7c Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 5 Mar 2025 10:05:18 -0800 Subject: [PATCH 24/30] add required unsafe annotations to `MutableRawSpan` --- Sources/Span/MutableRawSpan.swift | 109 ++++++++++++++++++------------ 1 file changed, 64 insertions(+), 45 deletions(-) diff --git a/Sources/Span/MutableRawSpan.swift b/Sources/Span/MutableRawSpan.swift index e626be83..3a2770a1 100644 --- a/Sources/Span/MutableRawSpan.swift +++ b/Sources/Span/MutableRawSpan.swift @@ -12,6 +12,7 @@ // A MutableRawSpan represents a span of memory which // contains initialized `Element` instances. +@safe @frozen @available(macOS 9999, *) public struct MutableRawSpan: ~Copyable & ~Escapable { @@ -23,16 +24,16 @@ public struct MutableRawSpan: ~Copyable & ~Escapable { @_alwaysEmitIntoClient internal func _start() -> UnsafeMutableRawPointer { - _pointer.unsafelyUnwrapped + unsafe _pointer.unsafelyUnwrapped } - @usableFromInline @inline(__always) + @_alwaysEmitIntoClient @lifetime(borrow pointer) - init( + internal init( _unchecked pointer: UnsafeMutableRawPointer?, byteCount: Int ) { - _pointer = pointer + _pointer = unsafe pointer _count = byteCount } } @@ -43,24 +44,27 @@ 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 = _overrideLifetime(span, borrowing: bytes) + self = unsafe _overrideLifetime(span, borrowing: bytes) } + @_alwaysEmitIntoClient @lifetime(borrow bytes) public init( _unsafeBytes bytes: borrowing Slice ) { - let rebased = UnsafeMutableRawBufferPointer(rebasing: bytes) + let rebased = unsafe UnsafeMutableRawBufferPointer(rebasing: bytes) let span = MutableRawSpan(_unsafeBytes: rebased) - self = _overrideLifetime(span, borrowing: bytes) + self = unsafe _overrideLifetime(span, borrowing: bytes) } + @_alwaysEmitIntoClient @lifetime(borrow pointer) public init( _unsafeStart pointer: UnsafeMutableRawPointer, @@ -70,34 +74,37 @@ extension MutableRawSpan { 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 = _overrideLifetime(span, borrowing: elements) + self = unsafe _overrideLifetime(span, borrowing: elements) } + @_alwaysEmitIntoClient @lifetime(borrow elements) public init( _unsafeElements elements: borrowing Slice> ) { - let rebased = UnsafeMutableBufferPointer(rebasing: elements) + let rebased = unsafe UnsafeMutableBufferPointer(rebasing: elements) let span = MutableRawSpan(_unsafeElements: rebased) - self = _overrideLifetime(span, borrowing: elements) + self = unsafe _overrideLifetime(span, borrowing: elements) } + @_alwaysEmitIntoClient @lifetime(elements) public init( _elements elements: consuming MutableSpan ) { - let bytes = UnsafeMutableRawBufferPointer( + let bytes = unsafe UnsafeMutableRawBufferPointer( start: elements._pointer, count: elements.count &* MemoryLayout.stride ) let span = MutableRawSpan(_unsafeBytes: bytes) - self = _overrideLifetime(span, copying: elements) + self = unsafe _overrideLifetime(span, copying: elements) } } @@ -111,29 +118,31 @@ extension MutableRawSpan { @_alwaysEmitIntoClient public var byteOffsets: Range { - .init(uncheckedBounds: (0, byteCount)) + 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 body(.init(start: nil, count: 0)) + return try unsafe body(.init(start: nil, count: 0)) } - return try body(.init(start: pointer, count: _count)) + 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 body(.init(start: nil, count: 0)) + return try unsafe body(.init(start: nil, count: 0)) } - return try body(.init(start: pointer, count: _count)) + return try unsafe body(.init(start: pointer, count: _count)) } } @@ -145,7 +154,7 @@ extension RawSpan { public init(_unsafeMutableRawSpan mutableSpan: borrowing MutableRawSpan) { let start = mutableSpan._start() let span = RawSpan(_unsafeStart: start, byteCount: mutableSpan.byteCount) - self = _overrideLifetime(span, borrowing: mutableSpan) + self = unsafe _overrideLifetime(span, borrowing: mutableSpan) } } @@ -153,6 +162,7 @@ extension RawSpan { extension MutableRawSpan { public var bytes: RawSpan { + @_alwaysEmitIntoClient @lifetime(borrow self) borrowing get { return RawSpan(_unsafeMutableRawSpan: self) @@ -160,30 +170,33 @@ extension MutableRawSpan { } @unsafe + @_alwaysEmitIntoClient @lifetime(borrow self) public borrowing func _unsafeView( as type: T.Type ) -> Span { - let bytes = UnsafeRawBufferPointer(start: _pointer, count: _count) + let bytes = unsafe UnsafeRawBufferPointer(start: _pointer, count: _count) let span = Span(_unsafeBytes: bytes) - return _overrideLifetime(span, borrowing: self) + return unsafe _overrideLifetime(span, borrowing: self) } @unsafe + @_alwaysEmitIntoClient @lifetime(borrow self) public mutating func _unsafeMutableView( as type: T.Type ) -> MutableSpan { - let bytes = UnsafeMutableRawBufferPointer(start: _pointer, count: _count) + let bytes = unsafe UnsafeMutableRawBufferPointer( + start: _pointer, count: _count + ) let span = MutableSpan(_unsafeBytes: bytes) - return _overrideLifetime(span, mutating: &self) + 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. /// @@ -211,7 +224,7 @@ extension MutableRawSpan { MemoryLayout.size <= (_count &- offset), "Byte offset range out of bounds" ) - return unsafeLoad(fromUncheckedByteOffset: offset, as: T.self) + return unsafe unsafeLoad(fromUncheckedByteOffset: offset, as: T.self) } /// Returns a new instance of the given type, constructed from the raw memory @@ -237,7 +250,7 @@ extension MutableRawSpan { public func unsafeLoad( fromUncheckedByteOffset offset: Int, as: T.Type ) -> T { - _start().load(fromByteOffset: offset, as: T.self) + unsafe _start().load(fromByteOffset: offset, as: T.self) } /// Returns a new instance of the given type, constructed from the raw memory @@ -266,7 +279,7 @@ extension MutableRawSpan { MemoryLayout.size <= (_count &- offset), "Byte offset range out of bounds" ) - return unsafeLoadUnaligned(fromUncheckedByteOffset: offset, as: T.self) + return unsafe unsafeLoadUnaligned(fromUncheckedByteOffset: offset, as: T.self) } /// Returns a new instance of the given type, constructed from the raw memory @@ -291,7 +304,7 @@ extension MutableRawSpan { public func unsafeLoadUnaligned( fromUncheckedByteOffset offset: Int, as: T.Type ) -> T { - _start().loadUnaligned(fromByteOffset: offset, as: T.self) + unsafe _start().loadUnaligned(fromByteOffset: offset, as: T.self) } @_alwaysEmitIntoClient @@ -303,7 +316,7 @@ extension MutableRawSpan { MemoryLayout.size <= (_count &- offset), "Byte offset range out of bounds" ) - storeBytes(of: value, toUncheckedByteOffset: offset, as: type) + unsafe storeBytes(of: value, toUncheckedByteOffset: offset, as: type) } @unsafe @@ -311,7 +324,7 @@ extension MutableRawSpan { public mutating func storeBytes( of value: T, toUncheckedByteOffset offset: Int, as type: T.Type ) { - _start().storeBytes(of: value, toByteOffset: offset, as: type) + unsafe _start().storeBytes(of: value, toByteOffset: offset, as: type) } } @@ -335,7 +348,9 @@ extension MutableRawSpan { var offset = 0 while offset + MemoryLayout.stride <= _count { guard let element = elements.next() else { break } - storeBytes(of: element, toUncheckedByteOffset: offset, as: Element.self) + unsafe storeBytes( + of: element, toUncheckedByteOffset: offset, as: Element.self + ) offset &+= MemoryLayout.stride } return offset @@ -385,7 +400,7 @@ extension MutableRawSpan { ) -> Int { if source.byteCount == 0 { return 0 } source.withUnsafeBytes { - _start().copyMemory(from: $0.baseAddress!, byteCount: $0.count) + unsafe _start().copyMemory(from: $0.baseAddress!, byteCount: $0.count) } return source.byteCount } @@ -423,7 +438,7 @@ extension MutableRawSpan { UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count), "Index range out of bounds" ) - return _extracting(unchecked: bounds) + return unsafe _extracting(unchecked: bounds) } /// Constructs a new span over the items within the supplied range of @@ -445,9 +460,9 @@ extension MutableRawSpan { @_alwaysEmitIntoClient @lifetime(borrow self) mutating public func _extracting(unchecked bounds: Range) -> Self { - let newStart = _pointer?.advanced(by: bounds.lowerBound) + let newStart = unsafe _pointer?.advanced(by: bounds.lowerBound) let newSpan = Self(_unchecked: newStart, byteCount: bounds.count) - return _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } /// Constructs a new span over the items within the supplied range of @@ -465,8 +480,10 @@ extension MutableRawSpan { /// - Complexity: O(1) @_alwaysEmitIntoClient @lifetime(borrow self) - mutating public func _extracting(_ bounds: some RangeExpression) -> Self { - _extracting(bounds.relative(to: byteOffsets).clamped(to: byteOffsets)) + 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 @@ -488,8 +505,10 @@ extension MutableRawSpan { @_alwaysEmitIntoClient @lifetime(borrow self) mutating public func _extracting(unchecked bounds: ClosedRange) -> Self { - let range = Range(uncheckedBounds: (bounds.lowerBound, bounds.upperBound+1)) - return _extracting(unchecked: range) + 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. @@ -505,7 +524,7 @@ extension MutableRawSpan { @lifetime(borrow self) mutating public func _extracting(_: UnboundedRange) -> Self { let newSpan = Self(_unchecked: _start(), byteCount: _count) - return _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } } @@ -534,7 +553,7 @@ extension MutableRawSpan { precondition(maxLength >= 0, "Can't have a prefix of negative length") let newCount = min(maxLength, byteCount) let newSpan = Self(_unchecked: _pointer, byteCount: newCount) - return _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } /// Returns a span over all but the given number of trailing elements. @@ -557,7 +576,7 @@ extension MutableRawSpan { 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 _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } /// Returns a span containing the final elements of the span, @@ -580,9 +599,9 @@ extension MutableRawSpan { 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 = _pointer?.advanced(by: byteCount &- newCount) + let newStart = unsafe _pointer?.advanced(by: byteCount &- newCount) let newSpan = Self(_unchecked: newStart, byteCount: newCount) - return _overrideLifetime(newSpan, copying: self) + return unsafe _overrideLifetime(newSpan, copying: self) } /// Returns a span over all but the given number of initial elements. @@ -604,8 +623,8 @@ extension MutableRawSpan { 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 = _pointer?.advanced(by: dropped) + let newStart = unsafe _pointer?.advanced(by: dropped) let newSpan = Self(_unchecked: newStart, byteCount: byteCount &- dropped) - return _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } } From 0b96db119e7c42c6f15c5a952df6a738b173af8e Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 5 Mar 2025 13:56:26 -0800 Subject: [PATCH 25/30] remove unneeded `unsafe` keywords --- Sources/Span/MutableSpan.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/Span/MutableSpan.swift b/Sources/Span/MutableSpan.swift index 9e0ba01a..aa4dff70 100644 --- a/Sources/Span/MutableSpan.swift +++ b/Sources/Span/MutableSpan.swift @@ -61,7 +61,7 @@ extension MutableSpan where Element: ~Copyable { public init( _unsafeElements buffer: UnsafeMutableBufferPointer ) { - unsafe precondition( + precondition( ((Int(bitPattern: buffer.baseAddress) & (MemoryLayout.alignment &- 1)) == 0), "baseAddress must be properly aligned to access Element" @@ -105,7 +105,7 @@ extension MutableSpan where Element: BitwiseCopyable { public init( _unsafeBytes buffer: UnsafeMutableRawBufferPointer ) { - unsafe precondition( + precondition( ((Int(bitPattern: buffer.baseAddress) & (MemoryLayout.alignment &- 1)) == 0), "baseAddress must be properly aligned to access Element" @@ -219,7 +219,7 @@ extension MutableSpan where Element: ~Copyable { @_alwaysEmitIntoClient public var _description: String { let addr = String( - unsafe UInt(bitPattern: _pointer), radix: 16, uppercase: false + UInt(bitPattern: _pointer), radix: 16, uppercase: false ) return "(0x\(addr), \(_count))" } From 8e76a05f4f055d6a2758ea6de2bd47aff9287e49 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 5 Mar 2025 13:56:41 -0800 Subject: [PATCH 26/30] annotate slicing examples --- Sources/Span/MutableSpanSlicing.swift | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Sources/Span/MutableSpanSlicing.swift b/Sources/Span/MutableSpanSlicing.swift index e6e4fb33..7db6229b 100644 --- a/Sources/Span/MutableSpanSlicing.swift +++ b/Sources/Span/MutableSpanSlicing.swift @@ -22,7 +22,7 @@ extension MutableSpan where Element: ~Copyable { "Index range out of bounds" ) let newSpan = MutableSpan(_unchecked: _start(), uncheckedBounds: bounds) - return _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } } @@ -35,11 +35,11 @@ extension MutableSpan where Element: ~Copyable { uncheckedBounds bounds: Range ) { let delta = bounds.lowerBound &* MemoryLayout.stride - let newStart = pointer.advanced(by: delta) + let newStart = unsafe pointer.advanced(by: delta) let newSpan = Self( _unchecked: newStart, count: bounds.upperBound &- bounds.lowerBound ) - self = _overrideLifetime(newSpan, borrowing: pointer) + self = unsafe _overrideLifetime(newSpan, borrowing: pointer) } } @@ -53,7 +53,7 @@ extension Span where Element: ~Copyable { ) { let mut = MutableSpan(_unchecked: pointer, uncheckedBounds: bounds) let newSpan = mut.span - self = _overrideLifetime(newSpan, borrowing: pointer) + self = unsafe _overrideLifetime(newSpan, borrowing: pointer) } } @@ -70,7 +70,7 @@ extension MutableSpan where Element: ~Copyable { "Index range out of bounds" ) let newSpan = MutableSpan(_unchecked: _start(), uncheckedBounds: bounds) - return _overrideLifetime(newSpan, mutating: &self) + return unsafe _overrideLifetime(newSpan, mutating: &self) } } } @@ -98,11 +98,11 @@ extension SubMutableSpan where Element: ~Copyable { public subscript (index: Index) -> Element { unsafeAddress { precondition(offset <= index && index < base.count) - return UnsafePointer(base._unsafeAddressOfElement(unchecked: index)) + return unsafe UnsafePointer(base._unsafeAddressOfElement(unchecked: index)) } unsafeMutableAddress { precondition(offset <= index && index < base.count) - return base._unsafeAddressOfElement(unchecked: index) + return unsafe base._unsafeAddressOfElement(unchecked: index) } } @@ -112,7 +112,7 @@ extension SubMutableSpan where Element: ~Copyable { let newSpan = Span( _unchecked: base._start(), uncheckedBounds: offset..(bounds.lowerBound, prefix) - return _overrideLifetime(subSpan, mutating: &self) + return unsafe _overrideLifetime(subSpan, mutating: &self) } } } @@ -157,9 +157,9 @@ extension MutableSpan where Element: Copyable { UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count), "Index range out of bounds" ) - let start = _start().advanced(by: bounds.lowerBound &* MemoryLayout.stride) - start.withMemoryRebound(to: Element.self, capacity: bounds.count) { - $0.update(repeating: repeatedValue, count: bounds.count) + 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) } } } From 4523e7a0631aefd171888ce89b14ad8f06dd5045 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 5 Mar 2025 14:38:46 -0800 Subject: [PATCH 27/30] add required unsafe annotations to `OutputSpan` --- Sources/Span/MutableSpan.swift | 2 +- Sources/Span/OutputSpan.swift | 106 ++++++++++-------- Sources/Span/StdlibOutputSpanExtensions.swift | 28 ++--- Tests/SpanTests/OutputSpanTests.swift | 6 +- 4 files changed, 77 insertions(+), 65 deletions(-) diff --git a/Sources/Span/MutableSpan.swift b/Sources/Span/MutableSpan.swift index aa4dff70..d552a93f 100644 --- a/Sources/Span/MutableSpan.swift +++ b/Sources/Span/MutableSpan.swift @@ -535,7 +535,7 @@ extension MutableSpan where Element: ~Copyable { public mutating func moveUpdate( fromContentsOf source: UnsafeMutableBufferPointer ) -> Index { - let s = unsafe OutputSpan(_initializing: source, initialized: source.count) + let s = OutputSpan(_initializing: source, initialized: source.count) return self.moveUpdate(fromContentsOf: s) } } diff --git a/Sources/Span/OutputSpan.swift b/Sources/Span/OutputSpan.swift index 61251abc..0d0c6508 100644 --- a/Sources/Span/OutputSpan.swift +++ b/Sources/Span/OutputSpan.swift @@ -12,6 +12,7 @@ // OutputSpan represents a span of memory which contains // a variable number of `Element` instances, followed by uninitialized memory. +@safe @frozen @available(macOS 9999, *) public struct OutputSpan: ~Copyable, ~Escapable { @@ -25,7 +26,7 @@ public struct OutputSpan: ~Copyable, ~Escapable { @_alwaysEmitIntoClient internal func _start() -> UnsafeMutableRawPointer { - _pointer.unsafelyUnwrapped + unsafe _pointer.unsafelyUnwrapped } @_alwaysEmitIntoClient @@ -39,9 +40,11 @@ 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) } } } @@ -53,7 +56,7 @@ public struct OutputSpan: ~Copyable, ~Escapable { capacity: Int, initialized: Int ) { - _pointer = start + _pointer = unsafe start self.capacity = capacity _initialized = initialized } @@ -99,9 +102,9 @@ extension OutputSpan where Element: ~Copyable { initialized: Int = 0 ) { precondition(capacity >= 0, "Capacity must be 0 or greater") - let buffer = UnsafeMutableBufferPointer(start: pointer, count: capacity) - let os = OutputSpan(_initializing: buffer, initialized: initialized) - self = _overrideLifetime(os, borrowing: pointer) + let buf = unsafe UnsafeMutableBufferPointer(start: pointer, count: capacity) + let os = OutputSpan(_initializing: buf, initialized: initialized) + self = unsafe _overrideLifetime(os, borrowing: pointer) } } @@ -114,9 +117,9 @@ extension OutputSpan { _initializing buffer: borrowing Slice>, initialized: Int = 0 ) { - let rebased = UnsafeMutableBufferPointer(rebasing: buffer) + let rebased = unsafe UnsafeMutableBufferPointer(rebasing: buffer) let os = OutputSpan(_initializing: rebased, initialized: 0) - self = _overrideLifetime(os, borrowing: buffer) + self = unsafe unsafe _overrideLifetime(os, borrowing: buffer) } } @@ -141,7 +144,7 @@ extension OutputSpan where Element: BitwiseCopyable { let os = OutputSpan( _unchecked: pointer, capacity: count, initialized: initialized ) - self = _overrideLifetime(os, borrowing: bytes) + self = unsafe _overrideLifetime(os, borrowing: bytes) } @_alwaysEmitIntoClient @@ -152,9 +155,9 @@ extension OutputSpan where Element: BitwiseCopyable { initialized: Int = 0 ) { precondition(capacity >= 0, "Capacity must be 0 or greater") - let buffer = UnsafeMutableRawBufferPointer(start: pointer, count: capacity) - let os = OutputSpan(_initializing: buffer, initialized: initialized) - self = _overrideLifetime(os, borrowing: pointer) + let buf = unsafe UnsafeMutableRawBufferPointer(start: pointer, count: capacity) + let os = OutputSpan(_initializing: buf, initialized: initialized) + self = unsafe _overrideLifetime(os, borrowing: pointer) } @_alwaysEmitIntoClient @@ -163,9 +166,9 @@ extension OutputSpan where Element: BitwiseCopyable { _initializing buffer: borrowing Slice, initialized: Int = 0 ) { - let rebased = UnsafeMutableRawBufferPointer(rebasing: buffer) + let rebased = unsafe UnsafeMutableRawBufferPointer(rebasing: buffer) let os = OutputSpan(_initializing: rebased, initialized: initialized) - self = _overrideLifetime(os, borrowing: buffer) + self = unsafe _overrideLifetime(os, borrowing: buffer) } } @@ -175,8 +178,8 @@ extension OutputSpan where Element: ~Copyable { @_alwaysEmitIntoClient 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 } @@ -184,14 +187,14 @@ extension OutputSpan where Element: ~Copyable { public mutating func deinitializeLastElement() -> 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) + _ = unsafe _start().withMemoryRebound(to: Element.self, capacity: _initialized) { + unsafe $0.deinitialize(count: _initialized) } _initialized = 0 } @@ -209,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 } @@ -231,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 } } @@ -249,11 +252,11 @@ extension OutputSpan { } 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, @@ -272,9 +275,9 @@ extension OutputSpan { source.count <= available, "destination span cannot contain every element from source." ) - let tail = _start().advanced(by: _initialized&*MemoryLayout.stride) + let tail = unsafe _start().advanced(by: _initialized&*MemoryLayout.stride) _ = source.withUnsafeBufferPointer { - tail.initializeMemory( + unsafe tail.initializeMemory( as: Element.self, from: $0.baseAddress!, count: $0.count ) } @@ -299,10 +302,10 @@ 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 @@ -324,7 +327,9 @@ extension OutputSpan { public mutating func moveAppend( fromContentsOf source: Slice> ) { - moveAppend(fromContentsOf: UnsafeMutableBufferPointer(rebasing: source)) + moveAppend( + fromContentsOf: unsafe UnsafeMutableBufferPointer(rebasing: source) + ) } } @@ -340,10 +345,10 @@ extension OutputSpan where Element: ~Copyable { public var span: Span { @lifetime(borrow self) borrowing get { - let pointer = _pointer?.assumingMemoryBound(to: Element.self) - let buffer = UnsafeBufferPointer(start: pointer, count: _initialized) + let pointer = unsafe _pointer?.assumingMemoryBound(to: Element.self) + let buffer = unsafe UnsafeBufferPointer(start: pointer, count: _initialized) let span = Span(_unsafeElements: buffer) - return _overrideLifetime(span, borrowing: self) + return unsafe _overrideLifetime(span, borrowing: self) } } @@ -351,10 +356,12 @@ extension OutputSpan where Element: ~Copyable { public var mutableSpan: MutableSpan { @lifetime(borrow self) mutating get { - let pointer = _pointer?.assumingMemoryBound(to: Element.self) - let buffer = UnsafeMutableBufferPointer(start: pointer, count: _initialized) + let pointer = unsafe _pointer?.assumingMemoryBound(to: Element.self) + let buffer = unsafe UnsafeMutableBufferPointer( + start: pointer, count: _initialized + ) let span = MutableSpan(_unsafeElements: buffer) - return _overrideLifetime(span, mutating: &self) + return unsafe _overrideLifetime(span, mutating: &self) } } } @@ -362,22 +369,27 @@ extension OutputSpan where Element: ~Copyable { @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) } } @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/StdlibOutputSpanExtensions.swift b/Sources/Span/StdlibOutputSpanExtensions.swift index 35a6e4ce..fce41a04 100644 --- a/Sources/Span/StdlibOutputSpanExtensions.swift +++ b/Sources/Span/StdlibOutputSpanExtensions.swift @@ -17,16 +17,16 @@ extension Array { capacity: Int, initializingWith initializer: (inout OutputSpan) throws -> Void ) rethrows { - try self.init( + try unsafe self.init( unsafeUninitializedCapacity: capacity, initializingWith: { (buffer, count) in - let pointer = buffer.baseAddress.unsafelyUnwrapped + 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) count = initialized.count } ) @@ -43,16 +43,16 @@ extension String { utf8Capacity capacity: Int, initializingWith initializer: (inout OutputSpan) throws -> Void ) rethrows { - try self.init( + try unsafe self.init( unsafeUninitializedCapacity: capacity, initializingUTF8With: { buffer in - let pointer = buffer.baseAddress.unsafelyUnwrapped + 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 } ) @@ -69,16 +69,16 @@ extension Data { 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() - let pointer = buffer.baseAddress.unsafelyUnwrapped + 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/Tests/SpanTests/OutputSpanTests.swift b/Tests/SpanTests/OutputSpanTests.swift index 883fc6c3..fcac8ce0 100644 --- a/Tests/SpanTests/OutputSpanTests.swift +++ b/Tests/SpanTests/OutputSpanTests.swift @@ -41,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) @@ -97,7 +97,7 @@ final class OutputSpanTests: XCTestCase { for i in 0...c { $0.append(i) } - let oops = $0.deinitializeLastElement() + let oops = $0.removeLast() XCTAssertEqual(oops, c) } a.withSpan { @@ -126,7 +126,7 @@ final class OutputSpanTests: XCTestCase { 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) } From 505d6d5dc4a785be53e31ae597081a43d67a6617 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 5 Mar 2025 15:00:14 -0800 Subject: [PATCH 28/30] add unsafe annotations for `Span` extensions --- Sources/Span/SpanExtensions.swift | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Sources/Span/SpanExtensions.swift b/Sources/Span/SpanExtensions.swift index 87546bea..c0806547 100644 --- a/Sources/Span/SpanExtensions.swift +++ b/Sources/Span/SpanExtensions.swift @@ -19,18 +19,18 @@ extension Span { public static var empty: Span { @lifetime(immortal) get { - let nilBasedBuffer = UnsafeBufferPointer(start: nil, count: 0) - let span = Span(_unsafeElements: nilBasedBuffer) - return _overrideLifetime(span, borrowing: immortalThing) + 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 nilBasedBuffer = UnsafeBufferPointer(start: nil, count: 0) - let span = Span(_unsafeElements: nilBasedBuffer) - self = _overrideLifetime(span, borrowing: immortalThing) + let empty = unsafe UnsafeBufferPointer(start: nil, count: 0) + let span = Span(_unsafeElements: empty) + self = unsafe _overrideLifetime(span, borrowing: immortalThing) } } @@ -59,7 +59,7 @@ extension Span where Element: Equatable { // return _swift_stdlib_memcmp(lhs.baseAddress, rhs.baseAddress, count) == 0 // } for o in 0..= count { return false } - if self[unchecked: offset] != otherElement { return false } + if unsafe self[unchecked: offset] != otherElement { return false } offset += 1 } return offset == count From 98b8b786379effa36cc2d04343d6ebf6ec7a9974 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 7 Mar 2025 09:14:32 -0800 Subject: [PATCH 29/30] rename two OutputSpan functions --- Sources/Span/OutputSpan.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/Span/OutputSpan.swift b/Sources/Span/OutputSpan.swift index 0d0c6508..4df8661b 100644 --- a/Sources/Span/OutputSpan.swift +++ b/Sources/Span/OutputSpan.swift @@ -184,7 +184,7 @@ extension OutputSpan where Element: ~Copyable { } @_alwaysEmitIntoClient - public mutating func deinitializeLastElement() -> Element? { + public mutating func removeLast() -> Element? { guard _initialized > 0 else { return nil } _initialized &-= 1 let p = unsafe _start().advanced(by: _initialized&*MemoryLayout.stride) @@ -192,7 +192,7 @@ extension OutputSpan where Element: ~Copyable { } @_alwaysEmitIntoClient - public mutating func deinitialize() { + public mutating func removeAll() { _ = unsafe _start().withMemoryRebound(to: Element.self, capacity: _initialized) { unsafe $0.deinitialize(count: _initialized) } From a26fc8e7e4c6e0d63b08951f5b7268044fb95c83 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 28 Feb 2025 13:10:09 -0800 Subject: [PATCH 30/30] complete span tests --- Tests/SpanTests/RawSpanTests.swift | 35 ++----- Tests/SpanTests/SpanTests.swift | 151 +++++++++++------------------ 2 files changed, 69 insertions(+), 117 deletions(-) diff --git a/Tests/SpanTests/RawSpanTests.swift b/Tests/SpanTests/RawSpanTests.swift index 874af754..7f2838bc 100644 --- a/Tests/SpanTests/RawSpanTests.swift +++ b/Tests/SpanTests/RawSpanTests.swift @@ -112,7 +112,7 @@ final class RawSpanTests: XCTestCase { let sub1 = span._extracting(0..<2) let sub2 = span._extracting(..<2) let sub3 = span._extracting(...) - let sub4 = span._extracting(unchecked: 2...) + let sub4 = span._extracting(2...) XCTAssertTrue( sub1._unsafeView(as: UInt8.self)._elementsEqual(sub2._unsafeView(as: UInt8.self)) ) @@ -137,7 +137,7 @@ final class RawSpanTests: XCTestCase { } } - func testUnsafeBytes() { + func testWithUnsafeBytes() { let capacity = 4 let array = Array(0..