Annotate stdlib functions to get a good performance even in resilient mode, when -sil-serialize-all is disabled

This commit mostly improves the performance of arrays and ranges.
It does not cover Strings, Dictionaries and Sets yet.
This commit is contained in:
Roman Levenstein
2017-01-18 14:55:08 -08:00
parent a8e4e72270
commit 29ad714bb7
47 changed files with 1294 additions and 11 deletions

View File

@@ -17,6 +17,7 @@ let arrayCount = 1024
// This test case exposes rdar://17440222 which caused rdar://17974483 (popFront
// being really slow).
@_versioned
protocol MyArrayBufferProtocol : MutableCollection, RandomAccessCollection {
associatedtype Element

View File

@@ -75,6 +75,7 @@ public func autoreleasepoolIfUnoptimizedReturnAutoreleased(
#endif
}
@_versioned
@_silgen_name("swift_stdlib_NSArray_getObjects")
internal func _stdlib_NSArray_getObjects(
nsArray: AnyObject,

View File

@@ -16,6 +16,7 @@
/// - x: A value to compare.
/// - y: Another value to compare.
/// - Returns: The lesser of `x` and `y`. If `x` is equal to `y`, returns `x`.
@_inlineable
public func min<T : Comparable>(_ x: T, _ y: T) -> T {
// In case `x == y` we pick `x`.
// This preserves any pre-existing order in case `T` has identity,
@@ -33,6 +34,7 @@ public func min<T : Comparable>(_ x: T, _ y: T) -> T {
/// - rest: Zero or more additional values.
/// - Returns: The least of all the arguments. If there are multiple equal
/// least arguments, the result is the first one.
@_inlineable
public func min<T : Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var minValue = min(min(x, y), z)
// In case `value == minValue`, we pick `minValue`. See min(_:_:).
@@ -48,6 +50,7 @@ public func min<T : Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {
/// - x: A value to compare.
/// - y: Another value to compare.
/// - Returns: The greater of `x` and `y`. If `x` is equal to `y`, returns `y`.
@_inlineable
public func max<T : Comparable>(_ x: T, _ y: T) -> T {
// In case `x == y`, we pick `y`. See min(_:_:).
return y >= x ? y : x
@@ -62,6 +65,7 @@ public func max<T : Comparable>(_ x: T, _ y: T) -> T {
/// - rest: Zero or more additional values.
/// - Returns: The greatest of all the arguments. If there are multiple equal
/// greatest arguments, the result is the last one.
@_inlineable
public func max<T : Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var maxValue = max(max(x, y), z)
// In case `value == maxValue`, we pick `value`. See min(_:_:).
@@ -85,13 +89,18 @@ public func max<T : Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {
///
/// To create an instance of `EnumeratedIterator`, call
/// `enumerated().makeIterator()` on a sequence or collection.
@_fixed_layout
public struct EnumeratedIterator<
Base : IteratorProtocol
> : IteratorProtocol, Sequence {
@_versioned
internal var _base: Base
@_versioned
internal var _count: Int
/// Construct from a `Base` iterator.
@_inlineable
@_versioned
internal init(_base: Base) {
self._base = _base
self._count = 0
@@ -104,6 +113,7 @@ public struct EnumeratedIterator<
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@_inlineable
public mutating func next() -> Element? {
guard let b = _base.next() else { return nil }
let result = (offset: _count, element: b)
@@ -128,15 +138,20 @@ public struct EnumeratedIterator<
/// }
/// // Prints "0: foo"
/// // Prints "1: bar"
@_fixed_layout
public struct EnumeratedSequence<Base : Sequence> : Sequence {
@_versioned
internal var _base: Base
/// Construct from a `Base` sequence.
@_inlineable
@_versioned
internal init(_base: Base) {
self._base = _base
}
/// Returns an iterator over the elements of this sequence.
@_inlineable
public func makeIterator() -> EnumeratedIterator<Base.Iterator> {
return EnumeratedIterator(_base: _base.makeIterator())
}

View File

@@ -17,10 +17,13 @@
import SwiftShims
@_fixed_layout
@_versioned
internal struct _ArrayBody {
@_versioned
var _storage: _SwiftArrayBodyStorage
@_inlineable
@_versioned
init(count: Int, capacity: Int, elementTypeIsBridgedVerbatim: Bool = false) {
_sanityCheck(count >= 0)
@@ -36,11 +39,15 @@ internal struct _ArrayBody {
/// constructed, but since we want to claim all the allocated
/// capacity after a new buffer is allocated, it's typical to want
/// to update it immediately after construction.
@_inlineable
@_versioned
init() {
_storage = _SwiftArrayBodyStorage(count: 0, _capacityAndFlags: 0)
}
/// The number of elements stored in this Array.
@_inlineable
@_versioned
var count: Int {
get {
return _assumeNonNegative(_storage.count)
@@ -52,6 +59,8 @@ internal struct _ArrayBody {
/// The number of elements that can be stored in this Array without
/// reallocation.
@_inlineable
@_versioned
var capacity: Int {
return Int(_capacityAndFlags >> 1)
}
@@ -62,6 +71,8 @@ internal struct _ArrayBody {
/// optimizer before 1.0 ships, so we store it in a bit here to
/// avoid the cost of calls into the runtime that compute the
/// answer.
@_inlineable
@_versioned
var elementTypeIsBridgedVerbatim: Bool {
get {
return (_capacityAndFlags & 0x1) != 0
@@ -74,6 +85,8 @@ internal struct _ArrayBody {
/// Storage optimization: compresses capacity and
/// elementTypeIsBridgedVerbatim together.
@_inlineable
@_versioned
var _capacityAndFlags: UInt {
get {
return _storage._capacityAndFlags

View File

@@ -26,10 +26,13 @@ internal typealias _ArrayBridgeStorage
internal struct _ArrayBuffer<Element> : _ArrayBufferProtocol {
/// Create an empty buffer.
@_inlineable
@_versioned
internal init() {
_storage = _ArrayBridgeStorage(native: _emptyArrayStorage)
}
@_inlineable
@_versioned // FIXME(abi): Used from tests
internal init(nsArray: _NSArrayCore) {
_sanityCheck(_isClassOrObjCExistential(Element.self))
@@ -40,6 +43,8 @@ internal struct _ArrayBuffer<Element> : _ArrayBufferProtocol {
///
/// - Precondition: The elements actually have dynamic type `U`, and `U`
/// is a class or `@objc` existential.
@_inlineable
@_versioned
internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> {
_sanityCheck(_isClassOrObjCExistential(Element.self))
_sanityCheck(_isClassOrObjCExistential(U.self))
@@ -48,6 +53,8 @@ internal struct _ArrayBuffer<Element> : _ArrayBufferProtocol {
/// The spare bits that are set when a native array needs deferred
/// element type checking.
@_inlineable
@_versioned
internal var deferredTypeCheckMask: Int { return 1 }
/// Returns an `_ArrayBuffer<U>` containing the same elements,
@@ -55,6 +62,8 @@ internal struct _ArrayBuffer<Element> : _ArrayBufferProtocol {
///
/// - Precondition: `U` is a class or `@objc` existential derived from
/// `Element`.
@_inlineable
@_versioned
internal func downcast<U>(
toBufferWithDeferredTypeCheckOf _: U.Type
) -> _ArrayBuffer<U> {
@@ -70,12 +79,16 @@ internal struct _ArrayBuffer<Element> : _ArrayBufferProtocol {
native: _native._storage, bits: deferredTypeCheckMask))
}
@_inlineable
@_versioned
internal var needsElementTypeCheck: Bool {
// NSArray's need an element typecheck when the element type isn't AnyObject
return !_isNativeTypeChecked && !(AnyObject.self is Element.Type)
}
//===--- private --------------------------------------------------------===//
@_inlineable
@_versioned
internal init(storage: _ArrayBridgeStorage) {
_storage = storage
}
@@ -86,17 +99,23 @@ internal struct _ArrayBuffer<Element> : _ArrayBufferProtocol {
extension _ArrayBuffer {
/// Adopt the storage of `source`.
@_inlineable
@_versioned
internal init(_buffer source: NativeBuffer, shiftedToStartIndex: Int) {
_sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
_storage = _ArrayBridgeStorage(native: source._storage)
}
/// `true`, if the array is native and does not need a deferred type check.
@_inlineable
@_versioned
internal var arrayPropertyIsNativeTypeChecked: Bool {
return _isNativeTypeChecked
}
/// Returns `true` iff this buffer's storage is uniquely-referenced.
@_inlineable
@_versioned
internal mutating func isUniquelyReferenced() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferenced_native_noSpareBits()
@@ -106,6 +125,8 @@ extension _ArrayBuffer {
/// Returns `true` iff this buffer's storage is either
/// uniquely-referenced or pinned.
@_inlineable
@_versioned
internal mutating func isUniquelyReferencedOrPinned() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferencedOrPinned_native_noSpareBits()
@@ -116,6 +137,7 @@ extension _ArrayBuffer {
/// Convert to an NSArray.
///
/// O(1) if the element type is bridged verbatim, O(*n*) otherwise.
@_inlineable
@_versioned // FIXME(abi): Used from tests
internal func _asCocoaArray() -> _NSArrayCore {
return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative
@@ -125,6 +147,8 @@ extension _ArrayBuffer {
/// `_ContiguousArrayBuffer` that can be grown in-place to allow the self
/// buffer store minimumCapacity elements, returns that buffer.
/// Otherwise, returns `nil`.
@_inlineable
@_versioned
internal mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int)
-> NativeBuffer? {
if _fastPath(isUniquelyReferenced()) {
@@ -136,10 +160,14 @@ extension _ArrayBuffer {
return nil
}
@_inlineable
@_versioned
internal mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
@_inlineable
@_versioned
internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool {
return isUniquelyReferencedOrPinned()
}
@@ -147,6 +175,8 @@ extension _ArrayBuffer {
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@_inlineable
@_versioned
internal func requestNativeBuffer() -> NativeBuffer? {
if !_isClassOrObjCExistential(Element.self) {
return _native
@@ -158,6 +188,8 @@ extension _ArrayBuffer {
// checks one element. The reason for this is that the ARC optimizer does not
// handle loops atm. and so can get blocked by the presence of a loop (over
// the range). This loop is not necessary for a single element access.
@_inlineable
@_versioned
@inline(never)
internal func _typeCheckSlowPath(_ index: Int) {
if _fastPath(_isNative) {
@@ -174,6 +206,8 @@ extension _ArrayBuffer {
}
}
@_inlineable
@_versioned
internal func _typeCheck(_ subRange: Range<Int>) {
if !_isClassOrObjCExistential(Element.self) {
return
@@ -192,6 +226,8 @@ extension _ArrayBuffer {
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer "past the end" of the
/// just-initialized memory.
@_inlineable
@_versioned
@discardableResult
internal func _copyContents(
subRange bounds: Range<Int>,
@@ -225,6 +261,8 @@ extension _ArrayBuffer {
/// Returns a `_SliceBuffer` containing the given sub-range of elements in
/// `bounds` from this buffer.
@_inlineable
@_versioned
internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
_typeCheck(bounds)
@@ -277,17 +315,22 @@ extension _ArrayBuffer {
/// A pointer to the first element.
///
/// - Precondition: The elements are known to be stored contiguously.
@_inlineable
@_versioned
internal var firstElementAddress: UnsafeMutablePointer<Element> {
_sanityCheck(_isNative, "must be a native buffer")
return _native.firstElementAddress
}
@_inlineable
@_versioned
internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {
return _fastPath(_isNative) ? firstElementAddress : nil
}
/// The number of elements the buffer stores.
@_inlineable
@_versioned
internal var count: Int {
@inline(__always)
get {
@@ -305,6 +348,8 @@ extension _ArrayBuffer {
/// wasNative == _isNative in the absence of inout violations.
/// Because the optimizer can hoist the original check it might have
/// been invalidated by illegal user code.
@_inlineable
@_versioned
internal func _checkInoutAndNativeBounds(_ index: Int, wasNative: Bool) {
_precondition(
_isNative == wasNative,
@@ -323,6 +368,8 @@ extension _ArrayBuffer {
/// wasNativeTypeChecked == _isNativeTypeChecked in the absence of
/// inout violations. Because the optimizer can hoist the original
/// check it might have been invalidated by illegal user code.
@_inlineable
@_versioned
internal func _checkInoutAndNativeTypeCheckedBounds(
_ index: Int, wasNativeTypeChecked: Bool
) {
@@ -336,10 +383,13 @@ extension _ArrayBuffer {
}
/// The number of elements the buffer can store without reallocation.
@_inlineable
@_versioned
internal var capacity: Int {
return _fastPath(_isNative) ? _native.capacity : _nonNative.count
}
@_inlineable
@_versioned
@inline(__always)
internal func getElement(_ i: Int, wasNativeTypeChecked: Bool) -> Element {
@@ -349,6 +399,7 @@ extension _ArrayBuffer {
return unsafeBitCast(_getElementSlowPath(i), to: Element.self)
}
@_inlineable
@_versioned
@inline(never)
internal func _getElementSlowPath(_ i: Int) -> AnyObject {
@@ -377,6 +428,8 @@ extension _ArrayBuffer {
}
/// Get or set the value of the ith element.
@_inlineable
@_versioned
internal subscript(i: Int) -> Element {
get {
return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked)
@@ -399,6 +452,8 @@ extension _ArrayBuffer {
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage. If no such storage exists, it is
/// created on-demand.
@_inlineable
@_versioned
internal func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
@@ -414,6 +469,8 @@ extension _ArrayBuffer {
/// over the underlying contiguous storage.
///
/// - Precondition: Such contiguous storage exists or the buffer is empty.
@_inlineable
@_versioned
internal mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
@@ -427,6 +484,8 @@ extension _ArrayBuffer {
}
/// An object that keeps the elements stored in this buffer alive.
@_inlineable
@_versioned
internal var owner: AnyObject {
return _fastPath(_isNative) ? _native._storage : _nonNative
}
@@ -434,6 +493,8 @@ extension _ArrayBuffer {
/// An object that keeps the elements stored in this buffer alive.
///
/// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`.
@_inlineable
@_versioned
internal var nativeOwner: AnyObject {
_sanityCheck(_isNative, "Expect a native array")
return _native._storage
@@ -442,6 +503,8 @@ extension _ArrayBuffer {
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
@_inlineable
@_versioned
internal var identity: UnsafeRawPointer {
if _isNative {
return _native.identity
@@ -455,6 +518,8 @@ extension _ArrayBuffer {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
@_inlineable
@_versioned
internal var startIndex: Int {
return 0
}
@@ -464,6 +529,8 @@ extension _ArrayBuffer {
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `index(after:)`.
@_inlineable
@_versioned
internal var endIndex: Int {
return count
}
@@ -474,6 +541,7 @@ extension _ArrayBuffer {
internal typealias Storage = _ContiguousArrayStorage<Element>
internal typealias NativeBuffer = _ContiguousArrayBuffer<Element>
@_inlineable
@_versioned
internal var _isNative: Bool {
if !_isClassOrObjCExistential(Element.self) {
@@ -484,6 +552,8 @@ extension _ArrayBuffer {
}
/// `true`, if the array is native and does not need a deferred type check.
@_inlineable
@_versioned
internal var _isNativeTypeChecked: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
@@ -495,6 +565,7 @@ extension _ArrayBuffer {
/// Our native representation.
///
/// - Precondition: `_isNative`.
@_inlineable
@_versioned
internal var _native: NativeBuffer {
return NativeBuffer(
@@ -505,11 +576,13 @@ extension _ArrayBuffer {
/// Fast access to the native representation.
///
/// - Precondition: `_isNativeTypeChecked`.
@_inlineable
@_versioned
internal var _nativeTypeChecked: NativeBuffer {
return NativeBuffer(_storage.nativeInstance_noSpareBits)
}
@_inlineable
@_versioned
internal var _nonNative: _NSArrayCore {
@inline(__always)

View File

@@ -129,10 +129,14 @@ internal protocol _ArrayBufferProtocol
extension _ArrayBufferProtocol {
@_inlineable
@_versioned
internal var subscriptBaseAddress: UnsafeMutablePointer<Element> {
return firstElementAddress
}
@_inlineable
@_versioned
internal mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
with newCount: Int,

View File

@@ -26,7 +26,12 @@
/// This type is used as a result of the _checkSubscript call to associate the
/// call with the array access call it guards.
public struct _DependenceToken {}
@_fixed_layout
public struct _DependenceToken {
@_inlineable
public init() {
}
}
%{
arrayTypes = [
@@ -451,9 +456,7 @@ if True:
}%
${SelfDocComment}
% if Self != 'ArraySlice':
@_fixed_layout
%end
public struct ${Self}<Element>
: RandomAccessCollection,
MutableCollection,
@@ -473,6 +476,7 @@ public struct ${Self}<Element>
/// For an instance of `${Self}`, `startIndex` is always zero. If the array
/// is empty, `startIndex` is equal to `endIndex`.
%end
@_inlineable
public var startIndex: Int {
%if Self == 'ArraySlice':
return _buffer.startIndex
@@ -500,10 +504,14 @@ public struct ${Self}<Element>
%if Self == 'ArraySlice':
return _buffer.endIndex
%else:
return _getCount()
@_inlineable
get {
return _getCount()
}
%end
}
@_inlineable
public func index(after i: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
@@ -513,6 +521,7 @@ public struct ${Self}<Element>
return i + 1
}
@_inlineable
public func formIndex(after i: inout Int) {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
@@ -522,6 +531,7 @@ public struct ${Self}<Element>
i += 1
}
@_inlineable
public func index(before i: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
@@ -531,6 +541,7 @@ public struct ${Self}<Element>
return i - 1
}
@_inlineable
public func formIndex(before i: inout Int) {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
@@ -560,6 +571,7 @@ public struct ${Self}<Element>
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
@_inlineable
public func index(_ i: Int, offsetBy n: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
@@ -610,6 +622,7 @@ public struct ${Self}<Element>
/// the method returns `nil`.
///
/// - SeeAlso: `index(_:offsetBy:)`, `formIndex(_:offsetBy:limitedBy:)`
@_inlineable
public func index(
_ i: Int, offsetBy n: Int, limitedBy limit: Int
) -> Int? {
@@ -632,6 +645,7 @@ public struct ${Self}<Element>
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`.
@_inlineable
public func distance(from start: Int, to end: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for Array performance. The optimizer is not
@@ -641,10 +655,12 @@ public struct ${Self}<Element>
return end - start
}
@_inlineable
public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) {
// NOTE: This method is a no-op for performance reasons.
}
@_inlineable
public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) {
// NOTE: This method is a no-op for performance reasons.
}
@@ -672,6 +688,7 @@ public struct ${Self}<Element>
/// If the array uses a bridged `NSArray` instance as its storage, the
/// efficiency is unspecified.
%end
@_inlineable
public subscript(index: Int) -> Element {
get {
// This call may be hoisted or eliminated by the optimizer. If
@@ -723,6 +740,7 @@ public struct ${Self}<Element>
///
/// - SeeAlso: `ArraySlice`
%end
@_inlineable
public subscript(bounds: Range<Int>) -> ArraySlice<Element> {
get {
_checkIndex(bounds.lowerBound)
@@ -744,28 +762,37 @@ public struct ${Self}<Element>
/// type check. May be hoisted by the optimizer, which means its
/// results may be stale by the time they are used if there is an
/// inout violation in user code.
@_inlineable
@_semantics("array.props.isNativeTypeChecked")
public // @testable
func _hoistableIsNativeTypeChecked() -> Bool {
return _buffer.arrayPropertyIsNativeTypeChecked
}
@_inlineable
@_versioned
@_semantics("array.get_count")
internal func _getCount() -> Int {
return _buffer.count
}
@_inlineable
@_versioned
@_semantics("array.get_capacity")
internal func _getCapacity() -> Int {
return _buffer.capacity
}
/// - Precondition: The array has a native buffer.
@_inlineable
@_versioned
@_semantics("array.owner")
internal func _getOwnerWithSemanticLabel_native() -> Builtin.NativeObject {
return Builtin.unsafeCastToNativeObject(_buffer.nativeOwner)
}
/// - Precondition: The array has a native buffer.
@_versioned
@inline(__always)
internal func _getOwner_native() -> Builtin.NativeObject {
#if _runtime(_ObjC)
@@ -785,6 +812,8 @@ public struct ${Self}<Element>
// FIXME(ABI)#12 : move to an initializer on _Buffer.
// Make sure the compiler does not inline _copyBuffer to reduce code size.
@inline(never)
@_inlineable
@_versioned
static internal func _copyBuffer(_ buffer: inout _Buffer) {
let newBuffer = _ContiguousArrayBuffer<Element>(
_uninitializedCount: buffer.count, minimumCapacity: buffer.count)
@@ -795,6 +824,8 @@ public struct ${Self}<Element>
_buffer: newBuffer, shiftedToStartIndex: buffer.startIndex)
}
@_inlineable
@_versioned
@_semantics("array.make_mutable")
internal mutating func _makeMutableAndUnique() {
if _slowPath(!_buffer.isMutableAndUniquelyReferenced()) {
@@ -802,6 +833,8 @@ public struct ${Self}<Element>
}
}
@_inlineable
@_versioned
@_semantics("array.make_mutable")
internal mutating func _makeMutableAndUniqueOrPinned() {
if _slowPath(!_buffer.isMutableAndUniquelyReferencedOrPinned()) {
@@ -812,6 +845,7 @@ public struct ${Self}<Element>
/// Check that the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@_versioned
@inline(__always)
internal func _checkSubscript_native(_ index: Int) {
% if Self != 'Array':
@@ -823,6 +857,7 @@ public struct ${Self}<Element>
/// Check that the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@_inlineable
@_semantics("array.check_subscript")
public // @testable
func _checkSubscript(
@@ -842,6 +877,8 @@ public struct ${Self}<Element>
}
/// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`.
@_inlineable
@_versioned
@_semantics("array.check_index")
internal func _checkIndex(_ index: Int) {
_precondition(index <= endIndex, "${Self} index is out of range")
@@ -867,6 +904,8 @@ public struct ${Self}<Element>
#endif
}
@_inlineable
@_versioned
@_semantics("array.get_element_address")
internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> {
return _buffer.subscriptBaseAddress + index
@@ -886,6 +925,9 @@ public struct ${Self}<Element>
/// Initialization from an existing buffer does not have "array.init"
/// semantics because the caller may retain an alias to buffer.
@_inlineable
@_versioned
internal init(_buffer: _Buffer) {
self._buffer = _buffer
}
@@ -893,6 +935,8 @@ public struct ${Self}<Element>
%if Self == 'ArraySlice':
/// Initialization from an existing buffer does not have "array.init"
/// semantics because the caller may retain an alias to buffer.
@_inlineable
@_versioned
internal init(_buffer buffer: _ContiguousArrayBuffer<Element>) {
self.init(_buffer: _Buffer(_buffer: buffer, shiftedToStartIndex: 0))
}
@@ -918,6 +962,7 @@ extension ${Self} : ExpressibleByArrayLiteral {
/// let ingredients = ["cocoa beans", "sugar", "cocoa butter", "salt"]
///
/// - Parameter elements: A variadic list of elements of the new array.
@_inlineable
public init(arrayLiteral elements: Element...) {
self = elements
}
@@ -936,6 +981,7 @@ extension ${Self} : ExpressibleByArrayLiteral {
/// ["cocoa beans", "sugar", "cocoa butter", "salt"]
///
/// - Parameter elements: A variadic list of elements of the new array.
@_inlineable
public init(arrayLiteral elements: Element...) {
self.init(_buffer: ContiguousArray(elements)._buffer)
}
@@ -972,6 +1018,7 @@ func _allocateUninitializedArray<Element>(_ builtinCount: Builtin.Word)
// Referenced by the compiler to deallocate array literals on the
// error path.
@_inlineable
@_semantics("array.dealloc_uninitialized")
public func _deallocateUninitialized${Self}<Element>(
_ array: ${Self}<Element>
@@ -994,6 +1041,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// emptyArray = []
/// print(emptyArray.isEmpty)
/// // Prints "true"
@_inlineable
@_semantics("array.init")
public init() {
_buffer = _Buffer()
@@ -1033,6 +1081,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"
///
/// - Parameter s: The sequence of elements to turn into an array.
@_inlineable
public init<S : Sequence>(_ s: S)
where S.Iterator.Element == Element {
@@ -1056,6 +1105,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the value passed in the
/// `repeating` parameter. `count` must be zero or greater.
@_inlineable
@_semantics("array.init")
public init(repeating repeatedValue: Element, count: Int) {
var p: UnsafeMutablePointer<Element>
@@ -1066,6 +1116,8 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
}
}
@_inlineable
@_versioned
@inline(never)
internal static func _allocateBufferUninitialized(
minimumCapacity: Int
@@ -1076,6 +1128,8 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
}
/// Construct a ${Self} of `count` uninitialized elements.
@_inlineable
@_versioned
internal init(_uninitializedCount count: Int) {
_precondition(count >= 0, "Can't construct ${Self} with count < 0")
// Note: Sinking this constructor into an else branch below causes an extra
@@ -1094,6 +1148,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// Entry point for `Array` literal construction; builds and returns
/// a ${Self} of `count` uninitialized elements.
@_inlineable
@_versioned
@_semantics("array.uninitialized")
internal static func _allocateUninitialized(
@@ -1110,6 +1165,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// first element.
///
/// - Precondition: `storage is _ContiguousArrayStorage`.
@_inlineable
@_versioned
@_semantics("array.uninitialized")
internal static func _adoptStorage(
@@ -1128,6 +1184,8 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// Entry point for aborting literal construction: deallocates
/// a ${Self} containing only uninitialized elements.
@_inlineable
@_versioned
internal mutating func _deallocateUninitialized() {
// Set the count to zero and just release as normal.
// Somewhat of a hack.
@@ -1136,6 +1194,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
%end
/// The number of elements in the array.
@_inlineable
public var count: Int {
return _getCount()
}
@@ -1165,11 +1224,13 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10))
/// // numbers.count == 10
/// // numbers.capacity == 12
@_inlineable
public var capacity: Int {
return _getCapacity()
}
/// An object that guarantees the lifetime of this array's elements.
@_inlineable
public // @testable
var _owner: AnyObject? {
return _buffer.owner
@@ -1177,11 +1238,14 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
@_inlineable
public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? {
return _buffer.firstElementAddressIfContiguous
}
%if Self != 'Array': # // Array does not necessarily have contiguous storage
@_inlineable
@_versioned
internal var _baseAddress: UnsafeMutablePointer<Element> {
return _buffer.firstElementAddress
}
@@ -1258,6 +1322,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// - Parameter minimumCapacity: The requested number of elements to store.
///
/// - Complexity: O(*n*), where *n* is the number of elements in the array.
@_inlineable
@_semantics("array.mutate_unknown")
public mutating func reserveCapacity(_ minimumCapacity: Int) {
if _buffer.requestUniqueMutableBackingBuffer(
@@ -1278,6 +1343,8 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// Copy the contents of the current buffer to a new unique mutable buffer.
/// The count of the new buffer is set to `oldCount`, the capacity of the
/// new buffer is big enough to hold 'oldCount' + 1 elements.
@_versioned
@_inlineable
@inline(never)
internal mutating func _copyToNewBuffer(oldCount: Int) {
let newCount = oldCount + 1
@@ -1287,6 +1354,8 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
&newBuffer, oldCount, 0, _IgnorePointer())
}
@_inlineable
@_versioned
@_semantics("array.make_mutable")
internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() {
if _slowPath(!_buffer.isMutableAndUniquelyReferenced()) {
@@ -1294,6 +1363,8 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
}
}
@_inlineable
@_versioned
@_semantics("array.mutate_unknown")
internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) {
_sanityCheck(_buffer.isMutableAndUniquelyReferenced())
@@ -1303,6 +1374,8 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
}
}
@_inlineable
@_versioned
@_semantics("array.mutate_unknown")
internal mutating func _appendElementAssumeUniqueAndCapacity(
_ oldCount: Int,
@@ -1337,6 +1410,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// - Complexity: Amortized O(1) over many additions. If the array uses a
/// bridged `NSArray` instance as its storage, the efficiency is
/// unspecified.
@_inlineable
public mutating func append(_ newElement: Element) {
_makeUniqueAndReserveCapacityIfNotUnique()
let oldCount = _getCount()
@@ -1358,6 +1432,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// - Parameter newElements: The elements to append to the array.
///
/// - Complexity: O(*n*), where *n* is the length of the resulting array.
@_inlineable
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Iterator.Element == Element {
@@ -1408,6 +1483,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// // Prints "[1.1, 1.5, 2.9, 1.2, 1.5, 1.3]"
///
/// - Returns: The element that was removed.
@_inlineable
public mutating func _customRemoveLast() -> Element? {
_precondition(count > 0, "can't removeLast from an empty ${Self}")
// FIXME(performance): if `self` is uniquely referenced, we should remove
@@ -1443,6 +1519,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// property.
///
/// - Complexity: O(*n*), where *n* is the length of the array.
@_inlineable
public mutating func insert(_ newElement: Element, at i: Int) {
_checkIndex(i)
self.replaceSubrange(i..<i, with: CollectionOfOne(newElement))
@@ -1463,6 +1540,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// - Returns: The element at the specified index.
///
/// - Complexity: O(*n*), where *n* is the length of the array.
@_inlineable
@discardableResult
public mutating func remove(at index: Int) -> Element {
let result = self[index]
@@ -1477,6 +1555,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
/// `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the array.
@_inlineable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
if !keepCapacity {
_buffer = _Buffer()
@@ -1488,6 +1567,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
//===--- algorithms -----------------------------------------------------===//
@_inlineable
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (UnsafeMutablePointer<Element>, Int) throws -> R
) rethrows -> R? {
@@ -1498,6 +1578,7 @@ extension ${Self} : RangeReplaceableCollection, _ArrayProtocol {
}
}
@_inlineable
public func _copyToContiguousArray() -> ContiguousArray<Element> {
if let n = _buffer.requestNativeBuffer() {
return ContiguousArray(_buffer: n)
@@ -1599,6 +1680,7 @@ extension ${Self} {
/// - Returns: The return value of the `body` closure parameter, if any.
///
/// - SeeAlso: `withUnsafeMutableBufferPointer`, `UnsafeBufferPointer`
@_inlineable
public func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
@@ -1686,6 +1768,7 @@ extension ${Self} {
return try body(&inoutBufferPointer)
}
@_inlineable
public func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Iterator.Element>
) -> (Iterator,UnsafeMutableBufferPointer<Iterator.Element>.Index) {
@@ -1718,9 +1801,13 @@ extension ${Self} {
}
%end
@_versioned
@_fixed_layout
internal struct _InitializeMemoryFromCollection<
C: Collection
> : _PointerFunction {
@_inlineable
@_versioned
func call(_ rawMemory: UnsafeMutablePointer<C.Iterator.Element>, count: Int) {
var p = rawMemory
var q = newValues.startIndex
@@ -1732,14 +1819,19 @@ internal struct _InitializeMemoryFromCollection<
_expectEnd(of: newValues, is: q)
}
@_inlineable
@_versioned
init(_ newValues: C) {
self.newValues = newValues
}
@_versioned
var newValues: C
}
extension _ArrayBufferProtocol {
@_inlineable
@_versioned
@inline(never)
internal mutating func _arrayOutOfPlaceReplace<C : Collection>(
_ bounds: Range<Int>,
@@ -1763,12 +1855,16 @@ extension _ArrayBufferProtocol {
/// A _debugPrecondition check that `i` has exactly reached the end of
/// `s`. This test is never used to ensure memory safety; that is
/// always guaranteed by measuring `s` once and re-using that value.
@_inlineable
@_versioned
internal func _expectEnd<C : Collection>(of s: C, is i: C.Index) {
_debugPrecondition(
i == s.endIndex,
"invalid Collection: count differed in successive traversals")
}
@_inlineable
@_versioned
internal func _growArrayCapacity(_ capacity: Int) -> Int {
return capacity * 2
}
@@ -1808,6 +1904,7 @@ extension ${Self} {
/// - Complexity: O(`subrange.count`) if you are replacing a suffix of the
/// array with an empty collection; otherwise, O(*n*), where *n* is the
/// length of the array.
@_inlineable
@_semantics("array.mutate_unknown")
public mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
@@ -1850,6 +1947,8 @@ extension _ArrayBufferProtocol {
/// The formula used to compute the new buffers capacity is:
/// max(requiredCapacity, source.capacity) if newCount <= source.capacity
/// max(requiredCapacity, _growArrayCapacity(source.capacity)) otherwise
@_inlineable
@_versioned
@inline(never)
internal func _forceCreateUniqueMutableBuffer(
newCount: Int, requiredCapacity: Int
@@ -1865,6 +1964,8 @@ extension _ArrayBufferProtocol {
/// The formula used to compute the new buffers capacity is:
/// max(minNewCapacity, source.capacity) if minNewCapacity <= source.capacity
/// max(minNewCapacity, _growArrayCapacity(source.capacity)) otherwise
@_inlineable
@_versioned
@inline(never)
internal func _forceCreateUniqueMutableBuffer(
countForNewBuffer: Int, minNewCapacity: Int
@@ -1881,6 +1982,8 @@ extension _ArrayBufferProtocol {
/// The formula used to compute the new capacity is:
/// max(requiredCapacity, source.capacity) if minNewCapacity <= source.capacity
/// max(requiredCapacity, _growArrayCapacity(source.capacity)) otherwise
@_inlineable
@_versioned
internal func _forceCreateUniqueMutableBufferImpl(
countForBuffer: Int, minNewCapacity: Int,
requiredCapacity: Int
@@ -1898,6 +2001,7 @@ extension _ArrayBufferProtocol {
}
}
@_versioned
internal protocol _PointerFunction {
associatedtype Element
func call(_: UnsafeMutablePointer<Element>, count: Int)
@@ -1911,6 +2015,8 @@ extension _ArrayBufferProtocol {
///
/// As an optimization, may move elements out of source rather than
/// copying when it isUniquelyReferenced.
@_inlineable
@_versioned
@inline(never)
internal mutating func _arrayOutOfPlaceUpdate<Initializer>(
_ dest: inout _ContiguousArrayBuffer<Element>,
@@ -1980,13 +2086,23 @@ extension _ArrayBufferProtocol {
}
}
@_versioned
@_fixed_layout
internal struct _IgnorePointer<T> : _PointerFunction {
@_inlineable
@_versioned
internal func call(_: UnsafeMutablePointer<T>, count: Int) {
_sanityCheck(count == 0)
}
@_versioned
@_inlineable
init() {
}
}
extension _ArrayBufferProtocol {
@_inlineable
@_versioned
@inline(never)
internal mutating func _outlinedMakeUniqueBuffer(bufferCount: Int) {
@@ -2002,6 +2118,8 @@ extension _ArrayBufferProtocol {
}
/// Append items from `newItems` to a buffer.
@_inlineable
@_versioned
internal mutating func _arrayAppendSequence<S : Sequence>(
_ newItems: S
) where S.Iterator.Element == Element {
@@ -2047,6 +2165,7 @@ extension _ArrayBufferProtocol {
// ArraySlice<Int> and Array<Int>.
/// Returns `true` if these arrays contain the same elements.
@_inlineable
public func == <Element : Equatable>(
lhs: ${Self}<Element>, rhs: ${Self}<Element>
) -> Bool {
@@ -2091,6 +2210,7 @@ public func == <Element : Equatable>(
}
/// Returns `true` if the arrays do not contain the same elements.
@_inlineable
public func != <Element : Equatable>(
lhs: ${Self}<Element>, rhs: ${Self}<Element>
) -> Bool {
@@ -2137,6 +2257,7 @@ extension ${Self} {
/// - Returns: The return value of the `body` closure parameter, if any.
///
/// - SeeAlso: `withUnsafeBytes`, `UnsafeMutableRawBufferPointer`
@_inlineable
public mutating func withUnsafeMutableBytes<R>(
_ body: (UnsafeMutableRawBufferPointer) throws -> R
) rethrows -> R {
@@ -2172,6 +2293,7 @@ extension ${Self} {
/// - Returns: The return value of the `body` closure parameter, if any.
///
/// - SeeAlso: `withUnsafeMutableBytes`, `UnsafeRawBufferPointer`
@_inlineable
public func withUnsafeBytes<R>(
_ body: (UnsafeRawBufferPointer) throws -> R
) rethrows -> R {
@@ -2184,6 +2306,7 @@ extension ${Self} {
#if _runtime(_ObjC)
extension Array {
@_inlineable
public // @SPI(Foundation)
func _bridgeToObjectiveCImpl() -> AnyObject {
return _buffer._asCocoaArray()
@@ -2194,6 +2317,7 @@ extension Array {
/// Returns `nil` otherwise.
// Note: this function exists here so that Foundation doesn't have
// to know Array's implementation details.
@_inlineable
public static func _bridgeFromObjectiveCAdoptingNativeStorageOf(
_ source: AnyObject
) -> Array? {
@@ -2212,6 +2336,7 @@ extension Array {
/// * it is statically known that the given `NSArray` is immutable;
/// * `Element` is bridged verbatim to Objective-C (i.e.,
/// is a reference type).
@_inlineable
public init(_immutableCocoaArray: _NSArrayCore) {
self = Array(_buffer: _ArrayBuffer(nsArray: _immutableCocoaArray))
}
@@ -2227,6 +2352,7 @@ extension Array {
/// - Complexity: O(*n*) if the array is bridged, where *n* is the length
/// of the array; otherwise, O(1).
/// - SeeAlso: `removeLast()`
@_inlineable
public mutating func popLast() -> Element? {
guard !isEmpty else { return nil }
return removeLast()
@@ -2241,6 +2367,7 @@ extension ContiguousArray {
///
/// - Complexity: O(1)
/// - SeeAlso: `removeLast()`
@_inlineable
public mutating func popLast() -> Element? {
guard !isEmpty else { return nil }
return removeLast()
@@ -2248,6 +2375,7 @@ extension ContiguousArray {
}
extension ArraySlice {
@_inlineable
public // @testable
init(_startIndex: Int) {
self.init(

View File

@@ -365,6 +365,7 @@ public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */>
///
/// - Precondition: the pointee has been initialized with an instance of type
/// `Pointee`.
@_inlineable
public var pointee: Pointee {
/// Retrieve the value the pointer points to.
@_transparent get {
@@ -447,6 +448,7 @@ public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */>
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_versioned
@_transparent
init<U>(_ from: UnsafePointer<U>) {
self._rawValue = from._rawValue
@@ -461,6 +463,7 @@ public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */>
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_versioned
@_transparent
init?<U>(_ from: UnsafePointer<U>?) {
guard let unwrapped = from else { return nil }
@@ -514,6 +517,7 @@ extension UnsafeRawPointer {
extension AutoreleasingUnsafeMutablePointer : CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
@_inlineable
public var debugDescription: String {
return _rawPointerToString(_rawValue)
}
@@ -527,6 +531,8 @@ public func == <Pointee>(
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
@_fixed_layout
@_versioned
internal struct _CocoaFastEnumerationStackBuf {
// Clang uses 16 pointers. So do we.
internal var _item0: UnsafeRawPointer?
@@ -551,6 +557,7 @@ internal struct _CocoaFastEnumerationStackBuf {
return 16
}
@_versioned
internal init() {
_item0 = nil
_item1 = _item0

View File

@@ -120,21 +120,29 @@ internal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject {
return unsafeBitCast(x, to: AnyObject.self)
}
@_inlineable
@_versioned
@_transparent
func == (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_inlineable
@_versioned
@_transparent
func != (lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool {
return !(lhs == rhs)
}
@_inlineable
@_versioned
@_transparent
func == (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@_inlineable
@_versioned
@_transparent
func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return !(lhs == rhs)
@@ -142,12 +150,14 @@ func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
/// Returns `true` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
@_inlineable
public func == (t0: Any.Type?, t1: Any.Type?) -> Bool {
return unsafeBitCast(t0, to: Int.self) == unsafeBitCast(t1, to: Int.self)
}
/// Returns `false` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.
@_inlineable
public func != (t0: Any.Type?, t1: Any.Type?) -> Bool {
return !(t0 == t1)
}

View File

@@ -210,6 +210,8 @@ func _memcpy(
///
/// The memory regions `source..<source + count` and
/// `dest..<dest + count` may overlap.
@_versioned
@_inlineable
func _memmove(
dest destination: UnsafeMutableRawPointer,
src: UnsafeRawPointer,

View File

@@ -13,6 +13,7 @@
// FIXME: swift-3-indexing-model: Generalize all tests to check both
// [Closed]Range and [Closed]CountableRange.
@_versioned
internal enum _ClosedRangeIndexRepresentation<Bound>
where
// FIXME(ABI)#176 (Type checker)
@@ -26,6 +27,7 @@ internal enum _ClosedRangeIndexRepresentation<Bound>
// FIXME(ABI)#23 (Nesting types in generics): should be a nested type in
// `ClosedRange`.
/// A position in a `CountableClosedRange` instance.
@_fixed_layout
public struct ClosedRangeIndex<Bound>
where
// FIXME(ABI)#176 (Type checker)
@@ -36,12 +38,19 @@ public struct ClosedRangeIndex<Bound>
Bound : _Strideable & Comparable,
Bound.Stride : SignedInteger {
/// Creates the "past the end" position.
@_inlineable
@_versioned
internal init() { _value = .pastEnd }
/// Creates a position `p` for which `r[p] == x`.
@_inlineable
@_versioned
internal init(_ x: Bound) { _value = .inRange(x) }
@_versioned
internal var _value: _ClosedRangeIndexRepresentation<Bound>
@_inlineable
@_versioned
internal var _dereferenced: Bound {
switch _value {
case .inRange(let x): return x
@@ -51,6 +60,7 @@ public struct ClosedRangeIndex<Bound>
}
extension ClosedRangeIndex : Comparable {
@_inlineable
public static func == (
lhs: ClosedRangeIndex<Bound>,
rhs: ClosedRangeIndex<Bound>
@@ -65,6 +75,7 @@ extension ClosedRangeIndex : Comparable {
}
}
@_inlineable
public static func < (
lhs: ClosedRangeIndex<Bound>,
rhs: ClosedRangeIndex<Bound>
@@ -83,6 +94,7 @@ extension ClosedRangeIndex : Comparable {
// FIXME(ABI)#175 (Type checker)
// WORKAROUND: needed because of rdar://25584401
/// An iterator over the elements of a `CountableClosedRange` instance.
@_fixed_layout
public struct ClosedRangeIterator<Bound> : IteratorProtocol, Sequence
where
// FIXME(ABI)#176 (Type checker)
@@ -90,15 +102,19 @@ public struct ClosedRangeIterator<Bound> : IteratorProtocol, Sequence
Bound : _Strideable & Comparable,
Bound.Stride : SignedInteger {
@_inlineable
@_versioned
internal init(_range r: CountableClosedRange<Bound>) {
_nextResult = r.lowerBound
_upperBound = r.upperBound
}
@_inlineable
public func makeIterator() -> ClosedRangeIterator {
return self
}
@_inlineable
public mutating func next() -> Bound? {
let r = _nextResult
if let x = r {
@@ -106,7 +122,9 @@ public struct ClosedRangeIterator<Bound> : IteratorProtocol, Sequence
}
return r
}
@_versioned
internal var _nextResult: Bound?
@_versioned
internal let _upperBound: Bound
}
@@ -158,6 +176,7 @@ public struct ClosedRangeIterator<Bound> : IteratorProtocol, Sequence
/// `stride(from:through:by:)` function.
///
/// - SeeAlso: `CountableRange`, `ClosedRange`, `Range`
@_fixed_layout
public struct CountableClosedRange<Bound> : RandomAccessCollection
where
// FIXME(ABI)#176 (Type checker)
@@ -188,21 +207,25 @@ public struct CountableClosedRange<Bound> : RandomAccessCollection
// FIXME(ABI)#175 (Type checker)
// WORKAROUND: needed because of rdar://25584401
@_inlineable
public func makeIterator() -> ClosedRangeIterator<Bound> {
return ClosedRangeIterator(_range: self)
}
/// The position of the first element in the range.
@_inlineable
public var startIndex: ClosedRangeIndex<Bound> {
return ClosedRangeIndex(lowerBound)
}
/// The range's "past the end" position---that is, the position one greater
/// than the last valid subscript argument.
@_inlineable
public var endIndex: ClosedRangeIndex<Bound> {
return ClosedRangeIndex()
}
@_inlineable
public func index(after i: Index) -> Index {
switch i._value {
case .inRange(let x):
@@ -214,6 +237,7 @@ public struct CountableClosedRange<Bound> : RandomAccessCollection
}
}
@_inlineable
public func index(before i: Index) -> Index {
switch i._value {
case .inRange(let x):
@@ -225,6 +249,7 @@ public struct CountableClosedRange<Bound> : RandomAccessCollection
}
}
@_inlineable
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
switch i._value {
case .inRange(let x):
@@ -248,6 +273,7 @@ public struct CountableClosedRange<Bound> : RandomAccessCollection
}
}
@_inlineable
public func distance(from start: Index, to end: Index) -> IndexDistance {
switch (start._value, end._value) {
case let (.inRange(left), .inRange(right)):
@@ -275,17 +301,20 @@ public struct CountableClosedRange<Bound> : RandomAccessCollection
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the range, and must not equal the range's end
/// index.
@_inlineable
public subscript(position: ClosedRangeIndex<Bound>) -> Bound {
// FIXME: swift-3-indexing-model: range checks and tests.
return position._dereferenced
}
@_inlineable
public subscript(bounds: Range<Index>)
-> RandomAccessSlice<CountableClosedRange<Bound>> {
return RandomAccessSlice(base: self, bounds: bounds)
}
// FIXME(ABI)#175 (Type checker)
@_inlineable
public // WORKAROUND: needed because of rdar://25584401
var indices: DefaultRandomAccessIndices<CountableClosedRange<Bound>> {
return DefaultRandomAccessIndices(
@@ -302,11 +331,13 @@ public struct CountableClosedRange<Bound> : RandomAccessCollection
/// to form `CountableClosedRange` instances is preferred.
///
/// - Parameter bounds: A tuple of the lower and upper bounds of the range.
@_inlineable
public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) {
self.lowerBound = bounds.lower
self.upperBound = bounds.upper
}
@_inlineable
public func _customContainsEquatableElement(_ element: Bound) -> Bool? {
return element >= self.lowerBound && element <= self.upperBound
}
@@ -315,6 +346,7 @@ public struct CountableClosedRange<Bound> : RandomAccessCollection
///
/// Because a closed range cannot represent an empty range, this property is
/// always `false`.
@_inlineable
public var isEmpty: Bool {
return false
}
@@ -378,6 +410,7 @@ public struct ClosedRange<
/// - Parameter element: The element to check for containment.
/// - Returns: `true` if `element` is contained in the range; otherwise,
/// `false`.
@_inlineable
public func contains(_ element: Bound) -> Bool {
return element >= self.lowerBound && element <= self.upperBound
}
@@ -386,6 +419,7 @@ public struct ClosedRange<
///
/// Because a closed range cannot represent an empty range, this property is
/// always `false`.
@_inlineable
public var isEmpty: Bool {
return false
}

View File

@@ -25,17 +25,24 @@ import SwiftShims
/// `Collection` conformance. Why not make
/// `_NSArrayCore` conform directly? It's a class, and I
/// don't want to pay for the dynamic dispatch overhead.
@_versioned
@_fixed_layout
internal struct _CocoaArrayWrapper : RandomAccessCollection {
typealias Indices = CountableRange<Int>
@_inlineable
@_versioned
var startIndex: Int {
return 0
}
@_inlineable
@_versioned
var endIndex: Int {
return buffer.count
}
@_inlineable
@_versioned
subscript(i: Int) -> AnyObject {
return buffer.objectAt(i)
}
@@ -50,6 +57,8 @@ internal struct _CocoaArrayWrapper : RandomAccessCollection {
/// is sometimes conservative and may return `nil` even when
/// contiguous storage exists, e.g., if array doesn't have a smart
/// implementation of countByEnumerating.
@_inlineable
@_versioned
func contiguousStorage(
_ subRange: Range<Int>
) -> UnsafeMutablePointer<AnyObject>?
@@ -72,11 +81,13 @@ internal struct _CocoaArrayWrapper : RandomAccessCollection {
: nil
}
@_versioned
@_transparent
init(_ buffer: _NSArrayCore) {
self.buffer = buffer
}
@_versioned
var buffer: _NSArrayCore
}
#endif

View File

@@ -370,6 +370,7 @@ public protocol _Indexable : _IndexableBase {
/// }
/// // Prints "15.0"
/// // Prints "20.0"
@_fixed_layout
public struct IndexingIterator<
Elements : _IndexableBase
// FIXME(ABI)#97 (Recursive Protocol Constraints):
@@ -377,6 +378,7 @@ public struct IndexingIterator<
// Elements : Collection
> : IteratorProtocol, Sequence {
@_inlineable
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements) {
@@ -408,14 +410,16 @@ public struct IndexingIterator<
///
/// - Returns: The next element in the underlying sequence if a next element
/// exists; otherwise, `nil`.
@_inlineable
public mutating func next() -> Elements._Element? {
if _position == _elements.endIndex { return nil }
let element = _elements[_position]
_elements.formIndex(after: &_position)
return element
}
@_versioned
internal let _elements: Elements
@_versioned
internal var _position: Elements.Index
}
@@ -980,6 +984,7 @@ extension _Indexable {
i = index(after: i)
}
@_inlineable
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
@@ -990,6 +995,7 @@ extension _Indexable {
"out of bounds: index >= endIndex")
}
@_inlineable
public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
@@ -1000,6 +1006,7 @@ extension _Indexable {
"out of bounds: index > endIndex")
}
@_inlineable
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
@@ -1042,6 +1049,7 @@ extension _Indexable {
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@_inlineable
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
return self._advanceForward(i, by: n)
}
@@ -1087,6 +1095,7 @@ extension _Indexable {
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@_inlineable
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
@@ -1107,6 +1116,7 @@ extension _Indexable {
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@_inlineable
public func formIndex(_ i: inout Index, offsetBy n: IndexDistance) {
i = index(i, offsetBy: n)
}
@@ -1133,6 +1143,7 @@ extension _Indexable {
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@_inlineable
public func formIndex(
_ i: inout Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Bool {
@@ -1160,6 +1171,7 @@ extension _Indexable {
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
@_inlineable
public func distance(from start: Index, to end: Index) -> IndexDistance {
_precondition(start <= end,
"Only BidirectionalCollections can have end come before start")
@@ -1174,6 +1186,8 @@ extension _Indexable {
}
/// Do not use this method directly; call advanced(by: n) instead.
@_inlineable
@_versioned
@inline(__always)
internal func _advanceForward(_ i: Index, by n: IndexDistance) -> Index {
_precondition(n >= 0,
@@ -1187,6 +1201,8 @@ extension _Indexable {
}
/// Do not use this method directly; call advanced(by: n, limit) instead.
@_inlineable
@_versioned
@inline(__always)
internal
func _advanceForward(
@@ -1211,6 +1227,7 @@ extension _Indexable {
/// `IndexingIterator<Self>`.
extension Collection where Iterator == IndexingIterator<Self> {
/// Returns an iterator over the elements of the collection.
@inline(__always)
public func makeIterator() -> IndexingIterator<Self> {
return IndexingIterator(_elements: self)
}
@@ -1242,6 +1259,7 @@ extension Collection where SubSequence == Slice<Self> {
/// the range must be valid indices of the collection.
///
/// - Complexity: O(1)
@_inlineable
public subscript(bounds: Range<Index>) -> Slice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
@@ -1255,6 +1273,7 @@ extension Collection where SubSequence == Self {
/// not empty; otherwise, `nil`.
///
/// - Complexity: O(1)
@_inlineable
public mutating func popFirst() -> Iterator.Element? {
// TODO: swift-3-indexing-model - review the following
guard !isEmpty else { return nil }
@@ -1283,6 +1302,7 @@ extension Collection {
/// // Prints "Hi ho, Silver!")
///
/// - Complexity: O(1)
@_inlineable
public var isEmpty: Bool {
return startIndex == endIndex
}
@@ -1296,6 +1316,7 @@ extension Collection {
/// print(firstNumber)
/// }
/// // Prints "10"
@_inlineable
public var first: Iterator.Element? {
// NB: Accessing `startIndex` may not be O(1) for some lazy collections,
// so instead of testing `isEmpty` and then returning the first element,
@@ -1318,6 +1339,7 @@ extension Collection {
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@_inlineable
public var underestimatedCount: Int {
// TODO: swift-3-indexing-model - review the following
return numericCast(count)
@@ -1333,6 +1355,7 @@ extension Collection {
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@_inlineable
public var count: IndexDistance {
return distance(from: startIndex, to: endIndex)
}
@@ -1348,6 +1371,7 @@ extension Collection {
/// `Optional(Optional(index))` if an element was found.
///
/// - Complexity: O(`count`).
@_inlineable
public // dispatching
func _customIndexOfEquatableElement(_: Iterator.Element) -> Index?? {
return nil
@@ -1376,6 +1400,7 @@ extension Collection {
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
@_inlineable
public func map<T>(
_ transform: (Iterator.Element) throws -> T
) rethrows -> [T] {
@@ -1418,6 +1443,7 @@ extension Collection {
///
/// - Complexity: O(*n*), where *n* is the number of elements to drop from
/// the beginning of the collection.
@_inlineable
public func dropFirst(_ n: Int) -> SubSequence {
_precondition(n >= 0, "Can't drop a negative number of elements from a collection")
let start = index(startIndex,
@@ -1443,6 +1469,7 @@ extension Collection {
/// at the end.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public func dropLast(_ n: Int) -> SubSequence {
_precondition(
n >= 0, "Can't drop a negative number of elements from a collection")
@@ -1461,6 +1488,7 @@ extension Collection {
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public func drop(
while predicate: (Iterator.Element) throws -> Bool
) rethrows -> SubSequence {
@@ -1487,6 +1515,7 @@ extension Collection {
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence starting at the beginning of this collection
/// with at most `maxLength` elements.
@_inlineable
public func prefix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
@@ -1505,6 +1534,7 @@ extension Collection {
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public func prefix(
while predicate: (Iterator.Element) throws -> Bool
) rethrows -> SubSequence {
@@ -1533,6 +1563,7 @@ extension Collection {
/// most `maxLength` elements.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public func suffix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
@@ -1569,6 +1600,7 @@ extension Collection {
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(through:)`
@_inlineable
public func prefix(upTo end: Index) -> SubSequence {
return self[startIndex..<end]
}
@@ -1597,6 +1629,7 @@ extension Collection {
/// - Returns: A subsequence starting at the `start` position.
///
/// - Complexity: O(1)
@_inlineable
public func suffix(from start: Index) -> SubSequence {
return self[start..<endIndex]
}
@@ -1622,6 +1655,7 @@ extension Collection {
///
/// - Complexity: O(1)
/// - SeeAlso: `prefix(upTo:)`
@_inlineable
public func prefix(through position: Index) -> SubSequence {
return prefix(upTo: index(after: position))
}
@@ -1677,6 +1711,7 @@ extension Collection {
/// split at that element.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
@_inlineable
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
@@ -1772,6 +1807,7 @@ extension Collection where Iterator.Element : Equatable {
/// subsequences are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
@_inlineable
public func split(
separator: Iterator.Element,
maxSplits: Int = Int.max,
@@ -1794,6 +1830,7 @@ extension Collection where SubSequence == Self {
///
/// - Complexity: O(1)
/// - SeeAlso: `popFirst()`
@_inlineable
@discardableResult
public mutating func removeFirst() -> Iterator.Element {
// TODO: swift-3-indexing-model - review the following
@@ -1812,6 +1849,7 @@ extension Collection where SubSequence == Self {
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*).
@_inlineable
public mutating func removeFirst(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
@@ -1822,6 +1860,7 @@ extension Collection where SubSequence == Self {
}
extension Collection {
@_inlineable
public func _preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {

View File

@@ -32,6 +32,7 @@ extension BidirectionalCollection {
/// print(lastNumber)
/// }
/// // Prints "50"
@_inlineable
public var last: Iterator.Element? {
return isEmpty ? nil : self[index(before: endIndex)]
}
@@ -62,6 +63,7 @@ extension Collection where ${IElement} : Equatable {
/// found in the collection, returns `nil`.
///
/// - SeeAlso: `index(where:)`
@_inlineable
public func index(of element: ${IElement}) -> Index? {
if let result = _customIndexOfEquatableElement(element) {
return result
@@ -101,6 +103,7 @@ extension Collection {
/// returns `nil`.
///
/// - SeeAlso: `index(of:)`
@_inlineable
public func index(
where predicate: (${IElement}) throws -> Bool
) rethrows -> Index? {
@@ -143,6 +146,7 @@ orderingExplanation = """\
//===----------------------------------------------------------------------===//
extension MutableCollection {
@_inlineable
public mutating func partition(
by belongsInSecondPartition: (${IElement}) throws -> Bool
) rethrows -> Index {
@@ -171,6 +175,7 @@ extension MutableCollection {
}
extension MutableCollection where Self : BidirectionalCollection {
@_inlineable
public mutating func partition(
by belongsInSecondPartition: (${IElement}) throws -> Bool
) rethrows -> Index {
@@ -257,6 +262,7 @@ extension ${Self} where Self.Iterator.Element : Comparable {
/// - Returns: A sorted array of the ${sequenceKind}'s elements.
///
/// - SeeAlso: `sorted(by:)`, `sort()`
@_inlineable
public func sorted() -> [Iterator.Element] {
var result = ContiguousArray(self)
result.sort()
@@ -330,6 +336,7 @@ ${orderingExplanation}
/// - Returns: A sorted array of the ${sequenceKind}'s elements.
///
/// - SeeAlso: `sorted()`, `sort(by:)`
@_inlineable
public func sorted(
by areInIncreasingOrder:
(${IElement}, ${IElement}) -> Bool
@@ -371,6 +378,7 @@ extension MutableCollection
/// students.sort(by: >)
/// print(students)
/// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
@_inlineable
public mutating func sort() {
let didSortUnsafeBuffer: Void? =
_withUnsafeMutableBufferPointerIfSupported {
@@ -441,6 +449,7 @@ ${orderingExplanation}
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its first
/// argument should be ordered before its second argument; otherwise,
/// `false`.
@_inlineable
public mutating func sort(
by areInIncreasingOrder:
(${IElement}, ${IElement}) -> Bool
@@ -505,6 +514,7 @@ extension ${Self} {
${subscriptCommentPre}
${subscriptCommentMid}
${subscriptCommentPost}
@_inlineable
public subscript(bounds: ClosedRange<Index>) -> SubSequence {
get {
return self[
@@ -533,6 +543,7 @@ extension ${Self} where Index : Strideable, Index.Stride : SignedInteger {
${subscriptCommentPre}
${subscriptCommentMid}
${subscriptCommentPost}
@_inlineable
public subscript(bounds: CountableRange<Index>) -> SubSequence {
get {
return self[Range(bounds)]
@@ -547,6 +558,7 @@ ${subscriptCommentPost}
${subscriptCommentPre}
${subscriptCommentMid}
${subscriptCommentPost}
@_inlineable
public subscript(bounds: CountableClosedRange<Index>) -> SubSequence {
get {
return self[ClosedRange(bounds)]

View File

@@ -17,36 +17,50 @@ import SwiftShims
/// initialized. See stdlib/runtime/GlobalObjects.cpp for details.
/// Because it's statically referenced, it requires non-lazy realization
/// by the Objective-C runtime.
@_fixed_layout
@_versioned
@objc_non_lazy_realization
internal final class _EmptyArrayStorage
: _ContiguousArrayStorageBase {
@_inlineable
@_versioned
init(_doNotCallMe: ()) {
_sanityCheckFailure("creating instance of _EmptyArrayStorage")
}
#if _runtime(_ObjC)
@_inlineable
@_versioned
override func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
return try body(UnsafeBufferPointer(start: nil, count: 0))
}
@_inlineable
@_versioned
override func _getNonVerbatimBridgedCount() -> Int {
return 0
}
@_inlineable
@_versioned
override func _getNonVerbatimBridgedHeapBuffer() -> _HeapBuffer<Int, AnyObject> {
return _HeapBuffer<Int, AnyObject>(
_HeapBufferStorage<Int, AnyObject>.self, 0, 0)
}
#endif
@_inlineable
@_versioned
override func canStoreElements(ofDynamicType _: Any.Type) -> Bool {
return false
}
/// A type that every element in the array is.
@_inlineable
@_versioned
override var staticElementType: Any.Type {
return Void.self
}
@@ -54,6 +68,8 @@ internal final class _EmptyArrayStorage
/// The empty array prototype. We use the same object for all empty
/// `[Native]Array<Element>`s.
@_inlineable
@_versioned
internal var _emptyArrayStorage : _EmptyArrayStorage {
return Builtin.bridgeFromRawPointer(
Builtin.addressof(&_swiftEmptyArrayStorage))
@@ -72,6 +88,8 @@ final class _ContiguousArrayStorage<Element> : _ContiguousArrayStorageBase {
/// If the `Element` is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements and return the result.
/// Otherwise, return `nil`.
@_inlineable
@_versioned
final override func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
@@ -84,6 +102,8 @@ final class _ContiguousArrayStorage<Element> : _ContiguousArrayStorageBase {
/// If `Element` is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements.
@_inlineable
@_versioned
internal final func _withVerbatimBridgedUnsafeBufferImpl(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> Void
) rethrows {
@@ -99,6 +119,8 @@ final class _ContiguousArrayStorage<Element> : _ContiguousArrayStorageBase {
/// Returns the number of elements in the array.
///
/// - Precondition: `Element` is bridged non-verbatim.
@_inlineable
@_versioned
override internal func _getNonVerbatimBridgedCount() -> Int {
_sanityCheck(
!_isBridgedVerbatimToObjectiveC(Element.self),
@@ -109,6 +131,8 @@ final class _ContiguousArrayStorage<Element> : _ContiguousArrayStorageBase {
/// Bridge array elements and return a new buffer that owns them.
///
/// - Precondition: `Element` is bridged non-verbatim.
@_inlineable
@_versioned
override internal func _getNonVerbatimBridgedHeapBuffer() ->
_HeapBuffer<Int, AnyObject> {
_sanityCheck(
@@ -131,6 +155,8 @@ final class _ContiguousArrayStorage<Element> : _ContiguousArrayStorageBase {
/// `Element`. We can't store anything else without violating type
/// safety; for example, the destructor has static knowledge that
/// all of the elements can be destroyed as `Element`.
@_inlineable
@_versioned
override func canStoreElements(
ofDynamicType proposedElementType: Any.Type
) -> Bool {
@@ -144,10 +170,14 @@ final class _ContiguousArrayStorage<Element> : _ContiguousArrayStorageBase {
}
/// A type that every element in the array is.
@_inlineable
@_versioned
override var staticElementType: Any.Type {
return Element.self
}
@_inlineable
@_versioned
internal final var _elementPointer : UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self))
}
@@ -161,6 +191,8 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// method, you must either initialize the `count` elements at the
/// result's `.firstElementAddress` or set the result's `.count`
/// to zero.
@_inlineable
@_versioned
internal init(
_uninitializedCount uninitializedCount: Int,
minimumCapacity: Int
@@ -191,12 +223,16 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
///
/// - Warning: storage may have been stack-allocated, so it's
/// crucial not to call, e.g., `malloc_size` on it.
@_inlineable
@_versioned
internal init(count: Int, storage: _ContiguousArrayStorage<Element>) {
_storage = storage
_initStorageHeader(count: count, capacity: count)
}
@_inlineable
@_versioned
internal init(_ storage: _ContiguousArrayStorageBase) {
_storage = storage
}
@@ -204,6 +240,8 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// Initialize the body part of our storage.
///
/// - Warning: does not initialize elements
@_inlineable
@_versioned
internal func _initStorageHeader(count: Int, capacity: Int) {
#if _runtime(_ObjC)
let verbatim = _isBridgedVerbatimToObjectiveC(Element.self)
@@ -220,23 +258,30 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
}
/// True, if the array is native and does not need a deferred type check.
@_inlineable
@_versioned
internal var arrayPropertyIsNativeTypeChecked: Bool {
return true
}
/// A pointer to the first element.
@_inlineable
@_versioned
internal var firstElementAddress: UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(Builtin.projectTailElems(_storage,
Element.self))
}
@_inlineable
@_versioned
internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {
return firstElementAddress
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage.
@_inlineable
@_versioned
internal func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
@@ -247,6 +292,8 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
@_inlineable
@_versioned
internal mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
@@ -257,15 +304,21 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
//===--- _ArrayBufferProtocol conformance -----------------------------------===//
/// Create an empty buffer.
@_inlineable
@_versioned
internal init() {
_storage = _emptyArrayStorage
}
@_inlineable
@_versioned
internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) {
_sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
self = buffer
}
@_inlineable
@_versioned
internal mutating func requestUniqueMutableBackingBuffer(
minimumCapacity: Int
) -> _ContiguousArrayBuffer<Element>? {
@@ -275,10 +328,14 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
return nil
}
@_inlineable
@_versioned
internal mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
@_inlineable
@_versioned
internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool {
return isUniquelyReferencedOrPinned()
}
@@ -286,10 +343,13 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@_inlineable
@_versioned
internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? {
return self
}
@_inlineable
@_versioned
@inline(__always)
internal func getElement(_ i: Int) -> Element {
@@ -298,6 +358,7 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
}
/// Get or set the value of the ith element.
@_inlineable
@_versioned
internal subscript(i: Int) -> Element {
@inline(__always)
@@ -319,6 +380,7 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
}
/// The number of elements the buffer stores.
@_inlineable
@_versioned
internal var count: Int {
get {
@@ -337,6 +399,8 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// Traps unless the given `index` is valid for subscripting, i.e.
/// `0 index < count`.
@_inlineable
@_versioned
@inline(__always)
func _checkValidSubscript(_ index : Int) {
_precondition(
@@ -346,6 +410,8 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
}
/// The number of elements the buffer can store without reallocation.
@_inlineable
@_versioned
internal var capacity: Int {
return _storage.countAndCapacity.capacity
}
@@ -353,6 +419,8 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer "past the end" of the
/// just-initialized memory.
@_inlineable
@_versioned
@discardableResult
internal func _copyContents(
subRange bounds: Range<Int>,
@@ -371,6 +439,8 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// Returns a `_SliceBuffer` containing the given `bounds` of values
/// from this buffer.
@_inlineable
@_versioned
internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
return _SliceBuffer(
@@ -389,6 +459,8 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// - Note: This does not mean the buffer is mutable. Other factors
/// may need to be considered, such as whether the buffer could be
/// some immutable Cocoa container.
@_inlineable
@_versioned
internal mutating func isUniquelyReferenced() -> Bool {
return _isUnique(&_storage)
}
@@ -396,6 +468,8 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// Returns `true` iff this buffer's storage is either
/// uniquely-referenced or pinned. NOTE: this does not mean
/// the buffer is mutable; see the comment on isUniquelyReferenced.
@_inlineable
@_versioned
internal mutating func isUniquelyReferencedOrPinned() -> Bool {
return _isUniqueOrPinned(&_storage)
}
@@ -406,6 +480,8 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// - Precondition: `Element` is bridged to Objective-C.
///
/// - Complexity: O(1).
@_inlineable
@_versioned
internal func _asCocoaArray() -> _NSArrayCore {
if count == 0 {
return _emptyArrayStorage
@@ -418,12 +494,15 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
#endif
/// An object that keeps the elements stored in this buffer alive.
@_inlineable
@_versioned
internal var owner: AnyObject {
return _storage
}
/// An object that keeps the elements stored in this buffer alive.
@_inlineable
@_versioned
internal var nativeOwner: AnyObject {
return _storage
}
@@ -432,12 +511,16 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
///
/// Two buffers address the same elements when they have the same
/// identity and count.
@_inlineable
@_versioned
internal var identity: UnsafeRawPointer {
return UnsafeRawPointer(firstElementAddress)
}
/// Returns `true` iff we have storage for elements of the given
/// `proposedElementType`. If not, we'll be treated as immutable.
@_inlineable
@_versioned
func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool {
return _storage.canStoreElements(ofDynamicType: proposedElementType)
}
@@ -447,6 +530,8 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// - Precondition: `U` is a class or `@objc` existential.
///
/// - Complexity: O(*n*)
@_inlineable
@_versioned
func storesOnlyElementsOfType<U>(
_: U.Type
) -> Bool {
@@ -466,10 +551,13 @@ internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
return true
}
@_versioned
internal var _storage: _ContiguousArrayStorageBase
}
/// Append the elements of `rhs` to `lhs`.
@_inlineable
@_versioned
internal func += <Element, C : Collection>(
lhs: inout _ContiguousArrayBuffer<Element>, rhs: C
) where C.Iterator.Element == Element {
@@ -506,6 +594,8 @@ extension _ContiguousArrayBuffer : RandomAccessCollection {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
@_inlineable
@_versioned
internal var startIndex: Int {
return 0
}
@@ -514,6 +604,8 @@ extension _ContiguousArrayBuffer : RandomAccessCollection {
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `index(after:)`.
@_inlineable
@_versioned
internal var endIndex: Int {
return count
}
@@ -522,11 +614,14 @@ extension _ContiguousArrayBuffer : RandomAccessCollection {
}
extension Sequence {
@_inlineable
public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> {
return _copySequenceToContiguousArray(self)
}
}
@_inlineable
@_versioned
internal func _copySequenceToContiguousArray<
S : Sequence
>(_ source: S) -> ContiguousArray<S.Iterator.Element> {
@@ -553,12 +648,15 @@ internal func _copySequenceToContiguousArray<
}
extension Collection {
@_inlineable
public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> {
return _copyCollectionToContiguousArray(self)
}
}
extension _ContiguousArrayBuffer {
@_inlineable
@_versioned
internal func _copyToContiguousArray() -> ContiguousArray<Element> {
return ContiguousArray(_buffer: self)
}
@@ -572,6 +670,8 @@ extension _ContiguousArrayBuffer {
/// ARC loops, the extra retain, release overhead cannot be eliminated which
/// makes assigning ranges very slow. Once this has been implemented, this code
/// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer.
@_inlineable
@_versioned
internal func _copyCollectionToContiguousArray<
C : Collection
>(_ source: C) -> ContiguousArray<C.Iterator.Element>
@@ -602,13 +702,19 @@ internal func _copyCollectionToContiguousArray<
/// This presents a "builder" interface for initializing an array buffer
/// element-by-element. The type is unsafe because it cannot be deinitialized
/// until the buffer has been finalized by a call to `finish`.
@_versioned
@_fixed_layout
internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> {
@_versioned
internal var result: _ContiguousArrayBuffer<Element>
@_versioned
internal var p: UnsafeMutablePointer<Element>
@_versioned
internal var remainingCapacity: Int
/// Initialize the buffer with an initial size of `initialCapacity`
/// elements.
@_versioned
@inline(__always) // For performance reasons.
init(initialCapacity: Int) {
if initialCapacity == 0 {
@@ -624,6 +730,7 @@ internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> {
}
/// Add an element to the buffer, reallocating if necessary.
@_versioned
@inline(__always) // For performance reasons.
mutating func add(_ element: Element) {
if remainingCapacity == 0 {
@@ -642,6 +749,7 @@ internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> {
}
/// Add an element to the buffer, which must have remaining capacity.
@_versioned
@inline(__always) // For performance reasons.
mutating func addWithExistingCapacity(_ element: Element) {
_sanityCheck(remainingCapacity > 0,
@@ -657,6 +765,7 @@ internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> {
///
/// Returns the fully-initialized buffer. `self` is reset to contain an
/// empty buffer and cannot be used afterward.
@_versioned
@inline(__always) // For performance reasons.
mutating func finish() -> ContiguousArray<Element> {
// Adjust the initialized count of the buffer.
@@ -671,6 +780,7 @@ internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> {
///
/// Returns the fully-initialized buffer. `self` is reset to contain an
/// empty buffer and cannot be used afterward.
@_versioned
@inline(__always) // For performance reasons.
mutating func finishWithOriginalCount() -> ContiguousArray<Element> {
_sanityCheck(remainingCapacity == result.capacity - result.count,

View File

@@ -24,6 +24,7 @@ from gyb_stdlib_support import (
import SwiftShims
@_versioned
@inline(never)
internal func _abstract(
file: StaticString = #file,
@@ -42,6 +43,7 @@ internal func _abstract(
/// underlying `IteratorProtocol`.
///
/// - SeeAlso: `AnySequence`
@_fixed_layout
public struct AnyIterator<Element> : IteratorProtocol {
/// Creates an iterator that wraps a base iterator but whose type depends
/// only on the base iterator's element type.
@@ -64,6 +66,7 @@ public struct AnyIterator<Element> : IteratorProtocol {
/// }
///
/// - Parameter base: An iterator to type-erase.
@_inlineable
public init<I : IteratorProtocol>(_ base: I) where I.Element == Element {
self._box = _IteratorBox(base)
}
@@ -84,10 +87,13 @@ public struct AnyIterator<Element> : IteratorProtocol {
/// - Parameter body: A closure that returns an optional element. `body` is
/// executed each time the `next()` method is called on the resulting
/// iterator.
@_inlineable
public init(_ body: @escaping () -> Element?) {
self._box = _IteratorBox(_ClosureBasedIterator(body))
}
@_inlineable
@_versioned
internal init(_box: _AnyIteratorBoxBase<Element>) {
self._box = _box
}
@@ -96,10 +102,12 @@ public struct AnyIterator<Element> : IteratorProtocol {
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@_inlineable
public func next() -> Element? {
return _box.next()
}
@_versioned
internal let _box: _AnyIteratorBoxBase<Element>
}
@@ -107,14 +115,23 @@ public struct AnyIterator<Element> : IteratorProtocol {
/// traversing the sequence consumes the iterator.
extension AnyIterator : Sequence {}
@_versioned
@_fixed_layout
internal struct _ClosureBasedIterator<Element> : IteratorProtocol {
@_inlineable
@_versioned
internal init(_ body: @escaping () -> Element?) {
self._body = body
}
@_inlineable
@_versioned
internal func next() -> Element? { return _body() }
@_versioned
internal let _body: () -> Element?
}
@_fixed_layout
@_versioned
internal class _AnyIteratorBoxBase<Element> : IteratorProtocol {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
@@ -122,14 +139,22 @@ internal class _AnyIteratorBoxBase<Element> : IteratorProtocol {
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Note: Subclasses must override this method.
@_versioned
internal func next() -> Element? { _abstract() }
}
@_fixed_layout
@_versioned
internal final class _IteratorBox<
Base : IteratorProtocol
> : _AnyIteratorBoxBase<Base.Element> {
@_inlineable
@_versioned
internal init(_ base: Base) { self._base = base }
@_inlineable
@_versioned
internal override func next() -> Base.Element? { return _base.next() }
@_versioned
internal var _base: Base
}
@@ -138,6 +163,8 @@ internal final class _IteratorBox<
% for Kind in ['Sequence', 'Collection', 'BidirectionalCollection', 'RandomAccessCollection']:
@_fixed_layout
@_versioned
% if Kind == 'Sequence':
internal class _AnySequenceBox<Element>
% elif Kind == 'Collection':
@@ -154,44 +181,62 @@ internal class _AnyRandomAccessCollectionBox<Element>
{
% if Kind == 'Sequence':
@_versioned
@_inlineable
internal func _makeIterator() -> AnyIterator<Element> { _abstract() }
@_versioned
@_inlineable
internal var _underestimatedCount: Int { _abstract() }
@_versioned
@_inlineable
internal func _map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
_abstract()
}
@_versioned
@_inlineable
internal func _filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
_abstract()
}
@_versioned
@_inlineable
internal func _forEach(
_ body: (Element) throws -> Void
) rethrows {
_abstract()
}
@_versioned
@_inlineable
internal func __customContainsEquatableElement(
_ element: Element
) -> Bool? {
_abstract()
}
@_versioned
@_inlineable
internal func __preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
_abstract()
}
@_versioned
@_inlineable
internal func __copyToContiguousArray() -> ContiguousArray<Element> {
_abstract()
}
@_versioned
@_inlineable
internal func __copyContents(initializing buf: UnsafeMutableBufferPointer<Element>)
-> (AnyIterator<Element>,UnsafeMutableBufferPointer<Element>.Index) {
_abstract()
@@ -200,34 +245,48 @@ internal class _AnyRandomAccessCollectionBox<Element>
% end
% override = 'override' if Kind != 'Sequence' else ''
@_versioned
@_inlineable
internal ${override} func _drop(
while predicate: (Element) throws -> Bool
) rethrows -> _Any${Kind}Box<Element> {
_abstract()
}
@_versioned
@_inlineable
internal ${override} func _dropFirst(_ n: Int) -> _Any${Kind}Box<Element> {
_abstract()
}
@_versioned
@_inlineable
internal ${override} func _dropLast(_ n: Int) -> _Any${Kind}Box<Element> {
_abstract()
}
@_versioned
@_inlineable
internal ${override} func _prefix(_ maxLength: Int) -> _Any${Kind}Box<Element> {
_abstract()
}
@_versioned
@_inlineable
internal ${override} func _prefix(
while predicate: (Element) throws -> Bool
) rethrows -> _Any${Kind}Box<Element> {
_abstract()
}
@_versioned
@_inlineable
internal ${override} func _suffix(_ maxLength: Int) -> _Any${Kind}Box<Element> {
_abstract()
}
@_versioned
@_inlineable
internal func _split(
maxSplits: Int, omittingEmptySubsequences: Bool,
whereSeparator isSeparator: (Element) throws -> Bool
@@ -236,34 +295,50 @@ internal class _AnyRandomAccessCollectionBox<Element>
}
% if Kind == 'Collection':
@_versioned
@_inlineable
internal subscript(i: _AnyIndexBox) -> Element { _abstract() }
@_versioned
@_inlineable
internal func _index(after i: _AnyIndexBox) -> _AnyIndexBox { _abstract() }
@_versioned
@_inlineable
internal func _formIndex(after i: _AnyIndexBox) { _abstract() }
@_versioned
@_inlineable
internal func _index(
_ i: _AnyIndexBox, offsetBy n: IntMax
) -> _AnyIndexBox {
_abstract()
}
@_versioned
@_inlineable
internal func _index(
_ i: _AnyIndexBox, offsetBy n: IntMax, limitedBy limit: _AnyIndexBox
) -> _AnyIndexBox? {
_abstract()
}
@_versioned
@_inlineable
internal func _formIndex(_ i: inout _AnyIndexBox, offsetBy n: IntMax) {
_abstract()
}
@_versioned
@_inlineable
internal func _formIndex(
_ i: inout _AnyIndexBox, offsetBy n: IntMax, limitedBy limit: _AnyIndexBox
) -> Bool {
_abstract()
}
@_versioned
@_inlineable
internal func _distance(
from start: _AnyIndexBox, to end: _AnyIndexBox
) -> IntMax {
@@ -283,6 +358,7 @@ internal class _AnyRandomAccessCollectionBox<Element>
var isEmpty: Bool { get }
*/
@_versioned
internal var _count: IntMax { _abstract() }
// TODO: swift-3-indexing-model: forward the following methods.
@@ -290,8 +366,11 @@ internal class _AnyRandomAccessCollectionBox<Element>
func _customIndexOfEquatableElement(element: Iterator.Element) -> Index??
*/
@_versioned
internal var _first: Element? { _abstract() }
@_versioned
@_inlineable
internal init(
_startIndex: _AnyIndexBox,
endIndex: _AnyIndexBox
@@ -300,12 +379,17 @@ internal class _AnyRandomAccessCollectionBox<Element>
self._endIndex = endIndex
}
@_versioned
internal let _startIndex: _AnyIndexBox
@_versioned
internal let _endIndex: _AnyIndexBox
% end
% if Kind in ['Collection', 'BidirectionalCollection', 'RandomAccessCollection']:
% override = 'override' if Kind != 'Collection' else ''
@_versioned
@_inlineable
internal ${override} subscript(
start start: _AnyIndexBox,
end end: _AnyIndexBox
@@ -313,8 +397,14 @@ internal class _AnyRandomAccessCollectionBox<Element>
% end
% if Kind == 'BidirectionalCollection':
@_versioned
@_inlineable
internal func _index(before i: _AnyIndexBox) -> _AnyIndexBox { _abstract() }
@_versioned
@_inlineable
internal func _formIndex(before i: _AnyIndexBox) { _abstract() }
@_versioned
@_inlineable
internal var _last: Element? { _abstract() }
% end
}
@@ -333,6 +423,8 @@ internal class _AnyRandomAccessCollectionBox<Element>
% assert False, 'Unknown kind'
% end
@_fixed_layout
@_versioned
internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Element>
where
S.SubSequence : ${Kind},
@@ -353,68 +445,100 @@ internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Elemen
{
internal typealias Element = S.Iterator.Element
@_versioned
@_inlineable
internal override func _makeIterator() -> AnyIterator<Element> {
return AnyIterator(_base.makeIterator())
}
@_versioned
@_inlineable
internal override var _underestimatedCount: Int {
return _base.underestimatedCount
}
@_versioned
@_inlineable
internal override func _map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
return try _base.map(transform)
}
@_versioned
@_inlineable
internal override func _filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _base.filter(isIncluded)
}
@_versioned
@_inlineable
internal override func _forEach(
_ body: (Element) throws -> Void
) rethrows {
return try _base.forEach(body)
}
@_versioned
@_inlineable
internal override func __customContainsEquatableElement(
_ element: Element
) -> Bool? {
return _base._customContainsEquatableElement(element)
}
@_versioned
@_inlineable
internal override func __preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
return try _base._preprocessingPass(preprocess)
}
@_versioned
@_inlineable
internal override func __copyToContiguousArray() -> ContiguousArray<Element> {
return _base._copyToContiguousArray()
}
@_versioned
@_inlineable
internal override func __copyContents(initializing buf: UnsafeMutableBufferPointer<Element>)
-> (AnyIterator<Element>,UnsafeMutableBufferPointer<Element>.Index) {
let (it,idx) = _base._copyContents(initializing: buf)
return (AnyIterator(it),idx)
}
@_versioned
@_inlineable
internal override func _drop(
while predicate: (Element) throws -> Bool
) rethrows -> _Any${Kind}Box<Element> {
return try _${Kind}Box<S.SubSequence>(_base: _base.drop(while: predicate))
}
@_versioned
@_inlineable
internal override func _dropFirst(_ n: Int) -> _Any${Kind}Box<Element> {
return _${Kind}Box<S.SubSequence>(_base: _base.dropFirst(n))
}
@_versioned
@_inlineable
internal override func _dropLast(_ n: Int) -> _Any${Kind}Box<Element> {
return _${Kind}Box<S.SubSequence>(_base: _base.dropLast(n))
}
@_versioned
@_inlineable
internal override func _prefix(
while predicate: (Element) throws -> Bool
) rethrows -> _Any${Kind}Box<Element> {
return try _${Kind}Box<S.SubSequence>(_base: _base.prefix(while: predicate))
}
@_versioned
@_inlineable
internal override func _prefix(_ maxLength: Int) -> _Any${Kind}Box<Element> {
return _${Kind}Box<S.SubSequence>(_base: _base.prefix(maxLength))
}
@_versioned
@_inlineable
internal override func _suffix(_ maxLength: Int) -> _Any${Kind}Box<Element> {
return _${Kind}Box<S.SubSequence>(_base: _base.suffix(maxLength))
}
% for ResultKind in EqualAndWeakerKinds:
@_versioned
@_inlineable
internal override func _split(
maxSplits: Int, omittingEmptySubsequences: Bool,
whereSeparator isSeparator: (Element) throws -> Bool
@@ -430,10 +554,14 @@ internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Elemen
% end
% if Kind == 'Sequence':
@_versioned
@_inlineable
internal init(_base: S) {
self._base = _base
}
% else:
@_versioned
//@_inlineable
internal init(_base: S) {
self._base = _base
super.init(
@@ -441,6 +569,8 @@ internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Elemen
endIndex: _IndexBox(_base: _base.endIndex))
}
@_versioned
@_inlineable
internal func _unbox(
_ position: _AnyIndexBox, file: StaticString = #file, line: UInt = #line
) -> S.Index {
@@ -450,10 +580,14 @@ internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Elemen
fatalError("Index type mismatch!", file: file, line: line)
}
@_versioned
@_inlineable
internal override subscript(position: _AnyIndexBox) -> Element {
return _base[_unbox(position)]
}
@_versioned
@_inlineable
internal override subscript(start start: _AnyIndexBox, end end: _AnyIndexBox)
-> _Any${Kind}Box<Element>
{
@@ -462,10 +596,14 @@ internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Elemen
)
}
@_versioned
@_inlineable
internal override func _index(after position: _AnyIndexBox) -> _AnyIndexBox {
return _IndexBox(_base: _base.index(after: _unbox(position)))
}
@_versioned
@_inlineable
internal override func _formIndex(after position: _AnyIndexBox) {
if let p = position as? _IndexBox<S.Index> {
return _base.formIndex(after: &p._base)
@@ -473,12 +611,16 @@ internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Elemen
fatalError("Index type mismatch!")
}
@_versioned
@_inlineable
internal override func _index(
_ i: _AnyIndexBox, offsetBy n: IntMax
) -> _AnyIndexBox {
return _IndexBox(_base: _base.index(_unbox(i), offsetBy: numericCast(n)))
}
@_versioned
@_inlineable
internal override func _index(
_ i: _AnyIndexBox,
offsetBy n: IntMax,
@@ -491,6 +633,8 @@ internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Elemen
.map { _IndexBox(_base: $0) }
}
@_versioned
@_inlineable
internal override func _formIndex(
_ i: inout _AnyIndexBox, offsetBy n: IntMax
) {
@@ -500,6 +644,8 @@ internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Elemen
fatalError("Index type mismatch!")
}
@_versioned
@_inlineable
internal override func _formIndex(
_ i: inout _AnyIndexBox, offsetBy n: IntMax, limitedBy limit: _AnyIndexBox
) -> Bool {
@@ -512,6 +658,8 @@ internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Elemen
fatalError("Index type mismatch!")
}
@_versioned
@_inlineable
internal override func _distance(
from start: _AnyIndexBox,
to end: _AnyIndexBox
@@ -519,19 +667,27 @@ internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Elemen
return numericCast(_base.distance(from: _unbox(start), to: _unbox(end)))
}
@_versioned
@_inlineable
internal override var _count: IntMax {
return numericCast(_base.count)
}
@_versioned
@_inlineable
internal override var _first: Element? {
return _base.first
}
% if Kind in ['BidirectionalCollection', 'RandomAccessCollection']:
@_versioned
@_inlineable
internal override func _index(before position: _AnyIndexBox) -> _AnyIndexBox {
return _IndexBox(_base: _base.index(before: _unbox(position)))
}
@_versioned
@_inlineable
internal override func _formIndex(before position: _AnyIndexBox) {
if let p = position as? _IndexBox<S.Index> {
return _base.formIndex(before: &p._base)
@@ -539,27 +695,37 @@ internal final class _${Kind}Box<S : ${Kind}> : _Any${Kind}Box<S.Iterator.Elemen
fatalError("Index type mismatch!")
}
@_versioned
@_inlineable
internal override var _last: Element? {
return _base.last
}
% end
% end
@_versioned
internal var _base: S
}
% end
@_versioned
@_fixed_layout
internal struct _ClosureBasedSequence<Iterator : IteratorProtocol>
: Sequence {
@_versioned
@_inlineable
internal init(_ makeUnderlyingIterator: @escaping () -> Iterator) {
self._makeUnderlyingIterator = makeUnderlyingIterator
}
@_versioned
@_inlineable
internal func makeIterator() -> Iterator {
return _makeUnderlyingIterator()
}
@_versioned
internal var _makeUnderlyingIterator: () -> Iterator
}
@@ -570,8 +736,11 @@ internal struct _ClosureBasedSequence<Iterator : IteratorProtocol>
/// underlying sequence.
///
/// - SeeAlso: `AnyIterator`
//@_versioned
@_fixed_layout
public struct AnySequence<Element> : Sequence {
/// Creates a new sequence that wraps and forwards operations to `base`.
@_inlineable
public init<S : Sequence>(_ base: S)
where
S.Iterator.Element == Element,
@@ -583,6 +752,7 @@ public struct AnySequence<Element> : Sequence {
/// Creates a sequence whose `makeIterator()` method forwards to
/// `makeUnderlyingIterator`.
@_inlineable
public init<I : IteratorProtocol>(
_ makeUnderlyingIterator: @escaping () -> I
) where I.Element == Element {
@@ -591,10 +761,13 @@ public struct AnySequence<Element> : Sequence {
public typealias Iterator = AnyIterator<Element>
@_versioned
@_inlineable
internal init(_box: _AnySequenceBox<Element>) {
self._box = _box
}
@_versioned
internal let _box: _AnySequenceBox<Element>
}
@@ -605,60 +778,72 @@ extension Any${Kind} {
% else:
/// Returns an iterator over the elements of this collection.
% end
@_inlineable
public func makeIterator() -> Iterator {
return _box._makeIterator()
}
@_inlineable
public var underestimatedCount: Int {
return _box._underestimatedCount
}
@_inlineable
public func map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
return try _box._map(transform)
}
@_inlineable
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _box._filter(isIncluded)
}
@_inlineable
public func forEach(
_ body: (Element) throws -> Void
) rethrows {
return try _box._forEach(body)
}
@_inlineable
public func drop(
while predicate: (Element) throws -> Bool
) rethrows -> Any${Kind}<Element> {
return try Any${Kind}(_box: _box._drop(while: predicate))
}
@_inlineable
public func dropFirst(_ n: Int) -> Any${Kind}<Element> {
return Any${Kind}(_box: _box._dropFirst(n))
}
@_inlineable
public func dropLast(_ n: Int) -> Any${Kind}<Element> {
return Any${Kind}(_box: _box._dropLast(n))
}
@_inlineable
public func prefix(
while predicate: (Element) throws -> Bool
) rethrows -> Any${Kind}<Element> {
return try Any${Kind}(_box: _box._prefix(while: predicate))
}
@_inlineable
public func prefix(_ maxLength: Int) -> Any${Kind}<Element> {
return Any${Kind}(_box: _box._prefix(maxLength))
}
@_inlineable
public func suffix(_ maxLength: Int) -> Any${Kind}<Element> {
return Any${Kind}(_box: _box._suffix(maxLength))
}
@_inlineable
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
@@ -670,22 +855,26 @@ extension Any${Kind} {
whereSeparator: isSeparator)
}
@_inlineable
public func _customContainsEquatableElement(
_ element: Element
) -> Bool? {
return _box.__customContainsEquatableElement(element)
}
@_inlineable
public func _preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
return try _box.__preprocessingPass(preprocess)
}
@_inlineable
public func _copyToContiguousArray() -> ContiguousArray<Element> {
return self._box.__copyToContiguousArray()
}
@_inlineable
public func _copyContents(initializing buf: UnsafeMutableBufferPointer<Iterator.Element>)
-> (AnyIterator<Element>,UnsafeMutableBufferPointer<Element>.Index) {
let (it,idx) = _box.__copyContents(initializing: buf)
@@ -697,6 +886,7 @@ extension Any${Kind} {
//===--- Index ------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
@_versioned
internal protocol _AnyIndexBox : class {
var _typeID: ObjectIdentifier { get }
@@ -707,31 +897,46 @@ internal protocol _AnyIndexBox : class {
func _isLess(than rhs: _AnyIndexBox) -> Bool
}
@_fixed_layout
@_versioned
internal final class _IndexBox<
BaseIndex : Comparable
> : _AnyIndexBox {
@_versioned
internal var _base: BaseIndex
@_versioned
@_inlineable
internal init(_base: BaseIndex) {
self._base = _base
}
@_versioned
@_inlineable
internal func _unsafeUnbox(_ other: _AnyIndexBox) -> BaseIndex {
return unsafeDowncast(other, to: _IndexBox.self)._base
}
@_versioned
@_inlineable
internal var _typeID: ObjectIdentifier {
return ObjectIdentifier(type(of: self))
}
@_versioned
@_inlineable
internal func _unbox<T : Comparable>() -> T? {
return (self as _AnyIndexBox as? _IndexBox<T>)?._base
}
@_versioned
@_inlineable
internal func _isEqual(to rhs: _AnyIndexBox) -> Bool {
return _base == _unsafeUnbox(rhs)
}
@_versioned
@_inlineable
internal func _isLess(than rhs: _AnyIndexBox) -> Bool {
return _base < _unsafeUnbox(rhs)
}
@@ -740,20 +945,27 @@ internal final class _IndexBox<
/// A wrapper over an underlying index that hides the specific underlying type.
///
/// - SeeAlso: `AnyCollection`
@_fixed_layout
public struct AnyIndex {
/// Creates a new index wrapping `base`.
@_inlineable
public init<BaseIndex : Comparable>(_ base: BaseIndex) {
self._box = _IndexBox(_base: base)
}
@_versioned
@_inlineable
internal init(_box: _AnyIndexBox) {
self._box = _box
}
@_versioned
@_inlineable
internal var _typeID: ObjectIdentifier {
return _box._typeID
}
@_versioned
internal var _box: _AnyIndexBox
}
@@ -766,6 +978,7 @@ extension AnyIndex : Comparable {
/// - Parameters:
/// - lhs: An index to compare.
/// - rhs: Another index to compare.
@_inlineable
public static func == (lhs: AnyIndex, rhs: AnyIndex) -> Bool {
_precondition(lhs._typeID == rhs._typeID, "base index types differ")
return lhs._box._isEqual(to: rhs._box)
@@ -779,6 +992,7 @@ extension AnyIndex : Comparable {
/// - Parameters:
/// - lhs: An index to compare.
/// - rhs: Another index to compare.
@_inlineable
public static func < (lhs: AnyIndex, rhs: AnyIndex) -> Bool {
_precondition(lhs._typeID == rhs._typeID, "base index types differ")
return lhs._box._isLess(than: rhs._box)
@@ -806,6 +1020,7 @@ protocol _AnyCollectionProtocol : Collection {
/// collection.
///
/// - SeeAlso: ${', '.join('`Any%sCollection`' % t for t in (2 * TRAVERSALS)[ti + 1 : ti + 3]) }
@_fixed_layout
public struct ${Self}<Element>
: _AnyCollectionProtocol, ${SelfProtocol} {
@@ -814,6 +1029,8 @@ public struct ${Self}<Element>
public typealias Iterator = AnyIterator<Element>
@_versioned
@_inlineable
internal init(_box: _${Self}Box<Element>) {
self._box = _box
}
@@ -825,6 +1042,7 @@ public struct ${Self}<Element>
/// - Parameter base: The collection to wrap.
///
/// - Complexity: O(1).
@_inlineable
public init<C : ${SubProtocol}>(_ base: C)
where
C.Iterator.Element == Element,
@@ -852,6 +1070,7 @@ public struct ${Self}<Element>
/// Creates an `${Self}` having the same underlying collection as `other`.
///
/// - Complexity: O(1)
@_inlineable
public init(
_ other: Any${SubProtocol}<Element>
) {
@@ -866,6 +1085,7 @@ public struct ${Self}<Element>
/// `${SelfProtocol}`, the result is `nil`.
///
/// - Complexity: O(1)
@_inlineable
public init?(
_ other: Any${collectionForTraversal(SuperTraversal)}<Element>
) {
@@ -883,6 +1103,7 @@ public struct ${Self}<Element>
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
@_inlineable
public var startIndex: AnyIndex {
return AnyIndex(_box: _box._startIndex)
}
@@ -892,6 +1113,7 @@ public struct ${Self}<Element>
///
/// `endIndex` is always reachable from `startIndex` by zero or more
/// applications of `index(after:)`.
@_inlineable
public var endIndex: AnyIndex {
return AnyIndex(_box: _box._endIndex)
}
@@ -900,31 +1122,37 @@ public struct ${Self}<Element>
///
/// - Precondition: `position` indicates a valid position in `self` and
/// `position != endIndex`.
@_inlineable
public subscript(position: AnyIndex) -> Element {
return _box[position._box]
}
@_inlineable
public subscript(bounds: Range<AnyIndex>) -> ${Self}<Element> {
return ${Self}(_box:
_box[start: bounds.lowerBound._box, end: bounds.upperBound._box])
}
@_inlineable
public func _failEarlyRangeCheck(_ index: AnyIndex, bounds: Range<AnyIndex>) {
// Do nothing. Doing a range check would involve unboxing indices,
// performing dynamic dispatch etc. This seems to be too costly for a fast
// range check for QoI purposes.
}
@_inlineable
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
// Do nothing. Doing a range check would involve unboxing indices,
// performing dynamic dispatch etc. This seems to be too costly for a fast
// range check for QoI purposes.
}
@_inlineable
public func index(after i: AnyIndex) -> AnyIndex {
return AnyIndex(_box: _box._index(after: i._box))
}
@_inlineable
public func formIndex(after i: inout AnyIndex) {
if _isUnique(&i._box) {
_box._formIndex(after: i._box)
@@ -934,10 +1162,12 @@ public struct ${Self}<Element>
}
}
@_inlineable
public func index(_ i: AnyIndex, offsetBy n: IntMax) -> AnyIndex {
return AnyIndex(_box: _box._index(i._box, offsetBy: n))
}
@_inlineable
public func index(
_ i: AnyIndex,
offsetBy n: IntMax,
@@ -947,6 +1177,7 @@ public struct ${Self}<Element>
.map { AnyIndex(_box:$0) }
}
@_inlineable
public func formIndex(_ i: inout AnyIndex, offsetBy n: IntMax) {
if _isUnique(&i._box) {
return _box._formIndex(&i._box, offsetBy: n)
@@ -955,6 +1186,7 @@ public struct ${Self}<Element>
}
}
@_inlineable
public func formIndex(
_ i: inout AnyIndex,
offsetBy n: IntMax,
@@ -971,6 +1203,7 @@ public struct ${Self}<Element>
return false
}
@_inlineable
public func distance(from start: AnyIndex, to end: AnyIndex) -> IntMax {
return _box._distance(from: start._box, to: end._box)
}
@@ -984,19 +1217,23 @@ public struct ${Self}<Element>
///
% end
/// - Complexity: ${'O(1)' if Traversal == 'RandomAccess' else 'O(*n*)'}
@_inlineable
public var count: IntMax {
return _box._count
}
@_inlineable
public var first: Element? {
return _box._first
}
% if Traversal == 'Bidirectional' or Traversal == 'RandomAccess':
@_inlineable
public func index(before i: AnyIndex) -> AnyIndex {
return AnyIndex(_box: _box._index(before: i._box))
}
@_inlineable
public func formIndex(before i: inout AnyIndex) {
if _isUnique(&i._box) {
_box._formIndex(before: i._box)
@@ -1006,17 +1243,20 @@ public struct ${Self}<Element>
}
}
@_inlineable
public var last: Element? {
return _box._last
}
% end
/// Uniquely identifies the stored underlying collection.
@_inlineable
public // Due to language limitations only
var _boxID: ObjectIdentifier {
return ObjectIdentifier(_box)
}
@_versioned
internal let _box: _${Self}Box<Element>
}
% end

View File

@@ -146,6 +146,7 @@ extension UnsignedInteger {
///
/// func f(_ x: Int32) {}
/// func g(_ x: Int64) { f(numericCast(x)) }
@_inlineable
public func numericCast<
T : _SignedInteger, U : _SignedInteger
>(_ x: T) -> U {
@@ -160,6 +161,7 @@ public func numericCast<
///
/// func f(_ x: UInt32) {}
/// func g(_ x: UInt64) { f(numericCast(x)) }
@_inlineable
public func numericCast<
T : UnsignedInteger, U : UnsignedInteger
>(_ x: T) -> U {
@@ -174,6 +176,7 @@ public func numericCast<
///
/// func f(_ x: UInt32) {}
/// func g(_ x: Int64) { f(numericCast(x)) }
@_inlineable
public func numericCast<
T : _SignedInteger, U : UnsignedInteger
>(_ x: T) -> U {
@@ -188,6 +191,7 @@ public func numericCast<
///
/// func f(_ x: Int32) {}
/// func g(_ x: UInt64) { f(numericCast(x)) }
@_inlineable
public func numericCast<
T : UnsignedInteger, U : _SignedInteger
>(_ x: T) -> U {

View File

@@ -793,6 +793,7 @@ public struct Set<Element : Hashable> :
/// must be finite.
/// - Returns: `true` if the set is a subset of `possibleSuperset`;
/// otherwise, `false`.
@_inlineable
public func isSubset<S : Sequence>(of possibleSuperset: S) -> Bool
where S.Iterator.Element == Element {
// FIXME(performance): isEmpty fast path, here and elsewhere.
@@ -820,6 +821,7 @@ public struct Set<Element : Hashable> :
/// `possibleStrictSuperset` must be finite.
/// - Returns: `true` is the set is strict subset of
/// `possibleStrictSuperset`; otherwise, `false`.
@_inlineable
public func isStrictSubset<S : Sequence>(of possibleStrictSuperset: S) -> Bool
where S.Iterator.Element == Element {
// FIXME: code duplication.
@@ -842,6 +844,7 @@ public struct Set<Element : Hashable> :
/// be finite.
/// - Returns: `true` if the set is a superset of `possibleSubset`;
/// otherwise, `false`.
@_inlineable
public func isSuperset<S : Sequence>(of possibleSubset: S) -> Bool
where S.Iterator.Element == Element {
// FIXME(performance): Don't build a set; just ask if every element is in
@@ -918,6 +921,7 @@ public struct Set<Element : Hashable> :
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set with the unique elements of this set and `other`.
@_inlineable
public func union<S : Sequence>(_ other: S) -> Set<Element>
where S.Iterator.Element == Element {
var newSet = self
@@ -938,6 +942,7 @@ public struct Set<Element : Hashable> :
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
@_inlineable
public mutating func formUnion<S : Sequence>(_ other: S)
where S.Iterator.Element == Element {
for item in other {
@@ -959,11 +964,13 @@ public struct Set<Element : Hashable> :
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set.
@_inlineable
public func subtracting<S : Sequence>(_ other: S) -> Set<Element>
where S.Iterator.Element == Element {
return self._subtracting(other)
}
@_versioned
internal func _subtracting<S : Sequence>(_ other: S) -> Set<Element>
where S.Iterator.Element == Element {
var newSet = self
@@ -1012,6 +1019,7 @@ public struct Set<Element : Hashable> :
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set.
@_inlineable
public func intersection<S : Sequence>(_ other: S) -> Set<Element>
where S.Iterator.Element == Element {
let otherSet = Set(other)
@@ -1031,6 +1039,7 @@ public struct Set<Element : Hashable> :
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
@_inlineable
public mutating func formIntersection<S : Sequence>(_ other: S)
where S.Iterator.Element == Element {
// Because `intersect` needs to both modify and iterate over
@@ -1065,6 +1074,7 @@ public struct Set<Element : Hashable> :
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set.
@_inlineable
public func symmetricDifference<S : Sequence>(_ other: S) -> Set<Element>
where S.Iterator.Element == Element {
var newSet = self
@@ -1089,6 +1099,7 @@ public struct Set<Element : Hashable> :
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
@_inlineable
public mutating func formSymmetricDifference<S : Sequence>(_ other: S)
where S.Iterator.Element == Element {
let otherSet = Set(other)
@@ -1148,6 +1159,8 @@ public struct Set<Element : Hashable> :
/// a set and some sequence (which may itself be a `Set`).
///
/// (isSubset: lhs ⊂ rhs, isEqual: lhs ⊂ rhs and |lhs| = |rhs|)
@_inlineable
@_versioned
internal func _compareSets<Element>(_ lhs: Set<Element>, _ rhs: Set<Element>)
-> (isSubset: Bool, isEqual: Bool) {
// FIXME(performance): performance could be better if we start by comparing
@@ -3333,6 +3346,7 @@ extension _Native${Self}Buffer
"don't call mutating methods on _Native${Self}Buffer")
}
@_versioned
internal static func fromArray(_ elements: [SequenceElementWithoutLabels])
-> Buffer
{
@@ -5107,6 +5121,7 @@ extension ${Self} {
///
/// - Complexity: Averages to O(1) over many calls to `popFirst()`.
%end
@_inlineable
public mutating func popFirst() -> Element? {
guard !isEmpty else { return nil }
return remove(at: startIndex)
@@ -5186,6 +5201,7 @@ extension Set {
///
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
@_inlineable
public func isSubset(of other: Set<Element>) -> Bool {
let (isSubset, isEqual) = _compareSets(self, other)
return isSubset || isEqual
@@ -5205,6 +5221,7 @@ extension Set {
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a superset of `other`; otherwise,
/// `false`.
@_inlineable
public func isSuperset(of other: Set<Element>) -> Bool {
return other.isSubset(of: self)
}
@@ -5223,6 +5240,7 @@ extension Set {
/// - Parameter other: Another set.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
@_inlineable
public func isDisjoint(with other: Set<Element>) -> Bool {
for member in self {
if other.contains(member) {
@@ -5246,6 +5264,7 @@ extension Set {
///
/// - Parameter other: Another set.
/// - Returns: A new set.
@_inlineable
public func subtracting(_ other: Set<Element>) -> Set<Element> {
return self._subtracting(other)
}
@@ -5267,6 +5286,7 @@ extension Set {
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a strict superset of
/// `other`; otherwise, `false`.
@_inlineable
public func isStrictSuperset(of other: Set<Element>) -> Bool {
return self.isSuperset(of: other) && self != other
}
@@ -5290,6 +5310,7 @@ extension Set {
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a strict subset of
/// `other`; otherwise, `false`.
@_inlineable
public func isStrictSubset(of other: Set<Element>) -> Bool {
return other.isStrictSuperset(of: self)
}
@@ -5310,6 +5331,7 @@ extension Set {
///
/// - Parameter other: Another set.
/// - Returns: A new set.
@_inlineable
public func intersection(_ other: Set<Element>) -> Set<Element> {
var newSet = Set<Element>()
for member in self {
@@ -5337,6 +5359,7 @@ extension Set {
/// // Prints "["Diana", "Chris", "Forlani", "Alicia", "Greta"]"
///
/// - Parameter other: Another set.
@_inlineable
public mutating func formSymmetricDifference(_ other: Set<Element>) {
for member in other {
if contains(member) {

View File

@@ -29,6 +29,7 @@ from gyb_stdlib_support import (
// <rdar://problem/17144340>
/// A collection of indices for an arbitrary ${collection}.
@_fixed_layout
public struct ${Self}<
Elements : _${collectionForTraversal(Traversal).replace('Collection', 'Indexable')}
// FIXME(ABI)#43 (Recursive Protocol Constraints):
@@ -39,6 +40,8 @@ public struct ${Self}<
// FIXME(compiler limitation): this typealias should be inferred.
public typealias Index = Elements.Index
@_inlineable
@_versioned
internal init(
_elements: Elements,
startIndex: Elements.Index,
@@ -49,14 +52,17 @@ public struct ${Self}<
self._endIndex = endIndex
}
@_inlineable
public var startIndex: Elements.Index {
return _startIndex
}
@_inlineable
public var endIndex: Elements.Index {
return _endIndex
}
@_inlineable
public subscript(i: Index) -> Elements.Index {
// FIXME: swift-3-indexing-model: range check.
return i
@@ -65,6 +71,7 @@ public struct ${Self}<
// FIXME(compiler limitation): this typealias should be inferred.
public typealias SubSequence = ${Self}<Elements>
@_inlineable
public subscript(bounds: Range<Index>) -> ${Self}<Elements> {
// FIXME: swift-3-indexing-model: range check.
return ${Self}(
@@ -73,22 +80,26 @@ public struct ${Self}<
endIndex: bounds.upperBound)
}
@_inlineable
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return _elements.index(after: i)
}
@_inlineable
public func formIndex(after i: inout Index) {
// FIXME: swift-3-indexing-model: range check.
_elements.formIndex(after: &i)
}
% if Traversal in ['Bidirectional', 'RandomAccess']:
@_inlineable
public func index(before i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return _elements.index(before: i)
}
@_inlineable
public func formIndex(before i: inout Index) {
// FIXME: swift-3-indexing-model: range check.
_elements.formIndex(before: &i)
@@ -98,12 +109,16 @@ public struct ${Self}<
// FIXME(compiler limitation): this typealias should be inferred.
public typealias Indices = ${Self}<Elements>
@_inlineable
public var indices: Indices {
return self
}
@_versioned
internal var _elements: Elements
@_versioned
internal var _startIndex: Elements.Index
@_versioned
internal var _endIndex: Elements.Index
}

View File

@@ -49,12 +49,14 @@ extension LazyCollectionProtocol where Elements == Self {
/// implemented lazily.
///
/// - See also: `LazySequenceProtocol`, `LazyCollection`
@_fixed_layout
public struct ${Self}<Base : ${TraversalCollection}> : LazyCollectionProtocol {
/// The type of the underlying collection.
public typealias Elements = Base
/// The underlying collection.
@_inlineable
public var elements: Elements { return _base }
/// A type that represents a valid position in the collection.
@@ -65,10 +67,13 @@ public struct ${Self}<Base : ${TraversalCollection}> : LazyCollectionProtocol {
/// Creates an instance with `base` as its underlying Collection
/// instance.
@_inlineable
@_versioned
internal init(_base: Base) {
self._base = _base
}
@_versioned
internal var _base: Base
}
@@ -81,6 +86,7 @@ extension ${Self} : Sequence {
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@_inlineable
public func makeIterator() -> Iterator {
return _base.makeIterator()
}
@@ -89,19 +95,23 @@ extension ${Self} : Sequence {
/// `self`, **nondestructively**.
///
/// - Complexity: O(*n*)
@_inlineable
public var underestimatedCount: Int { return _base.underestimatedCount }
@_inlineable
public func _copyToContiguousArray()
-> ContiguousArray<Base.Iterator.Element> {
return _base._copyToContiguousArray()
}
@_inlineable
public func _copyContents(
initializing buf: UnsafeMutableBufferPointer<Iterator.Element>
) -> (Iterator,UnsafeMutableBufferPointer<Iterator.Element>.Index) {
return _base._copyContents(initializing: buf)
}
@_inlineable
public func _customContainsEquatableElement(
_ element: Base.Iterator.Element
) -> Bool? {
@@ -113,6 +123,7 @@ extension ${Self} : ${TraversalCollection} {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
@_inlineable
public var startIndex: Base.Index {
return _base.startIndex
}
@@ -122,15 +133,18 @@ extension ${Self} : ${TraversalCollection} {
///
/// `endIndex` is always reachable from `startIndex` by zero or more
/// applications of `index(after:)`.
@_inlineable
public var endIndex: Base.Index {
return _base.endIndex
}
@_inlineable
public var indices: Base.Indices {
return _base.indices
}
// TODO: swift-3-indexing-model - add docs
@_inlineable
public func index(after i: Base.Index) -> Base.Index {
return _base.index(after: i)
}
@@ -139,6 +153,7 @@ extension ${Self} : ${TraversalCollection} {
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
@_inlineable
public subscript(position: Base.Index) -> Base.Iterator.Element {
return _base[position]
}
@@ -147,11 +162,13 @@ extension ${Self} : ${TraversalCollection} {
/// `self`'s elements.
///
/// - Complexity: O(1)
@_inlineable
public subscript(bounds: Range<Index>) -> ${Self}<${Slice}<Base>> {
return ${Slice}(base: _base, bounds: bounds).lazy
}
/// A Boolean value indicating whether the collection is empty.
@_inlineable
public var isEmpty: Bool {
return _base.isEmpty
}
@@ -165,6 +182,7 @@ extension ${Self} : ${TraversalCollection} {
///
/// - Complexity: O(1) if `Self` conforms to `RandomAccessCollection`;
/// O(*n*) otherwise.
@_inlineable
public var count: Base.IndexDistance {
return _base.count
}
@@ -176,6 +194,7 @@ extension ${Self} : ${TraversalCollection} {
/// `nil` otherwise.
///
/// - Complexity: O(*n*)
@_inlineable
public func _customIndexOfEquatableElement(
_ element: Base.Iterator.Element
) -> Index?? {
@@ -183,16 +202,19 @@ extension ${Self} : ${TraversalCollection} {
}
/// Returns the first element of `self`, or `nil` if `self` is empty.
@_inlineable
public var first: Base.Iterator.Element? {
return _base.first
}
// TODO: swift-3-indexing-model - add docs
@_inlineable
public func index(_ i: Index, offsetBy n: Base.IndexDistance) -> Index {
return _base.index(i, offsetBy: n)
}
// TODO: swift-3-indexing-model - add docs
@_inlineable
public func index(
_ i: Index, offsetBy n: Base.IndexDistance, limitedBy limit: Index
) -> Index? {
@@ -200,16 +222,19 @@ extension ${Self} : ${TraversalCollection} {
}
// TODO: swift-3-indexing-model - add docs
@_inlineable
public func distance(from start: Index, to end: Index) -> Base.IndexDistance {
return _base.distance(from:start, to: end)
}
% if Traversal != 'Forward':
@_inlineable
public func index(before i: Base.Index) -> Base.Index {
return _base.index(before: i)
}
@_inlineable
public var last: Base.Iterator.Element? {
return _base.last
}
@@ -226,6 +251,7 @@ extension ${TraversalCollection} {
/// need a part of the final collection to avoid unnecessary computation.
///
/// - SeeAlso: `LazySequenceProtocol`, `LazyCollectionProtocol`.
@_inlineable
public var lazy: ${Self}<Self> {
return ${Self}(_base: self)
}
@@ -235,6 +261,7 @@ extension ${TraversalCollection} {
// LazyCollectionProtocol (below) is not selected for some reason.
extension ${TraversalCollection} where Self : LazyCollectionProtocol {
/// Identical to `self`.
@_inlineable
public var lazy: Self { // Don't re-wrap already-lazy collections
return self
}

View File

@@ -12,6 +12,7 @@
/// Evaluate `f()` and return its result, ensuring that `x` is not
/// destroyed before f returns.
@_inlineable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: () throws -> Result
) rethrows -> Result {
@@ -21,6 +22,7 @@ public func withExtendedLifetime<T, Result>(
/// Evaluate `f(x)` and return its result, ensuring that `x` is not
/// destroyed before f returns.
@_inlineable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: (T) throws -> Result
) rethrows -> Result {
@@ -44,6 +46,7 @@ extension String {
/// The pointer argument is valid only for the duration of the closure's
/// execution.
/// - Returns: The return value of the `body` closure, if any.
@_inlineable
public func withCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
@@ -78,6 +81,7 @@ public func _fixLifetime<T>(_ x: T) {
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafePointer(to:_:)`
@_inlineable
public func withUnsafeMutablePointer<T, Result>(
to arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
@@ -104,6 +108,7 @@ public func withUnsafeMutablePointer<T, Result>(
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafeMutablePointer(to:_:)`
@_inlineable
public func withUnsafePointer<T, Result>(
to arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result

View File

@@ -473,11 +473,14 @@ public func == <Header, Element>(
/// `object`; the use of `inout` is an implementation artifact.
/// - Returns: `true` if `object` is known to have a single strong reference;
/// otherwise, `false`.
@_inlineable
public func isKnownUniquelyReferenced<T : AnyObject>(_ object: inout T) -> Bool
{
return _isUnique(&object)
}
@_inlineable
@_versioned
internal func _isKnownUniquelyReferencedOrPinned<T : AnyObject>(_ object: inout T) -> Bool {
return _isUniqueOrPinned(&object)
}
@@ -512,6 +515,7 @@ internal func _isKnownUniquelyReferencedOrPinned<T : AnyObject>(_ object: inout
/// `object`; the use of `inout` is an implementation artifact.
/// - Returns: `true` if `object` is known to have a single strong reference;
/// otherwise, `false`. If `object` is `nil`, the return value is `false`.
@_inlineable
public func isKnownUniquelyReferenced<T : AnyObject>(
_ object: inout T?
) -> Bool {

View File

@@ -21,6 +21,7 @@ from gyb_stdlib_support import (
/// The `IteratorProtocol` used by `MapSequence` and `MapCollection`.
/// Produces each element by passing the output of the `Base`
/// `IteratorProtocol` through a transform function returning `Element`.
@_fixed_layout
public struct LazyMapIterator<
Base : IteratorProtocol, Element
> : IteratorProtocol, Sequence {
@@ -31,20 +32,32 @@ public struct LazyMapIterator<
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@_inlineable
public mutating func next() -> Element? {
return _base.next().map(_transform)
}
@_inlineable
public var base: Base { return _base }
@_versioned
internal var _base: Base
@_versioned
internal let _transform: (Base.Element) -> Element
@_inlineable
@_versioned
internal init(_base: Base, _transform: @escaping (Base.Element) -> Element) {
self._base = _base
self._transform = _transform
}
}
/// A `Sequence` whose elements consist of those in a `Base`
/// `Sequence` passed through a transform function returning `Element`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
@_fixed_layout
public struct LazyMapSequence<Base : Sequence, Element>
: LazySequenceProtocol {
@@ -53,6 +66,7 @@ public struct LazyMapSequence<Base : Sequence, Element>
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@_inlineable
public func makeIterator() -> LazyMapIterator<Base.Iterator, Element> {
return LazyMapIterator(_base: _base.makeIterator(), _transform: _transform)
}
@@ -61,18 +75,23 @@ public struct LazyMapSequence<Base : Sequence, Element>
/// `self`, **nondestructively**.
///
/// - Complexity: O(*n*)
@_inlineable
public var underestimatedCount: Int {
return _base.underestimatedCount
}
/// Creates an instance with elements `transform(x)` for each element
/// `x` of base.
@_inlineable
@_versioned
internal init(_base: Base, transform: @escaping (Base.Iterator.Element) -> Element) {
self._base = _base
self._transform = transform
}
@_versioned
internal var _base: Base
@_versioned
internal let _transform: (Base.Iterator.Element) -> Element
}
@@ -91,6 +110,7 @@ public struct LazyMapSequence<Base : Sequence, Element>
/// `Collection` passed through a transform function returning `Element`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
@_fixed_layout
public struct ${Self}<
Base : ${collectionForTraversal(Traversal)}, Element
> : LazyCollectionProtocol, ${collectionForTraversal(Traversal)} {
@@ -98,18 +118,24 @@ public struct ${Self}<
// FIXME(compiler limitation): should be inferable.
public typealias Index = Base.Index
@_inlineable
public var startIndex: Base.Index { return _base.startIndex }
@_inlineable
public var endIndex: Base.Index { return _base.endIndex }
@_inlineable
public func index(after i: Index) -> Index { return _base.index(after: i) }
@_inlineable
public func formIndex(after i: inout Index) {
_base.formIndex(after: &i)
}
% if Traversal in ['Bidirectional', 'RandomAccess']:
@_inlineable
public func index(before i: Index) -> Index { return _base.index(before: i) }
@_inlineable
public func formIndex(before i: inout Index) {
_base.formIndex(before: &i)
}
@@ -119,10 +145,12 @@ public struct ${Self}<
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
@_inlineable
public subscript(position: Base.Index) -> Element {
return _transform(_base[position])
}
@_inlineable
public subscript(bounds: Range<Base.Index>) -> ${Slice}<${Self}> {
return ${Slice}(base: self, bounds: bounds)
}
@@ -141,11 +169,13 @@ public struct ${Self}<
public typealias Indices = Base.Indices
@_inlineable
public var indices: Indices {
return _base.indices
}
/// A Boolean value indicating whether the collection is empty.
@_inlineable
public var isEmpty: Bool { return _base.isEmpty }
/// The number of elements in the collection.
@@ -157,26 +187,32 @@ public struct ${Self}<
///
/// - Complexity: O(1) if `Index` conforms to `RandomAccessIndex`; O(*n*)
/// otherwise.
@_inlineable
public var count: Base.IndexDistance {
return _base.count
}
@_inlineable
public var first: Element? { return _base.first.map(_transform) }
% if Traversal in ['Bidirectional', 'RandomAccess']:
@_inlineable
public var last: Element? { return _base.last.map(_transform) }
% end
@_inlineable
public func index(_ i: Index, offsetBy n: Base.IndexDistance) -> Index {
return _base.index(i, offsetBy: n)
}
@_inlineable
public func index(
_ i: Index, offsetBy n: Base.IndexDistance, limitedBy limit: Index
) -> Index? {
return _base.index(i, offsetBy: n, limitedBy: limit)
}
@_inlineable
public func distance(from start: Index, to end: Index) -> Base.IndexDistance {
return _base.distance(from: start, to: end)
}
@@ -184,22 +220,28 @@ public struct ${Self}<
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@_inlineable
public func makeIterator() -> LazyMapIterator<Base.Iterator, Element> {
return LazyMapIterator(_base: _base.makeIterator(), _transform: _transform)
}
@_inlineable
public var underestimatedCount: Int {
return _base.underestimatedCount
}
/// Create an instance with elements `transform(x)` for each element
/// `x` of base.
@_inlineable
@_versioned
internal init(_base: Base, transform: @escaping (Base.Iterator.Element) -> Element) {
self._base = _base
self._transform = transform
}
@_versioned
internal var _base: Base
@_versioned
internal let _transform: (Base.Iterator.Element) -> Element
}
@@ -211,6 +253,7 @@ extension LazySequenceProtocol {
/// Returns a `LazyMapSequence` over this `Sequence`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
@_inlineable
public func map<U>(
_ transform: @escaping (Elements.Iterator.Element) -> U
) -> LazyMapSequence<Self.Elements, U> {
@@ -228,6 +271,7 @@ extension LazyCollectionProtocol
/// Returns a `LazyMapCollection` over this `Collection`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
@_inlineable
public func map<U>(
_ transform: @escaping (Elements.Iterator.Element) -> U
) -> LazyMap${collectionForTraversal(Traversal)}<Self.Elements, U> {

View File

@@ -161,7 +161,8 @@ public struct Mirror {
}
return nil
}
@_versioned
internal static func _superclassIterator<Subject>(
_ subject: Subject, _ ancestorRepresentation: AncestorRepresentation
) -> () -> Mirror? {

View File

@@ -333,6 +333,7 @@ public protocol MutableCollection : _MutableIndexable, Collection {
// TODO: swift-3-indexing-model - review the following
extension MutableCollection {
@_inlineable
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (UnsafeMutablePointer<Iterator.Element>, Int) throws -> R
) rethrows -> R? {
@@ -361,6 +362,7 @@ extension MutableCollection {
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
@_inlineable
public subscript(bounds: Range<Index>) -> MutableSlice<Self> {
get {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)

View File

@@ -157,6 +157,7 @@ public enum Optional<Wrapped> : ExpressibleByNilLiteral {
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@_inlineable
public func map<U>(
_ transform: (Wrapped) throws -> U
) rethrows -> U? {
@@ -187,6 +188,7 @@ public enum Optional<Wrapped> : ExpressibleByNilLiteral {
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@_inlineable
public func flatMap<U>(
_ transform: (Wrapped) throws -> U?
) rethrows -> U? {
@@ -235,6 +237,7 @@ public enum Optional<Wrapped> : ExpressibleByNilLiteral {
/// `unsafelyUnwrapped` only when you are confident that this instance
/// will never be equal to `nil` and only after you've tried using the
/// postfix `!` operator.
@_inlineable
public var unsafelyUnwrapped: Wrapped {
@inline(__always)
get {
@@ -249,6 +252,7 @@ public enum Optional<Wrapped> : ExpressibleByNilLiteral {
///
/// This version is for internal stdlib use; it avoids any checking
/// overhead for users, even in Debug builds.
@_inlineable
public // SPI(SwiftExperimental)
var _unsafelyUnwrappedUnchecked: Wrapped {
@inline(__always)
@@ -348,6 +352,7 @@ func _diagnoseUnexpectedNilOptional(_filenameStart: Builtin.RawPointer,
/// - Parameters:
/// - lhs: An optional value to compare.
/// - rhs: Another optional value to compare.
@_inlineable
public func == <T: Equatable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
@@ -392,6 +397,7 @@ public func == <T: Equatable>(lhs: T?, rhs: T?) -> Bool {
/// - Parameters:
/// - lhs: An optional value to compare.
/// - rhs: Another optional value to compare.
@_inlineable
public func != <T : Equatable>(lhs: T?, rhs: T?) -> Bool {
return !(lhs == rhs)
}
@@ -670,6 +676,7 @@ public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T?)
}
extension Optional {
@available(*, unavailable, renamed: "none")
public static var None: Optional<Wrapped> {
return .none

View File

@@ -344,6 +344,7 @@ internal func _adHocPrint_unlocked<T, TargetStream : TextOutputStream>(
}
}
@_versioned
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
@_semantics("stdlib_binary_only")
@@ -386,6 +387,8 @@ internal func _print_unlocked<T, TargetStream : TextOutputStream>(
///
/// This function is forbidden from being inlined because when building the
/// standard library inlining makes us drop the special semantics.
@_inlineable
@_versioned
@inline(never) @effects(readonly)
func _toStringReadOnlyStreamable<T : TextOutputStreamable>(_ x: T) -> String {
var result = ""
@@ -393,6 +396,8 @@ func _toStringReadOnlyStreamable<T : TextOutputStreamable>(_ x: T) -> String {
return result
}
@_inlineable
@_versioned
@inline(never) @effects(readonly)
func _toStringReadOnlyPrintable<T : CustomStringConvertible>(_ x: T) -> String {
return x.description

View File

@@ -131,6 +131,7 @@ extension RandomAccessCollection where SubSequence == RandomAccessSlice<Self> {
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
@_inlineable
public subscript(bounds: Range<Index>) -> RandomAccessSlice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return RandomAccessSlice(base: self, bounds: bounds)
@@ -185,6 +186,7 @@ extension _RandomAccessIndexable {
/// the method returns `nil`.
///
/// - Complexity: O(1)
@_inlineable
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
@@ -204,6 +206,7 @@ where Index : Strideable,
/// The indices that are valid for subscripting the collection, in ascending
/// order.
@_inlineable
public var indices: CountableRange<Index> {
return startIndex..<endIndex
}
@@ -213,6 +216,7 @@ where Index : Strideable,
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
@_inlineable
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: tests for the trap.
_failEarlyRangeCheck(
@@ -220,6 +224,7 @@ where Index : Strideable,
return i.advanced(by: 1)
}
@_inlineable
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
@@ -255,6 +260,7 @@ where Index : Strideable,
/// to `index(before:)`.
///
/// - Complexity: O(1)
@_inlineable
public func index(_ i: Index, offsetBy n: Index.Stride) -> Index {
let result = i.advanced(by: n)
// This range check is not precise, tighter bounds exist based on `n`.
@@ -276,6 +282,7 @@ where Index : Strideable,
/// - Returns: The distance between `start` and `end`.
///
/// - Complexity: O(1)
@_inlineable
public func distance(from start: Index, to end: Index) -> Index.Stride {
// FIXME: swift-3-indexing-model: tests for traps.
_failEarlyRangeCheck(

View File

@@ -78,6 +78,7 @@ public enum _DisabledRangeIndex_ {}
/// // Prints "0"
///
/// - SeeAlso: `CountableClosedRange`, `Range`, `ClosedRange`
@_fixed_layout
public struct CountableRange<Bound> : RandomAccessCollection
where
// FIXME(ABI)#176 (Type checker)
@@ -107,20 +108,24 @@ public struct CountableRange<Bound> : RandomAccessCollection
public typealias IndexDistance = Bound.Stride
@_inlineable
public var startIndex: Index {
return lowerBound
}
@_inlineable
public var endIndex: Index {
return upperBound
}
@_inlineable
public func index(after i: Index) -> Index {
_failEarlyRangeCheck(i, bounds: startIndex..<endIndex)
return i.advanced(by: 1)
}
@_inlineable
public func index(before i: Index) -> Index {
_precondition(i > lowerBound)
_precondition(i <= upperBound)
@@ -128,6 +133,7 @@ public struct CountableRange<Bound> : RandomAccessCollection
return i.advanced(by: -1)
}
@_inlineable
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
let r = i.advanced(by: n)
_precondition(r >= lowerBound)
@@ -135,6 +141,7 @@ public struct CountableRange<Bound> : RandomAccessCollection
return r
}
@_inlineable
public func distance(from start: Index, to end: Index) -> IndexDistance {
return start.distance(to: end)
}
@@ -145,6 +152,7 @@ public struct CountableRange<Bound> : RandomAccessCollection
///
/// - Parameter bounds: A range of the range's indices. The upper and lower
/// bounds of the `bounds` range must be valid indices of the collection.
@_inlineable
public subscript(bounds: Range<Index>) -> CountableRange<Bound> {
return CountableRange(bounds)
}
@@ -153,6 +161,7 @@ public struct CountableRange<Bound> : RandomAccessCollection
///
/// - Parameter bounds: A range of the range's indices. The upper and lower
/// bounds of the `bounds` range must be valid indices of the collection.
@_inlineable
public subscript(bounds: CountableRange<Bound>) -> CountableRange<Bound> {
return self[Range(bounds)]
}
@@ -161,6 +170,7 @@ public struct CountableRange<Bound> : RandomAccessCollection
/// The indices that are valid for subscripting the range, in ascending
/// order.
@_inlineable
public var indices: Indices {
return self
}
@@ -173,11 +183,13 @@ public struct CountableRange<Bound> : RandomAccessCollection
/// (`..<`) to form `CountableRange` instances is preferred.
///
/// - Parameter bounds: A tuple of the lower and upper bounds of the range.
@_inlineable
public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) {
self.lowerBound = bounds.lower
self.upperBound = bounds.upper
}
@_inlineable
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
return lowerBound <= element && element < upperBound
}
@@ -189,6 +201,7 @@ public struct CountableRange<Bound> : RandomAccessCollection
/// let empty = 10..<10
/// print(empty.isEmpty)
/// // Prints "true"
@_inlineable
public var isEmpty: Bool {
return lowerBound == upperBound
}
@@ -214,6 +227,7 @@ extension CountableRange {
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the range, and must not equal the range's end
/// index.
@_inlineable
public subscript(position: Index) -> Element {
// FIXME: swift-3-indexing-model: tests for the range check.
_debugPrecondition(self.contains(position), "Index out of range")
@@ -260,6 +274,7 @@ extension CountableRange
/// lower bounds of the `bounds` range must be valid indices of the
/// collection and `bounds.upperBound` must be less than the collection's
/// end index.
@_inlineable
public subscript(bounds: ClosedRange<Bound>) -> CountableRange<Bound> {
return self[bounds.lowerBound..<(bounds.upperBound.advanced(by: 1))]
}
@@ -270,6 +285,7 @@ extension CountableRange
/// lower bounds of the `bounds` range must be valid indices of the
/// collection and `bounds.upperBound` must be less than the collection's
/// end index.
@_inlineable
public subscript(
bounds: CountableClosedRange<Bound>
) -> CountableRange<Bound> {
@@ -312,7 +328,7 @@ public struct Range<
/// (`..<`) to form `Range` instances is preferred.
///
/// - Parameter bounds: A tuple of the lower and upper bounds of the range.
@inline(__always)
@_inlineable
public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) {
self.lowerBound = bounds.lower
self.upperBound = bounds.upper
@@ -339,6 +355,7 @@ public struct Range<
/// - Parameter element: The element to check for containment.
/// - Returns: `true` if `element` is contained in the range; otherwise,
/// `false`.
@_inlineable
public func contains(_ element: Bound) -> Bool {
return lowerBound <= element && element < upperBound
}
@@ -350,6 +367,7 @@ public struct Range<
/// let empty: Range = 10..<10
/// print(empty.isEmpty)
/// // Prints "true"
@_inlineable
public var isEmpty: Bool {
return lowerBound == upperBound
}
@@ -543,6 +561,7 @@ extension ${Self} : Equatable {
/// - Parameters:
/// - lhs: A range to compare.
/// - rhs: Another range to compare.
@_inlineable
public static func == (lhs: ${Self}<Bound>, rhs: ${Self}<Bound>) -> Bool {
return
lhs.lowerBound == rhs.lowerBound &&
@@ -587,6 +606,7 @@ extension ${Self} : Equatable {
/// - Parameters:
/// - lhs: A range.
/// - rhs: A value to match against `lhs`.
@_inlineable
public static func ~= (pattern: ${Self}<Bound>, value: Bound) -> Bool {
return pattern.contains(value)
}
@@ -611,6 +631,7 @@ extension ${Self} where Bound : _Strideable, Bound.Stride : SignedInteger {
// WORKAROUND rdar://25214598 - should be Bound : Strideable
/// The number of values contained in the range.
@_inlineable
public var count: Bound.Stride {
let distance = lowerBound.distance(to: upperBound)
% if 'Closed' in Self:

View File

@@ -516,6 +516,7 @@ public protocol RangeReplaceableCollection
//===----------------------------------------------------------------------===//
extension RangeReplaceableCollection {
@_inlineable
public subscript(bounds: Range<Index>) -> RangeReplaceableSlice<Self> {
return RangeReplaceableSlice(base: self, bounds: bounds)
}
@@ -534,6 +535,7 @@ extension RangeReplaceableCollection {
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the value passed in the
/// `repeating` parameter. `count` must be zero or greater.
@_inlineable
public init(repeating repeatedValue: Iterator.Element, count: Int) {
self.init()
if count != 0 {
@@ -546,6 +548,7 @@ extension RangeReplaceableCollection {
/// sequence.
///
/// - Parameter elements: The sequence of elements for the new collection.
@_inlineable
public init<S : Sequence>(_ elements: S)
where S.Iterator.Element == Iterator.Element {
self.init()
@@ -568,6 +571,7 @@ extension RangeReplaceableCollection {
///
/// - Complexity: O(1) on average, over many additions to the same
/// collection.
@_inlineable
public mutating func append(_ newElement: Iterator.Element) {
insert(newElement, at: endIndex)
}
@@ -590,6 +594,7 @@ extension RangeReplaceableCollection {
///
/// - Complexity: O(*n*), where *n* is the length of the resulting
/// collection.
@_inlineable
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Iterator.Element == Iterator.Element {
@@ -623,6 +628,7 @@ extension RangeReplaceableCollection {
/// `index` must be a valid index into the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public mutating func insert(
_ newElement: Iterator.Element, at i: Index
) {
@@ -655,6 +661,7 @@ extension RangeReplaceableCollection {
/// and `newElements`. If `i` is equal to the collection's `endIndex`
/// property, the complexity is O(*n*), where *n* is the length of
/// `newElements`.
@_inlineable
public mutating func insert<C : Collection>(
contentsOf newElements: C, at i: Index
) where C.Iterator.Element == Iterator.Element {
@@ -681,6 +688,7 @@ extension RangeReplaceableCollection {
/// - Returns: The removed element.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
@discardableResult
public mutating func remove(at position: Index) -> Iterator.Element {
_precondition(!isEmpty, "can't remove from an empty collection")
@@ -707,6 +715,7 @@ extension RangeReplaceableCollection {
/// bounds of the range must be valid indices of the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public mutating func removeSubrange(_ bounds: Range<Index>) {
replaceSubrange(bounds, with: EmptyCollection())
}
@@ -727,6 +736,7 @@ extension RangeReplaceableCollection {
/// number of elements in the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public mutating func removeFirst(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
@@ -751,6 +761,7 @@ extension RangeReplaceableCollection {
/// - Returns: The removed element.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
@discardableResult
public mutating func removeFirst() -> Iterator.Element {
_precondition(!isEmpty,
@@ -771,6 +782,7 @@ extension RangeReplaceableCollection {
/// again. The default value is `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
if !keepCapacity {
self = Self()
@@ -790,6 +802,7 @@ extension RangeReplaceableCollection {
/// less storage than requested or to take no action at all.
///
/// - Parameter n: The requested number of elements to store.
@_inlineable
public mutating func reserveCapacity(_ n: IndexDistance) {}
}
@@ -843,6 +856,7 @@ extension RangeReplaceableCollection where SubSequence == Self {
///
/// - Complexity: O(1)
/// - Precondition: `!self.isEmpty`.
@_inlineable
@discardableResult
public mutating func removeFirst() -> Iterator.Element {
_precondition(!isEmpty, "can't remove items from an empty collection")
@@ -866,6 +880,7 @@ extension RangeReplaceableCollection where SubSequence == Self {
/// number of elements in the collection.
///
/// - Complexity: O(1)
@_inlineable
public mutating func removeFirst(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
@@ -883,6 +898,8 @@ extension RangeReplaceableCollection
% end
{
/// Returns a half-open range denoting the same positions as `r`.
@_versioned
@_inlineable
internal func _makeHalfOpen(_ r: ${Range}<Index>) -> Range<Index> {
// The upperBound of the result depends on whether `r` is a closed
// range.
@@ -931,6 +948,7 @@ extension RangeReplaceableCollection
/// and `newElements`. If the call to `replaceSubrange` simply appends the
/// contents of `newElements` to the collection, the complexity is O(*n*),
/// where *n* is the length of `newElements`.
@_inlineable
public mutating func replaceSubrange<C>(
_ subrange: ${Range}<Index>,
with newElements: C
@@ -956,6 +974,7 @@ extension RangeReplaceableCollection
/// bounds of the range must be valid indices of the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@_inlineable
public mutating func removeSubrange(_ bounds: ${Range}<Index>) {
removeSubrange(_makeHalfOpen(bounds))
}
@@ -963,10 +982,12 @@ extension RangeReplaceableCollection
% end
extension RangeReplaceableCollection {
@_inlineable
public mutating func _customRemoveLast() -> Iterator.Element? {
return nil
}
@_inlineable
public mutating func _customRemoveLast(_ n: Int) -> Bool {
return false
}
@@ -977,12 +998,14 @@ extension RangeReplaceableCollection
Self : BidirectionalCollection,
SubSequence == Self {
@_inlineable
public mutating func _customRemoveLast() -> Iterator.Element? {
let element = last!
self = self[startIndex..<index(before: endIndex)]
return element
}
@_inlineable
public mutating func _customRemoveLast(_ n: Int) -> Bool {
self = self[startIndex..<index(endIndex, offsetBy: numericCast(-n))]
return true
@@ -1001,6 +1024,7 @@ extension RangeReplaceableCollection where Self : BidirectionalCollection {
/// - Returns: The last element of the collection.
///
/// - Complexity: O(1)
@_inlineable
@discardableResult
public mutating func removeLast() -> Iterator.Element {
_precondition(!isEmpty, "can't remove last element from an empty collection")
@@ -1025,6 +1049,7 @@ extension RangeReplaceableCollection where Self : BidirectionalCollection {
/// number of elements in the collection.
///
/// - Complexity: O(*n*), where *n* is the specified number of elements.
@_inlineable
public mutating func removeLast(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
@@ -1056,6 +1081,7 @@ extension RangeReplaceableCollection
/// - Returns: The last element of the collection.
///
/// - Complexity: O(1)
@_inlineable
@discardableResult
public mutating func removeLast() -> Iterator.Element {
_precondition(!isEmpty, "can't remove last element from an empty collection")
@@ -1080,6 +1106,7 @@ extension RangeReplaceableCollection
/// number of elements in the collection.
///
/// - Complexity: O(*n*), where *n* is the specified number of elements.
@_inlineable
public mutating func removeLast(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
@@ -1111,6 +1138,7 @@ extension RangeReplaceableCollection
/// - Parameters:
/// - lhs: A range-replaceable collection.
/// - rhs: A collection or finite sequence.
@_inlineable
public func + <C : RangeReplaceableCollection, S : Sequence>(lhs: C, rhs: S) -> C
where S.Iterator.Element == C.Iterator.Element {
@@ -1139,6 +1167,7 @@ public func + <C : RangeReplaceableCollection, S : Sequence>(lhs: C, rhs: S) ->
/// - Parameters:
/// - lhs: A collection or finite sequence.
/// - rhs: A range-replaceable collection.
@_inlineable
public func + <C : RangeReplaceableCollection, S : Sequence>(lhs: S, rhs: C) -> C
where S.Iterator.Element == C.Iterator.Element {
@@ -1167,6 +1196,7 @@ public func + <C : RangeReplaceableCollection, S : Sequence>(lhs: S, rhs: C) ->
/// - Parameters:
/// - lhs: A range-replaceable collection.
/// - rhs: Another range-replaceable collection.
@_inlineable
public func +<
RRC1 : RangeReplaceableCollection,
RRC2 : RangeReplaceableCollection
@@ -1196,6 +1226,7 @@ public func +<
/// - rhs: A collection or finite sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the resulting array.
@_inlineable
public func += <
R : RangeReplaceableCollection, S : Sequence
>(lhs: inout R, rhs: S)

View File

@@ -25,6 +25,7 @@
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
@_fixed_layout
public struct Repeated<Element> : RandomAccessCollection {
public typealias Indices = CountableRange<Int>
@@ -37,6 +38,8 @@ public struct Repeated<Element> : RandomAccessCollection {
/// Creates an instance that contains `count` elements having the
/// value `repeatedValue`.
@_versioned
@_inlineable
internal init(_repeating repeatedValue: Element, count: Int) {
_precondition(count >= 0, "Repetition count should be non-negative")
self.count = count
@@ -47,6 +50,7 @@ public struct Repeated<Element> : RandomAccessCollection {
///
/// In a `Repeated` collection, `startIndex` is always equal to zero. If the
/// collection is empty, `startIndex` is equal to `endIndex`.
@_inlineable
public var startIndex: Index {
return 0
}
@@ -56,6 +60,7 @@ public struct Repeated<Element> : RandomAccessCollection {
///
/// In a `Repeated` collection, `endIndex` is always equal to `count`. If the
/// collection is empty, `endIndex` is equal to `startIndex`.
@_inlineable
public var endIndex: Index {
return count
}
@@ -65,6 +70,7 @@ public struct Repeated<Element> : RandomAccessCollection {
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
@_inlineable
public subscript(position: Int) -> Element {
_precondition(position >= 0 && position < count, "Index out of range")
return repeatedValue
@@ -97,6 +103,7 @@ public struct Repeated<Element> : RandomAccessCollection {
/// - count: The number of times to repeat `element`.
/// - Returns: A collection that contains `count` elements that are all
/// `element`.
@_inlineable
public func repeatElement<T>(_ element: T, count n: Int) -> Repeated<T> {
return Repeated(_repeating: element, count: n)
}

View File

@@ -44,6 +44,7 @@ extension MutableCollection where Self : BidirectionalCollection {
/// An index that traverses the same positions as an underlying index,
/// with inverted traversal direction.
@_fixed_layout
public struct ReversedIndex<Base : Collection> : Comparable {
/// Creates a new index into a reversed collection for the position before
/// the specified index.
@@ -66,6 +67,7 @@ public struct ReversedIndex<Base : Collection> : Comparable {
/// `"r"`, the character before `"a"` in the `name` string.
///
/// - Parameter base: The position after the element to create an index for.
@_inlineable
public init(_ base: Base.Index) {
self.base = base
}
@@ -98,6 +100,7 @@ public struct ReversedIndex<Base : Collection> : Comparable {
/// // Prints "Last even number: 40"
public let base: Base.Index
@_inlineable
public static func == (
lhs: ReversedIndex<Base>,
rhs: ReversedIndex<Base>
@@ -105,6 +108,7 @@ public struct ReversedIndex<Base : Collection> : Comparable {
return lhs.base == rhs.base
}
@_inlineable
public static func < (
lhs: ReversedIndex<Base>,
rhs: ReversedIndex<Base>
@@ -130,6 +134,7 @@ public struct ReversedIndex<Base : Collection> : Comparable {
/// * `c.lazy.reversed().map(f)` maps lazily and returns a `LazyMapCollection`
///
/// - See also: `ReversedRandomAccessCollection`
@_fixed_layout
public struct ReversedCollection<
Base : BidirectionalCollection
> : BidirectionalCollection {
@@ -137,6 +142,8 @@ public struct ReversedCollection<
/// reverse order.
///
/// - Complexity: O(1)
@_versioned
@_inlineable
internal init(_base: Base) {
self._base = _base
}
@@ -153,27 +160,33 @@ public struct ReversedCollection<
/// encapsulates its iteration state.
public typealias Iterator = IndexingIterator<ReversedCollection>
@_inlineable
public var startIndex: Index {
return ReversedIndex(_base.endIndex)
}
@_inlineable
public var endIndex: Index {
return ReversedIndex(_base.startIndex)
}
@_inlineable
public func index(after i: Index) -> Index {
return ReversedIndex(_base.index(before: i.base))
}
@_inlineable
public func index(before i: Index) -> Index {
return ReversedIndex(_base.index(after: i.base))
}
@_inlineable
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
return ReversedIndex(_base.index(i.base, offsetBy: -n))
}
@_inlineable
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
@@ -181,15 +194,19 @@ public struct ReversedCollection<
return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { ReversedIndex($0) }
}
@_inlineable
public func distance(from start: Index, to end: Index) -> IndexDistance {
return _base.distance(from: end.base, to: start.base)
}
public typealias _Element = Base.Iterator.Element
@_inlineable
public subscript(position: Index) -> Base.Iterator.Element {
return _base[_base.index(before: position.base)]
}
@_inlineable
public subscript(bounds: Range<Index>) -> BidirectionalSlice<ReversedCollection> {
return BidirectionalSlice(base: self, bounds: bounds)
}
@@ -199,6 +216,7 @@ public struct ReversedCollection<
/// An index that traverses the same positions as an underlying index,
/// with inverted traversal direction.
@_fixed_layout
public struct ReversedRandomAccessIndex<
Base : RandomAccessCollection
> : Comparable {
@@ -225,6 +243,7 @@ public struct ReversedRandomAccessIndex<
/// the element *after* `"a"`.
///
/// - Parameter base: The position after the element to create an index for.
@_inlineable
public init(_ base: Base.Index) {
self.base = base
}
@@ -257,6 +276,7 @@ public struct ReversedRandomAccessIndex<
/// // Prints "Last even number: 40"
public let base: Base.Index
@_inlineable
public static func == (
lhs: ReversedRandomAccessIndex<Base>,
rhs: ReversedRandomAccessIndex<Base>
@@ -264,6 +284,7 @@ public struct ReversedRandomAccessIndex<
return lhs.base == rhs.base
}
@_inlineable
public static func < (
lhs: ReversedRandomAccessIndex<Base>,
rhs: ReversedRandomAccessIndex<Base>
@@ -279,6 +300,7 @@ public struct ReversedRandomAccessIndex<
/// - Note: This type is the result of `x.reversed()` where `x` is a
/// collection having random access indices.
/// - See also: `ReversedCollection`
@_fixed_layout
public struct ReversedRandomAccessCollection<
Base : RandomAccessCollection
> : RandomAccessCollection {
@@ -289,6 +311,8 @@ public struct ReversedRandomAccessCollection<
/// reverse order.
///
/// - Complexity: O(1)
@_versioned
@_inlineable
internal init(_base: Base) {
self._base = _base
}
@@ -307,28 +331,34 @@ public struct ReversedRandomAccessCollection<
ReversedRandomAccessCollection
>
@_inlineable
public var startIndex: Index {
return ReversedRandomAccessIndex(_base.endIndex)
}
@_inlineable
public var endIndex: Index {
return ReversedRandomAccessIndex(_base.startIndex)
}
@_inlineable
public func index(after i: Index) -> Index {
return ReversedRandomAccessIndex(_base.index(before: i.base))
}
@_inlineable
public func index(before i: Index) -> Index {
return ReversedRandomAccessIndex(_base.index(after: i.base))
}
@_inlineable
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
// FIXME: swift-3-indexing-model: tests.
return ReversedRandomAccessIndex(_base.index(i.base, offsetBy: -n))
}
@_inlineable
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
@@ -337,6 +367,7 @@ public struct ReversedRandomAccessCollection<
return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { Index($0) }
}
@_inlineable
public func distance(from start: Index, to end: Index) -> IndexDistance {
// FIXME: swift-3-indexing-model: tests.
return _base.distance(from: end.base, to: start.base)
@@ -345,6 +376,7 @@ public struct ReversedRandomAccessCollection<
public typealias _Element = Base.Iterator.Element
// FIXME(compiler limitation): this typealias should be inferred.
@_inlineable
public subscript(position: Index) -> Base.Iterator.Element {
return _base[_base.index(before: position.base)]
}
@@ -380,6 +412,7 @@ extension BidirectionalCollection {
/// // Prints "sdrawkcaB"
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> ReversedCollection<Self> {
return ReversedCollection(_base: self)
}
@@ -413,6 +446,7 @@ extension RandomAccessCollection {
/// // Prints "[7, 5, 3]"
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> ReversedRandomAccessCollection<Self> {
return ReversedRandomAccessCollection(_base: self)
}
@@ -426,6 +460,7 @@ extension LazyCollectionProtocol
/// Returns the elements of the collection in reverse order.
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> LazyBidirectionalCollection<
ReversedCollection<Elements>
> {
@@ -441,6 +476,7 @@ extension LazyCollectionProtocol
/// Returns the elements of the collection in reverse order.
///
/// - Complexity: O(1)
@_inlineable
public func reversed() -> LazyRandomAccessCollection<
ReversedRandomAccessCollection<Elements>
> {

View File

@@ -454,6 +454,8 @@ func _uint64ToString(
}
}
@_inlineable
@_versioned
func _rawPointerToString(_ value: Builtin.RawPointer) -> String {
var result = _uint64ToString(
UInt64(

View File

@@ -631,6 +631,7 @@ public protocol Sequence {
extension Sequence
where Self.Iterator == Self, Self : IteratorProtocol {
/// Returns an iterator over the elements of this sequence.
@_inlineable
public func makeIterator() -> Self {
return self
}
@@ -643,23 +644,34 @@ extension Sequence
///
/// This is a class - we require reference semantics to keep track
/// of how many elements we've already dropped from the underlying sequence.
@_versioned
@_fixed_layout
internal class _DropFirstSequence<Base : IteratorProtocol>
: Sequence, IteratorProtocol {
@_versioned
internal var _iterator: Base
@_versioned
internal let _limit: Int
@_versioned
internal var _dropped: Int
@_versioned
@_inlineable
internal init(_iterator: Base, limit: Int, dropped: Int = 0) {
self._iterator = _iterator
self._limit = limit
self._dropped = dropped
}
@_versioned
@_inlineable
internal func makeIterator() -> _DropFirstSequence<Base> {
return self
}
@_versioned
@_inlineable
internal func next() -> Base.Element? {
while _dropped < _limit {
if _iterator.next() == nil {
@@ -671,6 +683,8 @@ internal class _DropFirstSequence<Base : IteratorProtocol>
return _iterator.next()
}
@_versioned
@_inlineable
internal func dropFirst(_ n: Int) -> AnySequence<Base.Element> {
// If this is already a _DropFirstSequence, we need to fold in
// the current drop count and drop limit so no data is lost.
@@ -690,22 +704,33 @@ internal class _DropFirstSequence<Base : IteratorProtocol>
///
/// This is a class - we require reference semantics to keep track
/// of how many elements we've already taken from the underlying sequence.
@_fixed_layout
@_versioned
internal class _PrefixSequence<Base : IteratorProtocol>
: Sequence, IteratorProtocol {
@_versioned
internal let _maxLength: Int
@_versioned
internal var _iterator: Base
@_versioned
internal var _taken: Int
@_versioned
@_inlineable
internal init(_iterator: Base, maxLength: Int, taken: Int = 0) {
self._iterator = _iterator
self._maxLength = maxLength
self._taken = taken
}
@_versioned
@_inlineable
internal func makeIterator() -> _PrefixSequence<Base> {
return self
}
@_versioned
@_inlineable
internal func next() -> Base.Element? {
if _taken >= _maxLength { return nil }
_taken += 1
@@ -718,6 +743,8 @@ internal class _PrefixSequence<Base : IteratorProtocol>
return nil
}
@_versioned
@_inlineable
internal func prefix(_ maxLength: Int) -> AnySequence<Base.Element> {
return AnySequence(
_PrefixSequence(
@@ -734,12 +761,18 @@ internal class _PrefixSequence<Base : IteratorProtocol>
///
/// This is a class - we require reference semantics to keep track
/// of how many elements we've already dropped from the underlying sequence.
@_fixed_layout
@_versioned
internal class _DropWhileSequence<Base : IteratorProtocol>
: Sequence, IteratorProtocol {
@_versioned
internal var _iterator: Base
@_versioned
internal var _nextElement: Base.Element?
@_versioned
@_inlineable
internal init(
iterator: Base,
nextElement: Base.Element?,
@@ -753,10 +786,14 @@ internal class _DropWhileSequence<Base : IteratorProtocol>
}
}
@_versioned
@_inlineable
internal func makeIterator() -> _DropWhileSequence<Base> {
return self
}
@_versioned
@_inlineable
internal func next() -> Base.Element? {
guard _nextElement != nil else {
return _iterator.next()
@@ -767,6 +804,8 @@ internal class _DropWhileSequence<Base : IteratorProtocol>
return next
}
@_versioned
@_inlineable
internal func drop(
while predicate: (Base.Element) throws -> Bool
) rethrows -> AnySequence<Base.Element> {
@@ -800,6 +839,7 @@ extension Sequence {
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
@_inlineable
public func map<T>(
_ transform: (Iterator.Element) throws -> T
) rethrows -> [T] {
@@ -835,6 +875,7 @@ extension Sequence {
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be included in the returned array.
/// - Returns: An array of the elements that `includeElement` allowed.
@_inlineable
public func filter(
_ isIncluded: (Iterator.Element) throws -> Bool
) rethrows -> [Iterator.Element] {
@@ -868,6 +909,7 @@ extension Sequence {
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@_inlineable
public func suffix(_ maxLength: Int) -> AnySequence<Iterator.Element> {
_precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence")
if maxLength == 0 { return AnySequence([]) }
@@ -946,6 +988,7 @@ extension Sequence {
/// - isSeparator: A closure that returns `true` if its argument should be
/// used to split the sequence; otherwise, `false`.
/// - Returns: An array of subsequences, split from this sequence's elements.
@_inlineable
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
@@ -997,16 +1040,19 @@ extension Sequence {
/// the sequence, nondestructively.
///
/// - Complexity: O(*n*)
@_inlineable
public var underestimatedCount: Int {
return 0
}
@_inlineable
public func _preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
return nil
}
@_inlineable
public func _customContainsEquatableElement(
_ element: Iterator.Element
) -> Bool? {
@@ -1042,6 +1088,7 @@ extension Sequence {
///
/// - Parameter body: A closure that takes an element of the sequence as a
/// parameter.
@_inlineable
public func forEach(
_ body: (Iterator.Element) throws -> Void
) rethrows {
@@ -1051,6 +1098,8 @@ extension Sequence {
}
}
@_versioned
@_fixed_layout
internal enum _StopIteration : Error {
case stop
}
@@ -1073,6 +1122,7 @@ extension Sequence {
/// element is a match.
/// - Returns: The first element of the sequence that satisfies `predicate`,
/// or `nil` if there is no element that satisfies `predicate`.
@_inlineable
public func first(
where predicate: (Iterator.Element) throws -> Bool
) rethrows -> Iterator.Element? {
@@ -1135,6 +1185,7 @@ extension Sequence where Iterator.Element : Equatable {
/// start or end of the sequence. If `true`, only nonempty subsequences
/// are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this sequence's elements.
@_inlineable
public func split(
separator: Iterator.Element,
maxSplits: Int = Int.max,
@@ -1170,6 +1221,7 @@ extension Sequence where
/// elements.
///
/// - Complexity: O(1).
@_inlineable
public func dropFirst(_ n: Int) -> AnySequence<Iterator.Element> {
_precondition(n >= 0, "Can't drop a negative number of elements from a sequence")
if n == 0 { return AnySequence(self) }
@@ -1194,6 +1246,7 @@ extension Sequence where
/// - Returns: A subsequence leaving off the specified number of elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@_inlineable
public func dropLast(_ n: Int) -> AnySequence<Iterator.Element> {
_precondition(n >= 0, "Can't drop a negative number of elements from a sequence")
if n == 0 { return AnySequence(self) }
@@ -1243,6 +1296,7 @@ extension Sequence where
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
/// - SeeAlso: `prefix(while:)`
@_inlineable
public func drop(
while predicate: (Iterator.Element) throws -> Bool
) rethrows -> AnySequence<Iterator.Element> {
@@ -1269,6 +1323,7 @@ extension Sequence where
/// with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_inlineable
public func prefix(_ maxLength: Int) -> AnySequence<Iterator.Element> {
_precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence")
if maxLength == 0 {
@@ -1301,6 +1356,7 @@ extension Sequence where
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
/// - SeeAlso: `drop(while:)`
@_inlineable
public func prefix(
while predicate: (Iterator.Element) throws -> Bool
) rethrows -> AnySequence<Iterator.Element> {
@@ -1336,6 +1392,7 @@ extension Sequence {
/// sequence.
///
/// - Complexity: O(1)
@_inlineable
public func dropFirst() -> SubSequence { return dropFirst(1) }
/// Returns a subsequence containing all but the last element of the
@@ -1356,6 +1413,7 @@ extension Sequence {
/// - Returns: A subsequence leaving off the last element of the sequence.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@_inlineable
public func dropLast() -> SubSequence { return dropLast(1) }
}
@@ -1367,6 +1425,7 @@ extension Sequence {
///
/// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` are
/// initialized.
@_inlineable
public func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Iterator.Element>
) -> (Iterator,UnsafeMutableBufferPointer<Iterator.Element>.Index) {
@@ -1392,10 +1451,12 @@ extension Sequence {
/// given just an iterator `i`:
///
/// for x in IteratorSequence(i) { ... }
@_fixed_layout
public struct IteratorSequence<
Base : IteratorProtocol
> : IteratorProtocol, Sequence {
/// Creates an instance whose iterator is a copy of `base`.
@_inlineable
public init(_ base: Base) {
_base = base
}
@@ -1407,10 +1468,12 @@ public struct IteratorSequence<
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@_inlineable
public mutating func next() -> Base.Element? {
return _base.next()
}
@_versioned
internal var _base: Base
}

View File

@@ -95,6 +95,7 @@ extension Sequence {
/// // Prints "Mateo"
///
/// - Returns: A sequence of pairs enumerating the sequence.
@_inlineable
public func enumerated() -> EnumeratedSequence<Self> {
return EnumeratedSequence(_base: self)
}
@@ -147,6 +148,7 @@ ${orderingExplanation}
///
/// - SeeAlso: `min(by:)`
% end
@_inlineable
@warn_unqualified_access
public func min(
% if preds:
@@ -200,6 +202,7 @@ ${orderingExplanation}
///
/// - SeeAlso: `max(by:)`
% end
@_inlineable
@warn_unqualified_access
public func max(
% if preds:
@@ -273,6 +276,7 @@ ${equivalenceExplanation}
///
/// - SeeAlso: `starts(with:by:)`
% end
@_inlineable
public func starts<PossiblePrefix>(
with possiblePrefix: PossiblePrefix${"," if preds else ""}
% if preds:
@@ -350,6 +354,7 @@ ${equivalenceExplanation}
///
/// - SeeAlso: `elementsEqual(_:by:)`
% end
@_inlineable
public func elementsEqual<OtherSequence>(
_ other: OtherSequence${"," if preds else ""}
% if preds:
@@ -436,6 +441,7 @@ ${orderingExplanation}
/// perform localized comparison.
/// - SeeAlso: `lexicographicallyPrecedes(_:by:)`
% end
@_inlineable
public func lexicographicallyPrecedes<OtherSequence>(
_ other: OtherSequence${"," if preds else ""}
% if preds:
@@ -490,6 +496,7 @@ extension Sequence where Iterator.Element : Equatable {
/// - Parameter element: The element to find in the sequence.
/// - Returns: `true` if the element was found in the sequence; otherwise,
/// `false`.
@_inlineable
public func contains(_ element: ${GElement}) -> Bool {
if let result = _customContainsEquatableElement(element) {
return result
@@ -540,6 +547,7 @@ extension Sequence {
/// the passed element represents a match.
/// - Returns: `true` if the sequence contains an element that satisfies
/// `predicate`; otherwise, `false`.
@_inlineable
public func contains(
where predicate: (${GElement}) throws -> Bool
) rethrows -> Bool {
@@ -598,6 +606,7 @@ extension Sequence {
/// the caller.
/// - Returns: The final accumulated value. If the sequence has no elements,
/// the result is `initialResult`.
@_inlineable
public func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult:
@@ -625,6 +634,7 @@ extension Sequence {
///
/// - Returns: An array containing the elements of this sequence in
/// reverse order.
@_inlineable
public func reversed() -> [${GElement}] {
// FIXME(performance): optimize to 1 pass? But Array(self) can be
// optimized to a memcpy() sometimes. Those cases are usually collections,
@@ -670,6 +680,7 @@ extension Sequence {
/// - Complexity: O(*m* + *n*), where *m* is the length of this sequence
/// and *n* is the length of the result.
/// - SeeAlso: `joined()`, `map(_:)`
@_inlineable
public func flatMap<SegmentOfResult : Sequence>(
_ transform: (${GElement}) throws -> SegmentOfResult
) rethrows -> [SegmentOfResult.${GElement}] {
@@ -706,6 +717,7 @@ extension Sequence {
///
/// - Complexity: O(*m* + *n*), where *m* is the length of this sequence
/// and *n* is the length of the result.
@_inlineable
public func flatMap<ElementOfResult>(
_ transform: (${GElement}) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {

View File

@@ -17,6 +17,8 @@
#if _runtime(_ObjC)
import SwiftShims
@_inlineable
@_versioned
internal func _makeSwiftNSFastEnumerationState()
-> _SwiftNSFastEnumerationState {
return _SwiftNSFastEnumerationState(

View File

@@ -11,6 +11,7 @@
//===----------------------------------------------------------------------===//
/// Buffer type for `ArraySlice<Element>`.
@_fixed_layout
@_versioned
internal struct _SliceBuffer<Element>
: _ArrayBufferProtocol,
@@ -19,6 +20,8 @@ internal struct _SliceBuffer<Element>
internal typealias NativeStorage = _ContiguousArrayStorage<Element>
internal typealias NativeBuffer = _ContiguousArrayBuffer<Element>
@_inlineable
@_versioned
internal init(
owner: AnyObject, subscriptBaseAddress: UnsafeMutablePointer<Element>,
indices: Range<Int>, hasNativeBuffer: Bool
@@ -31,6 +34,8 @@ internal struct _SliceBuffer<Element>
_invariantCheck()
}
@_inlineable
@_versioned
internal init() {
let empty = _ContiguousArrayBuffer<Element>()
self.owner = empty.owner
@@ -40,6 +45,8 @@ internal struct _SliceBuffer<Element>
_invariantCheck()
}
@_inlineable
@_versioned
internal init(_buffer buffer: NativeBuffer, shiftedToStartIndex: Int) {
let shift = buffer.startIndex - shiftedToStartIndex
self.init(
@@ -49,6 +56,7 @@ internal struct _SliceBuffer<Element>
hasNativeBuffer: true)
}
@_versioned
internal func _invariantCheck() {
let isNative = _hasNativeBuffer
let isNativeStorage: Bool = owner is _ContiguousArrayStorageBase
@@ -58,16 +66,19 @@ internal struct _SliceBuffer<Element>
}
}
@_versioned
internal var _hasNativeBuffer: Bool {
return (endIndexAndFlags & 1) != 0
}
@_versioned
internal var nativeBuffer: NativeBuffer {
_sanityCheck(_hasNativeBuffer)
return NativeBuffer(
owner as? _ContiguousArrayStorageBase ?? _emptyArrayStorage)
}
@_versioned
internal var nativeOwner: AnyObject {
_sanityCheck(_hasNativeBuffer, "Expect a native array")
return owner
@@ -79,6 +90,7 @@ internal struct _SliceBuffer<Element>
/// - Precondition: This buffer is backed by a uniquely-referenced
/// `_ContiguousArrayBuffer` and
/// `insertCount <= numericCast(newValues.count)`.
@_versioned
internal mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
with insertCount: Int,
@@ -114,12 +126,15 @@ internal struct _SliceBuffer<Element>
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
@_versioned
internal var identity: UnsafeRawPointer {
return UnsafeRawPointer(firstElementAddress)
}
/// An object that keeps the elements stored in this buffer alive.
@_versioned
internal var owner: AnyObject
@_versioned
internal let subscriptBaseAddress: UnsafeMutablePointer<Element>
@_versioned
@@ -127,15 +142,18 @@ internal struct _SliceBuffer<Element>
return subscriptBaseAddress + startIndex
}
@_versioned
internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {
return firstElementAddress
}
/// [63:1: 63-bit index][0: has a native buffer]
@_versioned
internal var endIndexAndFlags: UInt
//===--- Non-essential bits ---------------------------------------------===//
@_versioned
internal mutating func requestUniqueMutableBackingBuffer(
minimumCapacity: Int
) -> NativeBuffer? {
@@ -165,10 +183,14 @@ internal struct _SliceBuffer<Element>
return nil
}
@_inlineable
@_versioned
internal mutating func isMutableAndUniquelyReferenced() -> Bool {
return _hasNativeBuffer && isUniquelyReferenced()
}
@_inlineable
@_versioned
internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool {
return _hasNativeBuffer && isUniquelyReferencedOrPinned()
}
@@ -176,6 +198,7 @@ internal struct _SliceBuffer<Element>
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@_versioned
internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? {
_invariantCheck()
if _fastPath(_hasNativeBuffer && nativeBuffer.count == count) {
@@ -184,6 +207,7 @@ internal struct _SliceBuffer<Element>
return nil
}
@_versioned
@discardableResult
internal func _copyContents(
subRange bounds: Range<Int>,
@@ -199,10 +223,12 @@ internal struct _SliceBuffer<Element>
}
/// True, if the array is native and does not need a deferred type check.
@_versioned
internal var arrayPropertyIsNativeTypeChecked: Bool {
return _hasNativeBuffer
}
@_versioned
internal var count: Int {
get {
return endIndex - startIndex
@@ -219,11 +245,13 @@ internal struct _SliceBuffer<Element>
/// Traps unless the given `index` is valid for subscripting, i.e.
/// `startIndex index < endIndex`
@_versioned
internal func _checkValidSubscript(_ index : Int) {
_precondition(
index >= startIndex && index < endIndex, "Index out of bounds")
}
@_versioned
internal var capacity: Int {
let count = self.count
if _slowPath(!_hasNativeBuffer) {
@@ -237,10 +265,12 @@ internal struct _SliceBuffer<Element>
return count
}
@_versioned
internal mutating func isUniquelyReferenced() -> Bool {
return isKnownUniquelyReferenced(&owner)
}
@_versioned
internal mutating func isUniquelyReferencedOrPinned() -> Bool {
return _isKnownUniquelyReferencedOrPinned(&owner)
}
@@ -267,6 +297,7 @@ internal struct _SliceBuffer<Element>
}
}
@_versioned
internal subscript(bounds: Range<Int>) -> _SliceBuffer {
get {
_sanityCheck(bounds.lowerBound >= startIndex)
@@ -287,6 +318,7 @@ internal struct _SliceBuffer<Element>
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
@_versioned
internal var startIndex: Int
/// The collection's "past the end" position---that is, the position one
@@ -294,6 +326,7 @@ internal struct _SliceBuffer<Element>
///
/// `endIndex` is always reachable from `startIndex` by zero or more
/// applications of `index(after:)`.
@_versioned
internal var endIndex: Int {
get {
return Int(endIndexAndFlags >> 1)
@@ -308,6 +341,8 @@ internal struct _SliceBuffer<Element>
//===--- misc -----------------------------------------------------------===//
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage.
@_inlineable
@_versioned
internal func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
@@ -318,6 +353,8 @@ internal struct _SliceBuffer<Element>
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
@_inlineable
@_versioned
internal mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {

View File

@@ -25,6 +25,8 @@ def cmp(a, b, p):
% preds = [True, False]
% for p in preds:
@_inlineable
@_versioned
func _insertionSort<C>(
_ elements: inout C,
subRange range: Range<C.Index>
@@ -80,6 +82,7 @@ func _insertionSort<C>(
///
/// - Precondition: `a < b && b < c`
/// - Postcondition: `elements[a] <= elements[b] && elements[b] <= elements[c]`
@_inlineable
public // @testable
func _sort3<C>(
_ elements: inout C,
@@ -151,6 +154,8 @@ func _sort3<C>(
///
/// - Precondition: The count of `range` must be >= 3:
/// `elements.distance(from: range.lowerBound, to: range.upperBound) >= 3`
@_inlineable
@_versioned
func _partition<C>(
_ elements: inout C,
subRange range: Range<C.Index>
@@ -200,6 +205,7 @@ func _partition<C>(
return lo
}
@_inlineable
public // @testable
func _introSort<C>(
_ elements: inout C,
@@ -224,6 +230,8 @@ func _introSort<C>(
depthLimit: depthLimit)
}
@_inlineable
@_versioned
func _introSortImpl<C>(
_ elements: inout C,
subRange range: Range<C.Index>
@@ -268,6 +276,8 @@ func _introSortImpl<C>(
depthLimit: depthLimit &- 1)
}
@_inlineable
@_versioned
func _siftDown<C>(
_ elements: inout C,
index: C.Index,
@@ -308,6 +318,8 @@ func _siftDown<C>(
}
}
@_inlineable
@_versioned
func _heapify<C>(
_ elements: inout C,
subRange range: Range<C.Index>
@@ -337,6 +349,8 @@ func _heapify<C>(
}
}
@_inlineable
@_versioned
func _heapSort<C>(
_ elements: inout C,
subRange range: Range<C.Index>
@@ -368,6 +382,7 @@ func _heapSort<C>(
/// Exchange the values of `a` and `b`.
///
/// - Precondition: `a` and `b` do not alias each other.
@_inlineable
public func swap<T>(_ a: inout T, _ b: inout T) {
// Semantically equivalent to (a, b) = (b, a).
// Microoptimized to avoid retain/release traffic.
@@ -384,3 +399,4 @@ public func swap<T>(_ a: inout T, _ b: inout T) {
// Initialize P2.
Builtin.initialize(tmp, p2)
}

View File

@@ -54,10 +54,12 @@ public protocol ${Self} : ${Conformance} {
% end
/// Compare two `Strideable`s.
@_inlineable
public func < <T : Strideable>(x: T, y: T) -> Bool {
return x.distance(to: y) > 0
}
@_inlineable
public func == <T : Strideable>(x: T, y: T) -> Bool {
return x.distance(to: y) == 0
}
@@ -72,6 +74,7 @@ public func == <T : Strideable>(x: T, y: T) -> Bool {
% if deprecated:
@available(swift, deprecated: ${DeprecationVersion}, obsoleted: 4.0, message: "Mixed-type addition is deprecated. Please use explicit type conversion.")
% end
@_inlineable
public func + <T : ${Base}>(lhs: T, rhs: T.Stride) -> T {
return lhs.advanced(by: rhs)
}
@@ -79,6 +82,7 @@ public func + <T : ${Base}>(lhs: T, rhs: T.Stride) -> T {
% if deprecated:
@available(swift, deprecated: ${DeprecationVersion}, obsoleted: 4.0, message: "Mixed-type addition is deprecated. Please use explicit type conversion.")
% end
@_inlineable
public func + <T : ${Base}>(lhs: T.Stride, rhs: T) -> T {
return rhs.advanced(by: lhs)
}
@@ -86,6 +90,7 @@ public func + <T : ${Base}>(lhs: T.Stride, rhs: T) -> T {
% if deprecated:
@available(swift, deprecated: ${DeprecationVersion}, obsoleted: 4.0, message: "Mixed-type subtraction is deprecated. Please use explicit type conversion.")
% end
@_inlineable
public func - <T : ${Base}>(lhs: T, rhs: T.Stride) -> T {
return lhs.advanced(by: -rhs)
}
@@ -93,6 +98,7 @@ public func - <T : ${Base}>(lhs: T, rhs: T.Stride) -> T {
% if deprecated:
@available(swift, deprecated: ${DeprecationVersion}, obsoleted: 4.0, message: "Mixed-type subtraction is deprecated. Please use explicit type conversion.")
% end
@_inlineable
public func - <T : ${Base}>(lhs: T, rhs: T) -> T.Stride {
return rhs.distance(to: lhs)
}
@@ -100,6 +106,7 @@ public func - <T : ${Base}>(lhs: T, rhs: T) -> T.Stride {
% if deprecated:
@available(swift, deprecated: ${DeprecationVersion}, obsoleted: 4.0, message: "Mixed-type addition is deprecated. Please use explicit type conversion.")
% end
@_inlineable
public func += <T : ${Base}>(lhs: inout T, rhs: T.Stride) {
lhs = lhs.advanced(by: rhs)
}
@@ -107,6 +114,7 @@ public func += <T : ${Base}>(lhs: inout T, rhs: T.Stride) {
% if deprecated:
@available(swift, deprecated: ${DeprecationVersion}, obsoleted: 4.0, message: "Mixed-type subtraction is deprecated. Please use explicit type conversion.")
% end
@_inlineable
public func -= <T : ${Base}>(lhs: inout T, rhs: T.Stride) {
lhs = lhs.advanced(by: -rhs)
}
@@ -157,6 +165,7 @@ public func -= <T : UnsignedInteger>(
//===----------------------------------------------------------------------===//
extension Strideable {
@_inlineable
public static func _step(
after current: (index: Int?, value: Self),
from start: Self, by distance: Self.Stride
@@ -166,6 +175,7 @@ extension Strideable {
}
extension Strideable where Stride : FloatingPoint {
@_inlineable
public static func _step(
after current: (index: Int?, value: Self),
from start: Self, by distance: Self.Stride
@@ -181,12 +191,22 @@ extension Strideable where Stride : FloatingPoint {
}
/// An iterator for `StrideTo<Element>`.
@_fixed_layout
public struct StrideToIterator<Element : Strideable> : IteratorProtocol {
@_versioned
internal let _start: Element
@_versioned
internal let _end: Element
@_versioned
internal let _stride: Element.Stride
@_versioned
internal var _current: (index: Int?, value: Element)
@_inlineable
@_versioned
internal init(_start: Element, end: Element, stride: Element.Stride) {
self._start = _start
_end = end
@@ -198,6 +218,8 @@ public struct StrideToIterator<Element : Strideable> : IteratorProtocol {
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@_inlineable
public mutating func next() -> Element? {
let result = _current.value
if _stride > 0 ? result >= _end : result <= _end {
@@ -209,16 +231,20 @@ public struct StrideToIterator<Element : Strideable> : IteratorProtocol {
}
/// A `Sequence` of values formed by striding over a half-open interval.
@_fixed_layout
public struct StrideTo<Element : Strideable> : Sequence, CustomReflectable {
// FIXME: should really be a Collection, as it is multipass
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@_inlineable
public func makeIterator() -> StrideToIterator<Element> {
return StrideToIterator(_start: _start, end: _end, stride: _stride)
}
@_inlineable
@_versioned
internal init(_start: Element, end: Element, stride: Element.Stride) {
_precondition(stride != 0, "stride size must not be zero")
// At start, striding away from end is allowed; it just makes for an
@@ -228,8 +254,13 @@ public struct StrideTo<Element : Strideable> : Sequence, CustomReflectable {
self._stride = stride
}
@_versioned
internal let _start: Element
@_versioned
internal let _end: Element
@_versioned
internal let _stride: Element.Stride
public var customMirror: Mirror {
@@ -240,6 +271,7 @@ public struct StrideTo<Element : Strideable> : Sequence, CustomReflectable {
/// Returns the sequence of values (`self`, `self + stride`, `self +
/// 2 * stride`, ... *last*) where *last* is the last value in the
/// progression that is less than `end`.
@_inlineable
public func stride<T : Strideable>(
from start: T, to end: T, by stride: T.Stride
) -> StrideTo<T> {
@@ -247,13 +279,25 @@ public func stride<T : Strideable>(
}
/// An iterator for `StrideThrough<Element>`.
@_fixed_layout
public struct StrideThroughIterator<Element : Strideable> : IteratorProtocol {
@_versioned
internal let _start: Element
@_versioned
internal let _end: Element
@_versioned
internal let _stride: Element.Stride
@_versioned
internal var _current: (index: Int?, value: Element)
@_versioned
internal var _didReturnEnd: Bool = false
@_inlineable
@_versioned
internal init(_start: Element, end: Element, stride: Element.Stride) {
self._start = _start
_end = end
@@ -265,6 +309,7 @@ public struct StrideThroughIterator<Element : Strideable> : IteratorProtocol {
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@_inlineable
public mutating func next() -> Element? {
let result = _current.value
if _stride > 0 ? result >= _end : result <= _end {
@@ -283,6 +328,7 @@ public struct StrideThroughIterator<Element : Strideable> : IteratorProtocol {
}
/// A `Sequence` of values formed by striding over a closed interval.
@_fixed_layout
public struct StrideThrough<
Element : Strideable
> : Sequence, CustomReflectable {
@@ -291,10 +337,13 @@ public struct StrideThrough<
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@_inlineable
public func makeIterator() -> StrideThroughIterator<Element> {
return StrideThroughIterator(_start: _start, end: _end, stride: _stride)
}
@_inlineable
@_versioned
internal init(_start: Element, end: Element, stride: Element.Stride) {
_precondition(stride != 0, "stride size must not be zero")
self._start = _start
@@ -302,8 +351,11 @@ public struct StrideThrough<
self._stride = stride
}
@_versioned
internal let _start: Element
@_versioned
internal let _end: Element
@_versioned
internal let _stride: Element.Stride
public var customMirror: Mirror {
@@ -317,6 +369,7 @@ public struct StrideThrough<
/// progression less than or equal to `end`.
///
/// - Note: There is no guarantee that `end` is an element of the sequence.
@_inlineable
public func stride<T : Strideable>(
from start: T, through end: T, by stride: T.Stride
) -> StrideThrough<T> {

View File

@@ -25,6 +25,7 @@ extension String : _ExpressibleByStringInterpolation {
/// "\(number) cookies cost \(price * number) dollars."
/// print(message)
/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
@_inlineable
@effects(readonly)
public init(stringInterpolation strings: String...) {
self.init()
@@ -40,6 +41,7 @@ extension String : _ExpressibleByStringInterpolation {
/// interpreting string interpolations.
///
/// - SeeAlso: `ExpressibleByStringInterpolation`
@_inlineable
public init<T>(stringInterpolationSegment expr: T) {
self = String(describing: expr)
}
@@ -50,6 +52,7 @@ extension String : _ExpressibleByStringInterpolation {
/// interpreting string interpolations.
///
/// - SeeAlso: `ExpressibleByStringInterpolation`
@_inlineable
public init<T: TextOutputStreamable> (stringInterpolationSegment expr: T) {
self = _toStringReadOnlyStreamable(expr)
}
@@ -60,6 +63,7 @@ extension String : _ExpressibleByStringInterpolation {
/// interpreting string interpolations.
///
/// - SeeAlso: `ExpressibleByStringInterpolation`
@_inlineable
public init<T: CustomStringConvertible> (stringInterpolationSegment expr: T) {
self = _toStringReadOnlyPrintable(expr)
}

View File

@@ -23,6 +23,7 @@ import SwiftShims
/// Returns `true` iff the given `index` is valid as a position, i.e. `0
/// index count`.
@_versioned
@_transparent
internal func _isValidArrayIndex(_ index: Int, count: Int) -> Bool {
return (index >= 0) && (index <= count)
@@ -30,6 +31,7 @@ internal func _isValidArrayIndex(_ index: Int, count: Int) -> Bool {
/// Returns `true` iff the given `index` is valid for subscripting, i.e.
/// `0 index < count`.
@_versioned
@_transparent
internal func _isValidArraySubscript(_ index: Int, count: Int) -> Bool {
return (index >= 0) && (index < count)
@@ -37,10 +39,13 @@ internal func _isValidArraySubscript(_ index: Int, count: Int) -> Bool {
/// An `NSArray` with Swift-native reference counting and contiguous
/// storage.
@_versioned
internal class _SwiftNativeNSArrayWithContiguousStorage
: _SwiftNativeNSArray { // Provides NSArray inheritance and native refcounting
// Operate on our contiguous storage
@_inlineable
@_versioned
internal func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
@@ -51,10 +56,14 @@ internal class _SwiftNativeNSArrayWithContiguousStorage
// Implement the APIs required by NSArray
extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
@_inlineable
@_versioned
@objc internal var count: Int {
return withUnsafeBufferOfObjects { $0.count }
}
@_inlineable
@_versioned
@objc(objectAtIndex:)
internal func objectAt(_ index: Int) -> AnyObject {
return withUnsafeBufferOfObjects {
@@ -66,6 +75,8 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
}
}
@_inlineable
@_versioned
@objc internal func getObjects(
_ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange
) {
@@ -91,6 +102,8 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
}
}
@_inlineable
@_versioned
@objc(countByEnumeratingWithState:objects:count:)
internal func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
@@ -113,6 +126,8 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
}
}
@_inlineable
@_versioned
@objc(copyWithZone:)
internal func copy(with _: _SwiftNSZone?) -> AnyObject {
return self
@@ -124,6 +139,11 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
///
/// Ideally instances of this class would be allocated in-line in the
/// buffers used for Array storage.
///
/// FIXME: If this class is not marked as @_fixed_layout and init
/// not marked as @_inlineable, many executable tests are crashing
/// in resilient stdlib builds.
@_versioned
@objc internal final class _SwiftDeferredNSArray
: _SwiftNativeNSArrayWithContiguousStorage {
@@ -131,19 +151,25 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
// operations on it.
//
// Do not access this property directly.
@_versioned
internal var _heapBufferBridged_DoNotUse: AnyObject?
// When this class is allocated inline, this property can become a
// computed one.
@_versioned
internal let _nativeStorage: _ContiguousArrayStorageBase
@_inlineable
@_versioned
internal var _heapBufferBridgedPtr: UnsafeMutablePointer<AnyObject?> {
return _getUnsafePointerToStoredProperties(self).assumingMemoryBound(
to: Optional<AnyObject>.self)
}
internal typealias HeapBufferStorage = _HeapBufferStorage<Int, AnyObject>
@_inlineable
@_versioned
internal var _heapBufferBridged: HeapBufferStorage? {
if let ref =
_stdlib_atomicLoadARCRef(object: _heapBufferBridgedPtr) {
@@ -152,10 +178,13 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
return nil
}
@_versioned
internal init(_nativeStorage: _ContiguousArrayStorageBase) {
self._nativeStorage = _nativeStorage
}
@_inlineable
@_versioned
internal func _destroyBridgedStorage(_ hb: HeapBufferStorage?) {
if let bridgedStorage = hb {
let heapBuffer = _HeapBuffer(bridgedStorage)
@@ -168,6 +197,8 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
_destroyBridgedStorage(_heapBufferBridged)
}
@_inlineable
@_versioned
internal override func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
@@ -212,6 +243,8 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
///
/// This override allows the count to be read without triggering
/// bridging of array elements.
@_inlineable
@_versioned
@objc
internal override var count: Int {
if let bridgedStorage = _heapBufferBridged {
@@ -225,13 +258,21 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore {
}
#else
// Empty shim version for non-objc platforms.
class _SwiftNativeNSArrayWithContiguousStorage {}
@_versioned
class _SwiftNativeNSArrayWithContiguousStorage {
@_inlineable
@_versioned
init() {}
}
#endif
/// Base class of the heap buffer backing arrays.
@_versioned
@_fixed_layout
internal class _ContiguousArrayStorageBase
: _SwiftNativeNSArrayWithContiguousStorage {
@_versioned
final var countAndCapacity: _ArrayBody
init(_doNotCallMeBase: ()) {
@@ -239,6 +280,8 @@ internal class _ContiguousArrayStorageBase
}
#if _runtime(_ObjC)
@_inlineable
@_versioned
internal override func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
@@ -252,6 +295,7 @@ internal class _ContiguousArrayStorageBase
/// If the stored type is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements and return the result.
/// Otherwise, return `nil`.
@_versioned
internal func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
@@ -259,11 +303,13 @@ internal class _ContiguousArrayStorageBase
"Concrete subclasses must implement _withVerbatimBridgedUnsafeBuffer")
}
@_versioned
internal func _getNonVerbatimBridgedCount() -> Int {
_sanityCheckFailure(
"Concrete subclasses must implement _getNonVerbatimBridgedCount")
}
@_versioned
internal func _getNonVerbatimBridgedHeapBuffer() ->
_HeapBuffer<Int, AnyObject> {
_sanityCheckFailure(
@@ -271,12 +317,14 @@ internal class _ContiguousArrayStorageBase
}
#endif
@_versioned
func canStoreElements(ofDynamicType _: Any.Type) -> Bool {
_sanityCheckFailure(
"Concrete subclasses must implement canStoreElements(ofDynamicType:)")
}
/// A type that every element in the array is.
@_versioned
var staticElementType: Any.Type {
_sanityCheckFailure(
"Concrete subclasses must implement staticElementType")

View File

@@ -12,6 +12,7 @@
/// An iterator for the elements in the buffer referenced by an
/// `UnsafeBufferPointer` or `UnsafeMutableBufferPointer` instance.
@_fixed_layout
public struct UnsafeBufferPointerIterator<Element>
: IteratorProtocol, Sequence {
@@ -19,6 +20,7 @@ public struct UnsafeBufferPointerIterator<Element>
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@_inlineable
public mutating func next() -> Element? {
if _position == _end { return nil }
@@ -27,7 +29,14 @@ public struct UnsafeBufferPointerIterator<Element>
return result
}
@_versioned
internal var _position, _end: UnsafePointer<Element>?
@_inlineable
public init(_position: UnsafePointer<Element>?, _end: UnsafePointer<Element>?) {
self._position = _position
self._end = _end
}
}
% for mutable in (True, False):
@@ -66,6 +75,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
///
/// The `startIndex` property of an `Unsafe${Mutable}BufferPointer` instance
/// is always zero.
@_inlineable
public var startIndex: Int {
return 0
}
@@ -75,10 +85,12 @@ public struct Unsafe${Mutable}BufferPointer<Element>
///
/// The `endIndex` property of an `Unsafe${Mutable}BufferPointer` instance is
/// always identical to `count`.
@_inlineable
public var endIndex: Int {
return count
}
@_inlineable
public func index(after i: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for UnsafeBufferPointer performance. The
@@ -88,6 +100,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
return i + 1
}
@_inlineable
public func formIndex(after i: inout Int) {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for UnsafeBufferPointer performance. The
@@ -97,6 +110,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
i += 1
}
@_inlineable
public func index(before i: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for UnsafeBufferPointer performance. The
@@ -106,6 +120,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
return i - 1
}
@_inlineable
public func formIndex(before i: inout Int) {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for UnsafeBufferPointer performance. The
@@ -115,6 +130,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
i -= 1
}
@_inlineable
public func index(_ i: Int, offsetBy n: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for UnsafeBufferPointer performance. The
@@ -124,6 +140,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
return i + n
}
@_inlineable
public func index(
_ i: Int, offsetBy n: Int, limitedBy limit: Int
) -> Int? {
@@ -139,6 +156,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
return i + n
}
@_inlineable
public func distance(from start: Int, to end: Int) -> Int {
// NOTE: this is a manual specialization of index movement for a Strideable
// index that is required for UnsafeBufferPointer performance. The
@@ -148,16 +166,19 @@ public struct Unsafe${Mutable}BufferPointer<Element>
return end - start
}
@_inlineable
public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) {
// NOTE: This method is a no-op for performance reasons.
}
@_inlineable
public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) {
// NOTE: This method is a no-op for performance reasons.
}
public typealias Indices = CountableRange<Int>
@_inlineable
public var indices: Indices {
return startIndex..<endIndex
}
@@ -198,6 +219,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
///
/// - Parameter i: The position of the element to access. `i` must be in the
/// range `0..<count`.
@_inlineable
public subscript(i: Int) -> Element {
get {
_debugPrecondition(i >= 0)
@@ -213,6 +235,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
%end
}
@_inlineable
public subscript(bounds: Range<Int>)
-> ${Mutable}RandomAccessSlice<Unsafe${Mutable}BufferPointer<Element>>
{
@@ -242,6 +265,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
/// `MemoryLayout<Element>.alignment`.
/// - count: The number of instances in the buffer. `count` must not be
/// negative.
@_inlineable
public init(start: Unsafe${Mutable}Pointer<Element>?, count: Int) {
_precondition(
count >= 0, "Unsafe${Mutable}BufferPointer with negative count")
@@ -255,6 +279,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
/// Returns an iterator over the elements of this buffer.
///
/// - Returns: An iterator over the elements of this buffer.
@_inlineable
public func makeIterator() -> UnsafeBufferPointerIterator<Element> {
return UnsafeBufferPointerIterator(_position: _position, _end: _end)
}
@@ -263,6 +288,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
///
/// If the `baseAddress` of this buffer is `nil`, the count is zero. However,
/// a buffer can have a `count` of zero even with a non-`nil` base address.
@_inlineable
public var baseAddress: Unsafe${Mutable}Pointer<Element>? {
return _position
}
@@ -271,6 +297,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
///
/// If the `baseAddress` of this buffer is `nil`, the count is zero. However,
/// a buffer can have a `count` of zero even with a non-`nil` base address.
@_inlineable
public var count: Int {
if let pos = _position {
return _end! - pos
@@ -278,6 +305,7 @@ public struct Unsafe${Mutable}BufferPointer<Element>
return 0
}
@_versioned
let _position, _end: Unsafe${Mutable}Pointer<Element>?
}
@@ -303,6 +331,7 @@ extension UnsafeMutableBufferPointer {
///
/// - Postcondition: The `Pointee`s at `self[startIndex..<returned index]` are
/// initialized.
@_inlineable
public func initialize<S: Sequence>(from source: S) -> (S.Iterator, Index)
where S.Iterator.Element == Iterator.Element {
return source._copyContents(initializing: self)

View File

@@ -419,6 +419,7 @@ public struct ${Self}<Pointee>
///
/// - Parameter count: The amount of memory to allocate, counted in instances
/// of `Pointee`.
@_inlineable
static public func allocate(capacity count: Int)
-> UnsafeMutablePointer<Pointee> {
let size = MemoryLayout<Pointee>.stride * count
@@ -436,6 +437,7 @@ public struct ${Self}<Pointee>
///
/// - Parameter capacity: The amount of memory to deallocate, counted in
/// instances of `Pointee`.
@_inlineable
public func deallocate(capacity: Int) {
let size = MemoryLayout<Pointee>.stride * capacity
Builtin.deallocRaw(
@@ -485,6 +487,7 @@ public struct ${Self}<Pointee>
/// - newValue: The instance to initialize this pointer's memory with.
/// - count: The number of consecutive copies of `newValue` to initialize.
/// `count` must not be negative. The default is `1`.
@_inlineable
public func initialize(to newValue: Pointee, count: Int = 1) {
// FIXME: add tests (since the `count` has been added)
_debugPrecondition(count >= 0,
@@ -512,6 +515,7 @@ public struct ${Self}<Pointee>
/// `move()`, the memory is uninitialized.
///
/// - Returns: The instance referenced by this pointer.
@_inlineable
public func move() -> Pointee {
return Builtin.take(_rawValue)
}
@@ -530,6 +534,7 @@ public struct ${Self}<Pointee>
/// pointer may overlap.
/// - count: The number of instances to copy from the memory referenced by
/// `source` to this pointer's memory. `count` must not be negative.
@_inlineable
public func assign(from source: UnsafePointer<Pointee>, count: Int) {
_debugPrecondition(
count >= 0, "${Self}.assign with negative count")
@@ -565,6 +570,7 @@ public struct ${Self}<Pointee>
/// referenced by `source` and this pointer may overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@_inlineable
public func moveInitialize(from source: ${Self}, count: Int) {
_debugPrecondition(
count >= 0, "${Self}.moveInitialize with negative count")
@@ -604,6 +610,7 @@ public struct ${Self}<Pointee>
/// referenced by `source` and this pointer must not overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@_inlineable
public func initialize(from source: UnsafePointer<Pointee>, count: Int) {
_debugPrecondition(
count >= 0, "${Self}.initialize with negative count")
@@ -630,6 +637,7 @@ public struct ${Self}<Pointee>
/// - Parameter source: A collection of elements of the pointer's `Pointee`
/// type.
// This is fundamentally unsafe since collections can underreport their count.
@_inlineable
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'UnsafeMutableBufferPointer.initialize(from:)' instead")
public func initialize<C : Collection>(from source: C)
where C.Iterator.Element == Pointee {
@@ -655,6 +663,7 @@ public struct ${Self}<Pointee>
/// referenced by `source` and this pointer must not overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@_inlineable
public func moveAssign(from source: ${Self}, count: Int) {
_debugPrecondition(
count >= 0, "${Self}.moveAssign(from:) with negative count")
@@ -681,6 +690,7 @@ public struct ${Self}<Pointee>
/// not be negative. The default value is `1`.
/// - Returns: A raw pointer to the same address as this pointer. The memory
/// referenced by the returned raw pointer is still bound to `Pointee`.
@_inlineable
@discardableResult
public func deinitialize(count: Int = 1) -> UnsafeMutableRawPointer {
_debugPrecondition(count >= 0, "${Self}.deinitialize with negative count")
@@ -732,6 +742,7 @@ public struct ${Self}<Pointee>
/// execution. If `body` has a return value, it is used as the return
/// value for the `withMemoryRebound(to:capacity:_:)` method.
/// - Returns: The return value of the `body` closure parameter, if any.
@_inlineable
public func withMemoryRebound<T, Result>(to type: T.Type, capacity count: Int,
_ body: (${Self}<T>) throws -> Result
) rethrows -> Result {
@@ -760,6 +771,7 @@ public struct ${Self}<Pointee>
///
/// - Parameter i: The offset from this pointer at which to access an
/// instance, measured in strides of the pointer's `Pointee` type.
@_inlineable
public subscript(i: Int) -> Pointee {
% if mutable:
@_transparent
@@ -787,6 +799,7 @@ public struct ${Self}<Pointee>
/// The hash value is not guaranteed to be stable across different
/// invocations of the same program. Do not persist the hash value across
/// program runs.
@_inlineable
public var hashValue: Int {
return Int(bitPattern: self)
}
@@ -798,6 +811,7 @@ public struct ${Self}<Pointee>
///
/// - Returns: A pointer advanced from this pointer by
/// `MemoryLayout<Pointee>.stride` bytes.
@_inlineable
public func successor() -> ${Self} {
return self + 1
}
@@ -809,6 +823,7 @@ public struct ${Self}<Pointee>
///
/// - Returns: A pointer shifted backward from this pointer by
/// `MemoryLayout<Pointee>.stride` bytes.
@_inlineable
public func predecessor() -> ${Self} {
return self - 1
}
@@ -832,6 +847,7 @@ public struct ${Self}<Pointee>
/// `MemoryLayout<Pointee>.stride`.
///
/// - SeeAlso: `MemoryLayout`
@_inlineable
public func distance(to end: ${Self}) -> Int {
return end - self
}
@@ -853,6 +869,7 @@ public struct ${Self}<Pointee>
/// `Pointee` type.
///
/// - SeeAlso: `MemoryLayout`
@_inlineable
public func advanced(by n: Int) -> ${Self} {
return self + n
}
@@ -1171,6 +1188,7 @@ extension ${Self} {
}
extension Int {
@_inlineable
public init<U>(bitPattern: ${Self}<U>?) {
if let bitPattern = bitPattern {
self = Int(Builtin.ptrtoint_Word(bitPattern._rawValue))
@@ -1181,6 +1199,7 @@ extension Int {
}
extension UInt {
@_inlineable
public init<U>(bitPattern: ${Self}<U>?) {
if let bitPattern = bitPattern {
self = UInt(Builtin.ptrtoint_Word(bitPattern._rawValue))

View File

@@ -94,6 +94,7 @@
% end
///
/// - SeeAlso: `Unsafe${Mutable}RawPointer`, `Unsafe${Mutable}BufferPointer`
@_fixed_layout
public struct Unsafe${Mutable}RawBufferPointer
: ${Mutable}Collection, RandomAccessCollection {
// TODO: Specialize `index` and `formIndex` and
@@ -104,6 +105,7 @@ public struct Unsafe${Mutable}RawBufferPointer
public typealias SubSequence = ${Self}
/// An iterator over the bytes viewed by a raw buffer pointer.
@_fixed_layout
public struct Iterator : IteratorProtocol, Sequence {
/// Advances to the next byte and returns it, or `nil` if no next byte
@@ -113,6 +115,7 @@ public struct Unsafe${Mutable}RawBufferPointer
///
/// - Returns: The next sequential byte in the raw buffer if another byte
/// exists; otherwise, `nil`.
@_inlineable
public mutating func next() -> UInt8? {
if _position == _end { return nil }
@@ -121,7 +124,15 @@ public struct Unsafe${Mutable}RawBufferPointer
return result
}
@_versioned
internal var _position, _end: UnsafeRawPointer?
@_versioned
@_inlineable
init(_position: UnsafeRawPointer?, _end: UnsafeRawPointer?) {
self._position = _position
self._end = _end
}
}
% if mutable:
@@ -132,6 +143,7 @@ public struct Unsafe${Mutable}RawBufferPointer
///
/// - Parameter size: The number of bytes to allocate.
/// - Returns: A word-aligned buffer pointer covering a region of memory.
@_inlineable
public static func allocate(count size: Int
) -> UnsafeMutableRawBufferPointer {
return UnsafeMutableRawBufferPointer(
@@ -146,6 +158,7 @@ public struct Unsafe${Mutable}RawBufferPointer
/// The memory to be deallocated must not be initialized or must be
/// initialized to a trivial type. For a buffer pointer `p`, all `p.count`
/// bytes referenced by `p` are deallocated.
@_inlineable
public func deallocate() {
_position?.deallocate(
bytes: count, alignedTo: MemoryLayout<UInt>.alignment)
@@ -177,6 +190,7 @@ public struct Unsafe${Mutable}RawBufferPointer
/// with `type`.
/// - Returns: A new instance of type `T`, copied from the buffer pointer's
/// memory.
@_inlineable
public func load<T>(fromByteOffset offset: Int = 0, as type: T.Type) -> T {
_debugPrecondition(offset >= 0, "${Self}.load with negative offset")
_debugPrecondition(offset + MemoryLayout<T>.size <= self.count,
@@ -210,6 +224,7 @@ public struct Unsafe${Mutable}RawBufferPointer
/// - type: The type to use for the newly constructed instance. The memory
/// must be initialized to a value of a type that is layout compatible
/// with `type`.
@_inlineable
public func storeBytes<T>(
of value: T, toByteOffset offset: Int = 0, as: T.Type
) {
@@ -236,6 +251,7 @@ public struct Unsafe${Mutable}RawBufferPointer
/// - source: A pointer to the memory to copy bytes from. The memory at
/// `source..<(source + count)` must be initialized to a trivial type.
/// - count: The number of bytes to copy. `count` must not be negative.
@_inlineable
public func copyBytes(from source: UnsafeRawBufferPointer) {
_debugPrecondition(source.count <= self.count,
"${Self}.copyBytes source has too many elements")
@@ -255,6 +271,7 @@ public struct Unsafe${Mutable}RawBufferPointer
///
/// - Parameter source: A collection of `UInt8` elements. `source.count` must
/// be less than or equal to this buffer's `count`.
@_inlineable
public func copyBytes<C : Collection>(from source: C
) where C.Iterator.Element == UInt8 {
_debugPrecondition(numericCast(source.count) <= self.count,
@@ -278,6 +295,7 @@ public struct Unsafe${Mutable}RawBufferPointer
/// non-`nil` `start`.
/// - count: The number of bytes to include in the buffer. `count` must not
/// be negative.
@_inlineable
public init(start: Unsafe${Mutable}RawPointer?, count: Int) {
_precondition(count >= 0, "${Self} with negative count")
_precondition(count == 0 || start != nil,
@@ -289,6 +307,7 @@ public struct Unsafe${Mutable}RawBufferPointer
/// Creates a new buffer over the same memory as the given buffer.
///
/// - Parameter bytes: The buffer to convert.
@_inlineable
public init(_ bytes: UnsafeMutableRawBufferPointer) {
self.init(start: bytes.baseAddress, count: bytes.count)
}
@@ -297,6 +316,7 @@ public struct Unsafe${Mutable}RawBufferPointer
/// Creates a new mutable buffer over the same memory as the given buffer.
///
/// - Parameter bytes: The buffer to convert.
@_inlineable
public init(mutating bytes: UnsafeRawBufferPointer) {
self.init(start: UnsafeMutableRawPointer(mutating: bytes.baseAddress),
count: bytes.count)
@@ -305,6 +325,7 @@ public struct Unsafe${Mutable}RawBufferPointer
/// Creates a new buffer over the same memory as the given buffer.
///
/// - Parameter bytes: The buffer to convert.
@_inlineable
public init(_ bytes: UnsafeRawBufferPointer) {
self.init(start: bytes.baseAddress, count: bytes.count)
}
@@ -314,6 +335,7 @@ public struct Unsafe${Mutable}RawBufferPointer
///
/// - Parameter buffer: The typed buffer to convert to a raw buffer. The
/// buffer's type `T` must be a trivial type.
@_inlineable
public init<T>(_ buffer: UnsafeMutableBufferPointer<T>) {
self.init(start: buffer.baseAddress!,
count: buffer.count * MemoryLayout<T>.stride)
@@ -324,6 +346,7 @@ public struct Unsafe${Mutable}RawBufferPointer
///
/// - Parameter buffer: The typed buffer to convert to a raw buffer. The
/// buffer's type `T` must be a trivial type.
@_inlineable
public init<T>(_ buffer: UnsafeBufferPointer<T>) {
self.init(start: buffer.baseAddress!,
count: buffer.count * MemoryLayout<T>.stride)
@@ -332,6 +355,7 @@ public struct Unsafe${Mutable}RawBufferPointer
/// Always zero, which is the index of the first byte in a
/// nonempty buffer.
@_inlineable
public var startIndex: Int {
return 0
}
@@ -341,12 +365,14 @@ public struct Unsafe${Mutable}RawBufferPointer
///
/// The `endIndex` property of an `Unsafe${Mutable}RawBufferPointer`
/// instance is always identical to `count`.
@_inlineable
public var endIndex: Int {
return count
}
public typealias Indices = CountableRange<Int>
@_inlineable
public var indices: Indices {
return startIndex..<endIndex
}
@@ -356,6 +382,7 @@ public struct Unsafe${Mutable}RawBufferPointer
///
/// - Parameter i: The offset of the byte to access. `i` must be in the range
/// `0..<count`.
@_inlineable
public subscript(i: Int) -> UInt8 {
get {
_debugPrecondition(i >= 0)
@@ -375,6 +402,7 @@ public struct Unsafe${Mutable}RawBufferPointer
///
/// - Parameter bounds: The range of byte offsets to access. The upper and
/// lower bounds of the range must be in the range `0...count`.
@_inlineable
public subscript(bounds: Range<Int>) -> Unsafe${Mutable}RawBufferPointer {
get {
_debugPrecondition(bounds.lowerBound >= startIndex)
@@ -399,6 +427,7 @@ public struct Unsafe${Mutable}RawBufferPointer
}
/// Returns an iterator over the bytes of this sequence.
@_inlineable
public func makeIterator() -> Iterator {
return Iterator(_position: _position, _end: _end)
}
@@ -407,6 +436,7 @@ public struct Unsafe${Mutable}RawBufferPointer
///
/// If the `baseAddress` of this buffer is `nil`, the count is zero. However,
/// a buffer can have a `count` of zero even with a non-`nil` base address.
@_inlineable
public var baseAddress: Unsafe${Mutable}RawPointer? {
return _position
}
@@ -415,6 +445,7 @@ public struct Unsafe${Mutable}RawBufferPointer
///
/// If the `baseAddress` of this buffer is `nil`, the count is zero. However,
/// a buffer can have a `count` of zero even with a non-`nil` base address.
@_inlineable
public var count: Int {
if let pos = _position {
return _end! - pos
@@ -445,6 +476,7 @@ public struct Unsafe${Mutable}RawBufferPointer
/// are initialized.
///
// TODO: Optimize where `C` is a `ContiguousArrayBuffer`.
@_inlineable
public func initializeMemory<S: Sequence>(
as: S.Iterator.Element.Type, from source: S
) -> (unwritten: S.Iterator, initialized: UnsafeMutableBufferPointer<S.Iterator.Element>) {
@@ -481,6 +513,7 @@ public struct Unsafe${Mutable}RawBufferPointer
}
% end # mutable
@_versioned
let _position, _end: Unsafe${Mutable}RawPointer?
}
@@ -512,6 +545,7 @@ extension Unsafe${Mutable}RawBufferPointer : CustomDebugStringConvertible {
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafeMutablePointer(to:_:)`, `withUnsafeBytes(of:_:)`
@_inlineable
public func withUnsafeMutableBytes<T, Result>(
of arg: inout T,
_ body: (UnsafeMutableRawBufferPointer) throws -> Result
@@ -540,6 +574,7 @@ public func withUnsafeMutableBytes<T, Result>(
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafePointer(to:_:)`, `withUnsafeMutableBytes(of:_:)`
@_inlineable
public func withUnsafeBytes<T, Result>(
of arg: inout T,
_ body: (UnsafeRawBufferPointer) throws -> Result

View File

@@ -429,6 +429,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
/// allocated, but not initialized.
///
/// - SeeAlso: `UnsafeMutablePointer`
@_inlineable
public static func allocate(
bytes size: Int, alignedTo: Int
) -> UnsafeMutableRawPointer {
@@ -446,6 +447,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
/// - Parameters:
/// - size: The number of bytes to deallocate.
/// - alignedTo: The alignment of the region to be deallocated, in bytes.
@_inlineable
public func deallocate(bytes size: Int, alignedTo: Int) {
Builtin.deallocRaw(
_rawValue, size._builtinWordValue, alignedTo._builtinWordValue)
@@ -553,6 +555,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
/// - value: The instance to copy into memory.
/// - Returns: A typed pointer to the memory referenced by this raw pointer,
/// offset by `index * MemoryLayout<T>.stride` bytes.
@_inlineable
@discardableResult
public func initializeMemory<T>(as type: T.Type, at index: Int = 0,
count: Int = 1, to value: T
@@ -614,6 +617,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
/// - count: The number of copies of `value` to copy into memory. `count`
/// must not be negative.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
@_inlineable
@discardableResult
public func initializeMemory<T>(
as type: T.Type, from source: UnsafePointer<T>, count: Int
@@ -677,6 +681,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
/// destination region.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
// This is fundamentally unsafe since collections can underreport their count.
@_inlineable
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'UnsafeMutableRawBufferPointer.initialize(from:)' instead")
@discardableResult
public func initializeMemory<C : Collection>(
@@ -719,6 +724,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
/// - count: The number of copies of `value` to copy into memory. `count`
/// must not be negative.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
@_inlineable
@discardableResult
public func moveInitializeMemory<T>(
as type: T.Type, from source: UnsafeMutablePointer<T>, count: Int
@@ -768,6 +774,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
/// - Returns: A new instance of type `T`, read from the raw bytes at
/// `offset`. The returned instance is memory-managed and unassociated
/// with the value in the memory referenced by this pointer.
@_inlineable
public func load<T>(fromByteOffset offset: Int = 0, as type: T.Type) -> T {
_debugPrecondition(0 == (UInt(bitPattern: self + offset)
& (UInt(MemoryLayout<T>.alignment) - 1)),
@@ -813,6 +820,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of `value`.
@_inlineable
public func storeBytes<T>(
of value: T, toByteOffset offset: Int = 0, as type: T.Type
) {
@@ -848,6 +856,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
/// region `source..<(source + count)` must be initialized to a trivial
/// type.
/// - count: The number of bytes to copy. `count` must not be negative.
@_inlineable
public func copyBytes(from source: UnsafeRawPointer, count: Int) {
_debugPrecondition(
count >= 0, "UnsafeMutableRawPointer.copyBytes with negative count")
@@ -865,6 +874,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
/// The hash value is not guaranteed to be stable across different
/// invocations of the same program. Do not persist the hash value across
/// program runs.
@_inlineable
public var hashValue: Int {
return Int(bitPattern: self)
}
@@ -876,6 +886,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
///
/// - Parameter x: The pointer to calculate the distance to.
/// - Returns: The distance from this pointer to `x`, in bytes.
@_inlineable
public func distance(to x: ${Self}) -> Int {
return Int(Builtin.sub_Word(Builtin.ptrtoint_Word(x._rawValue),
Builtin.ptrtoint_Word(_rawValue)))
@@ -893,6 +904,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer {
/// - Parameter n: The number of bytes to offset this pointer. `n` may be
/// positive, negative, or zero.
/// - Returns: A pointer offset from this pointer by `n` bytes.
@_inlineable
public func advanced(by n: Int) -> ${Self} {
return ${Self}(Builtin.gepRaw_Word(_rawValue, n._builtinWordValue))
}
@@ -960,10 +972,12 @@ extension Unsafe${Mutable}RawPointer : CustomPlaygroundQuickLookable {
}
extension OpaquePointer {
@_inlineable
public init(_ from: Unsafe${Mutable}RawPointer) {
self._rawValue = from._rawValue
}
@_inlineable
public init?(_ from: Unsafe${Mutable}RawPointer?) {
guard let unwrapped = from else { return nil }
self._rawValue = unwrapped._rawValue
@@ -971,6 +985,7 @@ extension OpaquePointer {
}
extension Int {
@_inlineable
public init(bitPattern: Unsafe${Mutable}RawPointer?) {
if let bitPattern = bitPattern {
self = Int(Builtin.ptrtoint_Word(bitPattern._rawValue))
@@ -981,6 +996,7 @@ extension Int {
}
extension UInt {
@_inlineable
public init(bitPattern: Unsafe${Mutable}RawPointer?) {
if let bitPattern = bitPattern {
self = UInt(Builtin.ptrtoint_Word(bitPattern._rawValue))

View File

@@ -57,9 +57,13 @@ protocol _CVarArgAligned : CVarArg {
}
#if arch(x86_64)
@_versioned
let _x86_64CountGPRegisters = 6
@_versioned
let _x86_64CountSSERegisters = 8
@_versioned
let _x86_64SSERegisterWords = 2
@_versioned
let _x86_64RegisterSaveWords = _x86_64CountGPRegisters + _x86_64CountSSERegisters * _x86_64SSERegisterWords
#endif
@@ -267,6 +271,7 @@ extension UnsafeMutablePointer : CVarArg {
extension AutoreleasingUnsafeMutablePointer : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@_inlineable
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
@@ -407,6 +412,7 @@ final internal class _VaListBuilder {
/// `CVaListPointer`.
final internal class _VaListBuilder {
@_versioned
struct Header {
var gp_offset = CUnsignedInt(0)
var fp_offset = CUnsignedInt(_x86_64CountGPRegisters * MemoryLayout<Int>.stride)

View File

@@ -10,6 +10,8 @@
//
//===----------------------------------------------------------------------===//
@_inlineable
@_versioned
internal func _writeBackMutableSlice<C, Slice_>(
_ self_: inout C, bounds: Range<C.Index>, slice: Slice_
) where