//===--- Arrays.swift.gyb -------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Three generic, mutable array-like types with value semantics. // // - `ContiguousArray` is a fast, contiguous array of `Element` with // a known backing store. // // - `ArraySlice` presents an arbitrary subsequence of some // contiguous sequence of `Element`s. // // - `Array` is like `ContiguousArray` when `Element` is not // an reference type or an Objective-C existential. Otherwise, it may use // an `NSArray` bridged from Cocoa for storage. // //===----------------------------------------------------------------------===// %{ arrayTypes = [ ('ContiguousArray', 'a ContiguousArray'), ('ArraySlice', 'an `ArraySlice`'), ('Array', 'an `Array`'), ] }% % for (Self, a_Self) in arrayTypes: %{ if True: O1 = ("O(1) unless `self`'s storage is" + ' shared with another live array; O(`count`) ' + ('if `self` does not wrap a bridged `NSArray`; ' + 'otherwise the efficiency is unspecified.' if Self == 'Array' else 'otherwise.')) contiguousCaveat = ( ' If no such storage exists, it is first created.' if Self == 'Array' else '') if Self == 'ContiguousArray': SelfDocComment = """\ /// A fast, contiguously-stored array of `Element`. /// /// Efficiency is equivalent to that of `Array`, unless `Element` is a /// `class` or `@objc` `protocol` type, in which case using /// `ContiguousArray` may be more efficient. Note, however, that /// `ContiguousArray` does not bridge to Objective-C. See `Array`, /// with which `ContiguousArray` shares most properties, for more /// detail.""" elif Self == 'ArraySlice': SelfDocComment = """\ /// The `Array`-like type that represents a sub-sequence of any /// `Array`, `ContiguousArray`, or other `ArraySlice`. /// /// `ArraySlice` always uses contiguous storage and does not bridge to /// Objective-C. /// /// - Warning: Long-term storage of `ArraySlice` instances is discouraged. /// /// Because a `ArraySlice` presents a *view* onto the storage of some /// larger array even after the original array's lifetime ends, /// storing the slice may prolong the lifetime of elements that are /// no longer accessible, which can manifest as apparent memory and /// object leakage. To prevent this effect, use `ArraySlice` only for /// transient computation.""" elif Self == 'Array': SelfDocComment = '''\ /// `Array` is an efficient, tail-growable random-access /// collection of arbitrary elements. /// /// Common Properties of Array Types /// ================================ /// /// The information in this section applies to all three of Swift's /// array types, `Array`, `ContiguousArray`, and /// `ArraySlice`. When you read the word "array" here in /// a normal typeface, it applies to all three of them. /// /// Value Semantics /// --------------- /// /// Each array variable, `let` binding, or stored property has an /// independent value that includes the values of all of its elements. /// Therefore, mutations to the array are not observable through its /// copies: /// /// var a = [1, 2, 3] /// var b = a /// b[0] = 4 /// print("a=\(a), b=\(b)") // a=[1, 2, 3], b=[4, 2, 3] /// /// (Of course, if the array stores `class` references, the objects /// are shared; only the values of the references are independent.) /// /// Arrays use Copy-on-Write so that their storage and elements are /// only copied lazily, upon mutation, when more than one array /// instance is using the same buffer. Therefore, the first in any /// sequence of mutating operations may cost `O(N)` time and space, /// where `N` is the length of the array. /// /// Growth and Capacity /// ------------------- /// /// When an array's contiguous storage fills up, new storage must be /// allocated and elements must be moved to the new storage. `Array`, /// `ContiguousArray`, and `ArraySlice` share an exponential growth /// strategy that makes `append` a constant time operation *when /// amortized over many invocations*. In addition to a `count` /// property, these array types have a `capacity` that reflects their /// potential to store elements without reallocation, and when you /// know how many elements you'll store, you can call /// `reserveCapacity` to pre-emptively reallocate and prevent /// intermediate reallocations. /// /// Objective-C Bridge /// ================== /// /// The main distinction between `Array` and the other array types is /// that it interoperates seamlessly and efficiently with Objective-C. /// /// `Array` is considered bridged to Objective-C iff `Element` /// is bridged to Objective-C. /// /// When `Element` is a `class` or `@objc` protocol type, `Array` may /// store its elements in an `NSArray`. Since any arbitrary subclass /// of `NSArray` can become an `Array`, there are no guarantees about /// representation or efficiency in this case (see also /// `ContiguousArray`). Since `NSArray` is immutable, it is just as /// though the storage was shared by some copy: the first in any /// sequence of mutating operations causes elements to be copied into /// unique, contiguous storage which may cost `O(N)` time and space, /// where `N` is the length of the array (or more, if the underlying /// `NSArray` is has unusual performance characteristics). /// /// Bridging to Objective-C /// ----------------------- /// /// Any bridged `Array` can be implicitly converted to an `NSArray`. /// When `Element` is a `class` or `@objc` protocol, bridging takes O(1) /// time and O(1) space. Other `Array`s must be bridged /// element-by-element, allocating a new object for each element, at a /// cost of at least O(`count`) time and space. /// /// Bridging from Objective-C /// ------------------------- /// /// An `NSArray` can be implicitly or explicitly converted to any /// bridged `Array`. This conversion calls `copyWithZone` /// on the `NSArray`, to ensure it won't be modified, and stores the /// result in the `Array`. Type-checking, to ensure the `NSArray`'s /// elements match or can be bridged to `Element`, is deferred until the /// first element access.''' # FIXME: Write about Array up/down-casting. else: raise AssertionError('Unhandled case: ' + Self) }% ${SelfDocComment} public struct ${Self} : CollectionType, MutableCollectionType, _DestructorSafeContainer { @available(*, unavailable, renamed="Element") public typealias T = Element /// Always zero, which is the index of the first element when non-empty. public var startIndex: Int { return 0 } /// A "past-the-end" element index; the successor of the last valid /// subscript argument. public var endIndex: Int { return _getCount() } #if _runtime(_ObjC) // FIXME: Code is duplicated here between the Objective-C and non-Objective-C // runtimes because config blocks can't appear inside a subscript function // without causing parse errors. When this is fixed, they should be merged // as described in the comment below. // rdar://problem/19553956 /// Access the `index`th element. Reading is O(1). Writing is /// ${O1}. public subscript(index: Int) -> Element { %if Self == 'Array': get { let isNativeNoTypeCheck = _getArrayPropertyIsNativeNoTypeCheck() _checkSubscript(index, hoistedIsNativeNoTypeCheckBuffer: isNativeNoTypeCheck) return _getElement(index, hoistedIsNativeNoTypeCheckBuffer: isNativeNoTypeCheck) } // on non-Objective-C, this should just be NativeOwner for all other // cases, including ArraySlice. %elif Self == 'ArraySlice': addressWithOwner { _checkSubscript(index, hoistedIsNativeBuffer: true) return (UnsafePointer(_buffer.baseAddress + index), Builtin.castToUnknownObject(_buffer.owner)) } %else: addressWithNativeOwner { _checkSubscript(index, hoistedIsNativeBuffer: true) return (UnsafePointer(_buffer.baseAddress + index), Builtin.castToNativeObject(_buffer.owner)) } %end mutableAddressWithPinnedNativeOwner { _makeMutableAndUniqueOrPinned() // When an array was made mutable we know it is a backed by a native array // buffer. _checkSubscript(index, hoistedIsNativeBuffer: true) // We are hiding the access to '_buffer.owner' behind a semantic function // to help the compiler hoist uniqueness checks in the case of class or // objective c existential typed array elements. In the value typed case // the extra call to _getOwner hinders optimization so we perform a check // and select based on the element type below. return (_getElementAddress(index), Builtin.tryPin( !_isClassOrObjCExistential(Element.self) ? Builtin.castToNativeObject(_buffer.owner) : _getOwner())) } } #else /// Access the `index`th element. Reading is O(1). Writing is /// ${O1}. public subscript(index: Int) -> Element { addressWithNativeOwner { _checkSubscript(index, hoistedIsNativeBuffer: true) return (UnsafePointer(_buffer.baseAddress + index), Builtin.castToNativeObject(_buffer.owner)) } mutableAddressWithPinnedNativeOwner { _makeMutableAndUniqueOrPinned() // When an array was made mutable we know it is a backed by a native array // buffer. _checkSubscript(index, hoistedIsNativeBuffer: true) return (_getElementAddress(index), Builtin.tryPin(Builtin.castToNativeObject(_buffer.owner))) } } #endif /// Access the elements indicated by the given half-open `subRange`. /// /// - Complexity: O(1). public subscript(subRange: Range) -> ArraySlice { get { _checkIndex(subRange.startIndex) _checkIndex(subRange.endIndex) return ArraySlice(_buffer[subRange]) } set(rhs) { _checkIndex(subRange.startIndex) _checkIndex(subRange.endIndex) if self[subRange]._buffer.identity != rhs._buffer.identity { self.replaceRange(subRange, with: rhs) } } } //===--- private --------------------------------------------------------===// @_semantics("array.props.isNative") public // @testable func _getArrayPropertyIsNative() -> Bool { return _buffer.arrayPropertyIsNative } /// Returns true if the array is native and does not need a deferred type /// check. @_semantics("array.props.isNativeNoTypeCheck") public // @testable func _getArrayPropertyIsNativeNoTypeCheck() -> Bool { return _buffer.arrayPropertyIsNativeNoTypeCheck } @_semantics("array.get_count") internal func _getCount() -> Int { return _buffer.count } @_semantics("array.get_capacity") internal func _getCapacity() -> Int { return _buffer.capacity } /// - Requires: The array has a native buffer. @_semantics("array.owner") internal func _getOwner() -> Builtin.NativeObject { return Builtin.castToNativeObject(_buffer.nativeOwner) } // Don't inline copyBuffer - this would inline the copy loop into the current // path preventing retains/releases to be matched accross that region. @inline(never) internal func _copyBuffer(inout buffer: _Buffer) { let newBuffer = _ContiguousArrayBuffer( count: buffer.count, minimumCapacity: buffer.count) buffer._uninitializedCopy( 0..= 0, "Negative ${Self} index is out of range") } @_semantics("array.get_element") @inline(__always) public // @testable func _getElement(index: Int, hoistedIsNativeNoTypeCheckBuffer : Bool) -> Element { return _buffer.getElement(index, hoistedIsNativeNoTypeCheckBuffer : hoistedIsNativeNoTypeCheckBuffer) } @_semantics("array.get_element_address") internal func _getElementAddress(index: Int) -> UnsafeMutablePointer { return _buffer._getBaseAddress() + index } %if Self == 'Array': #if _runtime(_ObjC) public typealias _Buffer = _ArrayBuffer #else public typealias _Buffer = _ContiguousArrayBuffer #endif %elif Self == 'ArraySlice': public typealias _Buffer = _SliceBuffer %else: public typealias _Buffer = _${Self.strip('_')}Buffer %end /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. public init(_ _buffer: _Buffer) { self._buffer = _buffer } public var _buffer: _Buffer } extension ${Self} : ArrayLiteralConvertible { %if Self == 'Array': // Optimized implementation for Array /// Create an instance containing `elements`. public init(arrayLiteral elements: Element...) { self = elements } %else: /// Create an instance containing `elements`. public init(arrayLiteral elements: Element...) { self.init(_extractOrCopyToNativeArrayBuffer(elements._buffer)) } %end } // Referenced by the compiler to allocate array literals. @_semantics("array.uninitialized") public func _allocateUninitialized${Self}(count: Builtin.Word) -> (${Self}, Builtin.RawPointer) { let (array, ptr) = ${Self}._allocateUninitialized(Int(count)) return (array, ptr._rawValue) } %if Self == 'Array': // Referenced by the compiler to deallocate array literals on the // error path. @_semantics("array.dealloc_uninitialized") public func _deallocateUninitialized${Self}( var array: ${Self} ) { array._deallocateUninitialized() } %end extension ${Self} : _ArrayType { /// Construct an empty ${Self}. @_semantics("array.init") public init() { _buffer = _Buffer() } /// Construct from an arbitrary sequence with elements of type `Element`. public init< S: SequenceType where S.Generator.Element == _Buffer.Element >(_ s: S) { self = ${Self}(_Buffer(s._copyToNativeArrayBuffer())) } /// Construct a ${Self} of `count` elements, each initialized to /// `repeatedValue`. @_semantics("array.init") public init(count: Int, repeatedValue: Element) { var p: UnsafeMutablePointer (self, p) = ${Self}._allocateUninitialized(count) for _ in 0..= 0, "Can't construct ${Self} with count < 0") _buffer = _Buffer() // Performance optimization: avoid reserveCapacity call if not needed. if count > 0 { reserveCapacity(count) } _buffer.count = count } /// Entry point for `Array` literal construction; builds and returns /// a ${Self} of `count` uninitialized elements. internal static func _allocateUninitialized( count: Int ) -> (${Self}, UnsafeMutablePointer) { let result = ${Self}(_uninitializedCount: count) return (result, result._buffer.baseAddress) } %if Self == 'Array': /// Entry point for aborting literal construction: deallocates /// a ${Self} containing only uninitialized elements. internal mutating func _deallocateUninitialized() { // Set the count to zero and just release as normal. // Somewhat of a hack. _buffer.count = 0 } %end /// The number of elements the ${Self} stores. public var count: Int { return _getCount() } /// The number of elements the `${Self}` can store without reallocation. public var capacity: Int { return _getCapacity() } /// An object that guarantees the lifetime of this array's elements. public // @testable var _owner: AnyObject? { return _buffer.owner } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. public var _baseAddressIfContiguous: UnsafeMutablePointer { return _buffer.baseAddress } %if Self != 'Array': # // Array does not necessarily have contiguous storage internal var _baseAddress: UnsafeMutablePointer { return _buffer.baseAddress } %end //===--- basic mutations ------------------------------------------------===// /// Reserve enough space to store `minimumCapacity` elements. /// /// - Postcondition: `capacity >= minimumCapacity` and the array has /// mutable contiguous storage. /// /// - Complexity: O(`count`). @_semantics("array.mutate_unknown") public mutating func reserveCapacity(minimumCapacity: Int) { if _buffer.requestUniqueMutableBackingBuffer(minimumCapacity) == nil { let newBuffer = _ContiguousArrayBuffer( count: count, minimumCapacity: minimumCapacity) _buffer._uninitializedCopy(0..= minimumCapacity) } /// Append `newElement` to the ${Self}. /// /// - Complexity: Amortized ${O1}. @_semantics("array.mutate_unknown") public mutating func append(newElement: Element) { // Checking for the isNative fast-path in the outermost if-statement helps // the optimizer to eliminate subsequent isNative checks, e.g. when // accessing _buffer.count. if _fastPath(_buffer.arrayPropertyIsNative) { let oldCount = _buffer.count if _buffer.requestUniqueMutableBackingBuffer(oldCount + 1) != nil { _buffer.count = oldCount + 1 (_buffer.baseAddress + oldCount).initialize(newElement) return } } _arrayAppendSlowPath(&_buffer, initializePointer: _InitializePointer(newElement)) } @inline(never) internal func _arrayAppendSlowPath<_Buffer: _ArrayBufferType>( inout buffer: _Buffer, initializePointer: _InitializePointer<_Buffer.Element> ) { let oldCount = buffer.count var newBuffer = Optional( _forceCreateUniqueMutableBuffer( &buffer, oldCount + 1, oldCount + 1)) _arrayOutOfPlaceUpdate( &buffer, &newBuffer, oldCount, 1, initializePointer) } /// Append the elements of `newElements` to `self`. /// /// - Complexity: O(*length of result*). public mutating func appendContentsOf< S : SequenceType where S.Generator.Element == Element >(newElements: S) { self += newElements } // An overload of `appendContentsOf()` that uses the += that is optimized for // collections. /// Append the elements of `newElements` to `self`. /// /// - Complexity: O(*length of result*). public mutating func appendContentsOf< C : CollectionType where C.Generator.Element == Element >(newElements: C) { self += newElements } /// Remove an element from the end of the ${Self} in O(1). /// /// - Requires: `count > 0`. public mutating func removeLast() -> Element { _precondition(count > 0, "can't removeLast from an empty ${Self}") let c = count // We don't check for "c - 1" underflow because C is known to be positive. let result = self[c &- 1] self.replaceRange((c &- 1).. Element { let result = self[index] self.replaceRange(index..<(index + 1), with: EmptyCollection()) return result } /// Remove all elements. /// /// - Postcondition: `capacity == 0` iff `keepCapacity` is `false`. /// /// - Complexity: O(`self.count`). public mutating func removeAll(keepCapacity keepCapacity: Bool = false) { if !keepCapacity { _buffer = _Buffer() } else { self.replaceRange(self.indices, with: EmptyCollection()) } } //===--- algorithms -----------------------------------------------------===// public mutating func _withUnsafeMutableBufferPointerIfSupported( @noescape body: (inout UnsafeMutableBufferPointer) throws -> R ) rethrows -> R? { // FIXME: Can't write simple code because of: // Assertion failure while emitting SIL for // _withUnsafeMutableBufferPointerIfSupported //return withUnsafeMutableBufferPointer { body($0) } return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in let r = try body(&bufferPointer) return r } } /// Interpose `self` between each consecutive pair of `elements`, /// and concatenate the elements of the resulting sequence. For /// example, `[-1, -2].join([[1, 2, 3], [4, 5, 6], [7, 8, 9]])` /// yields `[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]`. public func join< S : SequenceType where S.Generator.Element == ${Self} >(elements: S) -> ${Self} { return Swift.join(self, elements) } /// Returns a copy of `self` that has been sorted according to /// `isOrderedBefore`. /// /// - Requires: `isOrderedBefore` induces a /// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings) /// over the elements. @available(*, unavailable, message="call the 'sort()' method on the array") public func sorted(isOrderedBefore: (Element, Element) -> Bool) -> ${Self} { fatalError("unavailable function can't be called") } public func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer { return _extractOrCopyToNativeArrayBuffer(self._buffer) } } extension ${Self} : _Reflectable { /// Returns a mirror that reflects `self`. public func _getMirror() -> _MirrorType { return _ArrayTypeMirror(self) } } extension ${Self} : CustomStringConvertible, CustomDebugStringConvertible { internal func _makeDescription(isDebug isDebug: Bool) -> String { var result = "[" var first = true for item in self { if first { first = false } else { result += ", " } if isDebug { debugPrint(item, &result, appendNewline: false) } else { print(item, &result, appendNewline: false) } } result += "]" return result } /// A textual representation of `self`. public var description: String { return _makeDescription(isDebug: false) } /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return _makeDescription(isDebug: true) } } extension ${Self} { @transparent internal func _cPointerArgs() -> (AnyObject?, Builtin.RawPointer) { let p = _baseAddressIfContiguous if _fastPath(p != nil || isEmpty) { return (_owner, p._rawValue) } let n = _extractOrCopyToNativeArrayBuffer(self._buffer) return (n.owner, n.baseAddress._rawValue) } } extension ${Self} { /// Call `body(p)`, where `p` is a pointer to the `${Self}`'s /// contiguous storage.${contiguousCaveat} /// /// Often, the optimizer can eliminate bounds checks within an /// array algorithm, but when that fails, invoking the /// same algorithm on `body`'s argument lets you trade safety for /// speed. public func withUnsafeBufferPointer( @noescape body: (UnsafeBufferPointer) throws -> R ) rethrows -> R { return try _buffer.withUnsafeBufferPointer(body) } /// Call `body(p)`, where `p` is a pointer to the `${Self}`'s /// mutable contiguous storage.${contiguousCaveat} /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an array algorithm, but when that fails, invoking the /// same algorithm on `body`'s argument lets you trade safety for /// speed. /// /// - Warning: Do not rely on anything about `self` (the `${Self}` /// that is the target of this method) during the execution of /// `body`: it may not appear to have its correct value. Instead, /// use only the `UnsafeMutableBufferPointer` argument to `body`. public mutating func withUnsafeMutableBufferPointer( @noescape body: (inout UnsafeMutableBufferPointer) throws -> R ) rethrows -> R { // Ensure unique storage _arrayReserve(&_buffer, 0) // Ensure that body can't invalidate the storage or its bounds by // moving self into a temporary working array. var work = ${Self}() swap(&work, &self) // Create an UnsafeBufferPointer over work that we can pass to body let pointer = work._buffer.baseAddress let count = work.count var inoutBufferPointer = UnsafeMutableBufferPointer( start: pointer, count: count) // Put the working array back before returning. defer { _precondition( inoutBufferPointer.baseAddress == pointer && inoutBufferPointer.count == count, "${Self} withUnsafeMutableBufferPointer: replacing the buffer is not allowed") swap(&work, &self) } // Invoke the body. return try body(&inoutBufferPointer) } } %end internal struct _InitializeMemoryFromCollection< C: CollectionType > : _PointerFunctionType { func call(rawMemory: UnsafeMutablePointer, count: Int) { var p = rawMemory var q = newValues.startIndex for _ in 0..( inout source: B, _ subRange: Range, _ newValues: C, _ insertCount: Int ) { let growth = insertCount - subRange.count let newCount = source.count + growth var newBuffer = Optional( _forceCreateUniqueMutableBuffer(&source, newCount, newCount)) _arrayOutOfPlaceUpdate( &source, &newBuffer, subRange.startIndex, insertCount, _InitializeMemoryFromCollection(newValues) ) } /// 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. internal func _expectEnd( i: C.Index, _ s: C ) { _debugPrecondition( i == s.endIndex, "invalid CollectionType: count differed in successive traversals" ) } internal func _arrayNonSliceInPlaceReplace< B : _ArrayBufferType, C : CollectionType where C.Generator.Element == B.Element >(inout target: B, _ subRange: Range, _ insertCount: Int, _ newValues: C) { let oldCount = target.count let eraseCount = subRange.count let growth = insertCount - eraseCount target.count = oldCount + growth let elements = target.baseAddress _sanityCheck(elements != nil) let oldTailIndex = subRange.endIndex let oldTailStart = elements + oldTailIndex let newTailIndex = oldTailIndex + growth let newTailStart = oldTailStart + growth let tailCount = oldCount - subRange.endIndex if growth > 0 { // Slide the tail part of the buffer forwards, in reverse order // so as not to self-clobber. newTailStart.moveInitializeBackwardFrom(oldTailStart, count: tailCount) // Assign over the original subRange var i = newValues.startIndex for j in subRange { elements[j] = newValues[i++] } // Initialize the hole left by sliding the tail forward for j in oldTailIndex.. shrinkage { // If the tail length exceeds the shrinkage // Assign over the rest of the replaced range with the first // part of the tail. newTailStart.moveAssignFrom(oldTailStart, count: shrinkage) // slide the rest of the tail back oldTailStart.moveInitializeFrom( oldTailStart + shrinkage, count: tailCount - shrinkage) } else { // tail fits within erased elements // Assign over the start of the replaced range with the tail newTailStart.moveAssignFrom(oldTailStart, count: tailCount) // destroy elements remaining after the tail in subRange (newTailStart + tailCount).destroy(shrinkage - tailCount) } } } internal func _growArrayCapacity(capacity: Int) -> Int { return capacity * 2 } % for (Self, a_Self) in arrayTypes: extension ${Self} { /// Replace the given `subRange` of elements with `newElements`. /// /// - Complexity: O(`subRange.count`) if `subRange.endIndex /// == self.endIndex` and `isEmpty(newElements)`, O(N) otherwise. @_semantics("array.mutate_unknown") public mutating func replaceRange< C: CollectionType where C.Generator.Element == _Buffer.Element >( subRange: Range, with newElements: C ) { _precondition(subRange.startIndex >= 0, "${Self} replace: subRange start is negative") _precondition(subRange.endIndex <= self._buffer.endIndex, "${Self} replace: subRange extends past the end") let oldCount = self._buffer.count let eraseCount = subRange.count let insertCount = numericCast(newElements.count) as Int let growth = insertCount - eraseCount if self._buffer.requestUniqueMutableBackingBuffer(oldCount + growth) != nil { self._buffer.replace(subRange: subRange, with: insertCount, elementsOf: newElements) } else { _arrayOutOfPlaceReplace(&self._buffer, subRange, newElements, insertCount) } } } /// Extend `lhs` with the elements of `rhs`. public func += < Element, S : SequenceType where S.Generator.Element == Element >(inout lhs: ${Self}, rhs: S) { let oldCount = lhs.count let capacity = lhs.capacity let newCount = oldCount + rhs.underestimateCount() if newCount > capacity { lhs.reserveCapacity( max(newCount, _growArrayCapacity(capacity))) } _arrayAppendSequence(&lhs._buffer, rhs) } /// Extend `lhs` with the elements of `rhs`. public func += < Element, C : CollectionType where C.Generator.Element == Element >(inout lhs: ${Self}, rhs: C) { let rhsCount = numericCast(rhs.count) as Int let oldCount = lhs.count let capacity = lhs.capacity let newCount = oldCount + rhsCount // Ensure uniqueness, mutability, and sufficient storage. Note that // for consistency, we need unique lhs even if rhs is empty. lhs.reserveCapacity( newCount > capacity ? max(newCount, _growArrayCapacity(capacity)) : newCount) (lhs._buffer.baseAddress + oldCount).initializeFrom(rhs) lhs._buffer.count = newCount } % end //===--- generic helpers --------------------------------------------------===// @inline(never) internal func _forceCreateUniqueMutableBuffer<_Buffer : _ArrayBufferType>( inout source: _Buffer, _ newCount: Int, _ requiredCapacity: Int ) -> _ContiguousArrayBuffer<_Buffer.Element> { _sanityCheck(newCount >= 0) _sanityCheck(requiredCapacity >= newCount) let minimumCapacity = max( requiredCapacity, newCount > source.capacity ? _growArrayCapacity(source.capacity) : source.capacity) return _ContiguousArrayBuffer( count: newCount, minimumCapacity: minimumCapacity) } internal protocol _PointerFunctionType { typealias Element func call(_: UnsafeMutablePointer, count: Int) } /// Initialize the elements of dest by copying the first headCount /// items from source, calling initializeNewElements on the next /// uninitialized element, and finally by copying the last N items /// from source into the N remaining uninitialized elements of dest. /// /// As an optimization, may move elements out of source rather than /// copying when it isUniquelyReferenced. internal func _arrayOutOfPlaceUpdate< _Buffer : _ArrayBufferType, Initializer : _PointerFunctionType where Initializer.Element == _Buffer.Element >( inout source: _Buffer, inout _ dest: _ContiguousArrayBuffer<_Buffer.Element>?, _ headCount: Int, // Count of initial source elements to copy/move _ newCount: Int, // Count of new elements to insert _ initializeNewElements: Initializer ) { _sanityCheck(headCount >= 0) _sanityCheck(newCount >= 0) // Count of trailing source elements to copy/move let tailCount = dest!.count - headCount - newCount _sanityCheck(headCount + tailCount <= source.count) let sourceCount = source.count let oldCount = sourceCount - headCount - tailCount let destStart = dest!.baseAddress let newStart = destStart + headCount let newEnd = newStart + newCount // Check to see if we have storage we can move from if let backing = source.requestUniqueMutableBackingBuffer(sourceCount) { let sourceStart = source.baseAddress let oldStart = sourceStart + headCount // Destroy any items that may be lurking in a _SliceBuffer before // its real first element let backingStart = backing.baseAddress let sourceOffset = sourceStart - backingStart backingStart.destroy(sourceOffset) // Move the head items destStart.moveInitializeFrom(sourceStart, count: headCount) // Destroy unused source items oldStart.destroy(oldCount) initializeNewElements.call(newStart, count: newCount) // Move the tail items newEnd.moveInitializeFrom(oldStart + oldCount, count: tailCount) // Destroy any items that may be lurking in a _SliceBuffer after // its real last element let backingEnd = backingStart + backing.count let sourceEnd = sourceStart + sourceCount sourceEnd.destroy(backingEnd - sourceEnd) backing.count = 0 } else { let newStart = source._uninitializedCopy(0.. : _PointerFunctionType { internal func call(rawMemory: UnsafeMutablePointer, count: Int) { _sanityCheck(count == 1) // FIXME: it would be better if we could find a way to move, here rawMemory.initialize(newValue) } @transparent internal init(_ newValue: T) { self.newValue = newValue } internal var newValue: T } internal struct _IgnorePointer : _PointerFunctionType { internal func call(_: UnsafeMutablePointer, count: Int) { _sanityCheck(count == 0) } } internal func _arrayReserve<_Buffer : _ArrayBufferType>( inout buffer: _Buffer, _ minimumCapacity: Int ) { let count = buffer.count let requiredCapacity = max(count, minimumCapacity) if _fastPath( buffer.requestUniqueMutableBackingBuffer(requiredCapacity) != nil) { return } var newBuffer = Optional(_forceCreateUniqueMutableBuffer(&buffer, count, requiredCapacity)) _arrayOutOfPlaceUpdate(&buffer, &newBuffer, count, 0, _IgnorePointer()) } public // SPI(Foundation) func _extractOrCopyToNativeArrayBuffer< Buffer : _ArrayBufferType where Buffer.Generator.Element == Buffer.Element >(source: Buffer) -> _ContiguousArrayBuffer { if let n = source.requestNativeBuffer() { return n } return _copyCollectionToNativeArrayBuffer(source) } /// Append items from `newItems` to `buffer`. internal func _arrayAppendSequence< Buffer : _ArrayBufferType, S : SequenceType where S.Generator.Element == Buffer.Element >( inout buffer: Buffer, _ newItems: S ) { var stream = newItems.generate() var nextItem = stream.next() if nextItem == nil { return } // This will force uniqueness var count = buffer.count _arrayReserve(&buffer, count + 1) while true { let capacity = buffer.capacity let base = buffer.baseAddress while (nextItem != nil) && count < capacity { (base + count++).initialize(nextItem!) nextItem = stream.next() } buffer.count = count if nextItem == nil { return } _arrayReserve(&buffer, _growArrayCapacity(capacity)) } } % for (Self, a_Self) in arrayTypes: // NOTE: The '==' and '!=' below only handles array types // that are the same, e.g. Array and Array, not // ArraySlice and Array. /// Returns true if these arrays contain the same elements. public func == ( lhs: ${Self}, rhs: ${Self} ) -> Bool { let lhsCount = lhs.count if lhsCount != rhs.count { return false } // Test referential equality. if lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity { return true } var streamLHS = lhs.generate() var streamRHS = rhs.generate() var nextLHS = streamLHS.next() while nextLHS != nil { let nextRHS = streamRHS.next() if nextLHS != nextRHS { return false } nextLHS = streamLHS.next() } return true } /// Returns true if the arrays do not contain the same elements. public func != ( lhs: ${Self}, rhs: ${Self} ) -> Bool { return !(lhs == rhs) } %end #if _runtime(_ObjC) /// Returns an `Array` containing the same elements as `a` in /// O(1). /// /// - Requires: `Base` is a base class or base `@objc` protocol (such /// as `AnyObject`) of `Derived`. public func _arrayUpCast(a: Array) -> Array { // FIXME: Dynamic casting is currently not possible without the objc runtime: // rdar://problem/18801510 return Array(a._buffer.castToBufferOf(Base.self)) } #endif #if _runtime(_ObjC) extension Array { /// Try to downcast the source `NSArray` as our native buffer type. /// If it succeeds, create a new `Array` around it and return that. /// Return `nil` otherwise. // Note: this function exists here so that Foundation doesn't have // to know Array's implementation details. public static func _bridgeFromObjectiveCAdoptingNativeStorage( source: AnyObject ) -> Array? { if let deferred = source as? _SwiftDeferredNSArray { if let nativeStorage = deferred._nativeStorage as? _ContiguousArrayStorage { return Array(_ContiguousArrayBuffer(nativeStorage)) } } return nil } /// Private initializer used for bridging. /// /// Only use this initializer when both conditions are true: /// /// * it is statically known that the given `NSArray` is immutable; /// * `Element` is bridged verbatim to Objective-C (i.e., /// is a reference type). public init(_immutableCocoaArray: _NSArrayCoreType) { self = Array(_ArrayBuffer(nsArray: _immutableCocoaArray)) } } #endif extension Array { /// If `!self.isEmpty`, remove the last element and return it, otherwise /// return `nil`. /// /// - Complexity: O(`self.count`) if the array is bridged, /// otherwise O(1). public mutating func popLast() -> Element? { guard !isEmpty else { return nil } return removeLast() } } extension ContiguousArray { /// If `!self.isEmpty`, remove the last element and return it, otherwise /// return `nil`. /// /// - Complexity: O(1) public mutating func popLast() -> Element? { guard !isEmpty else { return nil } return removeLast() } } // ${'Local Variables'}: // eval: (read-only-mode 1) // End: