//===--- Reverse.swift.gyb - Lazy sequence reversal -----------*- swift -*-===// // // 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 // //===----------------------------------------------------------------------===// /// Return an `Array` containing the elements of `source` in reverse /// order. public func reverse( source: C ) -> [C.Generator.Element] { return lazy(source).reverse().array } % for traversal in ('Bidirectional', 'RandomAccess'): % View = '%sReverseView' % traversal % Self = 'Lazy%sCollection' % traversal % Index = 'Reverse%sIndex' % traversal % IndexProtocol = '%sIndexType' % traversal /// A wrapper for a `${IndexProtocol}` that reverses its /// direction of traversal public struct ${Index} : ${IndexProtocol} { var _base: I init(_ _base: I) { self._base = _base } public func successor() -> ${Index} { return ${Index}(_base.predecessor()) } public func predecessor() -> ${Index} { return ${Index}(_base.successor()) } typealias Distance = I.Distance % if traversal == 'RandomAccess': public func distanceTo(other: ${Index}) -> Distance { return other._base.distanceTo(_base) } public func advancedBy(amount: Distance) -> ${Index} { return ${Index}(_base.advancedBy(-amount)) } % end } public func == (lhs: ${Index}, rhs: ${Index}) -> Bool { return lhs._base == rhs._base } /// The lazy `CollectionType` returned by `reverse(c)` where `c` is a /// `CollectionType` with an `Index` conforming to `${IndexProtocol}` public struct ${View}< T: CollectionType where T.Index: ${IndexProtocol} > : CollectionType { public typealias Index = ${Index} public typealias Generator = IndexingGenerator<${View}> init(_ _base: T) { self._base = _base } public func generate() -> IndexingGenerator<${View}> { return IndexingGenerator(self) } public var startIndex: Index { return ${Index}(_base.endIndex) } public var endIndex: Index { return ${Index}(_base.startIndex) } public subscript(i: Index) -> T.Generator.Element { return _base[i._base.predecessor()] } var _base: T } 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}> { return LazyBidirectionalCollection<${View}>( ${View}(self._base) ) } } % end // ${'Local Variables'}: // eval: (read-only-mode 1) // End: