diff --git a/Sources/ContainersPreview/Protocols/Container/MutableContainer+UpdateSubrange.swift b/Sources/ContainersPreview/Protocols/Container/MutableContainer+UpdateSubrange.swift new file mode 100644 index 00000000..be766f03 --- /dev/null +++ b/Sources/ContainersPreview/Protocols/Container/MutableContainer+UpdateSubrange.swift @@ -0,0 +1,167 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import SpanPreview +import InternalCollectionsUtilities +#endif + +#if compiler(>=6.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.4, *) +extension MutableContainer +where Self: ~Copyable & ~Escapable, Element: ~Copyable +{ + @_alwaysEmitIntoClient + public mutating func updateSubrange( + _ subrange: Range, + updatingWith updater: (inout MutableSpan) throws(E) -> Void + ) throws(E) { + var i = subrange.lowerBound + while true { + var span = self.nextMutableSpan(after: &i, limitedBy: subrange.upperBound) + guard !span.isEmpty else { break } + try updater(&span) + } + } + + @_alwaysEmitIntoClient + public mutating func updateElements< + Failure: Error, + Source: Producer & ~Copyable & ~Escapable + >( + after index: inout Index, + from source: inout Source + ) throws(Failure) where Source.Element: ~Copyable { + // We cannot do in-place bulk updates, because we wouldn't be able to + // gracefully recover from a producer failure. + // See the `Failure == Never` refinement below for the faster (& far more + // convenient) in-place variant. + + // `offset` is the offset of the next item to update in the mutable span + // that starts at `index`. The loop invariant is that this remains zero; + // however, when `source` terminates before we reach the end of the + // container, then this can be left with some positive value that we must + // use to advance `index` before returning -- so that we properly indicate + // how far we updated elements in `self`. + var offset = 0 + defer { + if offset > 0 { + index = self.index(index, offsetBy: offset) + } + } + while offset == 0 { + var next = index + var dst = self.nextMutableSpan(after: &next) + guard !dst.isEmpty else { break } + try withTemporaryAllocation( + of: Element.self, + capacity: Swift.min(_producerBufferSize, dst.count) + ) { buf throws(Failure) in + while offset < dst.count { + defer { + if !buf.isEmpty { + // We need to updating all items that were successfully generated, + // whether or not we've run into failure/eof. + let j = offset &+ buf.count + dst._updateSubrange(Range(uncheckedBounds: (offset, j)), moving: &buf) + offset = j + } + } + guard try source.fill(&buf) else { return } + } + index = next + offset = 0 + } + } + } + + @_alwaysEmitIntoClient + public mutating func updateElements< + Source: CountedProducer & ~Copyable & ~Escapable + >( + after index: inout Index, + from source: inout Source + ) where Source.Element: ~Copyable { + // With a CountedProducer that doesn't throw, we can implement + // bulk updating in place. + var remaining = source.count + while remaining > 0 { + var target = self.nextMutableSpan(after: &index, maxCount: remaining) + guard !target.isEmpty else { break } + remaining -= target.count + target.withUnsafeMutableBufferPointer { buf in + buf.deinitialize() + var dst = OutputSpan(buffer: buf, initializedCount: 0) + source.fill(&dst) + let c = dst.finalize(for: buf) + precondition(c == buf.count, "Invalid CountedProducer") + } + } + } + + @_alwaysEmitIntoClient + public mutating func updateSubrange< + Source: CountedProducer & ~Copyable & ~Escapable + >( + _ subrange: Range, + from source: consuming Source + ) where Source.Element: ~Copyable { + var remaining = source.count + var i = subrange.lowerBound + while remaining > 0 { + var target = self.nextMutableSpan( + after: &i, + maxCount: remaining, + limitedBy: subrange.upperBound) + guard !target.isEmpty else { break } + remaining -= target.count + target.withUnsafeMutableBufferPointer { buf in + buf.deinitialize() + var dst = OutputSpan(buffer: buf, initializedCount: 0) + source.fill(&dst) + let c = dst.finalize(for: buf) + precondition(c == buf.count, "Invalid CountedProducer") + } + precondition( + remaining == 0 && i == subrange.upperBound, + "updateSubrange source length does not match target range") + } + } + + @_alwaysEmitIntoClient + public mutating func updateSubrange( + _ subrange: Range, + from source: consuming some Drain & ~Copyable & ~Escapable + ) { + var i = subrange.lowerBound + while true { + var dst = self.nextMutableSpan(after: &i, limitedBy: subrange.upperBound) + var j = 0 + guard !dst.isEmpty else { break } + repeat { + var src = source.drainNext(maxCount: dst.count &- j) + precondition( + !src.isEmpty, + "updateSubrange source length does not match target range") + let k = j &+ src.count + dst._updateSubrange(Range(uncheckedBounds: (j, k)), moving: &src) + j = k + } while !dst.isEmpty + } + precondition(i == subrange.upperBound, "Invalid MutableContainer") + source._expectEnd("updateSubrange source length does not match target range") + } +} + +#endif diff --git a/Sources/ContainersPreview/Protocols/Producer/Producer.swift b/Sources/ContainersPreview/Protocols/Producer/Producer.swift index 453cda21..bf2080ed 100644 --- a/Sources/ContainersPreview/Protocols/Producer/Producer.swift +++ b/Sources/ContainersPreview/Protocols/Producer/Producer.swift @@ -328,6 +328,18 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @_alwaysEmitIntoClient + @discardableResult + public mutating func fill( + _ target: inout OutputSpan + ) throws(Failure) -> Bool { + var result = false + while !target.isFull, try self.generate(into: &target) { + result = true + } + return result + } + /// Triggers a runtime trap if the producer is not at its end, consuming it in /// the process. This is implemented by checking if it is possible to /// skip one item. diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift index 25cf8507..cb5ad755 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift @@ -185,6 +185,9 @@ extension RigidDeque where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: ~Copyable { + // FIXME: This works around a Swift 6.5 name resolution issue; see usages below. + @usableFromInline internal typealias _Element = Element + @available(SwiftStdlib 5.0, *) @frozen public struct SubrangeConsumer: ~Copyable, ~Escapable { @@ -195,13 +198,18 @@ extension RigidDeque where Element: ~Copyable { @usableFromInline internal var _offsetRange: Range - + + // FIXME: This ought to be using `Element` directly, but when the package is + // built using the Xcode project, some Swift 6.5 nightlies appear to + // resolve it to a less available `Element` definition, causing a build + // failure. The availability indicates it may be `Iterable.Element` via + // the `Container` conformance; this is super confusing though. @usableFromInline - internal var _buffer1: UnsafeMutableBufferPointer + internal var _buffer1: UnsafeMutableBufferPointer<_Element> @usableFromInline - internal var _buffer2: UnsafeMutableBufferPointer - + internal var _buffer2: UnsafeMutableBufferPointer<_Element> + @_alwaysEmitIntoClient @inline(__always) @_lifetime(&_base) diff --git a/Sources/InternalCollectionsUtilities/MutableSpan+Extras.swift b/Sources/InternalCollectionsUtilities/MutableSpan+Extras.swift new file mode 100644 index 00000000..73ab536e --- /dev/null +++ b/Sources/InternalCollectionsUtilities/MutableSpan+Extras.swift @@ -0,0 +1,102 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) + +extension MutableSpan where Element: ~Copyable { + // FIXME: Replace with stdlib implementation when it becomes available + // (See also InputSpan-taking variant in SpanPreview) + @_alwaysEmitIntoClient + package mutating func _updateSubrange( + _ subrange: Range, + moving source: inout OutputSpan + ) { + precondition( + subrange.lowerBound >= 0 && subrange.upperBound <= count, + "Index range out of bounds") + precondition( + subrange.count == source.count, + "updateSubrange source count doesn't match target") + self.withUnsafeMutableBufferPointer { dst in + source.withUnsafeMutableBufferPointer { src, c in + // FIXME: Make sure this calls memcpy when Element is bitwise movable. + let i = dst + .extracting(unchecked: subrange) + .moveUpdate(fromContentsOf: src.extracting(first: c)) + precondition(i == subrange.count) + c = 0 + } + } + } + + // FIXME: Replace with stdlib implementation when it becomes available + // (See also InputSpan-taking variant in SpanPreview) + @_alwaysEmitIntoClient + package mutating func _updateAll( + moving source: inout OutputSpan + ) { + let count = self.count + precondition( + source.count == count, + "updateSubrange source count doesn't match target") + self.withUnsafeMutableBufferPointer { dst in + source.withUnsafeMutableBufferPointer { src, c in + // FIXME: Make sure this calls memcpy when Element is bitwise movable. + let i = dst.moveUpdate(fromContentsOf: src.extracting(first: c)) + assert(i == count) + } + } + } +} + +extension MutableSpan /* where Element: Copyable */ { + // FIXME: Replace with stdlib implementation when it becomes available + @_alwaysEmitIntoClient + package mutating func _updateSubrange( + _ subrange: Range, + copying source: borrowing Span + ) { + precondition( + subrange.lowerBound >= 0 && subrange.upperBound <= count, + "Index range out of bounds") + precondition( + subrange.count == source.count, + "updateSubrange source count doesn't match target") + self.withUnsafeMutableBufferPointer { dst in + source.withUnsafeBufferPointer { src in + // FIXME: Make sure this calls memcpy when Element is BitwiseCopyable. + let i = dst.extracting(unchecked: subrange).update(fromContentsOf: src) + precondition(i == subrange.count) + } + } + } + + // FIXME: Replace with stdlib implementation when it becomes available + @_alwaysEmitIntoClient + package mutating func _updateAll( + copying source: borrowing Span + ) { + precondition( + source.count == self.count, + "updateSubrange source count doesn't match target") + let i = self.withUnsafeMutableBufferPointer { dst in + source.withUnsafeBufferPointer { src in + // FIXME: Make sure this calls memcpy when Element is BitwiseCopyable. + dst.update(fromContentsOf: src) + } + } + precondition(i == self.count) + } +} + +#endif diff --git a/Sources/SpanPreview/MutableSpan+InputSpanHelpers.swift b/Sources/SpanPreview/MutableSpan+InputSpanHelpers.swift new file mode 100644 index 00000000..3bf5a9bf --- /dev/null +++ b/Sources/SpanPreview/MutableSpan+InputSpanHelpers.swift @@ -0,0 +1,60 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2026 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) && UnstableContainersPreview +extension MutableSpan where Element: ~Copyable { + // FIXME: Replace with stdlib implementation when it becomes available + @_alwaysEmitIntoClient + package mutating func _updateSubrange( + _ subrange: Range, + moving source: inout InputSpan + ) { + precondition( + subrange.lowerBound >= 0 && subrange.upperBound <= count, + "Index range out of bounds") + precondition( + subrange.count == source.count, + "updateSubrange source count doesn't match target") + self.withUnsafeMutableBufferPointer { dst in + source.withUnsafeMutableBufferPointer { src, c in + // FIXME: Make sure this calls memcpy when Element is bitwise movable. + let i = dst + .extracting(unchecked: subrange) + .moveUpdate(fromContentsOf: src.extracting(last: c)) + precondition(i == subrange.count) + c = 0 + } + } + } + + // FIXME: Replace with stdlib implementation when it becomes available + @_alwaysEmitIntoClient + package mutating func _updateAll( + moving source: inout InputSpan + ) { + let count = self.count + precondition( + source.count == count, + "updateSubrange source count doesn't match target") + self.withUnsafeMutableBufferPointer { dst in + source.withUnsafeMutableBufferPointer { src, c in + // FIXME: Make sure this calls memcpy when Element is bitwise movable. + let i = dst.moveUpdate(fromContentsOf: src.extracting(last: c)) + assert(i == count) + c = 0 + } + } + } +} + +#endif