From 7b578e5bfb8acecfe47fd4ecda1b9aeb3d5e158a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 4 Nov 2026 18:10:11 -0800 Subject: [PATCH] Review and fix filter implementations - Define a separate `filter` result on Iterable vs BorrowingIteratorProtocol - Fix handling of delimited iterators in Container.filter - Add fixmes for throwing - Inlinability and other small fixes --- Sources/ContainersPreview/CMakeLists.txt | 1 + .../Container/Container+Filter.swift | 47 +++++++++- .../Protocols/Container/Container.swift | 8 ++ .../BorrowingIteratorProtocol+Filter.swift | 14 +-- .../Protocols/Iterable/Iterable+Filter.swift | 76 +++++++++++++++ .../Protocols/Producer/Producer+Filter.swift | 2 + .../Container_Algorithms_Tests.swift | 93 +++++++++++++++++++ .../ConformanceCheckers/CheckContainer.swift | 26 +++++- 8 files changed, 256 insertions(+), 11 deletions(-) create mode 100644 Sources/ContainersPreview/Protocols/Iterable/Iterable+Filter.swift create mode 100644 Tests/ContainersTests/Container_Algorithms_Tests.swift diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index 9e7452d3..98720b4c 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -101,6 +101,7 @@ target_sources(${module_name} PRIVATE "Protocols/Iterable/BorrowingIteratorProtocol+Reduce.swift" "Protocols/Iterable/BorrowingIteratorProtocol+SpanwiseZip.swift" "Protocols/Iterable/Iterable+ElementsEqual.swift" + "Protocols/Iterable/Iterable+Filter.swift" "Protocols/Iterable/Iterable+Reduce.swift" "Protocols/Producer/CountedProducer.swift" "Protocols/Producer/Producer.swift" diff --git a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift index e5b53b48..de471a54 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift @@ -25,9 +25,10 @@ import InternalCollectionsUtilities extension Container where Self: ~Copyable /*& ~Escapable*/, Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func _filter( + public func filter( // FIXME: Ambiguity with Sequence.filter _ isIncluded: @escaping (borrowing Element) -> Bool ) -> ContainerFilter { + // FIXME: isIncluded should be allowed to throw ContainerFilter(_base: self, isIncluded: isIncluded) } } @@ -39,7 +40,12 @@ extension ContainerIterator where Base.Element: ~Copyable { public func filter( _ isIncluded: @escaping (borrowing Element) -> Bool ) -> ContainerFilter { - ContainerFilter(_base: _base, index: _position, isIncluded: isIncluded) + // FIXME: isIncluded should be allowed to throw + ContainerFilter( + _base: _base, + index: _position, + end: _end, + isIncluded: isIncluded) } } @@ -57,6 +63,9 @@ where Base.Element: ~Copyable @_alwaysEmitIntoClient public let _base: Ref // FIXME: This does not allow escapable Bases + @_alwaysEmitIntoClient + public let _end: Base.Index + @_alwaysEmitIntoClient public var _position: Base.Index @@ -68,11 +77,13 @@ where Base.Element: ~Copyable internal init( _base: Ref, index: Base.Index, + end: Base.Index, isIncluded: @escaping (borrowing Element) -> Bool ) { self._isIncluded = isIncluded self._base = _base self._position = index + self._end = end self._remainder = .init() } @@ -85,6 +96,7 @@ where Base.Element: ~Copyable self._isIncluded = isIncluded self._base = Ref(_base) self._position = _base.startIndex + self._end = _base.endIndex self._remainder = .init() } } @@ -92,7 +104,34 @@ where Base.Element: ~Copyable // FIXME: Sendable @available(SwiftStdlib 6.4, *) -extension ContainerFilter: BorrowingIteratorProtocol where Element: ~Copyable { +extension ContainerFilter: Iterable +where + Base: ~Copyable /* & ~Escapable */, + Element: ~Copyable +{ + @_lifetime(copy self) + package func _clone() -> Self { + var copy = ContainerFilter( + _base: self._base, + index: self._position, + end: self._end, + isIncluded: self._isIncluded) + copy._remainder = self._remainder + return copy + } + + @_lifetime(borrow self) + public func makeBorrowingIterator() -> Self { + self._clone() + } +} + +@available(SwiftStdlib 6.4, *) +extension ContainerFilter: BorrowingIteratorProtocol +where + Base: ~Copyable /* & ~Escapable */, + Element: ~Copyable +{ @_lifetime(&self) public mutating func nextSpan(maxCount: Int) -> Span { precondition(maxCount > 0) @@ -111,7 +150,7 @@ extension ContainerFilter: BorrowingIteratorProtocol where Element: ~Copyable { } return _remainder._trim(first: i) } - _remainder = _base.value.nextSpan(after: &_position) + _remainder = _base.value.nextSpan(after: &_position, limitedBy: _end) if _remainder.isEmpty { return .init() } } } diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift index 3ab8d954..02723ac8 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container.swift @@ -295,6 +295,14 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { public func makeBorrowingIterator(from start: Index) -> BorrowingIterator { self.makeBorrowingIterator(from: start, to: self.endIndex) } + + @_alwaysEmitIntoClient + @_transparent + @_lifetime(borrow self) + public func makeBorrowingIterator(in subrange: Range) -> BorrowingIterator { + // FIXME: Now that Index is Comparable, this should probably become the protocol requirement. + self.makeBorrowingIterator(from: subrange.lowerBound, to: subrange.upperBound) + } } @available(SwiftStdlib 6.4, *) diff --git a/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Filter.swift b/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Filter.swift index 3e1069d5..37162861 100644 --- a/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Filter.swift @@ -23,13 +23,14 @@ where @_lifetime(copy self) public consuming func filter( _ isIncluded: @escaping (borrowing Element) -> Bool - ) -> BorrowingFilter { - BorrowingFilter(_base: self, isIncluded: isIncluded) + ) -> BorrowingFilterIterator { + // FIXME: isIncluded should be allowed to throw + BorrowingFilterIterator(_base: self, isIncluded: isIncluded) } } @available(SwiftStdlib 6.4, *) -public struct BorrowingFilter< +public struct BorrowingFilterIterator< Base: BorrowingIteratorProtocol & ~Copyable & ~Escapable >: ~Copyable, ~Escapable where Base.Element: ~Copyable { @@ -37,7 +38,7 @@ where Base.Element: ~Copyable { public typealias Failure = Base.Failure @_alwaysEmitIntoClient - public let _isIncluded: (borrowing Element) throws(Failure) -> Bool + public let _isIncluded: (borrowing Element) -> Bool @_alwaysEmitIntoClient public var _base: Base @@ -56,8 +57,9 @@ where Base.Element: ~Copyable { // FIXME: Sendable @available(SwiftStdlib 6.4, *) -extension BorrowingFilter: BorrowingIteratorProtocol +extension BorrowingFilterIterator: BorrowingIteratorProtocol where Base: ~Copyable & ~Escapable, Base.Element: ~Copyable { + @inlinable @_lifetime(&self) public mutating func nextSpan(maxCount: Int) throws(Failure) -> Span { // FIXME: This is quite inefficient compared to Container's filter @@ -65,7 +67,7 @@ where Base: ~Copyable & ~Escapable, Base.Element: ~Copyable { let span = try _base.nextSpan(maxCount: 1) if span.isEmpty { return span } precondition(span.count == 1, "Invalid BorrowingIterator") - if unsafe try _isIncluded(span[unchecked: 0]) { return span } + if unsafe _isIncluded(span[unchecked: 0]) { return span } } } } diff --git a/Sources/ContainersPreview/Protocols/Iterable/Iterable+Filter.swift b/Sources/ContainersPreview/Protocols/Iterable/Iterable+Filter.swift new file mode 100644 index 00000000..122d9b33 --- /dev/null +++ b/Sources/ContainersPreview/Protocols/Iterable/Iterable+Filter.swift @@ -0,0 +1,76 @@ +//===----------------------------------------------------------------------===// +// +// 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.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.4, *) +extension Iterable +where + Self: ~Copyable /*& ~Escapable*/, + Element: ~Copyable +{ + @inlinable + @_lifetime(borrow self) + public borrowing func filter( // FIXME: Ambiguity with Sequence.filter + _ isIncluded: @escaping (borrowing Element) -> Bool + ) -> BorrowingFilter { + // FIXME: isIncluded should be allowed to throw + BorrowingFilter(_base: self, isIncluded: isIncluded) + } +} + +@available(SwiftStdlib 6.4, *) +public struct BorrowingFilter< + Base: Iterable & ~Copyable /*& ~Escapable*/ +>: ~Copyable, ~Escapable +where Base.Element: ~Copyable { + public typealias Element = Base.Element + public typealias Failure = Base.Failure + + @_alwaysEmitIntoClient + public let _isIncluded: (borrowing Element) -> Bool + + @_alwaysEmitIntoClient + public var _base: Ref // FIXME: Support for ~Escapable + + @inlinable + @_lifetime(borrow _base) + internal init( + _base: borrowing Base, + isIncluded: @escaping (borrowing Element) -> Bool + ) { + self._isIncluded = isIncluded + self._base = Ref(_base) + } +} + +// FIXME: Sendable + +@available(SwiftStdlib 6.4, *) +extension BorrowingFilter: Iterable +where + Base: ~Copyable /*& ~Escapable*/, + Base.Element: ~Copyable +{ + public typealias BorrowingIterator = BorrowingFilterIterator + + @inlinable + @_lifetime(borrow self) + public borrowing func makeBorrowingIterator() -> BorrowingIterator { + BorrowingFilterIterator( + _base: self._base.value.makeBorrowingIterator(), + isIncluded: self._isIncluded) + } +} + +#endif diff --git a/Sources/ContainersPreview/Protocols/Producer/Producer+Filter.swift b/Sources/ContainersPreview/Protocols/Producer/Producer+Filter.swift index e085f04b..be4a1376 100644 --- a/Sources/ContainersPreview/Protocols/Producer/Producer+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Producer/Producer+Filter.swift @@ -24,6 +24,7 @@ import InternalCollectionsUtilities @available(SwiftStdlib 5.0, *) extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_lifetime(copy self) + @inlinable public consuming func filter( // Note: The predicate is not throwing to avoid difficult exception safety problems _ isIncluded: @escaping (borrowing Element) -> Bool @@ -42,6 +43,7 @@ where Base.Element: ~Copyable { @_alwaysEmitIntoClient public var _base: Base + @_alwaysEmitIntoClient public let _isIncluded: (borrowing Element) -> Bool diff --git a/Tests/ContainersTests/Container_Algorithms_Tests.swift b/Tests/ContainersTests/Container_Algorithms_Tests.swift new file mode 100644 index 00000000..d1a73142 --- /dev/null +++ b/Tests/ContainersTests/Container_Algorithms_Tests.swift @@ -0,0 +1,93 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +import XCTest + +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import _CollectionsTestSupport +import InternalCollectionsUtilities +import SpanPreview +import BasicContainers +import DequeModule +#endif +import ContainersPreview + +#if compiler(>=6.4) && UnstableContainersPreview + +@available(SwiftStdlib 6.4, *) +final class Container_Algorithms_Tests: CollectionTestCase { + func test_filter_RigidArray_simple() { + let count = 100 + precondition(count.isMultiple(of: 10)) // Assumed below + withLifetimeTracking { tracker in + let items = RigidArray(copying: tracker.instances(for: 0 ..< count)) + let evens = items.filter { $0.payload.isMultiple(of: 2) } + + expectIterablePayloads(evens, equalTo: (0 ..< count / 2).map { 2 * $0 }) + } + } + + func test_filter_RigidArray_runs() { + let count = 100 + precondition(count.isMultiple(of: 10)) // Assumed below + withLifetimeTracking { tracker in + let items = RigidArray(copying: tracker.instances(for: 0 ..< count)) + + let runs = items.filter { !$0.payload.isMultiple(of: 5) } + let expectedRuns = (0 ..< count).filter { !$0.isMultiple(of: 5) } + expectIterablePayloads(runs, equalTo: expectedRuns) + + // Check that container filters can return larger chunks + expectEqualElements(runs._spanCounts(), repeatElement(4, count: count / 5)) + } + } + + func test_filter_RigidArray_slices() { + // Note: this dispatches to Iterable.filter, not ContainerIterator.filter. + // FIXME: Add a specialized `filter` on Span.BorrowingIterator. + withEvery("count", in: [0, 1, 5, 10, 20]) { count in + withLifetimeTracking { tracker in + let items = tracker.rigidArray(layout: ArrayLayout(capacity: count, count: count)) + withEveryRange("subrange", in: 0 ..< count) { subrange in + let runs = items.makeBorrowingIterator(in: subrange).filter { + !$0.payload.isMultiple(of: 3) + } + + let expectedRuns = subrange.filter { !$0.isMultiple(of: 3) } + expectBorrowingIteratorPayloads(runs, equalTo: expectedRuns) + } + } + } + } + + func test_filter_RigidDeque_slices() { + // Note: this dispatches to Iterable.filter, not ContainerIterator.filter. + withEveryFullDeque("layout", ofCapacities: [0, 1, 5, 10, 20]) { layout in + withLifetimeTracking { tracker in + let items = RigidDeque(layout: layout) { tracker.instance(for: $0) } + withEveryRange("subrange", in: 0 ..< layout.count) { subrange in + let runs = items.makeBorrowingIterator(in: subrange).filter { + !$0.payload.isMultiple(of: 3) + } + + let expectedRuns = subrange.filter { !$0.isMultiple(of: 3) } + expectBorrowingIteratorPayloads(runs, equalTo: expectedRuns) + } + } + } + } +} + +#endif diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift index 8fcd5611..cc630102 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift @@ -490,6 +490,18 @@ public func validateContainer< } } +@available(SwiftStdlib 6.4, *) +extension Iterable +where + Self: ~Copyable & ~Escapable, + Element: ~Copyable +{ + @inlinable + package borrowing func _spanCounts() throws(Failure) -> [Int] { + try makeBorrowingIterator()._spanCounts() + } +} + @available(SwiftStdlib 6.4, *) extension BorrowingIteratorProtocol where @@ -497,7 +509,7 @@ where Element: ~Copyable { @inlinable - internal consuming func _spanCounts() throws(Failure) -> [Int] { + package consuming func _spanCounts() throws(Failure) -> [Int] { var result: [Int] = [] var it = consume self while true { @@ -509,6 +521,18 @@ where } } +@available(SwiftStdlib 6.4, *) +extension BorrowingIteratorProtocol +where + Self: Iterable & ~Copyable & ~Escapable, + Element: ~Copyable +{ + @inlinable + package borrowing func _spanCounts() throws(Failure) -> [Int] { + try makeBorrowingIterator()._spanCounts() + } +} + @available(SwiftStdlib 6.4, *) extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { @inlinable