diff --git a/Package.swift b/Package.swift index a46642cd..18ec08df 100644 --- a/Package.swift +++ b/Package.swift @@ -55,18 +55,14 @@ var defines: [String] = [ let _sharedSettings: [SwiftSetting] = defines.map { .define($0) } + [ .enableExperimentalFeature("BuiltinModule"), .enableExperimentalFeature("NonescapableTypes"), - .enableExperimentalFeature("BitwiseCopyable"), .enableExperimentalFeature("RawLayout"), .enableExperimentalFeature("SuppressedAssociatedTypes"), ] -let _settings: [SwiftSetting] = _sharedSettings + [ - .swiftLanguageMode(.v6), -] -let _testSettings: [SwiftSetting] = _sharedSettings + [ - .swiftLanguageMode(.v5), -] +let _settings: [SwiftSetting] = _sharedSettings + [] + +let _testSettings: [SwiftSetting] = _sharedSettings + [] struct CustomTarget { enum Kind { 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/RawSpan.swift b/Sources/Future/RawSpan.swift index 97b79d41..3f73b2ff 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,13 +45,12 @@ 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 ) } @@ -70,11 +64,10 @@ 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)) } /// Unsafely create a `RawSpan` over initialized memory. @@ -88,14 +81,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` @@ -107,8 +153,7 @@ extension RawSpan { public init(_ span: borrowing Span) { self.init( _unchecked: UnsafeRawPointer(span._start), - byteCount: span.count * MemoryLayout.stride, - owner: span + byteCount: span.count * MemoryLayout.stride ) } } @@ -247,8 +292,7 @@ extension RawSpan { public func extracting(unchecked bounds: Range) -> Self { RawSpan( _unchecked: _pointer?.advanced(by: bounds.lowerBound), - byteCount: bounds.count, - owner: self + byteCount: bounds.count ) } @@ -352,7 +396,7 @@ extension RawSpan { public func unsafeView( as type: T.Type ) -> Span { - Span(unsafeStart: _start, byteCount: byteCount, owner: self) + Span(_unsafeStart: _start, byteCount: byteCount) } } @@ -520,7 +564,7 @@ extension RawSpan { public func extracting(first maxLength: Int) -> Self { precondition(maxLength >= 0, "Can't have a prefix of negative length.") let newCount = min(maxLength, byteCount) - return Self(_unchecked: _pointer, byteCount: newCount, owner: self) + return Self(_unchecked: _pointer, byteCount: newCount) } /// Returns a span over all but the given number of trailing bytes. @@ -541,7 +585,7 @@ extension RawSpan { public 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) } /// Returns a span containing the trailing bytes of the span, @@ -564,7 +608,7 @@ extension RawSpan { 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) } /// Returns a span over all but the given number of initial bytes. @@ -586,7 +630,7 @@ extension RawSpan { 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) + return Self(_unchecked: newStart, byteCount: byteCount&-dc) } } diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index 738bd569..49f34940 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -16,33 +16,37 @@ import Builtin // contains initialized instances of `Element`. @frozen public struct Span: Copyable, ~Escapable { - @usableFromInline - internal let _buffer: UnsafeBufferPointer + @usableFromInline let _buffer: UnsafeBufferPointer @usableFromInline @inline(__always) - internal var _pointer: UnsafePointer? { _buffer.baseAddress } + var _pointer: UnsafePointer? { _buffer.baseAddress } @usableFromInline @inline(__always) - internal var _start: UnsafePointer { _pointer.unsafelyUnwrapped } + var _start: UnsafePointer { _pointer.unsafelyUnwrapped } + +// @usableFromInline @inline(__always) +// var _start: UnsafeRawPointer { _pointer.unsafelyUnwrapped } @usableFromInline @inline(__always) - internal var _count: Int { _buffer.count } + var _count: Int { _buffer.count } @inlinable @inline(__always) - internal init( - _unchecked elements: UnsafeBufferPointer, - owner: borrowing Owner - ) { + internal init( + _unchecked elements: UnsafeBufferPointer + ) -> dependsOn(immortal) Self { _buffer = elements +// _pointer = .init(elements.baseAddress) +// _count = elements.count } - @inlinable @inline(__always) - internal init( + @_alwaysEmitIntoClient + internal init( _unchecked start: UnsafePointer?, - count: Int, - owner: borrowing Owner - ) { - self.init(_unchecked: .init(start: start, count: count), owner: owner) + count: Int + ) -> dependsOn(immortal) Self { + self.init(_unchecked: .init(start: start, count: count)) +// _pointer = .init(start) +// _count = count } } @@ -68,16 +72,15 @@ 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 - ) { + @_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)" ) - self.init(_unchecked: buffer, owner: owner) + self.init(_unchecked: buffer) } /// Unsafely create a `Span` over initialized memory. @@ -90,11 +93,10 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// - 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) + public init( + _unsafeElements buffer: UnsafeMutableBufferPointer + ) -> dependsOn(immortal) Self { + self.init(_unsafeElements: UnsafeBufferPointer(buffer)) } /// Unsafely create a `Span` over initialized memory. @@ -108,18 +110,17 @@ 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 - ) { + @_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(_unchecked: start, count: count) } } @@ -134,12 +135,11 @@ extension Span where Element: BitwiseCopyable { /// - 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) + @_alwaysEmitIntoClient + public init( + _unsafeElements buffer: UnsafeBufferPointer + ) -> dependsOn(immortal) Self { + self.init(_unchecked: buffer) } /// Unsafely create a `Span` over initialized memory. @@ -152,11 +152,10 @@ extension Span where Element: BitwiseCopyable { /// - 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) + public init( + _unsafeElements buffer: UnsafeMutableBufferPointer + ) -> dependsOn(immortal) Self { + self.init(_unsafeElements: UnsafeBufferPointer(buffer)) } /// Unsafely create a `Span` over initialized memory. @@ -170,14 +169,13 @@ 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 start: UnsafePointer, - count: Int, - owner: borrowing Owner - ) { + @_alwaysEmitIntoClient + public init( + _unsafeStart start: UnsafePointer, + count: Int + ) -> dependsOn(immortal) Self { precondition(count >= 0, "Count must not be negative") - self.init(_unchecked: start, count: count, owner: owner) + self.init(_unchecked: start, count: count) } /// Unsafely create a `Span` over initialized memory. @@ -194,19 +192,17 @@ 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 - ) { + @_alwaysEmitIntoClient + public init( + _unsafeBytes buffer: UnsafeRawBufferPointer + ) -> dependsOn(immortal) Self { let (byteCount, stride) = (buffer.count, MemoryLayout.stride) - assert(byteCount >= 0, "Count must not be negative") + precondition(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 + count: count ) } @@ -225,11 +221,10 @@ extension Span where Element: BitwiseCopyable { /// - owner: a binding whose lifetime must exceed that of /// the newly created `Span`. @_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,20 +238,18 @@ 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 - ) { + @_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 + count: count ) } } @@ -459,7 +452,10 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { @inlinable @inline(__always) public subscript(unchecked position: Int) -> Element { _read { - yield _start.advanced(by: position).pointee + let element = UnsafeRawPointer(_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 } } } @@ -491,7 +487,7 @@ extension Span where Element: BitwiseCopyable { @inlinable @inline(__always) public subscript(unchecked position: Int) -> Element { get { - let address = UnsafeRawPointer(_start.advanced(by: position)) + let address = UnsafeRawPointer(_start).advanced(by: position&*MemoryLayout.stride) return address.loadUnaligned(as: Element.self) } } @@ -538,8 +534,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { public func extracting(unchecked bounds: Range) -> Self { Span( _unchecked: _pointer?.advanced(by: bounds.lowerBound), - count: bounds.count, - owner: self + count: bounds.count ) } @@ -730,7 +725,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { public func extracting(first maxLength: Int) -> Self { precondition(maxLength >= 0, "Can't have a prefix of negative length.") let newCount = min(maxLength, count) - return Self(_unchecked: _pointer, count: newCount, owner: self) + return Self(_unchecked: _pointer, count: newCount) } /// Returns a span over all but the given number of trailing elements. @@ -751,7 +746,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { public func extracting(droppingLast k: Int) -> Self { precondition(k >= 0, "Can't drop a negative number of elements.") let droppedCount = min(k, count) - return Self(_unchecked: _pointer, count: count&-droppedCount, owner: self) + return Self(_unchecked: _pointer, count: count&-droppedCount) } /// Returns a span containing the final elements of the span, @@ -774,7 +769,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { 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) + return Self(_unchecked: newStart, count: newCount) } /// Returns a span over all but the given number of initial elements. @@ -796,6 +791,6 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { 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) + return Self(_unchecked: newStart, count: count&-droppedCount) } } diff --git a/Sources/Future/StdlibSpanExtensions.swift b/Sources/Future/StdlibSpanExtensions.swift new file mode 100644 index 00000000..e6b3dbb0 --- /dev/null +++ b/Sources/Future/StdlibSpanExtensions.swift @@ -0,0 +1,431 @@ +//===--- StdlibSpanExtensions.swift ---------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +extension UnsafeBufferPointer where Element: ~Copyable { + public func withSpan( + _ body: (_ elements: Span) throws(E) -> Result + ) throws(E) -> Result { + try body(Span(_unsafeElements: self)) + } + + public func withBytes( + _ body: (_ elements: RawSpan) throws(E) -> Result + ) throws(E) -> Result where Element: BitwiseCopyable { + try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(self))) + } +} + +extension UnsafeMutableBufferPointer where Element: ~Copyable { + public func withSpan( + _ body: (_ elements: Span) throws(E) -> Result + ) throws(E) -> Result { + try body(Span(_unsafeElements: self)) + } + + public func withBytes( + _ body: (_ elements: RawSpan) throws(E) -> Result + ) throws(E) -> Result where Element: BitwiseCopyable { + try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(self))) + } +} + +extension UnsafeRawBufferPointer { + public func withBytes( + _ body: (_ elements: RawSpan) throws(E) -> Result + ) throws(E) -> Result { + try body(RawSpan(_unsafeBytes: self)) + } +} + +extension UnsafeMutableRawBufferPointer { + public func withBytes( + _ body: (_ elements: RawSpan) throws(E) -> Result + ) throws(E) -> Result { + try body(RawSpan(_unsafeBytes: self)) + } +} + +extension Slice { + public func withSpan( + _ body: (_ elements: Span) throws(E) -> Result + ) throws(E) -> Result + where Base == UnsafeBufferPointer { + try body(Span(_unsafeElements: UnsafeBufferPointer(rebasing: self))) + } + + public func withBytes( + _ body: (_ elements: RawSpan) throws(E) -> Result + ) throws(E) -> Result + where Base == UnsafeBufferPointer { + try body(RawSpan(_unsafeBytes: .init(UnsafeBufferPointer(rebasing: self)))) + } + + public func withSpan( + _ body: (_ elements: Span) throws(E) -> Result + ) throws(E) -> Result + where Base == UnsafeMutableBufferPointer { + try body(Span(_unsafeElements: UnsafeBufferPointer(rebasing: self))) + } + + public func withBytes( + _ body: (_ elements: RawSpan) throws(E) -> Result + ) throws(E) -> Result + where Base == UnsafeMutableBufferPointer { + try body(RawSpan(_unsafeBytes: .init(UnsafeBufferPointer(rebasing: self)))) + } + + public func withBytes( + _ body: (_ elements: RawSpan) throws(E) -> Result + ) throws(E) -> Result + where Base == UnsafeRawBufferPointer { + try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(rebasing: self))) + } + + public func withBytes( + _ body: (_ elements: RawSpan) throws(E) -> Result + ) throws(E) -> Result + where Base == UnsafeMutableRawBufferPointer { + try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(rebasing: self))) + } +} + +#if false //FIXME: rdar://134382237 +import struct Foundation.Data + +extension Data { + public func withSpan( + _ body: (_ elements: Span) throws(E) -> Result + ) throws(E) -> Result { + let result: Swift.Result = withUnsafeBytes { + do throws(E) { + return .success(try body(Span(_unsafeBytes: $0))) + } catch { + return .failure(error) + } + } + switch result { + case .success(let s): return s + case .failure(let e): throw e + } + } + + public func withBytes( + _ body: (_ bytes: RawSpan) throws(E) -> Result + ) throws(E) -> Result { + let result: Swift.Result = withUnsafeBytes { + do throws(E) { + return .success(try body(RawSpan(_unsafeBytes: $0))) + } catch { + return .failure(error) + } + } + switch result { + case .success(let s): return s + case .failure(let e): throw e + } + } +} +#endif + +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) + } + switch consume result { + case .success(let s): return s + case .failure(let e): throw e + } + } + + public func withBytes( + _ body: (_ bytes: RawSpan) throws(E) -> Result + ) throws(E) -> Result where Element: BitwiseCopyable { + let result: Swift.Result = withUnsafeBytes { + do throws(E) { + return .success(try body(RawSpan(_unsafeBytes: $0))) + } catch { + return .failure(error) + } + } + switch result { + case .success(let s): return s + case .failure(let e): throw e + } + } +} + +extension ContiguousArray { + public func withSpan( + _ body: (_ elements: Span) throws(E) -> Result + ) throws(E) -> Result { + let result: Swift.Result = withUnsafeBufferPointer { + do throws(E) { + return .success(try body(Span(_unsafeElements: $0))) + } catch { + return .failure(error) + } + } + switch result { + case .success(let s): return s + case .failure(let e): throw e + } + } +} + +extension ContiguousArray where Element: BitwiseCopyable { + public func withBytes( + _ body: (_ bytes: RawSpan) throws(E) -> Result + ) throws(E) -> Result { + let result: Swift.Result = withUnsafeBytes { + do throws(E) { + return .success(try body(RawSpan(_unsafeBytes: $0))) + } catch { + return .failure(error) + } + } + switch result { + case .success(let s): return s + case .failure(let e): throw e + } + } +} + +extension ArraySlice { + public func withSpan( + _ body: (_ elements: Span) throws(E) -> Result + ) throws(E) -> Result { + let result: Swift.Result = withUnsafeBufferPointer { + do throws(E) { + let span = Span(_unsafeElements: $0) + print(span._start, span.count) + return .success(try body(span)) + } catch { + return .failure(error) + } + } + switch result { + case .success(let s): return s + case .failure(let e): throw e + } + } +} + +extension ArraySlice where Element: BitwiseCopyable { + public func withBytes( + _ body: (_ bytes: RawSpan) throws(E) -> Result + ) throws(E) -> Result { + let result: Swift.Result = withUnsafeBytes { + do throws(E) { + return .success(try body(RawSpan(_unsafeBytes: $0))) + } catch { + return .failure(error) + } + } + switch result { + case .success(let s): return s + case .failure(let e): throw e + } + } +} + +extension String.UTF8View { + public func withSpan( + _ body: (_ elements: Span) throws(E) -> Result + ) throws(E) -> Result { + let result: Swift.Result? = withContiguousStorageIfAvailable { + do throws(E) { + return .success(try body(Span(_unsafeElements: $0))) + } catch { + return .failure(error) + } + } + switch result { + case .success(let s)?: return s + case .failure(let e)?: throw e + case nil: return try ContiguousArray(self).withSpan(body) + } + } + + public func withBytes( + _ body: (_ bytes: RawSpan) throws(E) -> Result + ) throws(E) -> Result { + let result: Swift.Result? = withContiguousStorageIfAvailable { + do throws(E) { + return .success(try body(RawSpan(_unsafeElements: $0))) + } catch { + return .failure(error) + } + } + switch result { + case .success(let s)?: return s + case .failure(let e)?: throw e + case nil: return try ContiguousArray(self).withBytes(body) + } + } +} + +extension Substring.UTF8View { + public func withSpan( + _ body: (_ elements: Span) throws(E) -> Result + ) throws(E) -> Result { + let result: Swift.Result? = withContiguousStorageIfAvailable { + do throws(E) { + return .success(try body(Span(_unsafeElements: $0))) + } catch { + return .failure(error) + } + } + switch result { + case .success(let s)?: return s + case .failure(let e)?: throw e + case nil: return try ContiguousArray(self).withSpan(body) + } + } + + public func withBytes( + _ body: (_ bytes: RawSpan) throws(E) -> Result + ) throws(E) -> Result { + let result: Swift.Result? = withContiguousStorageIfAvailable { + do throws(E) { + return .success(try body(RawSpan(_unsafeElements: $0))) + } catch { + return .failure(error) + } + } + switch result { + case .success(let s)?: return s + case .failure(let e)?: throw e + case nil: return try ContiguousArray(self).withBytes(body) + } + } +} + +extension CollectionOfOne { + public func withSpan( + _ body: (_ elements: Span) throws(E) -> Result + ) throws(E) -> Result { + var collection = self + let result: Swift.Result = withUnsafePointer(to: &collection) { + $0.withMemoryRebound(to: Element.self, capacity: 1) { + do throws(E) { + return .success(try body(Span(_unsafeStart: $0, count: 1))) + } catch { + return .failure(error) + } + } + } + switch result { + case .success(let s): return s + case .failure(let e): throw e + } + } +} + +extension CollectionOfOne where Element: BitwiseCopyable { + public func withBytes( + _ body: (_ bytes: RawSpan) throws(E) -> Result + ) throws(E) -> Result { + var collection = self + let r: Swift.Result = Swift.withUnsafeBytes(of: &collection) { + do throws(E) { + return .success(try body(RawSpan(_unsafeBytes: $0))) + } catch { + return .failure(error) + } + } + switch r { + case .success(let s): return s + case .failure(let e): throw e + } + } +} + +extension KeyValuePairs { + public func withSpan( + _ body: ( + _ elements: Span<(key: Key, value: Value)> + ) throws(E) -> Result + ) throws(E) -> Result { + try Array(self).withSpan(body) + } +} + +extension KeyValuePairs where Element: BitwiseCopyable { + public func withBytes( + _ body: (_ bytes: RawSpan) throws(E) -> Result + ) throws(E) -> Result { + try Array(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(self)) + } +} + +//TODO: extend SIMD vectors with `withSpan` and with `withBytes`. diff --git a/Tests/FutureTests/RawSpanTests.swift b/Tests/FutureTests/RawSpanTests.swift index bea88a64..d599da07 100644 --- a/Tests/FutureTests/RawSpanTests.swift +++ b/Tests/FutureTests/RawSpanTests.swift @@ -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,7 +97,7 @@ final class RawSpanTests: XCTestCase { let capacity = 64 let a = Array(0.. diff --git a/Tests/FutureTests/SpanTests.swift b/Tests/FutureTests/SpanTests.swift index 8c9d3248..8446fc01 100644 --- a/Tests/FutureTests/SpanTests.swift +++ b/Tests/FutureTests/SpanTests.swift @@ -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) @@ -276,7 +274,7 @@ 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) @@ -287,7 +285,7 @@ final class SpanTests: XCTestCase { 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) @@ -298,7 +296,7 @@ final class SpanTests: XCTestCase { let a = Array(0..( - unsafeElements: UnsafeBufferPointer(start: nil, count: 0), owner: b + _unsafeElements: UnsafeBufferPointer(start: nil, count: 0) ) XCTAssertTrue(span.contains(subSpan)) @@ -390,11 +388,11 @@ final class SpanTests: XCTestCase { _ = b.initialize(fromContentsOf: 0..<8) defer { b.deallocate() } - let span = Span(unsafeElements: .init(b), owner: b) + let span = Span(_unsafeElements: b) let subSpan = span.extracting(last: 2) let emptySpan = span.extracting(first: 0) let nilSpan = Span( - unsafeElements: UnsafeBufferPointer(start: nil, count: 0), owner: b + _unsafeElements: UnsafeBufferPointer(start: nil, count: 0) ) var bounds: Range diff --git a/Tests/FutureTests/StdlibSpanExtensionTests.swift b/Tests/FutureTests/StdlibSpanExtensionTests.swift new file mode 100644 index 00000000..446bb7cd --- /dev/null +++ b/Tests/FutureTests/StdlibSpanExtensionTests.swift @@ -0,0 +1,184 @@ +//===--- 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 Future + +enum ErrorForTesting: Error, Equatable { case error, errorToo, errorAsWell } + +final class StdlibSpanExtensionTests: XCTestCase { + +#if false //FIXME: rdar://134382237 -- nightly toolchain cannot `import Darwin` + 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) + } + } +#endif + + 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.count) + 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 })) + } +}