//===--- CollectionAlgorithms.swift.gyb -----------------------------------===// // // 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 // //===----------------------------------------------------------------------===// %{ # We know we will eventually get a SequenceType.Element type. Define # a shorthand that we can use today. GElement = "Iterator.Element" }% //===----------------------------------------------------------------------===// // last //===----------------------------------------------------------------------===// extension Collection where Index : BidirectionalIndex { public var last: Iterator.Element? { return isEmpty ? nil : self[endIndex.predecessor()] } } //===----------------------------------------------------------------------===// // indexOf() //===----------------------------------------------------------------------===// extension Collection where ${GElement} : Equatable { /// Returns the first index where `value` appears in `self` or `nil` if /// `value` is not found. /// /// - Complexity: O(`self.count`). @warn_unused_result public func indexOf(element: ${GElement}) -> Index? { if let result = _customIndexOfEquatableElement(element) { return result } for i in self.indices { if self[i] == element { return i } } return nil } } extension Collection { /// Returns the first index where `predicate` returns `true` for the /// corresponding value, or `nil` if such value is not found. /// /// - Complexity: O(`self.count`). @warn_unused_result public func indexOf( @noescape predicate: (${GElement}) throws -> Bool ) rethrows -> Index? { for i in self.indices { if try predicate(self[i]) { return i } } return nil } } //===----------------------------------------------------------------------===// // indices //===----------------------------------------------------------------------===// extension Collection { /// Return the range of valid index values. /// /// The result's `endIndex` is the same as that of `self`. Because /// `Range` is half-open, iterating the values of the result produces /// all valid subscript arguments for `self`, omitting its `endIndex`. public var indices: Range { return Range(start: startIndex, end: endIndex) } } //===----------------------------------------------------------------------===// // MutableCollection //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // partition() //===----------------------------------------------------------------------===// %{ partitionDocComment = """\ /// Re-order the given `range` of elements in `self` and return /// a pivot index *p*. /// /// - Postcondition: For all *i* in `range.startIndex..<`\ *p*, and *j* /// in *p*\ `.., isOrderedBefore: (${GElement}, ${GElement}) -> Bool ) -> Index { var isOrderedBefore = isOrderedBefore % else: extension MutableCollection where Index : RandomAccessIndex, ${GElement} : Comparable { ${partitionDocComment} /// ${orderingRequirementForComparable} public mutating func partition(range: Range) -> Index { % end let maybeResult = _withUnsafeMutableBufferPointerIfSupported { (baseAddress, count) -> Index in var bufferPointer = UnsafeMutableBufferPointer(start: baseAddress, count: count) let startOffset = startIndex.distanceTo(range.startIndex) let unsafeBufferStartIndex = bufferPointer.startIndex + numericCast(startOffset) let endOffset = startIndex.distanceTo(range.endIndex) let unsafeBufferEndIndex = bufferPointer.startIndex + numericCast(endOffset) let unsafeBufferPivot = bufferPointer.partition( unsafeBufferStartIndex.. [Iterator.Element] { var result = ContiguousArray(self) result.sortInPlace() return Array(result) } } extension ${Self} { ${sortDocCommentForPredicate} /// ${sortIsUnstableForPredicate} /// ${orderingRequirementForPredicate} @warn_unused_result(${'mutable_variant="sortInPlace"' if Self == 'MutableCollection' else ''}) public func sort( @noescape isOrderedBefore: (Iterator.Element, Iterator.Element) -> Bool ) -> [Iterator.Element] { typealias EscapingBinaryPredicate = (Iterator.Element, Iterator.Element) -> Bool let escapableIsOrderedBefore = unsafeBitCast(isOrderedBefore, EscapingBinaryPredicate.self) var result = ContiguousArray(self) result.sortInPlace(escapableIsOrderedBefore) return Array(result) } } % end extension MutableCollection where Self.Index : RandomAccessIndex, Self.Iterator.Element : Comparable { ${sortInPlaceDocCommentForComparable} /// ${sortIsUnstableForComparable} /// ${orderingRequirementForComparable} public mutating func sortInPlace() { let didSortUnsafeBuffer: Void? = _withUnsafeMutableBufferPointerIfSupported { (baseAddress, count) -> Void in var bufferPointer = UnsafeMutableBufferPointer(start: baseAddress, count: count) bufferPointer.sortInPlace() return () } if didSortUnsafeBuffer == nil { _introSort(&self, self.indices) } } } extension MutableCollection where Self.Index : RandomAccessIndex { ${sortInPlaceDocCommentForPredicate} /// ${sortIsUnstableForPredicate} /// ${orderingRequirementForPredicate} public mutating func sortInPlace( @noescape isOrderedBefore: (Iterator.Element, Iterator.Element) -> Bool ) { typealias EscapingBinaryPredicate = (Iterator.Element, Iterator.Element) -> Bool let escapableIsOrderedBefore = unsafeBitCast(isOrderedBefore, EscapingBinaryPredicate.self) let didSortUnsafeBuffer: Void? = _withUnsafeMutableBufferPointerIfSupported { (baseAddress, count) -> Void in var bufferPointer = UnsafeMutableBufferPointer(start: baseAddress, count: count) bufferPointer.sortInPlace(escapableIsOrderedBefore) return () } if didSortUnsafeBuffer == nil { _introSort(&self, self.indices, escapableIsOrderedBefore) } } }