From 6c8dcadca4b201535443cfe4ca95a60b89fce3b0 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 19 Aug 2024 11:39:44 -0700 Subject: [PATCH 01/40] `swiftLanguageVersion` is now `swiftLanguageMode` --- Package.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index 93325e1d..a46642cd 100644 --- a/Package.swift +++ b/Package.swift @@ -61,11 +61,11 @@ let _sharedSettings: [SwiftSetting] = defines.map { .define($0) } + [ ] let _settings: [SwiftSetting] = _sharedSettings + [ - .swiftLanguageVersion(.v6), + .swiftLanguageMode(.v6), ] let _testSettings: [SwiftSetting] = _sharedSettings + [ - .swiftLanguageVersion(.v5), + .swiftLanguageMode(.v5), ] struct CustomTarget { From c290bd3d0453385a6334e1afa671f04cb8f4700a Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 29 Aug 2024 16:47:16 -0700 Subject: [PATCH 02/40] Copy `Span` prototype to its own branch --- Package.swift | 10 +- Sources/Future/ContiguousStorage.swift | 18 +- Sources/Future/RawSpan.swift | 122 +++-- Sources/Future/Span.swift | 155 +++---- Sources/Future/StdlibSpanExtensions.swift | 431 ++++++++++++++++++ Tests/FutureTests/RawSpanTests.swift | 53 +-- Tests/FutureTests/SpanTests.swift | 84 ++-- .../StdlibSpanExtensionTests.swift | 184 ++++++++ 8 files changed, 850 insertions(+), 207 deletions(-) create mode 100644 Sources/Future/StdlibSpanExtensions.swift create mode 100644 Tests/FutureTests/StdlibSpanExtensionTests.swift 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 })) + } +} From 7f13d84dd50f2b1fed453e300a28f2b1ab64de64 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 5 Sep 2024 17:49:37 -0700 Subject: [PATCH 03/40] update RawSpan to ~match proposal --- Sources/Future/RawSpan.swift | 54 ++++++++++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 11 deletions(-) diff --git a/Sources/Future/RawSpan.swift b/Sources/Future/RawSpan.swift index 3f73b2ff..84279867 100644 --- a/Sources/Future/RawSpan.swift +++ b/Sources/Future/RawSpan.swift @@ -173,7 +173,7 @@ extension RawSpan { String(UInt(bitPattern: _pointer), radix: 16, uppercase: false) } - public var description: String { + public var _description: String { "(0x\(_address), \(_count))" } } @@ -214,7 +214,7 @@ extension RawSpan { /// - position: an index to validate /// - Returns: true if `offset` is a valid index @inlinable @inline(__always) - public func validateBounds(_ offset: Int) -> Bool { + public func boundsContain(_ offset: Int) -> Bool { 0 <= offset && offset < byteCount } @@ -223,9 +223,9 @@ extension RawSpan { /// - Parameters: /// - position: an index to validate @inlinable @inline(__always) - public func assertValidity(_ offset: Int) { + public func boundsPrecondition(_ offset: Int) { precondition( - validateBounds(offset), "Offset out of bounds" + boundsContain(offset), "Offset out of bounds" ) } @@ -235,7 +235,7 @@ extension RawSpan { /// - 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 { + public func boundsContain(_ offsets: Range) -> Bool { 0 <= offsets.lowerBound && offsets.upperBound <= byteCount } @@ -244,13 +244,14 @@ extension RawSpan { /// - Parameters: /// - offsets: a range of indices to validate @inlinable @inline(__always) - public func assertValidity(_ offsets: Range) { + public func boundsPrecondition(_ offsets: Range) { precondition( - validateBounds(offsets), "Range of offsets out of bounds" + boundsContain(offsets), "Range of offsets out of bounds" ) } } +/* //MARK: extracting sub-spans extension RawSpan { @@ -269,7 +270,7 @@ extension RawSpan { /// - Complexity: O(1) @inlinable @inline(__always) public func extracting(_ bounds: Range) -> Self { - assertValidity(bounds) + boundsPrecondition(bounds) return extracting(unchecked: bounds) } @@ -350,6 +351,33 @@ extension RawSpan { self } } +*/ + +extension RawSpan { + @_alwaysEmitIntoClient + public mutating func _shrink(to bounds: Range) { + boundsPrecondition(bounds) + _shrink(unchecked: bounds) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(unchecked bounds: Range) { + self = RawSpan( + _unchecked: _pointer?.advanced(by: bounds.lowerBound), + byteCount: bounds.count + ) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(_ bounds: some RangeExpression) { + _shrink(to: bounds.relative(to: _byteOffsets)) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(unchecked bounds: some RangeExpression) { + _shrink(unchecked: bounds.relative(to: _byteOffsets)) + } +} extension RawSpan { @@ -424,7 +452,7 @@ extension RawSpan { public func unsafeLoad( fromByteOffset offset: Int = 0, as: T.Type ) -> T { - assertValidity( + boundsPrecondition( Range(uncheckedBounds: (offset, offset+MemoryLayout.size)) ) return unsafeLoad(fromUncheckedByteOffset: offset, as: T.self) @@ -475,7 +503,7 @@ extension RawSpan { public func unsafeLoadUnaligned( fromByteOffset offset: Int = 0, as: T.Type ) -> T { - assertValidity( + boundsPrecondition( Range(uncheckedBounds: (offset, offset+MemoryLayout.size)) ) return unsafeLoadUnaligned(fromUncheckedByteOffset: offset, as: T.self) @@ -543,6 +571,7 @@ extension RawSpan { } //MARK: one-sided slicing operations +/* extension RawSpan { /// Returns a span containing the initial bytes of this span, @@ -633,6 +662,7 @@ extension RawSpan { return Self(_unchecked: newStart, byteCount: byteCount&-dc) } } +*/ /// An error indicating that out-of-bounds access was attempted @frozen @@ -649,6 +679,7 @@ public struct OutOfBoundsError: Error { } } +/* extension RawSpan { /// Parse an instance of `T`, advancing `position`. @inlinable @@ -696,7 +727,7 @@ extension RawSpan { @inlinable public init(_ base: RawSpan, in range: Range) { - base.assertValidity(range) + base.boundsPrecondition(range) position = 0 self.base = base parseRange = range @@ -742,3 +773,4 @@ extension RawSpan { Cursor(self, in: range) } } +*/ From 3fda314bcd8574f37d5e771a956bf5c6fe605384 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 9 Sep 2024 15:45:44 -0700 Subject: [PATCH 04/40] updates to RawSpan --- Sources/Future/RawSpan.swift | 158 +++++++++++++-------------- Tests/FutureTests/RawSpanTests.swift | 58 +++++----- 2 files changed, 108 insertions(+), 108 deletions(-) diff --git a/Sources/Future/RawSpan.swift b/Sources/Future/RawSpan.swift index 84279867..43262833 100644 --- a/Sources/Future/RawSpan.swift +++ b/Sources/Future/RawSpan.swift @@ -149,7 +149,7 @@ extension RawSpan { /// - Parameters: /// - span: An existing `Span`, which will define both this /// `RawSpan`'s lifetime and the memory it represents. - @inlinable @inline(__always) + @_alwaysEmitIntoClient public init(_ span: borrowing Span) { self.init( _unchecked: UnsafeRawPointer(span._start), @@ -208,50 +208,37 @@ 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 + /// - position: a byte offset to validate + /// - Returns: true if `offset` is a valid byte offset @inlinable @inline(__always) 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 boundsPrecondition(_ offset: Int) { - precondition( - boundsContain(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 + /// - offsets: a range of byte offsets to validate + /// - Returns: true if `offsets` is a valid range of byte offsets @inlinable @inline(__always) public func boundsContain(_ offsets: Range) -> Bool { 0 <= 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 + /// - offsets: a range of byte offsets to validate + /// - Returns: true if `offsets` is a valid range of byte offsets @inlinable @inline(__always) - public func boundsPrecondition(_ offsets: Range) { - precondition( - boundsContain(offsets), "Range of offsets out of bounds" - ) + public func boundsContain(_ offsets: ClosedRange) -> Bool { + 0 <= offsets.lowerBound && offsets.upperBound < byteCount } } -/* //MARK: extracting sub-spans extension RawSpan { @@ -268,10 +255,15 @@ extension RawSpan { /// - Returns: A span over the bytes within `bounds` /// /// - Complexity: O(1) - @inlinable @inline(__always) - public func extracting(_ bounds: Range) -> Self { - boundsPrecondition(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 @@ -289,14 +281,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 ) } + @_alwaysEmitIntoClient + public mutating func _shrink(unchecked bounds: Range) { + self = _extracting(unchecked: bounds) + } + /// Constructs a new span over the bytes within the supplied range of /// positions within this span. /// @@ -311,8 +308,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 @@ -331,10 +333,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(unchecked bounds: some RangeExpression) { + self = _extracting(unchecked: bounds) } /// Constructs a new span over all the bytes of this span. @@ -347,37 +354,10 @@ extension RawSpan { /// /// - Complexity: O(1) @_alwaysEmitIntoClient - public func extracting(_: UnboundedRange) -> Self { + @usableFromInline func _extracting(_: UnboundedRange) -> Self { self } } -*/ - -extension RawSpan { - @_alwaysEmitIntoClient - public mutating func _shrink(to bounds: Range) { - boundsPrecondition(bounds) - _shrink(unchecked: bounds) - } - - @_alwaysEmitIntoClient - public mutating func _shrink(unchecked bounds: Range) { - self = RawSpan( - _unchecked: _pointer?.advanced(by: bounds.lowerBound), - byteCount: bounds.count - ) - } - - @_alwaysEmitIntoClient - public mutating func _shrink(_ bounds: some RangeExpression) { - _shrink(to: bounds.relative(to: _byteOffsets)) - } - - @_alwaysEmitIntoClient - public mutating func _shrink(unchecked bounds: some RangeExpression) { - _shrink(unchecked: bounds.relative(to: _byteOffsets)) - } -} extension RawSpan { @@ -452,9 +432,9 @@ extension RawSpan { public func unsafeLoad( fromByteOffset offset: Int = 0, as: T.Type ) -> T { - boundsPrecondition( + precondition(boundsContain( Range(uncheckedBounds: (offset, offset+MemoryLayout.size)) - ) + )) return unsafeLoad(fromUncheckedByteOffset: offset, as: T.self) } @@ -503,9 +483,9 @@ extension RawSpan { public func unsafeLoadUnaligned( fromByteOffset offset: Int = 0, as: T.Type ) -> T { - boundsPrecondition( + precondition(boundsContain( Range(uncheckedBounds: (offset, offset+MemoryLayout.size)) - ) + )) return unsafeLoadUnaligned(fromUncheckedByteOffset: offset, as: T.self) } @@ -571,7 +551,6 @@ extension RawSpan { } //MARK: one-sided slicing operations -/* extension RawSpan { /// Returns a span containing the initial bytes of this span, @@ -589,13 +568,18 @@ 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) } + @_alwaysEmitIntoClient + public mutating func _shrink(toFirst maxLength: Int) { + self = _extracting(first: maxLength) + } + /// Returns a span over all but the given number of trailing bytes. /// /// If the number of elements to drop exceeds the number of elements in @@ -610,13 +594,18 @@ 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) } + @_alwaysEmitIntoClient + public mutating func _shrink(droppingLast k: Int) { + self = _extracting(droppingLast: k) + } + /// Returns a span containing the trailing bytes of the span, /// up to the given maximum length. /// @@ -632,14 +621,19 @@ 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) } + @_alwaysEmitIntoClient + public mutating func _shrink(toLast maxLength: Int) { + self = _extracting(last: maxLength) + } + /// Returns a span over all but the given number of initial bytes. /// /// If the number of elements to drop exceeds the number of bytes in @@ -654,15 +648,19 @@ 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) } + + @_alwaysEmitIntoClient + public mutating func _shrink(droppingFirst k: Int) { + self = _extracting(droppingFirst: k) + } } -*/ /// An error indicating that out-of-bounds access was attempted @frozen @@ -679,7 +677,6 @@ public struct OutOfBoundsError: Error { } } -/* extension RawSpan { /// Parse an instance of `T`, advancing `position`. @inlinable @@ -710,7 +707,7 @@ extension RawSpan { guard end <= length else { throw OutOfBoundsError(expected: length, has: byteCount&-position) } - return extracting(position..) { - base.boundsPrecondition(range) + precondition(base.boundsContain(range)) position = 0 self.base = base parseRange = range @@ -758,7 +755,7 @@ extension RawSpan { /// The bytes that we've parsed so far @inlinable - public var parsedBytes: RawSpan { base.extracting(.. Date: Mon, 9 Sep 2024 16:44:58 -0700 Subject: [PATCH 05/40] updates to Span --- Sources/Future/Span.swift | 44 ++++++++++++++----------------- Tests/FutureTests/SpanTests.swift | 1 + 2 files changed, 21 insertions(+), 24 deletions(-) diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index 49f34940..6044024d 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -16,37 +16,28 @@ import Builtin // contains initialized instances of `Element`. @frozen public struct Span: Copyable, ~Escapable { - @usableFromInline let _buffer: UnsafeBufferPointer + @usableFromInline let _pointer: UnsafeRawPointer? @usableFromInline @inline(__always) - var _pointer: UnsafePointer? { _buffer.baseAddress } + var _start: UnsafeRawPointer { _pointer.unsafelyUnwrapped } - @usableFromInline @inline(__always) - var _start: UnsafePointer { _pointer.unsafelyUnwrapped } - -// @usableFromInline @inline(__always) -// var _start: UnsafeRawPointer { _pointer.unsafelyUnwrapped } - - @usableFromInline @inline(__always) - var _count: Int { _buffer.count } + @usableFromInline let _count: Int @inlinable @inline(__always) internal init( _unchecked elements: UnsafeBufferPointer ) -> dependsOn(immortal) Self { - _buffer = elements -// _pointer = .init(elements.baseAddress) -// _count = elements.count + _pointer = .init(elements.baseAddress) + _count = elements.count } @_alwaysEmitIntoClient internal init( - _unchecked start: UnsafePointer?, + _unchecked start: UnsafeRawPointer?, count: Int ) -> dependsOn(immortal) Self { - self.init(_unchecked: .init(start: start, count: count)) -// _pointer = .init(start) -// _count = count + _pointer = .init(start) + _count = count } } @@ -57,7 +48,7 @@ extension UnsafePointer where Pointee: ~Copyable /*& ~Escapable*/ { @usableFromInline @inline(__always) var isAligned: Bool { - (Int(bitPattern: self) & (MemoryLayout.alignment-1)) == 0 + (Int(bitPattern: self) & (MemoryLayout.alignment&-1)) == 0 } } @@ -533,7 +524,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { @inlinable @inline(__always) public func extracting(unchecked bounds: Range) -> Self { Span( - _unchecked: _pointer?.advanced(by: bounds.lowerBound), + _unchecked: _pointer?.advanced(by: bounds.lowerBound*MemoryLayout.stride), count: bounds.count ) } @@ -613,7 +604,12 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { 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)) } } @@ -680,7 +676,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { 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) + return span._start.advanced(by: span._count*MemoryLayout.stride) <= _start.advanced(by: _count*MemoryLayout.stride) } /// Returns the offsets where the memory of `span` is located within @@ -696,7 +692,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { precondition(contains(span)) var (s, e) = (0, 0) if _pointer != nil && span._pointer != nil { - s = _start.distance(to: span._start) + s = _start.distance(to: span._start)/MemoryLayout.stride e = s + span._count } return Range(uncheckedBounds: (s, e)) @@ -768,7 +764,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { public 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) + let newStart = _pointer?.advanced(by: (count&-newCount)*MemoryLayout.stride) return Self(_unchecked: newStart, count: newCount) } @@ -790,7 +786,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { public 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) + let newStart = _pointer?.advanced(by: droppedCount*MemoryLayout.stride) return Self(_unchecked: newStart, count: count&-droppedCount) } } diff --git a/Tests/FutureTests/SpanTests.swift b/Tests/FutureTests/SpanTests.swift index 8446fc01..956ce63e 100644 --- a/Tests/FutureTests/SpanTests.swift +++ b/Tests/FutureTests/SpanTests.swift @@ -331,6 +331,7 @@ final class SpanTests: XCTestCase { XCTAssertEqual(emptyBuffer.baseAddress, ub.baseAddress) let empty = Span(_unsafeElements: emptyBuffer) + XCTAssertEqual(empty.count, 0) empty.withUnsafeBufferPointer { XCTAssertNil($0.baseAddress) } From 6d0848fc7f83bfa219487c731de663f4f220f930 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 10 Sep 2024 18:03:26 -0700 Subject: [PATCH 06/40] improve standard library Span extensions --- Sources/Future/StdlibSpanExtensions.swift | 359 +++++++++++------- .../StdlibSpanExtensionTests.swift | 13 +- 2 files changed, 218 insertions(+), 154 deletions(-) diff --git a/Sources/Future/StdlibSpanExtensions.swift b/Sources/Future/StdlibSpanExtensions.swift index e6b3dbb0..5d8b2382 100644 --- a/Sources/Future/StdlibSpanExtensions.swift +++ b/Sources/Future/StdlibSpanExtensions.swift @@ -102,36 +102,46 @@ extension Slice { import struct Foundation.Data extension Data { - public func withSpan( + 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) + 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) } - switch result { - case .success(let s): return s - case .failure(let e): throw e - } + return try result.get() } - public func withBytes( + 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) + 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) } - switch result { - case .success(let s): return s - case .failure(let e): throw e - } + return try result.get() } } #endif @@ -185,235 +195,290 @@ extension Array { } return buffer.moveElement(from: 0) } - switch consume result { - case .success(let s): return s - case .failure(let e): throw e - } + return try result.get() } - public func withBytes( +// 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: Swift.Result = withUnsafeBytes { - do throws(E) { - return .success(try body(RawSpan(_unsafeBytes: $0))) - } catch { - return .failure(error) + 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) } - switch result { - case .success(let s): return s - case .failure(let e): throw e - } + return try result.get() } } extension ContiguousArray { - public func withSpan( + 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) + 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 result { - case .success(let s): return s - case .failure(let e): throw e - } + return try result.get() } } extension ContiguousArray where Element: BitwiseCopyable { - public func withBytes( + 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) + ) 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) } - switch result { - case .success(let s): return s - case .failure(let e): throw e - } + return try result.get() } } extension ArraySlice { - public func withSpan( + 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) + 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 result { - case .success(let s): return s - case .failure(let e): throw e - } + return try result.get() } } extension ArraySlice where Element: BitwiseCopyable { - public func withBytes( + 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) + ) 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) } - switch result { - case .success(let s): return s - case .failure(let e): throw e - } + return try result.get() } } extension String.UTF8View { - public func withSpan( + 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) + 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) } - switch result { - case .success(let s)?: return s - case .failure(let e)?: throw e - case nil: return try ContiguousArray(self).withSpan(body) + if let result { + return try result.get() } + return try ContiguousArray(self).withSpan(body) } - public func withBytes( + 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) + 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) } - switch result { - case .success(let s)?: return s - case .failure(let e)?: throw e - case nil: return try ContiguousArray(self).withBytes(body) + if let result { + return try result.get() } + return try ContiguousArray(self).withBytes(body) } } extension Substring.UTF8View { - public func withSpan( + 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) + 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) } - switch result { - case .success(let s)?: return s - case .failure(let e)?: throw e - case nil: return try ContiguousArray(self).withSpan(body) + if let result { + return try result.get() } + return try ContiguousArray(self).withSpan(body) } - public func withBytes( + 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) + 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) } - switch result { - case .success(let s)?: return s - case .failure(let e)?: throw e - case nil: return try ContiguousArray(self).withBytes(body) + if let result { + return try result.get() } + return try ContiguousArray(self).withBytes(body) } } extension CollectionOfOne { - public func withSpan( + 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) - } + 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)) } } - switch result { - case .success(let s): return s - case .failure(let e): throw e - } } } extension CollectionOfOne where Element: BitwiseCopyable { - public func withBytes( + 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 + return try Swift.withUnsafeBytes(of: &collection) { + bytes throws(E) -> Result in + try body(RawSpan(_unsafeBytes: bytes)) } } } extension KeyValuePairs { - public func withSpan( + public func withSpan( _ body: ( _ elements: Span<(key: Key, value: Value)> ) throws(E) -> Result ) throws(E) -> Result { - try Array(self).withSpan(body) + try ContiguousArray(self).withSpan(body) } } extension KeyValuePairs where Element: BitwiseCopyable { - public func withBytes( + public func withBytes( _ body: (_ bytes: RawSpan) throws(E) -> Result ) throws(E) -> Result { - try Array(self).withBytes(body) + try ContiguousArray(self).withBytes(body) } } extension Span where Element: ~Copyable /*& ~Escapable*/ { - public consuming func withSpan( + public consuming func withSpan( _ body: (_ elements: Span) throws(E) -> Result ) throws(E) -> Result { try body(self) @@ -421,7 +486,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { } extension Span where Element: BitwiseCopyable { - public consuming func withBytes( + public consuming func withBytes( _ body: (_ elements: RawSpan) throws(E) -> Result ) throws(E) -> Result { try body(RawSpan(self)) diff --git a/Tests/FutureTests/StdlibSpanExtensionTests.swift b/Tests/FutureTests/StdlibSpanExtensionTests.swift index 446bb7cd..4516e725 100644 --- a/Tests/FutureTests/StdlibSpanExtensionTests.swift +++ b/Tests/FutureTests/StdlibSpanExtensionTests.swift @@ -115,20 +115,19 @@ final class StdlibSpanExtensionTests: XCTestCase { 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)) + XCTAssertEqual($0[i], String(i)) } } -// do throws(ErrorForTesting) { -// try a.withSpan { _ throws(ErrorForTesting) in throw .error } -// } catch { -// XCTAssertEqual(error, .error) -// } + do throws(ErrorForTesting) { + try a.withSpan { _ throws(ErrorForTesting) in throw .error } + } catch { + XCTAssertEqual(error, .error) + } } func testArraySliceRawSpan() throws { From 46df1037866efd73278aa0f4116a77dbce1edbd8 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 10 Sep 2024 18:03:26 -0700 Subject: [PATCH 07/40] add missing stdlib Span extension --- Sources/Future/StdlibSpanExtensions.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Sources/Future/StdlibSpanExtensions.swift b/Sources/Future/StdlibSpanExtensions.swift index 5d8b2382..90f499a2 100644 --- a/Sources/Future/StdlibSpanExtensions.swift +++ b/Sources/Future/StdlibSpanExtensions.swift @@ -493,4 +493,12 @@ extension Span where Element: BitwiseCopyable { } } +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`. From 91506824d01d6024768886c8afd7dee70988fcee Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 12 Sep 2024 01:24:45 -0700 Subject: [PATCH 08/40] RawSpan review feedback --- Sources/Future/RawSpan.swift | 177 +++++----------------- Sources/Future/Span.swift | 4 +- Sources/Future/StdlibSpanExtensions.swift | 2 +- Tests/FutureTests/RawSpanTests.swift | 51 ++++--- 4 files changed, 66 insertions(+), 168 deletions(-) diff --git a/Sources/Future/RawSpan.swift b/Sources/Future/RawSpan.swift index 43262833..3e8963d7 100644 --- a/Sources/Future/RawSpan.swift +++ b/Sources/Future/RawSpan.swift @@ -150,7 +150,9 @@ extension RawSpan { /// - span: An existing `Span`, which will define both this /// `RawSpan`'s lifetime and the memory it represents. @_alwaysEmitIntoClient - public init(_ span: borrowing Span) { + public init( + _unsafeSpan span: borrowing Span + ) -> dependsOn(immortal) Self { self.init( _unchecked: UnsafeRawPointer(span._start), byteCount: span.count * MemoryLayout.stride @@ -158,15 +160,6 @@ extension RawSpan { } } -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 { @@ -186,13 +179,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 @@ -213,7 +206,7 @@ extension RawSpan { /// - Parameters: /// - position: a byte offset to validate /// - Returns: true if `offset` is a valid byte offset - @inlinable @inline(__always) + @_alwaysEmitIntoClient public func boundsContain(_ offset: Int) -> Bool { 0 <= offset && offset < byteCount } @@ -223,7 +216,7 @@ extension RawSpan { /// - Parameters: /// - offsets: a range of byte offsets to validate /// - Returns: true if `offsets` is a valid range of byte offsets - @inlinable @inline(__always) + @_alwaysEmitIntoClient public func boundsContain(_ offsets: Range) -> Bool { 0 <= offsets.lowerBound && offsets.upperBound <= byteCount } @@ -233,7 +226,7 @@ extension RawSpan { /// - Parameters: /// - offsets: a range of byte offsets to validate /// - Returns: true if `offsets` is a valid range of byte offsets - @inlinable @inline(__always) + @_alwaysEmitIntoClient public func boundsContain(_ offsets: ClosedRange) -> Bool { 0 <= offsets.lowerBound && offsets.upperBound < byteCount } @@ -290,7 +283,7 @@ extension RawSpan { } @_alwaysEmitIntoClient - public mutating func _shrink(unchecked bounds: Range) { + public mutating func _shrink(toUnchecked bounds: Range) { self = _extracting(unchecked: bounds) } @@ -340,7 +333,7 @@ extension RawSpan { } @_alwaysEmitIntoClient - public mutating func _shrink(unchecked bounds: some RangeExpression) { + public mutating func _shrink(toUnchecked bounds: some RangeExpression) { self = _extracting(unchecked: bounds) } @@ -428,7 +421,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( fromByteOffset offset: Int = 0, as: T.Type ) -> T { @@ -456,7 +449,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 { @@ -515,6 +508,12 @@ extension RawSpan { } extension RawSpan { + /// Returns a Boolean value indicating whether two `RawSpan` instances + /// refer to the same region in memory. + @_alwaysEmitIntoClient + public func isIdentical(to other: Self) -> Bool { + (self._pointer == other._pointer) && (self._count == other._count) + } /// Returns true if the memory represented by `span` is a subrange of /// the memory represented by `self` @@ -522,12 +521,13 @@ extension RawSpan { /// 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) + @_alwaysEmitIntoClient + public func isWithin(_ span: borrowing Self) -> Bool { + if _count > span._count { return false } + if _count == 0 { return true } + if _start < span._start { return false } + let lower = span._start.distance(to: _start) + return lower + _count <= span._count } /// Returns the offsets where the memory of `span` is located within @@ -538,15 +538,15 @@ 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 - } - return Range(uncheckedBounds: (s, e)) + @_alwaysEmitIntoClient + public func byteOffsetsWithin(_ span: borrowing Self) -> Range? { + if _count > span._count { return nil } + if _count == 0 { return Range(uncheckedBounds: (0, 0)) } + if _start < span._start { return nil } + let lower = span._start.distance(to: _start) + let upper = lower + _count + guard upper <= span._count else { return nil } + return Range(uncheckedBounds: (lower, upper)) } } @@ -661,112 +661,3 @@ extension RawSpan { self = _extracting(droppingFirst: k) } } - -/// 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) { - precondition(base.boundsContain(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) - } -} diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index 6044024d..4aeaa768 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -412,7 +412,7 @@ extension Span where Element: BitwiseCopyable { /// /// - Returns: a RawSpan over the memory represented by this span @inlinable @inline(__always) - public var rawSpan: RawSpan { RawSpan(self) } + public var rawSpan: RawSpan { RawSpan(_unsafeSpan: self) } } //MARK: integer offset subscripts @@ -634,7 +634,7 @@ extension Span where Element: BitwiseCopyable { public func withUnsafeBytes( _ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result ) throws(E) -> Result { - try RawSpan(self).withUnsafeBytes(body) + try RawSpan(_unsafeSpan: self).withUnsafeBytes(body) } } diff --git a/Sources/Future/StdlibSpanExtensions.swift b/Sources/Future/StdlibSpanExtensions.swift index 90f499a2..5e5787b9 100644 --- a/Sources/Future/StdlibSpanExtensions.swift +++ b/Sources/Future/StdlibSpanExtensions.swift @@ -489,7 +489,7 @@ extension Span where Element: BitwiseCopyable { public consuming func withBytes( _ body: (_ elements: RawSpan) throws(E) -> Result ) throws(E) -> Result { - try body(RawSpan(self)) + try body(RawSpan(_unsafeSpan: self)) } } diff --git a/Tests/FutureTests/RawSpanTests.swift b/Tests/FutureTests/RawSpanTests.swift index e4de3d98..c97f73b8 100644 --- a/Tests/FutureTests/RawSpanTests.swift +++ b/Tests/FutureTests/RawSpanTests.swift @@ -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) } @@ -140,7 +140,7 @@ final class RawSpanTests: XCTestCase { var prefix = span prefix._shrink(to: 0..<8) var beyond = prefix - beyond._shrink(unchecked: 16..<24) + beyond._shrink(toUnchecked: 16..<24) XCTAssertEqual(beyond.byteCount, 8) XCTAssertEqual(beyond.unsafeLoad(as: UInt8.self), 16) } @@ -149,7 +149,7 @@ final class RawSpanTests: XCTestCase { func testUnsafeBytes() { let capacity = 4 let array = 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) + var bounds: Range? + bounds = subSpan1.byteOffsetsWithin(span) + XCTAssertEqual(bounds, span._byteOffsets.prefix(6)) + bounds = subSpan2.byteOffsetsWithin(span) + XCTAssertEqual(bounds, span._byteOffsets.suffix(6)) + bounds = subSpan1.byteOffsetsWithin(subSpan2) + XCTAssertNil(bounds) + bounds = subSpan2.byteOffsetsWithin(subSpan1) + XCTAssertNil(bounds) + bounds = span.byteOffsetsWithin(subSpan2) + XCTAssertNil(bounds) + bounds = emptySpan.byteOffsetsWithin(nilSpan) XCTAssertEqual(bounds, 0..<0) - bounds = nilSpan.offsets(of: emptySpan) + bounds = nilSpan.byteOffsetsWithin(span) XCTAssertEqual(bounds, 0..<0) } } From 888318c3a1b10563edd63a910234f418b9950dbb Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 12 Sep 2024 02:41:17 -0700 Subject: [PATCH 09/40] Span review feedback --- Sources/Future/Span.swift | 253 ++++++++++++++++++++++---------------- 1 file changed, 148 insertions(+), 105 deletions(-) diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index 4aeaa768..1e5ed285 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -15,7 +15,7 @@ import Builtin // A Span represents a span of memory which // contains initialized instances of `Element`. @frozen -public struct Span: Copyable, ~Escapable { +public struct Span: Copyable, ~Escapable { @usableFromInline let _pointer: UnsafeRawPointer? @usableFromInline @inline(__always) @@ -23,14 +23,6 @@ public struct Span: Copyable, ~Escapable { @usableFromInline let _count: Int - @inlinable @inline(__always) - internal init( - _unchecked elements: UnsafeBufferPointer - ) -> dependsOn(immortal) Self { - _pointer = .init(elements.baseAddress) - _count = elements.count - } - @_alwaysEmitIntoClient internal init( _unchecked start: UnsafeRawPointer?, @@ -44,15 +36,22 @@ public struct Span: Copyable, ~Escapable { @available(*, unavailable) extension Span: Sendable {} -extension UnsafePointer where Pointee: ~Copyable /*& ~Escapable*/ { +extension UnsafePointer where Pointee: ~Copyable { - @usableFromInline @inline(__always) + @_alwaysEmitIntoClient var isAligned: Bool { (Int(bitPattern: self) & (MemoryLayout.alignment&-1)) == 0 } } -extension Span where Element: ~Copyable /*& ~Escapable*/ { +extension Span where Element: ~Copyable { + @_alwaysEmitIntoClient + internal init( + _unchecked elements: UnsafeBufferPointer + ) -> dependsOn(immortal) Self { + _pointer = .init(elements.baseAddress) + _count = elements.count + } /// Unsafely create a `Span` over initialized memory. /// @@ -69,7 +68,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { ) -> dependsOn(immortal) Self { precondition( buffer.count == 0 || buffer.baseAddress.unsafelyUnwrapped.isAligned, - "baseAddress must be properly aligned for accessing \(Element.self)" + "baseAddress must be properly aligned to access Element" ) self.init(_unchecked: buffer) } @@ -109,7 +108,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { precondition(count >= 0, "Count must not be negative") precondition( start.isAligned, - "baseAddress must be properly aligned for accessing \(Element.self)" + "baseAddress must be properly aligned to access Element" ) self.init(_unchecked: start, count: count) } @@ -257,6 +256,7 @@ extension Span where Element: Equatable { /// /// - Complexity: O(*m*), where *m* is the lesser of the length of the /// sequence and the length of `other`. + @_alwaysEmitIntoClient public func _elementsEqual(_ other: Self) -> Bool { guard count == other.count else { return false } if count == 0 { return true } @@ -283,7 +283,7 @@ 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 + @_alwaysEmitIntoClient public func _elementsEqual(_ other: some Collection) -> Bool { guard count == other.count else { return false } if count == 0 { return true } @@ -301,7 +301,7 @@ 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 + @_alwaysEmitIntoClient public func _elementsEqual(_ other: some Sequence) -> Bool { var offset = 0 for otherElement in other { @@ -313,27 +313,20 @@ 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 { -extension Span where Element: ~Copyable /*& ~Escapable*/ { - - private var _address: String { + @_alwaysEmitIntoClient + var _address: String { String(UInt(bitPattern: _pointer), radix: 16, uppercase: false) } + @_alwaysEmitIntoClient public var description: String { "(0x\(_address), \(_count))" } } -extension Span where Element: ~Copyable /*& ~Escapable*/ { +extension Span where Element: ~Copyable { /// The number of elements in the span. /// @@ -341,13 +334,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 @@ -356,67 +349,56 @@ 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*/ { +extension Span where Element: ~Copyable { /// Return true if `offset` 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 { + @_alwaysEmitIntoClient + public func boundsContain(_ offset: Int) -> Bool { 0 <= offset && offset < count } - /// Traps if `offset` is not a valid offset into this `Span` - /// - /// - 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 `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 { + @_alwaysEmitIntoClient + public func boundsContain(_ offsets: Range) -> Bool { 0 <= offsets.lowerBound && offsets.upperBound <= count } - /// Traps if `offsets` is not a valid range of offsets into this `Span` + /// Return true if `offsets` is 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" - ) + /// - Returns: true if `offsets` is a valid range of indices + @_alwaysEmitIntoClient + public func boundsContain(_ offsets: ClosedRange) -> Bool { + 0 <= offsets.lowerBound && offsets.upperBound < count } } 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(_unsafeSpan: self) } +#warning("Restore this computed property once lifetime annotations exist") +// /// Construct a RawSpan over the memory represented by this span +// /// +// /// - Returns: a RawSpan over the memory represented by this span +// @_alwaysEmitIntoClient +// public var rawSpan: RawSpan { RawSpan(self) } } //MARK: integer offset subscripts -extension Span where Element: ~Copyable /*& ~Escapable*/ { +extension Span where Element: ~Copyable { /// Accesses the element at the specified position in the `Span`. /// @@ -424,10 +406,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)) yield self[unchecked: position] } } @@ -440,7 +422,7 @@ 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(unchecked position: Int) -> Element { _read { let element = UnsafeRawPointer(_start).advanced(by: position&*MemoryLayout.stride) @@ -459,10 +441,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)) return self[unchecked: position] } } @@ -475,7 +457,7 @@ 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(unchecked position: Int) -> Element { get { let address = UnsafeRawPointer(_start).advanced(by: position&*MemoryLayout.stride) @@ -485,7 +467,7 @@ extension Span where Element: BitwiseCopyable { } //MARK: extracting sub-spans -extension Span where Element: ~Copyable /*& ~Escapable*/ { +extension Span where Element: ~Copyable { /// Constructs a new span over the items within the supplied range of /// positions within this span. @@ -500,10 +482,15 @@ 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) + @_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 items within the supplied range of @@ -521,14 +508,19 @@ 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 { + @_alwaysEmitIntoClient + @usableFromInline func _extracting(unchecked bounds: Range) -> Self { Span( _unchecked: _pointer?.advanced(by: bounds.lowerBound*MemoryLayout.stride), count: bounds.count ) } + @_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. /// @@ -543,8 +535,13 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// /// - Complexity: O(1) @_alwaysEmitIntoClient - public func extracting(_ bounds: some RangeExpression) -> Self { - extracting(bounds.relative(to: _indices)) + @usableFromInline func _extracting(_ bounds: some RangeExpression) -> Self { + _extracting(bounds.relative(to: _indices)) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(to bounds: some RangeExpression) { + self = _extracting(bounds) } /// Constructs a new span over the items within the supplied range of @@ -563,10 +560,15 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// /// - Complexity: O(1) @_alwaysEmitIntoClient - public func extracting( + @usableFromInline func _extracting( uncheckedBounds bounds: some RangeExpression ) -> Self { - extracting(unchecked: bounds.relative(to: _indices)) + _extracting(unchecked: bounds.relative(to: _indices)) + } + + @_alwaysEmitIntoClient + public mutating func _shrink(toUnchecked bounds: some RangeExpression) { + self = _extracting(uncheckedBounds: bounds) } /// Constructs a new span over all the items of this span. @@ -579,13 +581,13 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// /// - Complexity: O(1) @_alwaysEmitIntoClient - public func extracting(_: UnboundedRange) -> Self { + @usableFromInline func _extracting(_: UnboundedRange) -> Self { self } } //MARK: withUnsafePointer, etc. -extension Span where Element: ~Copyable /*& ~Escapable*/ { +extension Span where Element: ~Copyable { //FIXME: mark closure parameter as non-escaping /// Calls a closure with a pointer to the viewed contiguous storage. @@ -647,7 +649,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] } @@ -657,13 +659,19 @@ 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*/ { +extension Span where Element: ~Copyable { + /// Returns a Boolean value indicating whether two `Span` instances + /// refer to the same region in memory. + @_alwaysEmitIntoClient + public func isIdentical(to other: Self) -> Bool { + (self._pointer == other._pointer) && (self._count == other._count) + } /// Returns true if the memory represented by `span` is a subrange of /// the memory represented by `self` @@ -671,12 +679,24 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// 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*MemoryLayout.stride) <= _start.advanced(by: _count*MemoryLayout.stride) + @_alwaysEmitIntoClient + public func isWithin(_ span: borrowing Self) -> Bool { + if _count > span._count { return false } + if _count == 0 { return true } + if _start < span._start { return false } + let stride = MemoryLayout.stride +#warning("use isPOD once it is generalized") +// if _isPOD(Element.self) { + let byteOffset = span._start.distance(to: _start) + let (lower, r) = byteOffset.quotientAndRemainder(dividingBy: stride) + guard r == 0 else { return false } + return lower + _count <= span._count +// } else { +// // we have an alignment precondition, so we can omit a stride check +// let selfEnd = self._start.advanced(by: self._count*stride) +// let spanEnd = span._start.advanced(by: span._count*stride) +// return selfEnd <= spanEnd +// } } /// Returns the offsets where the memory of `span` is located within @@ -687,20 +707,23 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ { /// 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)/MemoryLayout.stride - e = s + span._count - } - return Range(uncheckedBounds: (s, e)) + @_alwaysEmitIntoClient + public func indicesWithin(_ span: borrowing Self) -> Range? { + if _count > span._count { return nil } + if _count == 0 { return Range(uncheckedBounds: (0, 0)) } + if _start < span._start { return nil } + let stride = MemoryLayout.stride + let byteOffset = span._start.distance(to: _start) + let (lower, r) = byteOffset.quotientAndRemainder(dividingBy: stride) + guard r == 0 else { return nil } + let upper = lower + _count + guard upper <= span._count else { return nil } + return Range(uncheckedBounds: (lower, upper)) } } //MARK: one-sided slicing operations -extension Span where Element: ~Copyable /*& ~Escapable*/ { +extension Span where Element: ~Copyable { /// Returns a span containing the initial elements of this span, /// up to the specified maximum length. @@ -717,13 +740,18 @@ 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 { + @_alwaysEmitIntoClient + @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) } + @_alwaysEmitIntoClient + public mutating func _shrink(toFirst maxLength: Int) { + self = _extracting(first: maxLength) + } + /// Returns a span over all but the given number of trailing elements. /// /// If the number of elements to drop exceeds the number of elements in @@ -738,13 +766,18 @@ 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 { + @_alwaysEmitIntoClient + @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) } + @_alwaysEmitIntoClient + public mutating func _shrink(droppingLast k: Int) { + self = _extracting(droppingLast: k) + } + /// Returns a span containing the final elements of the span, /// up to the given maximum length. /// @@ -760,14 +793,19 @@ 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 { + @_alwaysEmitIntoClient + @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)*MemoryLayout.stride) return Self(_unchecked: newStart, count: newCount) } + @_alwaysEmitIntoClient + public mutating func _shrink(toLast maxLength: Int) { + self = _extracting(last: maxLength) + } + /// Returns a span over all but the given number of initial elements. /// /// If the number of elements to drop exceeds the number of elements in @@ -782,11 +820,16 @@ 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 { + @_alwaysEmitIntoClient + @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*MemoryLayout.stride) return Self(_unchecked: newStart, count: count&-droppedCount) } + + @_alwaysEmitIntoClient + public mutating func _shrink(droppingFirst k: Int) { + self = _extracting(droppingFirst: k) + } } From bd528968fc979e1a99b4692fe6737fc3f8de32d3 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 12 Sep 2024 16:52:04 -0700 Subject: [PATCH 10/40] Span iterator draft --- Sources/Future/Span+Iterator.swift | 59 ++++++++++++++++++++++++++++++ Tests/FutureTests/SpanTests.swift | 20 ++++++++++ 2 files changed, 79 insertions(+) create mode 100644 Sources/Future/Span+Iterator.swift diff --git a/Sources/Future/Span+Iterator.swift b/Sources/Future/Span+Iterator.swift new file mode 100644 index 00000000..2ea485f0 --- /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? + + 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/Tests/FutureTests/SpanTests.swift b/Tests/FutureTests/SpanTests.swift index 956ce63e..e3826449 100644 --- a/Tests/FutureTests/SpanTests.swift +++ b/Tests/FutureTests/SpanTests.swift @@ -406,4 +406,24 @@ final class SpanTests: XCTestCase { bounds = nilSpan.offsets(of: emptySpan) 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(count: 8) + b.deallocate() + } + + let span = Span(_unsafeElements: b) + var iterator = Span.Iterator(span) + while let c = iterator.next() { + print(c.id) + } + } } From 8aebaa3ea8613367f0cb64f2384d94f0331c11a7 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 17 Sep 2024 17:57:05 -0700 Subject: [PATCH 11/40] improve RawSpan containment --- Sources/Future/RawSpan.swift | 16 ++++++++++------ Tests/FutureTests/RawSpanTests.swift | 11 +++++++---- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/Sources/Future/RawSpan.swift b/Sources/Future/RawSpan.swift index 3e8963d7..816e1ad9 100644 --- a/Sources/Future/RawSpan.swift +++ b/Sources/Future/RawSpan.swift @@ -524,9 +524,11 @@ extension RawSpan { @_alwaysEmitIntoClient public func isWithin(_ span: borrowing Self) -> Bool { if _count > span._count { return false } - if _count == 0 { return true } - if _start < span._start { return false } - let lower = span._start.distance(to: _start) + guard let start = _pointer, span._count > 0 else { + return _pointer == span._pointer + } + if start < span._start { return false } + let lower = span._start.distance(to: start) return lower + _count <= span._count } @@ -541,9 +543,11 @@ extension RawSpan { @_alwaysEmitIntoClient public func byteOffsetsWithin(_ span: borrowing Self) -> Range? { if _count > span._count { return nil } - if _count == 0 { return Range(uncheckedBounds: (0, 0)) } - if _start < span._start { return nil } - let lower = span._start.distance(to: _start) + guard let start = _pointer, span._count > 0 else { + return _pointer == span._pointer ? Range(uncheckedBounds: (0, 0)) : nil + } + if start < span._start { return nil } + let lower = span._start.distance(to: start) let upper = lower + _count guard upper <= span._count else { return nil } return Range(uncheckedBounds: (lower, upper)) diff --git a/Tests/FutureTests/RawSpanTests.swift b/Tests/FutureTests/RawSpanTests.swift index c97f73b8..9bfa23d9 100644 --- a/Tests/FutureTests/RawSpanTests.swift +++ b/Tests/FutureTests/RawSpanTests.swift @@ -261,14 +261,14 @@ final class RawSpanTests: XCTestCase { XCTAssertTrue(subSpan.isWithin(span)) XCTAssertFalse(span.isWithin(emptySpan)) XCTAssertTrue(emptySpan.isWithin(span)) - XCTAssertTrue(span.isWithin(fakeSpan)) - XCTAssertTrue(fakeSpan.isWithin(span)) + XCTAssertFalse(span.isWithin(fakeSpan)) + XCTAssertFalse(fakeSpan.isWithin(span)) XCTAssertFalse(span.isWithin(nilSpan)) XCTAssertFalse(fakeSpan.isWithin(nilSpan)) XCTAssertFalse(nilSpan.isWithin(emptySpan)) } - func testOffsets() { + func testByteOffsetsWithin() { let b = UnsafeMutableRawBufferPointer.allocate(byteCount: 8, alignment: 8) defer { b.deallocate() } @@ -292,8 +292,11 @@ final class RawSpanTests: XCTestCase { bounds = span.byteOffsetsWithin(subSpan2) XCTAssertNil(bounds) bounds = emptySpan.byteOffsetsWithin(nilSpan) - XCTAssertEqual(bounds, 0..<0) + XCTAssertNil(bounds) bounds = nilSpan.byteOffsetsWithin(span) + XCTAssertNil(bounds) + bounds = nilSpan.byteOffsetsWithin(nilSpan) XCTAssertEqual(bounds, 0..<0) + } } From c4435876d999367df9ef9431c431d4ae44106b18 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 17 Sep 2024 17:57:38 -0700 Subject: [PATCH 12/40] fix iterator test --- Sources/Future/Span+Iterator.swift | 2 +- Tests/FutureTests/SpanTests.swift | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Sources/Future/Span+Iterator.swift b/Sources/Future/Span+Iterator.swift index 2ea485f0..d808ff38 100644 --- a/Sources/Future/Span+Iterator.swift +++ b/Sources/Future/Span+Iterator.swift @@ -16,7 +16,7 @@ extension Span where Element: ~Copyable { var curPointer: UnsafeRawPointer? let endPointer: UnsafeRawPointer? - init(from span: consuming Span) -> dependsOn(immortal) Self { + public init(from span: consuming Span) -> dependsOn(immortal) Self { curPointer = span._pointer endPointer = span._pointer?.advanced( by: span.count*MemoryLayout.stride diff --git a/Tests/FutureTests/SpanTests.swift b/Tests/FutureTests/SpanTests.swift index e3826449..0bea690c 100644 --- a/Tests/FutureTests/SpanTests.swift +++ b/Tests/FutureTests/SpanTests.swift @@ -416,14 +416,16 @@ final class SpanTests: XCTestCase { let b = UnsafeMutableBufferPointer.allocate(capacity: 8) _ = b.initialize(fromContentsOf: (0..<8).map(C.init(id:))) defer { - b.deinitialize(count: 8) + b.deinitialize() b.deallocate() } let span = Span(_unsafeElements: b) - var iterator = Span.Iterator(span) + var iterator = Span.Iterator(from: span) + var i = 0 while let c = iterator.next() { - print(c.id) + XCTAssertEqual(i, c.id) + i += 1 } } } From fbabfd5d664a267567fa44651edf7a3b2af31fd5 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 17 Sep 2024 17:59:12 -0700 Subject: [PATCH 13/40] improve Span containment functions --- Sources/Future/RawSpan.swift | 31 +---- Sources/Future/Span.swift | 63 +++------ Tests/FutureTests/RawSpanTests.swift | 44 ++---- Tests/FutureTests/SpanTests.swift | 194 +++++++++++++++++---------- 4 files changed, 155 insertions(+), 177 deletions(-) diff --git a/Sources/Future/RawSpan.swift b/Sources/Future/RawSpan.swift index 816e1ad9..09ae8797 100644 --- a/Sources/Future/RawSpan.swift +++ b/Sources/Future/RawSpan.swift @@ -515,23 +515,6 @@ extension RawSpan { (self._pointer == other._pointer) && (self._count == other._count) } - /// 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` - @_alwaysEmitIntoClient - public func isWithin(_ span: borrowing Self) -> Bool { - if _count > span._count { return false } - guard let start = _pointer, span._count > 0 else { - return _pointer == span._pointer - } - if start < span._start { return false } - let lower = span._start.distance(to: start) - return lower + _count <= span._count - } - /// Returns the offsets where the memory of `span` is located within /// the memory represented by `self` /// @@ -541,15 +524,15 @@ extension RawSpan { /// - span: a subrange of `self` /// Returns: A range of offsets within `self` @_alwaysEmitIntoClient - public func byteOffsetsWithin(_ span: borrowing Self) -> Range? { - if _count > span._count { return nil } - guard let start = _pointer, span._count > 0 else { + 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 } - if start < span._start { return nil } - let lower = span._start.distance(to: start) - let upper = lower + _count - guard upper <= span._count else { return nil } + 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)) } } diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index 1e5ed285..3d0bab1b 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -389,12 +389,11 @@ extension Span where Element: ~Copyable { extension Span where Element: BitwiseCopyable { -#warning("Restore this computed property once lifetime annotations exist") -// /// Construct a RawSpan over the memory represented by this span -// /// -// /// - Returns: a RawSpan over the memory represented by this span -// @_alwaysEmitIntoClient -// public var rawSpan: RawSpan { RawSpan(self) } + /// Construct a RawSpan over the memory represented by this span + /// + /// - Returns: a RawSpan over the memory represented by this span + @_alwaysEmitIntoClient + public var _rawSpan: RawSpan { RawSpan(_unsafeSpan: self) } } //MARK: integer offset subscripts @@ -673,51 +672,25 @@ extension Span where Element: ~Copyable { (self._pointer == other._pointer) && (self._count == other._count) } - /// Returns true if the memory represented by `span` is a subrange of - /// the memory represented by `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 span of the same type as `self` - /// Returns: whether `span` is a subrange of `self` + /// - span: a span that may be a subrange of `self` + /// Returns: A range of offsets within `self`, or `nil` @_alwaysEmitIntoClient - public func isWithin(_ span: borrowing Self) -> Bool { - if _count > span._count { return false } - if _count == 0 { return true } - if _start < span._start { return false } + 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 + } + if subspanStart < _start { return nil } + let byteOffset = _start.distance(to: subspanStart) let stride = MemoryLayout.stride -#warning("use isPOD once it is generalized") -// if _isPOD(Element.self) { - let byteOffset = span._start.distance(to: _start) - let (lower, r) = byteOffset.quotientAndRemainder(dividingBy: stride) - guard r == 0 else { return false } - return lower + _count <= span._count -// } else { -// // we have an alignment precondition, so we can omit a stride check -// let selfEnd = self._start.advanced(by: self._count*stride) -// let spanEnd = span._start.advanced(by: span._count*stride) -// return selfEnd <= spanEnd -// } - } - - /// Returns the offsets where the memory of `span` is located within - /// the memory represented by `self` - /// - /// Note: `span` must be a subrange of `self` - /// - /// Parameters: - /// - span: a subrange of `self` - /// Returns: A range of offsets within `self` - @_alwaysEmitIntoClient - public func indicesWithin(_ span: borrowing Self) -> Range? { - if _count > span._count { return nil } - if _count == 0 { return Range(uncheckedBounds: (0, 0)) } - if _start < span._start { return nil } - let stride = MemoryLayout.stride - let byteOffset = span._start.distance(to: _start) let (lower, r) = byteOffset.quotientAndRemainder(dividingBy: stride) guard r == 0 else { return nil } - let upper = lower + _count - guard upper <= span._count else { return nil } + let upper = lower + span._count + guard upper <= _count else { return nil } return Range(uncheckedBounds: (lower, upper)) } } diff --git a/Tests/FutureTests/RawSpanTests.swift b/Tests/FutureTests/RawSpanTests.swift index 9bfa23d9..984833c1 100644 --- a/Tests/FutureTests/RawSpanTests.swift +++ b/Tests/FutureTests/RawSpanTests.swift @@ -243,32 +243,7 @@ final class RawSpanTests: XCTestCase { XCTAssertFalse(span.boundsContain(span.byteCount)) } - func testContainment() { - let b = UnsafeMutableRawBufferPointer.allocate(byteCount: 8, alignment: 8) - defer { b.deallocate() } - - let span = RawSpan(_unsafeBytes: b) - let subSpan = span._extracting(last: 2) - let emptySpan = span._extracting(first: 0) - let fakeSpan = RawSpan( - _unsafeStart: b.baseAddress!.advanced(by: 8), byteCount: 8 - ) - let nilSpan = RawSpan( - _unsafeBytes: UnsafeRawBufferPointer(start: nil, count: 0) - ) - - XCTAssertFalse(span.isWithin(subSpan)) - XCTAssertTrue(subSpan.isWithin(span)) - XCTAssertFalse(span.isWithin(emptySpan)) - XCTAssertTrue(emptySpan.isWithin(span)) - XCTAssertFalse(span.isWithin(fakeSpan)) - XCTAssertFalse(fakeSpan.isWithin(span)) - XCTAssertFalse(span.isWithin(nilSpan)) - XCTAssertFalse(fakeSpan.isWithin(nilSpan)) - XCTAssertFalse(nilSpan.isWithin(emptySpan)) - } - - func testByteOffsetsWithin() { + func testByteOffsetsOf() { let b = UnsafeMutableRawBufferPointer.allocate(byteCount: 8, alignment: 8) defer { b.deallocate() } @@ -281,22 +256,21 @@ final class RawSpanTests: XCTestCase { ) var bounds: Range? - bounds = subSpan1.byteOffsetsWithin(span) + bounds = span.byteOffsets(of: subSpan1) XCTAssertEqual(bounds, span._byteOffsets.prefix(6)) - bounds = subSpan2.byteOffsetsWithin(span) + bounds = span.byteOffsets(of: subSpan2) XCTAssertEqual(bounds, span._byteOffsets.suffix(6)) - bounds = subSpan1.byteOffsetsWithin(subSpan2) + bounds = subSpan2.byteOffsets(of: subSpan1) XCTAssertNil(bounds) - bounds = subSpan2.byteOffsetsWithin(subSpan1) + bounds = subSpan1.byteOffsets(of: subSpan2) XCTAssertNil(bounds) - bounds = span.byteOffsetsWithin(subSpan2) + bounds = subSpan2.byteOffsets(of: span) XCTAssertNil(bounds) - bounds = emptySpan.byteOffsetsWithin(nilSpan) + bounds = nilSpan.byteOffsets(of: emptySpan) XCTAssertNil(bounds) - bounds = nilSpan.byteOffsetsWithin(span) + bounds = span.byteOffsets(of: nilSpan) XCTAssertNil(bounds) - bounds = nilSpan.byteOffsetsWithin(nilSpan) + bounds = nilSpan.byteOffsets(of: nilSpan) XCTAssertEqual(bounds, 0..<0) - } } diff --git a/Tests/FutureTests/SpanTests.swift b/Tests/FutureTests/SpanTests.swift index 0bea690c..a30b107f 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 { @@ -113,7 +113,7 @@ final class SpanTests: XCTestCase { let array = Array(0...stride) } } @@ -144,10 +144,10 @@ final class SpanTests: XCTestCase { a.withUnsafeBufferPointer { let span = Span(_unsafeElements: $0) - XCTAssertEqual(span._elementsEqual(span.extracting(first: 1)), false) - XCTAssertEqual(span.extracting(0..<0)._elementsEqual(span.extracting(last: 0)), true) + XCTAssertEqual(span._elementsEqual(span._extracting(first: 1)), false) + XCTAssertEqual(span._extracting(0..<0)._elementsEqual(span._extracting(last: 0)), true) XCTAssertEqual(span._elementsEqual(span), true) - XCTAssertEqual(span.extracting(0..<3)._elementsEqual(span.extracting(last: 3)), false) + XCTAssertEqual(span._extracting(0..<3)._elementsEqual(span._extracting(last: 3)), false) let copy = span.withUnsafeBufferPointer(Array.init) copy.withUnsafeBufferPointer { @@ -164,7 +164,7 @@ final class SpanTests: XCTestCase { let span = Span(_unsafeElements: $0) XCTAssertEqual(span._elementsEqual(a), true) - XCTAssertEqual(span.extracting(0..<0)._elementsEqual([]), true) + XCTAssertEqual(span._extracting(0..<0)._elementsEqual([]), true) XCTAssertEqual(span._elementsEqual(a.dropLast()), false) } } @@ -177,7 +177,7 @@ final class SpanTests: XCTestCase { let s = AnySequence(a) XCTAssertEqual(span._elementsEqual(s), true) - XCTAssertEqual(span.extracting(0..<(capacity-1))._elementsEqual(s), false) + XCTAssertEqual(span._extracting(0..<(capacity-1))._elementsEqual(s), false) XCTAssertEqual(span._elementsEqual(s.dropFirst()), false) } } @@ -187,10 +187,10 @@ final class SpanTests: XCTestCase { let a = (0..(start: nil, count: 0) 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,19 +276,19 @@ final class SpanTests: XCTestCase { a.withUnsafeBufferPointer { let span = Span(_unsafeElements: $0) XCTAssertEqual(span.count, capacity) - XCTAssertEqual(span.extracting(last: capacity).first, 0) - XCTAssertEqual(span.extracting(last: capacity-1).first, 1) - XCTAssertEqual(span.extracting(last: 1).first, capacity-1) - XCTAssertEqual(span.extracting(droppingFirst: capacity).first, nil) - XCTAssertEqual(span.extracting(droppingFirst: 1).first, 1) + XCTAssertEqual(span._extracting(last: capacity).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) 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() { @@ -342,8 +342,8 @@ final class SpanTests: XCTestCase { let capacity = 8 let a = Array(0...allocate(capacity: 8) +// _ = b.initialize(fromContentsOf: 0..<8) +// defer { b.deallocate() } +// +// let span = Span(_unsafeElements: b) +// let subSpan = span._extracting(last: 2) +// let emptySpan = span._extracting(first: 0) +// let fakeSpan = Span( +// _unsafeStart: b.baseAddress!.advanced(by: 8), count: 8 +// ) +// let nilSpan = Span( +// _unsafeElements: UnsafeBufferPointer(start: nil, count: 0) +// ) +// let unalignedSpan = Span( +// _unsafeStart: UnsafeRawPointer(b.baseAddress!).advanced(by: 2).assumingMemoryBound(to: Int.self), +// count: 2 +// ) +// +// XCTAssertTrue(subSpan.isWithin(span))//.contains(subSpan)) +// XCTAssertFalse(span.isWithin(subSpan))//.contains(span)) +// XCTAssertTrue(emptySpan.isWithin(span))//.contains(emptySpan)) +// XCTAssertFalse(span.isWithin(emptySpan))//.contains(span)) +// XCTAssertFalse(fakeSpan.isWithin(span))//.contains(fakeSpan)) +// XCTAssertFalse(span.isWithin(fakeSpan))//.contains(span)) +// XCTAssertFalse(nilSpan.isWithin(span))//.contains(nilSpan)) +// XCTAssertFalse(nilSpan.isWithin(fakeSpan))//.contains(nilSpan)) +// XCTAssertTrue(nilSpan.isWithin(nilSpan)) +// XCTAssertFalse(emptySpan.isWithin(nilSpan))//.contains(emptySpan)) +// XCTAssertFalse(unalignedSpan.isWithin(span)) +// } + +// func testIndicesWithin() { +// let b = UnsafeMutableBufferPointer.allocate(capacity: 8) +// _ = b.initialize(fromContentsOf: 0..<8) +// defer { b.deallocate() } +// +// 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) +// ) +// let unalignedSpan = Span( +// _unsafeStart: UnsafeRawPointer(b.baseAddress!).advanced(by: 2).assumingMemoryBound(to: Int.self), +// count: 2 +// ) +// +// var bounds: Range? +// bounds = subSpan.indicesWithin(span) +// 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) +// XCTAssertEqual(bounds, 0..<0) +// } + + func testIndicesOf() { let b = UnsafeMutableBufferPointer.allocate(capacity: 8) _ = b.initialize(fromContentsOf: 0..<8) defer { b.deallocate() } let span = Span(_unsafeElements: b) - let subSpan = span.extracting(last: 2) - let emptySpan = span.extracting(first: 0) - let fakeSpan = Span( - _unsafeStart: b.baseAddress!.advanced(by: 8), count: 8 - ) + let subSpan1 = span._extracting(first: 6) + let subSpan2 = span._extracting(last: 6) + let emptySpan = span._extracting(first: 0) + let unalignedSpan = RawSpan(_unsafeSpan: span) + ._extracting(droppingFirst: 6) + ._extracting(droppingLast: 2) + .unsafeView(as: Int.self) let nilSpan = Span( _unsafeElements: UnsafeBufferPointer(start: nil, count: 0) ) - 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)) - } - - func testOffsets() { - let b = UnsafeMutableBufferPointer.allocate(capacity: 8) - _ = b.initialize(fromContentsOf: 0..<8) - defer { b.deallocate() } - - 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) - ) - - 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 = span.indices(of: unalignedSpan) + XCTAssertNil(bounds) + bounds = nilSpan.indices(of: nilSpan) XCTAssertEqual(bounds, 0..<0) } From f18b91b719d37649b0f4fb228ffe6bb3fd48698a Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sat, 28 Sep 2024 06:10:38 -0700 Subject: [PATCH 14/40] fix a bounds-checking detail --- Sources/Future/RawSpan.swift | 4 ++-- Sources/Future/Span.swift | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Sources/Future/RawSpan.swift b/Sources/Future/RawSpan.swift index 09ae8797..56078e26 100644 --- a/Sources/Future/RawSpan.swift +++ b/Sources/Future/RawSpan.swift @@ -218,7 +218,7 @@ extension RawSpan { /// - Returns: true if `offsets` is a valid range of byte offsets @_alwaysEmitIntoClient public func boundsContain(_ offsets: Range) -> Bool { - 0 <= offsets.lowerBound && offsets.upperBound <= byteCount + boundsContain(offsets.lowerBound) && offsets.upperBound <= byteCount } /// Return true if `offsets` is a valid range of offsets into this `RawSpan` @@ -228,7 +228,7 @@ extension RawSpan { /// - Returns: true if `offsets` is a valid range of byte offsets @_alwaysEmitIntoClient public func boundsContain(_ offsets: ClosedRange) -> Bool { - 0 <= offsets.lowerBound && offsets.upperBound < byteCount + boundsContain(offsets.lowerBound) && offsets.upperBound < byteCount } } diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index 3d0bab1b..998fa64e 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -373,7 +373,7 @@ extension Span where Element: ~Copyable { /// - Returns: true if `offsets` is a valid range of indices @_alwaysEmitIntoClient public func boundsContain(_ offsets: Range) -> Bool { - 0 <= offsets.lowerBound && offsets.upperBound <= count + boundsContain(offsets.lowerBound) && offsets.upperBound <= count } /// Return true if `offsets` is a valid range of offsets into this `Span` @@ -383,7 +383,7 @@ extension Span where Element: ~Copyable { /// - Returns: true if `offsets` is a valid range of indices @_alwaysEmitIntoClient public func boundsContain(_ offsets: ClosedRange) -> Bool { - 0 <= offsets.lowerBound && offsets.upperBound < count + boundsContain(offsets.lowerBound) && offsets.upperBound < count } } From d1bc334b8cda12ae04df37a2de55423a6e29a58f Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 27 Sep 2024 19:05:02 -0700 Subject: [PATCH 15/40] add OutputSpan --- Sources/Future/OutputSpan.swift | 293 ++++++++++++++++++++++++ Tests/FutureTests/OutputSpanTests.swift | 253 ++++++++++++++++++++ 2 files changed, 546 insertions(+) create mode 100644 Sources/Future/OutputSpan.swift create mode 100644 Tests/FutureTests/OutputSpanTests.swift diff --git a/Sources/Future/OutputSpan.swift b/Sources/Future/OutputSpan.swift new file mode 100644 index 00000000..95101fd5 --- /dev/null +++ b/Sources/Future/OutputSpan.swift @@ -0,0 +1,293 @@ +//===--- 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 +// +//===----------------------------------------------------------------------===// + +public struct OutputSpan: ~Copyable, ~Escapable { + @usableFromInline let _start: UnsafeMutablePointer + public let capacity: Int + public private(set) var initialized: Int = 0 + + deinit { + // `self` always borrows memory, and it shouldn't have gotten here. + // Failing to use `relinquishBorrowedMemory()` is an error. + if initialized > 0 { + fatalError() + } + } + + public init( + initializing pointer: UnsafeMutablePointer, + capacity: Int, + initialized: Int = 0, + owner: borrowing Owner + ) -> dependsOn(owner) Self { + self._start = pointer + self.capacity = capacity + self.initialized = initialized + } +} + +extension OutputSpan where Element: ~Copyable /*& ~Escapable*/ { + public mutating func appendElement(_ value: consuming Element) { + precondition(initialized < capacity, "Output buffer overflow") + _start.advanced(by: initialized).initialize(to: value) + initialized &+= 1 + } + + public mutating func deinitializeLastElement() -> Element? { + guard initialized > 0 else { return nil } + initialized &-= 1 + return _start.advanced(by: initialized).move() + } +} + +extension OutputSpan where Element: ~Copyable { + public mutating func deinitialize() { + let b = UnsafeMutableBufferPointer(start: _start, count: initialized) + b.deinitialize() + initialized = 0 + } +} + +extension OutputSpan { + public mutating func append( + from elements: S + ) -> S.Iterator where S: Sequence, S.Element == Element { + var iterator = elements.makeIterator() + append(from: &iterator) + return iterator + } + + public mutating func append( + from elements: inout some IteratorProtocol + ) { + while initialized < capacity { + guard let element = elements.next() else { break } + _start.advanced(by: initialized).initialize(to: element) + initialized &+= 1 + } + } + + public mutating func append( + fromContentsOf source: some Collection + ) { + let count = source.withContiguousStorageIfAvailable { + guard let sourceAddress = $0.baseAddress, !$0.isEmpty else { + return 0 + } + let available = capacity &- initialized + precondition( + $0.count <= available, + "buffer cannot contain every element from source." + ) + let tail = _start.advanced(by: initialized) + tail.initialize(from: sourceAddress, count: $0.count) + return $0.count + } + if let count { + initialized &+= count + return + } + + let available = capacity &- initialized + let tail = _start.advanced(by: initialized) + let suffix = UnsafeMutableBufferPointer(start: tail, count: available) + var (iterator, copied) = source._copyContents(initializing: suffix) + precondition( + iterator.next() == nil, + "buffer cannot contain every element from source." + ) + assert(initialized + copied <= capacity) + initialized &+= copied + } + + //FIXME: rdar://136838539 & rdar://136849171 + public mutating func append(fromContentsOf source: Span) { + let available = capacity &- initialized + precondition( + source.count <= available, + "buffer cannot contain every element from source." + ) + source.withUnsafeBufferPointer { + let tail = _start.advanced(by: initialized) + tail.initialize(from: $0.baseAddress!, count: $0.count) + } + initialized &+= source.count + } +} + +extension OutputSpan where Element: ~Copyable /*& ~Escapable*/ { + + public mutating func moveAppend( + fromContentsOf source: UnsafeMutableBufferPointer + ) { + guard let sourceAddress = source.baseAddress, !source.isEmpty else { + return + } + let available = capacity &- initialized + precondition( + source.count <= available, + "buffer cannot contain every element from source." + ) + let tail = _start.advanced(by: initialized) + tail.moveInitialize(from: sourceAddress, count: source.count) + initialized &+= source.count + } +} + +extension OutputSpan { + + public mutating func moveAppend( + fromContentsOf source: Slice> + ) { + moveAppend(fromContentsOf: UnsafeMutableBufferPointer(rebasing: source)) + } +} + +//extension OutputSpan where Element: ~Copyable /*& ~Escapable*/ { +// public mutating func initializeSuffixOutOfOrder( +// _ count: Int, +// body: (inout RandomAccessOutputSpan) throws(E) -> R +// ) throws(E) -> R { +// precondition(initialized + count < capacity) +// var out = RandomAccessOutputSpan( +// initializing: _start.advanced(by: initialized), capacity: count, owner: self +// ) +// let result = try body(&out) +// let buffer = out.relinquishBorrowedMemory() +// assert( +// buffer.baseAddress == _start.advanced(by: initialized) && +// initialized + buffer.count < capacity +// ) +// initialized &+= buffer.count +// return result +// } +//} + +extension OutputSpan { + public var initializedPrefix: Span { + get { Span(_unsafeStart: _start, count: initialized) } + } + + public func withSpan( + _ body: (Span) throws(E) -> R + ) throws(E) -> R { + try body(initializedPrefix) + } +} + +// public var mutatingInitializedPrefix: /*inout*/ MutableBufferView { +// mutating /* _read */ get /* mutating(self) */ { +// /* yield */ MutableBufferView( +// unsafeMutablePointer: _start, +// count: initialized, +// dependsOn: /* self */ _start +// ) +// } +// } + +// public mutating func withMutableBufferView( +// _ body: (inout MutableBufferView) throws -> R +// ) rethrows -> R { +// var view = MutableBufferView( +// unsafeMutablePointer: _start, +// count: initialized, +// dependsOn: /* self */ _start +// ) +// return try body(&view) +// } + +extension OutputSpan { + + public consuming func relinquishBorrowedMemory() -> UnsafeMutableBufferPointer { + let (start, initialized) = (self._start, self.initialized) + discard self + return .init(start: start, count: initialized) + } +} + +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, + owner: buffer + ) + 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, + owner: buffer + ) + 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, + owner: buffer + ) + try initializer(&output) + let initialized = output.relinquishBorrowedMemory() + assert(initialized.baseAddress == buffer.baseAddress) + return initialized.count + } + } + assert(count <= self.count) + self.replaceSubrange(count..: ~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, owner: self + ) + 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, owner: allocation) + 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: UnsafeBufferPointer(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) + } + } +} + +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))) + } +} From d374c35bdfce9d3be93d172b0c3115115bf7528a Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sat, 28 Sep 2024 06:07:42 -0700 Subject: [PATCH 16/40] move OutputSpan-providing extensions to their own file - and their tests, too --- Sources/Future/OutputSpan.swift | 78 ---------------- .../Future/StdlibOutputSpanExtensions.swift | 89 +++++++++++++++++++ Tests/FutureTests/OutputSpanTests.swift | 39 -------- .../StdlibOutputSpanExtensionTests.swift | 53 +++++++++++ 4 files changed, 142 insertions(+), 117 deletions(-) create mode 100644 Sources/Future/StdlibOutputSpanExtensions.swift create mode 100644 Tests/FutureTests/StdlibOutputSpanExtensionTests.swift diff --git a/Sources/Future/OutputSpan.swift b/Sources/Future/OutputSpan.swift index 95101fd5..83a8e586 100644 --- a/Sources/Future/OutputSpan.swift +++ b/Sources/Future/OutputSpan.swift @@ -213,81 +213,3 @@ extension OutputSpan { return .init(start: start, count: initialized) } } - -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, - owner: buffer - ) - 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, - owner: buffer - ) - 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, - owner: buffer - ) - try initializer(&output) - let initialized = output.relinquishBorrowedMemory() - assert(initialized.baseAddress == buffer.baseAddress) - return initialized.count - } - } - assert(count <= self.count) - self.replaceSubrange(count..) throws -> Void + ) rethrows { + try self.init( + unsafeUninitializedCapacity: capacity, + initializingWith: { (buffer, count) in + var output = OutputSpan( + initializing: buffer.baseAddress.unsafelyUnwrapped, + capacity: buffer.count, + owner: buffer + ) + 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, + owner: buffer + ) + 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, + owner: buffer + ) + try initializer(&output) + let initialized = output.relinquishBorrowedMemory() + assert(initialized.baseAddress == buffer.baseAddress) + return initialized.count + } + } + assert(count <= self.count) + self.replaceSubrange(count..: ~Copyable { @@ -213,41 +212,3 @@ final class OutputBufferTests: XCTestCase { } } } - -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/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))) + } +} From 98bf179defcd05a5e5cd0ae425f7c167a69646ab Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sat, 28 Sep 2024 06:17:34 -0700 Subject: [PATCH 17/40] update CMakeLists.txt --- Sources/Future/CMakeLists.txt | 4 ++++ 1 file changed, 4 insertions(+) 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" From 6ae687fc318355901f1c66b8bc715f131ee3376d Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sat, 28 Sep 2024 14:32:49 -0700 Subject: [PATCH 18/40] update span to match stdlib prototype implementation --- Package.swift | 1 + Sources/Future/Span.swift | 159 +++++++++++++++++++++++--------------- 2 files changed, 98 insertions(+), 62 deletions(-) diff --git a/Package.swift b/Package.swift index 18ec08df..ccd8a07a 100644 --- a/Package.swift +++ b/Package.swift @@ -53,6 +53,7 @@ var defines: [String] = [ ] let _sharedSettings: [SwiftSetting] = defines.map { .define($0) } + [ + .enableExperimentalFeature("AllowUnsafeAttribute"), .enableExperimentalFeature("BuiltinModule"), .enableExperimentalFeature("NonescapableTypes"), .enableExperimentalFeature("RawLayout"), diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index 998fa64e..9942905a 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -14,6 +14,7 @@ import Builtin // A Span represents a span of memory which // contains initialized instances of `Element`. +@_disallowFeatureSuppression(NonescapableTypes) @frozen public struct Span: Copyable, ~Escapable { @usableFromInline let _pointer: UnsafeRawPointer? @@ -23,29 +24,26 @@ public struct Span: Copyable, ~Escapable { @usableFromInline let _count: Int - @_alwaysEmitIntoClient - internal init( + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline @inline(__always) + init( _unchecked start: UnsafeRawPointer?, count: Int ) -> dependsOn(immortal) Self { - _pointer = .init(start) + _pointer = start _count = count } } +@_disallowFeatureSuppression(NonescapableTypes) @available(*, unavailable) extension Span: Sendable {} -extension UnsafePointer where Pointee: ~Copyable { - - @_alwaysEmitIntoClient - var isAligned: Bool { - (Int(bitPattern: self) & (MemoryLayout.alignment&-1)) == 0 - } -} - +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: ~Copyable { - @_alwaysEmitIntoClient + + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline @inline(__always) internal init( _unchecked elements: UnsafeBufferPointer ) -> dependsOn(immortal) Self { @@ -62,12 +60,14 @@ extension Span where Element: ~Copyable { /// - buffer: an `UnsafeBufferPointer` to initialized elements. /// - owner: a binding whose lifetime must exceed that of /// the newly created `Span`. + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public init( _unsafeElements buffer: UnsafeBufferPointer ) -> dependsOn(immortal) Self { precondition( - buffer.count == 0 || buffer.baseAddress.unsafelyUnwrapped.isAligned, + ((Int(bitPattern: buffer.baseAddress) & + (MemoryLayout.alignment&-1)) == 0), "baseAddress must be properly aligned to access Element" ) self.init(_unchecked: buffer) @@ -82,6 +82,7 @@ extension Span where Element: ~Copyable { /// - 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 @@ -100,20 +101,18 @@ extension Span where Element: ~Copyable { /// - count: the number of initialized elements in the span. /// - owner: a binding whose lifetime must exceed that of /// the newly created `Span`. + @_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 to access Element" - ) - self.init(_unchecked: start, count: count) + self.init(_unsafeElements: .init(start: start, count: count)) } } +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: BitwiseCopyable { /// Unsafely create a `Span` over initialized memory. @@ -125,6 +124,7 @@ extension Span where Element: BitwiseCopyable { /// - buffer: an `UnsafeBufferPointer` to initialized elements. /// - owner: a binding whose lifetime must exceed that of /// the newly created `Span`. + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public init( _unsafeElements buffer: UnsafeBufferPointer @@ -141,6 +141,7 @@ extension Span where Element: BitwiseCopyable { /// - 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 @@ -159,6 +160,7 @@ 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`. + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public init( _unsafeStart start: UnsafePointer, @@ -182,6 +184,7 @@ 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: UnsafeRawBufferPointer @@ -190,10 +193,8 @@ extension Span where Element: BitwiseCopyable { 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 - ) + _pointer = buffer.baseAddress + _count = count } /// Unsafely create a `Span` over initialized memory. @@ -210,6 +211,7 @@ 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 @@ -228,6 +230,7 @@ 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`. + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public init( _unsafeStart pointer: UnsafeRawPointer, @@ -237,13 +240,12 @@ extension Span where Element: BitwiseCopyable { let stride = MemoryLayout.stride let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride) precondition(remainder == 0) - self.init( - _unchecked: pointer.assumingMemoryBound(to: Element.self), - count: count - ) + _pointer = pointer + _count = count } } +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: Equatable { /// Returns a Boolean value indicating whether this and another span @@ -256,6 +258,7 @@ 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 } @@ -283,6 +286,7 @@ 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: some Collection) -> Bool { guard count == other.count else { return false } @@ -301,6 +305,7 @@ 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: some Sequence) -> Bool { var offset = 0 @@ -313,19 +318,17 @@ extension Span where Element: Equatable { } } +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: ~Copyable { - @_alwaysEmitIntoClient - var _address: String { - String(UInt(bitPattern: _pointer), radix: 16, uppercase: false) - } - @_alwaysEmitIntoClient public var description: String { - "(0x\(_address), \(_count))" + let addr = String(UInt(bitPattern: _pointer), radix: 16, uppercase: false) + return "(0x\(addr), \(_count))" } } +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: ~Copyable { /// The number of elements in the span. @@ -354,49 +357,57 @@ extension Span where Element: ~Copyable { } //MARK: Bounds Checking +@_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 + /// - index: an index to validate + /// - Returns: true if `index` is valid + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public func boundsContain(_ offset: Int) -> Bool { - 0 <= offset && offset < count + public func boundsContain(_ index: Int) -> Bool { + 0 <= index && index < _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 + /// - indices: a range of indices to validate + /// - Returns: true if `indices` is a valid range of indices + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public func boundsContain(_ offsets: Range) -> Bool { - boundsContain(offsets.lowerBound) && offsets.upperBound <= count + 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 + /// - indices: a range of indices to validate + /// - Returns: true if `indices` is a valid range of indices + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public func boundsContain(_ offsets: ClosedRange) -> Bool { - boundsContain(offsets.lowerBound) && offsets.upperBound < count + 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 + @_disallowFeatureSuppression(NonescapableTypes) + @unsafe //FIXME: remove when the lifetime inference is fixed @_alwaysEmitIntoClient - public var _rawSpan: RawSpan { RawSpan(_unsafeSpan: self) } + public var _unsafeRawSpan: RawSpan { RawSpan(_unsafeSpan: self) } } //MARK: integer offset subscripts +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: ~Copyable { /// Accesses the element at the specified position in the `Span`. @@ -421,6 +432,7 @@ extension Span where Element: ~Copyable { /// must be greater or equal to zero, and less than `count`. /// /// - Complexity: O(1) + @unsafe @_alwaysEmitIntoClient public subscript(unchecked position: Int) -> Element { _read { @@ -432,6 +444,7 @@ extension Span where Element: ~Copyable { } } +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: BitwiseCopyable { /// Accesses the element at the specified position in the `Span`. @@ -456,6 +469,7 @@ extension Span where Element: BitwiseCopyable { /// must be greater or equal to zero, and less than `count`. /// /// - Complexity: O(1) + @unsafe @_alwaysEmitIntoClient public subscript(unchecked position: Int) -> Element { get { @@ -466,6 +480,7 @@ extension Span where Element: BitwiseCopyable { } //MARK: extracting sub-spans +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: ~Copyable { /// Constructs a new span over the items within the supplied range of @@ -481,12 +496,13 @@ extension Span where Element: ~Copyable { /// - Returns: A `Span` over the items within `bounds` /// /// - Complexity: O(1) - @_alwaysEmitIntoClient + @_disallowFeatureSuppression(NonescapableTypes) @usableFromInline func _extracting(_ bounds: Range) -> Self { precondition(boundsContain(bounds)) return _extracting(unchecked: bounds) } + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func _shrink(to bounds: Range) { self = _extracting(bounds) @@ -507,14 +523,17 @@ extension Span where Element: ~Copyable { /// - Returns: A `Span` over the items within `bounds` /// /// - Complexity: O(1) - @_alwaysEmitIntoClient + @_disallowFeatureSuppression(NonescapableTypes) + @unsafe @usableFromInline func _extracting(unchecked bounds: Range) -> Self { Span( - _unchecked: _pointer?.advanced(by: bounds.lowerBound*MemoryLayout.stride), + _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) @@ -533,11 +552,12 @@ extension Span where Element: ~Copyable { /// - Returns: A `Span` over the items within `bounds` /// /// - Complexity: O(1) - @_alwaysEmitIntoClient + @_disallowFeatureSuppression(NonescapableTypes) @usableFromInline func _extracting(_ bounds: some RangeExpression) -> Self { _extracting(bounds.relative(to: _indices)) } + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func _shrink(to bounds: some RangeExpression) { self = _extracting(bounds) @@ -558,13 +578,16 @@ extension Span where Element: ~Copyable { /// - Returns: A `Span` over the items within `bounds` /// /// - Complexity: O(1) - @_alwaysEmitIntoClient + @_disallowFeatureSuppression(NonescapableTypes) + @unsafe @usableFromInline func _extracting( uncheckedBounds bounds: some RangeExpression ) -> Self { _extracting(unchecked: bounds.relative(to: _indices)) } + @_disallowFeatureSuppression(NonescapableTypes) + @unsafe @_alwaysEmitIntoClient public mutating func _shrink(toUnchecked bounds: some RangeExpression) { self = _extracting(uncheckedBounds: bounds) @@ -579,14 +602,15 @@ extension Span where Element: ~Copyable { /// - Returns: A `Span` over all the items of this span. /// /// - Complexity: O(1) - @_alwaysEmitIntoClient + @_disallowFeatureSuppression(NonescapableTypes) @usableFromInline func _extracting(_: UnboundedRange) -> Self { self } } //MARK: withUnsafePointer, etc. -extension Span where Element: ~Copyable { +@_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. @@ -601,8 +625,9 @@ extension Span where Element: ~Copyable { /// 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 { guard let pointer = _pointer, count > 0 else { @@ -614,6 +639,7 @@ extension Span where Element: ~Copyable { } } +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: BitwiseCopyable { //FIXME: mark closure parameter as non-escaping @@ -631,8 +657,9 @@ 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(_unsafeSpan: self).withUnsafeBytes(body) @@ -664,9 +691,11 @@ extension Span where Element: Copyable { } } +@_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) @@ -677,7 +706,8 @@ extension Span where Element: ~Copyable { /// /// Parameters: /// - span: a span that may be a subrange of `self` - /// Returns: A range of offsets within `self`, or `nil` + /// 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 } @@ -696,6 +726,7 @@ extension Span where Element: ~Copyable { } //MARK: one-sided slicing operations +@_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: ~Copyable { /// Returns a span containing the initial elements of this span, @@ -713,13 +744,14 @@ extension Span where Element: ~Copyable { /// - Returns: A span with at most `maxLength` elements. /// /// - Complexity: O(1) - @_alwaysEmitIntoClient + @_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) } + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func _shrink(toFirst maxLength: Int) { self = _extracting(first: maxLength) @@ -739,13 +771,14 @@ extension Span where Element: ~Copyable { /// - Returns: A span leaving off the specified number of elements at the end. /// /// - Complexity: O(1) - @_alwaysEmitIntoClient + @_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) } + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func _shrink(droppingLast k: Int) { self = _extracting(droppingLast: k) @@ -766,7 +799,7 @@ extension Span where Element: ~Copyable { /// - Returns: A span with at most `maxLength` elements. /// /// - Complexity: O(1) - @_alwaysEmitIntoClient + @_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) @@ -774,6 +807,7 @@ extension Span where Element: ~Copyable { return Self(_unchecked: newStart, count: newCount) } + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func _shrink(toLast maxLength: Int) { self = _extracting(last: maxLength) @@ -793,7 +827,7 @@ extension Span where Element: ~Copyable { /// - Returns: A span starting after the specified number of elements. /// /// - Complexity: O(1) - @_alwaysEmitIntoClient + @_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) @@ -801,6 +835,7 @@ extension Span where Element: ~Copyable { return Self(_unchecked: newStart, count: count&-droppedCount) } + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func _shrink(droppingFirst k: Int) { self = _extracting(droppingFirst: k) From 82eeb9c6e9dfaf1221b72bb2bfe1332f243d2c70 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sat, 28 Sep 2024 14:47:17 -0700 Subject: [PATCH 19/40] restore span extensions to `Foundation.Data` --- Sources/Future/StdlibSpanExtensions.swift | 2 -- Tests/FutureTests/StdlibSpanExtensionTests.swift | 3 +-- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/Sources/Future/StdlibSpanExtensions.swift b/Sources/Future/StdlibSpanExtensions.swift index 5e5787b9..55621c0d 100644 --- a/Sources/Future/StdlibSpanExtensions.swift +++ b/Sources/Future/StdlibSpanExtensions.swift @@ -98,7 +98,6 @@ extension Slice { } } -#if false //FIXME: rdar://134382237 import struct Foundation.Data extension Data { @@ -144,7 +143,6 @@ extension Data { return try result.get() } } -#endif extension Array { diff --git a/Tests/FutureTests/StdlibSpanExtensionTests.swift b/Tests/FutureTests/StdlibSpanExtensionTests.swift index 4516e725..4c31cfda 100644 --- a/Tests/FutureTests/StdlibSpanExtensionTests.swift +++ b/Tests/FutureTests/StdlibSpanExtensionTests.swift @@ -11,13 +11,13 @@ //===----------------------------------------------------------------------===// import XCTest +import Foundation 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 { @@ -47,7 +47,6 @@ final class StdlibSpanExtensionTests: XCTestCase { XCTAssertEqual(error, .error) } } -#endif func testArraySpan() throws { let a = (0..<4).map(String.init(_:)) From feabec869557c060e9f3391440942f3105df3977 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 30 Sep 2024 16:07:38 -0700 Subject: [PATCH 20/40] name a generic parameter properly --- Sources/Future/RawSpan.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/Future/RawSpan.swift b/Sources/Future/RawSpan.swift index 56078e26..431ccec5 100644 --- a/Sources/Future/RawSpan.swift +++ b/Sources/Future/RawSpan.swift @@ -150,12 +150,12 @@ extension RawSpan { /// - span: An existing `Span`, which will define both this /// `RawSpan`'s lifetime and the memory it represents. @_alwaysEmitIntoClient - public init( - _unsafeSpan span: borrowing Span + public init( + _unsafeSpan span: borrowing Span ) -> dependsOn(immortal) Self { self.init( _unchecked: UnsafeRawPointer(span._start), - byteCount: span.count * MemoryLayout.stride + byteCount: span.count &* MemoryLayout.stride ) } } From 8cb60d46d47ddb8c0580b3bd31838ed46886b0cd Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sat, 28 Sep 2024 14:27:11 -0700 Subject: [PATCH 21/40] add mutable span --- Sources/Future/MutableSpan.swift | 562 +++++++++++++++++++++++++++++++ 1 file changed, 562 insertions(+) create mode 100644 Sources/Future/MutableSpan.swift diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift new file mode 100644 index 00000000..db1a3ed4 --- /dev/null +++ b/Sources/Future/MutableSpan.swift @@ -0,0 +1,562 @@ +//===--- 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: UnsafeMutablePointer? + + @usableFromInline let _count: Int + + @usableFromInline @inline(__always) + var _start: UnsafeMutablePointer { _pointer.unsafelyUnwrapped } + + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline @inline(__always) + init( + _unchecked start: UnsafeMutablePointer?, + 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( + buffer.count == 0 || + ((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)) + } +} + +//TODO: initializers where Element: BitwiseCopyable + +//extension MutableSpan /*where Element: BitwiseCopyable*/ { +// +// public init( //FIXME: should be failable +// unsafeMutableRawBufferPointer buffer: UnsafeMutableRawBufferPointer, +// dependsOn owner: borrowing Owner +// ) { +// guard _isPOD(Element.self) else { fatalError() } +// guard let p = buffer.baseAddress else { /*return nil*/ fatalError() } +// let (q, r) = buffer.count.quotientAndRemainder(dividingBy: MemoryLayout.stride) +// precondition(r == 0) +// self.init(unsafeMutablePointer: p.assumingMemoryBound(to: Element.self), count: q, dependsOn: owner) +// } +//} + +//MARK: Sequence + +//extension MutableSpan /*: Sequence */ { +// +// public func makeIterator() -> SpanIterator { +// .init(from: 0, to: _count, dependsOn: /* self */ baseAddress) +// } +// +// //FIXME: mark closure parameter as non-escaping +// public func withContiguousStorageIfAvailable( +// _ body: (UnsafeBufferPointer) throws -> R +// ) rethrows -> R? { +// try Span(self).withContiguousStorageIfAvailable(body) +// } +//} + +@_disallowFeatureSuppression(NonescapableTypes) +extension Span where Element: ~Copyable { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init(_ mutableSpan: borrowing MutableSpan) { + self.init(_unchecked: mutableSpan._start, count: mutableSpan.count) + } +} + +@_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(other)) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func _elementsEqual(_ other: Span) -> Bool { + Span(self)._elementsEqual(other) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func _elementsEqual(_ other: some Collection) -> Bool { + Span(self)._elementsEqual(other) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func _elementsEqual(_ other: some Sequence) -> Bool { + Span(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 { Span(self)._unsafeRawSpan } +} + +@_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)) + yield self[unchecked: position] + } + _modify { + precondition(boundsContain(position)) + 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 stride = MemoryLayout.stride + let p = _start.advanced(by: position&*stride)._rawValue + let binding = Builtin.bindMemory(p, count._builtinWordValue, Element.self) + defer { Builtin.rebindMemory(p, binding) } + yield UnsafePointer(p).pointee + } + _modify { + let stride = MemoryLayout.stride + let p = _start.advanced(by: position&*stride)._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 UnsafeRawPointer(_start).loadUnaligned(fromByteOffset: offset, as: Element.self) + } + set { + let offset = position&*MemoryLayout.stride + UnsafeMutableRawPointer(_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(self).withUnsafeBufferPointer(body) + } + + //FIXME: mark closure parameter as non-escaping + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public func withUnsafeMutableBufferPointer( + _ body: (inout UnsafeMutableBufferPointer) throws(E) -> Result + ) throws(E) -> Result { + guard let pointer = _pointer, count > 0 else { + var buffer = UnsafeMutableBufferPointer(start: nil, count: 0) + return try body(&buffer) + } + return try pointer.withMemoryRebound(to: Element.self, capacity: count) { + ptr throws(E) -> Result in + var buf = UnsafeMutableBufferPointer(start: ptr, count: count) + defer { + precondition( + (buf.baseAddress, buf.count) == (ptr, count), + "MutableSpan.withUnsafeMutableBufferPointer: replacing the buffer is not allowed" + ) + } + return try body(&buf) + } + } +} + +@_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 func withUnsafeMutableBytes( + _ body: (_ buffer: UnsafeMutableRawBufferPointer) throws(E) -> Result + ) throws(E) -> Result { + let bytes = UnsafeMutableRawBufferPointer( + start: (_count == 0) ? nil : UnsafeMutableRawPointer(_start), + count: _count &* MemoryLayout.stride + ) + return try body(bytes) + } +} + +//MARK: UMBP-style update functions +extension MutableSpan { + + public func update(repeating repeatedValue: Element) { + _start.withMemoryRebound(to: Element.self, capacity: count) { + $0.update(repeating: repeatedValue, count: count) + } + } + + public mutating func update( + from source: S + ) -> (unwritten: S.Iterator, index: Int) where S.Element == Element { + var iterator = source.makeIterator() + guard !self.isEmpty else { return (iterator, 0) } + var index = 0 + while index < _count { + guard let value = iterator.next() else { break } + self[unchecked: index] = value + index &+= 1 + } + return (iterator, index) + } + + public mutating func update(fromContentsOf source: some Collection) -> Int { + let updated = source.withContiguousStorageIfAvailable { + [ count = self.count, baseAddress = self._start ] sourceBuffer in + guard let sourceAddress = sourceBuffer.baseAddress else { + return 0 + } + precondition( + sourceBuffer.count <= count, + "destination buffer view cannot contain every element from source." + ) + baseAddress.withMemoryRebound(to: Element.self, capacity: sourceBuffer.count) { + $0.update(from: sourceAddress, count: sourceBuffer.count) + } + return sourceBuffer.count + } + 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 { + preconditionFailure( + "destination buffer view cannot contain every element from source." + ) + break + } + self[unchecked: index] = value + index &+= 1 + } + return index + } +} + +extension MutableSpan where Element: Copyable { + + public mutating func update(fromContentsOf source: Span) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: borrowing MutableSpan) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: UnsafeBufferPointer) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: UnsafeMutableBufferPointer) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: Slice>) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: Slice>) -> Int { + return 0 + } +} + +extension MutableSpan where Element: ~Copyable { + + public mutating func moveUpdate(fromContentsOf source: UnsafeMutableBufferPointer) -> Int { + return 0 + } +} + +extension MutableSpan where Element: BitwiseCopyable { + //TODO: overload the various `update` functions to use memcpy + + public mutating func update(fromContentsOf source: some Collection) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: Span) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: borrowing MutableSpan) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: UnsafeBufferPointer) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: UnsafeMutableBufferPointer) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: Slice>) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: Slice>) -> Int { + return 0 + } + + public mutating func moveUpdate(fromContentsOf source: UnsafeMutableBufferPointer) -> Int { + return 0 + } + + public mutating func moveUpdate(fromContentsOf source: Slice>) -> Int { + return 0 + } +} + +//MARK: copyMemory +//FIXME: move these to a MutableRawSpan +extension MutableSpan where Element: BitwiseCopyable { + + @_alwaysEmitIntoClient + public func copyMemory( + from source: borrowing MutableSpan + ) -> Int { + guard _isPOD(Element.self) else { fatalError() } + return copyMemory(from: .init(source)) + } + + public func copyMemory(from source: Span) -> Int { + guard _isPOD(Element.self) else { fatalError() } + precondition( + source.count <= count, + "MutableSpan.copyMemory source has too many elements" + ) + UnsafeMutableRawPointer(_start).copyMemory( + from: source._start, + byteCount: source.count&*MemoryLayout.stride + ) + return 0.advanced(by: source.count) + } +} From 693ff4a389052cf37c7e1808331e70d2c040f12a Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 30 Sep 2024 17:51:40 -0700 Subject: [PATCH 22/40] add MutableSpan initializers where Element: BitwiseCopyable --- Sources/Future/MutableSpan.swift | 73 ++++++++++++++++++++------------ 1 file changed, 45 insertions(+), 28 deletions(-) diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift index db1a3ed4..22c68574 100644 --- a/Sources/Future/MutableSpan.swift +++ b/Sources/Future/MutableSpan.swift @@ -76,37 +76,54 @@ extension MutableSpan where Element: ~Copyable { } } -//TODO: initializers where Element: BitwiseCopyable +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan where Element: BitwiseCopyable { -//extension MutableSpan /*where Element: BitwiseCopyable*/ { -// -// public init( //FIXME: should be failable -// unsafeMutableRawBufferPointer buffer: UnsafeMutableRawBufferPointer, -// dependsOn owner: borrowing Owner -// ) { -// guard _isPOD(Element.self) else { fatalError() } -// guard let p = buffer.baseAddress else { /*return nil*/ fatalError() } -// let (q, r) = buffer.count.quotientAndRemainder(dividingBy: MemoryLayout.stride) -// precondition(r == 0) -// self.init(unsafeMutablePointer: p.assumingMemoryBound(to: Element.self), count: q, dependsOn: owner) -// } -//} + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeElements buffer: UnsafeMutableBufferPointer + ) -> dependsOn(immortal) Self { + self.init(_unchecked: buffer) + } -//MARK: Sequence + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeStart start: UnsafeMutablePointer, + count: Int + ) -> dependsOn(immortal) Self { + precondition(count >= 0, "Count must not be negative") + self.init(_unchecked: start, count: count) + } -//extension MutableSpan /*: Sequence */ { -// -// public func makeIterator() -> SpanIterator { -// .init(from: 0, to: _count, dependsOn: /* self */ baseAddress) -// } -// -// //FIXME: mark closure parameter as non-escaping -// public func withContiguousStorageIfAvailable( -// _ body: (UnsafeBufferPointer) throws -> R -// ) rethrows -> R? { -// try Span(self).withContiguousStorageIfAvailable(body) -// } -//} + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeBytes buffer: UnsafeMutableRawBufferPointer + ) -> dependsOn(immortal) Self { + let (byteCount, stride) = (buffer.count, MemoryLayout.stride) + precondition(byteCount >= 0, "Count must not be negative") + let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride) + precondition(remainder == 0) + _pointer = buffer.baseAddress?.assumingMemoryBound(to: Element.self) + _count = count + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public init( + _unsafeStart pointer: UnsafeMutableRawPointer, + 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) + _pointer = pointer.assumingMemoryBound(to: Element.self) + _count = count + } +} @_disallowFeatureSuppression(NonescapableTypes) extension Span where Element: ~Copyable { From 8af1843d071dd01053b5b22b3e5db7aba74f7844 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 1 Oct 2024 16:00:42 -0700 Subject: [PATCH 23/40] Span precondition tweaks --- Sources/Future/Span.swift | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index 9942905a..b4fdfe07 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -190,11 +190,9 @@ extension Span where Element: BitwiseCopyable { _unsafeBytes buffer: UnsafeRawBufferPointer ) -> dependsOn(immortal) Self { let (byteCount, stride) = (buffer.count, MemoryLayout.stride) - precondition(byteCount >= 0, "Count must not be negative") let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride) - precondition(remainder == 0) - _pointer = buffer.baseAddress - _count = count + 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. @@ -239,9 +237,8 @@ extension Span where Element: BitwiseCopyable { precondition(byteCount >= 0, "Count must not be negative") let stride = MemoryLayout.stride let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride) - precondition(remainder == 0) - _pointer = pointer - _count = count + precondition(remainder == 0, "Span must contain a whole number of elements") + self.init(_unchecked: pointer, count: count) } } @@ -419,7 +416,7 @@ extension Span where Element: ~Copyable { @_alwaysEmitIntoClient public subscript(_ position: Int) -> Element { _read { - precondition(boundsContain(position)) + precondition(boundsContain(position), "index out of bounds") yield self[unchecked: position] } } @@ -456,7 +453,7 @@ extension Span where Element: BitwiseCopyable { @_alwaysEmitIntoClient public subscript(_ position: Int) -> Element { get { - precondition(boundsContain(position)) + precondition(boundsContain(position), "index out of bounds") return self[unchecked: position] } } @@ -498,7 +495,7 @@ extension Span where Element: ~Copyable { /// - Complexity: O(1) @_disallowFeatureSuppression(NonescapableTypes) @usableFromInline func _extracting(_ bounds: Range) -> Self { - precondition(boundsContain(bounds)) + precondition(boundsContain(bounds), "index out of bounds") return _extracting(unchecked: bounds) } From cb84b912c213987c08418874b19513c3b17345e6 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 1 Oct 2024 16:04:33 -0700 Subject: [PATCH 24/40] Span test tweaks --- Tests/FutureTests/SpanTests.swift | 77 ++++++++----------------------- 1 file changed, 19 insertions(+), 58 deletions(-) diff --git a/Tests/FutureTests/SpanTests.swift b/Tests/FutureTests/SpanTests.swift index a30b107f..df3a1148 100644 --- a/Tests/FutureTests/SpanTests.swift +++ b/Tests/FutureTests/SpanTests.swift @@ -113,7 +113,7 @@ final class SpanTests: XCTestCase { let array = Array(0...stride) } } @@ -358,64 +358,25 @@ final class SpanTests: XCTestCase { XCTAssertEqual(prefix.count, 2) } -// func testContainment() { -// let b = UnsafeMutableBufferPointer.allocate(capacity: 8) -// _ = b.initialize(fromContentsOf: 0..<8) -// defer { b.deallocate() } -// -// let span = Span(_unsafeElements: b) -// let subSpan = span._extracting(last: 2) -// let emptySpan = span._extracting(first: 0) -// let fakeSpan = Span( -// _unsafeStart: b.baseAddress!.advanced(by: 8), count: 8 -// ) -// let nilSpan = Span( -// _unsafeElements: UnsafeBufferPointer(start: nil, count: 0) -// ) -// let unalignedSpan = Span( -// _unsafeStart: UnsafeRawPointer(b.baseAddress!).advanced(by: 2).assumingMemoryBound(to: Int.self), -// count: 2 -// ) -// -// XCTAssertTrue(subSpan.isWithin(span))//.contains(subSpan)) -// XCTAssertFalse(span.isWithin(subSpan))//.contains(span)) -// XCTAssertTrue(emptySpan.isWithin(span))//.contains(emptySpan)) -// XCTAssertFalse(span.isWithin(emptySpan))//.contains(span)) -// XCTAssertFalse(fakeSpan.isWithin(span))//.contains(fakeSpan)) -// XCTAssertFalse(span.isWithin(fakeSpan))//.contains(span)) -// XCTAssertFalse(nilSpan.isWithin(span))//.contains(nilSpan)) -// XCTAssertFalse(nilSpan.isWithin(fakeSpan))//.contains(nilSpan)) -// XCTAssertTrue(nilSpan.isWithin(nilSpan)) -// XCTAssertFalse(emptySpan.isWithin(nilSpan))//.contains(emptySpan)) -// XCTAssertFalse(unalignedSpan.isWithin(span)) -// } + func testIdentity() { + let b = UnsafeMutableBufferPointer.allocate(capacity: 8) + _ = b.initialize(fromContentsOf: 0..<8) + defer { b.deallocate() } -// func testIndicesWithin() { -// let b = UnsafeMutableBufferPointer.allocate(capacity: 8) -// _ = b.initialize(fromContentsOf: 0..<8) -// defer { b.deallocate() } -// -// 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) -// ) -// let unalignedSpan = Span( -// _unsafeStart: UnsafeRawPointer(b.baseAddress!).advanced(by: 2).assumingMemoryBound(to: Int.self), -// count: 2 -// ) -// -// var bounds: Range? -// bounds = subSpan.indicesWithin(span) -// 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) -// XCTAssertEqual(bounds, 0..<0) -// } + let span = Span(_unsafeElements: b) + let pre = span._extracting(first: 6) + let suf = span._extracting(last: 6) + + XCTAssertFalse( + pre.isIdentical(to: suf) + ) + XCTAssertFalse( + pre.isIdentical(to: span) + ) + XCTAssertTrue( + pre._extracting(last: 4).isIdentical(to: suf._extracting(first: 4)) + ) + } func testIndicesOf() { let b = UnsafeMutableBufferPointer.allocate(capacity: 8) From 1b7168f7273ddfc7d8b654474b25945a465c48c7 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 2 Oct 2024 17:23:25 -0700 Subject: [PATCH 25/40] more additions and fixes for MutableSpan --- Sources/Future/MutableSpan.swift | 168 +++++++++++++++++++------------ 1 file changed, 101 insertions(+), 67 deletions(-) diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift index 22c68574..92343b87 100644 --- a/Sources/Future/MutableSpan.swift +++ b/Sources/Future/MutableSpan.swift @@ -17,17 +17,17 @@ import Builtin @_disallowFeatureSuppression(NonescapableTypes) @frozen public struct MutableSpan: ~Copyable & ~Escapable { - @usableFromInline let _pointer: UnsafeMutablePointer? + @usableFromInline let _pointer: UnsafeMutableRawPointer? @usableFromInline let _count: Int @usableFromInline @inline(__always) - var _start: UnsafeMutablePointer { _pointer.unsafelyUnwrapped } + var _start: UnsafeMutableRawPointer { _pointer.unsafelyUnwrapped } @_disallowFeatureSuppression(NonescapableTypes) @usableFromInline @inline(__always) init( - _unchecked start: UnsafeMutablePointer?, + _unchecked start: UnsafeMutableRawPointer?, count: Int ) -> dependsOn(immortal) Self { _pointer = start @@ -57,7 +57,6 @@ extension MutableSpan where Element: ~Copyable { _unsafeElements buffer: UnsafeMutableBufferPointer ) -> dependsOn(immortal) Self { precondition( - buffer.count == 0 || ((Int(bitPattern: buffer.baseAddress) & (MemoryLayout.alignment&-1)) == 0), "baseAddress must be properly aligned to access Element" @@ -103,11 +102,9 @@ extension MutableSpan where Element: BitwiseCopyable { _unsafeBytes buffer: UnsafeMutableRawBufferPointer ) -> dependsOn(immortal) Self { let (byteCount, stride) = (buffer.count, MemoryLayout.stride) - precondition(byteCount >= 0, "Count must not be negative") let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride) - precondition(remainder == 0) - _pointer = buffer.baseAddress?.assumingMemoryBound(to: Element.self) - _count = count + precondition(remainder == 0, "Span must contain a whole number of elements") + self.init(_unchecked: buffer.baseAddress, count: count) } @_disallowFeatureSuppression(NonescapableTypes) @@ -119,9 +116,8 @@ extension MutableSpan where Element: BitwiseCopyable { precondition(byteCount >= 0, "Count must not be negative") let stride = MemoryLayout.stride let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride) - precondition(remainder == 0) - _pointer = pointer.assumingMemoryBound(to: Element.self) - _count = count + precondition(remainder == 0, "Span must contain a whole number of elements") + self.init(_unchecked: pointer, count: count) } } @@ -130,7 +126,7 @@ extension Span where Element: ~Copyable { @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public init(_ mutableSpan: borrowing MutableSpan) { + public init(_unsafeMutableSpan mutableSpan: borrowing MutableSpan) { self.init(_unchecked: mutableSpan._start, count: mutableSpan.count) } } @@ -156,25 +152,25 @@ extension MutableSpan where Element: Equatable { @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public func _elementsEqual(_ other: borrowing Self) -> Bool { - _elementsEqual(Span(other)) + _elementsEqual(Span(_unsafeMutableSpan: other)) } @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public func _elementsEqual(_ other: Span) -> Bool { - Span(self)._elementsEqual(other) + Span(_unsafeMutableSpan: self)._elementsEqual(other) } @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public func _elementsEqual(_ other: some Collection) -> Bool { - Span(self)._elementsEqual(other) + Span(_unsafeMutableSpan: self)._elementsEqual(other) } @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public func _elementsEqual(_ other: some Sequence) -> Bool { - Span(self)._elementsEqual(other) + Span(_unsafeMutableSpan: self)._elementsEqual(other) } } @@ -251,7 +247,7 @@ extension MutableSpan where Element: BitwiseCopyable { @_disallowFeatureSuppression(NonescapableTypes) @unsafe //FIXME: remove when the lifetime inference is fixed @_alwaysEmitIntoClient - public var _unsafeRawSpan: RawSpan { Span(self)._unsafeRawSpan } + public var _unsafeRawSpan: RawSpan { RawSpan(_unsafeMutableSpan: self) } } @_disallowFeatureSuppression(NonescapableTypes) @@ -268,11 +264,11 @@ extension MutableSpan where Element: ~Copyable { @_alwaysEmitIntoClient public subscript(_ position: Int) -> Element { _read { - precondition(boundsContain(position)) + precondition(boundsContain(position), "index out of bounds") yield self[unchecked: position] } _modify { - precondition(boundsContain(position)) + precondition(boundsContain(position), "index out of bounds") yield &self[unchecked: position] } } @@ -289,15 +285,15 @@ extension MutableSpan where Element: ~Copyable { @_alwaysEmitIntoClient public subscript(unchecked position: Int) -> Element { _read { - let stride = MemoryLayout.stride - let p = _start.advanced(by: position&*stride)._rawValue + 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 stride = MemoryLayout.stride - let p = _start.advanced(by: position&*stride)._rawValue + 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) @@ -340,12 +336,11 @@ extension MutableSpan where Element: BitwiseCopyable { public subscript(unchecked position: Int) -> Element { get { let offset = position&*MemoryLayout.stride - return UnsafeRawPointer(_start).loadUnaligned(fromByteOffset: offset, as: Element.self) + return _start.loadUnaligned(fromByteOffset: offset, as: Element.self) } set { let offset = position&*MemoryLayout.stride - UnsafeMutableRawPointer(_start) - .storeBytes(of: newValue, toByteOffset: offset, as: Element.self) + _start.storeBytes(of: newValue, toByteOffset: offset, as: Element.self) } } } @@ -359,30 +354,34 @@ extension MutableSpan where Element: ~Copyable { public func withUnsafeBufferPointer( _ body: (_ buffer: UnsafeBufferPointer) throws(E) -> Result ) throws(E) -> Result { - try Span(self).withUnsafeBufferPointer(body) + try Span(_unsafeMutableSpan: self).withUnsafeBufferPointer(body) } //FIXME: mark closure parameter as non-escaping @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public func withUnsafeMutableBufferPointer( + public mutating func withUnsafeMutableBufferPointer( _ body: (inout UnsafeMutableBufferPointer) throws(E) -> Result ) throws(E) -> Result { - guard let pointer = _pointer, count > 0 else { - var buffer = UnsafeMutableBufferPointer(start: nil, count: 0) - return try body(&buffer) - } - return try pointer.withMemoryRebound(to: Element.self, capacity: count) { - ptr throws(E) -> Result in - var buf = UnsafeMutableBufferPointer(start: ptr, count: count) + func executeBody( + _ start: UnsafeMutablePointer?, _ count: Int + ) throws(E) -> Result { + var buf = UnsafeMutableBufferPointer(start: start, count: count) defer { precondition( - (buf.baseAddress, buf.count) == (ptr, count), + (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) + } } } @@ -401,11 +400,11 @@ extension MutableSpan where Element: BitwiseCopyable { //FIXME: mark closure parameter as non-escaping @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public func withUnsafeMutableBytes( + public mutating func withUnsafeMutableBytes( _ body: (_ buffer: UnsafeMutableRawBufferPointer) throws(E) -> Result ) throws(E) -> Result { let bytes = UnsafeMutableRawBufferPointer( - start: (_count == 0) ? nil : UnsafeMutableRawPointer(_start), + start: (_count == 0) ? nil : _start, count: _count &* MemoryLayout.stride ) return try body(bytes) @@ -415,12 +414,14 @@ extension MutableSpan where Element: BitwiseCopyable { //MARK: UMBP-style update functions extension MutableSpan { - public func update(repeating repeatedValue: Element) { + @_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 { @@ -435,20 +436,10 @@ extension MutableSpan { return (iterator, index) } + @_alwaysEmitIntoClient public mutating func update(fromContentsOf source: some Collection) -> Int { let updated = source.withContiguousStorageIfAvailable { - [ count = self.count, baseAddress = self._start ] sourceBuffer in - guard let sourceAddress = sourceBuffer.baseAddress else { - return 0 - } - precondition( - sourceBuffer.count <= count, - "destination buffer view cannot contain every element from source." - ) - baseAddress.withMemoryRebound(to: Element.self, capacity: sourceBuffer.count) { - $0.update(from: sourceAddress, count: sourceBuffer.count) - } - return sourceBuffer.count + self.update(fromContentsOf: $0) } if let updated { return 0.advanced(by: updated) @@ -464,56 +455,85 @@ extension MutableSpan { var iterator = source.makeIterator() var index = 0 + let _count = _count while let value = iterator.next() { + print(value, index, _count) guard index < _count else { - preconditionFailure( + fatalError( "destination buffer view cannot contain every element from source." ) - break } self[unchecked: index] = value index &+= 1 } return index } -} - -extension MutableSpan where Element: Copyable { + @_alwaysEmitIntoClient public mutating func update(fromContentsOf source: Span) -> Int { - return 0 + source.withUnsafeBufferPointer { self.update(fromContentsOf: $0) } } + @_alwaysEmitIntoClient public mutating func update(fromContentsOf source: borrowing MutableSpan) -> Int { - return 0 + source.withUnsafeBufferPointer { self.update(fromContentsOf: $0) } } + @_alwaysEmitIntoClient public mutating func update(fromContentsOf source: UnsafeBufferPointer) -> Int { - return 0 + 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.update(from: sourceAddress, count: source.count) + } + return source.count } + @_alwaysEmitIntoClient public mutating func update(fromContentsOf source: UnsafeMutableBufferPointer) -> Int { - return 0 + self.update(fromContentsOf: .init(source)) } + @_alwaysEmitIntoClient public mutating func update(fromContentsOf source: Slice>) -> Int { - return 0 + self.update(fromContentsOf: .init(rebasing: source)) } + @_alwaysEmitIntoClient public mutating func update(fromContentsOf source: Slice>) -> Int { - return 0 + self.update(fromContentsOf: UnsafeMutableBufferPointer(rebasing: source)) } } extension MutableSpan where Element: ~Copyable { public mutating func moveUpdate(fromContentsOf source: UnsafeMutableBufferPointer) -> Int { - return 0 + 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 } } +extension MutableSpan { + + public mutating func moveUpdate(fromContentsOf source: Slice>) -> Int { + self.moveUpdate(fromContentsOf: .init(rebasing: source)) + } +} + + +#if false +//TODO: overload the various `update` functions to use memcpy extension MutableSpan where Element: BitwiseCopyable { - //TODO: overload the various `update` functions to use memcpy public mutating func update(fromContentsOf source: some Collection) -> Int { return 0 @@ -523,6 +543,11 @@ extension MutableSpan where Element: BitwiseCopyable { return 0 } + @unsafe + public mutating func update(fromContentsOf source: RawSpan) -> Int { + return 0 + } + public mutating func update(fromContentsOf source: borrowing MutableSpan) -> Int { return 0 } @@ -535,6 +560,14 @@ extension MutableSpan where Element: BitwiseCopyable { return 0 } + public mutating func update(fromContentsOf source: UnsafeRawBufferPointer) -> Int { + return 0 + } + + public mutating func update(fromContentsOf source: UnsafeMutableRawBufferPointer) -> Int { + return 0 + } + public mutating func update(fromContentsOf source: Slice>) -> Int { return 0 } @@ -543,14 +576,15 @@ extension MutableSpan where Element: BitwiseCopyable { return 0 } - public mutating func moveUpdate(fromContentsOf source: UnsafeMutableBufferPointer) -> Int { + public mutating func update(fromContentsOf source: Slice) -> Int { return 0 } - public mutating func moveUpdate(fromContentsOf source: Slice>) -> Int { + public mutating func update(fromContentsOf source: Slice) -> Int { return 0 } } +#endif //MARK: copyMemory //FIXME: move these to a MutableRawSpan @@ -561,7 +595,7 @@ extension MutableSpan where Element: BitwiseCopyable { from source: borrowing MutableSpan ) -> Int { guard _isPOD(Element.self) else { fatalError() } - return copyMemory(from: .init(source)) + return copyMemory(from: .init(_unsafeMutableSpan: source)) } public func copyMemory(from source: Span) -> Int { From 515165834186503b6e61661794e54526bbd32d79 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 3 Oct 2024 13:45:03 -0700 Subject: [PATCH 26/40] add more Span initializers --- Sources/Future/Span.swift | 52 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index b4fdfe07..9a276b49 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -112,6 +112,26 @@ extension Span where Element: ~Copyable { } } +@_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 { @@ -240,6 +260,38 @@ extension Span where Element: BitwiseCopyable { precondition(remainder == 0, "Span must contain a whole number of elements") self.init(_unchecked: pointer, count: count) } + + @_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) + @_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) From b432175fae6ccf9321b91f1be40f944f142c9d4d Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 3 Oct 2024 13:45:23 -0700 Subject: [PATCH 27/40] add more MutableSpan initializers --- Sources/Future/MutableSpan.swift | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift index 92343b87..47fa80ab 100644 --- a/Sources/Future/MutableSpan.swift +++ b/Sources/Future/MutableSpan.swift @@ -75,6 +75,18 @@ extension MutableSpan where Element: ~Copyable { } } +@_disallowFeatureSuppression(NonescapableTypes) +extension MutableSpan { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + internal init( + _unsafeElements elements: Slice> + ) -> dependsOn(immortal) Self { + self.init(_unsafeElements: UnsafeMutableBufferPointer(rebasing: elements)) + } +} + @_disallowFeatureSuppression(NonescapableTypes) extension MutableSpan where Element: BitwiseCopyable { @@ -119,6 +131,22 @@ extension MutableSpan where Element: BitwiseCopyable { precondition(remainder == 0, "Span must contain a whole number of elements") self.init(_unchecked: pointer, count: count) } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + internal init( + _unsafeElements elements: Slice> + ) -> dependsOn(immortal) Self { + self.init(_unsafeElements: UnsafeMutableBufferPointer(rebasing: elements)) + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + internal init( + _unsafeBytes buffer: Slice + ) -> dependsOn(immortal) Self { + self.init(_unsafeBytes: UnsafeMutableRawBufferPointer(rebasing: buffer)) + } } @_disallowFeatureSuppression(NonescapableTypes) From 5b590b95cf2e998c4b706c0af8ada62ca60121e9 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 3 Oct 2024 13:46:07 -0700 Subject: [PATCH 28/40] implement bulk-update functions for MutableSpan --- Sources/Future/MutableSpan.swift | 197 ++++++++++++++++++++++++------- 1 file changed, 157 insertions(+), 40 deletions(-) diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift index 47fa80ab..118a8b40 100644 --- a/Sources/Future/MutableSpan.swift +++ b/Sources/Future/MutableSpan.swift @@ -439,7 +439,7 @@ extension MutableSpan where Element: BitwiseCopyable { } } -//MARK: UMBP-style update functions +//MARK: bulk-update functions extension MutableSpan { @_alwaysEmitIntoClient @@ -465,7 +465,9 @@ extension MutableSpan { } @_alwaysEmitIntoClient - public mutating func update(fromContentsOf source: some Collection) -> Int { + public mutating func update( + fromContentsOf source: some Collection + ) -> Int { let updated = source.withContiguousStorageIfAvailable { self.update(fromContentsOf: $0) } @@ -483,9 +485,7 @@ extension MutableSpan { var iterator = source.makeIterator() var index = 0 - let _count = _count while let value = iterator.next() { - print(value, index, _count) guard index < _count else { fatalError( "destination buffer view cannot contain every element from source." @@ -503,12 +503,16 @@ extension MutableSpan { } @_alwaysEmitIntoClient - public mutating func update(fromContentsOf source: borrowing MutableSpan) -> Int { + public mutating func update( + fromContentsOf source: borrowing MutableSpan + ) -> Int { source.withUnsafeBufferPointer { self.update(fromContentsOf: $0) } } @_alwaysEmitIntoClient - public mutating func update(fromContentsOf source: UnsafeBufferPointer) -> Int { + public mutating func update( + fromContentsOf source: UnsafeBufferPointer + ) -> Int { guard let sourceAddress = source.baseAddress, source.count > 0 else { return 0 } precondition( source.count <= self.count, @@ -521,25 +525,35 @@ extension MutableSpan { } @_alwaysEmitIntoClient - public mutating func update(fromContentsOf source: UnsafeMutableBufferPointer) -> Int { + public mutating func update( + fromContentsOf source: UnsafeMutableBufferPointer + ) -> Int { self.update(fromContentsOf: .init(source)) } @_alwaysEmitIntoClient - public mutating func update(fromContentsOf source: Slice>) -> Int { + public mutating func update( + fromContentsOf source: Slice> + ) -> Int { self.update(fromContentsOf: .init(rebasing: source)) } @_alwaysEmitIntoClient - public mutating func update(fromContentsOf source: Slice>) -> Int { - self.update(fromContentsOf: UnsafeMutableBufferPointer(rebasing: source)) + public mutating func update( + fromContentsOf source: Slice> + ) -> Int { + self.update(fromContentsOf: UnsafeBufferPointer(rebasing: source)) } } extension MutableSpan where Element: ~Copyable { - public mutating func moveUpdate(fromContentsOf source: UnsafeMutableBufferPointer) -> Int { - guard let sourceAddress = source.baseAddress, source.count > 0 else { return 0 } + public mutating func moveUpdate( + fromContentsOf source: UnsafeMutableBufferPointer + ) -> Int { + guard let sourceAddress = source.baseAddress, source.count > 0 else { + return 0 + } precondition( source.count <= self.count, "destination span cannot contain every element from source." @@ -553,66 +567,169 @@ extension MutableSpan where Element: ~Copyable { extension MutableSpan { - public mutating func moveUpdate(fromContentsOf source: Slice>) -> Int { + public mutating func moveUpdate( + fromContentsOf source: Slice> + ) -> Int { self.moveUpdate(fromContentsOf: .init(rebasing: source)) } } -#if false -//TODO: overload the various `update` functions to use memcpy extension MutableSpan where Element: BitwiseCopyable { - public mutating func update(fromContentsOf source: some Collection) -> Int { - return 0 + @_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) } - public mutating func update(fromContentsOf source: Span) -> Int { - return 0 + @_alwaysEmitIntoClient + public mutating func update( + from source: S + ) -> (unwritten: S.Iterator, index: Int) + where S.Element == Element, Element: BitwiseCopyable { + var iterator = source.makeIterator() + guard !self.isEmpty else { return (iterator, 0) } + var index = 0 + while index < _count { + guard let value = iterator.next() else { break } + self[unchecked: index] = value + index &+= 1 + } + return (iterator, index) + } + + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: some Collection + ) -> Int where Element: BitwiseCopyable { + let updated = source.withContiguousStorageIfAvailable { + self.update(fromContentsOf: $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 + } + + public mutating func update( + fromContentsOf source: Span + ) -> Int where Element: BitwiseCopyable { + source.withUnsafeBufferPointer { self.update(fromContentsOf: $0) } } @unsafe - public mutating func update(fromContentsOf source: RawSpan) -> Int { - return 0 + public mutating func update( + fromContentsOf source: RawSpan + ) -> Int where Element: BitwiseCopyable { + source.withUnsafeBytes { self.update(fromContentsOf: $0) } } - public mutating func update(fromContentsOf source: borrowing MutableSpan) -> Int { - return 0 + public mutating func update( + fromContentsOf source: borrowing MutableSpan + ) -> Int where Element: BitwiseCopyable { + source.withUnsafeBufferPointer { self.update(fromContentsOf: $0) } } - public mutating func update(fromContentsOf source: UnsafeBufferPointer) -> Int { - return 0 + @_alwaysEmitIntoClient + public mutating func update( + fromContentsOf source: UnsafeBufferPointer + ) -> Int where Element: BitwiseCopyable { + 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.copyMemory( + from: sourceAddress, byteCount: source.count*MemoryLayout.stride + ) + return source.count } - public mutating func update(fromContentsOf source: UnsafeMutableBufferPointer) -> Int { - return 0 + public mutating func update( + fromContentsOf source: UnsafeMutableBufferPointer + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: .init(source)) } - public mutating func update(fromContentsOf source: UnsafeRawBufferPointer) -> Int { - return 0 + public mutating func update( + fromContentsOf source: UnsafeRawBufferPointer + ) -> Int where Element: BitwiseCopyable { + guard let sourceAddress = source.baseAddress, source.count > 0 else { + return 0 + } + let stride = MemoryLayout.stride + let (count, remainder) = source.count.quotientAndRemainder(dividingBy: stride) + precondition( + remainder == 0, + "source buffer must be a multiple of the destination's element's stride." + ) + precondition( + count <= self.count, + "destination span cannot contain every element from source." + ) + _start.copyMemory(from: sourceAddress, byteCount: source.count) + return count } - public mutating func update(fromContentsOf source: UnsafeMutableRawBufferPointer) -> Int { - return 0 + public mutating func update( + fromContentsOf source: UnsafeMutableRawBufferPointer + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: UnsafeRawBufferPointer(source)) } - public mutating func update(fromContentsOf source: Slice>) -> Int { - return 0 + public mutating func update( + fromContentsOf source: Slice> + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: .init(rebasing: source)) } - public mutating func update(fromContentsOf source: Slice>) -> Int { - return 0 + public mutating func update( + fromContentsOf source: Slice> + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: UnsafeBufferPointer(rebasing: source)) } - public mutating func update(fromContentsOf source: Slice) -> Int { - return 0 + public mutating func update( + fromContentsOf source: Slice + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: UnsafeRawBufferPointer(rebasing: source)) } - public mutating func update(fromContentsOf source: Slice) -> Int { - return 0 + public mutating func update( + fromContentsOf source: Slice + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: UnsafeRawBufferPointer(rebasing: source)) } } -#endif //MARK: copyMemory //FIXME: move these to a MutableRawSpan From 7311e07ff9953e9d94ac396b9926d52bf3a09728 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 2 Oct 2024 17:23:36 -0700 Subject: [PATCH 29/40] tests for MutableSpan --- Tests/FutureTests/MutableSpanTests.swift | 488 +++++++++++++++++++++++ 1 file changed, 488 insertions(+) create mode 100644 Tests/FutureTests/MutableSpanTests.swift diff --git a/Tests/FutureTests/MutableSpanTests.swift b/Tests/FutureTests/MutableSpanTests.swift new file mode 100644 index 00000000..411dab9a --- /dev/null +++ b/Tests/FutureTests/MutableSpanTests.swift @@ -0,0 +1,488 @@ +//===--- 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) + var i = b.initialize(fromContentsOf: (0.. Date: Thu, 3 Oct 2024 14:32:35 -0700 Subject: [PATCH 30/40] annotations for mutablespan --- Sources/Future/MutableSpan.swift | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift index 118a8b40..8ac971f8 100644 --- a/Sources/Future/MutableSpan.swift +++ b/Sources/Future/MutableSpan.swift @@ -440,6 +440,7 @@ extension MutableSpan where Element: BitwiseCopyable { } //MARK: bulk-update functions +@_disallowFeatureSuppression(NonescapableTypes) extension MutableSpan { @_alwaysEmitIntoClient @@ -497,11 +498,13 @@ extension MutableSpan { return index } + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func update(fromContentsOf source: Span) -> Int { source.withUnsafeBufferPointer { self.update(fromContentsOf: $0) } } + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: borrowing MutableSpan @@ -546,6 +549,7 @@ extension MutableSpan { } } +@_disallowFeatureSuppression(NonescapableTypes) extension MutableSpan where Element: ~Copyable { public mutating func moveUpdate( @@ -565,6 +569,7 @@ extension MutableSpan where Element: ~Copyable { } } +@_disallowFeatureSuppression(NonescapableTypes) extension MutableSpan { public mutating func moveUpdate( @@ -575,6 +580,7 @@ extension MutableSpan { } +@_disallowFeatureSuppression(NonescapableTypes) extension MutableSpan where Element: BitwiseCopyable { @_alwaysEmitIntoClient @@ -638,12 +644,16 @@ extension MutableSpan where Element: BitwiseCopyable { return index } + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: Span ) -> Int where Element: BitwiseCopyable { source.withUnsafeBufferPointer { self.update(fromContentsOf: $0) } } + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient @unsafe public mutating func update( fromContentsOf source: RawSpan @@ -651,6 +661,8 @@ extension MutableSpan where Element: BitwiseCopyable { source.withUnsafeBytes { self.update(fromContentsOf: $0) } } + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: borrowing MutableSpan ) -> Int where Element: BitwiseCopyable { @@ -674,12 +686,14 @@ extension MutableSpan where Element: BitwiseCopyable { return source.count } + @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: UnsafeMutableBufferPointer ) -> Int where Element: BitwiseCopyable { self.update(fromContentsOf: .init(source)) } + @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: UnsafeRawBufferPointer ) -> Int where Element: BitwiseCopyable { @@ -700,30 +714,35 @@ extension MutableSpan where Element: BitwiseCopyable { return count } + @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: UnsafeMutableRawBufferPointer ) -> Int where Element: BitwiseCopyable { self.update(fromContentsOf: UnsafeRawBufferPointer(source)) } + @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: Slice> ) -> Int where Element: BitwiseCopyable { self.update(fromContentsOf: .init(rebasing: source)) } + @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: Slice> ) -> Int where Element: BitwiseCopyable { self.update(fromContentsOf: UnsafeBufferPointer(rebasing: source)) } + @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: Slice ) -> Int where Element: BitwiseCopyable { self.update(fromContentsOf: UnsafeRawBufferPointer(rebasing: source)) } + @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: Slice ) -> Int where Element: BitwiseCopyable { @@ -733,8 +752,10 @@ extension MutableSpan where Element: BitwiseCopyable { //MARK: copyMemory //FIXME: move these to a MutableRawSpan +@_disallowFeatureSuppression(NonescapableTypes) extension MutableSpan where Element: BitwiseCopyable { + @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public func copyMemory( from source: borrowing MutableSpan @@ -743,6 +764,8 @@ extension MutableSpan where Element: BitwiseCopyable { return copyMemory(from: .init(_unsafeMutableSpan: source)) } + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient public func copyMemory(from source: Span) -> Int { guard _isPOD(Element.self) else { fatalError() } precondition( From 28b93832bc7bb5791031f0b561ba895a0a994433 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 4 Oct 2024 08:21:11 -0700 Subject: [PATCH 31/40] clean up `update()` overloads for `MutableSpan` --- Sources/Future/MutableSpan.swift | 191 +++++++++++-------------------- Sources/Future/RawSpan.swift | 14 +++ 2 files changed, 80 insertions(+), 125 deletions(-) diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift index 8ac971f8..52e34609 100644 --- a/Sources/Future/MutableSpan.swift +++ b/Sources/Future/MutableSpan.swift @@ -159,6 +159,22 @@ extension Span where Element: ~Copyable { } } +@_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 { @@ -470,7 +486,7 @@ extension MutableSpan { fromContentsOf source: some Collection ) -> Int { let updated = source.withContiguousStorageIfAvailable { - self.update(fromContentsOf: $0) + self.update(fromContentsOf: Span(_unsafeElements: $0)) } if let updated { return 0.advanced(by: updated) @@ -487,11 +503,10 @@ extension MutableSpan { 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." - ) - } + precondition( + index < _count, + "destination buffer view cannot contain every element from source." + ) self[unchecked: index] = value index &+= 1 } @@ -501,7 +516,17 @@ extension MutableSpan { @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient public mutating func update(fromContentsOf source: Span) -> Int { - source.withUnsafeBufferPointer { self.update(fromContentsOf: $0) } + 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) @@ -509,43 +534,7 @@ extension MutableSpan { public mutating func update( fromContentsOf source: borrowing MutableSpan ) -> Int { - source.withUnsafeBufferPointer { self.update(fromContentsOf: $0) } - } - - @_alwaysEmitIntoClient - public mutating func update( - fromContentsOf source: UnsafeBufferPointer - ) -> Int { - 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.update(from: sourceAddress, count: source.count) - } - return source.count - } - - @_alwaysEmitIntoClient - public mutating func update( - fromContentsOf source: UnsafeMutableBufferPointer - ) -> Int { - self.update(fromContentsOf: .init(source)) - } - - @_alwaysEmitIntoClient - public mutating func update( - fromContentsOf source: Slice> - ) -> Int { - self.update(fromContentsOf: .init(rebasing: source)) - } - - @_alwaysEmitIntoClient - public mutating func update( - fromContentsOf source: Slice> - ) -> Int { - self.update(fromContentsOf: UnsafeBufferPointer(rebasing: source)) + source.withSpan { self.update(fromContentsOf: $0) } } } @@ -616,7 +605,7 @@ extension MutableSpan where Element: BitwiseCopyable { fromContentsOf source: some Collection ) -> Int where Element: BitwiseCopyable { let updated = source.withContiguousStorageIfAvailable { - self.update(fromContentsOf: $0) + self.update(fromContentsOf: Span(_unsafeElements: $0)) } if let updated { return 0.advanced(by: updated) @@ -649,7 +638,23 @@ extension MutableSpan where Element: BitwiseCopyable { public mutating func update( fromContentsOf source: Span ) -> Int where Element: BitwiseCopyable { - source.withUnsafeBufferPointer { self.update(fromContentsOf: $0) } + 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) @@ -658,95 +663,39 @@ extension MutableSpan where Element: BitwiseCopyable { public mutating func update( fromContentsOf source: RawSpan ) -> Int where Element: BitwiseCopyable { - source.withUnsafeBytes { self.update(fromContentsOf: $0) } + self.update(fromContentsOf: source.unsafeView(as: Element.self)) } - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public mutating func update( - fromContentsOf source: borrowing MutableSpan - ) -> Int where Element: BitwiseCopyable { - source.withUnsafeBufferPointer { self.update(fromContentsOf: $0) } - } - - @_alwaysEmitIntoClient - public mutating func update( - fromContentsOf source: UnsafeBufferPointer - ) -> Int where Element: BitwiseCopyable { - 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.copyMemory( - from: sourceAddress, byteCount: source.count*MemoryLayout.stride - ) - return source.count - } - - @_alwaysEmitIntoClient - public mutating func update( - fromContentsOf source: UnsafeMutableBufferPointer - ) -> Int where Element: BitwiseCopyable { - self.update(fromContentsOf: .init(source)) - } + // 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 { - guard let sourceAddress = source.baseAddress, source.count > 0 else { - return 0 - } - let stride = MemoryLayout.stride - let (count, remainder) = source.count.quotientAndRemainder(dividingBy: stride) - precondition( - remainder == 0, - "source buffer must be a multiple of the destination's element's stride." - ) - precondition( - count <= self.count, - "destination span cannot contain every element from source." - ) - _start.copyMemory(from: sourceAddress, byteCount: source.count) - return count + self.update(fromContentsOf: RawSpan(_unsafeBytes: source)) } @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: UnsafeMutableRawBufferPointer ) -> Int where Element: BitwiseCopyable { - self.update(fromContentsOf: UnsafeRawBufferPointer(source)) - } - - @_alwaysEmitIntoClient - public mutating func update( - fromContentsOf source: Slice> - ) -> Int where Element: BitwiseCopyable { - self.update(fromContentsOf: .init(rebasing: source)) - } - - @_alwaysEmitIntoClient - public mutating func update( - fromContentsOf source: Slice> - ) -> Int where Element: BitwiseCopyable { - self.update(fromContentsOf: UnsafeBufferPointer(rebasing: source)) + self.update(fromContentsOf: RawSpan(_unsafeBytes: source)) } @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: Slice ) -> Int where Element: BitwiseCopyable { - self.update(fromContentsOf: UnsafeRawBufferPointer(rebasing: source)) + self.update(fromContentsOf: RawSpan(_unsafeBytes: source)) } @_alwaysEmitIntoClient public mutating func update( fromContentsOf source: Slice ) -> Int where Element: BitwiseCopyable { - self.update(fromContentsOf: UnsafeRawBufferPointer(rebasing: source)) + self.update(fromContentsOf: RawSpan(_unsafeBytes: source)) } } @@ -757,25 +706,17 @@ extension MutableSpan where Element: BitwiseCopyable { @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public func copyMemory( + public mutating func copyMemory( from source: borrowing MutableSpan - ) -> Int { - guard _isPOD(Element.self) else { fatalError() } - return copyMemory(from: .init(_unsafeMutableSpan: source)) + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: source.storage) } @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - public func copyMemory(from source: Span) -> Int { - guard _isPOD(Element.self) else { fatalError() } - precondition( - source.count <= count, - "MutableSpan.copyMemory source has too many elements" - ) - UnsafeMutableRawPointer(_start).copyMemory( - from: source._start, - byteCount: source.count&*MemoryLayout.stride - ) - return 0.advanced(by: source.count) + public mutating func copyMemory( + from source: Span + ) -> Int where Element: BitwiseCopyable { + self.update(fromContentsOf: source) } } diff --git a/Sources/Future/RawSpan.swift b/Sources/Future/RawSpan.swift index 431ccec5..e96f4567 100644 --- a/Sources/Future/RawSpan.swift +++ b/Sources/Future/RawSpan.swift @@ -54,6 +54,13 @@ extension RawSpan { ) } + @_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,6 +77,13 @@ extension RawSpan { 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. /// /// The memory over `count` bytes starting at From ffebc71d54165fcc7c77aa85af6c7310d01d0673 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sat, 28 Sep 2024 06:07:01 -0700 Subject: [PATCH 32/40] OutputSpan modernization --- Sources/Future/OutputSpan.swift | 444 +++++++++++++----- .../Future/StdlibOutputSpanExtensions.swift | 15 +- Tests/FutureTests/OutputSpanTests.swift | 58 ++- 3 files changed, 385 insertions(+), 132 deletions(-) diff --git a/Sources/Future/OutputSpan.swift b/Sources/Future/OutputSpan.swift index 83a8e586..1009cc77 100644 --- a/Sources/Future/OutputSpan.swift +++ b/Sources/Future/OutputSpan.swift @@ -10,54 +10,214 @@ // //===----------------------------------------------------------------------===// -public struct OutputSpan: ~Copyable, ~Escapable { - @usableFromInline let _start: UnsafeMutablePointer +// 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 - public private(set) var initialized: Int = 0 + + @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 _initialized > 0 { +#if false + _start.withMemoryRebound(to: Element.self, capacity: _initialized) { + $0.deinitialize(count: _initialized) + } +#else fatalError() +#endif } } - public init( - initializing pointer: UnsafeMutablePointer, + @_disallowFeatureSuppression(NonescapableTypes) + @usableFromInline @inline(__always) + init( + _unchecked start: UnsafeMutableRawPointer?, capacity: Int, - initialized: Int = 0, - owner: borrowing Owner - ) -> dependsOn(owner) Self { - self._start = pointer + initialized: Int + ) -> dependsOn(immortal) Self { + _pointer = start self.capacity = capacity - self.initialized = initialized + _initialized = initialized } } -extension OutputSpan where Element: ~Copyable /*& ~Escapable*/ { - public mutating func appendElement(_ value: consuming Element) { - precondition(initialized < capacity, "Output buffer overflow") - _start.advanced(by: initialized).initialize(to: value) - initialized &+= 1 +@_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 } - public mutating func deinitializeLastElement() -> Element? { - guard initialized > 0 else { return nil } - initialized &-= 1 - return _start.advanced(by: initialized).move() - } -} - -extension OutputSpan where Element: ~Copyable { - public mutating func deinitialize() { - let b = UnsafeMutableBufferPointer(start: _start, count: initialized) - b.deinitialize() - initialized = 0 + @_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 { @@ -66,85 +226,138 @@ extension OutputSpan { return iterator } + @_alwaysEmitIntoClient public mutating func append( from elements: inout some IteratorProtocol ) { - while initialized < capacity { + while _initialized < capacity { guard let element = elements.next() else { break } - _start.advanced(by: initialized).initialize(to: element) - initialized &+= 1 + 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 count = source.withContiguousStorageIfAvailable { - guard let sourceAddress = $0.baseAddress, !$0.isEmpty else { - return 0 - } - let available = capacity &- initialized - precondition( - $0.count <= available, - "buffer cannot contain every element from source." - ) - let tail = _start.advanced(by: initialized) - tail.initialize(from: sourceAddress, count: $0.count) - return $0.count + 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 let count { - initialized &+= count + if void != nil { return } - let available = capacity &- initialized - let tail = _start.advanced(by: initialized) - let suffix = UnsafeMutableBufferPointer(start: tail, count: available) - var (iterator, copied) = source._copyContents(initializing: suffix) + 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, - "buffer cannot contain every element from source." + "destination span cannot contain every element from source." ) - assert(initialized + copied <= capacity) - initialized &+= copied + 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 - public mutating func append(fromContentsOf source: Span) { - let available = capacity &- initialized + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func append( + fromContentsOf source: Span + ) { + guard !source.isEmpty else { return } precondition( source.count <= available, - "buffer cannot contain every element from source." + "destination span cannot contain every element from source." ) - source.withUnsafeBufferPointer { - let tail = _start.advanced(by: initialized) - tail.initialize(from: $0.baseAddress!, count: $0.count) + 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 + _initialized += source.count + } + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient + public mutating func append(fromContentsOf source: borrowing MutableSpan) { + source.withUnsafeBufferPointer { append(fromContentsOf: $0) } } } -extension OutputSpan where Element: ~Copyable /*& ~Escapable*/ { +@_disallowFeatureSuppression(NonescapableTypes) +extension OutputSpan where Element: ~Copyable { + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient public mutating func moveAppend( - fromContentsOf source: UnsafeMutableBufferPointer + fromContentsOf source: consuming Self ) { - guard let sourceAddress = source.baseAddress, !source.isEmpty else { - return - } - let available = capacity &- initialized + guard !source.isEmpty else { return } precondition( source.count <= available, "buffer cannot contain every element from source." ) - let tail = _start.advanced(by: initialized) - tail.moveInitialize(from: sourceAddress, count: source.count) - initialized &+= source.count + 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> ) { @@ -152,64 +365,61 @@ extension OutputSpan { } } -//extension OutputSpan where Element: ~Copyable /*& ~Escapable*/ { -// public mutating func initializeSuffixOutOfOrder( -// _ count: Int, -// body: (inout RandomAccessOutputSpan) throws(E) -> R -// ) throws(E) -> R { -// precondition(initialized + count < capacity) -// var out = RandomAccessOutputSpan( -// initializing: _start.advanced(by: initialized), capacity: count, owner: self -// ) -// let result = try body(&out) -// let buffer = out.relinquishBorrowedMemory() -// assert( -// buffer.baseAddress == _start.advanced(by: initialized) && -// initialized + buffer.count < capacity -// ) -// initialized &+= buffer.count -// return result -// } -//} +extension OutputSpan where Element: BitwiseCopyable { -extension OutputSpan { +} + +extension OutputSpan where Element: ~Copyable { + + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient public var initializedPrefix: Span { - get { Span(_unsafeStart: _start, count: initialized) } + get { Span(_unchecked: _pointer, count: _initialized) } } + @_disallowFeatureSuppression(NonescapableTypes) + @_alwaysEmitIntoClient public func withSpan( _ body: (Span) throws(E) -> R ) throws(E) -> R { try body(initializedPrefix) } -} -// public var mutatingInitializedPrefix: /*inout*/ MutableBufferView { -// mutating /* _read */ get /* mutating(self) */ { -// /* yield */ MutableBufferView( -// unsafeMutablePointer: _start, -// count: initialized, -// dependsOn: /* self */ _start -// ) -// } -// } - -// public mutating func withMutableBufferView( -// _ body: (inout MutableBufferView) throws -> R -// ) rethrows -> R { -// var view = MutableBufferView( -// unsafeMutablePointer: _start, -// count: initialized, -// dependsOn: /* self */ _start -// ) -// return try body(&view) -// } - -extension OutputSpan { - - public consuming func relinquishBorrowedMemory() -> UnsafeMutableBufferPointer { - let (start, initialized) = (self._start, self.initialized) - discard self - return .init(start: start, count: initialized) + @_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/StdlibOutputSpanExtensions.swift b/Sources/Future/StdlibOutputSpanExtensions.swift index 83e424b3..cc392a3c 100644 --- a/Sources/Future/StdlibOutputSpanExtensions.swift +++ b/Sources/Future/StdlibOutputSpanExtensions.swift @@ -20,9 +20,8 @@ extension Array { unsafeUninitializedCapacity: capacity, initializingWith: { (buffer, count) in var output = OutputSpan( - initializing: buffer.baseAddress.unsafelyUnwrapped, - capacity: buffer.count, - owner: buffer + _initializing: buffer.baseAddress.unsafelyUnwrapped, + capacity: buffer.count ) try initializer(&output) let initialized = output.relinquishBorrowedMemory() @@ -47,9 +46,8 @@ extension String { unsafeUninitializedCapacity: capacity, initializingUTF8With: { buffer in var output = OutputSpan( - initializing: buffer.baseAddress.unsafelyUnwrapped, - capacity: capacity, - owner: buffer + _initializing: buffer.baseAddress.unsafelyUnwrapped, + capacity: capacity ) try initializer(&output) let initialized = output.relinquishBorrowedMemory() @@ -73,9 +71,8 @@ extension Data { try rawBuffer.withMemoryRebound(to: UInt8.self) { buffer in buffer.deinitialize() var output = OutputSpan( - initializing: buffer.baseAddress.unsafelyUnwrapped, - capacity: capacity, - owner: buffer + _initializing: buffer.baseAddress.unsafelyUnwrapped, + capacity: capacity ) try initializer(&output) let initialized = output.relinquishBorrowedMemory() diff --git a/Tests/FutureTests/OutputSpanTests.swift b/Tests/FutureTests/OutputSpanTests.swift index b475c206..7b5ef543 100644 --- a/Tests/FutureTests/OutputSpanTests.swift +++ b/Tests/FutureTests/OutputSpanTests.swift @@ -31,7 +31,7 @@ struct Allocation: ~Copyable { ) rethrows { if count != nil { fatalError() } var outputBuffer = OutputSpan( - initializing: allocation, capacity: capacity, owner: self + _initializing: allocation, capacity: capacity ) do { try body(&outputBuffer) @@ -85,7 +85,7 @@ final class OutputBufferTests: XCTestCase { let allocation = UnsafeMutablePointer.allocate(capacity: c) defer { allocation.deallocate() } - let ob = OutputSpan(initializing: allocation, capacity: c, owner: allocation) + let ob = OutputSpan(_initializing: allocation, capacity: c) let initialized = ob.relinquishBorrowedMemory() XCTAssertNotNil(initialized.baseAddress) XCTAssertEqual(initialized.count, 0) @@ -110,6 +110,24 @@ final class OutputBufferTests: XCTestCase { XCTAssert(span._elementsEqual(0..(_unsafeElements: UnsafeBufferPointer(start: nil, count: 0)) - $0.append(fromContentsOf: storage) + array.withUnsafeBufferPointer { + // let storage = Span(_unsafeElements: $0) + let storage = Span(_unsafeElements: .init(start: nil, count: 0)) + $0.append(fromContentsOf: storage) + } #else $0.append(fromContentsOf: array) #endif @@ -203,7 +223,7 @@ final class OutputBufferTests: XCTestCase { try a.initialize { $0.appendElement(0) $0.appendElement(1) - XCTAssertTrue($0.initialized > 0) + XCTAssertTrue($0.count > 0) throw MyTestError.error } } @@ -211,4 +231,30 @@ final class OutputBufferTests: XCTestCase { 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() + } } From c8fc80381ec671b45e5aa1bba66e61d09249c90f Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 4 Oct 2024 15:20:11 -0700 Subject: [PATCH 33/40] remove workarounds --- Sources/Future/Span.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index 9a276b49..f6cfc139 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -485,7 +485,7 @@ extension Span where Element: ~Copyable { @_alwaysEmitIntoClient public subscript(unchecked position: Int) -> Element { _read { - let element = UnsafeRawPointer(_start).advanced(by: position&*MemoryLayout.stride) + 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 @@ -522,7 +522,7 @@ extension Span where Element: BitwiseCopyable { @_alwaysEmitIntoClient public subscript(unchecked position: Int) -> Element { get { - let address = UnsafeRawPointer(_start).advanced(by: position&*MemoryLayout.stride) + let address = _start.advanced(by: position&*MemoryLayout.stride) return address.loadUnaligned(as: Element.self) } } From e9d7ea806a154e23aa51b8650c3f43e2ac8930b7 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 4 Oct 2024 15:21:26 -0700 Subject: [PATCH 34/40] require `Span` to be aligned --- Sources/Future/Span.swift | 5 +++++ Tests/FutureTests/SpanTests.swift | 21 +++++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index f6cfc139..cd63c5af 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -209,6 +209,11 @@ extension Span where Element: BitwiseCopyable { 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) let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride) precondition(remainder == 0, "Span must contain a whole number of elements") diff --git a/Tests/FutureTests/SpanTests.swift b/Tests/FutureTests/SpanTests.swift index df3a1148..b951eb3e 100644 --- a/Tests/FutureTests/SpanTests.swift +++ b/Tests/FutureTests/SpanTests.swift @@ -387,10 +387,12 @@ final class SpanTests: XCTestCase { 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) ) @@ -410,8 +412,6 @@ final class SpanTests: XCTestCase { XCTAssertNil(bounds) bounds = span.indices(of: nilSpan) XCTAssertNil(bounds) - bounds = span.indices(of: unalignedSpan) - XCTAssertNil(bounds) bounds = nilSpan.indices(of: nilSpan) XCTAssertEqual(bounds, 0..<0) } @@ -437,4 +437,21 @@ final class SpanTests: XCTestCase { 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) + } } From 57b5388c858f816f99a6c10ceb5a7736aabd1c5d Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 4 Oct 2024 15:22:40 -0700 Subject: [PATCH 35/40] remove duplicated initializers - these have become duplicates in a world where Span must always be aligned --- Sources/Future/Span.swift | 76 +-------------------------------------- 1 file changed, 1 insertion(+), 75 deletions(-) diff --git a/Sources/Future/Span.swift b/Sources/Future/Span.swift index cd63c5af..8be06ca1 100644 --- a/Sources/Future/Span.swift +++ b/Sources/Future/Span.swift @@ -135,61 +135,6 @@ extension Span { @_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`. - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public init( - _unsafeElements buffer: UnsafeBufferPointer - ) -> dependsOn(immortal) Self { - self.init(_unchecked: buffer) - } - - /// 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`. - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public init( - _unsafeElements buffer: UnsafeMutableBufferPointer - ) -> dependsOn(immortal) Self { - self.init(_unsafeElements: UnsafeBufferPointer(buffer)) - } - - /// 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`. - @_disallowFeatureSuppression(NonescapableTypes) - @_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) - } - /// Unsafely create a `Span` over initialized memory. /// /// The memory in `unsafeBytes` must be owned by the instance `owner` @@ -260,26 +205,7 @@ extension Span where Element: BitwiseCopyable { 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, "Span must contain a whole number of elements") - self.init(_unchecked: pointer, count: count) - } - - @_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)) + self.init(_unsafeBytes: .init(start: pointer, count: byteCount)) } @_disallowFeatureSuppression(NonescapableTypes) From f5f02e2f6a55c5382ee9171c5bc3bc5aa4c98850 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 4 Oct 2024 15:23:04 -0700 Subject: [PATCH 36/40] rename some tests --- Tests/FutureTests/SpanTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/FutureTests/SpanTests.swift b/Tests/FutureTests/SpanTests.swift index b951eb3e..eede50cf 100644 --- a/Tests/FutureTests/SpanTests.swift +++ b/Tests/FutureTests/SpanTests.swift @@ -206,7 +206,7 @@ final class SpanTests: XCTestCase { } } - func testOffsetSubscript() { + func testElementSubscript() { let capacity = 4 let a = (0.. Date: Fri, 4 Oct 2024 15:41:26 -0700 Subject: [PATCH 37/40] `MutableSpan` must be aligned --- Sources/Future/MutableSpan.swift | 40 +++++++------------------------- 1 file changed, 8 insertions(+), 32 deletions(-) diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift index 52e34609..10bf47d6 100644 --- a/Sources/Future/MutableSpan.swift +++ b/Sources/Future/MutableSpan.swift @@ -80,7 +80,7 @@ extension MutableSpan { @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - internal init( + public init( _unsafeElements elements: Slice> ) -> dependsOn(immortal) Self { self.init(_unsafeElements: UnsafeMutableBufferPointer(rebasing: elements)) @@ -90,29 +90,16 @@ extension MutableSpan { @_disallowFeatureSuppression(NonescapableTypes) extension MutableSpan where Element: BitwiseCopyable { - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - public init( - _unsafeElements buffer: UnsafeMutableBufferPointer - ) -> dependsOn(immortal) Self { - 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(_unchecked: start, count: count) - } - @_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") @@ -126,23 +113,12 @@ extension MutableSpan where Element: BitwiseCopyable { 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, "Span must contain a whole number of elements") - self.init(_unchecked: pointer, count: count) + self.init(_unsafeBytes: .init(start: pointer, count: byteCount)) } @_disallowFeatureSuppression(NonescapableTypes) @_alwaysEmitIntoClient - internal init( - _unsafeElements elements: Slice> - ) -> dependsOn(immortal) Self { - self.init(_unsafeElements: UnsafeMutableBufferPointer(rebasing: elements)) - } - - @_disallowFeatureSuppression(NonescapableTypes) - @_alwaysEmitIntoClient - internal init( + public init( _unsafeBytes buffer: Slice ) -> dependsOn(immortal) Self { self.init(_unsafeBytes: UnsafeMutableRawBufferPointer(rebasing: buffer)) From b82dd4eb9b3d80f945fdc2a5ada2e9d8f1703bb2 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sat, 5 Oct 2024 00:10:37 -0700 Subject: [PATCH 38/40] refine update-from-sequence functions - a function that mutates an iterator is much more modular --- Sources/Future/MutableSpan.swift | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift index 10bf47d6..43d35ccb 100644 --- a/Sources/Future/MutableSpan.swift +++ b/Sources/Future/MutableSpan.swift @@ -447,14 +447,21 @@ extension MutableSpan { from source: S ) -> (unwritten: S.Iterator, index: Int) where S.Element == Element { var iterator = source.makeIterator() - guard !self.isEmpty else { return (iterator, 0) } + 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 value = iterator.next() else { break } - self[unchecked: index] = value + guard let element = elements.next() else { break } + self[unchecked: index] = element index &+= 1 } - return (iterator, index) + return index } @_alwaysEmitIntoClient @@ -566,14 +573,21 @@ extension MutableSpan where Element: BitwiseCopyable { ) -> (unwritten: S.Iterator, index: Int) where S.Element == Element, Element: BitwiseCopyable { var iterator = source.makeIterator() - guard !self.isEmpty else { return (iterator, 0) } + 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 value = iterator.next() else { break } - self[unchecked: index] = value + guard let element = elements.next() else { break } + self[unchecked: index] = element index &+= 1 } - return (iterator, index) + return index } @_alwaysEmitIntoClient From dc63d5e048d6cae40999ae8badb08d12f86157ec Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Sat, 5 Oct 2024 00:51:41 -0700 Subject: [PATCH 39/40] add a safer `moveUpdate` --- Sources/Future/MutableSpan.swift | 23 +++++++++++++++++++++++ Tests/FutureTests/MutableSpanTests.swift | 11 +++++++---- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/Sources/Future/MutableSpan.swift b/Sources/Future/MutableSpan.swift index 43d35ccb..76a3a41e 100644 --- a/Sources/Future/MutableSpan.swift +++ b/Sources/Future/MutableSpan.swift @@ -524,9 +524,28 @@ extension MutableSpan { @_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 } @@ -538,6 +557,10 @@ extension MutableSpan where Element: ~Copyable { $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 } } diff --git a/Tests/FutureTests/MutableSpanTests.swift b/Tests/FutureTests/MutableSpanTests.swift index 411dab9a..8fa98487 100644 --- a/Tests/FutureTests/MutableSpanTests.swift +++ b/Tests/FutureTests/MutableSpanTests.swift @@ -459,19 +459,22 @@ final class MutableSpanTests: XCTestCase { XCTAssertEqual(a.allSatisfy({ $0.id == .max }), true) var b = UnsafeMutableBufferPointer.allocate(capacity: capacity) - var i = b.initialize(fromContentsOf: (0.. Date: Sun, 6 Oct 2024 11:16:43 -0700 Subject: [PATCH 40/40] post-rebase compatibility fixes --- Sources/DequeModule/Deque+Collection.swift | 2 ++ Sources/DequeModule/Deque+Equatable.swift | 2 ++ Sources/DequeModule/Deque.swift | 2 ++ Sources/DequeModule/RigidDeque.swift | 6 +++--- Sources/Future/Containers/NewArray.swift | 4 ++-- Sources/Future/Containers/RigidArray.swift | 10 ++++++---- .../OrderedSet/OrderedSet Diffing Tests.swift | 4 ++-- .../AssertionContexts/TestContext.swift | 2 +- 8 files changed, 20 insertions(+), 12 deletions(-) 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/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/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() {} }