Skip to content

Commit 268d7cb

Browse files
committed
Support .lazy version of doubly reversed collection (with ReversedCollectionProtocol)
1 parent a009ae2 commit 268d7cb

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

stdlib/public/core/Reverse.swift

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@ extension MutableCollection where Self: BidirectionalCollection {
3535
}
3636
}
3737

38+
/// A collection that presents the elements of its base collection
39+
/// in reverse order.
40+
///
41+
/// - See also: `ReversedCollection` below.
42+
public protocol ReversedCollectionProtocol: BidirectionalCollection {
43+
/// A `Collection` that can contain the same elements as this one,
44+
/// just in reverse order.
45+
associatedtype Elements: Collection where Elements.Iterator.Element == Iterator.Element
46+
var elements: Elements { get }
47+
}
48+
3849
/// A collection that presents the elements of its base collection
3950
/// in reverse order.
4051
///
@@ -84,7 +95,16 @@ extension ReversedCollection {
8495
}
8596
}
8697
}
87-
98+
99+
extension ReversedCollection: ReversedCollectionProtocol {
100+
/// The type of the underlying collection.
101+
public typealias Elements = Base
102+
103+
/// The underlying collection.
104+
@inlinable
105+
public var elements: Elements { return _base }
106+
}
107+
88108
extension ReversedCollection.Iterator: IteratorProtocol, Sequence {
89109
public typealias Element = Base.Element
90110

@@ -254,13 +274,8 @@ extension ReversedCollection: BidirectionalCollection {
254274
extension ReversedCollection: RandomAccessCollection where Base: RandomAccessCollection { }
255275

256276
extension ReversedCollection {
257-
/// This is optimization to return identity of doubly reversed collection
277+
/// This is optimization to return original collection of doubly reversed collection
258278
/// For example [1,2].reversed().reversed() => [1,2]
259-
///
260-
/// Returns a view presenting the elements of the collection in reverse
261-
/// order.
262-
///
263-
/// - Complexity: O(1)
264279
public func reversed() -> Base {
265280
return _base
266281
}
@@ -298,6 +313,14 @@ extension BidirectionalCollection {
298313
}
299314
}
300315

316+
extension LazyCollection where Base: ReversedCollectionProtocol {
317+
/// This is optimization to return original collection of doubly reversed lazy collection
318+
/// For example [1,2].lazy.reversed().reversed() => [1,2].lazy
319+
public func reversed() -> LazyCollection<Elements.Elements> {
320+
return elements.elements.lazy
321+
}
322+
}
323+
301324
extension LazyCollectionProtocol
302325
where
303326
Self: BidirectionalCollection,

0 commit comments

Comments
 (0)