Permalink
Switch branches/tags
4.1-dont-hardcode-numbers-in-objc-block-sil 5.0-dont-hardcode-numbers-in-objc-block-sil Character-test-patch Compare-types-with-equal-equal SR-2545 TensorFlowLite UnicodeEncoding anotherdayanothercommit asyncawait bananaphone builtin-int128 cherr42 codable_test_comment_fix core-team-resolution-2017-05-10 dabrahams-append-contentsOf-replaceRange dcci-build-script-backend demangledmepatatino distributed-test dwa-where-clause-cleanup empty-collection-debugPrecondition external-swift-stdlib _fastCStringContents fix-macos-build-runtime fixmeSC generic-typealias-1-lldb gsb-superclass gyb-nested-expand hoist-to-stringprotocol hoist-to-stringprotocol.1 inhibit-implicit-conversions inline-ASCII-grapheme-fastpaths is-swift-bit-5 latest-emacs-fix-fix marcrasi-const-evaluator-part-1 marcrasi-const-evaluator-part-2 marcrasi-const-evaluator-part-3 marcrasi-last-irgen-attrs marcrasi-static-assert master-llvm-swift5-transition master-next master move-debugging-executables-into-its-own-section no-6-figure-benchmarks owned_fix patatinomio pr-66bbf1369684fc75517cfe6a12718d3cdf6a09d6 pr-94ee6e6c6e2d268f47f17dead77e4feb169c24e6 preservesugar rdar-43033749-fix-batch-mode-no-diags-swift-5.0-branch readme-add-tf-gpu remotemirrorsfixmacho remove-narrow-perf-hack revert-12818-cover-model revert-12843-force-on-named-lazy-member-loading revert-13168-large_type_lldb_workaround revert-13438-re-cover-model revert-13597-master revert-14840-concat_thin revert-14846-rdar-37790062-alt revert-15421-disable_autolinkextract revert-15602-deserialize-clang-importer-witness-tables-4.2 revert-16072-disable_failing_test revert-16149-rdar39629937-master revert-16188-assert-metadata-mangled-name-roundtrip revert-17271-DIOptWritePR revert-17370-raj-cp-allargs revert-17668-master revert-18066-sr8022-workaround revert-18156-generalized-accessors revert-18226-42480588 revert-18315-fix-argument-convention revert-18500-swift-syntax-dependency revert-18624-unbreak_unified_linux_builds revert-19006-error-bridging-integer-type revert-19050-revert-19006-error-bridging-integer-type revert-19097-fluctuation-of-the-pupil revert-19130-run-remote-run revert-19138-revert-19130-run-remote-run revert-19202-rework-type-checking-designated-protocol revert-19253-serialize-generic-typealias revert-19300-explicit-implicit-conversion revert-19447-fix-req-diagnstics-not-to-print-special-names revert-19500-updateValue-but-not-the-key revert-19689-keep-sourcekitd-response-alive-while-variant-lives revert-20129-make-nsobject-hashvalue-final revert-20187-another-42247881 revert-20191-revert-20190-rdar45708367 revert-20444-rdar-45659733-5.0 revert-20561-multi-payload-xi revert-20846-swift-5.0-default-to-gold-linker revert-20956-irgen-invariant-load revert-21199-14 rst-to-markdown runtime-fix-swift-error-box-comparison rxwei-patch-1 sequence=collection shahmishal-patch-1 shahmishal/swift-4.2-branch-update shahmishal/test-swift-4.2-branch silgen-tests-should-build-modules silgen-transform-null-context-3.0 stable static-rangereplaceable-plus stdlib-BidirectionalCollection.removeLast stdlib-default-RangeReplaceableCollection.SubSequence-3.0 stdlib-indexing stdlib-manual stdlib-swift4-build substring-views substring swift-2.2-branch swift-2.2-with-migration-attributes swift-2.3-branch swift-3.0-branch swift-3.0-preview-1-branch swift-3.0-preview-2-branch swift-3.0-preview-3-branch swift-3.0-preview-4-branch swift-3.0-preview-5-branch swift-3.0-preview-5-speculative swift-3.0.1-preview-2-branch swift-3.1-branch swift-4.0-branch-04-18-2017 swift-4.0-branch-06-02-2017 swift-4.0-branch-06-23-2017 swift-4.0-branch-07-11-2017 swift-4.0-branch-10-10-2017 swift-4.0-branch swift-4.1-branch swift-4.2-branch-03-26-2018 swift-4.2-branch-04-20-2018 swift-4.2-branch-04-30-2018 swift-4.2-branch-06-11-2018 swift-4.2-branch swift-4.2-xcode-10-beta-5 swift-5.0-branch-10-15-2018 swift-5.0-branch-11-16-2018 swift-5.0-branch-12-12-2018 swift-5.0-branch swift-master-xcode-10-beta-5 swiftstringview-specialization tensorflow-merge tensorflow testing-windows the-runtime-stands-alone-5 typelist-existential unicode-rethink unioc update-checkout-swift-5
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
173 lines (155 sloc) 5.37 KB
//===--- CollectionOfOne.swift - A Collection with one element ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A collection containing a single element.
///
/// You can use a `CollectionOfOne` instance when you need to efficiently
/// represent a single value as a collection. For example, you can add a
/// single element to an array by using a `CollectionOfOne` instance with the
/// concatenation operator (`+`):
///
/// let a = [1, 2, 3, 4]
/// let toAdd = 100
/// let b = a + CollectionOfOne(toAdd)
/// // b == [1, 2, 3, 4, 100]
@_fixed_layout // trivial-implementation
public struct CollectionOfOne<Element> {
@usableFromInline // trivial-implementation
internal var _element: Element
/// Creates an instance containing just the given element.
///
/// - Parameter element: The element to store in the collection.
@inlinable // trivial-implementation
public init(_ element: Element) {
self._element = element
}
}
extension CollectionOfOne {
/// An iterator that produces one or zero instances of an element.
///
/// `IteratorOverOne` is the iterator for the `CollectionOfOne` type.
@_fixed_layout // trivial-implementation
public struct Iterator {
@usableFromInline // trivial-implementation
internal var _elements: Element?
/// Construct an instance that generates `_element!`, or an empty
/// sequence if `_element == nil`.
@inlinable // trivial-implementation
public // @testable
init(_elements: Element?) {
self._elements = _elements
}
}
}
extension CollectionOfOne.Iterator: IteratorProtocol {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Returns: The next element in the underlying sequence, if a next element
/// exists; otherwise, `nil`.
@inlinable // trivial-implementation
public mutating func next() -> Element? {
let result = _elements
_elements = nil
return result
}
}
extension CollectionOfOne: RandomAccessCollection, MutableCollection {
public typealias Index = Int
public typealias Indices = Range<Int>
public typealias SubSequence = Slice<CollectionOfOne<Element>>
/// The position of the first element.
///
/// In a `CollectionOfOne` instance, `startIndex` is always `0`.
@inlinable // trivial-implementation
public var startIndex: Index {
return 0
}
/// The "past the end" position---that is, the position one greater than the
/// last valid subscript argument.
///
/// In a `CollectionOfOne` instance, `endIndex` is always `1`.
@inlinable // trivial-implementation
public var endIndex: Index {
return 1
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be `0`.
/// - Returns: The index value immediately after `i`.
@inlinable // trivial-implementation
public func index(after i: Index) -> Index {
_precondition(i == startIndex)
return 1
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be `1`.
/// - Returns: The index value immediately before `i`.
@inlinable // trivial-implementation
public func index(before i: Index) -> Index {
_precondition(i == endIndex)
return 0
}
/// Returns an iterator over the elements of this collection.
///
/// - Complexity: O(1)
@inlinable // trivial-implementation
public __consuming func makeIterator() -> Iterator {
return Iterator(_elements: _element)
}
/// Accesses the element at the specified position.
///
/// - Parameter position: The position of the element to access. The only
/// valid position in a `CollectionOfOne` instance is `0`.
@inlinable // trivial-implementation
public subscript(position: Int) -> Element {
get {
_precondition(position == 0, "Index out of range")
return _element
}
_modify {
_precondition(position == 0, "Index out of range")
yield &_element
}
}
@inlinable // trivial-implementation
public subscript(bounds: Range<Int>) -> SubSequence {
get {
_failEarlyRangeCheck(bounds, bounds: 0..<1)
return Slice(base: self, bounds: bounds)
}
set {
_failEarlyRangeCheck(bounds, bounds: 0..<1)
let n = newValue.count
_precondition(bounds.count == n, "CollectionOfOne can't be resized")
if n == 1 { self = newValue.base }
}
}
/// The number of elements in the collection, which is always one.
@inlinable // trivial-implementation
public var count: Int {
return 1
}
}
extension CollectionOfOne : CustomDebugStringConvertible {
/// A textual representation of the collection, suitable for debugging.
public var debugDescription: String {
return "CollectionOfOne(\(String(reflecting: _element)))"
}
}
extension CollectionOfOne : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: ["element": _element])
}
}