mirror of
https://github.com/apple/swift.git
synced 2025-12-21 12:14:44 +01:00
93 lines
2.5 KiB
Swift
93 lines
2.5 KiB
Swift
%# -*- mode: swift -*-
|
|
//===--- Reverse.swift - Lazy sequence reversal ---------------------------===//
|
|
//
|
|
// This source file is part of the Swift.org open source project
|
|
//
|
|
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
|
|
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
//
|
|
// See http://swift.org/LICENSE.txt for license information
|
|
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
/// A wrapper for a `BidirectionalIndex` that reverses its
|
|
/// direction of traversal
|
|
@public struct ReverseIndex<I: BidirectionalIndex> : BidirectionalIndex {
|
|
var _base: I
|
|
|
|
init(_ _base: I) { self._base = _base }
|
|
|
|
@public func successor() -> ReverseIndex {
|
|
return ReverseIndex(_base.predecessor())
|
|
}
|
|
|
|
@public func predecessor() -> ReverseIndex {
|
|
return ReverseIndex(_base.successor())
|
|
}
|
|
}
|
|
|
|
@public func == <I> (lhs: ReverseIndex<I>, rhs: ReverseIndex<I>) -> Bool {
|
|
return lhs._base == rhs._base
|
|
}
|
|
|
|
/// The lazy `Collection` returned by `reverse(c)` where `c` is a
|
|
/// `Collection`
|
|
@public struct ReverseView<
|
|
T: Collection where T.IndexType: BidirectionalIndex
|
|
> : Collection {
|
|
@public typealias IndexType = ReverseIndex<T.IndexType>
|
|
@public typealias GeneratorType = IndexingGenerator<ReverseView>
|
|
|
|
init(_ _base: T) {
|
|
self._base = _base
|
|
}
|
|
|
|
@public func generate() -> IndexingGenerator<ReverseView> {
|
|
return IndexingGenerator(self)
|
|
}
|
|
|
|
@public var startIndex: IndexType {
|
|
return ReverseIndex(_base.endIndex)
|
|
}
|
|
|
|
@public var endIndex: IndexType {
|
|
return ReverseIndex(_base.startIndex)
|
|
}
|
|
|
|
@public subscript(i: IndexType) -> T.GeneratorType.Element {
|
|
return _base[i._base.predecessor()]
|
|
}
|
|
|
|
var _base: T
|
|
}
|
|
|
|
/*
|
|
/// Return a lazy Collection containing the elements `x` of `source` for
|
|
/// which `includeElement(x)` is `true`
|
|
@public func reverse<
|
|
C: Collection where C.IndexType: BidirectionalIndex
|
|
>(source: C) -> ReverseView<C> {
|
|
return ReverseView(source)
|
|
}
|
|
*/
|
|
|
|
% traversals = ('Bidirectional', 'RandomAccess')
|
|
% for View, Self in [
|
|
% ('ReverseView', 'Lazy%sCollection' % t) for t in traversals
|
|
% ]:
|
|
|
|
extension ${Self} {
|
|
/// Return a `${View}` over this `${Self}`. The elements of
|
|
/// the result are computed lazily, each time they are read, by
|
|
/// calling `transform` function on a base element.
|
|
@public
|
|
func reverse() -> LazyBidirectionalCollection<${View}<S>> {
|
|
return LazyBidirectionalCollection<ReverseView<S>>(
|
|
ReverseView<S>(self._base)
|
|
)
|
|
}
|
|
}
|
|
|
|
% end
|