diff --git a/Package.swift b/Package.swift index 93325e1d..ccd8a07a 100644 --- a/Package.swift +++ b/Package.swift @@ -53,20 +53,17 @@ var defines: [String] = [ ] let _sharedSettings: [SwiftSetting] = defines.map { .define($0) } + [ + .enableExperimentalFeature("AllowUnsafeAttribute"), .enableExperimentalFeature("BuiltinModule"), .enableExperimentalFeature("NonescapableTypes"), - .enableExperimentalFeature("BitwiseCopyable"), .enableExperimentalFeature("RawLayout"), .enableExperimentalFeature("SuppressedAssociatedTypes"), ] -let _settings: [SwiftSetting] = _sharedSettings + [ - .swiftLanguageVersion(.v6), -] -let _testSettings: [SwiftSetting] = _sharedSettings + [ - .swiftLanguageVersion(.v5), -] +let _settings: [SwiftSetting] = _sharedSettings + [] + +let _testSettings: [SwiftSetting] = _sharedSettings + [] struct CustomTarget { enum Kind { diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque+Collection.swift index 8bf44b8f..adb896a8 100644 --- a/Sources/DequeModule/Deque+Collection.swift +++ b/Sources/DequeModule/Deque+Collection.swift @@ -13,6 +13,8 @@ import InternalCollectionsUtilities #endif +import Future + extension Deque { // Implementation note: we could also use the default `IndexingIterator` here. // This custom implementation performs direct storage access to eliminate any diff --git a/Sources/DequeModule/Deque+Equatable.swift b/Sources/DequeModule/Deque+Equatable.swift index 45d49c37..eb0f4709 100644 --- a/Sources/DequeModule/Deque+Equatable.swift +++ b/Sources/DequeModule/Deque+Equatable.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import Future + extension Deque: Equatable where Element: Equatable { /// Returns a Boolean value indicating whether two values are equal. Two /// deques are considered equal if they contain the same elements in the same diff --git a/Sources/DequeModule/Deque.swift b/Sources/DequeModule/Deque.swift index 33b2cadc..034bb806 100644 --- a/Sources/DequeModule/Deque.swift +++ b/Sources/DequeModule/Deque.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import Future + /// A collection implementing a double-ended queue. `Deque` (pronounced "deck") /// implements an ordered random-access collection that supports efficient /// insertions and removals from both ends. diff --git a/Sources/DequeModule/RigidDeque.swift b/Sources/DequeModule/RigidDeque.swift index 35b39f1e..118a4290 100644 --- a/Sources/DequeModule/RigidDeque.swift +++ b/Sources/DequeModule/RigidDeque.swift @@ -95,16 +95,16 @@ public struct _DequeBorrowingIterator: BorrowingIteratorProt let d = Swift.min(maximumCount, _segments.first.count - _offset) let slice = _segments.first.extracting(_offset ..< _offset + d) _offset += d - return Span(unsafeElements: slice, owner: self) + return Span(_unsafeElements: slice) } guard let second = _segments.second else { - return Span(unsafeElements: UnsafeBufferPointer._empty, owner: self) + return Span(_unsafeElements: UnsafeBufferPointer._empty) } let o = _offset - _segments.first.count let d = Swift.min(maximumCount, second.count - o) let slice = second.extracting(o ..< o + d) _offset += d - return Span(unsafeElements: slice, owner: self) + return Span(_unsafeElements: slice) } } diff --git a/Sources/Future/CMakeLists.txt b/Sources/Future/CMakeLists.txt index 6ade7dbd..f9ef82e0 100644 --- a/Sources/Future/CMakeLists.txt +++ b/Sources/Future/CMakeLists.txt @@ -12,9 +12,13 @@ add_library(Future "Cell.swift" "ContiguousStorage.swift" "Inout.swift" + "OutputSpan.swift" "LifetimeOverride.swift" "RawSpan.swift" "Span.swift" + "Span+Iterator.swift" + "StdlibOutputSpanExtensions.swift" + "StdlibSpanExtensions.swift" "Containers/Shared.swift" "Containers/Container.swift" "Containers/DynamicArray.swift" diff --git a/Sources/Future/Containers/NewArray.swift b/Sources/Future/Containers/NewArray.swift index 8c9b0111..423fb565 100644 --- a/Sources/Future/Containers/NewArray.swift +++ b/Sources/Future/Containers/NewArray.swift @@ -27,7 +27,7 @@ extension NewArray { // FIXME: This is what I want to write; alas, lifetimes are messed up. return _storage.value.storage #else - return Span(unsafeElements: _storage.value._items, owner: self) + return Span(_unsafeElements: _storage.value._items) #endif } } @@ -108,7 +108,7 @@ extension NewArray: RangeReplaceableCollection { self._storage = Shared(RigidArray(capacity: 0)) } - public func replaceSubrange( + mutating public func replaceSubrange( _ subrange: Range, with newElements: some Collection ) { diff --git a/Sources/Future/Containers/RigidArray.swift b/Sources/Future/Containers/RigidArray.swift index 5d190222..86c049d8 100644 --- a/Sources/Future/Containers/RigidArray.swift +++ b/Sources/Future/Containers/RigidArray.swift @@ -60,7 +60,7 @@ extension RigidArray where Element: ~Copyable { extension RigidArray where Element: ~Copyable { public var storage: Span { - Span(unsafeElements: _items, owner: self) + Span(_unsafeElements: _items) } } @@ -84,7 +84,7 @@ extension RigidArray: RandomAccessContainer where Element: ~Copyable { let end = _offset + Swift.min(maximumCount, _items.count - _offset) defer { _offset = end } let chunk = _items.extracting(Range(uncheckedBounds: (_offset, end))) - return Span(unsafeElements: chunk, owner: self) + return Span(_unsafeElements: chunk) } } @@ -242,7 +242,8 @@ extension RigidArray { internal func _copy(capacity: Int) -> Self { precondition(capacity >= count) var result = RigidArray(capacity: capacity) - result._storage.initializeAll(fromContentsOf: _storage) + let initialized = result._storage.initialize(fromContentsOf: _storage) + precondition(initialized == count) result._count = count return result } @@ -251,7 +252,8 @@ extension RigidArray { internal mutating func _move(capacity: Int) -> Self { precondition(capacity >= count) var result = RigidArray(capacity: capacity) - result._storage.moveInitializeAll(fromContentsOf: _storage) + let initialized = result._storage.moveInitialize(fromContentsOf: _storage) + precondition(initialized == count) result._count = count self._count = 0 return result diff --git a/Sources/Future/ContiguousStorage.swift b/Sources/Future/ContiguousStorage.swift index 3a747d9d..27a4f00f 100644 --- a/Sources/Future/ContiguousStorage.swift +++ b/Sources/Future/ContiguousStorage.swift @@ -24,13 +24,13 @@ extension Array: ContiguousStorage { public var storage: Span { _read { if let a = _baseAddressIfContiguous { - yield Span(unsafeStart: a, count: count, owner: self) + yield Span(_unsafeStart: a, count: count) } else { let a = ContiguousArray(copy self) #if true let s = Span( - unsafeStart: a._baseAddressIfContiguous!, count: a.count, owner: a + _unsafeStart: a._baseAddressIfContiguous!, count: a.count ) #else let s = a.storage @@ -45,7 +45,7 @@ extension ContiguousArray: ContiguousStorage { public var storage: Span { borrowing get { Span( - unsafeStart: _baseAddressIfContiguous!, count: count, owner: self + _unsafeStart: _baseAddressIfContiguous!, count: count ) } } @@ -57,13 +57,13 @@ extension CollectionOfOne: ContiguousStorage { /* ideally: (with strawman syntax) @addressable let value = self._element yield Span( - unsafePointer: Builtin.addressable(value), count: 1, owner: self - ) + unsafePointer: Builtin.addressable(value), count: 1 + ) */ let a = ContiguousArray(self) yield Span( - unsafeStart: a._baseAddressIfContiguous!, count: 1, owner: a + _unsafeStart: a._baseAddressIfContiguous!, count: 1 ) } } @@ -85,18 +85,18 @@ extension String.UTF8View: ContiguousStorage { let a = ContiguousArray(self) // yield a.storage yield Span( - unsafeStart: a._baseAddressIfContiguous!, count: 1, owner: a + _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, owner: self) + 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, owner: a + _unsafeStart: a._baseAddressIfContiguous!, count: 1 ) } } diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift new file mode 100644 index 00000000..76a3a41e --- /dev/null +++ b/Sources/Future/MutableSpan.swift @@ -0,0 +1,735 @@ +//===--- MutableSpan.swift ------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import Builtin + +// A MutableSpan represents a span of memory which +// contains initialized `Element` instances. +@_disallowFeatureSuppression(NonescapableTypes) +@frozen +public struct MutableSpan: ~Copyable & ~Escapable { + @usableFromInline let _pointer: UnsafeMutableRawPointer? + + @usableFromInline let _count: Int + + @usableFromInline @inline(__always) + var _start: UnsafeMutableRawPointer { _pointer.unsafelyUnwrapped } + + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline @inline(__always) + init( + _unchecked start: UnsafeMutableRawPointer?, + count: Int + ) -> dependsOn(immortal) Self { + _pointer = start + _count = count + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +@available(*, unavailable) +extension MutableSpan: Sendable {} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: ~Copyable { + + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline @inline(__always) + internal init( + _unchecked elements: UnsafeMutableBufferPointer + ) -> dependsOn(immortal) Self { + _pointer = .init(elements.baseAddress) + _count = elements.count + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeElements buffer: UnsafeMutableBufferPointer + ) -> dependsOn(immortal) Self { + precondition( + ((Int(bitPattern: buffer.baseAddress) & + (MemoryLayout.alignment&-1)) == 0), + "baseAddress must be properly aligned to access Element" + ) + self.init(_unchecked: buffer) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeStart start: UnsafeMutablePointer, + count: Int + ) -> dependsOn(immortal) Self { + precondition(count >= 0, "Count must not be negative") + self.init(_unsafeElements: .init(start: start, count: count)) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeElements elements: Slice> + ) -> dependsOn(immortal) Self { + self.init(_unsafeElements: UnsafeMutableBufferPointer(rebasing: elements)) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: BitwiseCopyable { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeBytes buffer: UnsafeMutableRawBufferPointer + ) -> dependsOn(immortal) Self { + precondition( + ((Int(bitPattern: buffer.baseAddress) & + (MemoryLayout.alignment&-1)) == 0), + "baseAddress must be properly aligned to access Element" + ) + let (byteCount, stride) = (buffer.count, MemoryLayout.stride) + let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride) + precondition(remainder == 0, "Span must contain a whole number of elements") + self.init(_unchecked: buffer.baseAddress, count: count) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeStart pointer: UnsafeMutableRawPointer, + byteCount: Int + ) -> dependsOn(immortal) Self { + precondition(byteCount >= 0, "Count must not be negative") + self.init(_unsafeBytes: .init(start: pointer, count: byteCount)) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeBytes buffer: Slice + ) -> dependsOn(immortal) Self { + self.init(_unsafeBytes: UnsafeMutableRawBufferPointer(rebasing: buffer)) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension Span where Element: ~Copyable { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init(_unsafeMutableSpan mutableSpan: borrowing MutableSpan) { + self.init(_unchecked: mutableSpan._start, count: mutableSpan.count) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: ~Copyable { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public var storage: Span { Span(_unsafeMutableSpan: self) } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func withSpan( + _ body: (Span) throws(E) -> Result + ) throws(E) -> Result { + try body(Span(_unsafeMutableSpan: self)) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension RawSpan { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeMutableSpan mutableSpan: borrowing MutableSpan + ) { + self.init( + _unchecked: mutableSpan._start, + byteCount: mutableSpan.count &* MemoryLayout.stride + ) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: Equatable { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func _elementsEqual(_ other: borrowing Self) -> Bool { + _elementsEqual(Span(_unsafeMutableSpan: other)) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func _elementsEqual(_ other: Span) -> Bool { + Span(_unsafeMutableSpan: self)._elementsEqual(other) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func _elementsEqual(_ other: some Collection) -> Bool { + Span(_unsafeMutableSpan: self)._elementsEqual(other) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func _elementsEqual(_ other: some Sequence) -> Bool { + Span(_unsafeMutableSpan: self)._elementsEqual(other) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: ~Copyable { + + @_alwaysEmitIntoClient + public var description: String { + let addr = String(UInt(bitPattern: _pointer), radix: 16, uppercase: false) + return "(0x\(addr), \(_count))" + } +} + +//MARK: Collection, RandomAccessCollection +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: ~Copyable { + + @_alwaysEmitIntoClient + public var count: Int { _count } + + @_alwaysEmitIntoClient + public var isEmpty: Bool { _count == 0 } + + @_alwaysEmitIntoClient + public var _indices: Range { + Range(uncheckedBounds: (0, _count)) + } +} + +//MARK: Bounds Checking +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: ~Copyable { + + /// Return true if `index` is a valid offset into this `Span` + /// + /// - Parameters: + /// - index: an index to validate + /// - Returns: true if `index` is valid + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func boundsContain(_ index: Int) -> Bool { + 0 <= index && index < _count + } + + /// Return true if `indices` is a valid range of indices into this `Span` + /// + /// - Parameters: + /// - indices: a range of indices to validate + /// - Returns: true if `indices` is a valid range of indices + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func boundsContain(_ indices: Range) -> Bool { + boundsContain(indices.lowerBound) && indices.upperBound <= _count + } + + /// Return true if `indices` is a valid range of indices into this `Span` + /// + /// - Parameters: + /// - indices: a range of indices to validate + /// - Returns: true if `indices` is a valid range of indices + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func boundsContain(_ indices: ClosedRange) -> Bool { + boundsContain(indices.lowerBound) && indices.upperBound < _count + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: BitwiseCopyable { + + /// Construct a RawSpan over the memory represented by this span + /// + /// - Returns: a RawSpan over the memory represented by this span + @_disallowFeatureSuppression(NonescapableTypes) + @unsafe //FIXME: remove when the lifetime inference is fixed + @_alwaysEmitIntoClient + public var _unsafeRawSpan: RawSpan { RawSpan(_unsafeMutableSpan: self) } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: ~Copyable { + + + /// Accesses the element at the specified position in the `Span`. + /// + /// - Parameter position: The offset of the element to access. `position` + /// must be greater or equal to zero, and less than `count`. + /// + /// - Complexity: O(1) + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public subscript(_ position: Int) -> Element { + _read { + precondition(boundsContain(position), "index out of bounds") + yield self[unchecked: position] + } + _modify { + precondition(boundsContain(position), "index out of bounds") + yield &self[unchecked: position] + } + } + + /// Accesses the element at the specified position in the `Span`. + /// + /// This subscript does not validate `position`; this is an unsafe operation. + /// + /// - Parameter position: The offset of the element to access. `position` + /// must be greater or equal to zero, and less than `count`. + /// + /// - Complexity: O(1) + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public subscript(unchecked position: Int) -> Element { + _read { + let offset = position&*MemoryLayout.stride + let p = UnsafeRawPointer(_start).advanced(by: offset)._rawValue + let binding = Builtin.bindMemory(p, count._builtinWordValue, Element.self) + defer { Builtin.rebindMemory(p, binding) } + yield UnsafePointer(p).pointee + } + _modify { + let offset = position&*MemoryLayout.stride + let p = UnsafeMutableRawPointer(_start).advanced(by: offset)._rawValue + let binding = Builtin.bindMemory(p, 1._builtinWordValue, Element.self) + defer { Builtin.rebindMemory(p, binding) } + yield &(UnsafeMutablePointer(p).pointee) + } + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: BitwiseCopyable { + + /// Accesses the element at the specified position in the `Span`. + /// + /// - Parameter position: The offset of the element to access. `position` + /// must be greater or equal to zero, and less than `count`. + /// + /// - Complexity: O(1) + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public subscript(_ position: Int) -> Element { + get { + precondition(boundsContain(position)) + return self[unchecked: position] + } + set { + precondition(boundsContain(position)) + self[unchecked: position] = newValue + } + } + + /// Accesses the element at the specified position in the `Span`. + /// + /// This subscript does not validate `position`; this is an unsafe operation. + /// + /// - Parameter position: The offset of the element to access. `position` + /// must be greater or equal to zero, and less than `count`. + /// + /// - Complexity: O(1) + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public subscript(unchecked position: Int) -> Element { + get { + let offset = position&*MemoryLayout.stride + return _start.loadUnaligned(fromByteOffset: offset, as: Element.self) + } + set { + let offset = position&*MemoryLayout.stride + _start.storeBytes(of: newValue, toByteOffset: offset, as: Element.self) + } + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: ~Copyable { + + //FIXME: mark closure parameter as non-escaping + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func withUnsafeBufferPointer( + _ body: (_ buffer: UnsafeBufferPointer) throws(E) -> Result + ) throws(E) -> Result { + try Span(_unsafeMutableSpan: self).withUnsafeBufferPointer(body) + } + + //FIXME: mark closure parameter as non-escaping + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func withUnsafeMutableBufferPointer( + _ body: (inout UnsafeMutableBufferPointer) throws(E) -> Result + ) throws(E) -> Result { + func executeBody( + _ start: UnsafeMutablePointer?, _ count: Int + ) throws(E) -> Result { + var buf = UnsafeMutableBufferPointer(start: start, count: count) + defer { + precondition( + (buf.baseAddress, buf.count) == (start, count), + "MutableSpan.withUnsafeMutableBufferPointer: replacing the buffer is not allowed" + ) + } + return try body(&buf) + } + guard let pointer = _pointer, count > 0 else { + return try executeBody(nil, 0) + } + return try pointer.withMemoryRebound(to: Element.self, capacity: count) { + pointer throws(E) -> Result in + return try executeBody(pointer, count) + } + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: BitwiseCopyable { + + //FIXME: mark closure parameter as non-escaping + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func withUnsafeBytes( + _ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result + ) throws(E) -> Result { + try RawSpan(_unsafeMutableSpan: self).withUnsafeBytes(body) + } + + //FIXME: mark closure parameter as non-escaping + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func withUnsafeMutableBytes( + _ body: (_ buffer: UnsafeMutableRawBufferPointer) throws(E) -> Result + ) throws(E) -> Result { + let bytes = UnsafeMutableRawBufferPointer( + start: (_count == 0) ? nil : _start, + count: _count &* MemoryLayout.stride + ) + return try body(bytes) + } +} + +//MARK: bulk-update functions +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan { + + @_alwaysEmitIntoClient + public mutating func update(repeating repeatedValue: Element) { + _start.withMemoryRebound(to: Element.self, capacity: count) { + $0.update(repeating: repeatedValue, count: count) + } + } + + @_alwaysEmitIntoClient + public mutating func update( + from source: S + ) -> (unwritten: S.Iterator, index: Int) where S.Element == Element { + var iterator = source.makeIterator() + let index = update(from: &iterator) + return (iterator, index) + } + + @_alwaysEmitIntoClient + public mutating func update( + from elements: inout some IteratorProtocol + ) -> Int { + var index = 0 + while index < _count { + guard let element = elements.next() else { break } + self[unchecked: index] = element + index &+= 1 + } + return index + } + + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: some Collection + ) -> Int { + let updated = source.withContiguousStorageIfAvailable { + self.update(fromContentsOf: Span(_unsafeElements: $0)) + } + if let updated { + return 0.advanced(by: updated) + } + + if self.isEmpty { + precondition( + source.isEmpty, + "destination buffer view cannot contain every element from source." + ) + return 0 + } + + var iterator = source.makeIterator() + var index = 0 + while let value = iterator.next() { + precondition( + index < _count, + "destination buffer view cannot contain every element from source." + ) + self[unchecked: index] = value + index &+= 1 + } + return index + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func update(fromContentsOf source: Span) -> Int { + guard !source.isEmpty else { return 0 } + precondition( + source.count <= self.count, + "destination span cannot contain every element from source." + ) + _start.withMemoryRebound(to: Element.self, capacity: source.count) { dest in + source._start.withMemoryRebound(to: Element.self, capacity: source.count) { + dest.update(from: $0, count: source.count) + } + } + return source.count + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: borrowing MutableSpan + ) -> Int { + source.withSpan { self.update(fromContentsOf: $0) } + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: ~Copyable { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func moveUpdate( + fromContentsOf source: consuming OutputSpan + ) -> Int { + guard !source.isEmpty else { return 0 } + precondition( + source.count <= self.count, + "destination span cannot contain every element from source." + ) + let buffer = source.relinquishBorrowedMemory() + // we must now deinitialize the returned UMBP + _start.moveInitializeMemory( + as: Element.self, from: buffer.baseAddress!, count: buffer.count + ) + return buffer.count + } + + public mutating func moveUpdate( + fromContentsOf source: UnsafeMutableBufferPointer + ) -> Int { +#if false + guard let sourceAddress = source.baseAddress, source.count > 0 else { + return 0 + } + precondition( + source.count <= self.count, + "destination span cannot contain every element from source." + ) + _start.withMemoryRebound(to: Element.self, capacity: source.count) { + $0.moveUpdate(from: sourceAddress, count: source.count) + } + return source.count +#else + let source = OutputSpan(_initializing: source, initialized: source.count) + return self.moveUpdate(fromContentsOf: source) +#endif + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan { + + public mutating func moveUpdate( + fromContentsOf source: Slice> + ) -> Int { + self.moveUpdate(fromContentsOf: .init(rebasing: source)) + } +} + + +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: BitwiseCopyable { + + @_alwaysEmitIntoClient + public mutating func update( + repeating repeatedValue: Element + ) where Element: BitwiseCopyable { + guard count > 0 else { return } + // rebind _start manually in order to avoid assumptions about alignment. + let rp = _start._rawValue + let binding = Builtin.bindMemory(rp, count._builtinWordValue, Element.self) + UnsafeMutablePointer(rp).update(repeating: repeatedValue, count: count) + Builtin.rebindMemory(rp, binding) + } + + @_alwaysEmitIntoClient + public mutating func update( + from source: S + ) -> (unwritten: S.Iterator, index: Int) + where S.Element == Element, Element: BitwiseCopyable { + var iterator = source.makeIterator() + let index = update(from: &iterator) + return (iterator, index) + } + + @_alwaysEmitIntoClient + public mutating func update( + from elements: inout some IteratorProtocol + ) -> Int { + var index = 0 + while index < _count { + guard let element = elements.next() else { break } + self[unchecked: index] = element + index &+= 1 + } + return index + } + + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: some Collection + ) -> Int where Element: BitwiseCopyable { + let updated = source.withContiguousStorageIfAvailable { + self.update(fromContentsOf: Span(_unsafeElements: $0)) + } + if let updated { + return 0.advanced(by: updated) + } + + if self.isEmpty { + precondition( + source.isEmpty, + "destination buffer view cannot contain every element from source." + ) + return 0 + } + + var iterator = source.makeIterator() + var index = 0 + while let value = iterator.next() { + guard index < _count else { + fatalError( + "destination buffer view cannot contain every element from source." + ) + } + self[unchecked: index] = value + index &+= 1 + } + return index + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: Span + ) -> Int where Element: BitwiseCopyable { + guard !source.isEmpty else { return 0 } + precondition( + source.count <= self.count, + "destination span cannot contain every element from source." + ) + _start.copyMemory( + from: source._start, byteCount: source.count&*MemoryLayout.stride + ) + return source.count + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: borrowing MutableSpan + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: source.storage) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + @unsafe + public mutating func update( + fromContentsOf source: RawSpan + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: source.unsafeView(as: Element.self)) + } + + // We have to define the overloads for raw buffers and their slices, + // otherwise they would try to use their `Collection` conformance + // and fail due to the mismatch in `Element` type. + + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: UnsafeRawBufferPointer + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: RawSpan(_unsafeBytes: source)) + } + + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: UnsafeMutableRawBufferPointer + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: RawSpan(_unsafeBytes: source)) + } + + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: Slice + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: RawSpan(_unsafeBytes: source)) + } + + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: Slice + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: RawSpan(_unsafeBytes: source)) + } +} + +//MARK: copyMemory +//FIXME: move these to a MutableRawSpan +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: BitwiseCopyable { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func copyMemory( + from source: borrowing MutableSpan + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: source.storage) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func copyMemory( + from source: Span + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: source) + } +} diff --git a/Sources/Future/OutputSpan.swift b/Sources/Future/OutputSpan.swift new file mode 100644 index 00000000..1009cc77 --- /dev/null +++ b/Sources/Future/OutputSpan.swift @@ -0,0 +1,425 @@ +//===--- OutputSpan.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 +// +//===----------------------------------------------------------------------===// + +// OutputSpan represents a span of memory which contains +// a variable number of `Element` instances, followed by uninitialized memory. +@_disallowFeatureSuppression(NonescapableTypes) +@frozen +public struct OutputSpan: ~Copyable, ~Escapable { + @usableFromInline let _pointer: UnsafeMutableRawPointer? + + public let capacity: Int + + @usableFromInline + var _initialized: Int = 0 + + @usableFromInline @inline(__always) + var _start: UnsafeMutableRawPointer { _pointer.unsafelyUnwrapped } + + @_alwaysEmitIntoClient + public var available: Int { capacity &- _initialized } + + @_alwaysEmitIntoClient + public var count: Int { _initialized } + + @_alwaysEmitIntoClient + public var isEmpty: Bool { _initialized == 0 } + + deinit { + // `self` always borrows memory, and it shouldn't have gotten here. + // Failing to use `relinquishBorrowedMemory()` is an error. + if _initialized > 0 { +#if false + _start.withMemoryRebound(to: Element.self, capacity: _initialized) { + $0.deinitialize(count: _initialized) + } +#else + fatalError() +#endif + } + } + + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline @inline(__always) + init( + _unchecked start: UnsafeMutableRawPointer?, + capacity: Int, + initialized: Int + ) -> dependsOn(immortal) Self { + _pointer = start + self.capacity = capacity + _initialized = initialized + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +@available(*, unavailable) +extension OutputSpan: Sendable {} + +@_disallowFeatureSuppression(NonescapableTypes) +extension OutputSpan where Element: ~Copyable { + + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline @inline(__always) + init( + _unchecked buffer: UnsafeMutableBufferPointer, + initialized: Int + ) -> dependsOn(immortal) Self { + _pointer = .init(buffer.baseAddress) + capacity = buffer.count + _initialized = initialized + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _initializing buffer: UnsafeMutableBufferPointer, + initialized: Int = 0 + ) -> dependsOn(immortal) Self { + precondition( + ((Int(bitPattern: buffer.baseAddress) & + (MemoryLayout.alignment&-1)) == 0), + "baseAddress must be properly aligned to access Element" + ) + self.init(_unchecked: buffer, initialized: initialized) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _initializing pointer: UnsafeMutablePointer, + capacity: Int, + initialized: Int = 0 + ) -> dependsOn(immortal) Self { + precondition(capacity >= 0, "Capacity must be 0 or greater") + self.init( + _initializing: .init(start: pointer, count: capacity), + initialized: initialized + ) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension OutputSpan { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _initializing buffer: Slice>, + initialized: Int = 0 + ) -> dependsOn(immortal) Self { + self.init(_initializing: .init(rebasing: buffer), initialized: initialized) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension OutputSpan where Element: BitwiseCopyable { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _initializing bytes: UnsafeMutableRawBufferPointer, + initialized: Int = 0 + ) -> dependsOn(immortal) Self { + precondition( + ((Int(bitPattern: bytes.baseAddress) & + (MemoryLayout.alignment&-1)) == 0), + "baseAddress must be properly aligned to access Element" + ) + 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 + ) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _initializing pointer: UnsafeMutableRawPointer, + capacity: Int, + initialized: Int = 0 + ) -> dependsOn(immortal) Self { + precondition(capacity >= 0, "Capacity must be 0 or greater") + self.init( + _initializing: .init(start: pointer, count: capacity), + initialized: initialized + ) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _initializing buffer: Slice, + initialized: Int = 0 + ) -> dependsOn(immortal) Self { + self.init( + _initializing: UnsafeMutableRawBufferPointer(rebasing: buffer), + initialized: initialized + ) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension OutputSpan where Element: ~Copyable { + + @_alwaysEmitIntoClient + public mutating func appendElement(_ value: consuming Element) { + precondition(_initialized < capacity, "Output buffer overflow") + let p = _start.advanced(by: _initialized&*MemoryLayout.stride) + p.initializeMemory(as: Element.self, to: value) + _initialized &+= 1 + } + + @_alwaysEmitIntoClient + 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() }) + } + + @_alwaysEmitIntoClient + public mutating func deinitialize() { + _ = _start.withMemoryRebound(to: Element.self, capacity: _initialized) { + $0.deinitialize(count: _initialized) + } + _initialized = 0 + } +} + +//MARK: bulk-update functions +@_disallowFeatureSuppression(NonescapableTypes) +extension OutputSpan { + + @_alwaysEmitIntoClient + public mutating func append(repeating repeatedValue: Element, count: Int) { + let available = capacity &- _initialized + precondition( + count <= available, + "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) + } + _initialized &+= count + } + + @_alwaysEmitIntoClient + public mutating func append( + from elements: S + ) -> S.Iterator where S: Sequence, S.Element == Element { + var iterator = elements.makeIterator() + append(from: &iterator) + return iterator + } + + @_alwaysEmitIntoClient + public mutating func append( + from elements: inout some IteratorProtocol + ) { + 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) + _initialized &+= 1 + } + } + + @_alwaysEmitIntoClient + public mutating func append( + 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) + var (iterator, copied) = + tail.withMemoryRebound(to: Element.self, capacity: available) { + let suffix = UnsafeMutableBufferPointer(start: $0, count: available) + return source._copyContents(initializing: suffix) + } + precondition( + iterator.next() == nil, + "destination span cannot contain every element from source." + ) + assert(_initialized + copied <= capacity) // invariant check + _initialized &+= copied + } + + //FIXME: remove once rdar://136838539 & rdar://136849171 are fixed + public mutating func append( + fromContentsOf source: UnsafeBufferPointer + ) { + guard !source.isEmpty else { return } + precondition( + source.count <= available, + "destination span cannot contain every element from source." + ) + let tail = _start.advanced(by: _initialized&*MemoryLayout.stride) + source.baseAddress!.withMemoryRebound(to: Element.self, capacity: source.count) { + _ = tail.initializeMemory(as: Element.self, from: $0, count: source.count) + } + _initialized += source.count + } + + //FIXME: rdar://136838539 & rdar://136849171 + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func append( + fromContentsOf source: Span + ) { + 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._start.withMemoryRebound(to: Element.self, capacity: source.count) { + _ = tail.initializeMemory(as: Element.self, from: $0, count: source.count) + } + _initialized += source.count + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func append(fromContentsOf source: borrowing MutableSpan) { + source.withUnsafeBufferPointer { append(fromContentsOf: $0) } + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension OutputSpan where Element: ~Copyable { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func moveAppend( + fromContentsOf source: consuming Self + ) { + guard !source.isEmpty else { return } + precondition( + source.count <= available, + "buffer cannot contain every element from source." + ) + let buffer = source.relinquishBorrowedMemory() + // we must now deinitialize the returned UMBP + let tail = _start.advanced(by: _initialized&*MemoryLayout.stride) + tail.moveInitializeMemory( + as: Element.self, from: buffer.baseAddress!, count: buffer.count + ) + _initialized &+= buffer.count + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func moveAppend( + fromContentsOf source: UnsafeMutableBufferPointer + ) { +#if false //FIXME: rdar://136838539 & rdar://136849171 + let source = OutputSpan(_initializing: source, initialized: source.count) + moveAppend(fromContentsOf: source) +#else + guard !source.isEmpty else { return } + precondition( + source.count <= available, + "buffer cannot contain every element from source." + ) + let tail = _start.advanced(by: _initialized&*MemoryLayout.stride) + tail.moveInitializeMemory( + as: Element.self, from: source.baseAddress!, count: source.count + ) + _initialized &+= source.count +#endif + } +} + +extension OutputSpan { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func moveAppend( + fromContentsOf source: Slice> + ) { + moveAppend(fromContentsOf: UnsafeMutableBufferPointer(rebasing: source)) + } +} + +extension OutputSpan where Element: BitwiseCopyable { + +} + +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." + ) + } + return try body(&span) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension OutputSpan where Element: ~Copyable { + + @_alwaysEmitIntoClient + 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) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) +extension OutputSpan where Element: BitwiseCopyable { + + @_alwaysEmitIntoClient + public consuming func relinquishBorrowedBytes() -> UnsafeMutableRawBufferPointer { + let (start, count) = (self._pointer, self._initialized) + discard self + return .init(start: start, count: count&*MemoryLayout.stride) + } +} diff --git a/Sources/Future/RawSpan.swift b/Sources/Future/RawSpan.swift index 97b79d41..e96f4567 100644 --- a/Sources/Future/RawSpan.swift +++ b/Sources/Future/RawSpan.swift @@ -10,27 +10,22 @@ // //===----------------------------------------------------------------------===// -import Builtin - // A RawSpan represents a span of initialized memory // of unspecified type. @frozen public struct RawSpan: Copyable, ~Escapable { - @usableFromInline - internal let _pointer: UnsafeRawPointer? + @usableFromInline let _pointer: UnsafeRawPointer? @usableFromInline @inline(__always) - internal var _start: UnsafeRawPointer { _pointer.unsafelyUnwrapped } + var _start: UnsafeRawPointer { _pointer.unsafelyUnwrapped } - @usableFromInline - internal let _count: Int + @usableFromInline let _count: Int - @inlinable @inline(__always) - internal init( + @_alwaysEmitIntoClient + internal init( _unchecked start: UnsafeRawPointer?, - byteCount: Int, - owner: borrowing Owner - ) { + byteCount: Int + ) -> dependsOn(immortal) Self { _pointer = start _count = byteCount } @@ -50,16 +45,22 @@ extension RawSpan { /// - buffer: an `UnsafeRawBufferPointer` to initialized memory. /// - owner: a binding whose lifetime must exceed that of /// the newly created `RawSpan`. - @inlinable @inline(__always) - public init( - unsafeBytes buffer: UnsafeRawBufferPointer, - owner: borrowing Owner - ) { + @_alwaysEmitIntoClient + public init( + _unsafeBytes buffer: UnsafeRawBufferPointer + ) -> dependsOn(immortal) Self { self.init( - _unchecked: buffer.baseAddress, byteCount: buffer.count, owner: owner + _unchecked: buffer.baseAddress, byteCount: buffer.count ) } + @_alwaysEmitIntoClient + public init( + _unsafeBytes buffer: Slice + ) -> dependsOn(immortal) Self { + self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer)) + } + /// Unsafely create a `RawSpan` over initialized memory. /// /// The memory in `buffer` must be owned by the instance `owner`, @@ -70,11 +71,17 @@ extension RawSpan { /// - owner: a binding whose lifetime must exceed that of /// the newly created `RawSpan`. @_alwaysEmitIntoClient - public init( - unsafeBytes buffer: UnsafeMutableRawBufferPointer, - owner: borrowing Owner - ) { - self.init(unsafeBytes: UnsafeRawBufferPointer(buffer), owner: owner) + public init( + _unsafeBytes buffer: UnsafeMutableRawBufferPointer + ) -> dependsOn(immortal) Self { + self.init(_unsafeBytes: UnsafeRawBufferPointer(buffer)) + } + + @_alwaysEmitIntoClient + public init( + _unsafeBytes buffer: Slice + ) -> dependsOn(immortal) Self { + self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer)) } /// Unsafely create a `RawSpan` over initialized memory. @@ -88,14 +95,67 @@ extension RawSpan { /// - byteCount: the number of initialized bytes in the span. /// - owner: a binding whose lifetime must exceed that of /// the newly created `RawSpan`. - @inlinable @inline(__always) - public init( - unsafeStart pointer: UnsafeRawPointer, - byteCount: Int, - owner: borrowing Owner - ) { + @_alwaysEmitIntoClient + public init( + _unsafeStart pointer: UnsafeRawPointer, + byteCount: Int + ) -> dependsOn(immortal) Self { precondition(byteCount >= 0, "Count must not be negative") - self.init(_unchecked: pointer, byteCount: byteCount, owner: owner) + self.init(_unchecked: pointer, byteCount: byteCount) + } + + /// Unsafely create a `RawSpan` over initialized memory. + /// + /// The memory in `buffer` must be owned by the instance `owner`, + /// meaning that as long as `owner` is alive the memory will remain valid. + /// + /// - Parameters: + /// - buffer: an `UnsafeRawBufferPointer` to initialized memory. + /// - owner: a binding whose lifetime must exceed that of + /// the newly created `RawSpan`. + @_alwaysEmitIntoClient + public init( + _unsafeElements buffer: UnsafeBufferPointer + ) -> dependsOn(immortal) Self { + self.init(_unsafeBytes: UnsafeRawBufferPointer(buffer)) + } + + /// Unsafely create a `RawSpan` over initialized memory. + /// + /// The memory in `buffer` must be owned by the instance `owner`, + /// meaning that as long as `owner` is alive the memory will remain valid. + /// + /// - Parameters: + /// - buffer: an `UnsafeMutableRawBufferPointer` to initialized memory. + /// - owner: a binding whose lifetime must exceed that of + /// the newly created `RawSpan`. + @_alwaysEmitIntoClient + public init( + _unsafeElements buffer: UnsafeMutableBufferPointer + ) -> dependsOn(immortal) Self { + self.init(_unsafeElements: UnsafeBufferPointer(buffer)) + } + + /// Unsafely create a `RawSpan` over initialized memory. + /// + /// The memory over `count` bytes starting at + /// `pointer` must be owned by the instance `owner`, + /// meaning that as long as `owner` is alive the memory will remain valid. + /// + /// - Parameters: + /// - pointer: a pointer to the first initialized byte. + /// - byteCount: the number of initialized bytes in the span. + /// - owner: a binding whose lifetime must exceed that of + /// the newly created `RawSpan`. + @_alwaysEmitIntoClient + public init( + _unsafeStart pointer: UnsafePointer, + count: Int + ) -> dependsOn(immortal) Self { + precondition(count >= 0, "Count must not be negative") + self.init( + _unchecked: pointer, byteCount: count*MemoryLayout.stride + ) } /// Create a `RawSpan` over the memory represented by a `Span` @@ -103,32 +163,24 @@ extension RawSpan { /// - Parameters: /// - span: An existing `Span`, which will define both this /// `RawSpan`'s lifetime and the memory it represents. - @inlinable @inline(__always) - public init(_ span: borrowing Span) { + @_alwaysEmitIntoClient + public init( + _unsafeSpan span: borrowing Span + ) -> dependsOn(immortal) Self { self.init( _unchecked: UnsafeRawPointer(span._start), - byteCount: span.count * MemoryLayout.stride, - owner: span + byteCount: span.count &* MemoryLayout.stride ) } } -extension RawSpan { - /// Returns a Boolean value indicating whether two `RawSpan` instances - /// refer to the same region in memory. - @inlinable @inline(__always) - public static func ===(_ a: Self, _ b: Self) -> Bool { - (a._pointer == b._pointer) && (a._count == b._count) - } -} - extension RawSpan { private var _address: String { String(UInt(bitPattern: _pointer), radix: 16, uppercase: false) } - public var description: String { + public var _description: String { "(0x\(_address), \(_count))" } } @@ -141,13 +193,13 @@ extension RawSpan { /// instead of comparing `count` to zero. /// /// - Complexity: O(1) - @inlinable @inline(__always) + @_alwaysEmitIntoClient public var byteCount: Int { _count } /// A Boolean value indicating whether the span is empty. /// /// - Complexity: O(1) - @inlinable @inline(__always) + @_alwaysEmitIntoClient public var isEmpty: Bool { byteCount == 0 } /// The indices that are valid for subscripting the span, in ascending @@ -163,46 +215,34 @@ extension RawSpan { //MARK: Bounds Checking extension RawSpan { - /// Return true if `offset` is a valid offset into this `RawSpan` + /// Return true if `offset` is a valid byte offset into this `RawSpan` /// /// - Parameters: - /// - position: an index to validate - /// - Returns: true if `offset` is a valid index - @inlinable @inline(__always) - public func validateBounds(_ offset: Int) -> Bool { + /// - position: a byte offset to validate + /// - Returns: true if `offset` is a valid byte offset + @_alwaysEmitIntoClient + public func boundsContain(_ offset: Int) -> Bool { 0 <= offset && offset < byteCount } - /// Traps if `offset` is not a valid offset into this `RawSpan` - /// - /// - Parameters: - /// - position: an index to validate - @inlinable @inline(__always) - public func assertValidity(_ offset: Int) { - precondition( - validateBounds(offset), "Offset out of bounds" - ) - } - /// Return true if `offsets` is a valid range of offsets into this `RawSpan` /// /// - Parameters: - /// - offsets: a range of indices to validate - /// - Returns: true if `offsets` is a valid range of indices - @inlinable @inline(__always) - public func validateBounds(_ offsets: Range) -> Bool { - 0 <= offsets.lowerBound && offsets.upperBound <= byteCount + /// - offsets: a range of byte offsets to validate + /// - Returns: true if `offsets` is a valid range of byte offsets + @_alwaysEmitIntoClient + public func boundsContain(_ offsets: Range) -> Bool { + boundsContain(offsets.lowerBound) && offsets.upperBound <= byteCount } - /// Traps if `offsets` is not a valid range of offsets into this `RawSpan` + /// Return true if `offsets` is a valid range of offsets into this `RawSpan` /// /// - Parameters: - /// - offsets: a range of indices to validate - @inlinable @inline(__always) - public func assertValidity(_ offsets: Range) { - precondition( - validateBounds(offsets), "Range of offsets out of bounds" - ) + /// - offsets: a range of byte offsets to validate + /// - Returns: true if `offsets` is a valid range of byte offsets + @_alwaysEmitIntoClient + public func boundsContain(_ offsets: ClosedRange) -> Bool { + boundsContain(offsets.lowerBound) && offsets.upperBound < byteCount } } @@ -222,10 +262,15 @@ extension RawSpan { /// - Returns: A span over the bytes within `bounds` /// /// - Complexity: O(1) - @inlinable @inline(__always) - public func extracting(_ bounds: Range) -> Self { - assertValidity(bounds) - return extracting(unchecked: bounds) + @_alwaysEmitIntoClient + @usableFromInline func _extracting(_ bounds: Range) -> Self { + precondition(boundsContain(bounds)) + return _extracting(unchecked: bounds) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(to bounds: Range) { + self = _extracting(bounds) } /// Constructs a new span over the bytes within the supplied range of @@ -243,15 +288,19 @@ extension RawSpan { /// - Returns: A span over the bytes within `bounds` /// /// - Complexity: O(1) - @inlinable @inline(__always) - public func extracting(unchecked bounds: Range) -> Self { + @_alwaysEmitIntoClient + @usableFromInline func _extracting(unchecked bounds: Range) -> Self { RawSpan( _unchecked: _pointer?.advanced(by: bounds.lowerBound), - byteCount: bounds.count, - owner: self + byteCount: bounds.count ) } + @_alwaysEmitIntoClient + public mutating func _shrink(toUnchecked bounds: Range) { + self = _extracting(unchecked: bounds) + } + /// Constructs a new span over the bytes within the supplied range of /// positions within this span. /// @@ -266,8 +315,13 @@ extension RawSpan { /// /// - Complexity: O(1) @_alwaysEmitIntoClient - public func extracting(_ bounds: some RangeExpression) -> Self { - extracting(bounds.relative(to: _byteOffsets)) + @usableFromInline func _extracting(_ bounds: some RangeExpression) -> Self { + _extracting(bounds.relative(to: _byteOffsets)) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(_ bounds: some RangeExpression) { + self = _extracting(bounds) } /// Constructs a new span over the bytes within the supplied range of @@ -286,10 +340,15 @@ extension RawSpan { /// /// - Complexity: O(1) @_alwaysEmitIntoClient - public func extracting( + @usableFromInline func _extracting( unchecked bounds: some RangeExpression ) -> Self { - extracting(unchecked: bounds.relative(to: _byteOffsets)) + _extracting(unchecked: bounds.relative(to: _byteOffsets)) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(toUnchecked bounds: some RangeExpression) { + self = _extracting(unchecked: bounds) } /// Constructs a new span over all the bytes of this span. @@ -302,7 +361,7 @@ extension RawSpan { /// /// - Complexity: O(1) @_alwaysEmitIntoClient - public func extracting(_: UnboundedRange) -> Self { + @usableFromInline func _extracting(_: UnboundedRange) -> Self { self } } @@ -352,7 +411,7 @@ extension RawSpan { public func unsafeView( as type: T.Type ) -> Span { - Span(unsafeStart: _start, byteCount: byteCount, owner: self) + Span(_unsafeStart: _start, byteCount: byteCount) } } @@ -376,13 +435,13 @@ extension RawSpan { /// - 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. - @inlinable @inline(__always) + @_alwaysEmitIntoClient public func unsafeLoad( fromByteOffset offset: Int = 0, as: T.Type ) -> T { - assertValidity( + precondition(boundsContain( Range(uncheckedBounds: (offset, offset+MemoryLayout.size)) - ) + )) return unsafeLoad(fromUncheckedByteOffset: offset, as: T.self) } @@ -404,7 +463,7 @@ extension RawSpan { /// - 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. - @inlinable @inline(__always) + @_alwaysEmitIntoClient public func unsafeLoad( fromUncheckedByteOffset offset: Int, as: T.Type ) -> T { @@ -431,9 +490,9 @@ extension RawSpan { public func unsafeLoadUnaligned( fromByteOffset offset: Int = 0, as: T.Type ) -> T { - assertValidity( + precondition(boundsContain( Range(uncheckedBounds: (offset, offset+MemoryLayout.size)) - ) + )) return unsafeLoadUnaligned(fromUncheckedByteOffset: offset, as: T.self) } @@ -463,19 +522,11 @@ extension RawSpan { } extension RawSpan { - - /// Returns true if the memory represented by `span` is a subrange of - /// the memory represented by `self` - /// - /// Parameters: - /// - span: a span of the same type as `self` - /// Returns: whether `span` is a subrange of `self` - @inlinable @inline(__always) - public func contains(_ span: borrowing Self) -> Bool { - if span._count > _count { return false } - if _count == 0 || span._count == 0 { return true } - if _start > span._start { return false } - return span._start.advanced(by: span._count) <= _start.advanced(by: _count) + /// 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 @@ -486,15 +537,17 @@ extension RawSpan { /// Parameters: /// - span: a subrange of `self` /// Returns: A range of offsets within `self` - @inlinable @inline(__always) - public func offsets(of span: borrowing Self) -> Range { - precondition(contains(span)) - var (s, e) = (0, 0) - if _pointer != nil && span._pointer != nil { - s = _start.distance(to: span._start) - e = s + span._count + @_alwaysEmitIntoClient + public func byteOffsets(of span: borrowing Self) -> Range? { + if span._count > _count { return nil } + guard let subspanStart = span._pointer, _count > 0 else { + return _pointer == span._pointer ? Range(uncheckedBounds: (0, 0)) : nil } - return Range(uncheckedBounds: (s, e)) + if subspanStart < _start { return nil } + let lower = _start.distance(to: subspanStart) + let upper = lower + span._count + guard upper <= _count else { return nil } + return Range(uncheckedBounds: (lower, upper)) } } @@ -516,11 +569,16 @@ extension RawSpan { /// - Returns: A span with at most `maxLength` bytes. /// /// - Complexity: O(1) - @inlinable - public func extracting(first maxLength: Int) -> Self { + @_alwaysEmitIntoClient + @usableFromInline 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, owner: self) + return Self(_unchecked: _pointer, byteCount: newCount) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(toFirst maxLength: Int) { + self = _extracting(first: maxLength) } /// Returns a span over all but the given number of trailing bytes. @@ -537,11 +595,16 @@ extension RawSpan { /// - Returns: A span leaving off the specified number of bytes at the end. /// /// - Complexity: O(1) - @inlinable - public func extracting(droppingLast k: Int) -> Self { + @_alwaysEmitIntoClient + @usableFromInline func _extracting(droppingLast k: Int) -> Self { precondition(k >= 0, "Can't drop a negative number of elements.") let dc = min(k, byteCount) - return Self(_unchecked: _pointer, byteCount: byteCount&-dc, owner: self) + return Self(_unchecked: _pointer, byteCount: byteCount&-dc) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(droppingLast k: Int) { + self = _extracting(droppingLast: k) } /// Returns a span containing the trailing bytes of the span, @@ -559,12 +622,17 @@ extension RawSpan { /// - Returns: A span with at most `maxLength` bytes. /// /// - Complexity: O(1) - @inlinable - public func extracting(last maxLength: Int) -> Self { + @_alwaysEmitIntoClient + @usableFromInline 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, owner: self) + return Self(_unchecked: newStart, byteCount: newCount) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(toLast maxLength: Int) { + self = _extracting(last: maxLength) } /// Returns a span over all but the given number of initial bytes. @@ -581,120 +649,16 @@ extension RawSpan { /// - Returns: A span starting after the specified number of bytes. /// /// - Complexity: O(1) - @inlinable - public func extracting(droppingFirst k: Int) -> Self { + @_alwaysEmitIntoClient + @usableFromInline func _extracting(droppingFirst k: Int) -> Self { precondition(k >= 0, "Can't drop a negative number of elements.") let dc = min(k, byteCount) let newStart = _pointer?.advanced(by: dc) - return Self(_unchecked: newStart, byteCount: byteCount&-dc, owner: self) - } -} - -/// An error indicating that out-of-bounds access was attempted -@frozen -public struct OutOfBoundsError: Error { - /// The number of elements expected - public var expected: Int - - /// The number of elements found - public var has: Int - - @inlinable - public init(expected: Int, has: Int) { - (self.expected, self.has) = (expected, has) - } -} - -extension RawSpan { - /// Parse an instance of `T`, advancing `position`. - @inlinable - public func parse( - _ position: inout Int, as t: T.Type = T.self - ) throws(OutOfBoundsError) -> T { - let length = MemoryLayout.size - guard position >= 0 else { - throw OutOfBoundsError(expected: length, has: 0) - } - let end = position &+ length - guard end <= length else { - throw OutOfBoundsError(expected: length, has: byteCount&-position) - } - return unsafeLoadUnaligned(fromUncheckedByteOffset: position, as: T.self) - } - - /// Parse `numBytes` of data, advancing `position`. - @inlinable - public func parse( - _ position: inout Int, numBytes: some FixedWidthInteger - ) throws (OutOfBoundsError) -> Self { - let length = Int(numBytes) - guard position >= 0 else { - throw OutOfBoundsError(expected: length, has: 0) - } - let end = position &+ length - guard end <= length else { - throw OutOfBoundsError(expected: length, has: byteCount&-position) - } - return extracting(position.. - - /// The current parsing position - public var position: Int - - @inlinable - public init(_ base: RawSpan, in range: Range) { - base.assertValidity(range) - position = 0 - self.base = base - parseRange = range - } - - @inlinable - public init(_ base: RawSpan) { - position = 0 - self.base = base - parseRange = base._byteOffsets - } - - /// Parse an instance of `T` and advance - @inlinable - public mutating func parse( - _ t: T.Type = T.self - ) throws(OutOfBoundsError) -> T { - try base.parse(&position, as: T.self) - } - - /// Parse `numBytes`and advance - @inlinable - public mutating func parse( - numBytes: some FixedWidthInteger - ) throws (OutOfBoundsError) -> RawSpan { - try base.parse(&position, numBytes: numBytes) - } - - /// The bytes that we've parsed so far - @inlinable - public var parsedBytes: RawSpan { base.extracting(.. Cursor { Cursor(self) } - - @inlinable - public func makeCursor(in range: Range) -> Cursor { - Cursor(self, in: range) + return Self(_unchecked: newStart, byteCount: byteCount&-dc) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(droppingFirst k: Int) { + self = _extracting(droppingFirst: k) } } diff --git a/Sources/Future/Span+Iterator.swift b/Sources/Future/Span+Iterator.swift new file mode 100644 index 00000000..d808ff38 --- /dev/null +++ b/Sources/Future/Span+Iterator.swift @@ -0,0 +1,59 @@ +//===--- 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? + + public init(from span: consuming Span) -> dependsOn(immortal) Self { + 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 index 738bd569..8be06ca1 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -14,50 +14,42 @@ import Builtin // A Span represents a span of memory which // contains initialized instances of `Element`. +@_disallowFeatureSuppression(NonescapableTypes) @frozen -public struct Span: Copyable, ~Escapable { - @usableFromInline - internal let _buffer: UnsafeBufferPointer +public struct Span: Copyable, ~Escapable { + @usableFromInline let _pointer: UnsafeRawPointer? @usableFromInline @inline(__always) - internal var _pointer: UnsafePointer? { _buffer.baseAddress } + var _start: UnsafeRawPointer { _pointer.unsafelyUnwrapped } + @usableFromInline let _count: Int + + @_disallowFeatureSuppression(NonescapableTypes) @usableFromInline @inline(__always) - internal var _start: UnsafePointer { _pointer.unsafelyUnwrapped } - - @usableFromInline @inline(__always) - internal var _count: Int { _buffer.count } - - @inlinable @inline(__always) - internal init( - _unchecked elements: UnsafeBufferPointer, - owner: borrowing Owner - ) { - _buffer = elements - } - - @inlinable @inline(__always) - internal init( - _unchecked start: UnsafePointer?, - count: Int, - owner: borrowing Owner - ) { - self.init(_unchecked: .init(start: start, count: count), owner: owner) + init( + _unchecked start: UnsafeRawPointer?, + count: Int + ) -> dependsOn(immortal) Self { + _pointer = start + _count = count } } +@_disallowFeatureSuppression(NonescapableTypes) @available(*, unavailable) extension Span: Sendable {} -extension UnsafePointer where Pointee: ~Copyable /*& ~Escapable*/ { +@_disallowFeatureSuppression(NonescapableTypes) +extension Span where Element: ~Copyable { + @_disallowFeatureSuppression(NonescapableTypes) @usableFromInline @inline(__always) - var isAligned: Bool { - (Int(bitPattern: self) & (MemoryLayout.alignment-1)) == 0 + internal init( + _unchecked elements: UnsafeBufferPointer + ) -> dependsOn(immortal) Self { + _pointer = .init(elements.baseAddress) + _count = elements.count } -} - -extension Span where Element: ~Copyable /*& ~Escapable*/ { /// Unsafely create a `Span` over initialized memory. /// @@ -68,16 +60,17 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - buffer: an `UnsafeBufferPointer` to initialized elements. /// - owner: a binding whose lifetime must exceed that of /// the newly created `Span`. - @inlinable @inline(__always) - public init( - unsafeElements buffer: UnsafeBufferPointer, - owner: borrowing Owner - ) { + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeElements buffer: UnsafeBufferPointer + ) -> dependsOn(immortal) Self { precondition( - buffer.count == 0 || buffer.baseAddress.unsafelyUnwrapped.isAligned, - "baseAddress must be properly aligned for accessing \(Element.self)" + ((Int(bitPattern: buffer.baseAddress) & + (MemoryLayout.alignment&-1)) == 0), + "baseAddress must be properly aligned to access Element" ) - self.init(_unchecked: buffer, owner: owner) + self.init(_unchecked: buffer) } /// Unsafely create a `Span` over initialized memory. @@ -89,12 +82,12 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - buffer: an `UnsafeMutableBufferPointer` to initialized elements. /// - owner: a binding whose lifetime must exceed that of /// the newly created `Span`. + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public init( - unsafeElements buffer: UnsafeMutableBufferPointer, - owner: borrowing Owner - ) { - self.init(unsafeElements: UnsafeBufferPointer(buffer), owner: owner) + public init( + _unsafeElements buffer: UnsafeMutableBufferPointer + ) -> dependsOn(immortal) Self { + self.init(_unsafeElements: UnsafeBufferPointer(buffer)) } /// Unsafely create a `Span` over initialized memory. @@ -108,78 +101,40 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - count: the number of initialized elements in the span. /// - owner: a binding whose lifetime must exceed that of /// the newly created `Span`. - @inlinable @inline(__always) - public init( - unsafeStart start: UnsafePointer, - count: Int, - owner: borrowing Owner - ) { + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeStart start: UnsafePointer, + count: Int + ) -> dependsOn(immortal) Self { precondition(count >= 0, "Count must not be negative") - precondition( - start.isAligned, - "baseAddress must be properly aligned for accessing \(Element.self)" - ) - self.init(_unchecked: start, count: count, owner: owner) + self.init(_unsafeElements: .init(start: start, count: count)) } } +@_disallowFeatureSuppression(NonescapableTypes) +extension Span { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeElements buffer: Slice> + ) -> dependsOn(immortal) Self { + self.init(_unsafeElements: UnsafeBufferPointer(rebasing: buffer)) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeElements buffer: Slice> + ) -> dependsOn(immortal) Self { + self.init(_unsafeElements: UnsafeBufferPointer(rebasing: buffer)) + } +} + +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: BitwiseCopyable { - /// Unsafely create a `Span` over initialized memory. - /// - /// The memory in `buffer` must be owned by the instance `owner`, - /// meaning that as long as `owner` is alive the memory will remain valid. - /// - /// - Parameters: - /// - buffer: an `UnsafeBufferPointer` to initialized elements. - /// - owner: a binding whose lifetime must exceed that of - /// the newly created `Span`. - @inlinable @inline(__always) - public init( - unsafeElements buffer: UnsafeBufferPointer, - owner: borrowing Owner - ) { - self.init(_unchecked: buffer, owner: owner) - } - - /// Unsafely create a `Span` over initialized memory. - /// - /// The memory in `buffer` must be owned by the instance `owner`, - /// meaning that as long as `owner` is alive the memory will remain valid. - /// - /// - Parameters: - /// - buffer: an `UnsafeMutableBufferPointer` to initialized elements. - /// - owner: a binding whose lifetime must exceed that of - /// the newly created `Span`. - @_alwaysEmitIntoClient - public init( - unsafeElements buffer: UnsafeMutableBufferPointer, - owner: borrowing Owner - ) { - self.init(unsafeElements: UnsafeBufferPointer(buffer), owner: owner) - } - - /// Unsafely create a `Span` over initialized memory. - /// - /// The memory representing `count` instances starting at - /// `pointer` must be owned by the instance `owner`, - /// meaning that as long as `owner` is alive the memory will remain valid. - /// - /// - Parameters: - /// - pointer: a pointer to the first initialized element. - /// - count: the number of initialized elements in the span. - /// - owner: a binding whose lifetime must exceed that of - /// the newly created `Span`. - @inlinable @inline(__always) - public init( - unsafeStart start: UnsafePointer, - count: Int, - owner: borrowing Owner - ) { - precondition(count >= 0, "Count must not be negative") - self.init(_unchecked: start, count: count, owner: owner) - } - /// Unsafely create a `Span` over initialized memory. /// /// The memory in `unsafeBytes` must be owned by the instance `owner` @@ -194,20 +149,20 @@ extension Span where Element: BitwiseCopyable { /// - type: the type to use when interpreting the bytes in memory. /// - owner: a binding whose lifetime must exceed that of /// the newly created `Span`. - @inlinable @inline(__always) - public init( - unsafeBytes buffer: UnsafeRawBufferPointer, - owner: borrowing Owner - ) { + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeBytes buffer: UnsafeRawBufferPointer + ) -> dependsOn(immortal) Self { + precondition( + ((Int(bitPattern: buffer.baseAddress) & + (MemoryLayout.alignment&-1)) == 0), + "baseAddress must be properly aligned to access Element" + ) let (byteCount, stride) = (buffer.count, MemoryLayout.stride) - assert(byteCount >= 0, "Count must not be negative") let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride) - precondition(remainder == 0) - self.init( - _unchecked: buffer.baseAddress?.assumingMemoryBound(to: Element.self), - count: count, - owner: owner - ) + precondition(remainder == 0, "Span must contain a whole number of elements") + self.init(_unchecked: buffer.baseAddress, count: count) } /// Unsafely create a `Span` over initialized memory. @@ -224,12 +179,12 @@ extension Span where Element: BitwiseCopyable { /// - type: the type to use when interpreting the bytes in memory. /// - owner: a binding whose lifetime must exceed that of /// the newly created `Span`. + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public init( - unsafeBytes buffer: UnsafeMutableRawBufferPointer, - owner: borrowing Owner - ) { - self.init(unsafeBytes: UnsafeRawBufferPointer(buffer), owner: owner) + public init( + _unsafeBytes buffer: UnsafeMutableRawBufferPointer + ) -> dependsOn(immortal) Self { + self.init(_unsafeBytes: UnsafeRawBufferPointer(buffer)) } /// Unsafely create a `Span` over initialized memory. @@ -243,24 +198,34 @@ extension Span where Element: BitwiseCopyable { /// - count: the number of initialized elements in the span. /// - owner: a binding whose lifetime must exceed that of /// the newly created `Span`. - @inlinable @inline(__always) - public init( - unsafeStart pointer: UnsafeRawPointer, - byteCount: Int, - owner: borrowing Owner - ) { + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeStart pointer: UnsafeRawPointer, + byteCount: Int + ) -> dependsOn(immortal) Self { precondition(byteCount >= 0, "Count must not be negative") - let stride = MemoryLayout.stride - let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride) - precondition(remainder == 0) - self.init( - _unchecked: pointer.assumingMemoryBound(to: Element.self), - count: count, - owner: owner - ) + self.init(_unsafeBytes: .init(start: pointer, count: byteCount)) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeBytes buffer: Slice + ) -> dependsOn(immortal) Self { + self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer)) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeBytes buffer: Slice + ) -> dependsOn(immortal) Self { + self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer)) } } +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: Equatable { /// Returns a Boolean value indicating whether this and another span @@ -273,6 +238,8 @@ extension Span where Element: Equatable { /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient public func _elementsEqual(_ other: Self) -> Bool { guard count == other.count else { return false } if count == 0 { return true } @@ -299,7 +266,8 @@ extension Span where Element: Equatable { /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. - @inlinable + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient public func _elementsEqual(_ other: some Collection) -> Bool { guard count == other.count else { return false } if count == 0 { return true } @@ -317,7 +285,8 @@ extension Span where Element: Equatable { /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. - @inlinable + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient public func _elementsEqual(_ other: some Sequence) -> Bool { var offset = 0 for otherElement in other { @@ -329,27 +298,18 @@ extension Span where Element: Equatable { } } -extension Span where Element: ~Copyable /*& ~Escapable*/ { - /// Returns a Boolean value indicating whether two `RawSpan` instances - /// refer to the same region in memory. - @inlinable @inline(__always) - public static func ===(_ a: Self, _ b: Self) -> Bool { - (a._pointer == b._pointer) && (a._count == b._count) - } -} - -extension Span where Element: ~Copyable /*& ~Escapable*/ { - - private var _address: String { - String(UInt(bitPattern: _pointer), radix: 16, uppercase: false) - } +@_disallowFeatureSuppression(NonescapableTypes) +extension Span where Element: ~Copyable { + @_alwaysEmitIntoClient public var description: String { - "(0x\(_address), \(_count))" + let addr = String(UInt(bitPattern: _pointer), radix: 16, uppercase: false) + return "(0x\(addr), \(_count))" } } -extension Span where Element: ~Copyable /*& ~Escapable*/ { +@_disallowFeatureSuppression(NonescapableTypes) +extension Span where Element: ~Copyable { /// The number of elements in the span. /// @@ -357,13 +317,13 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// instead of comparing `count` to zero. /// /// - Complexity: O(1) - @inlinable @inline(__always) + @_alwaysEmitIntoClient public var count: Int { _count } /// A Boolean value indicating whether the span is empty. /// /// - Complexity: O(1) - @inlinable @inline(__always) + @_alwaysEmitIntoClient public var isEmpty: Bool { _count == 0 } /// The indices that are valid for subscripting the span, in ascending @@ -372,67 +332,63 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - Complexity: O(1) @_alwaysEmitIntoClient public var _indices: Range { - .init(uncheckedBounds: (0, _count)) + Range(uncheckedBounds: (0, _count)) } } //MARK: Bounds Checking -extension Span where Element: ~Copyable /*& ~Escapable*/ { +@_disallowFeatureSuppression(NonescapableTypes) +extension Span where Element: ~Copyable { - /// Return true if `offset` is a valid offset into this `Span` + /// Return true if `index` is a valid offset into this `Span` /// /// - Parameters: - /// - position: an index to validate - /// - Returns: true if `offset` is a valid index - @inlinable @inline(__always) - public func validateBounds(_ offset: Int) -> Bool { - 0 <= offset && offset < count + /// - index: an index to validate + /// - Returns: true if `index` is valid + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func boundsContain(_ index: Int) -> Bool { + 0 <= index && index < _count } - /// Traps if `offset` is not a valid offset into this `Span` + /// Return true if `indices` is a valid range of indices into this `Span` /// /// - Parameters: - /// - position: an index to validate - @inlinable @inline(__always) - public func assertValidity(_ offset: Int) { - precondition( - validateBounds(offset), "Offset out of bounds" - ) + /// - 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 `offsets` is a valid range of offsets into this `Span` + /// Return true if `indices` is a valid range of indices into this `Span` /// /// - Parameters: - /// - offsets: a range of indices to validate - /// - Returns: true if `offsets` is a valid range of indices - @inlinable @inline(__always) - public func validateBounds(_ offsets: Range) -> Bool { - 0 <= offsets.lowerBound && offsets.upperBound <= count - } - - /// Traps if `offsets` is not a valid range of offsets into this `Span` - /// - /// - Parameters: - /// - offsets: a range of indices to validate - @inlinable @inline(__always) - public func assertValidity(_ offsets: Range) { - precondition( - validateBounds(offsets), "Range of offsets out of bounds" - ) + /// - indices: a range of indices to validate + /// - Returns: true if `indices` is a valid range of indices + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func boundsContain(_ indices: ClosedRange) -> Bool { + boundsContain(indices.lowerBound) && indices.upperBound < _count } } +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: BitwiseCopyable { /// Construct a RawSpan over the memory represented by this span /// /// - Returns: a RawSpan over the memory represented by this span - @inlinable @inline(__always) - public var rawSpan: RawSpan { RawSpan(self) } + @_disallowFeatureSuppression(NonescapableTypes) + @unsafe //FIXME: remove when the lifetime inference is fixed + @_alwaysEmitIntoClient + public var _unsafeRawSpan: RawSpan { RawSpan(_unsafeSpan: self) } } //MARK: integer offset subscripts -extension Span where Element: ~Copyable /*& ~Escapable*/ { +@_disallowFeatureSuppression(NonescapableTypes) +extension Span where Element: ~Copyable { /// Accesses the element at the specified position in the `Span`. /// @@ -440,10 +396,10 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// must be greater or equal to zero, and less than `count`. /// /// - Complexity: O(1) - @inlinable @inline(__always) + @_alwaysEmitIntoClient public subscript(_ position: Int) -> Element { _read { - assertValidity(position) + precondition(boundsContain(position), "index out of bounds") yield self[unchecked: position] } } @@ -456,14 +412,19 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// must be greater or equal to zero, and less than `count`. /// /// - Complexity: O(1) - @inlinable @inline(__always) + @unsafe + @_alwaysEmitIntoClient public subscript(unchecked position: Int) -> Element { _read { - yield _start.advanced(by: position).pointee + let element = _start.advanced(by: position&*MemoryLayout.stride) + let binding = Builtin.bindMemory(element._rawValue, count._builtinWordValue, Element.self) + defer { Builtin.rebindMemory(element._rawValue, binding) } + yield UnsafePointer(element._rawValue).pointee } } } +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: BitwiseCopyable { /// Accesses the element at the specified position in the `Span`. @@ -472,10 +433,10 @@ extension Span where Element: BitwiseCopyable { /// must be greater or equal to zero, and less than `count`. /// /// - Complexity: O(1) - @inlinable @inline(__always) + @_alwaysEmitIntoClient public subscript(_ position: Int) -> Element { get { - assertValidity(position) + precondition(boundsContain(position), "index out of bounds") return self[unchecked: position] } } @@ -488,17 +449,19 @@ extension Span where Element: BitwiseCopyable { /// must be greater or equal to zero, and less than `count`. /// /// - Complexity: O(1) - @inlinable @inline(__always) + @unsafe + @_alwaysEmitIntoClient public subscript(unchecked position: Int) -> Element { get { - let address = UnsafeRawPointer(_start.advanced(by: position)) + let address = _start.advanced(by: position&*MemoryLayout.stride) return address.loadUnaligned(as: Element.self) } } } //MARK: extracting sub-spans -extension Span where Element: ~Copyable /*& ~Escapable*/ { +@_disallowFeatureSuppression(NonescapableTypes) +extension Span where Element: ~Copyable { /// Constructs a new span over the items within the supplied range of /// positions within this span. @@ -513,10 +476,16 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - Returns: A `Span` over the items within `bounds` /// /// - Complexity: O(1) - @inlinable @inline(__always) - public func extracting(_ bounds: Range) -> Self { - assertValidity(bounds) - return extracting(unchecked: bounds) + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline func _extracting(_ bounds: Range) -> Self { + precondition(boundsContain(bounds), "index out of bounds") + return _extracting(unchecked: bounds) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func _shrink(to bounds: Range) { + self = _extracting(bounds) } /// Constructs a new span over the items within the supplied range of @@ -534,15 +503,22 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - Returns: A `Span` over the items within `bounds` /// /// - Complexity: O(1) - @inlinable @inline(__always) - public func extracting(unchecked bounds: Range) -> Self { + @_disallowFeatureSuppression(NonescapableTypes) + @unsafe + @usableFromInline func _extracting(unchecked bounds: Range) -> Self { Span( - _unchecked: _pointer?.advanced(by: bounds.lowerBound), - count: bounds.count, - owner: self + _unchecked: _pointer?.advanced(by: bounds.lowerBound&*MemoryLayout.stride), + count: bounds.count ) } + @_disallowFeatureSuppression(NonescapableTypes) + @unsafe + @_alwaysEmitIntoClient + public mutating func _shrink(toUnchecked bounds: Range) { + self = _extracting(unchecked: bounds) + } + /// Constructs a new span over the items within the supplied range of /// positions within this span. /// @@ -556,9 +532,15 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - Returns: A `Span` over the items within `bounds` /// /// - Complexity: O(1) + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline func _extracting(_ bounds: some RangeExpression) -> Self { + _extracting(bounds.relative(to: _indices)) + } + + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public func extracting(_ bounds: some RangeExpression) -> Self { - extracting(bounds.relative(to: _indices)) + public mutating func _shrink(to bounds: some RangeExpression) { + self = _extracting(bounds) } /// Constructs a new span over the items within the supplied range of @@ -576,11 +558,19 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - Returns: A `Span` over the items within `bounds` /// /// - Complexity: O(1) - @_alwaysEmitIntoClient - public func extracting( + @_disallowFeatureSuppression(NonescapableTypes) + @unsafe + @usableFromInline func _extracting( uncheckedBounds bounds: some RangeExpression ) -> Self { - extracting(unchecked: bounds.relative(to: _indices)) + _extracting(unchecked: bounds.relative(to: _indices)) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @unsafe + @_alwaysEmitIntoClient + public mutating func _shrink(toUnchecked bounds: some RangeExpression) { + self = _extracting(uncheckedBounds: bounds) } /// Constructs a new span over all the items of this span. @@ -592,14 +582,15 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - Returns: A `Span` over all the items of this span. /// /// - Complexity: O(1) - @_alwaysEmitIntoClient - public func extracting(_: UnboundedRange) -> Self { + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline func _extracting(_: UnboundedRange) -> Self { self } } //MARK: withUnsafePointer, etc. -extension Span where Element: ~Copyable /*& ~Escapable*/ { +@_disallowFeatureSuppression(NonescapableTypes) +extension Span where Element: ~Copyable { //FIXME: mark closure parameter as non-escaping /// Calls a closure with a pointer to the viewed contiguous storage. @@ -614,14 +605,21 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// 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. + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public func withUnsafeBufferPointer( + public func withUnsafeBufferPointer( _ body: (_ buffer: UnsafeBufferPointer) throws(E) -> Result ) throws(E) -> Result { - try body(.init(start: (count==0) ? nil : _start, count: count)) + guard let pointer = _pointer, count > 0 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)) } } +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: BitwiseCopyable { //FIXME: mark closure parameter as non-escaping @@ -639,11 +637,12 @@ extension Span where Element: BitwiseCopyable { /// The closure's parameter is valid only for the duration of /// its execution. /// - Returns: The return value of the `body` closure parameter. + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public func withUnsafeBytes( + public func withUnsafeBytes( _ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result ) throws(E) -> Result { - try RawSpan(self).withUnsafeBytes(body) + try RawSpan(_unsafeSpan: self).withUnsafeBytes(body) } } @@ -656,7 +655,7 @@ extension Span where Element: Copyable { /// If the span is empty, the value of this property is `nil`. /// /// - Returns: The first element in the span, or `nil` if empty - @inlinable + @_alwaysEmitIntoClient public var first: Element? { isEmpty ? nil : self[unchecked: 0] } @@ -666,50 +665,49 @@ extension Span where Element: Copyable { /// If the span is empty, the value of this property is `nil`. /// /// - Returns: The last element in the span, or `nil` if empty - @inlinable + @_alwaysEmitIntoClient public var last: Element? { isEmpty ? nil : self[unchecked: count &- 1] } } -extension Span where Element: ~Copyable /*& ~Escapable*/ { - - /// Returns true if the memory represented by `span` is a subrange of - /// the memory represented by `self` - /// - /// Parameters: - /// - span: a span of the same type as `self` - /// Returns: whether `span` is a subrange of `self` - @inlinable @inline(__always) - public func contains(_ span: borrowing Self) -> Bool { - if span._count > _count { return false } - if _count == 0 || span._count == 0 { return true } - if _start > span._start { return false } - return span._start.advanced(by: span._count) <= _start.advanced(by: _count) +@_disallowFeatureSuppression(NonescapableTypes) +extension Span where Element: ~Copyable { + /// Returns a Boolean value indicating whether two `Span` instances + /// refer to the same region in memory. + @_disallowFeatureSuppression(NonescapableTypes) + @_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` + /// 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 subrange of `self` - /// Returns: A range of offsets within `self` - @inlinable @inline(__always) - public func offsets(of span: borrowing Self) -> Range { - precondition(contains(span)) - var (s, e) = (0, 0) - if _pointer != nil && span._pointer != nil { - s = _start.distance(to: span._start) - e = s + span._count + /// - span: a span that may be a subrange of `self` + /// Returns: A range of indices within `self`, or `nil` + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func indices(of span: borrowing Self) -> Range? { + if span._count > _count { return nil } + guard let subspanStart = span._pointer, _count > 0 else { + return _pointer == span._pointer ? Range(uncheckedBounds: (0, 0)) : nil } - return Range(uncheckedBounds: (s, e)) + if subspanStart < _start { return nil } + let byteOffset = _start.distance(to: subspanStart) + let stride = MemoryLayout.stride + let (lower, r) = byteOffset.quotientAndRemainder(dividingBy: stride) + guard r == 0 else { return nil } + let upper = lower + span._count + guard upper <= _count else { return nil } + return Range(uncheckedBounds: (lower, upper)) } } //MARK: one-sided slicing operations -extension Span where Element: ~Copyable /*& ~Escapable*/ { +@_disallowFeatureSuppression(NonescapableTypes) +extension Span where Element: ~Copyable { /// Returns a span containing the initial elements of this span, /// up to the specified maximum length. @@ -726,11 +724,17 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - Returns: A span with at most `maxLength` elements. /// /// - Complexity: O(1) - @inlinable - public func extracting(first maxLength: Int) -> Self { + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline 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, owner: self) + return Self(_unchecked: _pointer, count: newCount) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func _shrink(toFirst maxLength: Int) { + self = _extracting(first: maxLength) } /// Returns a span over all but the given number of trailing elements. @@ -747,11 +751,17 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - Returns: A span leaving off the specified number of elements at the end. /// /// - Complexity: O(1) - @inlinable - public func extracting(droppingLast k: Int) -> Self { + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline 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, owner: self) + return Self(_unchecked: _pointer, count: count&-droppedCount) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func _shrink(droppingLast k: Int) { + self = _extracting(droppingLast: k) } /// Returns a span containing the final elements of the span, @@ -769,12 +779,18 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - Returns: A span with at most `maxLength` elements. /// /// - Complexity: O(1) - @inlinable - public func extracting(last maxLength: Int) -> Self { + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline func _extracting(last maxLength: Int) -> Self { precondition(maxLength >= 0, "Can't have a suffix of negative length.") let newCount = min(maxLength, count) - let newStart = _pointer?.advanced(by: count&-newCount) - return Self(_unchecked: newStart, count: newCount, owner: self) + let newStart = _pointer?.advanced(by: (count&-newCount)*MemoryLayout.stride) + return Self(_unchecked: newStart, count: newCount) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func _shrink(toLast maxLength: Int) { + self = _extracting(last: maxLength) } /// Returns a span over all but the given number of initial elements. @@ -791,11 +807,17 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - Returns: A span starting after the specified number of elements. /// /// - Complexity: O(1) - @inlinable - public func extracting(droppingFirst k: Int) -> Self { + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline func _extracting(droppingFirst k: Int) -> Self { precondition(k >= 0, "Can't drop a negative number of elements.") let droppedCount = min(k, count) - let newStart = _pointer?.advanced(by: droppedCount) - return Self(_unchecked: newStart, count: count&-droppedCount, owner: self) + let newStart = _pointer?.advanced(by: droppedCount*MemoryLayout.stride) + return Self(_unchecked: newStart, count: count&-droppedCount) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func _shrink(droppingFirst k: Int) { + self = _extracting(droppingFirst: k) } } diff --git a/Sources/Future/StdlibOutputSpanExtensions.swift b/Sources/Future/StdlibOutputSpanExtensions.swift new file mode 100644 index 00000000..cc392a3c --- /dev/null +++ b/Sources/Future/StdlibOutputSpanExtensions.swift @@ -0,0 +1,86 @@ +//===--- StdlibOutputSpanExtensions.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 Array { + + public init( + capacity: Int, + initializingWith initializer: (inout OutputSpan) throws -> Void + ) rethrows { + try self.init( + unsafeUninitializedCapacity: capacity, + initializingWith: { (buffer, count) in + var output = OutputSpan( + _initializing: buffer.baseAddress.unsafelyUnwrapped, + capacity: buffer.count + ) + try initializer(&output) + let initialized = output.relinquishBorrowedMemory() + assert(initialized.baseAddress == buffer.baseAddress) + count = initialized.count + } + ) + } +} + +extension String { + + // also see https://github.com/apple/swift/pull/23050 + // and `final class __SharedStringStorage` + + @available(macOS 11, *) + public init( + utf8Capacity capacity: Int, + initializingWith initializer: (inout OutputSpan) throws -> Void + ) rethrows { + try self.init( + unsafeUninitializedCapacity: capacity, + initializingUTF8With: { buffer in + var output = OutputSpan( + _initializing: buffer.baseAddress.unsafelyUnwrapped, + capacity: capacity + ) + try initializer(&output) + let initialized = output.relinquishBorrowedMemory() + assert(initialized.baseAddress == buffer.baseAddress) + return initialized.count + } + ) + } +} + +import Foundation + +extension Data { + + public init( + capacity: Int, + initializingWith initializer: (inout OutputSpan) throws -> Void + ) rethrows { + self = Data(count: capacity) // initialized with zeroed buffer + let count = try self.withUnsafeMutableBytes { rawBuffer in + try rawBuffer.withMemoryRebound(to: UInt8.self) { buffer in + buffer.deinitialize() + var output = OutputSpan( + _initializing: buffer.baseAddress.unsafelyUnwrapped, + capacity: capacity + ) + try initializer(&output) + let initialized = output.relinquishBorrowedMemory() + assert(initialized.baseAddress == buffer.baseAddress) + return initialized.count + } + } + assert(count <= self.count) + self.replaceSubrange(count..( + _ 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(_unsafeSpan: 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/MutableSpanTests.swift b/Tests/FutureTests/MutableSpanTests.swift new file mode 100644 index 00000000..8fa98487 --- /dev/null +++ b/Tests/FutureTests/MutableSpanTests.swift @@ -0,0 +1,491 @@ +//===--- MutableSpanTests.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 +@testable import Future + +class ID { + let id: Int + init(id: Int) { + self.id = id + } + deinit { + // print(id) + } +} + +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..(_unsafeBytes: $0) + XCTAssertEqual(b.count, capacity) + + let r = MutableSpan(_unsafeBytes: $0) + XCTAssertEqual(r.count, capacity*MemoryLayout.stride) + } + +// let v = UnsafeRawBufferPointer(start: nil, count: 0) +// XCTAssertNil(MutableSpan(unsafeRawBufferPointer: v)) + } + +// 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) + } + } + + func testSpanIndices() { + let capacity = 4 + var a = Array(0..(unsafeUninitializedCapacity: capacity) { + for i in $0.indices { + $0.initializeElement(at: i, to: .random(in: 0..<10)) + } + $1 = $0.count + } + a.withUnsafeMutableBufferPointer { + var v1 = MutableSpan(_unsafeElements: $0) + + XCTAssertEqual(v1._elementsEqual(Span(_unsafeMutableSpan: v1)._extracting(first: 1)), false) + XCTAssertEqual(Span(_unsafeMutableSpan: v1)._extracting(first: 0)._elementsEqual(Span(_unsafeMutableSpan: v1)._extracting(last: 0)), true) + XCTAssertEqual(v1._elementsEqual(v1), true) + XCTAssertEqual(Span(_unsafeMutableSpan: v1)._extracting(first: 3)._elementsEqual(Span(_unsafeMutableSpan: v1)._extracting(last: 3)), false) + + var b = v1.withUnsafeMutableBufferPointer { Array($0) } + b.withUnsafeMutableBufferPointer { + let v2 = MutableSpan(_unsafeElements: $0) + XCTAssertEqual(v1._elementsEqual(v2), true) + } + } + } + + func testElementsEqualCollection() { + let capacity = 4 + var a = Array(0..( + _unsafeElements: .init(start: $0.baseAddress, count: 0) + ) + emptySpan.withUnsafeMutableBufferPointer { + XCTAssertEqual($0.count, 0) + XCTAssertNil($0.baseAddress) + } + } + XCTAssertEqual(Int(a[i]), i+1) + } + + public func testWithUnsafeMutableBytes() { + let capacity: UInt8 = 64 + var a = Array(0..( + _unsafeElements: .init(start: $0.baseAddress, count: 0) + ) + emptySpan.withUnsafeMutableBytes { + XCTAssertEqual($0.count, 0) + XCTAssertNil($0.baseAddress) + } + } + XCTAssertEqual(Int(a[i]), i+1) + } + + public func testUpdateRepeatingBitwiseCopyable() { + var a = Array(0..<8) + XCTAssertEqual(a.contains(.max), false) + a.withUnsafeMutableBufferPointer { + var span = MutableSpan(_unsafeElements: $0) + span.update(repeating: .max) + } + XCTAssertEqual(a.allSatisfy({ $0 == .max }), true) + } + + public func testUpdateRepeating() { + var a = (0..<8).map(ID.init(id:)) + XCTAssertEqual(a.map(\.id).contains(.max), false) + a.withUnsafeMutableBufferPointer { + var span = MutableSpan(_unsafeElements: $0) + span.update(repeating: ID(id: .max)) + } + XCTAssertEqual(a.allSatisfy({ $0.id == .max }), true) + } + + public func testUpdateFromSequenceBitwiseCopyable() { + let capacity = 8 + 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)) + var (iterator, updated) = span.update(from: 0..<0) + XCTAssertNil(iterator.next()) + XCTAssertEqual(updated, 0) + + span = MutableSpan(_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) + } + XCTAssertEqual(a.elementsEqual(0...allocate(capacity: capacity) + + a.withUnsafeMutableBufferPointer { + var span = MutableSpan(_unsafeElements: $0) + + var o = OutputSpan(_initializing: b) + o.append(fromContentsOf: (0..: ~Copyable { + let allocation: UnsafeMutablePointer + let capacity: Int + var count: Int? = nil + + init(of count: Int = 1, _ t: T.Type) { + precondition(count >= 0) + capacity = count + allocation = UnsafeMutablePointer.allocate(capacity: capacity) + } + + var isInitialized: Bool { count != nil } + + mutating func initialize( + _ body: (/* mutating */ inout OutputSpan) throws -> Void + ) rethrows { + if count != nil { fatalError() } + var outputBuffer = OutputSpan( + _initializing: allocation, capacity: capacity + ) + do { + try body(&outputBuffer) + let initialized = outputBuffer.relinquishBorrowedMemory() + assert(initialized.baseAddress == allocation) + count = initialized.count + } + catch { + outputBuffer.deinitialize() + let empty = outputBuffer.relinquishBorrowedMemory() + assert(empty.baseAddress == allocation) + assert(empty.count == 0) + throw error + } + } + + borrowing func examine( + _ body: (borrowing Span) throws(E) -> R + ) throws(E) -> R { + try body(initializedPrefix) + } + + var initializedPrefix: Span { + Span(_unsafeStart: allocation, count: count ?? 0) + } + +// mutating func mutate( +// _ body: (/* mutating */ inout MutableBufferView) -> R +// ) -> R { +// guard let count else { fatalError() } +// var mutable = MutableBufferView( +// baseAddress: allocation, count: count, dependsOn: /*self*/ allocation +// ) +// return body(&mutable) +// } + + deinit { + if let count { + allocation.deinitialize(count: count) + } + allocation.deallocate() + } +} + +enum MyTestError: Error { case error } + +final class OutputBufferTests: XCTestCase { + + func testOutputBufferInitialization() { + let c = 48 + let allocation = UnsafeMutablePointer.allocate(capacity: c) + defer { allocation.deallocate() } + + let ob = OutputSpan(_initializing: allocation, capacity: c) + let initialized = ob.relinquishBorrowedMemory() + XCTAssertNotNil(initialized.baseAddress) + XCTAssertEqual(initialized.count, 0) + } + + func testInitializeBufferByAppendingElements() { + var a = Allocation(of: 48, Int.self) + let c = 10 + a.initialize { + for i in 0...c { + $0.appendElement(i) + } + let oops = $0.deinitializeLastElement() + XCTAssertEqual(oops, c) + } + a.examine { + XCTAssertEqual($0.count, c) + XCTAssert($0._elementsEqual(0..(_unsafeElements: .init(start: nil, count: 0)) + $0.append(fromContentsOf: storage) + } + #else + $0.append(fromContentsOf: array) + #endif + } + + let span = a.initializedPrefix + XCTAssertEqual(span.count, c) + XCTAssert(span._elementsEqual(0...allocate(capacity: c) + for i in 0.. 0) + throw MyTestError.error + } + } + catch MyTestError.error { + XCTAssertEqual(a.isInitialized, false) + } + } + + func testMutateOutputSpan() throws { + let b = UnsafeMutableBufferPointer.allocate(capacity: 10) + defer { b.deallocate() } + + var span = OutputSpan(_initializing: b) + XCTAssertEqual(span.count, 0) + span.append(fromContentsOf: 0..<10) + XCTAssertEqual(span.count, 10) + + 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 + } + + let r = span.relinquishBorrowedMemory() + print(Array(r)) + r.deinitialize() + } +} diff --git a/Tests/FutureTests/RawSpanTests.swift b/Tests/FutureTests/RawSpanTests.swift index bea88a64..984833c1 100644 --- a/Tests/FutureTests/RawSpanTests.swift +++ b/Tests/FutureTests/RawSpanTests.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// import XCTest -import Future +@testable import Future final class RawSpanTests: XCTestCase { @@ -30,14 +30,14 @@ final class RawSpanTests: XCTestCase { func testInitWithSpanOfIntegers() { let capacity = 4 let a = Array(0...stride) XCTAssertFalse(span.isEmpty) } func testInitWithEmptySpanOfIntegers() { let a: [Int] = [] - let span = RawSpan(a.storage) + let span = RawSpan(_unsafeSpan: a.storage) XCTAssertTrue(span.isEmpty) } @@ -45,12 +45,12 @@ final class RawSpanTests: XCTestCase { let capacity = 4 var a = Array(0...stride) } a.withUnsafeMutableBytes { - let span = RawSpan(unsafeBytes: $0, owner: $0) + let span = RawSpan(_unsafeBytes: $0) XCTAssertEqual(span.byteCount, capacity*MemoryLayout.stride) } } @@ -61,9 +61,8 @@ final class RawSpanTests: XCTestCase { a.withUnsafeBytes { let pointer = $0.baseAddress! let span = RawSpan( - unsafeStart: pointer, - byteCount: capacity*MemoryLayout.stride, - owner: a + _unsafeStart: pointer, + byteCount: capacity*MemoryLayout.stride ) XCTAssertEqual(span.byteCount, $0.count) } @@ -71,9 +70,8 @@ final class RawSpanTests: XCTestCase { a.withUnsafeMutableBytes { let pointer = $0.baseAddress! let span = RawSpan( - unsafeStart: pointer, - byteCount: capacity*MemoryLayout.stride, - owner: $0 + _unsafeStart: pointer, + byteCount: capacity*MemoryLayout.stride ) XCTAssertEqual(span.byteCount, $0.count) } @@ -83,7 +81,7 @@ final class RawSpanTests: XCTestCase { let capacity = 4 let s = (0...stride let s0 = span.unsafeLoad(as: String.self) @@ -99,9 +97,11 @@ final class RawSpanTests: XCTestCase { let capacity = 64 let a = Array(0.. - bounds = span.offsets(of: subSpan) - XCTAssertEqual(bounds, span._byteOffsets.suffix(2)) - bounds = span.offsets(of: emptySpan) - XCTAssertEqual(bounds, span._byteOffsets.prefix(0)) - bounds = span.offsets(of: nilSpan) - XCTAssertEqual(bounds, 0..<0) - bounds = nilSpan.offsets(of: emptySpan) + var bounds: Range? + bounds = span.byteOffsets(of: subSpan1) + XCTAssertEqual(bounds, span._byteOffsets.prefix(6)) + bounds = span.byteOffsets(of: subSpan2) + XCTAssertEqual(bounds, span._byteOffsets.suffix(6)) + bounds = subSpan2.byteOffsets(of: subSpan1) + XCTAssertNil(bounds) + bounds = subSpan1.byteOffsets(of: subSpan2) + XCTAssertNil(bounds) + bounds = subSpan2.byteOffsets(of: span) + XCTAssertNil(bounds) + bounds = nilSpan.byteOffsets(of: emptySpan) + XCTAssertNil(bounds) + bounds = span.byteOffsets(of: nilSpan) + XCTAssertNil(bounds) + bounds = nilSpan.byteOffsets(of: nilSpan) XCTAssertEqual(bounds, 0..<0) } } diff --git a/Tests/FutureTests/SpanTests.swift b/Tests/FutureTests/SpanTests.swift index 8c9d3248..eede50cf 100644 --- a/Tests/FutureTests/SpanTests.swift +++ b/Tests/FutureTests/SpanTests.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// import XCTest -import Future +@testable import Future final class SpanTests: XCTestCase { @@ -31,19 +31,19 @@ final class SpanTests: XCTestCase { let capacity = 4 var s = (0..(unsafeBytes: $0, owner: $0) + let b = Span(_unsafeBytes: $0) XCTAssertEqual(b.count, capacity) - let r = Span(unsafeBytes: $0, owner: $0) + let r = Span(_unsafeBytes: $0) XCTAssertEqual(r.count, capacity*MemoryLayout.stride) let p = Span( - unsafeStart: $0.baseAddress!, - byteCount: capacity*MemoryLayout.stride, - owner: $0 + _unsafeStart: $0.baseAddress!, + byteCount: capacity*MemoryLayout.stride ) XCTAssertEqual(p.count, capacity) } a.withUnsafeMutableBytes { - let b = Span(unsafeBytes: $0, owner: $0) + let b = Span(_unsafeBytes: $0) XCTAssertEqual(b.count, capacity) let p = Span( - unsafeStart: $0.baseAddress!, - byteCount: capacity*MemoryLayout.stride, - owner: $0 + _unsafeStart: $0.baseAddress!, + byteCount: capacity*MemoryLayout.stride ) XCTAssertEqual(p.count, capacity) } @@ -100,11 +98,11 @@ final class SpanTests: XCTestCase { let capacity = 4 let a = Array(0...stride) } } @@ -124,7 +122,7 @@ final class SpanTests: XCTestCase { let capacity = 4 let a = Array(0..(start: nil, count: 0) - let span = Span(unsafeElements: b, owner: b) + let span = Span(_unsafeElements: b) XCTAssertEqual(span.count, b.count) - XCTAssertEqual(span.extracting(first: 1).count, b.count) - XCTAssertEqual(span.extracting(droppingLast: 1).count, b.count) + XCTAssertEqual(span._extracting(first: 1).count, b.count) + XCTAssertEqual(span._extracting(droppingLast: 1).count, b.count) } } @@ -276,21 +274,21 @@ final class SpanTests: XCTestCase { let capacity = 4 let a = Array(0..(unsafeElements: $0, owner: $0) + 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).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) } do { let b = UnsafeBufferPointer(start: nil, count: 0) - let span = Span(unsafeElements: b, owner: b) + let span = Span(_unsafeElements: b) XCTAssertEqual(span.count, b.count) - XCTAssertEqual(span.extracting(last: 1).count, b.count) - XCTAssertEqual(span.extracting(droppingFirst: 1).count, b.count) + XCTAssertEqual(span._extracting(last: 1).count, b.count) + XCTAssertEqual(span._extracting(droppingFirst: 1).count, b.count) } } public func testWithUnsafeBytes() { @@ -298,7 +296,7 @@ final class SpanTests: XCTestCase { let a = Array(0...allocate(capacity: 8) _ = b.initialize(fromContentsOf: 0..<8) defer { b.deallocate() } - let span = Span(unsafeElements: .init(b), owner: b) - let subSpan = span.extracting(last: 2) - let emptySpan = span.extracting(first: 0) - let fakeSpan = Span( - unsafeStart: b.baseAddress!.advanced(by: 8), count: 8, owner: b - ) - let nilSpan = Span( - unsafeElements: UnsafeBufferPointer(start: nil, count: 0), owner: b - ) + let span = Span(_unsafeElements: b) + let pre = span._extracting(first: 6) + let suf = span._extracting(last: 6) - XCTAssertTrue(span.contains(subSpan)) - XCTAssertFalse(subSpan.contains(span)) - XCTAssertTrue(span.contains(emptySpan)) - XCTAssertFalse(emptySpan.contains(span)) - XCTAssertFalse(span.contains(fakeSpan)) - XCTAssertFalse(fakeSpan.contains(span)) - XCTAssertTrue(span.contains(nilSpan)) - XCTAssertTrue(fakeSpan.contains(nilSpan)) - XCTAssertTrue(nilSpan.contains(emptySpan)) + XCTAssertFalse( + pre.isIdentical(to: suf) + ) + XCTAssertFalse( + pre.isIdentical(to: span) + ) + XCTAssertTrue( + pre._extracting(last: 4).isIdentical(to: suf._extracting(first: 4)) + ) } - func testOffsets() { + func testIndicesOf() { let b = UnsafeMutableBufferPointer.allocate(capacity: 8) _ = b.initialize(fromContentsOf: 0..<8) defer { b.deallocate() } - let span = Span(unsafeElements: .init(b), owner: b) - let subSpan = span.extracting(last: 2) - let emptySpan = span.extracting(first: 0) + let span = Span(_unsafeElements: b) + let subSpan1 = span._extracting(first: 6) + let subSpan2 = span._extracting(last: 6) + let emptySpan = span._extracting(first: 0) +/* This isn't relevant until we can support unaligned spans + let unalignedSpan = RawSpan(_unsafeSpan: span) + ._extracting(droppingFirst: 6) + ._extracting(droppingLast: 2) + .unsafeView(as: Int.self) +*/ let nilSpan = Span( - unsafeElements: UnsafeBufferPointer(start: nil, count: 0), owner: b + _unsafeElements: UnsafeBufferPointer(start: nil, count: 0) ) - var bounds: Range - bounds = span.offsets(of: subSpan) - XCTAssertEqual(bounds, span._indices.suffix(2)) - bounds = span.offsets(of: emptySpan) - XCTAssertEqual(bounds, span._indices.prefix(0)) - bounds = span.offsets(of: nilSpan) - XCTAssertEqual(bounds, 0..<0) - bounds = nilSpan.offsets(of: emptySpan) + var bounds: Range? + bounds = span.indices(of: subSpan1) + XCTAssertEqual(bounds, span._indices.prefix(6)) + bounds = span.indices(of: subSpan2) + XCTAssertEqual(bounds, span._indices.suffix(6)) + bounds = subSpan2.indices(of: subSpan1) + XCTAssertNil(bounds) + bounds = subSpan1.indices(of: subSpan2) + XCTAssertNil(bounds) + bounds = subSpan2.indices(of: span) + XCTAssertNil(bounds) + bounds = nilSpan.indices(of: emptySpan) + XCTAssertNil(bounds) + bounds = span.indices(of: nilSpan) + XCTAssertNil(bounds) + bounds = nilSpan.indices(of: nilSpan) 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 testTypeErasedSpanOfBitwiseCopyable() { + let b = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 8) + defer { b.deallocate() } + let initialized = b.initializeMemory(as: UInt8.self, fromContentsOf: 0..<64) + XCTAssertEqual(initialized.count, 64) + defer { initialized.deinitialize() } + + func test(_ span: Span) -> T { + span[0] + } + + // let span = Span(_unsafeBytes: b.dropFirst().dropLast(7)) + let span = Span(_unsafeBytes: b.dropFirst(4)) + let first = test(span) + XCTAssertEqual(first, 0x07060504) + } } diff --git a/Tests/FutureTests/StdlibOutputSpanExtensionTests.swift b/Tests/FutureTests/StdlibOutputSpanExtensionTests.swift new file mode 100644 index 00000000..a3c6847d --- /dev/null +++ b/Tests/FutureTests/StdlibOutputSpanExtensionTests.swift @@ -0,0 +1,53 @@ +//===--- StdlibOutputSpanExtensionTests.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 + +final class OutputBufferUsageTests: 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)) + } + }) + XCTAssertEqual(array.count, 16) + XCTAssert(array.elementsEqual(0..<16)) + XCTAssertGreaterThanOrEqual(array.capacity, 32) + } + + func testDataInitializationExample() { + var data: Data + data = Data(capacity: 32, initializingWith: { output in + for i in 0..<(output.capacity/2) { + output.appendElement(UInt8(clamping: i)) + } + }) + XCTAssertEqual(data.count, 16) + XCTAssert(data.elementsEqual(0..<16)) + } + + func testStringInitializationExample() { + var string: String + 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)) + } + }) + XCTAssertEqual(string.utf8.count, 16) + XCTAssert(string.utf8.elementsEqual(c..<(c+16))) + } +} diff --git a/Tests/FutureTests/StdlibSpanExtensionTests.swift b/Tests/FutureTests/StdlibSpanExtensionTests.swift new file mode 100644 index 00000000..4c31cfda --- /dev/null +++ b/Tests/FutureTests/StdlibSpanExtensionTests.swift @@ -0,0 +1,182 @@ +//===--- 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 { + print($0._indices) + 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/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift index b5ea03f2..9d012a8f 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift @@ -18,13 +18,13 @@ import _CollectionsTestSupport #endif class MeasuringHashable: Hashable { - static var equalityChecks = 0 + nonisolated(unsafe) static var equalityChecks = 0 static func == (lhs: MeasuringHashable, rhs: MeasuringHashable) -> Bool { MeasuringHashable.equalityChecks += 1 return lhs._inner == rhs._inner } - static var hashChecks = 0 + nonisolated(unsafe) static var hashChecks = 0 func hash(into hasher: inout Hasher) { MeasuringHashable.hashChecks += 1 _inner.hash(into: &hasher) diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift b/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift index ad3b89af..59816e67 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift @@ -20,7 +20,7 @@ public final class TestContext { internal var _trace: [Entry] = [] // FIXME: This ought to be a thread-local variable. - internal static var _current: TestContext? + nonisolated(unsafe) internal static var _current: TestContext? public init() {} }