Files
swift-mirror/stdlib/public/core/CollectionAlgorithms.swift.gyb
2016-04-06 09:20:30 -07:00

408 lines
11 KiB
Swift

//===--- CollectionAlgorithms.swift.gyb -----------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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 Sequence.Element type. Define
# a shorthand that we can use today.
IElement = "Iterator.Element"
}%
//===----------------------------------------------------------------------===//
// last
//===----------------------------------------------------------------------===//
extension BidirectionalCollection {
public var last: Iterator.Element? {
return isEmpty ? nil : self[predecessor(of: endIndex)]
}
}
//===----------------------------------------------------------------------===//
// index(of:)/index(where:)
//===----------------------------------------------------------------------===//
extension Collection where ${IElement} : 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 index(of element: ${IElement}) -> Index? {
if let result = _customIndexOfEquatableElement(element) {
return result
}
var i = self.startIndex
while i != self.endIndex {
if self[i] == element {
return i
}
self.formSuccessor(&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 index(
@noescape where predicate: (${IElement}) throws -> Bool
) rethrows -> Index? {
var i = self.startIndex
while i != self.endIndex {
if try predicate(self[i]) {
return i
}
self.formSuccessor(&i)
}
return nil
}
}
//===----------------------------------------------------------------------===//
// MutableCollection
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// partition()
//===----------------------------------------------------------------------===//
%{
partitionDocComment = """\
/// Re-order the given `range` of elements in `self` and return
/// a pivot index *p*.
///
/// - Postcondition: For all *i* in `range.lowerBound..<`\ *p*, and *j*
/// in *p*\ `..<range.upperBound`, `less(self[`\ *i*\ `],
/// self[`\ *j*\ `]) && !less(self[`\ *j*\ `], self[`\ *p*\ `])`.
/// Only returns `range.upperBound` when `self` is empty."""
orderingRequirementForPredicate = """\
/// - Precondition: `isOrderedBefore` is a
/// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings)
/// over the elements in `self`."""
orderingRequirementForComparable = """\
/// - Precondition: The less-than operator (`func <`) defined in
/// the `Comparable` conformance is a
/// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings)
/// over the elements in `self`."""
}%
% # Generate two versions: with explicit predicates and with
% # a Comparable requirement.
% for preds in [ True, False ]:
% if preds:
extension MutableCollection where Self : RandomAccessCollection
% else:
extension MutableCollection
where Self : RandomAccessCollection, ${IElement} : Comparable
% end
{
% if preds:
${partitionDocComment}
///
${orderingRequirementForPredicate}
@warn_unused_result
public mutating func partition(
@noescape isOrderedBefore isOrderedBefore:
(${IElement}, ${IElement}) -> Bool
) -> Index
% else:
${partitionDocComment}
///
${orderingRequirementForComparable}
@warn_unused_result
public mutating func partition() -> Index
% end
{
let maybeOffset = _withUnsafeMutableBufferPointerIfSupported {
(baseAddress, count) -> Int in
var bufferPointer =
UnsafeMutableBufferPointer(start: baseAddress, count: count)
let unsafeBufferPivot = bufferPointer.partition(
% if preds:
isOrderedBefore: isOrderedBefore
% end
)
return unsafeBufferPivot - bufferPointer.startIndex
}
if let offset = maybeOffset {
return index(numericCast(offset), stepsFrom: startIndex)
}
% if preds:
typealias EscapingBinaryPredicate =
(${IElement}, ${IElement}) -> Bool
var escapableIsOrderedBefore =
unsafeBitCast(isOrderedBefore, to: EscapingBinaryPredicate.self)
return _partition(
&self,
subRange: startIndex..<endIndex,
isOrderedBefore: &escapableIsOrderedBefore)
% else:
return _partition(&self, subRange: startIndex..<endIndex)
% end
}
}
% end
//===----------------------------------------------------------------------===//
// sorted()
//===----------------------------------------------------------------------===//
%{
sortedDocCommentForPredicate = """\
/// Returns an `Array` containing the sorted elements of `source`
/// according to `isOrderedBefore`."""
sortedDocCommentForComparable = """\
/// Returns an `Array` containing the sorted elements of `source`."""
sortDocCommentForPredicate = """\
/// Sort `self` in-place according to `isOrderedBefore`."""
sortDocCommentForComparable = """\
/// Sort `self` in-place."""
sortIsUnstableForPredicate = """\
/// The sorting algorithm is not stable (can change the relative order of
/// elements for which `isOrderedBefore` does not establish an order)."""
sortIsUnstableForComparable = """\
/// The sorting algorithm is not stable (can change the relative order of
/// elements that compare equal)."""
}%
% for Self in [ 'Sequence', 'MutableCollection' ]:
extension ${Self} where Self.Iterator.Element : Comparable {
${sortedDocCommentForComparable}
///
${sortIsUnstableForComparable}
///
${orderingRequirementForComparable}
@warn_unused_result(${'mutable_variant: "sort"' if Self == 'MutableCollection' else ''})
public func sorted() -> [Iterator.Element] {
var result = ContiguousArray(self)
result.sort()
return Array(result)
}
}
extension ${Self} {
${sortedDocCommentForPredicate}
///
${sortIsUnstableForPredicate}
///
${orderingRequirementForPredicate}
@warn_unused_result(${'mutable_variant: "sort"' if Self == 'MutableCollection' else ''})
public func sorted(
@noescape isOrderedBefore isOrderedBefore:
(${IElement}, ${IElement}) -> Bool
) -> [Iterator.Element] {
var result = ContiguousArray(self)
result.sort(isOrderedBefore: isOrderedBefore)
return Array(result)
}
}
% end
extension MutableCollection
where
Self : RandomAccessCollection,
Self.Iterator.Element : Comparable {
${sortDocCommentForComparable}
///
${sortIsUnstableForComparable}
///
${orderingRequirementForComparable}
public mutating func sort() {
let didSortUnsafeBuffer: Void? =
_withUnsafeMutableBufferPointerIfSupported {
(baseAddress, count) -> Void in
var bufferPointer =
UnsafeMutableBufferPointer(start: baseAddress, count: count)
bufferPointer.sort()
return ()
}
if didSortUnsafeBuffer == nil {
_introSort(&self, subRange: startIndex..<endIndex)
}
}
}
extension MutableCollection where Self : RandomAccessCollection {
${sortDocCommentForPredicate}
///
${sortIsUnstableForPredicate}
///
${orderingRequirementForPredicate}
public mutating func sort(
@noescape isOrderedBefore isOrderedBefore:
(${IElement}, ${IElement}) -> Bool
) {
typealias EscapingBinaryPredicate =
(Iterator.Element, Iterator.Element) -> Bool
let escapableIsOrderedBefore =
unsafeBitCast(isOrderedBefore, to: EscapingBinaryPredicate.self)
let didSortUnsafeBuffer: Void? =
_withUnsafeMutableBufferPointerIfSupported {
(baseAddress, count) -> Void in
var bufferPointer =
UnsafeMutableBufferPointer(start: baseAddress, count: count)
bufferPointer.sort(isOrderedBefore: escapableIsOrderedBefore)
return ()
}
if didSortUnsafeBuffer == nil {
_introSort(
&self,
subRange: startIndex..<endIndex,
isOrderedBefore: escapableIsOrderedBefore)
}
}
}
% for Self in 'Indexable', 'MutableIndexable':
// WORKAROUND rdar://25214066 - should be on Collection
extension ${Self} {
public subscript(bounds: ClosedRange<Index>) -> SubSequence {
get {
return self[
Range(
uncheckedBounds: (
lower: bounds.lowerBound,
upper: successor(of: bounds.upperBound)))
]
}
% if 'Mutable' in Self:
set {
self[
Range(
uncheckedBounds: (
lower: bounds.lowerBound,
upper: successor(of: bounds.upperBound)))
] = newValue
}
% end
}
}
// WORKAROUND rdar://25214066 - should be on Collection
extension ${Self} where Index : Strideable, Index.Stride : Integer {
public subscript(bounds: CountableRange<Index>) -> SubSequence {
get {
return self[Range(bounds)]
}
% if 'Mutable' in Self:
set {
self[Range(bounds)] = newValue
}
% end
}
public subscript(bounds: CountableClosedRange<Index>) -> SubSequence {
get {
return self[ClosedRange(bounds)]
}
% if 'Mutable' in Self:
set {
self[ClosedRange(bounds)] = newValue
}
% end
}
}
% end
//===--- Unavailable stuff ------------------------------------------------===//
extension MutableCollection where Self : RandomAccessCollection {
@available(*, unavailable, message: "slice the collection using the range, and call partition(isOrderedBefore:)")
public mutating func partition(
range: Range<Index>,
isOrderedBefore: (${IElement}, ${IElement}) -> Bool
) -> Index {
fatalError("unavailable function can't be called")
}
}
extension MutableCollection
where Self : RandomAccessCollection, ${IElement} : Comparable {
@available(*, unavailable, message: "slice the collection using the range, and call partition()")
public mutating func partition(range: Range<Index>) -> Index {
fatalError("unavailable function can't be called")
}
}
extension MutableCollection
where
Self : RandomAccessCollection,
Self.Iterator.Element : Comparable {
@available(*, unavailable, renamed: "sort")
public mutating func sortInPlace() {
fatalError("unavailable function can't be called")
}
}
extension MutableCollection where Self : RandomAccessCollection {
@available(*, unavailable, renamed: "sort(isOrderedBefore:)")
public mutating func sortInPlace(
@noescape isOrderedBefore: (Iterator.Element, Iterator.Element) -> Bool
) {
fatalError("unavailable function can't be called")
}
}
extension Collection where ${IElement} : Equatable {
@available(*, unavailable, renamed: "index(of:)")
@warn_unused_result
public func indexOf(element: ${IElement}) -> Index? {
fatalError("unavailable function can't be called")
}
}
extension Collection {
@available(*, unavailable, renamed: "index(where:)")
@warn_unused_result
public func indexOf(
@noescape predicate: (${IElement}) throws -> Bool
) rethrows -> Index? {
fatalError("unavailable function can't be called")
}
}