content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// This file is copied from swift-collections and should not be modified here.\n/// Rather all changes should be made to swift-collections and copied back.\n\nimport Swift\n\n/// A collection implementing a double-ended queue. `Deque` (pronounced "deck")\n/// implements an ordered random-access collection that supports efficient\n/// insertions and removals from both ends.\n///\n/// var colors: Deque = ["red", "yellow", "blue"]\n///\n/// Deques implement the same indexing semantics as arrays: they use integer\n/// indices, and the first element of a nonempty deque is always at index zero.\n/// Like arrays, deques conform to `RangeReplaceableCollection`,\n/// `MutableCollection` and `RandomAccessCollection`, providing a familiar\n/// interface for manipulating their contents:\n///\n/// print(colors[1]) // "yellow"\n/// print(colors[3]) // Runtime error: Index out of range\n///\n/// colors.insert("green", at: 1)\n/// // ["red", "green", "yellow", "blue"]\n///\n/// colors.remove(at: 2) // "yellow"\n/// // ["red", "green", "blue"]\n///\n/// Like all variable-size collections on the standard library, `Deque`\n/// implements value semantics: each deque has an independent value that\n/// includes the values of its elements. Modifying one deque does not affect any\n/// others:\n///\n/// var copy = deque\n/// copy[1] = "violet"\n/// print(copy) // ["red", "violet", "blue"]\n/// print(deque) // ["red", "green", "blue"]\n///\n/// This is implemented with the copy-on-write optimization. Multiple copies of\n/// a deque share the same underlying storage until you modify one of the\n/// copies. When that happens, the deque being modified replaces its storage\n/// with a uniquely owned copy of itself, which is then modified in place.\n///\n/// `Deque` stores its elements in a circular buffer, which allows efficient\n/// insertions and removals at both ends of the collection; however, this comes\n/// at the cost of potentially discontiguous storage. In contrast, `Array` is\n/// (usually) backed by a contiguous buffer, where new data can be efficiently\n/// appended to the end, but inserting at the front is relatively slow, as\n/// existing elements need to be shifted to make room.\n///\n/// This difference in implementation means that while the interface of a deque\n/// is very similar to an array, the operations have different performance\n/// characteristics. Mutations near the front are expected to be significantly\n/// faster in deques, but arrays may measure slightly faster for general\n/// random-access lookups.\n///\n/// Deques provide a handful of additional operations that make it easier to\n/// insert and remove elements at the front. This includes queue operations such\n/// as `popFirst` and `prepend`, including the ability to directly prepend a\n/// sequence of elements:\n///\n/// colors.append("green")\n/// colors.prepend("orange")\n/// // colors: ["orange", "red", "blue", "yellow", "green"]\n///\n/// colors.popLast() // "green"\n/// colors.popFirst() // "orange"\n/// // colors: ["red", "blue", "yellow"]\n///\n/// colors.prepend(contentsOf: ["purple", "teal"])\n/// // colors: ["purple", "teal", "red", "blue", "yellow"]\n///\n/// Unlike arrays, deques do not currently provide direct unsafe access to their\n/// underlying storage. They also lack a `capacity` property -- the size of the\n/// storage buffer at any given point is an unstable implementation detail that\n/// should not affect application logic. (However, deques do provide a\n/// `reserveCapacity` method.)\nstruct _Deque<Element> {\n internal typealias _Slot = _DequeSlot\n\n internal var _storage: _Storage\n\n internal init(_storage: _Storage) {\n self._storage = _storage\n }\n\n /// Creates and empty deque with preallocated space for at least the specified\n /// number of elements.\n ///\n /// - Parameter minimumCapacity: The minimum number of elements that the\n /// newly created deque should be able to store without reallocating its\n /// storage buffer.\n init(minimumCapacity: Int) {\n self._storage = _Storage(minimumCapacity: minimumCapacity)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_Deque_Deque.swift | cpp_apple_swift_stdlib_public_Concurrency_Deque_Deque.swift | Swift | 4,525 | 0.95 | 0.047619 | 0.888889 | react-lib | 253 | 2024-09-10T03:38:44.779743 | BSD-3-Clause | false | c4a56322cb6519f3d4fb8880eb550a8c |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// This file is copied from swift-collections and should not be modified here.\n/// Rather all changes should be made to swift-collections and copied back.\n\nimport Swift\n\nextension Collection {\n internal func _rebased<Element>() -> UnsafeBufferPointer<Element>\n where Self == UnsafeBufferPointer<Element>.SubSequence {\n unsafe .init(rebasing: self)\n }\n}\n\nextension Collection {\n internal func _rebased<Element>() -> UnsafeMutableBufferPointer<Element>\n where Self == UnsafeMutableBufferPointer<Element>.SubSequence {\n unsafe .init(rebasing: self)\n }\n}\n\nextension UnsafeMutableBufferPointer {\n internal func _initialize(from source: UnsafeBufferPointer<Element>) {\n assert(source.count == count)\n guard source.count > 0 else { return }\n unsafe baseAddress!.initialize(from: source.baseAddress!, count: source.count)\n }\n\n internal func _initialize<C: Collection>(\n from elements: C\n ) where C.Element == Element {\n assert(elements.count == count)\n var (it, copied) = unsafe elements._copyContents(initializing: self)\n precondition(copied == count)\n precondition(it.next() == nil)\n }\n\n internal func _deinitializeAll() {\n guard count > 0 else { return }\n unsafe baseAddress!.deinitialize(count: count)\n }\n\n internal func _assign<C: Collection>(\n from replacement: C\n ) where C.Element == Element {\n guard self.count > 0 else { return }\n unsafe self[0 ..< count]._rebased()._deinitializeAll()\n unsafe _initialize(from: replacement)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_Deque_UnsafeMutableBufferPointer+Utilities.swift | cpp_apple_swift_stdlib_public_Concurrency_Deque_UnsafeMutableBufferPointer+Utilities.swift | Swift | 1,930 | 0.95 | 0.016949 | 0.235294 | awesome-app | 662 | 2024-02-16T08:18:26.416906 | MIT | false | d5df71cbb6cec08968c4797144ad9982 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// This file is copied from swift-collections and should not be modified here.\n/// Rather all changes should be made to swift-collections and copied back.\n\nimport Swift\n\ninternal class _DequeBuffer<Element>: ManagedBuffer<_DequeBufferHeader, Element> {\n deinit {\n unsafe self.withUnsafeMutablePointers { header, elements in\n unsafe header.pointee._checkInvariants()\n\n let capacity = unsafe header.pointee.capacity\n let count = unsafe header.pointee.count\n let startSlot = unsafe header.pointee.startSlot\n\n if startSlot.position + count <= capacity {\n unsafe (elements + startSlot.position).deinitialize(count: count)\n } else {\n let firstRegion = capacity - startSlot.position\n unsafe (elements + startSlot.position).deinitialize(count: firstRegion)\n unsafe elements.deinitialize(count: count - firstRegion)\n }\n }\n }\n}\n\nextension _DequeBuffer: CustomStringConvertible {\n internal var description: String {\n unsafe withUnsafeMutablePointerToHeader { "_DequeStorage<\(Element.self)>\(unsafe $0.pointee)" }\n }\n}\n\n/// The type-punned empty singleton storage instance.\nnonisolated(unsafe) internal let _emptyDequeStorage = _DequeBuffer<Void>.create(\n minimumCapacity: 0,\n makingHeaderWith: { _ in\n _DequeBufferHeader(capacity: 0, count: 0, startSlot: .init(at: 0))\n })\n\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_Deque__DequeBuffer.swift | cpp_apple_swift_stdlib_public_Concurrency_Deque__DequeBuffer.swift | Swift | 1,780 | 0.95 | 0.061224 | 0.317073 | python-kit | 111 | 2025-02-03T14:28:27.466862 | Apache-2.0 | false | 8cf3477cee6167ed54e198d82aac3809 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// This file is copied from swift-collections and should not be modified here.\n/// Rather all changes should be made to swift-collections and copied back.\n\nimport Swift\n\ninternal struct _DequeBufferHeader {\n var capacity: Int\n\n var count: Int\n\n var startSlot: _DequeSlot\n\n init(capacity: Int, count: Int, startSlot: _DequeSlot) {\n self.capacity = capacity\n self.count = count\n self.startSlot = startSlot\n _checkInvariants()\n }\n\n #if COLLECTIONS_INTERNAL_CHECKS\n internal func _checkInvariants() {\n precondition(capacity >= 0)\n precondition(count >= 0 && count <= capacity)\n precondition(startSlot.position >= 0 && startSlot.position <= capacity)\n }\n #else\n internal func _checkInvariants() {}\n #endif // COLLECTIONS_INTERNAL_CHECKS\n}\n\nextension _DequeBufferHeader: CustomStringConvertible {\n internal var description: String {\n "(capacity: \(capacity), count: \(count), startSlot: \(startSlot))"\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_Deque__DequeBufferHeader.swift | cpp_apple_swift_stdlib_public_Concurrency_Deque__DequeBufferHeader.swift | Swift | 1,372 | 0.95 | 0.043478 | 0.394737 | react-lib | 425 | 2024-11-18T03:34:53.717010 | MIT | false | e2082f3df938f714e5936994759ec5e0 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// This file is copied from swift-collections and should not be modified here.\n/// Rather all changes should be made to swift-collections and copied back.\n\nimport Swift\n\ninternal struct _DequeSlot {\n internal var position: Int\n\n init(at position: Int) {\n assert(position >= 0)\n self.position = position\n }\n}\n\nextension _DequeSlot {\n internal static var zero: Self { Self(at: 0) }\n\n internal func advanced(by delta: Int) -> Self {\n Self(at: position &+ delta)\n }\n\n internal func orIfZero(_ value: Int) -> Self {\n guard position > 0 else { return Self(at: value) }\n return self\n }\n}\n\nextension _DequeSlot: CustomStringConvertible {\n internal var description: String {\n "@\(position)"\n }\n}\n\nextension _DequeSlot: Equatable {\n static func ==(left: Self, right: Self) -> Bool {\n left.position == right.position\n }\n}\n\nextension _DequeSlot: Comparable {\n static func <(left: Self, right: Self) -> Bool {\n left.position < right.position\n }\n}\n\nextension Range where Bound == _DequeSlot {\n internal var _count: Int { upperBound.position - lowerBound.position }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_Deque__DequeSlot.swift | cpp_apple_swift_stdlib_public_Concurrency_Deque__DequeSlot.swift | Swift | 1,526 | 0.95 | 0.016949 | 0.25 | vue-tools | 253 | 2024-12-10T20:54:45.847818 | Apache-2.0 | false | c5ce10a61fe699f51c76cccb7e898ff6 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n//\n//===----------------------------------------------------------------------===//\n\n/// This file is copied from swift-collections and should not be modified here.\n/// Rather all changes should be made to swift-collections and copied back.\n\nimport Swift\n\n@unsafe\ninternal struct _UnsafeWrappedBuffer<Element> {\n internal let first: UnsafeBufferPointer<Element>\n\n internal let second: UnsafeBufferPointer<Element>?\n\n internal init(\n _ first: UnsafeBufferPointer<Element>,\n _ second: UnsafeBufferPointer<Element>? = nil\n ) {\n unsafe self.first = unsafe first\n unsafe self.second = unsafe second\n unsafe assert(first.count > 0 || second == nil)\n }\n\n internal init(\n start: UnsafePointer<Element>,\n count: Int\n ) {\n unsafe self.init(UnsafeBufferPointer(start: start, count: count))\n }\n\n internal init(\n first start1: UnsafePointer<Element>,\n count count1: Int,\n second start2: UnsafePointer<Element>,\n count count2: Int\n ) {\n unsafe self.init(UnsafeBufferPointer(start: start1, count: count1),\n UnsafeBufferPointer(start: start2, count: count2))\n }\n\n internal var count: Int { unsafe first.count + (second?.count ?? 0) }\n}\n\n@unsafe\ninternal struct _UnsafeMutableWrappedBuffer<Element> {\n internal let first: UnsafeMutableBufferPointer<Element>\n\n internal let second: UnsafeMutableBufferPointer<Element>?\n\n internal init(\n _ first: UnsafeMutableBufferPointer<Element>,\n _ second: UnsafeMutableBufferPointer<Element>? = nil\n ) {\n unsafe self.first = unsafe first\n unsafe self.second = unsafe second?.count == 0 ? nil : second\n unsafe assert(first.count > 0 || second == nil)\n }\n\n internal init(\n start: UnsafeMutablePointer<Element>,\n count: Int\n ) {\n unsafe self.init(UnsafeMutableBufferPointer(start: start, count: count))\n }\n\n internal init(\n first start1: UnsafeMutablePointer<Element>,\n count count1: Int,\n second start2: UnsafeMutablePointer<Element>,\n count count2: Int\n ) {\n unsafe self.init(UnsafeMutableBufferPointer(start: start1, count: count1),\n UnsafeMutableBufferPointer(start: start2, count: count2))\n }\n\n internal init(mutating buffer: _UnsafeWrappedBuffer<Element>) {\n unsafe self.init(.init(mutating: buffer.first),\n buffer.second.map { unsafe .init(mutating: $0) })\n }\n}\n\nextension _UnsafeMutableWrappedBuffer {\n internal var count: Int { unsafe first.count + (second?.count ?? 0) }\n\n internal func prefix(_ n: Int) -> Self {\n assert(n >= 0)\n if unsafe n >= self.count {\n return unsafe self\n }\n if unsafe n <= first.count {\n return unsafe Self(first.prefix(n)._rebased())\n }\n return unsafe Self(first, second!.prefix(n - first.count)._rebased())\n }\n\n internal func suffix(_ n: Int) -> Self {\n assert(n >= 0)\n if unsafe n >= self.count {\n return unsafe self\n }\n guard let second = unsafe second else {\n return unsafe Self(first.suffix(n)._rebased())\n }\n if n <= second.count {\n return unsafe Self(second.suffix(n)._rebased())\n }\n return unsafe Self(first.suffix(n - second.count)._rebased(), second)\n }\n}\n\nextension _UnsafeMutableWrappedBuffer {\n internal func deinitialize() {\n unsafe first._deinitializeAll()\n unsafe second?._deinitializeAll()\n }\n\n internal func initialize<I: IteratorProtocol>(\n fromPrefixOf iterator: inout I\n ) -> Int\n where I.Element == Element {\n var copied = 0\n var gap = unsafe first\n var wrapped = false\n while true {\n if copied == gap.count {\n guard !wrapped, let second = unsafe second, second.count > 0 else { break }\n unsafe gap = unsafe second\n copied = 0\n wrapped = true\n }\n guard let next = iterator.next() else { break }\n unsafe (gap.baseAddress! + copied).initialize(to: next)\n copied += 1\n }\n return unsafe wrapped ? first.count + copied : copied\n }\n\n internal func initialize<S: Sequence>(\n fromSequencePrefix elements: __owned S\n ) -> (iterator: S.Iterator, count: Int)\n where S.Element == Element {\n guard unsafe second == nil || first.count >= elements.underestimatedCount else {\n var it = elements.makeIterator()\n let copied = unsafe initialize(fromPrefixOf: &it)\n return (it, copied)\n }\n // Note: Array._copyContents traps when not given enough space, so we\n // need to check if we have enough contiguous space available above.\n //\n // FIXME: Add support for segmented (a.k.a. piecewise contiguous)\n // collections to the stdlib.\n var (it, copied) = unsafe elements._copyContents(initializing: first)\n if unsafe copied == first.count, let second = unsafe second {\n var i = 0\n while i < second.count {\n guard let next = it.next() else { break }\n unsafe (second.baseAddress! + i).initialize(to: next)\n i += 1\n }\n copied += i\n }\n return (it, copied)\n }\n\n internal func initialize<C: Collection>(\n from elements: __owned C\n ) where C.Element == Element {\n unsafe assert(self.count == elements.count)\n if let second = unsafe second {\n let wrap = unsafe elements.index(elements.startIndex, offsetBy: first.count)\n unsafe first._initialize(from: elements[..<wrap])\n unsafe second._initialize(from: elements[wrap...])\n } else {\n unsafe first._initialize(from: elements)\n }\n }\n\n internal func assign<C: Collection>(\n from elements: C\n ) where C.Element == Element {\n unsafe assert(elements.count == self.count)\n unsafe deinitialize()\n unsafe initialize(from: elements)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_Deque__UnsafeWrappedBuffer.swift | cpp_apple_swift_stdlib_public_Concurrency_Deque__UnsafeWrappedBuffer.swift | Swift | 5,922 | 0.95 | 0.062176 | 0.099415 | vue-tools | 183 | 2024-06-20T02:09:31.306665 | BSD-3-Clause | false | 799777d4e9ee65dbb2914aec0f450c9c |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n// ==== DiscardingTaskGroup ---------------------------------------------------\n\n/// Starts a new scope that can contain a dynamic number of child tasks.\n///\n/// Unlike a ``TaskGroup``, the child tasks as well as their results are\n/// discarded as soon as the tasks complete. This prevents the discarding\n/// task group from accumulating many results waiting to be consumed, and is\n/// best applied in situations where the result of a child task is some form\n/// of side-effect.\n///\n/// A group waits for all of its child tasks\n/// to complete before it returns. Even cancelled tasks must run until\n/// completion before this function returns.\n/// Cancelled child tasks cooperatively react to cancellation and attempt\n/// to return as early as possible.\n/// After this function returns, the task group is always empty.\n///\n/// It is not possible to explicitly await completion of child-tasks,\n/// however the group will automatically await *all* child task completions\n/// before returning from this function:\n///\n/// ```\n/// await withDiscardingTaskGroup(...) { group in\n/// group.addTask { /* slow-task */ }\n/// // slow-task executes...\n/// }\n/// // guaranteed that slow-task has completed and the group is empty & destroyed\n/// ```\n///\n/// Task Group Cancellation\n/// =======================\n///\n/// You can cancel a task group and all of its child tasks\n/// by calling the ``TaskGroup/cancelAll()`` method on the task group,\n/// or by canceling the task in which the group is running.\n///\n/// If you call `addTask(priority:operation:)` to create a new task in a canceled group,\n/// that task is immediately canceled after creation.\n/// Alternatively, you can call `asyncUnlessCancelled(priority:operation:)`,\n/// which doesn't create the task if the group has already been canceled.\n/// Choosing between these two functions\n/// lets you control how to react to cancellation within a group:\n/// some child tasks need to run regardless of cancellation,\n/// but other tasks are better not even being created\n/// when you know they can't produce useful results.\n///\n/// Because the tasks you add to a group with this method are nonthrowing,\n/// those tasks can't respond to cancellation by throwing `CancellationError`.\n/// The tasks must handle cancellation in some other way,\n/// such as returning the work completed so far, returning an empty result, or returning `nil`.\n/// For tasks that need to handle cancellation by throwing an error,\n/// use the `withThrowingDiscardingTaskGroup(returning:body:)` method instead.\n///\n/// - SeeAlso: ``withThrowingDiscardingTaskGroup(returning:body:)``\n@available(SwiftStdlib 5.9, *)\n#if !hasFeature(Embedded)\n@backDeployed(before: SwiftStdlib 6.0)\n#endif\n@inlinable\npublic func withDiscardingTaskGroup<GroupResult>(\n returning returnType: GroupResult.Type = GroupResult.self,\n isolation: isolated (any Actor)? = #isolation,\n body: (inout DiscardingTaskGroup) async -> GroupResult\n) async -> GroupResult {\n let flags = taskGroupCreateFlags(\n discardResults: true\n )\n\n let _group = Builtin.createTaskGroupWithFlags(flags, GroupResult.self)\n var group = DiscardingTaskGroup(group: _group)\n defer { Builtin.destroyTaskGroup(_group) }\n\n let result = await body(&group)\n\n try! await group.awaitAllRemainingTasks() // try!-safe, cannot throw since this is a non throwing group\n\n return result\n}\n\n// Note: hack to stage out @_unsafeInheritExecutor forms of various functions\n// in favor of #isolation. The _unsafeInheritExecutor_ prefix is meaningful\n// to the type checker.\n//\n// This function also doubles as an ABI-compatibility shim predating the\n// introduction of #isolation.\n@available(SwiftStdlib 5.9, *)\n@_unsafeInheritExecutor // for ABI compatibility\n@_silgen_name("$ss23withDiscardingTaskGroup9returning4bodyxxm_xs0bcD0VzYaXEtYalF")\npublic func _unsafeInheritExecutor_withDiscardingTaskGroup<GroupResult>(\n returning returnType: GroupResult.Type = GroupResult.self,\n body: (inout DiscardingTaskGroup) async -> GroupResult\n) async -> GroupResult {\n let flags = taskGroupCreateFlags(\n discardResults: true\n )\n\n let _group = Builtin.createTaskGroupWithFlags(flags, GroupResult.self)\n var group = DiscardingTaskGroup(group: _group)\n defer { Builtin.destroyTaskGroup(_group) }\n\n let result = await body(&group)\n\n try! await group.awaitAllRemainingTasks() // try!-safe, cannot throw since this is a non throwing group\n\n return result\n}\n\n/// A discarding group that contains dynamically created child tasks.\n///\n/// To create a discarding task group,\n/// call the ``withDiscardingTaskGroup(returning:body:)`` method.\n///\n/// Don't use a task group from outside the task where you created it.\n/// In most cases,\n/// the Swift type system prevents a task group from escaping like that\n/// because adding a child task to a task group is a mutating operation,\n/// and mutation operations can't be performed\n/// from a concurrent execution context like a child task.\n///\n/// ### Task execution order\n/// Tasks added to a task group execute concurrently, and may be scheduled in\n/// any order.\n///\n/// ### Discarding behavior\n/// A discarding task group eagerly discards and releases its child tasks as\n/// soon as they complete. This allows for the efficient releasing of memory used\n/// by those tasks, which are not retained for future `next()` calls, as would\n/// be the case with a ``TaskGroup``.\n///\n/// ### Cancellation behavior\n/// A discarding task group becomes cancelled in one of the following ways:\n///\n/// - when ``cancelAll()`` is invoked on it,\n/// - when the ``Task`` running this task group is cancelled.\n///\n/// Since a `DiscardingTaskGroup` is a structured concurrency primitive, cancellation is\n/// automatically propagated through all of its child-tasks (and their child\n/// tasks).\n///\n/// A cancelled task group can still keep adding tasks, however they will start\n/// being immediately cancelled, and may act accordingly to this. To avoid adding\n/// new tasks to an already cancelled task group, use ``addTaskUnlessCancelled(priority:body:)``\n/// rather than the plain ``addTask(priority:body:)`` which adds tasks unconditionally.\n///\n/// For information about the language-level concurrency model that `DiscardingTaskGroup` is part of,\n/// see [Concurrency][concurrency] in [The Swift Programming Language][tspl].\n///\n/// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html\n/// [tspl]: https://docs.swift.org/swift-book/\n///\n/// - SeeAlso: ``TaskGroup``\n/// - SeeAlso: ``ThrowingTaskGroup``\n/// - SeeAlso: ``ThrowingDiscardingTaskGroup``\n@available(SwiftStdlib 5.9, *)\n@frozen\npublic struct DiscardingTaskGroup {\n\n @usableFromInline\n internal let _group: Builtin.RawPointer\n\n // No public initializers\n @inlinable\n init(group: Builtin.RawPointer) {\n self._group = group\n }\n\n /// Await all the remaining tasks on this group.\n ///\n /// - Throws: The first error that was encountered by this group.\n @usableFromInline\n internal mutating func awaitAllRemainingTasks() async throws {\n let _: Void? = try await _taskGroupWaitAll(group: _group, bodyError: nil)\n }\n\n /// A Boolean value that indicates whether the group has any remaining tasks.\n ///\n /// At the start of the body of a `withDiscardingTaskGroup(of:returning:body:)` call,\n /// the task group is always empty.\n ///\n /// It's guaranteed to be empty when returning from that body\n /// because a task group waits for all child tasks to complete before returning.\n ///\n /// - Returns: `true` if the group has no pending tasks; otherwise `false`.\n public var isEmpty: Bool {\n _taskGroupIsEmpty(_group)\n }\n\n /// Cancel all of the remaining tasks in the group.\n ///\n /// If you add a task to a group after canceling the group,\n /// that task is canceled immediately after being added to the group.\n ///\n /// Immediately cancelled child tasks should therefore cooperatively check for and\n /// react to cancellation, e.g. by throwing an `CancellationError` at their\n /// earliest convenience, or otherwise handling the cancellation.\n ///\n /// There are no restrictions on where you can call this method.\n /// Code inside a child task or even another task can cancel a group,\n /// however one should be very careful to not keep a reference to the\n /// group longer than the `with...TaskGroup(...) { ... }` method body is executing.\n ///\n /// - SeeAlso: `Task.isCancelled`\n /// - SeeAlso: `DiscardingTaskGroup.isCancelled`\n public func cancelAll() {\n _taskGroupCancelAll(group: _group)\n }\n\n /// A Boolean value that indicates whether the group was canceled.\n ///\n /// To cancel a group, call the `DiscardingTaskGroup.cancelAll()` method.\n ///\n /// If the task that's currently running this group is canceled,\n /// the group is also implicitly canceled,\n /// which is also reflected in this property's value.\n public var isCancelled: Bool {\n return _taskGroupIsCancelled(group: _group)\n }\n}\n\n@available(SwiftStdlib 5.9, *)\n@available(*, unavailable)\nextension DiscardingTaskGroup: Sendable { }\n\n// ==== ThrowingDiscardingTaskGroup -------------------------------------------\n\n/// Starts a new scope that can contain a dynamic number of child tasks.\n///\n/// Unlike a ``ThrowingTaskGroup``, the child tasks as well as their results are\n/// discarded as soon as the tasks complete. This prevents the discarding\n/// task group from accumulating many results waiting to be consumed, and is\n/// best applied in situations where the result of a child task is some form\n/// of side-effect.\n///\n/// A group waits for all of its child tasks\n/// to complete before it returns. Even cancelled tasks must run until\n/// completion before this function returns.\n/// Cancelled child tasks cooperatively react to cancellation and attempt\n/// to return as early as possible.\n/// After this function returns, the task group is always empty.\n///\n/// It is not possible to explicitly await completion of child-tasks,\n/// however the group will automatically await *all* child task completions\n/// before returning from this function:\n///\n/// ```\n/// try await withThrowingDiscardingTaskGroup(of: Void.self) { group in\n/// group.addTask { /* slow-task */ }\n/// // slow-task executes...\n/// }\n/// // guaranteed that slow-task has completed and the group is empty & destroyed\n/// ```\n///\n/// Task Group Cancellation\n/// =======================\n///\n/// You can cancel a task group and all of its child tasks\n/// by calling the ``TaskGroup/cancelAll()`` method on the task group,\n/// or by canceling the task in which the group is running.\n///\n/// If you call `addTask(priority:operation:)` to create a new task in a canceled group,\n/// that task is immediately canceled after creation.\n/// Alternatively, you can call `asyncUnlessCancelled(priority:operation:)`,\n/// which doesn't create the task if the group has already been canceled.\n/// Choosing between these two functions\n/// lets you control how to react to cancellation within a group:\n/// some child tasks need to run regardless of cancellation,\n/// but other tasks are better not even being created\n/// when you know they can't produce useful results.\n///\n/// Error Handling and Implicit Cancellation\n/// ========================================\n///\n/// Since it is not possible to explicitly await individual task completions,\n/// it is also not possible to "re-throw" an error thrown by one of the child\n/// tasks using the same pattern as one would in a ``ThrowingTaskGroup``:\n///\n/// ```\n/// // ThrowingTaskGroup, pattern not applicable to ThrowingDiscardingTaskGroup\n/// try await withThrowingTaskGroup(of: Void.self) { group in\n/// group.addTask { try boom() }\n/// try await group.next() // re-throws "boom"\n/// }\n/// ```\n///\n/// Since discarding task groups don't have access to `next()`, this pattern\n/// cannot be used.\n/// Instead,\n/// a *throwing discarding task group implicitly cancels itself whenever any\n/// of its child tasks throws*.\n///\n/// The *first error* thrown inside such task group\n/// is then retained and thrown\n/// out of the `withThrowingDiscardingTaskGroup` method when it returns.\n///\n/// ```\n/// try await withThrowingDiscardingTaskGroup { group in\n/// group.addTask { try boom(1) }\n/// group.addTask { try boom(2, after: .seconds(5)) }\n/// group.addTask { try boom(3, after: .seconds(5)) }\n/// }\n/// ```\n///\n/// Generally, this suits the typical use cases of a\n/// discarding task group well, however, if you want to prevent specific\n/// errors from canceling the group you can catch them inside the child\n/// task's body like this:\n///\n/// ```\n/// try await withThrowingDiscardingTaskGroup { group in\n/// group.addTask {\n/// do {\n/// try boom(1)\n/// } catch is HarmlessError {\n/// return\n/// }\n/// }\n/// group.addTask {\n/// try boom(2, after: .seconds(5))\n/// }\n/// }\n/// ```\n@available(SwiftStdlib 5.9, *)\n#if !hasFeature(Embedded)\n@backDeployed(before: SwiftStdlib 6.0)\n#endif\n@inlinable\npublic func withThrowingDiscardingTaskGroup<GroupResult>(\n returning returnType: GroupResult.Type = GroupResult.self,\n isolation: isolated (any Actor)? = #isolation,\n body: (inout ThrowingDiscardingTaskGroup<Error>) async throws -> GroupResult\n) async throws -> GroupResult {\n let flags = taskGroupCreateFlags(\n discardResults: true\n )\n\n let _group = Builtin.createTaskGroupWithFlags(flags, GroupResult.self)\n var group = ThrowingDiscardingTaskGroup<Error>(group: _group)\n defer { Builtin.destroyTaskGroup(_group) }\n\n let result: GroupResult\n do {\n result = try await body(&group)\n } catch {\n group.cancelAll()\n\n try await group.awaitAllRemainingTasks(bodyError: error)\n\n throw error\n }\n\n try await group.awaitAllRemainingTasks(bodyError: nil)\n\n return result\n}\n\n@available(SwiftStdlib 5.9, *)\n@_unsafeInheritExecutor // for ABI compatibility\n@_silgen_name("$ss31withThrowingDiscardingTaskGroup9returning4bodyxxm_xs0bcdE0Vys5Error_pGzYaKXEtYaKlF")\npublic func _unsafeInheritExecutor_withThrowingDiscardingTaskGroup<GroupResult>(\n returning returnType: GroupResult.Type = GroupResult.self,\n body: (inout ThrowingDiscardingTaskGroup<Error>) async throws -> GroupResult\n) async throws -> GroupResult {\n let flags = taskGroupCreateFlags(\n discardResults: true\n )\n\n let _group = Builtin.createTaskGroupWithFlags(flags, GroupResult.self)\n var group = ThrowingDiscardingTaskGroup<Error>(group: _group)\n defer { Builtin.destroyTaskGroup(_group) }\n\n let result: GroupResult\n do {\n result = try await body(&group)\n } catch {\n group.cancelAll()\n\n try await group.awaitAllRemainingTasks(bodyError: error)\n\n throw error\n }\n\n try await group.awaitAllRemainingTasks(bodyError: nil)\n\n return result\n}\n\n\n/// A throwing discarding group that contains dynamically created child tasks.\n///\n/// To create a discarding task group,\n/// call the ``withDiscardingTaskGroup(returning:body:)`` method.\n///\n/// Don't use a task group from outside the task where you created it.\n/// In most cases,\n/// the Swift type system prevents a task group from escaping like that\n/// because adding a child task to a task group is a mutating operation,\n/// and mutation operations can't be performed\n/// from a concurrent execution context like a child task.\n///\n/// ### Task execution order\n/// Tasks added to a task group execute concurrently, and may be scheduled in\n/// any order.\n///\n/// ### Discarding behavior\n/// A discarding task group eagerly discards and releases its child tasks as\n/// soon as they complete. This allows for the efficient releasing of memory used\n/// by those tasks, which are not retained for future `next()` calls, as would\n/// be the case with a ``TaskGroup``.\n///\n/// ### Cancellation behavior\n/// A throwing discarding task group becomes cancelled in one of the following ways:\n///\n/// - when ``cancelAll()`` is invoked on it,\n/// - when an error is thrown out of the `withThrowingDiscardingTaskGroup { ... }` closure,\n/// - when the ``Task`` running this task group is cancelled.\n///\n/// But also, and uniquely in *discarding* task groups:\n/// - when *any* of its child tasks throws.\n///\n/// The group becoming cancelled automatically, and cancelling all of its child tasks,\n/// whenever *any* child task throws an error is a behavior unique to discarding task groups,\n/// because achieving such semantics is not possible otherwise, due to the missing `next()` method\n/// on discarding groups. Accumulating task groups can implement this by manually polling `next()`\n/// and deciding to `cancelAll()` when they decide an error should cause the group to become cancelled,\n/// however a discarding group cannot poll child tasks for results and therefore assumes that child\n/// task throws are an indication of a group wide failure. In order to avoid such behavior,\n/// use a ``DiscardingTaskGroup`` instead of a throwing one, or catch specific errors in\n/// operations submitted using `addTask`.\n///\n/// Since a `ThrowingDiscardingTaskGroup` is a structured concurrency primitive, cancellation is\n/// automatically propagated through all of its child-tasks (and their child\n/// tasks).\n///\n/// A cancelled task group can still keep adding tasks, however they will start\n/// being immediately cancelled, and may act accordingly to this. To avoid adding\n/// new tasks to an already cancelled task group, use ``addTaskUnlessCancelled(priority:body:)``\n/// rather than the plain ``addTask(priority:body:)`` which adds tasks unconditionally.\n///\n/// For information about the language-level concurrency model that `DiscardingTaskGroup` is part of,\n/// see [Concurrency][concurrency] in [The Swift Programming Language][tspl].\n///\n/// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html\n/// [tspl]: https://docs.swift.org/swift-book/\n///\n/// - SeeAlso: ``TaskGroup``\n/// - SeeAlso: ``ThrowingTaskGroup``\n/// - SeeAlso: ``DiscardingTaskGroup``\n@available(SwiftStdlib 5.9, *)\n@frozen\npublic struct ThrowingDiscardingTaskGroup<Failure: Error> {\n\n @usableFromInline\n internal let _group: Builtin.RawPointer\n\n // No public initializers\n @inlinable\n init(group: Builtin.RawPointer) {\n self._group = group\n }\n\n /// Await all the remaining tasks on this group.\n @usableFromInline\n internal mutating func awaitAllRemainingTasks(bodyError: Error?) async throws {\n let _: Void? = try await _taskGroupWaitAll(group: _group, bodyError: bodyError)\n }\n\n /// A Boolean value that indicates whether the group has any remaining tasks.\n ///\n /// At the start of the body of a `withThrowingDiscardingTaskGroup(returning:body:)` call,\n /// the task group is always empty.\n ///\n /// It's guaranteed to be empty when returning from that body\n /// because a task group waits for all child tasks to complete before returning.\n ///\n /// - Returns: `true` if the group has no pending tasks; otherwise `false`.\n public var isEmpty: Bool {\n _taskGroupIsEmpty(_group)\n }\n\n /// Cancel all of the remaining tasks in the group.\n ///\n /// If you add a task to a group after canceling the group,\n /// that task is canceled immediately after being added to the group.\n ///\n /// Immediately cancelled child tasks should therefore cooperatively check for and\n /// react to cancellation, e.g. by throwing an `CancellationError` at their\n /// earliest convenience, or otherwise handling the cancellation.\n ///\n /// There are no restrictions on where you can call this method.\n /// Code inside a child task or even another task can cancel a group,\n /// however one should be very careful to not keep a reference to the\n /// group longer than the `with...TaskGroup(...) { ... }` method body is executing.\n ///\n /// - SeeAlso: `Task.isCancelled`\n /// - SeeAlso: `ThrowingDiscardingTaskGroup.isCancelled`\n public func cancelAll() {\n _taskGroupCancelAll(group: _group)\n }\n\n /// A Boolean value that indicates whether the group was canceled.\n ///\n /// To cancel a group, call the `ThrowingDiscardingTaskGroup.cancelAll()` method.\n ///\n /// If the task that's currently running this group is canceled,\n /// the group is also implicitly canceled,\n /// which is also reflected in this property's value.\n public var isCancelled: Bool {\n return _taskGroupIsCancelled(group: _group)\n }\n}\n\n@available(SwiftStdlib 5.9, *)\n@available(*, unavailable)\nextension ThrowingDiscardingTaskGroup: Sendable { }\n\n// ==== -----------------------------------------------------------------------\n// MARK: Runtime functions\n\n/// Always returns `nil`.\n@available(SwiftStdlib 5.9, *)\n@usableFromInline\n@discardableResult\n@_silgen_name("swift_taskGroup_waitAll")\nfunc _taskGroupWaitAll<T>(\n group: Builtin.RawPointer,\n bodyError: Error?\n) async throws -> T?\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_DiscardingTaskGroup.swift | cpp_apple_swift_stdlib_public_Concurrency_DiscardingTaskGroup.swift | Swift | 21,207 | 0.95 | 0.10536 | 0.707071 | node-utils | 596 | 2024-01-18T22:11:46.173466 | BSD-3-Clause | false | cf1cca1931af1272c09087ebea192c23 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if !$Embedded && !os(WASI)\n\nimport Swift\n\n// We can't import Dispatch from here, sadly, because it apparently has a\n// transitive dependency on Combine (which in turn depends on _Concurrency).\n\n// import Dispatch\n\n// .. Dispatch Interface .......................................................\n\n// .. Main Executor ............................................................\n\n@available(SwiftStdlib 6.2, *)\npublic class DispatchMainExecutor: RunLoopExecutor, @unchecked Sendable {\n var threaded = false\n\n public init() {}\n\n public func run() throws {\n if threaded {\n fatalError("DispatchMainExecutor does not support recursion")\n }\n\n threaded = true\n _dispatchMain()\n }\n\n public func stop() {\n fatalError("DispatchMainExecutor cannot be stopped")\n }\n}\n\n@available(SwiftStdlib 6.2, *)\nextension DispatchMainExecutor: SerialExecutor {\n\n public func enqueue(_ job: consuming ExecutorJob) {\n _dispatchEnqueueMain(UnownedJob(job))\n }\n\n public var isMainExecutor: Bool { true }\n\n public func checkIsolated() {\n _dispatchAssertMainQueue()\n }\n}\n\n@available(SwiftStdlib 6.2, *)\nextension DispatchMainExecutor: SchedulableExecutor {\n public var asSchedulable: SchedulableExecutor? {\n return self\n }\n\n public func enqueue<C: Clock>(_ job: consuming ExecutorJob,\n at instant: C.Instant,\n tolerance: C.Duration? = nil,\n clock: C) {\n let tolSec, tolNanosec: CLongLong\n if let tolerance = tolerance {\n (tolSec, tolNanosec) = delay(from: tolerance, clock: clock)\n } else {\n tolSec = 0\n tolNanosec = -1\n }\n\n let (clockID, seconds, nanoseconds) = timestamp(for: instant, clock: clock)\n\n _dispatchEnqueueWithDeadline(CBool(false),\n CLongLong(seconds), CLongLong(nanoseconds),\n CLongLong(tolSec), CLongLong(tolNanosec),\n clockID.rawValue,\n UnownedJob(job))\n }\n}\n\n@available(SwiftStdlib 6.2, *)\nextension DispatchMainExecutor: MainExecutor {}\n\n// .. Task Executor ............................................................\n\n@available(SwiftStdlib 6.2, *)\npublic class DispatchGlobalTaskExecutor: TaskExecutor, SchedulableExecutor,\n @unchecked Sendable {\n public init() {}\n\n public func enqueue(_ job: consuming ExecutorJob) {\n _dispatchEnqueueGlobal(UnownedJob(job))\n }\n\n public var isMainExecutor: Bool { false }\n\n public func enqueue<C: Clock>(_ job: consuming ExecutorJob,\n at instant: C.Instant,\n tolerance: C.Duration? = nil,\n clock: C) {\n let tolSec, tolNanosec: CLongLong\n if let tolerance = tolerance {\n (tolSec, tolNanosec) = delay(from: tolerance, clock: clock)\n } else {\n tolSec = 0\n tolNanosec = -1\n }\n\n let (clockID, seconds, nanoseconds) = timestamp(for: instant, clock: clock)\n\n _dispatchEnqueueWithDeadline(CBool(true),\n CLongLong(seconds), CLongLong(nanoseconds),\n CLongLong(tolSec), CLongLong(tolNanosec),\n clockID.rawValue,\n UnownedJob(job))\n }\n}\n\n// .. Clock Support ............................................................\n\n/// DispatchMainExecutor and DispatchTaskExecutor both implement this\n/// protocol.\n///\n/// It is used to help convert instants and durations from arbitrary `Clock`s\n/// to Dispatch's time base.\n@available(SwiftStdlib 6.2, *)\nprotocol DispatchExecutorProtocol: Executor {\n\n /// Convert an `Instant` from the specified clock to a tuple identifying\n /// the Dispatch clock and the seconds and nanoseconds components.\n ///\n /// Parameters:\n ///\n /// - for instant: The `Instant` to convert.\n /// - clock: The `Clock` instant that the `Instant` came from.\n ///\n /// Returns: A tuple of `(clockID, seconds, nanoseconds)`.\n func timestamp<C: Clock>(for instant: C.Instant, clock: C)\n -> (clockID: DispatchClockID, seconds: Int64, nanoseconds: Int64)\n\n /// Convert a `Duration` from the specified clock to a tuple containing\n /// seconds and nanosecond components.\n func delay<C: Clock>(from duration: C.Duration, clock: C)\n -> (seconds: Int64, nanoseconds: Int64)\n\n}\n\n/// An enumeration identifying one of the Dispatch-supported clocks\nenum DispatchClockID: CInt {\n case continuous = 1\n case suspending = 2\n}\n\n@available(SwiftStdlib 6.2, *)\nextension DispatchExecutorProtocol {\n\n func timestamp<C: Clock>(for instant: C.Instant, clock: C)\n -> (clockID: DispatchClockID, seconds: Int64, nanoseconds: Int64) {\n if clock.traits.contains(.continuous) {\n let dispatchClock: ContinuousClock = .continuous\n let instant = dispatchClock.convert(instant: instant, from: clock)!\n let (seconds, attoseconds) = instant._value.components\n let nanoseconds = attoseconds / 1_000_000_000\n return (clockID: .continuous,\n seconds: Int64(seconds),\n nanoseconds: Int64(nanoseconds))\n } else {\n let dispatchClock: SuspendingClock = .suspending\n let instant = dispatchClock.convert(instant: instant, from: clock)!\n let (seconds, attoseconds) = instant._value.components\n let nanoseconds = attoseconds / 1_000_000_000\n return (clockID: .suspending,\n seconds: Int64(seconds),\n nanoseconds: Int64(nanoseconds))\n }\n }\n\n func delay<C: Clock>(from duration: C.Duration, clock: C)\n -> (seconds: Int64, nanoseconds: Int64) {\n let swiftDuration = clock.convert(from: duration)!\n let (seconds, attoseconds) = swiftDuration.components\n let nanoseconds = attoseconds / 1_000_000_000\n return (seconds: seconds, nanoseconds: nanoseconds)\n }\n\n}\n\n@available(SwiftStdlib 6.2, *)\nextension DispatchGlobalTaskExecutor: DispatchExecutorProtocol {\n}\n\n@available(SwiftStdlib 6.2, *)\nextension DispatchMainExecutor: DispatchExecutorProtocol {\n}\n\n#endif // !$Embedded && !os(WASI)\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_DispatchExecutor.swift | cpp_apple_swift_stdlib_public_Concurrency_DispatchExecutor.swift | Swift | 6,670 | 0.95 | 0.068966 | 0.226994 | python-kit | 925 | 2023-07-28T06:10:38.721508 | Apache-2.0 | false | e7673c47b74bc98f567f31e309a69b6e |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n// .. Main Executor ............................................................\n\n@available(SwiftStdlib 6.2, *)\npublic final class DummyMainExecutor: MainExecutor, @unchecked Sendable {\n public init() {}\n\n public func run() throws {\n fatalError("There is no executor implementation active")\n }\n\n public func stop() {\n fatalError("There is no executor implementation active")\n }\n\n #if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n public func enqueue(_ job: UnownedJob) {\n fatalError("There is no executor implementation active")\n }\n #else\n public func enqueue(_ job: consuming ExecutorJob) {\n fatalError("There is no executor implementation active")\n }\n #endif\n\n public var isMainExecutor: Bool { true }\n\n public func checkIsolated() {\n // Do nothing\n }\n}\n\n// .. Task Executor ............................................................\n\n@available(SwiftStdlib 6.2, *)\npublic final class DummyTaskExecutor: TaskExecutor, @unchecked Sendable {\n public init() {}\n\n #if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n public func enqueue(_ job: UnownedJob) {\n fatalError("There is no executor implementation active")\n }\n #else\n public func enqueue(_ job: consuming ExecutorJob) {\n fatalError("There is no executor implementation active")\n }\n #endif\n\n public var isMainExecutor: Bool { false }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_DummyExecutor.swift | cpp_apple_swift_stdlib_public_Concurrency_DummyExecutor.swift | Swift | 1,873 | 0.95 | 0.095238 | 0.392157 | node-utils | 416 | 2025-03-28T10:29:06.363595 | GPL-3.0 | false | e9edbd18cfafa1d9a45dc0a0828ed6a2 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_deletedAsyncMethodError")\n@usableFromInline internal func swift_deletedAsyncMethodError() async {\n fatalError("Fatal error: Call of deleted method")\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_Errors.swift | cpp_apple_swift_stdlib_public_Concurrency_Errors.swift | Swift | 733 | 0.95 | 0.105263 | 0.647059 | awesome-app | 716 | 2023-12-28T23:23:36.832612 | GPL-3.0 | false | 99c499ec719adc0092e6f3c8b73c54f0 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n/// A service that can execute jobs.\n@available(SwiftStdlib 5.1, *)\npublic protocol Executor: AnyObject, Sendable {\n\n // Since lack move-only type support in the SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY configuration\n // Do not deprecate the UnownedJob enqueue in that configuration just yet - as we cannot introduce the replacements.\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @available(SwiftStdlib 5.1, *)\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n func enqueue(_ job: UnownedJob)\n\n // Cannot introduce these methods in SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n // since it lacks move-only type support.\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @available(SwiftStdlib 5.9, *)\n @available(*, deprecated, message: "Implement 'enqueue(_: consuming ExecutorJob)' instead")\n func enqueue(_ job: consuming Job)\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @available(SwiftStdlib 5.9, *)\n func enqueue(_ job: consuming ExecutorJob)\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n #if !$Embedded\n /// `true` if this is the main executor.\n @available(SwiftStdlib 6.2, *)\n var isMainExecutor: Bool { get }\n #endif\n}\n\n@available(SwiftStdlib 6.2, *)\npublic protocol SchedulableExecutor: Executor {\n\n #if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n /// Enqueue a job to run after a specified delay.\n ///\n /// You need only implement one of the two enqueue functions here;\n /// the default implementation for the other will then call the one\n /// you have implemented.\n ///\n /// Parameters:\n ///\n /// - job: The job to schedule.\n /// - after: A `Duration` specifying the time after which the job\n /// is to run. The job will not be executed before this\n /// time has elapsed.\n /// - tolerance: The maximum additional delay permissible before the\n /// job is executed. `nil` means no limit.\n /// - clock: The clock used for the delay.\n @available(SwiftStdlib 6.2, *)\n func enqueue<C: Clock>(_ job: consuming ExecutorJob,\n after delay: C.Duration,\n tolerance: C.Duration?,\n clock: C)\n\n /// Enqueue a job to run at a specified time.\n ///\n /// You need only implement one of the two enqueue functions here;\n /// the default implementation for the other will then call the one\n /// you have implemented.\n ///\n /// Parameters:\n ///\n /// - job: The job to schedule.\n /// - at: The `Instant` at which the job should run. The job\n /// will not be executed before this time.\n /// - tolerance: The maximum additional delay permissible before the\n /// job is executed. `nil` means no limit.\n /// - clock: The clock used for the delay..\n @available(SwiftStdlib 6.2, *)\n func enqueue<C: Clock>(_ job: consuming ExecutorJob,\n at instant: C.Instant,\n tolerance: C.Duration?,\n clock: C)\n\n #endif // !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n}\n\nextension Executor {\n /// Return this executable as a SchedulableExecutor, or nil if that is\n /// unsupported.\n ///\n /// Executors that implement SchedulableExecutor should provide their\n /// own copy of this method, which will allow the compiler to avoid a\n /// potentially expensive runtime cast.\n @available(SwiftStdlib 6.2, *)\n var asSchedulable: SchedulableExecutor? {\n return self as? SchedulableExecutor\n }\n}\n\nextension Executor {\n @available(SwiftStdlib 6.2, *)\n @usableFromInline\n internal var _isComplexEquality: Bool { false }\n}\n\nextension Executor where Self: Equatable {\n @available(SwiftStdlib 6.2, *)\n @usableFromInline\n internal var _isComplexEquality: Bool { true }\n}\n\nextension Executor {\n\n #if !$Embedded\n // This defaults to `false` so that existing third-party Executor\n // implementations will work as expected.\n @available(SwiftStdlib 6.2, *)\n public var isMainExecutor: Bool { false }\n #endif\n\n}\n\n// Delay support\n@available(SwiftStdlib 6.2, *)\nextension SchedulableExecutor {\n\n #if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n @available(SwiftStdlib 6.2, *)\n public func enqueue<C: Clock>(_ job: consuming ExecutorJob,\n after delay: C.Duration,\n tolerance: C.Duration? = nil,\n clock: C) {\n // If you crash here with a mutual recursion, it's because you didn't\n // implement one of these two functions\n enqueue(job, at: clock.now.advanced(by: delay),\n tolerance: tolerance, clock: clock)\n }\n\n @available(SwiftStdlib 6.2, *)\n public func enqueue<C: Clock>(_ job: consuming ExecutorJob,\n at instant: C.Instant,\n tolerance: C.Duration? = nil,\n clock: C) {\n // If you crash here with a mutual recursion, it's because you didn't\n // implement one of these two functions\n enqueue(job, after: clock.now.duration(to: instant),\n tolerance: tolerance, clock: clock)\n }\n\n #endif // !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n}\n\n/// A service that executes jobs.\n///\n/// ### Custom Actor Executors\n/// By default, all actor types execute tasks on a shared global concurrent pool.\n/// The global pool does not guarantee any thread (or dispatch queue) affinity,\n/// so actors are free to use different threads as they execute tasks.\n///\n/// > The runtime may perform various optimizations to minimize un-necessary\n/// > thread switching.\n///\n/// Sometimes it is important to be able to customize the execution behavior\n/// of an actor. For example, when an actor is known to perform heavy blocking\n/// operations (such as IO), and we would like to keep this work *off* the global\n/// shared pool, as blocking it may prevent other actors from being responsive.\n///\n/// You can implement a custom executor, by conforming a type to the\n/// ``SerialExecutor`` protocol, and implementing the ``enqueue(_:)`` method.\n///\n/// Once implemented, you can configure an actor to use such executor by\n/// implementing the actor's ``Actor/unownedExecutor`` computed property.\n/// For example, you could accept an executor in the actor's initializer,\n/// store it as a variable (in order to retain it for the duration of the\n/// actor's lifetime), and return it from the `unownedExecutor` computed\n/// property like this:\n///\n/// ```\n/// actor MyActor {\n/// let myExecutor: MyExecutor\n///\n/// // accepts an executor to run this actor on.\n/// init(executor: MyExecutor) {\n/// self.myExecutor = executor\n/// }\n///\n/// nonisolated var unownedExecutor: UnownedSerialExecutor {\n/// self.myExecutor.asUnownedSerialExecutor()\n/// }\n/// }\n/// ```\n///\n/// It is also possible to use a form of shared executor, either created as a\n/// global or static property, which you can then re-use for every MyActor\n/// instance:\n///\n/// ```\n/// actor MyActor {\n/// // Serial executor reused by *all* instances of MyActor!\n/// static let sharedMyActorsExecutor = MyExecutor() // implements SerialExecutor\n///\n///\n/// nonisolated var unownedExecutor: UnownedSerialExecutor {\n/// Self.sharedMyActorsExecutor.asUnownedSerialExecutor()\n/// }\n/// }\n/// ```\n///\n/// In the example above, *all* "MyActor" instances would be using the same\n/// serial executor, which would result in only one of such actors ever being\n/// run at the same time. This may be useful if some of your code has some\n/// "specific thread" requirement when interoperating with non-Swift runtimes\n/// for example.\n///\n/// Since the ``UnownedSerialExecutor`` returned by the `unownedExecutor`\n/// property *does not* retain the executor, you must make sure the lifetime of\n/// it extends beyond the lifetime of any actor or task using it, as otherwise\n/// it may attempt to enqueue work on a released executor object, causing a crash.\n/// The executor returned by unownedExecutor *must* always be the same object,\n/// and returning different executors can lead to unexpected behavior.\n///\n/// Alternatively, you can also use existing serial executor implementations,\n/// such as Dispatch's `DispatchSerialQueue` or others.\n@available(SwiftStdlib 5.1, *)\npublic protocol SerialExecutor: Executor {\n // This requirement is repeated here as a non-override so that we\n // get a redundant witness-table entry for it. This allows us to\n // avoid drilling down to the base conformance just for the basic\n // work-scheduling operation.\n @_nonoverride\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @available(SwiftStdlib 5.1, *)\n @available(*, deprecated, message: "Implement 'enqueue(_: consuming ExecutorJob)' instead")\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n func enqueue(_ job: UnownedJob)\n\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n // This requirement is repeated here as a non-override so that we\n // get a redundant witness-table entry for it. This allows us to\n // avoid drilling down to the base conformance just for the basic\n // work-scheduling operation.\n @_nonoverride\n @available(SwiftStdlib 5.9, *)\n @available(*, deprecated, message: "Implement 'enqueue(_: consuming ExecutorJob)' instead")\n func enqueue(_ job: consuming Job)\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n // This requirement is repeated here as a non-override so that we\n // get a redundant witness-table entry for it. This allows us to\n // avoid drilling down to the base conformance just for the basic\n // work-scheduling operation.\n @_nonoverride\n @available(SwiftStdlib 5.9, *)\n func enqueue(_ job: consuming ExecutorJob)\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n /// Convert this executor value to the optimized form of borrowed\n /// executor references.\n @unsafe\n func asUnownedSerialExecutor() -> UnownedSerialExecutor\n\n /// If this executor has complex equality semantics, and the runtime needs to\n /// compare two executors, it will first attempt the usual pointer-based\n /// equality / check, / and if it fails it will compare the types of both\n /// executors, if they are the same, / it will finally invoke this method,\n /// in an\n /// attempt to let the executor itself decide / if this and the `other`\n /// executor represent the same serial, exclusive, isolation context.\n ///\n /// This method must be implemented with great care, as wrongly returning\n /// `true` would allow / code from a different execution context (e.g. thread)\n /// to execute code which was intended to be isolated by another actor.\n ///\n /// This check is not used when performing executor switching.\n ///\n /// This check is used when performing ``Actor/assertIsolated()``,\n /// ``Actor/preconditionIsolated()``, ``Actor/assumeIsolated()`` and similar\n /// APIs which assert about the same "exclusive serial execution context".\n ///\n /// - Parameter other: the executor to compare with.\n /// - Returns: `true`, if `self` and the `other` executor actually are\n /// mutually exclusive and it is safe–from a concurrency\n /// perspective–to execute code assuming one on the other.\n @available(SwiftStdlib 5.9, *)\n func isSameExclusiveExecutionContext(other: Self) -> Bool\n\n /// Last resort "fallback" isolation check, called when the concurrency runtime\n /// is comparing executors e.g. during ``assumeIsolated()`` and is unable to prove\n /// serial equivalence between the expected (this object), and the current executor.\n ///\n /// During executor comparison, the Swift concurrency runtime attempts to compare\n /// current and expected executors in a few ways (including "complex" equality\n /// between executors (see ``isSameExclusiveExecutionContext(other:)``), and if all\n /// those checks fail, this method is invoked on the expected executor.\n ///\n /// This method MUST crash if it is unable to prove that the current execution\n /// context belongs to this executor. At this point usual executor comparison would\n /// have already failed, though the executor may have some external tracking of\n /// threads it owns, and may be able to prove isolation nevertheless.\n ///\n /// A default implementation is provided that unconditionally crashes the\n /// program, and prevents calling code from proceeding with potentially\n /// not thread-safe execution.\n ///\n /// - Warning: This method must crash and halt program execution if unable\n /// to prove the isolation of the calling context.\n @available(SwiftStdlib 6.0, *)\n func checkIsolated()\n\n @available(SwiftStdlib 6.2, *)\n func isIsolatingCurrentContext() -> Bool\n\n}\n\n@available(SwiftStdlib 6.0, *)\nextension SerialExecutor {\n\n #if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @available(SwiftStdlib 6.2, *)\n public var isMainExecutor: Bool { return MainActor.executor._isSameExecutor(self) }\n #endif\n\n @available(SwiftStdlib 6.0, *)\n public func checkIsolated() {\n #if !$Embedded\n fatalError("Unexpected isolation context, expected to be executing on \(Self.self)")\n #else\n Builtin.int_trap()\n #endif\n }\n\n @available(SwiftStdlib 6.2, *)\n internal func _isSameExecutor(_ rhs: some SerialExecutor) -> Bool {\n if rhs === self {\n return true\n }\n if let rhs = rhs as? Self {\n return isSameExclusiveExecutionContext(other: rhs)\n }\n return false\n }\n}\n\n@available(SwiftStdlib 6.2, *)\nextension SerialExecutor {\n\n @available(SwiftStdlib 6.2, *)\n public func isIsolatingCurrentContext() -> Bool {\n self.checkIsolated()\n return true\n }\n}\n\n/// An executor that may be used as preferred executor by a task.\n///\n/// ### Impact of setting a task executor preference\n/// By default, without setting a task executor preference, nonisolated\n/// asynchronous functions, as well as methods declared on default actors --\n/// that is actors which do not require a specific executor -- execute on\n/// Swift's default global concurrent executor. This is an executor shared by\n/// the entire runtime to execute any work which does not have strict executor\n/// requirements.\n///\n/// By setting a task executor preference, either with a\n/// ``withTaskExecutorPreference(_:operation:)``, creating a task with a preference\n/// (`Task(executorPreference:)`, or `group.addTask(executorPreference:)`), the task and all of its child\n/// tasks (unless a new preference is set) will be preferring to execute on\n/// the provided task executor.\n///\n/// Unstructured tasks do not inherit the task executor.\n@available(SwiftStdlib 6.0, *)\npublic protocol TaskExecutor: Executor {\n // This requirement is repeated here as a non-override so that we\n // get a redundant witness-table entry for it. This allows us to\n // avoid drilling down to the base conformance just for the basic\n // work-scheduling operation.\n @_nonoverride\n func enqueue(_ job: UnownedJob)\n\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n // This requirement is repeated here as a non-override so that we\n // get a redundant witness-table entry for it. This allows us to\n // avoid drilling down to the base conformance just for the basic\n // work-scheduling operation.\n @_nonoverride\n @available(*, deprecated, message: "Implement 'enqueue(_: consuming ExecutorJob)' instead")\n func enqueue(_ job: consuming Job)\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n // This requirement is repeated here as a non-override so that we\n // get a redundant witness-table entry for it. This allows us to\n // avoid drilling down to the base conformance just for the basic\n // work-scheduling operation.\n @_nonoverride\n func enqueue(_ job: consuming ExecutorJob)\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n func asUnownedTaskExecutor() -> UnownedTaskExecutor\n}\n\n@available(SwiftStdlib 6.0, *)\nextension TaskExecutor {\n public func asUnownedTaskExecutor() -> UnownedTaskExecutor {\n unsafe UnownedTaskExecutor(ordinary: self)\n }\n}\n\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 5.9, *)\nextension Executor {\n\n // Delegation goes like this:\n // Unowned Job -> Executor Job -> Job -> ---||---\n\n public func enqueue(_ job: UnownedJob) {\n self.enqueue(ExecutorJob(job))\n }\n\n public func enqueue(_ job: consuming ExecutorJob) {\n self.enqueue(Job(job))\n }\n\n public func enqueue(_ job: consuming Job) {\n self.enqueue(UnownedJob(job))\n }\n}\n#endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n@available(SwiftStdlib 5.9, *)\nextension SerialExecutor {\n @available(SwiftStdlib 5.9, *)\n public func asUnownedSerialExecutor() -> UnownedSerialExecutor {\n unsafe UnownedSerialExecutor(ordinary: self)\n }\n}\n\n@available(SwiftStdlib 5.9, *)\nextension SerialExecutor {\n\n @available(SwiftStdlib 5.9, *)\n public func isSameExclusiveExecutionContext(other: Self) -> Bool {\n return self === other\n }\n\n}\n\n@available(SwiftStdlib 6.2, *)\nextension SerialExecutor where Self: Equatable {\n\n @available(SwiftStdlib 6.2, *)\n public func isSameExclusiveExecutionContext(other: Self) -> Bool {\n return self == other\n }\n\n}\n\n/// An executor that is backed by some kind of run loop.\n///\n/// The idea here is that some executors may work by running a loop\n/// that processes events of some sort; we want a way to enter that loop,\n/// and we would also like a way to trigger the loop to exit.\n@available(SwiftStdlib 6.2, *)\npublic protocol RunLoopExecutor: Executor {\n /// Run the executor's run loop.\n ///\n /// This method will synchronously block the calling thread. Nested calls to\n /// `run()` may be permitted, however it is not permitted to call `run()` on a\n /// single executor instance from more than one thread.\n func run() throws\n\n /// Run the executor's run loop until a condition is satisfied.\n ///\n /// Not every `RunLoopExecutor` will support this method; you must not call\n /// it unless you *know* that it is supported. The default implementation\n /// generates a fatal error.\n ///\n /// Parameters:\n ///\n /// - condition: A closure that returns `true` if the run loop should\n /// stop.\n func runUntil(_ condition: () -> Bool) throws\n\n /// Signal to the run loop to stop running and return.\n ///\n /// This method may be called from the same thread that is in the `run()`\n /// method, or from some other thread. It will not wait for the run loop to\n /// stop; calling this method simply signals that the run loop *should*, as\n /// soon as is practicable, stop the innermost `run()` invocation and make\n /// that `run()` invocation return.\n func stop()\n}\n\n@available(SwiftStdlib 6.2, *)\nextension RunLoopExecutor {\n\n public func runUntil(_ condition: () -> Bool) throws {\n fatalError("run(until condition:) not supported on this executor")\n }\n\n}\n\n\n/// The main executor must conform to these three protocols; we have to\n/// make this a protocol for compatibility with Embedded Swift.\n@available(SwiftStdlib 6.2, *)\npublic protocol MainExecutor: RunLoopExecutor, SerialExecutor {\n}\n\n\n/// An ExecutorFactory is used to create the default main and task\n/// executors.\n@available(SwiftStdlib 6.2, *)\npublic protocol ExecutorFactory {\n #if !$Embedded\n /// Constructs and returns the main executor, which is started implicitly\n /// by the `async main` entry point and owns the "main" thread.\n static var mainExecutor: any MainExecutor { get }\n #endif\n\n /// Constructs and returns the default or global executor, which is the\n /// default place in which we run tasks.\n static var defaultExecutor: any TaskExecutor { get }\n}\n\n@available(SwiftStdlib 6.2, *)\ntypealias DefaultExecutorFactory = PlatformExecutorFactory\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_createExecutors")\npublic func _createExecutors<F: ExecutorFactory>(factory: F.Type) {\n #if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n MainActor._executor = factory.mainExecutor\n #endif\n Task._defaultExecutor = factory.defaultExecutor\n}\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_createDefaultExecutors")\nfunc _createDefaultExecutors() {\n if Task._defaultExecutor == nil {\n _createExecutors(factory: DefaultExecutorFactory.self)\n }\n}\n\n#if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\nextension MainActor {\n @available(SwiftStdlib 6.2, *)\n static var _executor: (any MainExecutor)? = nil\n\n /// The main executor, which is started implicitly by the `async main`\n /// entry point and owns the "main" thread.\n ///\n /// Attempting to set this after the first `enqueue` on the main\n /// executor is a fatal error.\n @available(SwiftStdlib 6.2, *)\n public static var executor: any MainExecutor {\n // It would be good if there was a Swift way to do this\n _createDefaultExecutorsOnce()\n return _executor!\n }\n}\n#endif // !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\nextension Task where Success == Never, Failure == Never {\n @available(SwiftStdlib 6.2, *)\n static var _defaultExecutor: (any TaskExecutor)? = nil\n\n /// The default or global executor, which is the default place in which\n /// we run tasks.\n ///\n /// Attempting to set this after the first `enqueue` on the global\n /// executor is a fatal error.\n @available(SwiftStdlib 6.2, *)\n public static var defaultExecutor: any TaskExecutor {\n // It would be good if there was a Swift way to do this\n _createDefaultExecutorsOnce()\n return _defaultExecutor!\n }\n}\n\nextension Task where Success == Never, Failure == Never {\n /// Get the current executor; this is the executor that the currently\n /// executing task is executing on.\n ///\n /// This will return, in order of preference:\n ///\n /// 1. The custom executor associated with an `Actor` on which we are\n /// currently running, or\n /// 2. The preferred executor for the currently executing `Task`, or\n /// 3. The task executor for the current thread\n ///\n /// If none of these exist, returns the default executor.\n @available(SwiftStdlib 6.2, *)\n @_unavailableInEmbedded\n public static var currentExecutor: any Executor {\n if let activeExecutor = unsafe _getActiveExecutor().asSerialExecutor() {\n return activeExecutor\n } else if let taskExecutor = unsafe _getPreferredTaskExecutor().asTaskExecutor() {\n return taskExecutor\n } else if let taskExecutor = unsafe _getCurrentTaskExecutor().asTaskExecutor() {\n return taskExecutor\n }\n return defaultExecutor\n }\n\n /// Get the preferred executor for the current `Task`, if any.\n @available(SwiftStdlib 6.2, *)\n public static var preferredExecutor: (any TaskExecutor)? {\n if let taskExecutor = unsafe _getPreferredTaskExecutor().asTaskExecutor() {\n return taskExecutor\n }\n return nil\n }\n\n /// Get the current *schedulable* executor, if any.\n ///\n /// This follows the same logic as `currentExecutor`, except that it ignores\n /// any executor that isn't a `SchedulableExecutor`.\n @available(SwiftStdlib 6.2, *)\n @_unavailableInEmbedded\n public static var currentSchedulableExecutor: (any SchedulableExecutor)? {\n if let activeExecutor = unsafe _getActiveExecutor().asSerialExecutor(),\n let schedulable = activeExecutor.asSchedulable {\n return schedulable\n }\n if let taskExecutor = unsafe _getPreferredTaskExecutor().asTaskExecutor(),\n let schedulable = taskExecutor.asSchedulable {\n return schedulable\n }\n if let taskExecutor = unsafe _getCurrentTaskExecutor().asTaskExecutor(),\n let schedulable = taskExecutor.asSchedulable {\n return schedulable\n }\n if let schedulable = defaultExecutor.asSchedulable {\n return schedulable\n }\n return nil\n }\n}\n\n\n/// An unowned reference to a serial executor (a `SerialExecutor`\n/// value).\n///\n/// This is an optimized type used internally by the core scheduling\n/// operations. It is an unowned reference to avoid unnecessary\n/// reference-counting work even when working with actors abstractly.\n/// Generally there are extra constraints imposed on core operations\n/// in order to allow this. For example, keeping an actor alive must\n/// also keep the actor's associated executor alive; if they are\n/// different objects, the executor must be referenced strongly by the\n/// actor.\n@available(SwiftStdlib 5.1, *)\n@unsafe\n@frozen\npublic struct UnownedSerialExecutor: Sendable {\n @usableFromInline\n internal var executor: Builtin.Executor\n\n /// SPI: Do not use. Cannot be marked @_spi, since we need to use it from Distributed module\n /// which needs to reach for this from an @_transparent function which prevents @_spi use.\n @available(SwiftStdlib 5.9, *)\n public var _executor: Builtin.Executor {\n unsafe self.executor\n }\n\n @inlinable\n public init(_ executor: Builtin.Executor) {\n unsafe self.executor = executor\n }\n\n @inlinable\n public init<E: SerialExecutor>(ordinary executor: __shared E) {\n unsafe self.executor = Builtin.buildOrdinarySerialExecutorRef(executor)\n }\n\n /// Opts the executor into complex "same exclusive execution context" equality checks.\n ///\n /// This means what when asserting or assuming executors, and the current and expected\n /// executor are not the same instance (by object equality), the runtime may invoke\n /// `isSameExclusiveExecutionContext` in order to compare the executors for equality.\n ///\n /// Implementing such complex equality can be useful if multiple executor instances\n /// actually use the same underlying serialization context and can be therefore\n /// safely treated as the same serial exclusive execution context (e.g. multiple\n /// dispatch queues targeting the same serial queue).\n @available(SwiftStdlib 5.9, *)\n @inlinable\n public init<E: SerialExecutor>(complexEquality executor: __shared E) {\n unsafe self.executor = Builtin.buildComplexEqualitySerialExecutorRef(executor)\n }\n\n /// Automatically opt-in to complex equality semantics if the Executor\n /// implements `Equatable`.\n @available(SwiftStdlib 6.2, *)\n @inlinable\n public init<E: SerialExecutor>(_ executor: __shared E) {\n if executor._isComplexEquality {\n unsafe self.executor = Builtin.buildComplexEqualitySerialExecutorRef(executor)\n } else {\n unsafe self.executor = Builtin.buildOrdinarySerialExecutorRef(executor)\n }\n }\n\n @_spi(ConcurrencyExecutors)\n @available(SwiftStdlib 5.9, *)\n public var _isComplexEquality: Bool {\n unsafe _executor_isComplexEquality(self)\n }\n\n @available(SwiftStdlib 6.2, *)\n public func asSerialExecutor() -> (any SerialExecutor)? {\n return unsafe unsafeBitCast(executor, to: (any SerialExecutor)?.self)\n }\n}\n\n\n@available(SwiftStdlib 6.0, *)\n@unsafe\n@frozen\npublic struct UnownedTaskExecutor: Sendable {\n @usableFromInline\n internal var executor: Builtin.Executor\n\n /// SPI: Do not use. Cannot be marked @_spi, since we need to use it from Distributed module\n /// which needs to reach for this from an @_transparent function which prevents @_spi use.\n @available(SwiftStdlib 6.0, *)\n public var _executor: Builtin.Executor {\n unsafe self.executor\n }\n\n @inlinable\n public init(_ executor: Builtin.Executor) {\n unsafe self.executor = executor\n }\n\n @inlinable\n public init<E: TaskExecutor>(ordinary executor: __shared E) {\n unsafe self.executor = Builtin.buildOrdinaryTaskExecutorRef(executor)\n }\n\n @available(SwiftStdlib 6.2, *)\n @inlinable\n public init<E: TaskExecutor>(_ executor: __shared E) {\n unsafe self.executor = Builtin.buildOrdinaryTaskExecutorRef(executor)\n }\n\n @available(SwiftStdlib 6.2, *)\n public func asTaskExecutor() -> (any TaskExecutor)? {\n return unsafe unsafeBitCast(executor, to: (any TaskExecutor)?.self)\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension UnownedTaskExecutor: Equatable {\n @inlinable\n public static func == (_ lhs: UnownedTaskExecutor, _ rhs: UnownedTaskExecutor) -> Bool {\n unsafe unsafeBitCast(lhs.executor, to: (Int, Int).self) == unsafeBitCast(rhs.executor, to: (Int, Int).self)\n }\n}\n\n/// Returns either `true` or will CRASH if called from a different executor\n/// than the passed `executor`.\n///\n/// This method will attempt to verify the current executor against `executor`,\n/// and as a last-resort call through to `SerialExecutor.checkIsolated`.\n///\n/// This method will never return `false`. It either can verify we're on the\n/// correct executor, or will crash the program. It should be used in\n/// isolation correctness guaranteeing APIs.\n///\n/// Generally, Swift programs should be constructed such that it is statically\n/// known that a specific executor is used, for example by using global actors or\n/// custom executors. However, in some APIs it may be useful to provide an\n/// additional runtime check for this, especially when moving towards Swift\n/// concurrency from other runtimes which frequently use such assertions.\n///\n/// - Parameter executor: The expected executor.\n@_spi(ConcurrencyExecutors)\n@available(SwiftStdlib 5.9, *)\n@_silgen_name("swift_task_isOnExecutor") // This function will CRASH rather than return `false`!\npublic func _taskIsOnExecutor<Executor: SerialExecutor>(_ executor: Executor) -> Bool\n\n@_spi(ConcurrencyExecutors)\n@available(SwiftStdlib 5.9, *)\n@_silgen_name("swift_executor_isComplexEquality")\npublic func _executor_isComplexEquality(_ executor: UnownedSerialExecutor) -> Bool\n\n@available(SwiftStdlib 5.1, *)\n@_transparent\npublic // COMPILER_INTRINSIC\nfunc _checkExpectedExecutor(_filenameStart: Builtin.RawPointer,\n _filenameLength: Builtin.Word,\n _filenameIsASCII: Builtin.Int1,\n _line: Builtin.Word,\n _executor: Builtin.Executor) {\n if _taskIsCurrentExecutor(_executor) {\n return\n }\n\n _reportUnexpectedExecutor(\n _filenameStart, _filenameLength, _filenameIsASCII, _line, _executor)\n}\n\n/// Primarily a debug utility.\n///\n/// If the passed in ExecutorJob is a Task, returns the complete 64bit TaskId,\n/// otherwise returns only the job's 32bit Id.\n///\n/// - Returns: the Id stored in this ExecutorJob or Task, for purposes of debug printing\n@available(SwiftStdlib 5.9, *)\n@_silgen_name("swift_task_getJobTaskId")\ninternal func _getJobTaskId(_ job: UnownedJob) -> UInt64\n\n@available(SwiftStdlib 5.9, *)\n@_silgen_name("_task_serialExecutor_isSameExclusiveExecutionContext")\ninternal func _task_serialExecutor_isSameExclusiveExecutionContext<E>(current currentExecutor: E, executor: E) -> Bool\n where E: SerialExecutor {\n currentExecutor.isSameExclusiveExecutionContext(other: executor)\n}\n\n@available(SwiftStdlib 6.0, *)\n@_silgen_name("_task_serialExecutor_checkIsolated")\ninternal func _task_serialExecutor_checkIsolated<E>(executor: E)\n where E: SerialExecutor {\n executor.checkIsolated()\n}\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("_task_serialExecutor_isIsolatingCurrentContext")\ninternal func _task_serialExecutor_isIsolatingCurrentContext<E>(executor: E) -> Bool\n where E: SerialExecutor {\n return executor.isIsolatingCurrentContext()\n}\n\n/// Obtain the executor ref by calling the executor's `asUnownedSerialExecutor()`.\n/// The obtained executor ref will have all the user-defined flags set on the executor.\n@available(SwiftStdlib 5.9, *)\n@_silgen_name("_task_serialExecutor_getExecutorRef")\ninternal func _task_serialExecutor_getExecutorRef<E>(_ executor: E) -> Builtin.Executor\n where E: SerialExecutor {\n return unsafe executor.asUnownedSerialExecutor().executor\n}\n\n/// Obtain the executor ref by calling the executor's `asUnownedTaskExecutor()`.\n/// The obtained executor ref will have all the user-defined flags set on the executor.\n@_unavailableInEmbedded\n@available(SwiftStdlib 6.0, *)\n@_silgen_name("_task_taskExecutor_getTaskExecutorRef")\ninternal func _task_taskExecutor_getTaskExecutorRef<E>(_ taskExecutor: E) -> Builtin.Executor\n where E: TaskExecutor {\n return unsafe taskExecutor.asUnownedTaskExecutor().executor\n}\n\n// Used by the concurrency runtime\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("_swift_task_enqueueOnExecutor")\ninternal func _enqueueOnExecutor<E>(job unownedJob: UnownedJob, executor: E)\nwhere E: SerialExecutor {\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n if #available(SwiftStdlib 5.9, *) {\n executor.enqueue(ExecutorJob(context: unownedJob._context))\n } else {\n executor.enqueue(unownedJob)\n }\n #else // SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n executor.enqueue(unownedJob)\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n}\n\n@_unavailableInEmbedded\n@available(SwiftStdlib 6.0, *)\n@_silgen_name("_swift_task_enqueueOnTaskExecutor")\ninternal func _enqueueOnTaskExecutor<E>(job unownedJob: UnownedJob, executor: E) where E: TaskExecutor {\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n executor.enqueue(ExecutorJob(context: unownedJob._context))\n #else // SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n executor.enqueue(unownedJob)\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n}\n\n#if SWIFT_CONCURRENCY_USES_DISPATCH\n// This must take a DispatchQueueShim, not something like AnyObject,\n// or else SILGen will emit a retain/release in unoptimized builds,\n// which won't work because DispatchQueues aren't actually\n// Swift-retainable.\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_enqueueOnDispatchQueue")\ninternal func _enqueueOnDispatchQueue(_ job: UnownedJob,\n queue: DispatchQueueShim)\n\n/// Used by the runtime solely for the witness table it produces.\n/// FIXME: figure out some way to achieve that which doesn't generate\n/// all the other metadata\n///\n/// Expected to work for any primitive dispatch queue; note that this\n/// means a dispatch_queue_t, which is not the same as DispatchQueue\n/// on platforms where that is an instance of a wrapper class.\n@available(SwiftStdlib 5.1, *)\ninternal final class DispatchQueueShim: @unchecked Sendable, SerialExecutor {\n func enqueue(_ job: UnownedJob) {\n _enqueueOnDispatchQueue(job, queue: self)\n }\n\n func asUnownedSerialExecutor() -> UnownedSerialExecutor {\n return unsafe UnownedSerialExecutor(ordinary: self)\n }\n}\n#endif // SWIFT_CONCURRENCY_USES_DISPATCH\n\n@available(SwiftStdlib 6.1, *)\n@_silgen_name("swift_task_deinitOnExecutor")\n@usableFromInline\ninternal func _deinitOnExecutor(_ object: __owned AnyObject,\n _ work: @convention(thin) (__owned AnyObject) -> Void,\n _ executor: Builtin.Executor,\n _ flags: Builtin.Word)\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_Executor.swift | cpp_apple_swift_stdlib_public_Concurrency_Executor.swift | Swift | 35,250 | 0.95 | 0.100108 | 0.476248 | awesome-app | 443 | 2024-08-04T19:08:12.499059 | BSD-3-Clause | false | 392268842c2ff17e26461ae75e91c19a |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\nimport SwiftShims\n\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n// ==== -----------------------------------------------------------------------\n// MARK: Precondition executors\n\n@available(SwiftStdlib 5.1, *)\nextension SerialExecutor {\n /// Stops program execution if the current task is not executing on this\n /// serial executor.\n ///\n /// This function's effect varies depending on the build flag used:\n ///\n /// * In playgrounds and `-Onone` builds (the default for Xcode's Debug\n /// configuration), stops program execution in a debuggable state after\n /// printing `message`.\n ///\n /// * In `-O` builds (the default for Xcode's Release configuration), stops\n /// program execution.\n ///\n /// - Note: Because this check is performed against the actor's serial executor,\n /// if another actor uses the same serial executor--by using\n /// that actor's serial executor as its own ``Actor/unownedExecutor``--this\n /// check will succeed. From a concurrency safety perspective, the\n /// serial executor guarantees mutual exclusion of those two actors.\n ///\n /// - Parameters:\n /// - message: The message to print if the assertion fails.\n /// - file: The file name to print if the assertion fails. The default value is\n /// the file where this method was called.\n /// - line: The line number to print if the assertion fails The default value is\n /// the line where this method was called.\n @available(SwiftStdlib 5.1, *)\n #if !$Embedded\n @backDeployed(before: SwiftStdlib 5.9)\n #endif\n @_unavailableInEmbedded\n public func preconditionIsolated(\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #fileID, line: UInt = #line\n ) {\n guard _isDebugAssertConfiguration() || _isReleaseAssertConfiguration() else {\n return\n }\n\n let expectationCheck = unsafe _taskIsCurrentExecutor(self.asUnownedSerialExecutor().executor)\n\n /// TODO: implement the logic in-place perhaps rather than delegating to precondition()?\n precondition(expectationCheck,\n // TODO: offer information which executor we actually got\n "Incorrect actor executor assumption; Expected '\(self)' executor. \(message())",\n file: file, line: line) // short-cut so we get the exact same failure reporting semantics\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Actor {\n /// Stops program execution if the current task is not executing on this\n /// actor's serial executor.\n ///\n /// This function's effect varies depending on the build flag used:\n ///\n /// * In playgrounds and `-Onone` builds (the default for Xcode's Debug\n /// configuration), stops program execution in a debuggable state after\n /// printing `message`.\n ///\n /// * In `-O` builds (the default for Xcode's Release configuration), stops\n /// program execution.\n ///\n /// - Note: This check is performed against the actor's serial executor,\n /// meaning that / if another actor uses the same serial executor--by using\n /// that actor's serial executor as its own ``Actor/unownedExecutor``--this\n /// check will succeed , as from a concurrency safety perspective, the\n /// serial executor guarantees mutual exclusion of those two actors.\n ///\n /// - Parameters:\n /// - message: The message to print if the assertion fails.\n /// - file: The file name to print if the assertion fails. The default is\n /// where this method was called.\n /// - line: The line number to print if the assertion fails The default is\n /// where this method was called.\n @available(SwiftStdlib 5.1, *)\n #if !$Embedded\n @backDeployed(before: SwiftStdlib 5.9)\n #endif\n @_unavailableInEmbedded\n public nonisolated func preconditionIsolated(\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #fileID, line: UInt = #line\n ) {\n guard _isDebugAssertConfiguration() || _isReleaseAssertConfiguration() else {\n return\n }\n\n // NOTE: This method will CRASH in new runtime versions,\n // if it would have previously returned `false`.\n // It will call through to SerialExecutor.checkIsolated` as a last resort.\n let expectationCheck = unsafe _taskIsCurrentExecutor(self.unownedExecutor.executor)\n\n precondition(expectationCheck,\n unsafe "Incorrect actor executor assumption; Expected '\(self.unownedExecutor)' executor. \(message())",\n file: file, line: line)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension GlobalActor {\n /// Stops program execution if the current task is not executing on this\n /// actor's serial executor.\n ///\n /// This function's effect varies depending on the build flag used:\n ///\n /// * In playgrounds and `-Onone` builds (the default for Xcode's Debug\n /// configuration), stops program execution in a debuggable state after\n /// printing `message`.\n ///\n /// * In `-O` builds (the default for Xcode's Release configuration), stops\n /// program execution.\n ///\n /// - Note: This check is performed against the actor's serial executor,\n /// meaning that / if another actor uses the same serial executor--by using\n /// that actor's serial executor as its own ``Actor/unownedExecutor``--this\n /// check will succeed , as from a concurrency safety perspective, the\n /// serial executor guarantees mutual exclusion of those two actors.\n ///\n /// - Parameters:\n /// - message: The message to print if the assertion fails.\n /// - file: The file name to print if the assertion fails. The default is\n /// where this method was called.\n /// - line: The line number to print if the assertion fails The default is\n /// where this method was called.\n @available(SwiftStdlib 5.1, *)\n #if !$Embedded\n @backDeployed(before: SwiftStdlib 5.9)\n #endif\n @_unavailableInEmbedded\n public static func preconditionIsolated(\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #fileID, line: UInt = #line\n ) {\n Self.shared.preconditionIsolated(message(), file: file, line: line)\n }\n}\n\n// ==== -----------------------------------------------------------------------\n// MARK: Assert executors\n\n@available(SwiftStdlib 5.1, *)\nextension SerialExecutor {\n /// Stops program execution if the current task is not executing on this\n /// serial executor.\n ///\n /// This function's effect varies depending on the build flag used:\n ///\n /// * In playgrounds and `-Onone` builds (the default for Xcode's Debug\n /// configuration), stops program execution in a debuggable state after\n /// printing `message`.\n ///\n /// * In `-O` builds (the default for Xcode's Release configuration),\n /// the isolation check is not performed and there are no effects.\n ///\n /// - Note: This check is performed against the actor's serial executor,\n /// meaning that / if another actor uses the same serial executor--by using\n /// that actor's serial executor as its own ``Actor/unownedExecutor``--this\n /// check will succeed , as from a concurrency safety perspective, the\n /// serial executor guarantees mutual exclusion of those two actors.\n ///\n /// - Parameters:\n /// - message: The message to print if the assertion fails.\n /// - file: The file name to print if the assertion fails. The default is\n /// where this method was called.\n /// - line: The line number to print if the assertion fails The default is\n /// where this method was called.\n @available(SwiftStdlib 5.1, *)\n #if !$Embedded\n @backDeployed(before: SwiftStdlib 5.9)\n #endif\n @_unavailableInEmbedded\n public func assertIsolated(\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #fileID, line: UInt = #line\n ) {\n guard _isDebugAssertConfiguration() else {\n return\n }\n\n guard unsafe _taskIsCurrentExecutor(self.asUnownedSerialExecutor().executor) else {\n // TODO: offer information which executor we actually got\n let msg = "Incorrect actor executor assumption; Expected '\(self)' executor. \(message())"\n /// TODO: implement the logic in-place perhaps rather than delegating to precondition()?\n assertionFailure(msg, file: file, line: line)\n return\n }\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Actor {\n /// Stops program execution if the current task is not executing on this\n /// actor's serial executor.\n ///\n /// This function's effect varies depending on the build flag used:\n ///\n /// * In playgrounds and `-Onone` builds (the default for Xcode's Debug\n /// configuration), stops program execution in a debuggable state after\n /// printing `message`.\n ///\n /// * In `-O` builds (the default for Xcode's Release configuration),\n /// the isolation check is not performed and there are no effects.\n ///\n /// - Note: This check is performed against the actor's serial executor,\n /// meaning that / if another actor uses the same serial executor--by using\n /// that actor's serial executor as its own ``Actor/unownedExecutor``--this\n /// check will succeed , as from a concurrency safety perspective, the\n /// serial executor guarantees mutual exclusion of those two actors.\n ///\n /// - Parameters:\n /// - message: The message to print if the assertion fails.\n /// - file: The file name to print if the assertion fails. The default is\n /// where this method was called.\n /// - line: The line number to print if the assertion fails The default is\n /// where this method was called.\n @available(SwiftStdlib 5.1, *)\n #if !$Embedded\n @backDeployed(before: SwiftStdlib 5.9)\n #endif\n @_unavailableInEmbedded\n public nonisolated func assertIsolated(\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #fileID, line: UInt = #line\n ) {\n guard _isDebugAssertConfiguration() else {\n return\n }\n\n guard unsafe _taskIsCurrentExecutor(self.unownedExecutor.executor) else {\n let msg = unsafe "Incorrect actor executor assumption; Expected '\(self.unownedExecutor)' executor. \(message())"\n /// TODO: implement the logic in-place perhaps rather than delegating to precondition()?\n assertionFailure(msg, file: file, line: line) // short-cut so we get the exact same failure reporting semantics\n return\n }\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension GlobalActor {\n /// Stops program execution if the current task is not executing on this\n /// actor's serial executor.\n ///\n /// This function's effect varies depending on the build flag used:\n ///\n /// * In playgrounds and `-Onone` builds (the default for Xcode's Debug\n /// configuration), stops program execution in a debuggable state after\n /// printing `message`.\n ///\n /// * In `-O` builds (the default for Xcode's Release configuration),\n /// the isolation check is not performed and there are no effects.\n ///\n /// - Note: This check is performed against the actor's serial executor,\n /// meaning that / if another actor uses the same serial executor--by using\n /// that actor's serial executor as its own ``Actor/unownedExecutor``--this\n /// check will succeed , as from a concurrency safety perspective, the\n /// serial executor guarantees mutual exclusion of those two actors.\n ///\n /// - Parameters:\n /// - message: The message to print if the assertion fails.\n /// - file: The file name to print if the assertion fails. The default is\n /// where this method was called.\n /// - line: The line number to print if the assertion fails The default is\n /// where this method was called.\n @available(SwiftStdlib 5.1, *)\n #if !$Embedded\n @backDeployed(before: SwiftStdlib 5.9)\n #endif\n @_unavailableInEmbedded\n public static func assertIsolated(\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #fileID, line: UInt = #line\n ) {\n Self.shared.assertIsolated(message(), file: file, line: line)\n }\n}\n\n// ==== -----------------------------------------------------------------------\n// MARK: Assume Executor\n\n@available(SwiftStdlib 5.1, *)\nextension Actor {\n /// Assume that the current task is executing on this actor's serial executor,\n /// or stop program execution otherwise.\n ///\n /// You call this method to *assume and verify* that the currently\n /// executing synchronous function is actually executing on the serial\n /// executor of this actor.\n ///\n /// If that is the case, the operation is invoked with an `isolated` version\n /// of the actor, allowing synchronous access to actor local state without\n /// hopping through asynchronous boundaries.\n ///\n /// If the current context is not running on the actor's serial executor, or\n /// if the actor is a reference to a remote actor, this method will crash\n /// with a fatal error (similar to ``preconditionIsolated()``).\n ///\n /// Note that this check is performed against the passed in actor's serial\n /// executor, meaning that if another actor uses the same serial executor--by\n /// using that actor's ``Actor/unownedExecutor`` as its own\n /// ``Actor/unownedExecutor``--this check will succeed, as from a concurrency\n /// safety perspective, the serial executor guarantees mutual exclusion of\n /// those two actors.\n ///\n /// This method can only be used from synchronous functions, as asynchronous\n /// functions should instead perform a normal method call to the actor, which\n /// will hop task execution to the target actor if necessary.\n ///\n /// - Note: This check is performed against the actor's serial executor,\n /// meaning that / if another actor uses the same serial executor--by using\n /// another actor's executor as its own ``Actor/unownedExecutor``\n /// --this check will succeed , as from a concurrency safety perspective,\n /// the serial executor guarantees mutual exclusion of those two actors.\n ///\n /// - Parameters:\n /// - operation: the operation that will be executed if the current context\n /// is executing on the actors serial executor.\n /// - file: The file name to print if the assertion fails. The default is\n /// where this method was called.\n /// - line: The line number to print if the assertion fails The default is\n /// where this method was called.\n /// - Returns: the return value of the `operation`\n /// - Throws: rethrows the `Error` thrown by the operation if it threw\n @available(SwiftStdlib 5.1, *)\n @_alwaysEmitIntoClient\n @_unavailableFromAsync(message: "express the closure as an explicit function declared on the specified 'actor' instead")\n @_unavailableInEmbedded\n public nonisolated func assumeIsolated<T : Sendable>(\n _ operation: (isolated Self) throws -> T,\n file: StaticString = #fileID, line: UInt = #line\n ) rethrows -> T {\n typealias YesActor = (isolated Self) throws -> T\n typealias NoActor = (Self) throws -> T\n\n /// This is guaranteed to be fatal if the check fails,\n /// as this is our "safe" version of this API.\n let executor: Builtin.Executor = unsafe self.unownedExecutor.executor\n guard _taskIsCurrentExecutor(executor) else {\n // TODO: offer information which executor we actually got\n fatalError("Incorrect actor executor assumption; Expected same executor as \(self).", file: file, line: line)\n }\n\n // To do the unsafe cast, we have to pretend it's @escaping.\n return try withoutActuallyEscaping(operation) {\n (_ fn: @escaping YesActor) throws -> T in\n let rawFn = unsafe unsafeBitCast(fn, to: NoActor.self)\n return try rawFn(self)\n }\n }\n\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n @_unavailableInEmbedded\n @_silgen_name("$sScAsE14assumeIsolated_4file4lineqd__qd__xYiKXE_s12StaticStringVSutKlF")\n internal nonisolated func __abi__assumeIsolated<T : Sendable>(\n _ operation: (isolated Self) throws -> T,\n _ file: StaticString, _ line: UInt\n ) rethrows -> T {\n try assumeIsolated(operation, file: file, line: line)\n }\n}\n\n#endif // not SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_ExecutorAssertions.swift | cpp_apple_swift_stdlib_public_Concurrency_ExecutorAssertions.swift | Swift | 16,581 | 0.95 | 0.18799 | 0.631579 | python-kit | 325 | 2025-04-05T23:29:40.024928 | GPL-3.0 | false | 4ad9ac365fd8de82bf97b40a819f2961 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Functions to bridge between C++ and Swift. This does not include the\n// *Impl functions because we need them separate for Embedded Swift.\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("_swift_exit")\ninternal func _exit(result: CInt)\n\n#if !$Embedded\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("_swift_task_isMainExecutorSwift")\ninternal func _isMainExecutor<E>(_ executor: E) -> Bool where E: SerialExecutor {\n return executor.isMainExecutor\n}\n#endif\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("_swift_task_checkIsolatedSwift")\ninternal func checkIsolated<E>(executor: E) where E: SerialExecutor {\n executor.checkIsolated()\n}\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("_swift_task_isIsolatingCurrentContextSwift")\ninternal func isIsolatingCurrentContext<E>(executor: E) -> Bool\n where E: SerialExecutor\n{\n return executor.isIsolatingCurrentContext()\n}\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("_swift_getActiveExecutor")\ninternal func _getActiveExecutor() -> UnownedSerialExecutor\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("_swift_getCurrentTaskExecutor")\ninternal func _getCurrentTaskExecutor() -> UnownedTaskExecutor\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("_swift_getPreferredTaskExecutor")\ninternal func _getPreferredTaskExecutor() -> UnownedTaskExecutor\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_job_allocate")\ninternal func _jobAllocate(_ job: Builtin.Job,\n _ capacity: Int) -> UnsafeMutableRawPointer\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_job_deallocate")\ninternal func _jobDeallocate(_ job: Builtin.Job,\n _ address: UnsafeMutableRawPointer)\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_job_getPriority")\ninternal func _jobGetPriority(_ job: Builtin.Job) -> UInt8\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_job_getKind")\ninternal func _jobGetKind(_ job: Builtin.Job) -> UInt8\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_job_getExecutorPrivateData")\ninternal func _jobGetExecutorPrivateData(\n _ job: Builtin.Job\n) -> UnsafeMutableRawPointer\n\n#if !$Embedded\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_getMainExecutor")\ninternal func _getMainExecutor() -> any SerialExecutor {\n return MainActor.executor\n}\n#else\n// For task-to-thread model, this is implemented in C++\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_getMainExecutor")\ninternal func _getMainExecutor() -> any SerialExecutor\n#endif // SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n#endif // !$Embedded\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_dispatchMain")\ninternal func _dispatchMain()\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_dispatchEnqueueMain")\ninternal func _dispatchEnqueueMain(_ job: UnownedJob)\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_dispatchEnqueueGlobal")\ninternal func _dispatchEnqueueGlobal(_ job: UnownedJob)\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_dispatchEnqueueWithDeadline")\ninternal func _dispatchEnqueueWithDeadline(_ global: CBool,\n _ sec: CLongLong,\n _ nsec: CLongLong,\n _ tsec: CLongLong,\n _ tnsec: CLongLong,\n _ clock: CInt,\n _ job: UnownedJob)\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_dispatchAssertMainQueue")\ninternal func _dispatchAssertMainQueue()\n\n@_silgen_name("swift_createDefaultExecutorsOnce")\nfunc _createDefaultExecutorsOnce()\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_ExecutorBridge.swift | cpp_apple_swift_stdlib_public_Concurrency_ExecutorBridge.swift | Swift | 4,271 | 0.95 | 0.048387 | 0.230769 | awesome-app | 386 | 2024-09-22T02:12:21.065380 | Apache-2.0 | false | 4f221341a77fb61723302c71f64c0746 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Implementations of the *Impl functions that bridge to Swift.\n//\n// These are separate from the functions in ExecutorBridge.swift so that we\n// can omit this file from the Embedded Swift version of Concurrency for now.\n// (This means that the existing co-operative executor will still work.)\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_asyncMainDrainQueueImpl")\ninternal func drainMainQueue() {\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n try! MainActor.executor.run()\n _exit(result: 0)\n #else\n fatalError("swift_task_asyncMainDrainQueue() not supported with task-to-thread")\n #endif\n}\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_donateThreadToGlobalExecutorUntilImpl")\ninternal func donateToGlobalExecutor(\n condition: @convention(c) (_ ctx: UnsafeMutableRawPointer) -> CBool,\n context: UnsafeMutableRawPointer\n) {\n if let runnableExecutor = Task.defaultExecutor as? RunLoopExecutor {\n try! runnableExecutor.runUntil { unsafe Bool(condition(context)) }\n } else {\n fatalError("Global executor does not support thread donation")\n }\n}\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_getMainExecutorImpl")\ninternal func getMainExecutor() -> UnownedSerialExecutor {\n return unsafe _getMainExecutor().asUnownedSerialExecutor()\n}\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_enqueueMainExecutorImpl")\ninternal func enqueueOnMainExecutor(job unownedJob: UnownedJob) {\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n MainActor.executor.enqueue(unownedJob)\n #else\n fatalError("swift_task_enqueueMainExecutor() not supported for task-to-thread")\n #endif\n}\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_enqueueGlobalImpl")\ninternal func enqueueOnGlobalExecutor(job unownedJob: UnownedJob) {\n Task.defaultExecutor.enqueue(unownedJob)\n}\n\n#if !$Embedded\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_enqueueGlobalWithDelayImpl")\ninternal func enqueueOnGlobalExecutor(delay: CUnsignedLongLong,\n job unownedJob: UnownedJob) {\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n Task.defaultExecutor.asSchedulable!.enqueue(ExecutorJob(unownedJob),\n after: .nanoseconds(delay),\n clock: .continuous)\n #else\n fatalError("swift_task_enqueueGlobalWithDelay() not supported for task-to-thread")\n #endif\n}\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_enqueueGlobalWithDeadlineImpl")\ninternal func enqueueOnGlobalExecutor(seconds: CLongLong,\n nanoseconds: CLongLong,\n leewaySeconds: CLongLong,\n leewayNanoseconds: CLongLong,\n clock: CInt,\n job unownedJob: UnownedJob) {\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n let delay = Duration.seconds(seconds) + Duration.nanoseconds(nanoseconds)\n let leeway = Duration.seconds(leewaySeconds) + Duration.nanoseconds(leewayNanoseconds)\n switch clock {\n case _ClockID.suspending.rawValue:\n Task.defaultExecutor.asSchedulable!.enqueue(ExecutorJob(unownedJob),\n after: delay,\n tolerance: leeway,\n clock: .suspending)\n case _ClockID.continuous.rawValue:\n Task.defaultExecutor.asSchedulable!.enqueue(ExecutorJob(unownedJob),\n after: delay,\n tolerance: leeway,\n clock: .continuous)\n default:\n fatalError("Unknown clock ID \(clock)")\n }\n #else\n fatalError("swift_task_enqueueGlobalWithDeadline() not supported for task-to-thread")\n #endif\n}\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_ExecutorImpl.swift | cpp_apple_swift_stdlib_public_Concurrency_ExecutorImpl.swift | Swift | 4,556 | 0.95 | 0.133929 | 0.317308 | python-kit | 563 | 2024-06-30T23:07:21.889772 | BSD-3-Clause | false | 0d68353415f4e1cc48c280cc79d62919 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n/// A type that represents a globally-unique actor that can be used to isolate\n/// various declarations anywhere in the program.\n///\n/// A type that conforms to the `GlobalActor` protocol and is marked with\n/// the `@globalActor` attribute can be used as a custom attribute. Such types\n/// are called global actor types, and can be applied to any declaration to\n/// specify that such types are isolated to that global actor type. When using\n/// such a declaration from another actor (or from nonisolated code),\n/// synchronization is performed through the shared actor instance to ensure\n/// mutually-exclusive access to the declaration.\n///\n/// ## Custom Actor Executors\n/// A global actor uses a custom executor if it needs to customize its execution\n/// semantics, for example, by making sure all of its invocations are run on a\n/// specific thread or dispatch queue.\n///\n/// This is done the same way as with normal non-global actors, by declaring a\n/// ``Actor/unownedExecutor`` nonisolated property in the ``ActorType``\n/// underlying this global actor.\n///\n/// It is *not* necessary to override the ``sharedUnownedExecutor`` static\n/// property of the global actor, as its default implementation already\n/// delegates to the ``shared.unownedExecutor``, which is the most reasonable\n/// and correct implementation of this protocol requirement.\n///\n/// You can find out more about custom executors, by referring to the\n/// ``SerialExecutor`` protocol's documentation.\n///\n/// - SeeAlso: ``SerialExecutor``\n@available(SwiftStdlib 5.1, *)\npublic protocol GlobalActor {\n /// The type of the shared actor instance that will be used to provide\n /// mutually-exclusive access to declarations annotated with the given global\n /// actor type.\n associatedtype ActorType: Actor\n\n /// The shared actor instance that will be used to provide mutually-exclusive\n /// access to declarations annotated with the given global actor type.\n ///\n /// The value of this property must always evaluate to the same actor\n /// instance.\n static var shared: ActorType { get }\n\n /// Shorthand for referring to the `shared.unownedExecutor` of this global actor.\n ///\n /// When declaring a global actor with a custom executor, prefer to implement\n /// the underlying actor's ``Actor/unownedExecutor`` property, and leave this\n /// `sharedUnownedExecutor` default implementation in-place as it will simply\n /// delegate to the `shared.unownedExecutor`.\n ///\n /// The value of this property must be equivalent to `shared.unownedExecutor`,\n /// as it may be used by the Swift concurrency runtime or explicit user code with\n /// that assumption in mind.\n ///\n /// Returning different executors for different invocations of this computed\n /// property is also illegal, as it could lead to inconsistent synchronization\n /// of the underlying actor.\n ///\n /// - SeeAlso: ``SerialExecutor``\n static var sharedUnownedExecutor: UnownedSerialExecutor { get }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension GlobalActor {\n public static var sharedUnownedExecutor: UnownedSerialExecutor {\n unsafe shared.unownedExecutor\n }\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_GlobalActor.swift | cpp_apple_swift_stdlib_public_Concurrency_GlobalActor.swift | Swift | 3,643 | 0.95 | 0.072289 | 0.831169 | react-lib | 313 | 2025-06-05T19:32:51.714639 | Apache-2.0 | false | 4baeb220f910e3ca1c885ab6fdd43ec1 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n// None of TaskExecutor APIs are available in task-to-thread concurrency model.\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n/// The global concurrent executor that is used by default for Swift Concurrency\n/// tasks.\n///\n/// The executor's implementation is platform dependent.\n/// By default it uses a fixed size pool of threads and should not be used for\n/// blocking operations which do not guarantee forward progress as doing so may\n/// prevent other tasks from being executed and render the system unresponsive.\n///\n/// You may pass this executor explicitly to a ``Task`` initializer as a task\n/// executor preference, in order to ensure and document that task be executed\n/// on the global executor, instead e.g. inheriting the enclosing actor's\n/// executor. Refer to ``withTaskExecutorPreference(_:operation:)`` for a\n/// detailed discussion of task executor preferences.\n///\n/// Customizing the global concurrent executor is currently not supported.\n@available(SwiftStdlib 6.0, *)\n@available(*, deprecated, renamed: "Task.defaultExecutor")\n@_unavailableInEmbedded\npublic var globalConcurrentExecutor: any TaskExecutor {\n get {\n if #available(SwiftStdlib 6.2, *) {\n return Task.defaultExecutor\n } else {\n return _DefaultGlobalConcurrentExecutor.shared\n }\n }\n}\n\n/// A task executor which enqueues all work on the default global concurrent\n/// thread pool that is used as the default executor for Swift concurrency\n/// tasks.\n@available(SwiftStdlib 6.0, *)\n@_unavailableInEmbedded\ninternal final class _DefaultGlobalConcurrentExecutor: TaskExecutor {\n public static let shared: _DefaultGlobalConcurrentExecutor = .init()\n\n private init() {}\n\n public func enqueue(_ job: consuming ExecutorJob) {\n _enqueueJobGlobal(UnownedJob(job)._context)\n }\n\n public func asUnownedTaskExecutor() -> UnownedTaskExecutor {\n // The "default global concurrent executor" is simply the "undefined" one.\n // We represent it as the `(0, 0)` ExecutorRef and it is handled properly\n // by the runtime, without having to call through to the\n // `_DefaultGlobalConcurrentExecutor` declared in Swift.\n unsafe UnownedTaskExecutor(_getUndefinedTaskExecutor())\n }\n}\n\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_GlobalConcurrentExecutor.swift | cpp_apple_swift_stdlib_public_Concurrency_GlobalConcurrentExecutor.swift | Swift | 2,728 | 0.95 | 0.130435 | 0.590164 | python-kit | 309 | 2024-06-20T14:21:55.857876 | MIT | false | b08686cf65ae227ffdda44ece2f9dcc4 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n#if !$Embedded\n\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n@globalActor public final actor MainActor: GlobalActor {\n public static let shared = MainActor()\n\n @inlinable\n public nonisolated var unownedExecutor: UnownedSerialExecutor {\n return unsafe UnownedSerialExecutor(Builtin.buildMainActorExecutorRef())\n }\n\n @inlinable\n public static var sharedUnownedExecutor: UnownedSerialExecutor {\n return unsafe UnownedSerialExecutor(Builtin.buildMainActorExecutorRef())\n }\n\n @inlinable\n public nonisolated func enqueue(_ job: UnownedJob) {\n _enqueueOnMain(job)\n }\n}\n#else\n/// A singleton actor whose executor is equivalent to the main\n/// dispatch queue.\n@available(SwiftStdlib 5.1, *)\n@globalActor public final actor MainActor: GlobalActor {\n public static let shared = MainActor()\n\n @inlinable\n public nonisolated var unownedExecutor: UnownedSerialExecutor {\n return unsafe UnownedSerialExecutor(Builtin.buildMainActorExecutorRef())\n }\n\n @inlinable\n public static var sharedUnownedExecutor: UnownedSerialExecutor {\n return unsafe UnownedSerialExecutor(Builtin.buildMainActorExecutorRef())\n }\n\n @inlinable\n public nonisolated func enqueue(_ job: UnownedJob) {\n _enqueueOnMain(job)\n }\n}\n#endif\n\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 5.1, *)\nextension MainActor {\n /// Execute the given body closure on the main actor.\n ///\n /// Historical ABI entry point, superseded by the Sendable version that is\n /// also inlined to back-deploy a semantic fix where this operation would\n /// not hop back at the end.\n @usableFromInline\n static func run<T>(\n resultType: T.Type = T.self,\n body: @MainActor @Sendable () throws -> T\n ) async rethrows -> T {\n return try await body()\n }\n\n /// Execute the given body closure on the main actor.\n @_alwaysEmitIntoClient\n public static func run<T: Sendable>(\n resultType: T.Type = T.self,\n body: @MainActor @Sendable () throws -> T\n ) async rethrows -> T {\n return try await body()\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension MainActor {\n /// Assume that the current task is executing on the main actor's\n /// serial executor, or stop program execution.\n ///\n /// This method allows to *assume and verify* that the currently\n /// executing synchronous function is actually executing on the serial\n /// executor of the MainActor.\n ///\n /// If that is the case, the operation is invoked with an `isolated` version\n /// of the actor, / allowing synchronous access to actor local state without\n /// hopping through asynchronous boundaries.\n ///\n /// If the current context is not running on the actor's serial executor, or\n /// if the actor is a reference to a remote actor, this method will crash\n /// with a fatal error (similar to ``preconditionIsolated()``).\n ///\n /// This method can only be used from synchronous functions, as asynchronous\n /// functions should instead perform a normal method call to the actor, which\n /// will hop task execution to the target actor if necessary.\n ///\n /// - Note: This check is performed against the MainActor's serial executor,\n /// meaning that / if another actor uses the same serial executor--by using\n /// ``MainActor/sharedUnownedExecutor`` as its own\n /// ``Actor/unownedExecutor``--this check will succeed , as from a concurrency\n /// safety perspective, the serial executor guarantees mutual exclusion of\n /// those two actors.\n ///\n /// - Parameters:\n /// - operation: the operation that will be executed if the current context\n /// is executing on the MainActor's serial executor.\n /// - file: The file name to print if the assertion fails. The default is\n /// where this method was called.\n /// - line: The line number to print if the assertion fails The default is\n /// where this method was called.\n /// - Returns: the return value of the `operation`\n /// - Throws: rethrows the `Error` thrown by the operation if it threw\n @available(SwiftStdlib 5.1, *)\n @_alwaysEmitIntoClient\n @_unavailableFromAsync(message: "await the call to the @MainActor closure directly")\n public static func assumeIsolated<T : Sendable>(\n _ operation: @MainActor () throws -> T,\n file: StaticString = #fileID, line: UInt = #line\n ) rethrows -> T {\n typealias YesActor = @MainActor () throws -> T\n typealias NoActor = () throws -> T\n\n /// This is guaranteed to be fatal if the check fails,\n /// as this is our "safe" version of this API.\n let executor: Builtin.Executor = unsafe Self.shared.unownedExecutor.executor\n guard _taskIsCurrentExecutor(executor) else {\n // TODO: offer information which executor we actually got\n #if !$Embedded\n fatalError("Incorrect actor executor assumption; Expected same executor as \(self).", file: file, line: line)\n #else\n Builtin.int_trap()\n #endif\n }\n\n // To do the unsafe cast, we have to pretend it's @escaping.\n return try withoutActuallyEscaping(operation) {\n (_ fn: @escaping YesActor) throws -> T in\n let rawFn = unsafe unsafeBitCast(fn, to: NoActor.self)\n return try rawFn()\n }\n }\n\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n @_silgen_name("$sScM14assumeIsolated_4file4linexxyKScMYcXE_s12StaticStringVSutKlFZ")\n internal static func __abi__assumeIsolated<T : Sendable>(\n _ operation: @MainActor () throws -> T,\n _ file: StaticString, _ line: UInt\n ) rethrows -> T {\n try assumeIsolated(operation, file: file, line: line)\n }\n}\n#endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n#endif // !$Embedded\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_MainActor.swift | cpp_apple_swift_stdlib_public_Concurrency_MainActor.swift | Swift | 6,264 | 0.95 | 0.11976 | 0.450331 | react-lib | 748 | 2023-10-29T00:09:50.568773 | Apache-2.0 | false | e264e8d29288ab74f5c50c162c7ab999 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n// N.B. It would be nice to rename this file to ExecutorJob.swift, but when\n// trying that we hit an error from the API digester claiming that\n//\n// +Var UnownedJob.context has mangled name changing from\n// 'Swift.UnownedJob.(context in #UNSTABLE ID#) : Builtin.Job' to\n// 'Swift.UnownedJob.(context in #UNSTABLE ID#) : Builtin.Job'\n//\n// This is odd because `context` is private, so it isn't really part of\n// the module API.\n\n// TODO: It would be better if some of the functions here could be inlined into\n// the Swift code. In particular, some of the ones that deal with data held on\n// ExecutorJob.\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_job_run")\n@usableFromInline\ninternal func _swiftJobRun(_ job: UnownedJob,\n _ executor: UnownedSerialExecutor) -> ()\n\n@_unavailableInEmbedded\n@available(SwiftStdlib 6.0, *)\n@_silgen_name("swift_job_run_on_task_executor")\n@usableFromInline\ninternal func _swiftJobRunOnTaskExecutor(_ job: UnownedJob,\n _ executor: UnownedTaskExecutor) -> ()\n\n@_unavailableInEmbedded\n@available(SwiftStdlib 6.0, *)\n@_silgen_name("swift_job_run_on_serial_and_task_executor")\n@usableFromInline\ninternal func _swiftJobRunOnTaskExecutor(_ job: UnownedJob,\n _ serialExecutor: UnownedSerialExecutor,\n _ taskExecutor: UnownedTaskExecutor) -> ()\n\n// ==== -----------------------------------------------------------------------\n// MARK: UnownedJob\n\n/// A unit of schedulable work.\n///\n/// Unless you're implementing a scheduler,\n/// you don't generally interact with jobs directly.\n///\n/// An `UnownedJob` must be eventually run *exactly once* using ``runSynchronously(on:)``.\n/// Not doing so is effectively going to leak and "hang" the work that the job represents (e.g. a ``Task``).\n@available(SwiftStdlib 5.1, *)\n@frozen\npublic struct UnownedJob: Sendable {\n private var context: Builtin.Job\n\n @usableFromInline\n @available(SwiftStdlib 5.9, *)\n internal init(context: Builtin.Job) {\n self.context = context\n }\n\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n /// Create an `UnownedJob` whose lifetime must be managed carefully until it is run exactly once.\n @available(SwiftStdlib 5.9, *)\n public init(_ job: __owned Job) { // must remain '__owned' in order to not break ABI\n self.context = job.context\n }\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n #if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n /// Create an `UnownedJob` whose lifetime must be managed carefully until it is run exactly once.\n @available(SwiftStdlib 5.9, *)\n public init(_ job: __owned ExecutorJob) { // must remain '__owned' in order to not break ABI\n self.context = job.context\n }\n #endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n /// The priority of this job.\n @available(SwiftStdlib 5.9, *)\n public var priority: JobPriority {\n let raw: UInt8\n if #available(SwiftStdlib 6.2, *) {\n raw = _jobGetPriority(context)\n } else {\n // Since we're building the new version of the stdlib, we should\n // never get here.\n Builtin.unreachable()\n }\n return JobPriority(rawValue: raw)\n }\n\n @available(SwiftStdlib 5.9, *)\n internal var _context: Builtin.Job {\n context\n }\n\n /// Deprecated API to run a job on a specific executor.\n @_alwaysEmitIntoClient\n @inlinable\n @available(*, deprecated, renamed: "ExecutorJob.runSynchronously(on:)")\n public func _runSynchronously(on executor: UnownedSerialExecutor) {\n unsafe _swiftJobRun(self, executor)\n }\n\n /// Run this job on the passed in executor.\n ///\n /// This operation runs the job on the calling thread and *blocks* until the job completes.\n /// The intended use of this method is for an executor to determine when and where it\n /// wants to run the job and then call this method on it.\n ///\n /// The passed in executor reference is used to establish the executor context for the job,\n /// and should be the same executor as the one semantically calling the `runSynchronously` method.\n ///\n /// - Parameter executor: the executor this job will be semantically running on.\n @_alwaysEmitIntoClient\n @inlinable\n public func runSynchronously(on executor: UnownedSerialExecutor) {\n unsafe _swiftJobRun(self, executor)\n }\n\n /// Run this job isolated to the passed task executor.\n ///\n /// This operation runs the job on the calling thread and *blocks* until the job completes.\n /// The intended use of this method is for an executor to determine when and where it\n /// wants to run the job and then call this method on it.\n ///\n /// The passed in executor reference is used to establish the executor context for the job,\n /// and should be the same executor as the one semantically calling the `runSynchronously` method.\n ///\n /// This operation consumes the job, preventing it accidental use after it has been run.\n ///\n /// Converting a `ExecutorJob` to an ``UnownedJob`` and invoking ``UnownedJob/runSynchronously(_:)` on it multiple times is undefined behavior,\n /// as a job can only ever be run once, and must not be accessed after it has been run.\n ///\n /// - Parameter executor: the task executor this job will be run on.\n ///\n /// - SeeAlso: ``runSynchronously(isolatedTo:taskExecutor:)``\n @_unavailableInEmbedded\n @available(SwiftStdlib 6.0, *)\n @_alwaysEmitIntoClient\n @inlinable\n public func runSynchronously(on executor: UnownedTaskExecutor) {\n unsafe _swiftJobRunOnTaskExecutor(self, executor)\n }\n\n /// Run this job isolated to the passed in serial executor, while executing it on the specified task executor.\n ///\n /// This operation runs the job on the calling thread and *blocks* until the job completes.\n /// The intended use of this method is for an executor to determine when and where it\n /// wants to run the job and then call this method on it.\n ///\n /// The passed in executor reference is used to establish the executor context for the job,\n /// and should be the same executor as the one semantically calling the `runSynchronously` method.\n ///\n /// This operation consumes the job, preventing it accidental use after it has been run.\n ///\n /// Converting a `ExecutorJob` to an ``UnownedJob`` and invoking\n /// ``UnownedJob/runSynchronously(isolatedTo:taskExecutor:)` on it multiple times\n /// is undefined behavior, as a job can only ever be run once, and must not be\n /// accessed after it has been run.\n ///\n /// - Parameter serialExecutor: the executor this job will be semantically running on.\n /// - Parameter taskExecutor: the task executor this job will be run on.\n ///\n /// - SeeAlso: ``runSynchronously(on:)``\n @_unavailableInEmbedded\n @available(SwiftStdlib 6.0, *)\n @_alwaysEmitIntoClient\n @inlinable\n public func runSynchronously(isolatedTo serialExecutor: UnownedSerialExecutor,\n taskExecutor: UnownedTaskExecutor) {\n unsafe _swiftJobRunOnTaskExecutor(self, serialExecutor, taskExecutor)\n }\n\n}\n\n@_unavailableInEmbedded\n@available(SwiftStdlib 5.9, *)\nextension UnownedJob: CustomStringConvertible {\n @available(SwiftStdlib 5.9, *)\n public var description: String {\n let id = _getJobTaskId(self)\n /// Tasks are always assigned a unique ID, however some jobs may not have it set,\n /// and it appearing as 0 for _different_ jobs may lead to misunderstanding it as\n /// being "the same 0 id job", we specifically print 0 (id not set) as nil.\n if (id > 0) {\n return "\(Self.self)(id: \(id))"\n } else {\n return "\(Self.self)(id: nil)"\n }\n }\n}\n\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n/// Deprecated equivalent of ``ExecutorJob``.\n///\n/// A unit of schedulable work.\n///\n/// Unless you're implementing a scheduler,\n/// you don't generally interact with jobs directly.\n@available(SwiftStdlib 5.9, *)\n@available(*, deprecated, renamed: "ExecutorJob")\n@frozen\npublic struct Job: Sendable, ~Copyable {\n internal var context: Builtin.Job\n\n @usableFromInline\n internal init(context: __owned Builtin.Job) {\n self.context = context\n }\n\n public init(_ job: UnownedJob) {\n self.context = job._context\n }\n\n public init(_ job: __owned ExecutorJob) {\n self.context = job.context\n }\n\n public var priority: JobPriority {\n let raw: UInt8\n if #available(SwiftStdlib 6.2, *) {\n raw = _jobGetPriority(self.context)\n } else {\n // We are building the new version of the code, so we should never\n // get here.\n Builtin.unreachable()\n }\n return JobPriority(rawValue: raw)\n }\n\n // TODO: move only types cannot conform to protocols, so we can't conform to CustomStringConvertible;\n // we can still offer a description to be called explicitly though.\n @_unavailableInEmbedded\n public var description: String {\n let id = _getJobTaskId(UnownedJob(context: self.context))\n /// Tasks are always assigned a unique ID, however some jobs may not have it set,\n /// and it appearing as 0 for _different_ jobs may lead to misunderstanding it as\n /// being "the same 0 id job", we specifically print 0 (id not set) as nil.\n if (id > 0) {\n return "Job(id: \(id))"\n } else {\n return "Job(id: nil)"\n }\n }\n}\n\n@available(SwiftStdlib 5.9, *)\nextension Job {\n\n /// Run this job on the passed in executor.\n ///\n /// This operation runs the job on the calling thread and *blocks* until the job completes.\n /// The intended use of this method is for an executor to determine when and where it\n /// wants to run the job and then call this method on it.\n ///\n /// The passed in executor reference is used to establish the executor context for the job,\n /// and should be the same executor as the one semantically calling the `runSynchronously` method.\n ///\n /// This operation consumes the job, preventing it accidental use after it has been run.\n ///\n /// Converting a `ExecutorJob` to an ``UnownedJob`` and invoking ``UnownedJob/runSynchronously(_:)` on it multiple times is undefined behavior,\n /// as a job can only ever be run once, and must not be accessed after it has been run.\n ///\n /// - Parameter executor: the executor this job will be semantically running on.\n @_alwaysEmitIntoClient\n @inlinable\n __consuming public func runSynchronously(on executor: UnownedSerialExecutor) {\n unsafe _swiftJobRun(UnownedJob(self), executor)\n }\n}\n\n/// A unit of schedulable work.\n///\n/// Unless you're implementing a scheduler,\n/// you don't generally interact with jobs directly.\n@available(SwiftStdlib 5.9, *)\n@frozen\npublic struct ExecutorJob: Sendable, ~Copyable {\n internal var context: Builtin.Job\n\n @usableFromInline\n internal init(context: __owned Builtin.Job) {\n self.context = context\n }\n\n public init(_ job: UnownedJob) {\n self.context = job._context\n }\n\n public init(_ job: __owned Job) {\n self.context = job.context\n }\n\n public var priority: JobPriority {\n let raw: UInt8\n if #available(SwiftStdlib 6.2, *) {\n raw = _jobGetPriority(self.context)\n } else {\n // We are building the new version of the code, so we should never\n // get here.\n Builtin.unreachable()\n }\n return JobPriority(rawValue: raw)\n }\n\n /// Execute a closure, passing it the bounds of the executor private data\n /// for the job.\n ///\n /// Parameters:\n ///\n /// - body: The closure to execute.\n ///\n /// Returns the result of executing the closure.\n @available(SwiftStdlib 6.2, *)\n public func withUnsafeExecutorPrivateData<R, E>(body: (UnsafeMutableRawBufferPointer) throws(E) -> R) throws(E) -> R {\n let base = unsafe _jobGetExecutorPrivateData(self.context)\n let size = unsafe 2 * MemoryLayout<OpaquePointer>.stride\n return unsafe try body(UnsafeMutableRawBufferPointer(start: base,\n count: size))\n }\n\n /// Kinds of schedulable jobs\n @available(SwiftStdlib 6.2, *)\n @frozen\n public struct Kind: Sendable, RawRepresentable {\n public typealias RawValue = UInt8\n\n /// The raw job kind value.\n public var rawValue: RawValue\n\n /// Creates a new instance with the specified raw value.\n public init?(rawValue: Self.RawValue) {\n self.rawValue = rawValue\n }\n\n /// A task.\n public static let task = Kind(rawValue: RawValue(0))!\n\n // Job kinds >= 192 are private to the implementation.\n public static let firstReserved = Kind(rawValue: RawValue(192))!\n }\n\n /// What kind of job this is.\n @available(SwiftStdlib 6.2, *)\n public var kind: Kind {\n return Kind(rawValue: _jobGetKind(self.context))!\n }\n\n // TODO: move only types cannot conform to protocols, so we can't conform to CustomStringConvertible;\n // we can still offer a description to be called explicitly though.\n @_unavailableInEmbedded\n public var description: String {\n let id = _getJobTaskId(UnownedJob(context: self.context))\n /// Tasks are always assigned a unique ID, however some jobs may not have it set,\n /// and it appearing as 0 for _different_ jobs may lead to misunderstanding it as\n /// being "the same 0 id job", we specifically print 0 (id not set) as nil.\n if (id > 0) {\n return "ExecutorJob(id: \(id))"\n } else {\n return "ExecutorJob(id: nil)"\n }\n }\n}\n\n@available(SwiftStdlib 5.9, *)\nextension ExecutorJob {\n\n /// Run this job on the passed in executor.\n ///\n /// This operation runs the job on the calling thread and *blocks* until the job completes.\n /// The intended use of this method is for an executor to determine when and where it\n /// wants to run the job and then call this method on it.\n ///\n /// The passed in executor reference is used to establish the executor context for the job,\n /// and should be the same executor as the one semantically calling the `runSynchronously` method.\n ///\n /// This operation consumes the job, preventing it accidental use after it has been run.\n ///\n /// Converting a `ExecutorJob` to an ``UnownedJob`` and invoking ``UnownedJob/runSynchronously(_:)` on it multiple times is undefined behavior,\n /// as a job can only ever be run once, and must not be accessed after it has been run.\n ///\n /// - Parameter executor: the executor this job will be semantically running on.\n @_alwaysEmitIntoClient\n @inlinable\n __consuming public func runSynchronously(on executor: UnownedSerialExecutor) {\n unsafe _swiftJobRun(UnownedJob(self), executor)\n }\n\n /// Run this job on the passed in task executor.\n ///\n /// This operation runs the job on the calling thread and *blocks* until the job completes.\n /// The intended use of this method is for an executor to determine when and where it\n /// wants to run the job and then call this method on it.\n ///\n /// The passed in executor reference is used to establish the executor context for the job,\n /// and should be the same executor as the one semantically calling the `runSynchronously` method.\n ///\n /// This operation consumes the job, preventing it accidental use after it has been run.\n ///\n /// Converting a `ExecutorJob` to an ``UnownedJob`` and invoking ``UnownedJob/runSynchronously(_:)` on it multiple times is undefined behavior,\n /// as a job can only ever be run once, and must not be accessed after it has been run.\n ///\n /// - Parameter executor: the executor this job will be run on.\n ///\n /// - SeeAlso: ``runSynchronously(isolatedTo:taskExecutor:)``\n @_unavailableInEmbedded\n @available(SwiftStdlib 6.0, *)\n @_alwaysEmitIntoClient\n @inlinable\n __consuming public func runSynchronously(on executor: UnownedTaskExecutor) {\n unsafe _swiftJobRunOnTaskExecutor(UnownedJob(self), executor)\n }\n\n /// Run this job isolated to the passed in serial executor, while executing it on the specified task executor.\n ///\n /// This operation runs the job on the calling thread and *blocks* until the job completes.\n /// The intended use of this method is for an executor to determine when and where it\n /// wants to run the job and then call this method on it.\n ///\n /// The passed in executor reference is used to establish the executor context for the job,\n /// and should be the same executor as the one semantically calling the `runSynchronously` method.\n ///\n /// This operation consumes the job, preventing it accidental use after it has been run.\n ///\n /// - Parameter serialExecutor: the executor this job will be semantically running on.\n /// - Parameter taskExecutor: the task executor this job will be run on.\n ///\n /// - SeeAlso: ``runSynchronously(on:)``\n @_unavailableInEmbedded\n @available(SwiftStdlib 6.0, *)\n @_alwaysEmitIntoClient\n @inlinable\n __consuming public func runSynchronously(isolatedTo serialExecutor: UnownedSerialExecutor,\n taskExecutor: UnownedTaskExecutor) {\n unsafe _swiftJobRunOnTaskExecutor(UnownedJob(self), serialExecutor, taskExecutor)\n }\n}\n\n// Stack-disciplined job-local allocator support\n@available(SwiftStdlib 6.2, *)\nextension ExecutorJob {\n\n /// Obtain a stack-disciplined job-local allocator.\n ///\n /// If the job does not support allocation, this property will be `nil`.\n public var allocator: LocalAllocator? {\n guard self.kind == .task else {\n return nil\n }\n\n return LocalAllocator(context: self.context)\n }\n\n /// A job-local stack-disciplined allocator.\n ///\n /// This can be used to allocate additional data required by an\n /// executor implementation; memory allocated in this manner will\n /// be released automatically when the job is disposed of by the\n /// runtime.\n ///\n /// N.B. Because this allocator is stack disciplined, explicitly\n /// deallocating memory out-of-order will cause your program to abort.\n public struct LocalAllocator {\n internal var context: Builtin.Job\n\n /// Allocate a specified number of bytes of uninitialized memory.\n public func allocate(capacity: Int) -> UnsafeMutableRawBufferPointer {\n let base = unsafe _jobAllocate(context, capacity)\n return unsafe UnsafeMutableRawBufferPointer(start: base, count: capacity)\n }\n\n /// Allocate uninitialized memory for a single instance of type `T`.\n public func allocate<T>(as type: T.Type) -> UnsafeMutablePointer<T> {\n let base = unsafe _jobAllocate(context, MemoryLayout<T>.size)\n return unsafe base.bindMemory(to: type, capacity: 1)\n }\n\n /// Allocate uninitialized memory for the specified number of\n /// instances of type `T`.\n public func allocate<T>(capacity: Int, as type: T.Type)\n -> UnsafeMutableBufferPointer<T> {\n let base = unsafe _jobAllocate(context, MemoryLayout<T>.stride * capacity)\n let typedBase = unsafe base.bindMemory(to: T.self, capacity: capacity)\n return unsafe UnsafeMutableBufferPointer<T>(start: typedBase, count: capacity)\n }\n\n /// Deallocate previously allocated memory. Note that the task\n /// allocator is stack disciplined, so if you deallocate a block of\n /// memory, all memory allocated after that block is also deallocated.\n public func deallocate(_ buffer: UnsafeMutableRawBufferPointer) {\n unsafe _jobDeallocate(context, buffer.baseAddress!)\n }\n\n /// Deallocate previously allocated memory. Note that the task\n /// allocator is stack disciplined, so if you deallocate a block of\n /// memory, all memory allocated after that block is also deallocated.\n public func deallocate<T>(_ pointer: UnsafeMutablePointer<T>) {\n unsafe _jobDeallocate(context, UnsafeMutableRawPointer(pointer))\n }\n\n /// Deallocate previously allocated memory. Note that the task\n /// allocator is stack disciplined, so if you deallocate a block of\n /// memory, all memory allocated after that block is also deallocated.\n public func deallocate<T>(_ buffer: UnsafeMutableBufferPointer<T>) {\n unsafe _jobDeallocate(context, UnsafeMutableRawPointer(buffer.baseAddress!))\n }\n\n }\n\n}\n\n\n#endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n// ==== -----------------------------------------------------------------------\n// MARK: JobPriority\n\n/// The priority of this job.\n///\n/// The executor determines how priority information affects the way tasks are scheduled.\n/// The behavior varies depending on the executor currently being used.\n/// Typically, executors attempt to run tasks with a higher priority\n/// before tasks with a lower priority.\n/// However, the semantics of how priority is treated are left up to each\n/// platform and `Executor` implementation.\n///\n/// A ExecutorJob's priority is roughly equivalent to a `TaskPriority`,\n/// however, since not all jobs are tasks, represented as separate type.\n///\n/// Conversions between the two priorities are available as initializers on the respective types.\n@available(SwiftStdlib 5.9, *)\n@frozen\npublic struct JobPriority: Sendable {\n public typealias RawValue = UInt8\n\n /// The raw priority value.\n public var rawValue: RawValue\n}\n\n@available(SwiftStdlib 5.9, *)\nextension TaskPriority {\n /// Convert this ``UnownedJob/Priority`` to a ``TaskPriority``.\n ///\n /// Most values are directly interchangeable, but this initializer reserves the right to fail for certain values.\n @available(SwiftStdlib 5.9, *)\n public init?(_ p: JobPriority) {\n guard p.rawValue != 0 else {\n // 0 is "undefined"\n return nil\n }\n self = TaskPriority(rawValue: p.rawValue)\n }\n}\n\n@available(SwiftStdlib 5.9, *)\nextension JobPriority: Equatable {\n public static func == (lhs: JobPriority, rhs: JobPriority) -> Bool {\n lhs.rawValue == rhs.rawValue\n }\n\n public static func != (lhs: JobPriority, rhs: JobPriority) -> Bool {\n lhs.rawValue != rhs.rawValue\n }\n}\n\n@available(SwiftStdlib 5.9, *)\nextension JobPriority: Comparable {\n public static func < (lhs: JobPriority, rhs: JobPriority) -> Bool {\n lhs.rawValue < rhs.rawValue\n }\n\n public static func <= (lhs: JobPriority, rhs: JobPriority) -> Bool {\n lhs.rawValue <= rhs.rawValue\n }\n\n public static func > (lhs: JobPriority, rhs: JobPriority) -> Bool {\n lhs.rawValue > rhs.rawValue\n }\n\n public static func >= (lhs: JobPriority, rhs: JobPriority) -> Bool {\n lhs.rawValue >= rhs.rawValue\n }\n}\n\n// ==== -----------------------------------------------------------------------\n// MARK: UnsafeContinuation\n\n/// A mechanism to interface\n/// between synchronous and asynchronous code,\n/// without correctness checking.\n///\n/// A *continuation* is an opaque representation of program state.\n/// To create a continuation in asynchronous code,\n/// call the `withUnsafeContinuation(_:)` or\n/// `withUnsafeThrowingContinuation(_:)` function.\n/// To resume the asynchronous task,\n/// call the `resume(returning:)`,\n/// `resume(throwing:)`,\n/// `resume(with:)`,\n/// or `resume()` method.\n///\n/// - Important: You must call a resume method exactly once\n/// on every execution path throughout the program.\n/// Resuming from a continuation more than once is undefined behavior.\n/// Never resuming leaves the task in a suspended state indefinitely,\n/// and leaks any associated resources.\n///\n/// `CheckedContinuation` performs runtime checks\n/// for missing or multiple resume operations.\n/// `UnsafeContinuation` avoids enforcing these invariants at runtime\n/// because it aims to be a low-overhead mechanism\n/// for interfacing Swift tasks with\n/// event loops, delegate methods, callbacks,\n/// and other non-`async` scheduling mechanisms.\n/// However, during development, the ability to verify that the\n/// invariants are being upheld in testing is important.\n/// Because both types have the same interface,\n/// you can replace one with the other in most circumstances,\n/// without making other changes.\n@available(SwiftStdlib 5.1, *)\n@frozen\n@unsafe\npublic struct UnsafeContinuation<T, E: Error>: Sendable {\n @usableFromInline internal var context: Builtin.RawUnsafeContinuation\n\n @_alwaysEmitIntoClient\n internal init(_ context: Builtin.RawUnsafeContinuation) {\n unsafe self.context = context\n }\n\n /// Resume the task that's awaiting the continuation\n /// by returning the given value.\n ///\n /// - Parameter value: The value to return from the continuation.\n ///\n /// A continuation must be resumed exactly once.\n /// If the continuation has already resumed,\n /// then calling this method results in undefined behavior.\n ///\n /// After calling this method,\n /// control immediately returns to the caller.\n /// The task continues executing\n /// when its executor schedules it.\n @_alwaysEmitIntoClient\n public func resume(returning value: sending T) where E == Never {\n #if compiler(>=5.5) && $BuiltinContinuation\n unsafe Builtin.resumeNonThrowingContinuationReturning(context, value)\n #else\n fatalError("Swift compiler is incompatible with this SDK version")\n #endif\n }\n\n /// Resume the task that's awaiting the continuation\n /// by returning the given value.\n ///\n /// - Parameter value: The value to return from the continuation.\n ///\n /// A continuation must be resumed exactly once.\n /// If the continuation has already resumed,\n /// then calling this method results in undefined behavior.\n ///\n /// After calling this method,\n /// control immediately returns to the caller.\n /// The task continues executing\n /// when its executor schedules it.\n @_alwaysEmitIntoClient\n public func resume(returning value: sending T) {\n #if compiler(>=5.5) && $BuiltinContinuation\n unsafe Builtin.resumeThrowingContinuationReturning(context, value)\n #else\n fatalError("Swift compiler is incompatible with this SDK version")\n #endif\n }\n\n /// Resume the task that's awaiting the continuation\n /// by throwing the given error.\n ///\n /// - Parameter error: The error to throw from the continuation.\n ///\n /// A continuation must be resumed exactly once.\n /// If the continuation has already resumed,\n /// then calling this method results in undefined behavior.\n ///\n /// After calling this method,\n /// control immediately returns to the caller.\n /// The task continues executing\n /// when its executor schedules it.\n @_alwaysEmitIntoClient\n public func resume(throwing error: consuming E) {\n #if compiler(>=5.5) && $BuiltinContinuation\n unsafe Builtin.resumeThrowingContinuationThrowing(context, error)\n #else\n fatalError("Swift compiler is incompatible with this SDK version")\n #endif\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension UnsafeContinuation {\n /// Resume the task that's awaiting the continuation\n /// by returning or throwing the given result value.\n ///\n /// - Parameter result: The result.\n /// If it contains a `.success` value,\n /// the continuation returns that value;\n /// otherwise, it throws the `.error` value.\n ///\n /// A continuation must be resumed exactly once.\n /// If the continuation has already resumed,\n /// then calling this method results in undefined behavior.\n ///\n /// After calling this method,\n /// control immediately returns to the caller.\n /// The task continues executing\n /// when its executor schedules it.\n @_alwaysEmitIntoClient\n public func resume<Er: Error>(with result: __shared sending Result<T, Er>) where E == Error {\n switch result {\n case .success(let val):\n unsafe self.resume(returning: val)\n case .failure(let err):\n unsafe self.resume(throwing: err)\n }\n }\n\n /// Resume the task that's awaiting the continuation\n /// by returning or throwing the given result value.\n ///\n /// - Parameter result: The result.\n /// If it contains a `.success` value,\n /// the continuation returns that value;\n /// otherwise, it throws the `.error` value.\n ///\n /// A continuation must be resumed exactly once.\n /// If the continuation has already resumed,\n /// then calling this method results in undefined behavior.\n ///\n /// After calling this method,\n /// control immediately returns to the caller.\n /// The task continues executing\n /// when its executor schedules it.\n @_alwaysEmitIntoClient\n public func resume(with result: __shared sending Result<T, E>) {\n switch result {\n case .success(let val):\n unsafe self.resume(returning: val)\n case .failure(let err):\n unsafe self.resume(throwing: err)\n }\n }\n\n /// Resume the task that's awaiting the continuation by returning.\n ///\n /// A continuation must be resumed exactly once.\n /// If the continuation has already resumed,\n /// then calling this method results in undefined behavior.\n ///\n /// After calling this method,\n /// control immediately returns to the caller.\n /// The task continues executing\n /// when its executor schedules it.\n @_alwaysEmitIntoClient\n public func resume() where T == Void {\n unsafe self.resume(returning: ())\n }\n}\n\n#if _runtime(_ObjC)\n\n// Intrinsics used by SILGen to resume or fail continuations.\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\ninternal func _resumeUnsafeContinuation<T>(\n _ continuation: UnsafeContinuation<T, Never>,\n _ value: sending T\n) {\n unsafe continuation.resume(returning: value)\n}\n\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\ninternal func _resumeUnsafeThrowingContinuation<T>(\n _ continuation: UnsafeContinuation<T, Error>,\n _ value: sending T\n) {\n unsafe continuation.resume(returning: value)\n}\n\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\ninternal func _resumeUnsafeThrowingContinuationWithError<T>(\n _ continuation: UnsafeContinuation<T, Error>,\n _ error: consuming Error\n) {\n unsafe continuation.resume(throwing: error)\n}\n\n#endif\n\n\n/// Invokes the passed in closure with a unsafe continuation for the current task.\n///\n/// The body of the closure executes synchronously on the calling task, and once it returns\n/// the calling task is suspended. It is possible to immediately resume the task, or escape the\n/// continuation in order to complete it afterwards, which will then resume the suspended task.\n///\n/// You must invoke the continuation's `resume` method exactly once.\n///\n/// Missing to invoke it (eventually) will cause the calling task to remain suspended\n/// indefinitely which will result in the task "hanging" as well as being leaked with\n/// no possibility to destroy it.\n///\n/// Unlike the "checked" continuation variant, the `UnsafeContinuation` does not\n/// detect or diagnose any kind of misuse, so you need to be extra careful to avoid\n/// calling `resume` twice or forgetting to call resume before letting go of the\n/// continuation object.\n///\n/// - Parameter fn: A closure that takes an `UnsafeContinuation` parameter.\n/// - Returns: The value continuation is resumed with.\n///\n/// - SeeAlso: `withUnsafeThrowingContinuation(function:_:)`\n/// - SeeAlso: `withCheckedContinuation(function:_:)`\n/// - SeeAlso: `withCheckedThrowingContinuation(function:_:)`\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\n@unsafe\npublic func withUnsafeContinuation<T>(\n isolation: isolated (any Actor)? = #isolation,\n _ fn: (UnsafeContinuation<T, Never>) -> Void\n) async -> sending T {\n return await Builtin.withUnsafeContinuation {\n unsafe fn(UnsafeContinuation<T, Never>($0))\n }\n}\n\n/// Invokes the passed in closure with a unsafe continuation for the current task.\n///\n/// The body of the closure executes synchronously on the calling task, and once it returns\n/// the calling task is suspended. It is possible to immediately resume the task, or escape the\n/// continuation in order to complete it afterwards, which will then resume the suspended task.\n///\n/// If `resume(throwing:)` is called on the continuation, this function throws that error.\n///\n/// You must invoke the continuation's `resume` method exactly once.\n///\n/// Missing to invoke it (eventually) will cause the calling task to remain suspended\n/// indefinitely which will result in the task "hanging" as well as being leaked with\n/// no possibility to destroy it.\n///\n/// Unlike the "checked" continuation variant, the `UnsafeContinuation` does not\n/// detect or diagnose any kind of misuse, so you need to be extra careful to avoid\n/// calling `resume` twice or forgetting to call resume before letting go of the\n/// continuation object.\n///\n/// - Parameter fn: A closure that takes an `UnsafeContinuation` parameter.\n/// - Returns: The value continuation is resumed with.\n///\n/// - SeeAlso: `withUnsafeContinuation(function:_:)`\n/// - SeeAlso: `withCheckedContinuation(function:_:)`\n/// - SeeAlso: `withCheckedThrowingContinuation(function:_:)`\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\n@unsafe\npublic func withUnsafeThrowingContinuation<T>(\n isolation: isolated (any Actor)? = #isolation,\n _ fn: (UnsafeContinuation<T, Error>) -> Void\n) async throws -> sending T {\n return try await Builtin.withUnsafeThrowingContinuation {\n unsafe fn(UnsafeContinuation<T, Error>($0))\n }\n}\n\n// Note: hack to stage out @_unsafeInheritExecutor forms of various functions\n// in favor of #isolation. The _unsafeInheritExecutor_ prefix is meaningful\n// to the type checker.\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\n@_unsafeInheritExecutor\npublic func _unsafeInheritExecutor_withUnsafeContinuation<T>(\n _ fn: (UnsafeContinuation<T, Never>) -> Void\n) async -> sending T {\n return await Builtin.withUnsafeContinuation {\n unsafe fn(UnsafeContinuation<T, Never>($0))\n }\n}\n\n// Note: hack to stage out @_unsafeInheritExecutor forms of various functions\n// in favor of #isolation. The _unsafeInheritExecutor_ prefix is meaningful\n// to the type checker.\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\n@_unsafeInheritExecutor\npublic func _unsafeInheritExecutor_withUnsafeThrowingContinuation<T>(\n _ fn: (UnsafeContinuation<T, Error>) -> Void\n) async throws -> sending T {\n return try await Builtin.withUnsafeThrowingContinuation {\n unsafe fn(UnsafeContinuation<T, Error>($0))\n }\n}\n\n/// A hack to mark an SDK that supports swift_continuation_await.\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\npublic func _abiEnableAwaitContinuation() {\n fatalError("never use this function")\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_PartialAsyncTask.swift | cpp_apple_swift_stdlib_public_Concurrency_PartialAsyncTask.swift | Swift | 34,489 | 0.95 | 0.065431 | 0.509662 | vue-tools | 712 | 2023-09-06T08:43:01.114141 | BSD-3-Clause | false | 627602cca410b5e5e6f106b252fd555c |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n// This platform uses a single, global, CooperativeExecutor\n@available(SwiftStdlib 6.2, *)\npublic struct PlatformExecutorFactory: ExecutorFactory {\n static let executor = CooperativeExecutor()\n public static var mainExecutor: any MainExecutor { executor }\n public static var defaultExecutor: any TaskExecutor { executor }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_PlatformExecutorCooperative.swift | cpp_apple_swift_stdlib_public_Concurrency_PlatformExecutorCooperative.swift | Swift | 861 | 0.95 | 0.095238 | 0.631579 | node-utils | 742 | 2024-02-18T03:17:36.706194 | BSD-3-Clause | false | 41ead0b219e446a81506948f080d897e |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY && (os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(visionOS))\n\nimport Swift\n\n@available(SwiftStdlib 6.2, *)\npublic struct PlatformExecutorFactory: ExecutorFactory {\n public static var mainExecutor: any MainExecutor {\n if CoreFoundation.isPresent {\n return CFMainExecutor()\n } else {\n return DispatchMainExecutor()\n }\n }\n\n public static var defaultExecutor: any TaskExecutor {\n if CoreFoundation.isPresent {\n return CFTaskExecutor()\n } else {\n return DispatchGlobalTaskExecutor()\n }\n }\n}\n\n#endif // os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(visionOS)\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_PlatformExecutorDarwin.swift | cpp_apple_swift_stdlib_public_Concurrency_PlatformExecutorDarwin.swift | Swift | 1,196 | 0.95 | 0.138889 | 0.419355 | vue-tools | 329 | 2024-08-11T20:54:20.719981 | MIT | false | 837d4d797c7073496b194c20abc402be |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if !$Embedded && (os(Linux) || os(Android))\n\nimport Swift\n\n// The default executors for now are Dispatch-based\n@available(SwiftStdlib 6.2, *)\npublic struct PlatformExecutorFactory: ExecutorFactory {\n public static let mainExecutor: any MainExecutor = DispatchMainExecutor()\n public static let defaultExecutor: any TaskExecutor\n = DispatchGlobalTaskExecutor()\n}\n\n#endif // os(Linux)\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_PlatformExecutorLinux.swift | cpp_apple_swift_stdlib_public_Concurrency_PlatformExecutorLinux.swift | Swift | 908 | 0.95 | 0.16 | 0.666667 | react-lib | 232 | 2024-09-19T20:30:23.589446 | BSD-3-Clause | false | 3304ba2dc8c7e50aab1b9d5b9fcd2998 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n@available(SwiftStdlib 6.2, *)\npublic struct PlatformExecutorFactory: ExecutorFactory {\n public static let mainExecutor: any MainExecutor = DummyMainExecutor()\n public static let defaultExecutor: any TaskExecutor = DummyTaskExecutor()\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_PlatformExecutorNone.swift | cpp_apple_swift_stdlib_public_Concurrency_PlatformExecutorNone.swift | Swift | 773 | 0.95 | 0.105263 | 0.647059 | node-utils | 162 | 2025-01-16T12:11:58.662481 | Apache-2.0 | false | ef4f8852efd4eabb23f3b78d065ae19a |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if !$Embedded && os(Windows)\n\nimport Swift\n\n// The default executors for now are Dispatch-based\n@available(SwiftStdlib 6.2, *)\npublic struct PlatformExecutorFactory: ExecutorFactory {\n public static let mainExecutor: any MainExecutor = DispatchMainExecutor()\n public static let defaultExecutor: any TaskExecutor =\n DispatchGlobalTaskExecutor()\n}\n\n#endif // os(Windows)\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_PlatformExecutorWindows.swift | cpp_apple_swift_stdlib_public_Concurrency_PlatformExecutorWindows.swift | Swift | 895 | 0.95 | 0.16 | 0.666667 | python-kit | 957 | 2024-08-10T01:44:07.750077 | GPL-3.0 | false | 11a59d2d5503b219782c1d3772565771 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n/// A generic priority queue, with a user-defined comparison function.\nstruct PriorityQueue<T> {\n /// The backing store.\n var storage: [T] = []\n\n /// The comparison function; this should compare the priorities of\n /// two items in the queue, returning `true` if they satisfy the\n /// desired condition.\n ///\n /// A `>` test will produce a max-queue, while a `<` test will\n /// result in a min-queue.\n var compare: (borrowing T, borrowing T) -> Bool\n\n /// Initialise the queue.\n ///\n /// The queue is set up such that if the comparison function in use\n /// is `>`, it will be a max-queue, while if the comparison function\n /// is `<`, it will be a min-queue.\n ///\n /// Parameters:\n ///\n /// - compare: A closure that takes two arguments of type T, and\n /// returns true if some condition holds.\n ///\n init(compare: @escaping (borrowing T, borrowing T) -> Bool) {\n self.compare = compare\n }\n\n /// Push an item onto the queue.\n ///\n /// Parameters:\n ///\n /// - _ value: The item to push onto the queue.\n ///\n mutating func push(_ value: T) {\n storage.append(value)\n upHeap(ndx: storage.count - 1)\n }\n\n /// The highest priority item from the queue, or `nil` if none.\n var top: T? {\n if storage.isEmpty {\n return nil\n }\n return storage[0]\n }\n\n /// Conditionally pop the highest priority item from the queue.\n ///\n /// If the comparison function is `>`, this will return the largest\n /// item in the queue. If the comparison function is `<`, it will\n /// return the smallest.\n ///\n /// Parameters:\n ///\n /// - when: A closure that allows code to test the top item before\n /// popping.\n ///\n /// Returns: The next item in the queue, following the comparison\n /// rule.\n ///\n mutating func pop(when condition: (borrowing T) -> Bool) -> T? {\n if storage.isEmpty {\n return nil\n }\n if !condition(storage[0]) {\n return nil\n }\n storage.swapAt(0, storage.count - 1)\n let result = storage.removeLast()\n if !storage.isEmpty {\n downHeap(ndx: 0)\n }\n return result\n }\n\n /// Pop the highest priority item from the queue.\n ///\n /// If the comparison function is `>`, this will return the largest\n /// item in the queue. If the comparison function is `<`, it will\n /// return the smallest.\n ///\n /// Returns: The next item in the queue, following the comparison\n /// rule.\n ///\n mutating func pop() -> T? {\n if storage.isEmpty {\n return nil\n }\n storage.swapAt(0, storage.count - 1)\n let result = storage.removeLast()\n if !storage.isEmpty {\n downHeap(ndx: 0)\n }\n return result\n }\n\n /// Fix the heap condition by iterating upwards.\n ///\n /// Iterate upwards from the specified entry, exchanging it with\n /// its parent if the parent and child do not satisfy the comparison\n /// function.\n ///\n /// This is used when pushing items onto the queue.\n ///\n /// Parameters:\n ///\n /// - ndx: The index at which to start.\n ///\n private mutating func upHeap(ndx: Int) {\n var theNdx = ndx\n while theNdx > 0 {\n let parentNdx = theNdx / 2\n\n if !compare(storage[theNdx], storage[parentNdx]) {\n break\n }\n\n storage.swapAt(theNdx, parentNdx)\n theNdx = parentNdx\n }\n }\n\n /// Fix the heap condition by iterating downwards.\n ///\n /// Iterate downwards from the specified entry, checking that its\n /// children satisfy the comparison function. If they do, stop,\n /// otherwise exchange the parent entry with the highest priority\n /// child.\n ///\n /// This is used when popping items from the queue.\n ///\n /// Parameters:\n ///\n /// - ndx: The index at which to start.\n ///\n private mutating func downHeap(ndx: Int) {\n var theNdx = ndx\n while true {\n let leftNdx = 2 * theNdx\n\n if leftNdx >= storage.count {\n break\n }\n\n let rightNdx = 2 * theNdx + 1\n var largestNdx = theNdx\n\n if compare(storage[leftNdx], storage[largestNdx]) {\n largestNdx = leftNdx\n }\n\n if rightNdx < storage.count\n && compare(storage[rightNdx], storage[largestNdx]) {\n largestNdx = rightNdx\n }\n\n if largestNdx == theNdx {\n break\n }\n\n storage.swapAt(theNdx, largestNdx)\n theNdx = largestNdx\n }\n }\n}\n\nextension PriorityQueue where T: Comparable {\n /// Initialise the priority queue.\n ///\n /// `Comparable` types have a default implementation, which passes the\n /// `>` operator as the comparison function, thus providing a max-queue.\n ///\n /// If you are using a `Comparable` type and require a min-queue, you\n /// can make one with\n ///\n /// ```swift\n /// let minQueue = PriorityQueue(compare: <)\n /// ```\n ///\n init() {\n self.init(compare: >)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_PriorityQueue.swift | cpp_apple_swift_stdlib_public_Concurrency_PriorityQueue.swift | Swift | 5,295 | 0.95 | 0.171717 | 0.541899 | node-utils | 492 | 2025-04-22T06:33:43.242593 | BSD-3-Clause | false | ad9bd36c2ea17b3398e9e64840040d27 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n// This file provides source compatibility shims to help migrate code\n// using earlier versions of the concurrency library to the latest syntax.\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Success == Never, Failure == Never {\n @available(*, deprecated, message: "Task.Priority has been removed; use TaskPriority")\n public typealias Priority = TaskPriority\n\n @available(*, deprecated, message: "Task.Handle has been removed; use Task")\n public typealias Handle = _Concurrency.Task\n\n @available(*, deprecated, message: "Task.CancellationError has been removed; use CancellationError")\n @_alwaysEmitIntoClient\n public static func CancellationError() -> _Concurrency.CancellationError {\n return _Concurrency.CancellationError()\n }\n\n @available(*, deprecated, renamed: "yield()")\n @_alwaysEmitIntoClient\n public static func suspend() async {\n await yield()\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension TaskPriority {\n @available(*, deprecated, message: "unspecified priority will be removed; use nil")\n @_alwaysEmitIntoClient\n public static var unspecified: TaskPriority {\n .init(rawValue: 0x00)\n }\n\n @available(*, deprecated, message: "userInteractive priority will be removed")\n @_alwaysEmitIntoClient\n public static var userInteractive: TaskPriority {\n .init(rawValue: 0x21)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\n@available(*, deprecated, renamed: "withTaskCancellationHandler(operation:onCancel:)")\npublic func withTaskCancellationHandler<T>(\n handler: @Sendable () -> Void,\n operation: () async throws -> T\n) async rethrows -> T {\n try await withTaskCancellationHandler(operation: operation, onCancel: handler)\n}\n\n// Note: hack to stage out @_unsafeInheritExecutor forms of various functions\n// in favor of #isolation. The _unsafeInheritExecutor_ prefix is meaningful\n// to the type checker.\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\n@_unsafeInheritExecutor\n@available(*, deprecated, renamed: "withTaskCancellationHandler(operation:onCancel:)")\npublic func _unsafeInheritExecutor_withTaskCancellationHandler<T>(\n handler: @Sendable () -> Void,\n operation: () async throws -> T\n) async rethrows -> T {\n try await withTaskCancellationHandler(operation: operation, onCancel: handler)\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Success == Never, Failure == Never {\n @available(*, deprecated, message: "`Task.withCancellationHandler` has been replaced by `withTaskCancellationHandler` and will be removed shortly.")\n @_alwaysEmitIntoClient\n public static func withCancellationHandler<T>(\n handler: @Sendable () -> Void,\n operation: () async throws -> T\n ) async rethrows -> T {\n try await withTaskCancellationHandler(operation: operation, onCancel: handler)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Failure == Error {\n #if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @discardableResult\n @_alwaysEmitIntoClient\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public static func runDetached(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> Success\n ) -> Task<Success, Failure> {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n #else\n @discardableResult\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "`Task.runDetached` was replaced by `Task.detached` and will be removed shortly.")\n public static func runDetached(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> Success\n ) -> Task<Success, Failure> {\n detached(priority: priority, operation: operation)\n }\n #endif\n}\n\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@discardableResult\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n@_alwaysEmitIntoClient\npublic func detach<T>(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> T\n) -> Task<T, Never> {\n fatalError("Unavailable in task-to-thread concurrency model")\n}\n#else\n@discardableResult\n@available(SwiftStdlib 5.1, *)\n@available(*, deprecated, message: "`detach` was replaced by `Task.detached` and will be removed shortly.")\n@_alwaysEmitIntoClient\npublic func detach<T>(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> T\n) -> Task<T, Never> {\n Task.detached(priority: priority, operation: operation)\n}\n#endif\n\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@discardableResult\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n@_alwaysEmitIntoClient\npublic func detach<T>(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> T\n) -> Task<T, Error> {\n fatalError("Unavailable in task-to-thread concurrency model")\n}\n#else\n@discardableResult\n@available(SwiftStdlib 5.1, *)\n@available(*, deprecated, message: "`detach` was replaced by `Task.detached` and will be removed shortly.")\n@_alwaysEmitIntoClient\npublic func detach<T>(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> T\n) -> Task<T, Error> {\n Task.detached(priority: priority, operation: operation)\n}\n#endif\n\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@discardableResult\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n@_alwaysEmitIntoClient\npublic func asyncDetached<T>(\n priority: TaskPriority? = nil,\n @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> T\n) -> Task<T, Never> {\n fatalError("Unavailable in task-to-thread concurrency model")\n}\n#else\n@discardableResult\n@available(SwiftStdlib 5.1, *)\n@available(*, deprecated, message: "`asyncDetached` was replaced by `Task.detached` and will be removed shortly.")\n@_alwaysEmitIntoClient\npublic func asyncDetached<T>(\n priority: TaskPriority? = nil,\n @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> T\n) -> Task<T, Never> {\n return Task.detached(priority: priority, operation: operation)\n}\n#endif\n\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@discardableResult\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n@_alwaysEmitIntoClient\npublic func asyncDetached<T>(\n priority: TaskPriority? = nil,\n @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> T\n) -> Task<T, Error> {\n fatalError("Unavailable in task-to-thread concurrency model")\n}\n#else\n@discardableResult\n@available(SwiftStdlib 5.1, *)\n@available(*, deprecated, message: "`asyncDetached` was replaced by `Task.detached` and will be removed shortly.")\n@_alwaysEmitIntoClient\npublic func asyncDetached<T>(\n priority: TaskPriority? = nil,\n @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> T\n) -> Task<T, Error> {\n return Task.detached(priority: priority, operation: operation)\n}\n#endif\n\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n@discardableResult\n@_alwaysEmitIntoClient\npublic func async<T>(\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> T\n) -> Task<T, Never> {\n fatalError("Unavailable in task-to-thread concurrency model")\n}\n#else\n@available(SwiftStdlib 5.1, *)\n@available(*, deprecated, message: "`async` was replaced by `Task.init` and will be removed shortly.")\n@discardableResult\n@_alwaysEmitIntoClient\npublic func async<T>(\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> T\n) -> Task<T, Never> {\n .init(priority: priority, operation: operation)\n}\n#endif\n\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n@discardableResult\n@_alwaysEmitIntoClient\npublic func async<T>(\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> T\n) -> Task<T, Error> {\n fatalError("Unavailable in task-to-thread concurrency model")\n}\n#else\n@available(SwiftStdlib 5.1, *)\n@available(*, deprecated, message: "`async` was replaced by `Task.init` and will be removed shortly.")\n@discardableResult\n@_alwaysEmitIntoClient\npublic func async<T>(\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> T\n) -> Task<T, Error> {\n .init(priority: priority, operation: operation)\n}\n#endif\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Success == Never, Failure == Never {\n @available(*, deprecated, message: "`Task.Group` was replaced by `ThrowingTaskGroup` and `TaskGroup` and will be removed shortly.")\n public typealias Group<TaskResult: Sendable> = ThrowingTaskGroup<TaskResult, Error>\n\n @available(*, deprecated, message: "`Task.withGroup` was replaced by `withThrowingTaskGroup` and `withTaskGroup` and will be removed shortly.")\n @_alwaysEmitIntoClient\n public static func withGroup<TaskResult: Sendable, BodyResult>(\n resultType: TaskResult.Type,\n returning returnType: BodyResult.Type = BodyResult.self,\n body: (inout Task.Group<TaskResult>) async throws -> BodyResult\n ) async rethrows -> BodyResult {\n try await withThrowingTaskGroup(of: resultType) { group in\n try await body(&group)\n }\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task {\n @available(*, deprecated, message: "get() has been replaced by .value")\n @_alwaysEmitIntoClient\n public func get() async throws -> Success {\n return try await value\n }\n\n @available(*, deprecated, message: "getResult() has been replaced by .result")\n @_alwaysEmitIntoClient\n public func getResult() async -> Result<Success, Failure> {\n return await result\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Failure == Never {\n @available(*, deprecated, message: "get() has been replaced by .value")\n @_alwaysEmitIntoClient\n public func get() async -> Success {\n return await value\n }\n}\n\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 5.1, *)\nextension TaskGroup {\n @available(*, deprecated, renamed: "addTask(priority:operation:)")\n @_alwaysEmitIntoClient\n public mutating func add(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) async -> Bool {\n return self.addTaskUnlessCancelled(priority: priority) {\n await operation()\n }\n }\n\n @available(*, deprecated, renamed: "addTask(priority:operation:)")\n @_alwaysEmitIntoClient\n public mutating func spawn(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) {\n addTask(priority: priority, operation: operation)\n }\n\n @available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)")\n @_alwaysEmitIntoClient\n public mutating func spawnUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) -> Bool {\n addTaskUnlessCancelled(priority: priority, operation: operation)\n }\n\n @available(*, deprecated, renamed: "addTask(priority:operation:)")\n @_alwaysEmitIntoClient\n public mutating func async(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) {\n addTask(priority: priority, operation: operation)\n }\n\n @available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)")\n @_alwaysEmitIntoClient\n public mutating func asyncUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) -> Bool {\n addTaskUnlessCancelled(priority: priority, operation: operation)\n }\n}\n#else\n@available(SwiftStdlib 5.1, *)\nextension TaskGroup {\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model", renamed: "addTaskUnlessCancelled(operation:)")\n public mutating func add(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) async -> Bool {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n\n @available(*, deprecated, renamed: "addTaskUnlessCancelled(operation:)")\n @_alwaysEmitIntoClient\n public mutating func add(\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) async -> Bool {\n return self.addTaskUnlessCancelled {\n await operation()\n }\n }\n\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model", renamed: "addTask(operation:)")\n public mutating func spawn(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n\n @available(*, deprecated, renamed: "addTask(operation:)")\n @_alwaysEmitIntoClient\n public mutating func spawn(\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) {\n addTask(operation: operation)\n }\n\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model", renamed: "addTaskUnlessCancelled(operation:)")\n public mutating func spawnUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) -> Bool {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n\n @available(*, deprecated, renamed: "addTaskUnlessCancelled(operation:)")\n @_alwaysEmitIntoClient\n public mutating func spawnUnlessCancelled(\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) -> Bool {\n addTaskUnlessCancelled(operation: operation)\n }\n\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model", renamed: "addTask(operation:)")\n public mutating func async(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n\n @available(*, deprecated, renamed: "addTask(operation:)")\n @_alwaysEmitIntoClient\n public mutating func async(\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) {\n addTask(operation: operation)\n }\n\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model", renamed: "addTaskUnlessCancelled(operation:)")\n public mutating func asyncUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) -> Bool {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n\n @available(*, deprecated, renamed: "addTaskUnlessCancelled(operation:)")\n @_alwaysEmitIntoClient\n public mutating func asyncUnlessCancelled(\n operation: __owned @Sendable @escaping () async -> ChildTaskResult\n ) -> Bool {\n addTaskUnlessCancelled(operation: operation)\n }\n}\n#endif\n\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 5.1, *)\nextension ThrowingTaskGroup {\n @available(*, deprecated, renamed: "addTask(priority:operation:)")\n @_alwaysEmitIntoClient\n public mutating func add(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) async -> Bool {\n return self.addTaskUnlessCancelled(priority: priority) {\n try await operation()\n }\n }\n\n @available(*, deprecated, renamed: "addTask(priority:operation:)")\n @_alwaysEmitIntoClient\n public mutating func spawn(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) {\n addTask(priority: priority, operation: operation)\n }\n\n @available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)")\n @_alwaysEmitIntoClient\n public mutating func spawnUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) -> Bool {\n addTaskUnlessCancelled(priority: priority, operation: operation)\n }\n\n @available(*, deprecated, renamed: "addTask(priority:operation:)")\n @_alwaysEmitIntoClient\n public mutating func async(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) {\n addTask(priority: priority, operation: operation)\n }\n\n @available(*, deprecated, renamed: "addTaskUnlessCancelled(priority:operation:)")\n @_alwaysEmitIntoClient\n public mutating func asyncUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) -> Bool {\n addTaskUnlessCancelled(priority: priority, operation: operation)\n }\n}\n#else\n@available(SwiftStdlib 5.1, *)\nextension ThrowingTaskGroup {\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model", renamed: "addTaskUnlessCancelled(operation:)")\n public mutating func add(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) async -> Bool {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n\n @available(*, deprecated, renamed: "addTaskUnlessCancelled(operation:)")\n @_alwaysEmitIntoClient\n public mutating func add(\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) async -> Bool {\n return self.addTaskUnlessCancelled {\n try await operation()\n }\n }\n\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model", renamed: "addTask(operation:)")\n public mutating func spawn(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n\n @available(*, deprecated, renamed: "addTask(operation:)")\n @_alwaysEmitIntoClient\n public mutating func spawn(\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) {\n addTask(operation: operation)\n }\n\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model", renamed: "addTaskUnlessCancelled(operation:)")\n public mutating func spawnUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) -> Bool {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n\n @available(*, deprecated, renamed: "addTaskUnlessCancelled(operation:)")\n @_alwaysEmitIntoClient\n public mutating func spawnUnlessCancelled(\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) -> Bool {\n addTaskUnlessCancelled(operation: operation)\n }\n\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model", renamed: "addTask(operation:)")\n public mutating func async(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n\n @available(*, deprecated, renamed: "addTask(operation:)")\n @_alwaysEmitIntoClient\n public mutating func async(\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) {\n addTask(operation: operation)\n }\n\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model", renamed: "addTaskUnlessCancelled(operation:)")\n public mutating func asyncUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) -> Bool {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n\n @available(*, deprecated, renamed: "addTaskUnlessCancelled(operation:)")\n @_alwaysEmitIntoClient\n public mutating func asyncUnlessCancelled(\n operation: __owned @Sendable @escaping () async throws -> ChildTaskResult\n ) -> Bool {\n addTaskUnlessCancelled(operation: operation)\n }\n}\n#endif\n\n@available(SwiftStdlib 5.1, *)\n@available(*, deprecated, message: "please use UnsafeContinuation<..., Error>")\npublic typealias UnsafeThrowingContinuation<T> = UnsafeContinuation<T, Error>\n\n@available(SwiftStdlib 5.1, *)\n@available(*, deprecated, renamed: "UnownedJob")\npublic typealias PartialAsyncTask = UnownedJob\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_SourceCompatibilityShims.swift | cpp_apple_swift_stdlib_public_Concurrency_SourceCompatibilityShims.swift | Swift | 21,172 | 0.95 | 0.032702 | 0.083176 | vue-tools | 179 | 2024-02-19T09:21:52.667386 | MIT | false | 2082a080bfa3786ec0260c3745c97848 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Swift\n\n/// A clock that measures time that always increments but stops incrementing\n/// while the system is asleep.\n///\n/// `SuspendingClock` can be considered as a system awake time clock. The frame\n/// of reference of the `Instant` may be bound machine boot or some other\n/// locally defined reference point. This means that the instants are\n/// only comparable on the same machine in the same booted session.\n///\n/// This clock is suitable for high resolution measurements of execution.\n@available(SwiftStdlib 5.7, *)\n@_unavailableInEmbedded\npublic struct SuspendingClock: Sendable {\n public struct Instant: Sendable {\n internal var _value: Swift.Duration\n\n internal init(_value: Swift.Duration) {\n self._value = _value\n }\n }\n\n public init() { }\n}\n\n#if !$Embedded\n@available(SwiftStdlib 5.7, *)\nextension SuspendingClock.Instant: Codable {\n}\n#endif\n\n@available(SwiftStdlib 5.7, *)\n@_unavailableInEmbedded\nextension Clock where Self == SuspendingClock {\n /// A clock that measures time that always increments but stops incrementing\n /// while the system is asleep.\n ///\n /// try await Task.sleep(until: .now + .seconds(3), clock: .suspending)\n ///\n @available(SwiftStdlib 5.7, *)\n public static var suspending: SuspendingClock { return SuspendingClock() }\n}\n\n@available(SwiftStdlib 5.7, *)\n@_unavailableInEmbedded\nextension SuspendingClock: Clock {\n /// The current instant accounting for machine suspension.\n @available(SwiftStdlib 5.7, *)\n public var now: SuspendingClock.Instant {\n SuspendingClock.now\n }\n\n /// The current instant accounting for machine suspension.\n @available(SwiftStdlib 5.7, *)\n public static var now: SuspendingClock.Instant {\n var seconds = Int64(0)\n var nanoseconds = Int64(0)\n unsafe _getTime(\n seconds: &seconds,\n nanoseconds: &nanoseconds,\n clock: _ClockID.suspending.rawValue)\n return Instant(\n _value: Duration(_seconds: seconds, nanoseconds: nanoseconds)\n )\n }\n\n /// The minimum non-zero resolution between any two calls to `now`.\n @available(SwiftStdlib 5.7, *)\n public var minimumResolution: Swift.Duration {\n var seconds = Int64(0)\n var nanoseconds = Int64(0)\n unsafe _getClockRes(\n seconds: &seconds,\n nanoseconds: &nanoseconds,\n clock: _ClockID.suspending.rawValue)\n return Duration(_seconds: seconds, nanoseconds: nanoseconds)\n }\n\n /// The suspending clock is monotonic\n @available(SwiftStdlib 6.2, *)\n public var traits: ClockTraits {\n return [.monotonic]\n }\n\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n /// Suspend task execution until a given deadline within a tolerance.\n /// If no tolerance is specified then the system may adjust the deadline\n /// to coalesce CPU wake-ups to more efficiently process the wake-ups in\n /// a more power efficient manner.\n ///\n /// If the task is canceled before the time ends, this function throws\n /// `CancellationError`.\n ///\n /// This function doesn't block the underlying thread.\n @available(SwiftStdlib 5.7, *)\n public func sleep(\n until deadline: Instant, tolerance: Swift.Duration? = nil\n ) async throws {\n if #available(SwiftStdlib 6.2, *) {\n try await Task._sleep(until: deadline,\n tolerance: tolerance,\n clock: self)\n } else {\n // Should never see this\n Builtin.unreachable()\n }\n }\n#else\n @available(SwiftStdlib 5.7, *)\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public func sleep(\n until deadline: Instant, tolerance: Swift.Duration? = nil\n ) async throws {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n#endif\n}\n\n@available(SwiftStdlib 5.7, *)\n@_unavailableInEmbedded\nextension SuspendingClock.Instant: InstantProtocol {\n @available(SwiftStdlib 5.7, *)\n public static var now: SuspendingClock.Instant { SuspendingClock().now }\n\n @available(SwiftStdlib 5.7, *)\n public func advanced(by duration: Swift.Duration) -> SuspendingClock.Instant {\n SuspendingClock.Instant(_value: _value + duration)\n }\n\n @available(SwiftStdlib 5.7, *)\n public func duration(to other: SuspendingClock.Instant) -> Swift.Duration {\n other._value - _value\n }\n\n @available(SwiftStdlib 5.7, *)\n public func hash(into hasher: inout Hasher) {\n hasher.combine(_value)\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func == (\n _ lhs: SuspendingClock.Instant, _ rhs: SuspendingClock.Instant\n ) -> Bool {\n return lhs._value == rhs._value\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func < (\n _ lhs: SuspendingClock.Instant, _ rhs: SuspendingClock.Instant\n ) -> Bool {\n return lhs._value < rhs._value\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func + (\n _ lhs: SuspendingClock.Instant, _ rhs: Swift.Duration\n ) -> SuspendingClock.Instant {\n lhs.advanced(by: rhs)\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func += (\n _ lhs: inout SuspendingClock.Instant, _ rhs: Swift.Duration\n ) {\n lhs = lhs.advanced(by: rhs)\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func - (\n _ lhs: SuspendingClock.Instant, _ rhs: Swift.Duration\n ) -> SuspendingClock.Instant {\n lhs.advanced(by: .zero - rhs)\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func -= (\n _ lhs: inout SuspendingClock.Instant, _ rhs: Swift.Duration\n ) {\n lhs = lhs.advanced(by: .zero - rhs)\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func - (\n _ lhs: SuspendingClock.Instant, _ rhs: SuspendingClock.Instant\n ) -> Swift.Duration {\n rhs.duration(to: lhs)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_SuspendingClock.swift | cpp_apple_swift_stdlib_public_Concurrency_SuspendingClock.swift | Swift | 6,120 | 0.95 | 0.070352 | 0.247191 | python-kit | 720 | 2025-04-17T05:18:20.204145 | Apache-2.0 | false | 52b7bd4ab1bd023baecb49023678550c |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n@_implementationOnly import SwiftConcurrencyInternalShims\n\n// ==== Task Priority Escalation -----------------------------------------------\n\n@available(SwiftStdlib 6.2, *)\nextension Task {\n /// Manually escalate the task `priority` of this task to the `newPriority`.\n ///\n /// - Warning: This API should rarely be used, and instead you can rely on\n /// structured concurrency and implicit priority escalation which happens\n /// when a higher priority task awaits on a result of a lower priority task.\n ///\n /// I.e. using `await` on the target task usually is the correct way to\n /// escalate the target task to the current priority of the calling task,\n /// especially because in such setup if the waiting task gets escalated,\n /// the waited on task would be escalated automatically as well.\n ///\n /// The concurrency runtime is free to interpret and handle escalation\n /// depending on platform characteristics.\n ///\n /// Priority escalation is propagated to child tasks of the waited-on task,\n /// and will trigger any priority escalation handlers, if any were registered.\n ///\n /// Escalation can only *increase* the priority of a task, and\n /// de-escalating priority is not supported.\n ///\n /// This method can be called from any task or thread.\n ///\n /// - Parameters:\n /// - task: the task which to escalate the priority of\n /// - newPriority: the new priority the task should continue executing on\n @available(SwiftStdlib 6.2, *)\n public func escalatePriority(to newPriority: TaskPriority) {\n _taskEscalate(self._task, newPriority: newPriority.rawValue)\n }\n}\n\n@available(SwiftStdlib 6.2, *)\nextension UnsafeCurrentTask {\n /// Escalate the task `priority` of the passed in task to the `newPriority`.\n ///\n /// - Warning: This API should rarely be used, and instead you can rely on\n /// structured concurrency and implicit priority escalation which happens\n /// when a higher priority task awaits on a result of a lower priority task.\n ///\n /// I.e. using `await` on the target task usually is the correct way to\n /// escalate the target task to the current priority of the calling task,\n /// especially because in such setup if the waiting task gets escalated,\n /// the waited on task would be escalated automatically as well.\n ///\n /// The concurrency runtime is free to interpret and handle escalation\n /// depending on platform characteristics.\n ///\n /// Priority escalation is propagated to child tasks of the waited-on task,\n /// and will trigger any priority escalation handlers, if any were registered.\n ///\n /// Escalation can only *increase* the priority of a task, and\n /// de-escalating priority is not supported.\n ///\n /// This method can be called from any task or thread.\n ///\n /// - Parameters:\n /// - task: the task which to escalate the priority of\n /// - newPriority: the new priority the task should continue executing on\n @available(SwiftStdlib 6.2, *)\n public func escalatePriority(to newPriority: TaskPriority) {\n unsafe _taskEscalate(self._task, newPriority: newPriority.rawValue)\n }\n}\n\n// ==== Task Priority Escalation Handlers --------------------------------------\n\n/// Runs the passed `operation` while registering a task priority escalation handler.\n/// The handler will be triggered concurrently to the current task if the current\n/// is subject to priority escalation.\n///\n/// The handler may perform additional actions upon priority escalation,\n/// but cannot influence how the escalation influences the task, i.e. the task's\n/// priority will be escalated regardless of actions performed in the handler.\n///\n/// The handler will only trigger if a priority escalation occurs while the\n/// operation is in progress.\n///\n/// If multiple task escalation handlers are nester they will all be triggered.\n///\n/// Task escalation propagates through structured concurrency child-tasks.\n///\n/// - Parameters:\n/// - operation: the operation during which to listen for priority escalation\n/// - handler: handler to invoke, concurrently to `operation`,\n/// when priority escalation happens\n/// - Returns: the value returned by `operation`\n/// - Throws: when the `operation` throws an error\n@available(SwiftStdlib 6.2, *)\npublic func withTaskPriorityEscalationHandler<T, E>(\n operation: () async throws(E) -> T,\n onPriorityEscalated handler: @Sendable (TaskPriority, TaskPriority) -> Void,\n isolation: isolated (any Actor)? = #isolation\n) async throws(E) -> T {\n return try await __withTaskPriorityEscalationHandler0(\n operation: operation,\n onPriorityEscalated: {\n handler(TaskPriority(rawValue: $0), TaskPriority(rawValue: $1))\n })\n}\n\n// Method necessary in order to avoid the handler0 to be destroyed too eagerly.\n@available(SwiftStdlib 6.2, *)\n@_alwaysEmitIntoClient\nfunc __withTaskPriorityEscalationHandler0<T, E>(\n operation: () async throws(E) -> T,\n onPriorityEscalated handler0: @Sendable (UInt8, UInt8) -> Void,\n isolation: isolated (any Actor)? = #isolation\n) async throws(E) -> T {\n let record = unsafe _taskAddPriorityEscalationHandler(handler: handler0)\n defer { unsafe _taskRemovePriorityEscalationHandler(record: record) }\n\n return try await operation()\n} | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_Task+PriorityEscalation.swift | cpp_apple_swift_stdlib_public_Concurrency_Task+PriorityEscalation.swift | Swift | 5,759 | 0.95 | 0.099237 | 0.685484 | react-lib | 951 | 2023-09-06T11:43:03.800039 | MIT | false | c3a03c33364cad489420374b7dc83597 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n// None of TaskExecutor APIs are available in task-to-thread concurrency model.\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n\n/// Configure the current task hierarchy's task executor preference to the passed ``TaskExecutor``,\n/// and execute the passed in closure by immediately hopping to that executor.\n///\n/// ### Task executor preference semantics\n/// Task executors influence _where_ nonisolated asynchronous functions, and default actor methods execute.\n/// The preferred executor will be used whenever possible, rather than hopping to the global concurrent pool.\n///\n/// For an in depth discussion of this topic, see ``TaskExecutor``.\n///\n/// ### Disabling task executor preference\n/// Passing `nil` as executor means disabling any preference preference (if it was set) and the task hierarchy\n/// will execute without any executor preference until a different preference is set.\n///\n/// ### Asynchronous function execution semantics in presence of task executor preferences\n/// The following diagram illustrates on which executor an `async` function will\n/// execute, in presence (or lack thereof) a task executor preference.\n///\n/// ```\n/// [ func / closure ] - /* where should it execute? */\n/// |\n/// +--------------+ +===========================+\n/// +-------- | is isolated? | - yes -> | actor has unownedExecutor |\n/// | +--------------+ +===========================+\n/// | | |\n/// | yes no\n/// | | |\n/// | v v\n/// | +=======================+ /* task executor preference? */\n/// | | on specified executor | | |\n/// | +=======================+ yes no\n/// | | |\n/// | | v\n/// | | +==========================+\n/// | | | default (actor) executor |\n/// | v +==========================+\n/// v +==============================+\n/// /* task executor preference? */ ---- yes ----> | on Task's preferred executor |\n/// | +==============================+\n/// no\n/// |\n/// v\n/// +===============================+\n/// | on global concurrent executor |\n/// +===============================+\n/// ```\n///\n/// In short, without a task executor preference, `nonisolated async` functions\n/// will execute on the global concurrent executor. If a task executor preference\n/// is present, such `nonisolated async` functions will execute on the preferred\n/// task executor.\n///\n/// Isolated functions semantically execute on the actor they are isolated to,\n/// however if such actor does not declare a custom executor (it is a "default\n/// actor") in presence of a task executor preference, tasks executing on this\n/// actor will use the preferred executor as source of threads to run the task,\n/// while isolated on the actor.\n///\n/// ### Example\n///\n/// Task {\n/// // case 0) "no task executor preference"\n///\n/// // default task executor\n/// // ...\n/// await SomeDefaultActor().hello() // default executor\n/// await ActorWithCustomExecutor().hello() // 'hello' executes on actor's custom executor\n///\n/// // child tasks execute on default executor:\n/// async let x = ...\n/// await withTaskGroup(of: Int.self) { group in g.addTask { 7 } }\n///\n/// await withTaskExecutorPreference(specific) {\n/// // case 1) 'specific' task executor preference\n///\n/// // 'specific' task executor\n/// // ...\n/// await SomeDefaultActor().hello() // 'hello' executes on 'specific' executor\n/// await ActorWithCustomExecutor().hello() // 'hello' executes on actor's custom executor (same as case 0)\n///\n/// // child tasks execute on 'specific' task executor:\n/// async let x = ...\n/// await withTaskGroup(of: Int.self) { group in\n/// group.addTask { 7 } // child task executes on 'specific' executor\n/// group.addTask(executorPreference: globalConcurrentExecutor) { 13 } // child task executes on global concurrent executor\n/// }\n///\n/// // disable the task executor preference:\n/// await withTaskExecutorPreference(globalConcurrentExecutor) {\n/// // equivalent to case 0) preference is globalConcurrentExecutor\n///\n/// // default task executor\n/// // ...\n/// await SomeDefaultActor().hello() // default executor (same as case 0)\n/// await ActorWithCustomExecutor().hello() // 'hello' executes on actor's custom executor (same as case 0)\n///\n/// // child tasks execute on default executor (same as case 0):\n/// async let x = ...\n/// await withTaskGroup(of: Int.self) { group in group.addTask { 7 } }\n/// }\n/// }\n/// }\n///\n/// - Parameters:\n/// - taskExecutor: the executor to use as preferred task executor for this\n/// operation, and any child tasks created inside the `operation` closure.\n/// If `nil` it is interpreted as "no preference" and calling this method\n/// will have no impact on execution semantics of the `operation`\n/// - operation: the operation to execute on the passed executor\n/// - Returns: the value returned from the `operation` closure\n/// - Throws: if the operation closure throws\n/// - SeeAlso: ``TaskExecutor``\n@_unavailableInEmbedded\n@available(SwiftStdlib 6.0, *)\npublic func withTaskExecutorPreference<T, Failure>(\n _ taskExecutor: (any TaskExecutor)?,\n isolation: isolated (any Actor)? = #isolation,\n operation: () async throws(Failure) -> T\n) async throws(Failure) -> T {\n guard let taskExecutor else {\n // User explicitly passed a "nil" preference, so we invoke the operation\n // as is, which will hop to it's expected executor without any change in\n // executor preference semantics.\n //\n // We allow this in order to easily drive task executor preference from\n // configuration where the preference may be an optional; so users don't\n // have to write two code paths for "if there is a preference and if there\n // isn't".\n return try await operation()\n }\n\n let taskExecutorBuiltin: Builtin.Executor =\n unsafe taskExecutor.asUnownedTaskExecutor().executor\n\n let record = unsafe _pushTaskExecutorPreference(taskExecutorBuiltin)\n defer {\n unsafe _popTaskExecutorPreference(record: record)\n }\n\n // No need to manually hop to the target executor, because as we execute\n // the operation, its enqueue will respect the attached executor preference.\n return try await operation()\n}\n\n// Note: hack to stage out @_unsafeInheritExecutor forms of various functions\n// in favor of #isolation. The _unsafeInheritExecutor_ prefix is meaningful\n// to the type checker.\n//\n// This function also doubles as an ABI-compatibility shim predating the\n// introduction of #isolation.\n@_unavailableInEmbedded\n@available(SwiftStdlib 6.0, *)\n@_unsafeInheritExecutor // for ABI compatibility\n@_silgen_name("$ss26withTaskExecutorPreference_9operationxSch_pSg_xyYaYbKXEtYaKs8SendableRzlF")\npublic func _unsafeInheritExecutor_withTaskExecutorPreference<T: Sendable>(\n _ taskExecutor: (any TaskExecutor)?,\n operation: @Sendable () async throws -> T\n) async rethrows -> T {\n guard let taskExecutor else {\n return try await operation()\n }\n\n let taskExecutorBuiltin: Builtin.Executor =\n unsafe taskExecutor.asUnownedTaskExecutor().executor\n\n let record = unsafe _pushTaskExecutorPreference(taskExecutorBuiltin)\n defer {\n unsafe _popTaskExecutorPreference(record: record)\n }\n\n return try await operation()\n}\n\n/// Task with specified executor -----------------------------------------------\n\n@available(SwiftStdlib 6.0, *)\n@_unavailableInEmbedded\nextension Task where Failure == Never {\n /// Runs the given nonthrowing operation asynchronously\n /// as part of a new top-level task on behalf of the current actor.\n ///\n /// This overload allows specifying a preferred ``TaskExecutor`` on which\n /// the `operation`, as well as all child tasks created from this task will be\n /// executing whenever possible. Refer to ``TaskExecutor`` for a detailed discussion\n /// of the effect of task executors on execution semantics of asynchronous code.\n ///\n /// Use this function when creating asynchronous work\n /// that operates on behalf of the synchronous function that calls it.\n /// Like `Task.detached(priority:operation:)`,\n /// this function creates a separate, top-level task.\n /// Unlike `Task.detached(priority:operation:)`,\n /// the task created by `Task.init(priority:operation:)`\n /// inherits the priority and actor context of the caller,\n /// so the operation is treated more like an asynchronous extension\n /// to the synchronous operation.\n ///\n /// You need to keep a reference to the task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - taskExecutor: the preferred task executor for this task,\n /// and any child tasks created by it. Explicitly passing `nil` is\n /// interpreted as "no preference".\n /// - priority: The priority of the task.\n /// Pass `nil` to use the priority from `Task.currentPriority`.\n /// - operation: The operation to perform.\n /// - SeeAlso: ``withTaskExecutorPreference(_:operation:)``\n @discardableResult\n @_alwaysEmitIntoClient\n public init(\n executorPreference taskExecutor: consuming (any TaskExecutor)?,\n priority: TaskPriority? = nil,\n operation: sending @escaping () async -> Success\n ) {\n guard let taskExecutor else {\n self = Self.init(priority: priority, operation: operation)\n return\n }\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: true,\n inheritContext: true, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n#if $BuiltinCreateAsyncTaskOwnedTaskExecutor\n let (task, _) = Builtin.createTask(\n flags: flags,\n initialTaskExecutorConsuming: taskExecutor,\n operation: operation)\n#else\n let executorBuiltin: Builtin.Executor =\n taskExecutor.asUnownedTaskExecutor().executor\n let (task, _) = Builtin.createAsyncTaskWithExecutor(\n flags, executorBuiltin, operation)\n#endif\n self._task = task\n }\n}\n\n@available(SwiftStdlib 6.0, *)\n@_unavailableInEmbedded\nextension Task where Failure == Error {\n /// Runs the given throwing operation asynchronously\n /// as part of a new top-level task on behalf of the current actor.\n ///\n /// Use this function when creating asynchronous work\n /// that operates on behalf of the synchronous function that calls it.\n /// Like `Task.detached(priority:operation:)`,\n /// this function creates a separate, top-level task.\n /// Unlike `detach(priority:operation:)`,\n /// the task created by `Task.init(priority:operation:)`\n /// inherits the priority and actor context of the caller,\n /// so the operation is treated more like an asynchronous extension\n /// to the synchronous operation.\n ///\n /// You need to keep a reference to the task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - taskExecutor: the preferred task executor for this task,\n /// and any child tasks created by it. Explicitly passing `nil` is\n /// interpreted as "no preference".\n /// - priority: The priority of the task.\n /// Pass `nil` to use the priority from `Task.currentPriority`.\n /// - operation: The operation to perform.\n /// - SeeAlso: ``withTaskExecutorPreference(_:operation:)``\n @discardableResult\n @_alwaysEmitIntoClient\n public init(\n executorPreference taskExecutor: consuming (any TaskExecutor)?,\n priority: TaskPriority? = nil,\n operation: sending @escaping () async throws -> Success\n ) {\n guard let taskExecutor else {\n self = Self.init(priority: priority, operation: operation)\n return\n }\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: true,\n inheritContext: true, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n#if $BuiltinCreateAsyncTaskOwnedTaskExecutor\n let (task, _) = Builtin.createTask(\n flags: flags,\n initialTaskExecutorConsuming: taskExecutor,\n operation: operation)\n#else\n let executorBuiltin: Builtin.Executor =\n taskExecutor.asUnownedTaskExecutor().executor\n let (task, _) = Builtin.createAsyncTaskWithExecutor(\n flags, executorBuiltin, operation)\n#endif\n self._task = task\n }\n}\n\n// ==== Detached tasks ---------------------------------------------------------\n\n@available(SwiftStdlib 6.0, *)\n@_unavailableInEmbedded\nextension Task where Failure == Never {\n /// Runs the given nonthrowing operation asynchronously\n /// as part of a new top-level task.\n ///\n /// Don't use a detached task if it's possible\n /// to model the operation using structured concurrency features like child tasks.\n /// Child tasks inherit the parent task's priority and task-local storage,\n /// and canceling a parent task automatically cancels all of its child tasks.\n /// You need to handle these considerations manually with a detached task.\n ///\n /// You need to keep a reference to the detached task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - taskExecutor: the preferred task executor for this task,\n /// and any child tasks created by it. Explicitly passing `nil` is\n /// interpreted as "no preference".\n /// - priority: The priority of the task.\n /// Pass `nil` to use the priority from `Task.currentPriority`.\n /// - operation: The operation to perform.\n /// - Returns: A reference to the newly created task.\n /// - SeeAlso: ``withTaskExecutorPreference(_:operation:)``\n @discardableResult\n @_alwaysEmitIntoClient\n public static func detached(\n executorPreference taskExecutor: (any TaskExecutor)?,\n priority: TaskPriority? = nil,\n operation: sending @escaping () async -> Success\n ) -> Task<Success, Failure> {\n guard let taskExecutor else {\n return Self.detached(priority: priority, operation: operation)\n }\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: false,\n inheritContext: false, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n#if $BuiltinCreateAsyncTaskOwnedTaskExecutor\n let (task, _) = Builtin.createTask(\n flags: flags,\n initialTaskExecutorConsuming: taskExecutor,\n operation: operation)\n#else\n let executorBuiltin: Builtin.Executor =\n taskExecutor.asUnownedTaskExecutor().executor\n let (task, _) = Builtin.createAsyncTaskWithExecutor(\n flags, executorBuiltin, operation)\n#endif\n return Task(task)\n }\n}\n\n@available(SwiftStdlib 6.0, *)\n@_unavailableInEmbedded\nextension Task where Failure == Error {\n /// Runs the given throwing operation asynchronously\n /// as part of a new top-level task.\n ///\n /// If the operation throws an error, this method propagates that error.\n ///\n /// Don't use a detached task if it's possible\n /// to model the operation using structured concurrency features like child tasks.\n /// Child tasks inherit the parent task's priority and task-local storage,\n /// and canceling a parent task automatically cancels all of its child tasks.\n /// You need to handle these considerations manually with a detached task.\n ///\n /// You need to keep a reference to the detached task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - taskExecutor: the preferred task executor for this task,\n /// and any child tasks created by it. Explicitly passing `nil` is\n /// interpreted as "no preference".\n /// - priority: The priority of the task.\n /// Pass `nil` to use the priority from `Task.currentPriority`.\n /// - operation: The operation to perform.\n /// - Returns: A reference to the newly created task.\n /// - SeeAlso: ``withTaskExecutorPreference(_:operation:)``\n @discardableResult\n @_alwaysEmitIntoClient\n public static func detached(\n executorPreference taskExecutor: (any TaskExecutor)?,\n priority: TaskPriority? = nil,\n operation: sending @escaping () async throws -> Success\n ) -> Task<Success, Failure> {\n guard let taskExecutor else {\n return Self.detached(priority: priority, operation: operation)\n }\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: false,\n inheritContext: false, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n#if $BuiltinCreateAsyncTaskOwnedTaskExecutor\n let (task, _) = Builtin.createTask(\n flags: flags,\n initialTaskExecutorConsuming: taskExecutor,\n operation: operation)\n#else\n let executorBuiltin: Builtin.Executor =\n taskExecutor.asUnownedTaskExecutor().executor\n let (task, _) = Builtin.createAsyncTaskWithExecutor(\n flags, executorBuiltin, operation)\n#endif\n return Task(task)\n }\n}\n\n// ==== Unsafe Current Task ----------------------------------------------------\n\n@available(SwiftStdlib 6.0, *)\n@_unavailableInEmbedded\nextension UnsafeCurrentTask {\n\n /// The current ``TaskExecutor`` preference, if this task has one configured.\n ///\n /// The executor may be used to compare for equality with an expected executor preference.\n ///\n /// The lifetime of an executor is not guaranteed by an ``UnownedTaskExecutor``,\n /// so accessing it must be handled with great case -- and the program must use other\n /// means to guarantee the executor remains alive while it is in use.\n @available(SwiftStdlib 6.0, *)\n public var unownedTaskExecutor: UnownedTaskExecutor? {\n let ref = _getPreferredUnownedTaskExecutor()\n return unsafe UnownedTaskExecutor(ref)\n }\n}\n\n// ==== Runtime ---------------------------------------------------------------\n\n@available(SwiftStdlib 6.0, *)\n@_silgen_name("swift_task_getPreferredTaskExecutor")\ninternal func _getPreferredUnownedTaskExecutor() -> Builtin.Executor\n\ntypealias TaskExecutorPreferenceStatusRecord = UnsafeRawPointer\n\n@available(SwiftStdlib 6.0, *)\n@_silgen_name("swift_task_pushTaskExecutorPreference")\ninternal func _pushTaskExecutorPreference(_ executor: Builtin.Executor)\n -> TaskExecutorPreferenceStatusRecord\n\n@available(SwiftStdlib 6.0, *)\n@_silgen_name("swift_task_popTaskExecutorPreference")\ninternal func _popTaskExecutorPreference(\n record: TaskExecutorPreferenceStatusRecord\n)\n\n/// Get the "undefined" task executor reference.\n///\n/// It can be used to compare against, and is semantically equivalent to\n/// "no preference".\n@available(SwiftStdlib 6.0, *)\n@usableFromInline\ninternal func _getUndefinedTaskExecutor() -> Builtin.Executor {\n // Similar to the `_getGenericSerialExecutor` this method relies\n // on the runtime representation of the "undefined" executor\n // to be specifically `{0, 0}` (a null-pointer to an executor and witness\n // table).\n //\n // Rather than call into the runtime to return the\n // `TaskExecutorRef::undefined()`` we this information to bitcast\n // and return it directly.\n unsafe unsafeBitCast((UInt(0), UInt(0)), to: Builtin.Executor.self)\n}\n\n#endif // !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_Task+TaskExecutor.swift | cpp_apple_swift_stdlib_public_Concurrency_Task+TaskExecutor.swift | Swift | 21,540 | 0.95 | 0.101594 | 0.612288 | react-lib | 640 | 2025-02-07T18:22:13.087650 | GPL-3.0 | false | 0b1b7ce8528a7246dfeec34b015c3596 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n@_implementationOnly import SwiftConcurrencyInternalShims\n\n// ==== Task -------------------------------------------------------------------\n\n/// A unit of asynchronous work.\n///\n/// When you create an instance of `Task`,\n/// you provide a closure that contains the work for that task to perform.\n/// Tasks can start running immediately after creation;\n/// you don't explicitly start or schedule them.\n/// After creating a task, you use the instance to interact with it ---\n/// for example, to wait for it to complete or to cancel it.\n/// It's not a programming error to discard a reference to a task\n/// without waiting for that task to finish or canceling it.\n/// A task runs regardless of whether you keep a reference to it.\n/// However, if you discard the reference to a task,\n/// you give up the ability\n/// to wait for that task's result or cancel the task.\n///\n/// To support operations on the current task,\n/// which can be either a detached task or child task,\n/// `Task` also exposes class methods like `yield()`.\n/// Because these methods are asynchronous,\n/// they're always invoked as part of an existing task.\n///\n/// Only code that's running as part of the task can interact with that task.\n/// To interact with the current task,\n/// you call one of the static methods on `Task`.\n///\n/// A task's execution can be seen as a series of periods where the task ran.\n/// Each such period ends at a suspension point or the\n/// completion of the task.\n/// These periods of execution are represented by instances of `PartialAsyncTask`.\n/// Unless you're implementing a custom executor,\n/// you don't directly interact with partial tasks.\n///\n/// For information about the language-level concurrency model that `Task` is part of,\n/// see [Concurrency][concurrency] in [The Swift Programming Language][tspl].\n///\n/// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html\n/// [tspl]: https://docs.swift.org/swift-book/\n///\n/// Task Cancellation\n/// =================\n///\n/// Tasks include a shared mechanism for indicating cancellation,\n/// but not a shared implementation for how to handle cancellation.\n/// Depending on the work you're doing in the task,\n/// the correct way to stop that work varies.\n/// Likewise,\n/// it's the responsibility of the code running as part of the task\n/// to check for cancellation whenever stopping is appropriate.\n/// In a long-task that includes multiple pieces,\n/// you might need to check for cancellation at several points,\n/// and handle cancellation differently at each point.\n/// If you only need to throw an error to stop the work,\n/// call the `Task.checkCancellation()` function to check for cancellation.\n/// Other responses to cancellation include\n/// returning the work completed so far, returning an empty result, or returning `nil`.\n///\n/// Cancellation is a purely Boolean state;\n/// there's no way to include additional information\n/// like the reason for cancellation.\n/// This reflects the fact that a task can be canceled for many reasons,\n/// and additional reasons can accrue during the cancellation process.\n///\n/// ### Task closure lifetime\n/// Tasks are initialized by passing a closure containing the code that will be executed by a given task.\n///\n/// After this code has run to completion, the task has completed, resulting in either\n/// a failure or result value, this closure is eagerly released.\n///\n/// Retaining a task object doesn't indefinitely retain the closure,\n/// because any references that a task holds are released\n/// after the task completes.\n/// Consequently, tasks rarely need to capture weak references to values.\n///\n/// For example, in the following snippet of code it is not necessary to capture the actor as `weak`,\n/// because as the task completes it'll let go of the actor reference, breaking the\n/// reference cycle between the Task and the actor holding it.\n///\n/// ```\n/// struct Work: Sendable {}\n///\n/// actor Worker {\n/// var work: Task<Void, Never>?\n/// var result: Work?\n///\n/// deinit {\n/// // even though the task is still retained,\n/// // once it completes it no longer causes a reference cycle with the actor\n///\n/// print("deinit actor")\n/// }\n///\n/// func start() {\n/// work = Task {\n/// print("start task work")\n/// try? await Task.sleep(for: .seconds(3))\n/// self.result = Work() // we captured self\n/// print("completed task work")\n/// // but as the task completes, this reference is released\n/// }\n/// // we keep a strong reference to the task\n/// }\n/// }\n/// ```\n///\n/// And using it like this:\n///\n/// ```\n/// await Worker().start()\n/// ```\n///\n/// Note that the actor is only retained by the start() method's use of `self`,\n/// and that the start method immediately returns, without waiting for the\n/// unstructured `Task` to finish. Once the task is completed and its closure is\n/// destroyed, the strong reference to the actor is also released allowing the\n/// actor to deinitialize as expected.\n///\n/// Therefore, the above call will consistently result in the following output:\n///\n/// ```other\n/// start task work\n/// completed task work\n/// deinit actor\n/// ```\n@available(SwiftStdlib 5.1, *)\n@frozen\npublic struct Task<Success: Sendable, Failure: Error>: Sendable {\n @usableFromInline\n internal let _task: Builtin.NativeObject\n\n @_alwaysEmitIntoClient\n internal init(_ task: Builtin.NativeObject) {\n self._task = task\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task {\n /// The result from a throwing task, after it completes.\n ///\n /// If the task hasn't completed,\n /// accessing this property waits for it to complete\n /// and its priority increases to that of the current task.\n /// Note that this might not be as effective as\n /// creating the task with the correct priority,\n /// depending on the executor's scheduling details.\n ///\n /// If the task throws an error, this property propagates that error.\n /// Tasks that respond to cancellation by throwing `CancellationError`\n /// have that error propagated here upon cancellation.\n ///\n /// - Returns: The task's result.\n public var value: Success {\n get async throws {\n return try await _taskFutureGetThrowing(_task)\n }\n }\n\n /// The result or error from a throwing task, after it completes.\n ///\n /// If the task hasn't completed,\n /// accessing this property waits for it to complete\n /// and its priority increases to that of the current task.\n /// Note that this might not be as effective as\n /// creating the task with the correct priority,\n /// depending on the executor's scheduling details.\n ///\n /// - Returns: If the task succeeded,\n /// `.success` with the task's result as the associated value;\n /// otherwise, `.failure` with the error as the associated value.\n public var result: Result<Success, Failure> {\n get async {\n do {\n return .success(try await value)\n } catch {\n return .failure(error as! Failure) // as!-safe, guaranteed to be Failure\n }\n }\n }\n\n /// Cancels this task.\n ///\n /// Cancelling a task has three primary effects:\n ///\n /// - It flags the task as canceled.\n /// - It causes any active cancellation handlers on the task to run, once.\n /// - It cancels any child tasks and task groups of the task, including\n /// those created in the future. If those tasks have cancellation handlers,\n /// they also are triggered.\n ///\n /// Task cancellation is cooperative and idempotent.\n ///\n /// Cancelling a task does not automatically cause arbitrary functions on the task\n /// to stop running or throw errors. A function _may_ choose to react\n /// to cancellation by ending its work early, and it is conventional to\n /// signal that to callers by throwing `CancellationError`. However,\n /// a function that doesn't specifically check for cancellation will\n /// run to completion normally, even if the task it is running on is\n /// canceled. However, that function might still end early if it calls\n /// other code that handles cancellation by throwing and that function doesn't\n /// handle the error.\n ///\n /// It's safe to cancel a task from any task or thread. It's safe for\n /// multiple tasks or threads to cancel the same task at the same\n /// time. Cancelling a task that has already been canceled has no\n /// additional effect.\n ///\n /// `cancel` may need to acquire locks and synchronously run\n /// arbitrary cancellation-handler code associated with the\n /// canceled task. To reduce the risk of deadlock, it is\n /// recommended that callers release any locks they might be\n /// holding before they call cancel.\n ///\n /// If the task has already run past the last point where it could have\n /// performed a cancellation check, cancelling it may have no observable effects.\n ///\n /// - SeeAlso: `Task.checkCancellation()`\n /// - SeeAlso: `withTaskCancellationHandler(operation:onCancel:isolation:)`\n public func cancel() {\n Builtin.cancelAsyncTask(_task)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Failure == Never {\n /// The result from a nonthrowing task, after it completes.\n ///\n /// If the task hasn't completed yet,\n /// accessing this property waits for it to complete\n /// and its priority increases to that of the current task.\n /// Note that this might not be as effective as\n /// creating the task with the correct priority,\n /// depending on the executor's scheduling details.\n ///\n /// Tasks that never throw an error can still check for cancellation,\n /// but they need to use an approach like returning `nil`\n /// instead of throwing an error.\n public var value: Success {\n get async {\n return await _taskFutureGet(_task)\n }\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task: Hashable {\n public func hash(into hasher: inout Hasher) {\n UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task: Equatable {\n public static func ==(lhs: Self, rhs: Self) -> Bool {\n unsafe UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) ==\n UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task))\n }\n}\n\n// ==== Task Priority ----------------------------------------------------------\n\n/// The priority of a task.\n///\n/// The executor determines how priority information affects the way tasks are scheduled.\n/// The behavior varies depending on the executor currently being used.\n/// Typically, executors attempt to run tasks with a higher priority\n/// before tasks with a lower priority.\n/// However, the semantics of how priority is treated are left up to each\n/// platform and `Executor` implementation.\n///\n/// Child tasks automatically inherit their parent task's priority.\n/// Detached tasks created by `detach(priority:operation:)` don't inherit task priority\n/// because they aren't attached to the current task.\n///\n/// In some situations the priority of a task is elevated ---\n/// that is, the task is treated as it if had a higher priority,\n/// without actually changing the priority of the task:\n///\n/// - If a task runs on behalf of an actor,\n/// and a new higher-priority task is enqueued to the actor,\n/// then the actor's current task is temporarily elevated\n/// to the priority of the enqueued task.\n/// This priority elevation allows the new task\n/// to be processed at the priority it was enqueued with.\n/// - If a higher-priority task calls the `get()` method,\n/// then the priority of this task increases until the task completes.\n///\n/// In both cases, priority elevation helps you prevent a low-priority task\n/// from blocking the execution of a high priority task,\n/// which is also known as *priority inversion*.\n@available(SwiftStdlib 5.1, *)\npublic struct TaskPriority: RawRepresentable, Sendable {\n public typealias RawValue = UInt8\n public var rawValue: UInt8\n\n public init(rawValue: UInt8) {\n self.rawValue = rawValue\n }\n\n public static let high: TaskPriority = .init(rawValue: 0x19)\n\n @_alwaysEmitIntoClient\n public static var medium: TaskPriority {\n .init(rawValue: 0x15)\n }\n\n public static let low: TaskPriority = .init(rawValue: 0x11)\n\n public static let userInitiated: TaskPriority = high\n public static let utility: TaskPriority = low\n public static let background: TaskPriority = .init(rawValue: 0x09)\n\n @available(*, deprecated, renamed: "medium")\n public static let `default`: TaskPriority = .init(rawValue: 0x15)\n}\n\n@available(SwiftStdlib 5.1, *)\nextension TaskPriority: Equatable {\n public static func == (lhs: TaskPriority, rhs: TaskPriority) -> Bool {\n lhs.rawValue == rhs.rawValue\n }\n\n public static func != (lhs: TaskPriority, rhs: TaskPriority) -> Bool {\n lhs.rawValue != rhs.rawValue\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension TaskPriority: Comparable {\n public static func < (lhs: TaskPriority, rhs: TaskPriority) -> Bool {\n lhs.rawValue < rhs.rawValue\n }\n\n public static func <= (lhs: TaskPriority, rhs: TaskPriority) -> Bool {\n lhs.rawValue <= rhs.rawValue\n }\n\n public static func > (lhs: TaskPriority, rhs: TaskPriority) -> Bool {\n lhs.rawValue > rhs.rawValue\n }\n\n public static func >= (lhs: TaskPriority, rhs: TaskPriority) -> Bool {\n lhs.rawValue >= rhs.rawValue\n }\n}\n\n\n@available(SwiftStdlib 5.9, *)\n@_unavailableInEmbedded\nextension TaskPriority: CustomStringConvertible {\n @available(SwiftStdlib 5.9, *)\n public var description: String {\n switch self.rawValue {\n case Self.low.rawValue:\n return "\(Self.self).low"\n case Self.medium.rawValue:\n return "\(Self.self).medium"\n case Self.high.rawValue:\n return "\(Self.self).high"\n case Self.background.rawValue:\n return "\(Self.self).background"\n default:\n return "\(Self.self)(rawValue: \(self.rawValue))"\n }\n }\n}\n\n#if !SWIFT_CONCURRENCY_EMBEDDED\n@available(SwiftStdlib 5.1, *)\nextension TaskPriority: Codable { }\n#endif\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Success == Never, Failure == Never {\n\n /// The current task's priority.\n ///\n /// If you access this property outside of any task,\n /// this queries the system to determine the\n /// priority at which the current function is running.\n /// If the system can't provide a priority,\n /// this property's value is `Priority.default`.\n public static var currentPriority: TaskPriority {\n unsafe withUnsafeCurrentTask { unsafeTask in\n // If we are running on behalf of a task, use that task's priority.\n if let unsafeTask = unsafe unsafeTask {\n return unsafe unsafeTask.priority\n }\n\n // Otherwise, query the system.\n return TaskPriority(rawValue: UInt8(_getCurrentThreadPriority()))\n }\n }\n\n /// The current task's base priority.\n ///\n /// If you access this property outside of any task, this returns nil\n @available(SwiftStdlib 5.7, *)\n public static var basePriority: TaskPriority? {\n unsafe withUnsafeCurrentTask { task in\n // If we are running on behalf of a task, use that task's priority.\n if let unsafeTask = unsafe task {\n return unsafe TaskPriority(rawValue: _taskBasePriority(unsafeTask._task))\n }\n return nil\n }\n }\n\n}\n\n@available(SwiftStdlib 5.1, *)\nextension TaskPriority {\n /// Downgrade user-interactive to user-initiated.\n var _downgradeUserInteractive: TaskPriority {\n return self\n }\n}\n\n// ==== Job Flags --------------------------------------------------------------\n\n/// Flags for schedulable jobs.\n///\n/// This is a port of the C++ FlagSet.\n@available(SwiftStdlib 5.1, *)\nstruct JobFlags {\n /// Kinds of schedulable jobs.\n enum Kind: Int32 {\n case task = 0\n }\n\n /// The actual bit representation of these flags.\n var bits: Int32 = 0\n\n /// The kind of job described by these flags.\n var kind: Kind {\n get {\n Kind(rawValue: bits & 0xFF)!\n }\n\n set {\n bits = (bits & ~0xFF) | newValue.rawValue\n }\n }\n\n /// Whether this is an asynchronous task.\n var isAsyncTask: Bool { kind == .task }\n\n /// The priority given to the job.\n var priority: TaskPriority? {\n get {\n let value = (Int(bits) & 0xFF00) >> 8\n\n if value == 0 {\n return nil\n }\n\n return TaskPriority(rawValue: UInt8(value))\n }\n\n set {\n bits = (bits & ~0xFF00) | Int32((Int(newValue?.rawValue ?? 0) << 8))\n }\n }\n\n /// Whether this is a child task.\n var isChildTask: Bool {\n get {\n (bits & (1 << 24)) != 0\n }\n\n set {\n if newValue {\n bits = bits | 1 << 24\n } else {\n bits = (bits & ~(1 << 24))\n }\n }\n }\n\n /// Whether this is a future.\n var isFuture: Bool {\n get {\n (bits & (1 << 25)) != 0\n }\n\n set {\n if newValue {\n bits = bits | 1 << 25\n } else {\n bits = (bits & ~(1 << 25))\n }\n }\n }\n\n /// Whether this is a group child.\n var isGroupChildTask: Bool {\n get {\n (bits & (1 << 26)) != 0\n }\n\n set {\n if newValue {\n bits = bits | 1 << 26\n } else {\n bits = (bits & ~(1 << 26))\n }\n }\n }\n\n /// Whether this is a task created by the 'async' operation, which\n /// conceptually continues the work of the synchronous code that invokes\n /// it.\n var isContinuingAsyncTask: Bool {\n get {\n (bits & (1 << 27)) != 0\n }\n\n set {\n if newValue {\n bits = bits | 1 << 27\n } else {\n bits = (bits & ~(1 << 27))\n }\n }\n }\n}\n\n// ==== Task Creation Flags --------------------------------------------------\n\n/// Form task creation flags for use with the createAsyncTask builtins.\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\nfunc taskCreateFlags(\n priority: TaskPriority?, isChildTask: Bool, copyTaskLocals: Bool,\n inheritContext: Bool, enqueueJob: Bool,\n addPendingGroupTaskUnconditionally: Bool,\n isDiscardingTask: Bool,\n isSynchronousStart: Bool\n) -> Int {\n var bits = 0\n bits |= (bits & ~0xFF) | Int(priority?.rawValue ?? 0)\n if isChildTask {\n bits |= 1 << 8\n }\n if copyTaskLocals {\n bits |= 1 << 10\n }\n if inheritContext {\n bits |= 1 << 11\n }\n if enqueueJob {\n bits |= 1 << 12\n }\n if addPendingGroupTaskUnconditionally {\n bits |= 1 << 13\n }\n if isDiscardingTask {\n bits |= 1 << 14\n }\n // 15 is used by 'IsTaskFunctionConsumed'\n if isSynchronousStart {\n bits |= 1 << 16\n }\n return bits\n}\n\n// ==== Task Creation ----------------------------------------------------------\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Failure == Never {\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @discardableResult\n @_alwaysEmitIntoClient\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public init(\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success\n ) {\n fatalError("Unavailable in task-to-thread concurrency model.")\n }\n#else\n /// Runs the given nonthrowing operation asynchronously\n /// as part of a new top-level task on behalf of the current actor.\n ///\n /// Use this function when creating asynchronous work\n /// that operates on behalf of the synchronous function that calls it.\n /// Like `Task.detached(priority:operation:)`,\n /// this function creates a separate, top-level task.\n /// Unlike `Task.detached(priority:operation:)`,\n /// the task created by `Task.init(priority:operation:)`\n /// inherits the priority and actor context of the caller,\n /// so the operation is treated more like an asynchronous extension\n /// to the synchronous operation.\n ///\n /// You need to keep a reference to the task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - priority: The priority of the task.\n /// Pass `nil` to use the priority from `Task.currentPriority`.\n /// - operation: The operation to perform.\n @discardableResult\n @_alwaysEmitIntoClient\n public init(\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success\n ) {\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: true,\n inheritContext: true, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n // Create the asynchronous task.\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n let (task, _) = Builtin.createTask(flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n operation: operation)\n\n self._task = task\n }\n#endif\n}\n\n@available(SwiftStdlib 6.2, *)\nextension Task where Failure == Never {\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @discardableResult\n @_alwaysEmitIntoClient\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public init(\n name: String?,\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success\n ) {\n fatalError("Unavailable in task-to-thread concurrency model.")\n }\n#elseif $Embedded\n @discardableResult\n @_alwaysEmitIntoClient\n @available(SwiftStdlib 6.2, *)\n public init(\n name: String?,\n // TaskExecutor is unavailable in embedded\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: sending @escaping () async -> Success\n ) {\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority,\n isChildTask: false,\n copyTaskLocals: true,\n inheritContext: true,\n enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false,\n isSynchronousStart: false)\n\n // Create the asynchronous task.\n let (task, _) = Builtin.createAsyncTask(flags, operation)\n\n self._task = task\n }\n#else\n /// Runs the given nonthrowing operation asynchronously\n /// as part of a new top-level task on behalf of the current actor.\n ///\n /// Use this function when creating asynchronous work\n /// that operates on behalf of the synchronous function that calls it.\n /// Like `Task.detached(priority:operation:)`,\n /// this function creates a separate, top-level task.\n /// Unlike `Task.detached(priority:operation:)`,\n /// the task created by `Task.init(priority:operation:)`\n /// inherits the priority and actor context of the caller,\n /// so the operation is treated more like an asynchronous extension\n /// to the synchronous operation.\n ///\n /// You need to keep a reference to the task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - name: The high-level human-readable name given for this task\n /// - priority: The priority of the task.\n /// Pass `nil` to use the priority from `Task.currentPriority`.\n /// - operation: The operation to perform.\n @discardableResult\n @_alwaysEmitIntoClient\n @available(SwiftStdlib 6.2, *)\n public init(\n name: String?,\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success\n ) {\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: true,\n inheritContext: true, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n // Create the asynchronous task.\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n var task: Builtin.NativeObject?\n #if $BuiltinCreateAsyncTaskName\n if let name {\n task =\n unsafe name.utf8CString.withUnsafeBufferPointer { nameBytes in\n Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskName: nameBytes.baseAddress!._rawValue,\n operation: operation).0\n }\n }\n #endif\n if task == nil {\n // either no task name was set, or names are unsupported\n task = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n operation: operation).0\n }\n\n self._task = task!\n }\n#endif\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Failure == Error {\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @discardableResult\n @_alwaysEmitIntoClient\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public init(\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success\n ) {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n#else\n /// Runs the given throwing operation asynchronously\n /// as part of a new top-level task on behalf of the current actor.\n ///\n /// Use this function when creating asynchronous work\n /// that operates on behalf of the synchronous function that calls it.\n /// Like `Task.detached(priority:operation:)`,\n /// this function creates a separate, top-level task.\n /// Unlike `detach(priority:operation:)`,\n /// the task created by `Task.init(priority:operation:)`\n /// inherits the priority and actor context of the caller,\n /// so the operation is treated more like an asynchronous extension\n /// to the synchronous operation.\n ///\n /// You need to keep a reference to the task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - priority: The priority of the task.\n /// Pass `nil` to use the priority from `Task.currentPriority`.\n /// - operation: The operation to perform.\n @discardableResult\n @_alwaysEmitIntoClient\n public init(\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success\n ) {\n // Set up the task flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: true,\n inheritContext: true, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n // Create the asynchronous task future.\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n let (task, _) = Builtin.createTask(flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n operation: operation)\n\n self._task = task\n }\n#endif\n}\n\n\n@available(SwiftStdlib 6.2, *)\nextension Task where Failure == Error {\n #if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @discardableResult\n @_alwaysEmitIntoClient\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public init(\n name: String?,\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success\n) {\n fatalError("Unavailable in task-to-thread concurrency model.")\n}\n #elseif $Embedded\n @discardableResult\n @_alwaysEmitIntoClient\n @available(SwiftStdlib 6.2, *)\n public init(\n name: String?,\n // TaskExecutor is unavailable in embedded\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: sending @escaping () async throws -> Success\n) {\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: true,\n inheritContext: true, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n // Create the asynchronous task.\n let (task, _) = Builtin.createAsyncTask(flags, operation)\n\nself._task = task\n}\n #else\n /// Runs the given nonthrowing operation asynchronously\n /// as part of a new top-level task on behalf of the current actor.\n ///\n /// Use this function when creating asynchronous work\n /// that operates on behalf of the synchronous function that calls it.\n /// Like `Task.detached(priority:operation:)`,\n /// this function creates a separate, top-level task.\n /// Unlike `Task.detached(priority:operation:)`,\n /// the task created by `Task.init(priority:operation:)`\n /// inherits the priority and actor context of the caller,\n /// so the operation is treated more like an asynchronous extension\n /// to the synchronous operation.\n ///\n /// You need to keep a reference to the task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - name: The high-level human-readable name given for this task\n /// - priority: The priority of the task.\n /// Pass `nil` to use the priority from `Task.currentPriority`.\n /// - operation: The operation to perform.\n @discardableResult\n @_alwaysEmitIntoClient\n @available(SwiftStdlib 6.2, *)\n public init(\n name: String?,\n priority: TaskPriority? = nil,\n @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success\n) {\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: true,\n inheritContext: true, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n // Create the asynchronous task.\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n var task: Builtin.NativeObject?\n #if $BuiltinCreateAsyncTaskName\n if let name {\n task =\n unsafe name.utf8CString.withUnsafeBufferPointer { nameBytes in\n Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskName: nameBytes.baseAddress!._rawValue,\n operation: operation).0\n }\n }\n #endif\n if task == nil {\n // either no task name was set, or names are unsupported\n task = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n operation: operation).0\n }\n\n self._task = task!\n }\n #endif\n}\n\n// ==== Detached Tasks ---------------------------------------------------------\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Failure == Never {\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @discardableResult\n @_alwaysEmitIntoClient\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public static func detached(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async -> Success\n ) -> Task<Success, Failure> {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n#else\n /// Runs the given nonthrowing operation asynchronously\n /// as part of a new top-level task.\n ///\n /// Don't use a detached task if it's possible\n /// to model the operation using structured concurrency features like child tasks.\n /// Child tasks inherit the parent task's priority and task-local storage,\n /// and canceling a parent task automatically cancels all of its child tasks.\n /// You need to handle these considerations manually with a detached task.\n ///\n /// You need to keep a reference to the detached task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - priority: The priority of the task.\n /// - operation: The operation to perform.\n ///\n /// - Returns: A reference to the task.\n @discardableResult\n @_alwaysEmitIntoClient\n public static func detached(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async -> Success\n ) -> Task<Success, Failure> {\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: false,\n inheritContext: false, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n // Create the asynchronous task future.\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n let (task, _) = Builtin.createTask(flags: flags,\n initialSerialExecutor:\n builtinSerialExecutor,\n operation: operation)\n\n return Task(task)\n }\n#endif\n}\n\n@available(SwiftStdlib 6.2, *)\nextension Task where Failure == Never {\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @discardableResult\n @_alwaysEmitIntoClient\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public static func detached(\n name: String?,\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async -> Success\n ) -> Task<Success, Failure> {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n#else\n /// Runs the given nonthrowing operation asynchronously\n /// as part of a new top-level task.\n ///\n /// Don't use a detached task if it's possible\n /// to model the operation using structured concurrency features like child tasks.\n /// Child tasks inherit the parent task's priority and task-local storage,\n /// and canceling a parent task automatically cancels all of its child tasks.\n /// You need to handle these considerations manually with a detached task.\n ///\n /// You need to keep a reference to the detached task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - name: Human readable name of the task.\n /// - priority: The priority of the task.\n /// - operation: The operation to perform.\n ///\n /// - Returns: A reference to the task.\n @discardableResult\n @_alwaysEmitIntoClient\n public static func detached(\n name: String?,\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async -> Success\n ) -> Task<Success, Failure> {\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: false,\n inheritContext: false, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n // Create the asynchronous task.\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n var task: Builtin.NativeObject?\n #if $BuiltinCreateAsyncTaskName\n if let name {\n task =\n unsafe name.utf8CString.withUnsafeBufferPointer { nameBytes in\n Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskName: nameBytes.baseAddress!._rawValue,\n operation: operation).0\n }\n }\n #endif\n if task == nil {\n // either no task name was set, or names are unsupported\n task = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n operation: operation).0\n }\n\n return Task(task!)\n }\n#endif\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Failure == Error {\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @discardableResult\n @_alwaysEmitIntoClient\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public static func detached(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async throws -> Success\n ) -> Task<Success, Failure> {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n#else\n /// Runs the given throwing operation asynchronously\n /// as part of a new top-level task.\n ///\n /// If the operation throws an error, this method propagates that error.\n ///\n /// Don't use a detached task if it's possible\n /// to model the operation using structured concurrency features like child tasks.\n /// Child tasks inherit the parent task's priority and task-local storage,\n /// and canceling a parent task automatically cancels all of its child tasks.\n /// You need to handle these considerations manually with a detached task.\n ///\n /// You need to keep a reference to the detached task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - priority: The priority of the task.\n /// - operation: The operation to perform.\n ///\n /// - Returns: A reference to the task.\n @discardableResult\n @_alwaysEmitIntoClient\n public static func detached(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async throws -> Success\n ) -> Task<Success, Failure> {\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: false,\n inheritContext: false, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n // Create the asynchronous task future.\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n let (task, _) = Builtin.createTask(flags: flags,\n initialSerialExecutor:\n builtinSerialExecutor,\n operation: operation)\n\n return Task(task)\n }\n#endif\n}\n\n@available(SwiftStdlib 6.2, *)\nextension Task where Failure == Error {\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n @discardableResult\n @_alwaysEmitIntoClient\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public static func detached(\n name: String?,\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async throws -> Success\n ) -> Task<Success, Failure> {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n#else\n /// Runs the given throwing operation asynchronously\n /// as part of a new top-level task.\n ///\n /// If the operation throws an error, this method propagates that error.\n ///\n /// Don't use a detached task if it's possible\n /// to model the operation using structured concurrency features like child tasks.\n /// Child tasks inherit the parent task's priority and task-local storage,\n /// and canceling a parent task automatically cancels all of its child tasks.\n /// You need to handle these considerations manually with a detached task.\n ///\n /// You need to keep a reference to the detached task\n /// if you want to cancel it by calling the `Task.cancel()` method.\n /// Discarding your reference to a detached task\n /// doesn't implicitly cancel that task,\n /// it only makes it impossible for you to explicitly cancel the task.\n ///\n /// - Parameters:\n /// - priority: The priority of the task.\n /// - operation: The operation to perform.\n ///\n /// - Returns: A reference to the task.\n @discardableResult\n @_alwaysEmitIntoClient\n public static func detached(\n name: String?,\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async throws -> Success\n ) -> Task<Success, Failure> {\n // Set up the job flags for a new task.\n let flags = taskCreateFlags(\n priority: priority, isChildTask: false, copyTaskLocals: false,\n inheritContext: false, enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n // Create the asynchronous task future.\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n var task: Builtin.NativeObject?\n #if $BuiltinCreateAsyncTaskName\n if let name {\n task =\n unsafe name.utf8CString.withUnsafeBufferPointer { nameBytes in\n Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskName: nameBytes.baseAddress!._rawValue,\n operation: operation).0\n }\n }\n #endif\n if task == nil {\n // either no task name was set, or names are unsupported\n task = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n operation: operation).0\n }\n\n return Task(task!)\n }\n#endif\n}\n\n// ==== Task Name --------------------------------------------------------------\n\n@available(SwiftStdlib 6.2, *)\nextension Task where Success == Never, Failure == Never {\n\n /// Returns the human-readable name of the current task,\n /// if it was set during the tasks' creation.\n ///\n /// Tasks can be named during their creation, which can be helpful to identify\n /// unique tasks which may be created at same source locations, for example:\n ///\n /// func process(items: [Int]) async {\n /// await withTaskGroup { group in\n /// for item in items {\n /// group.addTask(name: "process-\(item)") {\n /// await process(item)\n /// }\n /// }\n /// }\n /// }\n @available(SwiftStdlib 6.2, *)\n public static var name: String? {\n return _getCurrentTaskNameString()\n }\n}\n\n// ==== Voluntary Suspension -----------------------------------------------------\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Success == Never, Failure == Never {\n\n /// Suspends the current task and allows other tasks to execute.\n ///\n /// A task can voluntarily suspend itself\n /// in the middle of a long-running operation\n /// that doesn't contain any suspension points,\n /// to let other tasks run for a while\n /// before execution returns to this task.\n ///\n /// If this task is the highest-priority task in the system,\n /// the executor immediately resumes execution of the same task.\n /// As such,\n /// this method isn't necessarily a way to avoid resource starvation.\n public static func yield() async {\n return await Builtin.withUnsafeContinuation { (continuation: Builtin.RawUnsafeContinuation) -> Void in\n let job = _taskCreateNullaryContinuationJob(\n priority: Int(Task.currentPriority.rawValue),\n continuation: continuation)\n\n #if !$Embedded && !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n if #available(SwiftStdlib 6.2, *) {\n let executor = Task.currentExecutor\n\n executor.enqueue(ExecutorJob(context: job))\n } else {\n _enqueueJobGlobal(job)\n }\n #else\n _enqueueJobGlobal(job)\n #endif\n }\n }\n}\n\n// ==== UnsafeCurrentTask ------------------------------------------------------\n\n/// Calls a closure with an unsafe reference to the current task.\n///\n/// If you call this function from the body of an asynchronous function,\n/// the unsafe task handle passed to the closure is always non-`nil`\n/// because an asynchronous function always runs in the context of a task.\n/// However, if you call this function from the body of a synchronous function,\n/// and that function isn't executing in the context of any task,\n/// the unsafe task handle is `nil`.\n///\n/// Don't store an unsafe task reference\n/// for use outside this method's closure.\n/// Storing an unsafe reference doesn't affect the task's actual life cycle,\n/// and the behavior of accessing an unsafe task reference\n/// outside of the `withUnsafeCurrentTask(body:)` method's closure isn't defined.\n/// There's no safe way to retrieve a reference to the current task\n/// and save it for long-term use.\n/// To query the current task without saving a reference to it,\n/// use properties like `currentPriority`.\n/// If you need to store a reference to a task,\n/// create an unstructured task using `Task.detached(priority:operation:)` instead.\n///\n/// - Parameters:\n/// - body: A closure that takes an `UnsafeCurrentTask` parameter.\n/// If `body` has a return value,\n/// that value is also used as the return value\n/// for the `withUnsafeCurrentTask(body:)` function.\n///\n/// - Returns: The return value, if any, of the `body` closure.\n@available(SwiftStdlib 5.1, *)\npublic func withUnsafeCurrentTask<T>(body: (UnsafeCurrentTask?) throws -> T) rethrows -> T {\n guard let _task = _getCurrentAsyncTask() else {\n return try unsafe body(nil)\n }\n\n // FIXME: This retain seems pretty wrong, however if we don't we WILL crash\n // with "destroying a task that never completed" in the task's destroy.\n // How do we solve this properly?\n Builtin.retain(_task)\n\n return try unsafe body(UnsafeCurrentTask(_task))\n}\n\n@available(SwiftStdlib 6.0, *)\npublic func withUnsafeCurrentTask<T>(body: (UnsafeCurrentTask?) async throws -> T) async rethrows -> T {\n guard let _task = _getCurrentAsyncTask() else {\n return try unsafe await body(nil)\n }\n\n // FIXME: This retain seems pretty wrong, however if we don't we WILL crash\n // with "destroying a task that never completed" in the task's destroy.\n // How do we solve this properly?\n Builtin.retain(_task)\n\n return try unsafe await body(UnsafeCurrentTask(_task))\n}\n\n/// An unsafe reference to the current task.\n///\n/// To get an instance of `UnsafeCurrentTask` for the current task,\n/// call the `withUnsafeCurrentTask(body:)` method.\n/// Don't store an unsafe task reference\n/// for use outside that method's closure.\n/// Storing an unsafe reference doesn't affect the task's actual life cycle,\n/// and the behavior of accessing an unsafe task reference\n/// outside of the `withUnsafeCurrentTask(body:)` method's closure isn't defined.\n///\n/// Only APIs on `UnsafeCurrentTask` that are also part of `Task`\n/// are safe to invoke from a task other than\n/// the task that this `UnsafeCurrentTask` instance refers to.\n/// Calling other APIs from another task is undefined behavior,\n/// breaks invariants in other parts of the program running on this task,\n/// and may lead to crashes or data loss.\n///\n/// For information about the language-level concurrency model that `UnsafeCurrentTask` is part of,\n/// see [Concurrency][concurrency] in [The Swift Programming Language][tspl].\n///\n/// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html\n/// [tspl]: https://docs.swift.org/swift-book/\n@available(SwiftStdlib 5.1, *)\n@unsafe\npublic struct UnsafeCurrentTask {\n internal let _task: Builtin.NativeObject\n\n // May only be created by the standard library.\n internal init(_ task: Builtin.NativeObject) {\n unsafe self._task = task\n }\n\n /// A Boolean value that indicates whether the current task was canceled.\n ///\n /// After the value of this property becomes `true`, it remains `true` indefinitely.\n /// There is no way to uncancel a task.\n ///\n /// - SeeAlso: `checkCancellation()`\n public var isCancelled: Bool {\n unsafe _taskIsCancelled(_task)\n }\n\n /// The current task's priority.\n ///\n /// - SeeAlso: `TaskPriority`\n /// - SeeAlso: `Task.currentPriority`\n public var priority: TaskPriority {\n unsafe TaskPriority(rawValue: _taskCurrentPriority(_task))\n }\n\n /// The current task's base priority.\n ///\n /// - SeeAlso: `TaskPriority`\n /// - SeeAlso: `Task.basePriority`\n @available(SwiftStdlib 5.9, *)\n public var basePriority: TaskPriority {\n unsafe TaskPriority(rawValue: _taskBasePriority(_task))\n }\n\n /// Cancel the current task.\n public func cancel() {\n unsafe _taskCancel(_task)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable)\nextension UnsafeCurrentTask: Sendable { }\n\n@available(SwiftStdlib 5.1, *)\nextension UnsafeCurrentTask: @unsafe Hashable {\n public func hash(into hasher: inout Hasher) {\n unsafe UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension UnsafeCurrentTask: Equatable {\n public static func ==(lhs: Self, rhs: Self) -> Bool {\n unsafe UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) ==\n UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task))\n }\n}\n\n// ==== Internal ---------------------------------------------------------------\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_getCurrent")\npublic func _getCurrentAsyncTask() -> Builtin.NativeObject?\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_getJobFlags")\nfunc getJobFlags(_ task: Builtin.NativeObject) -> JobFlags\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_enqueueGlobal")\n@usableFromInline\nfunc _enqueueJobGlobal(_ task: Builtin.Job)\n\n@available(SwiftStdlib 5.9, *)\nfunc _enqueueJobGlobal(_ task: UnownedJob) {\n _enqueueJobGlobal(task._context)\n}\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_enqueueGlobalWithDelay")\n@usableFromInline\nfunc _enqueueJobGlobalWithDelay(_ delay: UInt64, _ task: Builtin.Job)\n\n@available(SwiftStdlib 5.9, *)\nfunc _enqueueJobGlobalWithDelay(_ delay: UInt64, _ task: UnownedJob) {\n return _enqueueJobGlobalWithDelay(delay, task._context)\n}\n\n@available(SwiftStdlib 5.7, *)\n@_silgen_name("swift_task_enqueueGlobalWithDeadline")\n@usableFromInline\nfunc _enqueueJobGlobalWithDeadline(_ seconds: Int64, _ nanoseconds: Int64,\n _ toleranceSec: Int64, _ toleranceNSec: Int64,\n _ clock: Int32, _ task: UnownedJob)\n\n@usableFromInline\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_addPriorityEscalationHandler")\nfunc _taskAddPriorityEscalationHandler(\n handler: (UInt8, UInt8) -> Void\n) -> UnsafeRawPointer /*EscalationNotificationStatusRecord*/\n\n@usableFromInline\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_removePriorityEscalationHandler")\nfunc _taskRemovePriorityEscalationHandler(\n record: UnsafeRawPointer /*EscalationNotificationStatusRecord*/\n)\n\n@available(SwiftStdlib 5.1, *)\n@usableFromInline\n@_silgen_name("swift_task_asyncMainDrainQueue")\ninternal func _asyncMainDrainQueue() -> Never\n\n@available(SwiftStdlib 5.1, *)\n@usableFromInline\n@_silgen_name("swift_task_getMainExecutor")\ninternal func _getMainExecutor() -> Builtin.Executor\n\n/// Get the default generic serial executor.\n///\n/// It is used by default used by tasks and default actors,\n/// unless other executors are specified.\n@available(SwiftStdlib 6.0, *)\n@usableFromInline\ninternal func _getGenericSerialExecutor() -> Builtin.Executor {\n // The `SerialExecutorRef` to "default generic executor" is guaranteed\n // to be a zero value;\n //\n // As the runtime relies on this in multiple places,\n // so instead of a runtime call to get this executor ref, we bitcast a "zero"\n // of expected size to the builtin executor type.\n unsafe unsafeBitCast((UInt(0), UInt(0)), to: Builtin.Executor.self)\n}\n\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n@usableFromInline\n@preconcurrency\ninternal func _runAsyncMain(_ asyncFun: @Sendable @escaping () async throws -> ()) {\n fatalError("Unavailable in task-to-thread concurrency model")\n}\n#elseif !SWIFT_CONCURRENCY_EMBEDDED\n@available(SwiftStdlib 5.1, *)\n@usableFromInline\n@preconcurrency\ninternal func _runAsyncMain(_ asyncFun: @Sendable @escaping () async throws -> ()) {\n let taskFlags = taskCreateFlags(\n priority: nil, isChildTask: false, copyTaskLocals: false,\n inheritContext: false, enqueueJob: false,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n\n let (theTask, _) = Builtin.createAsyncTask(taskFlags) {\n do {\n try await asyncFun()\n exit(0)\n } catch {\n _errorInMain(error)\n }\n }\n\n let job = Builtin.convertTaskToJob(theTask)\n if #available(SwiftStdlib 6.2, *) {\n MainActor.executor.enqueue(ExecutorJob(context: job))\n } else {\n Builtin.unreachable()\n }\n\n _asyncMainDrainQueue()\n}\n#endif\n\n// FIXME: both of these ought to take their arguments _owned so that\n// we can do a move out of the future in the common case where it's\n// unreferenced\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_future_wait")\npublic func _taskFutureGet<T>(_ task: Builtin.NativeObject) async -> T\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_future_wait_throwing")\npublic func _taskFutureGetThrowing<T>(_ task: Builtin.NativeObject) async throws -> T\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_cancel")\npublic func _taskCancel(_ task: Builtin.NativeObject)\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_isCancelled")\n@usableFromInline\nfunc _taskIsCancelled(_ task: Builtin.NativeObject) -> Bool\n\n@_silgen_name("swift_task_currentPriority")\ninternal func _taskCurrentPriority(_ task: Builtin.NativeObject) -> UInt8\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_escalate")\n@discardableResult\ninternal func _taskEscalate(_ task: Builtin.NativeObject, newPriority: UInt8) -> UInt8\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_basePriority")\ninternal func _taskBasePriority(_ task: Builtin.NativeObject) -> UInt8\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_createNullaryContinuationJob")\nfunc _taskCreateNullaryContinuationJob(priority: Int, continuation: Builtin.RawUnsafeContinuation) -> Builtin.Job\n\n@available(SwiftStdlib 5.1, *)\n@usableFromInline\n@_silgen_name("swift_task_isCurrentExecutor")\nfunc _taskIsCurrentExecutor(_ executor: Builtin.Executor) -> Bool\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_isCurrentExecutorWithFlags")\n@usableFromInline\ninternal func _taskIsCurrentExecutor(\n executor: Builtin.Executor, flags: UInt64) -> Bool\n\n@available(SwiftStdlib 6.2, *)\nextension GlobalActor {\n @available(SwiftStdlib 6.2, *)\n @_silgen_name("_swift_task_isCurrentGlobalActor")\n internal static func _taskIsCurrentGlobalActor() -> Bool {\n let executor = unsafe sharedUnownedExecutor\n return unsafe _taskIsCurrentExecutor(executor: executor.executor, flags: 0)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\n@usableFromInline\n@_silgen_name("swift_task_reportUnexpectedExecutor")\nfunc _reportUnexpectedExecutor(_ _filenameStart: Builtin.RawPointer,\n _ _filenameLength: Builtin.Word,\n _ _filenameIsASCII: Builtin.Int1,\n _ _line: Builtin.Word,\n _ _executor: Builtin.Executor)\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_getCurrentThreadPriority")\nfunc _getCurrentThreadPriority() -> Int\n\n@available(SwiftStdlib 6.2, *)\n@_silgen_name("swift_task_getCurrentTaskName")\ninternal func _getCurrentTaskName() -> UnsafePointer<UInt8>?\n\n@available(SwiftStdlib 6.2, *)\ninternal func _getCurrentTaskNameString() -> String? {\n if let stringPtr = unsafe _getCurrentTaskName() {\n unsafe String(cString: stringPtr)\n } else {\n nil\n }\n}\n\n\n#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 5.8, *)\n@usableFromInline\n@_unavailableFromAsync(message: "Use _taskRunInline from a sync context to begin an async context.")\ninternal func _taskRunInline<T>(_ body: () async -> T) -> T {\n#if compiler(>=5.5) && $BuiltinTaskRunInline\n return Builtin.taskRunInline(body)\n#else\n fatalError("Unsupported Swift compiler")\n#endif\n}\n\n@available(SwiftStdlib 5.8, *)\nextension Task where Failure == Never {\n /// Start an async context within the current sync context and run the\n /// provided async closure, returning the value it produces.\n @available(SwiftStdlib 5.8, *)\n @_spi(_TaskToThreadModel)\n @_unavailableFromAsync(message: "Use Task.runInline from a sync context to begin an async context.")\n public static func runInline(_ body: () async -> Success) -> Success {\n return _taskRunInline(body)\n }\n}\n\n@available(SwiftStdlib 5.8, *)\nextension Task where Failure == Error {\n @available(SwiftStdlib 5.8, *)\n @_alwaysEmitIntoClient\n @usableFromInline\n internal static func _runInlineHelper<T>(\n body: () async -> Result<T, Error>,\n rescue: (Result<T, Error>) throws -> T\n ) rethrows -> T {\n return try rescue(\n _taskRunInline(body)\n )\n }\n\n /// Start an async context within the current sync context and run the\n /// provided async closure, returning or throwing the value or error it\n /// produces.\n @available(SwiftStdlib 5.8, *)\n @_spi(_TaskToThreadModel)\n @_unavailableFromAsync(message: "Use Task.runInline from a sync context to begin an async context.")\n public static func runInline(_ body: () async throws -> Success) rethrows -> Success {\n return try _runInlineHelper(\n body: {\n do {\n let value = try await body()\n return Result.success(value)\n }\n catch let error {\n return Result.failure(error)\n }\n },\n rescue: { try $0.get() }\n )\n }\n}\n#endif\n\n#if _runtime(_ObjC)\n\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n/// Intrinsic used by SILGen to launch a task for bridging a Swift async method\n/// which was called through its ObjC-exported completion-handler-based API.\n@available(SwiftStdlib 5.1, *)\n@_alwaysEmitIntoClient\n@usableFromInline\ninternal func _runTaskForBridgedAsyncMethod(@_inheritActorContext _ body: __owned @Sendable @escaping () async -> Void) {\n#if compiler(>=5.6)\n Task(operation: body)\n#else\n Task<Int, Error> {\n await body()\n return 0\n }\n#endif\n}\n#endif\n\n#endif\n\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_Task.swift | cpp_apple_swift_stdlib_public_Concurrency_Task.swift | Swift | 59,225 | 0.75 | 0.095632 | 0.427178 | vue-tools | 680 | 2023-12-06T03:54:13.953174 | BSD-3-Clause | false | d5fcaa957402c941f27e2a9caa813c21 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n// ==== Task Cancellation ------------------------------------------------------\n\n/// Execute an operation with a cancellation handler that's immediately\n/// invoked if the current task is canceled.\n///\n/// This differs from the operation cooperatively checking for cancellation\n/// and reacting to it in that the cancellation handler is _always_ and\n/// _immediately_ invoked when the task is canceled. For example, even if the\n/// operation is running code that never checks for cancellation, a cancellation\n/// handler still runs and provides a chance to run some cleanup code:\n///\n/// ```\n/// await withTaskCancellationHandler {\n/// var sum = 0\n/// while condition {\n/// sum += 1\n/// }\n/// return sum\n/// } onCancel: {\n/// // This onCancel closure might execute concurrently with the operation.\n/// condition.cancel()\n/// }\n/// ```\n///\n/// ### Execution order and semantics\n/// The `operation` closure is always invoked, even when the\n/// `withTaskCancellationHandler(operation:onCancel:)` method is called from a task\n/// that was already cancelled.\n///\n/// When `withTaskCancellationHandler(operation:onCancel:)` is used in a task that has already been\n/// cancelled, the cancellation handler will be executed\n/// immediately before the `operation` closure gets to execute.\n///\n/// This allows the cancellation handler to set some external "cancelled" flag\n/// that the operation may be *atomically* checking for in order to avoid\n/// performing any actual work once the operation gets to run.\n///\n/// The `operation` closure executes on the calling execution context, and doesn't\n/// suspend or change execution context unless code contained within the closure\n/// does so. In other words, the potential suspension point of the\n/// `withTaskCancellationHandler(operation:onCancel:)` never suspends by itself before\n/// executing the operation.\n///\n/// If cancellation occurs while the operation is running, the cancellation\n/// handler executes *concurrently* with the operation.\n///\n/// ### Cancellation handlers and locks\n///\n/// Cancellation handlers which acquire locks must take care to avoid deadlock.\n/// The cancellation handler may be invoked while holding internal locks\n/// associated with the task or other tasks. Other operations on the task, such\n/// as resuming a continuation, may acquire these same internal locks.\n/// Therefore, if a cancellation handler must acquire a lock, other code should\n/// not cancel tasks or resume continuations while holding that lock.\n@available(SwiftStdlib 5.1, *)\n#if !$Embedded\n@backDeployed(before: SwiftStdlib 6.0)\n#endif\npublic func withTaskCancellationHandler<T>(\n operation: () async throws -> T,\n onCancel handler: @Sendable () -> Void,\n isolation: isolated (any Actor)? = #isolation\n) async rethrows -> T {\n // unconditionally add the cancellation record to the task.\n // if the task was already cancelled, it will be executed right away.\n let record = unsafe _taskAddCancellationHandler(handler: handler)\n defer { unsafe _taskRemoveCancellationHandler(record: record) }\n\n return try await operation()\n}\n\n// Note: hack to stage out @_unsafeInheritExecutor forms of various functions\n// in favor of #isolation. The _unsafeInheritExecutor_ prefix is meaningful\n// to the type checker.\n//\n// This function also doubles as an ABI-compatibility shim predating the\n// introduction of #isolation.\n@_unsafeInheritExecutor // ABI compatibility with Swift 5.1\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("$ss27withTaskCancellationHandler9operation8onCancelxxyYaKXE_yyYbXEtYaKlF")\npublic func _unsafeInheritExecutor_withTaskCancellationHandler<T>(\n operation: () async throws -> T,\n onCancel handler: @Sendable () -> Void\n) async rethrows -> T {\n // unconditionally add the cancellation record to the task.\n // if the task was already cancelled, it will be executed right away.\n let record = unsafe _taskAddCancellationHandler(handler: handler)\n defer { unsafe _taskRemoveCancellationHandler(record: record) }\n\n return try await operation()\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task {\n /// A Boolean value that indicates whether the task should stop executing.\n ///\n /// After the value of this property becomes `true`, it remains `true` indefinitely.\n /// There is no way to uncancel a task.\n ///\n /// - SeeAlso: `checkCancellation()`\n @_transparent public var isCancelled: Bool {\n _taskIsCancelled(_task)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Success == Never, Failure == Never {\n /// A Boolean value that indicates whether the task should stop executing.\n ///\n /// After the value of this property becomes `true`, it remains `true` indefinitely.\n /// There is no way to uncancel a task.\n ///\n /// - SeeAlso: `checkCancellation()`\n public static var isCancelled: Bool {\n unsafe withUnsafeCurrentTask { task in\n unsafe task?.isCancelled ?? false\n }\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Task where Success == Never, Failure == Never {\n /// Throws an error if the task was canceled.\n ///\n /// The error is always an instance of `CancellationError`.\n ///\n /// - SeeAlso: `isCancelled()`\n @_unavailableInEmbedded\n public static func checkCancellation() throws {\n if Task<Never, Never>.isCancelled {\n throw _Concurrency.CancellationError()\n }\n }\n}\n\n/// An error that indicates a task was canceled.\n///\n/// This error is also thrown automatically by `Task.checkCancellation()`,\n/// if the current task has been canceled.\n@available(SwiftStdlib 5.1, *)\npublic struct CancellationError: Error {\n // no extra information, cancellation is intended to be light-weight\n public init() {}\n}\n\n@usableFromInline\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_addCancellationHandler")\nfunc _taskAddCancellationHandler(handler: () -> Void) -> UnsafeRawPointer /*CancellationNotificationStatusRecord*/\n\n@usableFromInline\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_removeCancellationHandler")\nfunc _taskRemoveCancellationHandler(\n record: UnsafeRawPointer /*CancellationNotificationStatusRecord*/\n)\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_TaskCancellation.swift | cpp_apple_swift_stdlib_public_Concurrency_TaskCancellation.swift | Swift | 6,609 | 0.95 | 0.123529 | 0.620253 | vue-tools | 389 | 2025-06-13T02:58:02.864388 | GPL-3.0 | false | edd22f8b6630db671f4d04709c2a1a29 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n// FIXME: This is a workaround for trouble including gyb-generated sources\n\n#if SWIFT_CONCURRENCY_EMBEDDED\n\n@available(SwiftStdlib 5.1, *)\nextension TaskGroup {\n\n @available(SwiftStdlib 5.1, *)\n @_alwaysEmitIntoClient\n public mutating func addTask(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async -> ChildTaskResult\n ) {\n let flags = taskCreateFlags(\n priority: priority,\n isChildTask: true,\n copyTaskLocals: false,\n inheritContext: false,\n enqueueJob: true,\n addPendingGroupTaskUnconditionally: true,\n isDiscardingTask: false,\n isSynchronousStart: false\n )\n\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n _ = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskGroup: _group,\n operation: operation).0\n }\n\n @available(SwiftStdlib 5.1, *)\n @_alwaysEmitIntoClient\n public mutating func addTaskUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async -> ChildTaskResult\n ) -> Bool {\n let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false)\n\n guard canAdd else {\n return false\n }\n\n let flags = taskCreateFlags(\n priority: priority,\n isChildTask: true,\n copyTaskLocals: false,\n inheritContext: false,\n enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: true,\n isSynchronousStart: false\n )\n\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n _ = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskGroup: _group,\n operation: operation).0\n\n return true\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension ThrowingTaskGroup {\n\n @available(SwiftStdlib 5.1, *)\n @_alwaysEmitIntoClient\n public mutating func addTask(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async throws -> ChildTaskResult\n ) {\n let flags = taskCreateFlags(\n priority: priority,\n isChildTask: true,\n copyTaskLocals: false,\n inheritContext: false,\n enqueueJob: true,\n addPendingGroupTaskUnconditionally: true,\n isDiscardingTask: false,\n isSynchronousStart: false\n )\n\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n _ = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskGroup: _group,\n operation: operation).0\n }\n\n @available(SwiftStdlib 5.1, *)\n @_alwaysEmitIntoClient\n public mutating func addTaskUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async throws -> ChildTaskResult\n ) -> Bool {\n let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false)\n\n guard canAdd else {\n return false\n }\n\n let flags = taskCreateFlags(\n priority: priority,\n isChildTask: true,\n copyTaskLocals: false,\n inheritContext: false,\n enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: true,\n isSynchronousStart: false\n )\n\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n _ = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskGroup: _group,\n operation: operation).0\n\n return true\n }\n}\n\n@available(SwiftStdlib 5.9, *)\nextension DiscardingTaskGroup {\n\n @available(SwiftStdlib 5.9, *)\n @_alwaysEmitIntoClient\n public mutating func addTask(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async -> Void\n ) {\n let flags = taskCreateFlags(\n priority: priority,\n isChildTask: true,\n copyTaskLocals: false,\n inheritContext: false,\n enqueueJob: true,\n addPendingGroupTaskUnconditionally: true,\n isDiscardingTask: true,\n isSynchronousStart: false\n )\n\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n _ = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskGroup: _group,\n operation: operation).0\n }\n\n @available(SwiftStdlib 5.9, *)\n @_alwaysEmitIntoClient\n public mutating func addTaskUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async -> Void\n ) -> Bool {\n let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false)\n\n guard canAdd else {\n return false\n }\n\n let flags = taskCreateFlags(\n priority: priority,\n isChildTask: true,\n copyTaskLocals: false,\n inheritContext: false,\n enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: true,\n isSynchronousStart: false\n )\n\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n _ = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskGroup: _group,\n operation: operation).0\n\n return true\n }\n}\n\n@available(SwiftStdlib 5.9, *)\nextension ThrowingDiscardingTaskGroup {\n\n @available(SwiftStdlib 5.9, *)\n @_alwaysEmitIntoClient\n public mutating func addTask(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async throws -> Void\n ) {\n let flags = taskCreateFlags(\n priority: priority,\n isChildTask: true,\n copyTaskLocals: false,\n inheritContext: false,\n enqueueJob: true,\n addPendingGroupTaskUnconditionally: true,\n isDiscardingTask: true,\n isSynchronousStart: false\n )\n\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n \n _ = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskGroup: _group,\n operation: operation).0\n }\n\n @available(SwiftStdlib 5.9, *)\n @_alwaysEmitIntoClient\n public mutating func addTaskUnlessCancelled(\n priority: TaskPriority? = nil,\n operation: sending @escaping @isolated(any) () async throws -> Void\n ) -> Bool {\n let canAdd = _taskGroupAddPendingTask(group: _group, unconditionally: false)\n\n guard canAdd else {\n return false\n }\n\n let flags = taskCreateFlags(\n priority: priority,\n isChildTask: true,\n copyTaskLocals: false,\n inheritContext: false,\n enqueueJob: true,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: true,\n isSynchronousStart: false\n )\n\n let builtinSerialExecutor =\n unsafe Builtin.extractFunctionIsolation(operation)?.unownedExecutor.executor\n\n _ = Builtin.createTask(\n flags: flags,\n initialSerialExecutor: builtinSerialExecutor,\n taskGroup: _group,\n operation: operation).0\n\n return true\n }\n}\n\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_TaskGroup+Embedded.swift | cpp_apple_swift_stdlib_public_Concurrency_TaskGroup+Embedded.swift | Swift | 7,710 | 0.95 | 0.014134 | 0.058577 | awesome-app | 68 | 2024-03-26T00:00:19.716924 | Apache-2.0 | false | 25da49363e1301c0dbd41d67c0afce80 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n// ==== TaskGroup --------------------------------------------------------------\n\n/// Starts a new scope that can contain a dynamic number of child tasks.\n///\n/// A group waits for all of its child tasks\n/// to complete or be canceled before it returns.\n/// After this function returns, the task group is always empty.\n///\n/// To collect the results of the group's child tasks,\n/// you can use a `for`-`await`-`in` loop:\n///\n/// var sum = 0\n/// for await result in group {\n/// sum += result\n/// }\n///\n/// If you need more control or only a few results,\n/// you can call `next()` directly:\n///\n/// guard let first = await group.next() else {\n/// group.cancelAll()\n/// return 0\n/// }\n/// let second = await group.next() ?? 0\n/// group.cancelAll()\n/// return first + second\n///\n/// Task Group Cancellation\n/// =======================\n///\n/// You can cancel a task group and all of its child tasks\n/// by calling the `cancelAll()` method on the task group,\n/// or by canceling the task in which the group is running.\n///\n/// If you call `addTask(name:priority:operation:)` to create a new task in a canceled group,\n/// that task is immediately canceled after creation.\n/// Alternatively, you can call `addTaskUnlessCancelled(name:priority:operation:)`,\n/// which doesn't create the task if the group has already been canceled.\n/// Choosing between these two functions\n/// lets you control how to react to cancellation within a group:\n/// some child tasks need to run regardless of cancellation,\n/// but other tasks are better not even being created\n/// when you know they can't produce useful results.\n///\n/// Because the tasks you add to a group with this method are nonthrowing,\n/// those tasks can't respond to cancellation by throwing `CancellationError`.\n/// The tasks must handle cancellation in some other way,\n/// such as returning the work completed so far, returning an empty result, or returning `nil`.\n/// For tasks that need to handle cancellation by throwing an error,\n/// use the `withThrowingTaskGroup(of:returning:body:)` method instead.\n@available(SwiftStdlib 5.1, *)\n#if !hasFeature(Embedded)\n@backDeployed(before: SwiftStdlib 6.0)\n#endif\n@inlinable\npublic func withTaskGroup<ChildTaskResult, GroupResult>(\n of childTaskResultType: ChildTaskResult.Type = ChildTaskResult.self,\n returning returnType: GroupResult.Type = GroupResult.self,\n isolation: isolated (any Actor)? = #isolation,\n body: (inout TaskGroup<ChildTaskResult>) async -> GroupResult\n) async -> GroupResult {\n #if compiler(>=5.5) && $BuiltinTaskGroupWithArgument\n\n let _group = Builtin.createTaskGroup(ChildTaskResult.self)\n var group = TaskGroup<ChildTaskResult>(group: _group)\n\n // Run the withTaskGroup body.\n let result = await body(&group)\n\n await group.awaitAllRemainingTasks()\n\n Builtin.destroyTaskGroup(_group)\n return result\n\n #else\n fatalError("Swift compiler is incompatible with this SDK version")\n #endif\n}\n\n// Note: hack to stage out @_unsafeInheritExecutor forms of various functions\n// in favor of #isolation. The _unsafeInheritExecutor_ prefix is meaningful\n// to the type checker.\n//\n// This function also doubles as an ABI-compatibility shim predating the\n// introduction of #isolation.\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("$ss13withTaskGroup2of9returning4bodyq_xm_q_mq_ScGyxGzYaXEtYar0_lF")\n@_unsafeInheritExecutor // for ABI compatibility\n@inlinable\npublic func _unsafeInheritExecutor_withTaskGroup<ChildTaskResult, GroupResult>(\n of childTaskResultType: ChildTaskResult.Type,\n returning returnType: GroupResult.Type = GroupResult.self,\n body: (inout TaskGroup<ChildTaskResult>) async -> GroupResult\n) async -> GroupResult {\n #if compiler(>=5.5) && $BuiltinTaskGroupWithArgument\n\n let _group = Builtin.createTaskGroup(ChildTaskResult.self)\n var group = TaskGroup<ChildTaskResult>(group: _group)\n\n // Run the withTaskGroup body.\n let result = await body(&group)\n\n await group.awaitAllRemainingTasks()\n\n Builtin.destroyTaskGroup(_group)\n return result\n\n #else\n fatalError("Swift compiler is incompatible with this SDK version")\n #endif\n}\n\n/// Starts a new scope that can contain a dynamic number of throwing child tasks.\n///\n/// A group waits for all of its child tasks\n/// to complete before it returns. Even cancelled tasks must run until\n/// completion before this function returns.\n/// Cancelled child tasks cooperatively react to cancellation and attempt\n/// to return as early as possible.\n/// After this function returns, the task group is always empty.\n///\n/// To collect the results of the group's child tasks,\n/// you can use a `for`-`await`-`in` loop:\n///\n/// var sum = 0\n/// for try await result in group {\n/// sum += result\n/// }\n///\n/// If you need more control or only a few results,\n/// you can call `next()` directly:\n///\n/// guard let first = try await group.next() else {\n/// group.cancelAll()\n/// return 0\n/// }\n/// let second = await group.next() ?? 0\n/// group.cancelAll()\n/// return first + second\n///\n/// Task Group Cancellation\n/// =======================\n///\n/// You can cancel a task group and all of its child tasks\n/// by calling the `cancelAll()` method on the task group,\n/// or by canceling the task in which the group is running.\n///\n/// If you call `addTask(name:priority:operation:)` to create a new task in a canceled group,\n/// that task is immediately canceled after creation.\n/// Alternatively, you can call `addTaskUnlessCancelled(name:priority:operation:)`,\n/// which doesn't create the task if the group has already been canceled.\n/// Choosing between these two functions\n/// lets you control how to react to cancellation within a group:\n/// some child tasks need to run regardless of cancellation,\n/// but other tasks are better not even being created\n/// when you know they can't produce useful results.\n///\n/// Error Handling\n/// ==============\n///\n/// Throwing an error in one of the child tasks of a task group\n/// doesn't immediately cancel the other tasks in that group.\n/// However,\n/// throwing out of the `body` of the `withThrowingTaskGroup` method does cancel\n/// the group, and all of its child tasks.\n/// For example,\n/// if you call `next()` in the task group and propagate its error,\n/// all other tasks are canceled.\n/// For example, in the code below,\n/// nothing is canceled and the group doesn't throw an error:\n///\n/// try await withThrowingTaskGroup(of: Void.self) { group in\n/// group.addTask { throw SomeError() }\n/// }\n///\n/// In contrast, this example throws `SomeError`\n/// and cancels all of the tasks in the group:\n///\n/// try await withThrowingTaskGroup(of: Void.self) { group in\n/// group.addTask { throw SomeError() }\n/// try await group.next()\n/// }\n///\n/// An individual task throws its error\n/// in the corresponding call to `Group.next()`,\n/// which gives you a chance to handle the individual error\n/// or to let the group rethrow the error.\n@available(SwiftStdlib 5.1, *)\n#if !hasFeature(Embedded)\n@backDeployed(before: SwiftStdlib 6.0)\n#endif\n@inlinable\npublic func withThrowingTaskGroup<ChildTaskResult, GroupResult>(\n of childTaskResultType: ChildTaskResult.Type = ChildTaskResult.self,\n returning returnType: GroupResult.Type = GroupResult.self,\n isolation: isolated (any Actor)? = #isolation,\n body: (inout ThrowingTaskGroup<ChildTaskResult, Error>) async throws -> GroupResult\n) async rethrows -> GroupResult {\n #if compiler(>=5.5) && $BuiltinTaskGroupWithArgument\n\n let _group = Builtin.createTaskGroup(ChildTaskResult.self)\n var group = ThrowingTaskGroup<ChildTaskResult, Error>(group: _group)\n\n do {\n // Run the withTaskGroup body.\n let result = try await body(&group)\n\n await group.awaitAllRemainingTasks()\n Builtin.destroyTaskGroup(_group)\n\n return result\n } catch {\n group.cancelAll()\n\n await group.awaitAllRemainingTasks()\n Builtin.destroyTaskGroup(_group)\n\n throw error\n }\n\n #else\n fatalError("Swift compiler is incompatible with this SDK version")\n #endif\n}\n\n// Note: hack to stage out @_unsafeInheritExecutor forms of various functions\n// in favor of #isolation. The _unsafeInheritExecutor_ prefix is meaningful\n// to the type checker.\n//\n// This function also doubles as an ABI-compatibility shim predating the\n// introduction of #isolation.\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("$ss21withThrowingTaskGroup2of9returning4bodyq_xm_q_mq_Scgyxs5Error_pGzYaKXEtYaKr0_lF")\n@_unsafeInheritExecutor // for ABI compatibility\npublic func _unsafeInheritExecutor_withThrowingTaskGroup<ChildTaskResult, GroupResult>(\n of childTaskResultType: ChildTaskResult.Type,\n returning returnType: GroupResult.Type = GroupResult.self,\n body: (inout ThrowingTaskGroup<ChildTaskResult, Error>) async throws -> GroupResult\n) async rethrows -> GroupResult {\n #if compiler(>=5.5) && $BuiltinTaskGroupWithArgument\n\n let _group = Builtin.createTaskGroup(ChildTaskResult.self)\n var group = ThrowingTaskGroup<ChildTaskResult, Error>(group: _group)\n\n do {\n // Run the withTaskGroup body.\n let result = try await body(&group)\n\n await group.awaitAllRemainingTasks()\n Builtin.destroyTaskGroup(_group)\n\n return result\n } catch {\n group.cancelAll()\n\n await group.awaitAllRemainingTasks()\n Builtin.destroyTaskGroup(_group)\n\n throw error\n }\n\n #else\n fatalError("Swift compiler is incompatible with this SDK version")\n #endif\n}\n\n/// A group that contains dynamically created child tasks.\n///\n/// To create a task group,\n/// call the `withTaskGroup(of:returning:body:)` method.\n///\n/// Don't use a task group from outside the task where you created it.\n/// In most cases,\n/// the Swift type system prevents a task group from escaping like that\n/// because adding a child task to a task group is a mutating operation,\n/// and mutation operations can't be performed\n/// from a concurrent execution context like a child task.\n///\n/// ### Task execution order\n///\n/// Tasks added to a task group execute concurrently, and may be scheduled in\n/// any order.\n///\n/// ### Cancellation behavior\n/// A task group becomes cancelled in one of the following ways:\n///\n/// - when ``cancelAll()`` is invoked on it,\n/// - when the ``Task`` running this task group is cancelled.\n///\n/// Since a `TaskGroup` is a structured concurrency primitive, cancellation is\n/// automatically propagated through all of its child-tasks (and their child\n/// tasks).\n///\n/// A cancelled task group can still keep adding tasks, however they will start\n/// being immediately cancelled, and may act accordingly to this. To avoid adding\n/// new tasks to an already cancelled task group, use ``addTaskUnlessCancelled(name:priority:body:)``\n/// rather than the plain ``addTask(name:priority:body:)`` which adds tasks unconditionally.\n///\n/// For information about the language-level concurrency model that `TaskGroup` is part of,\n/// see [Concurrency][concurrency] in [The Swift Programming Language][tspl].\n///\n/// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html\n/// [tspl]: https://docs.swift.org/swift-book/\n///\n@available(SwiftStdlib 5.1, *)\n@frozen\npublic struct TaskGroup<ChildTaskResult: Sendable> {\n\n /// Group task into which child tasks offer their results,\n /// and the `next()` function polls those results from.\n @usableFromInline\n internal let _group: Builtin.RawPointer\n\n // No public initializers\n @inlinable\n init(group: Builtin.RawPointer) {\n self._group = group\n }\n\n /// Waits for the next child task to complete,\n /// and returns the value it returned.\n ///\n /// The values returned by successive calls to this method\n /// appear in the order that the tasks *completed*,\n /// not in the order that those tasks were added to the task group.\n /// For example:\n ///\n /// group.addTask { 1 }\n /// group.addTask { 2 }\n ///\n /// print(await group.next())\n /// // Prints either "2" or "1".\n ///\n /// If there aren't any pending tasks in the task group,\n /// this method returns `nil`,\n /// which lets you write the following\n /// to wait for a single task to complete:\n ///\n /// if let first = try await group.next() {\n /// return first\n /// }\n ///\n /// It also lets you write code like the following\n /// to wait for all the child tasks to complete,\n /// collecting the values they returned:\n ///\n /// while let value = try await group.next() {\n /// collected += value\n /// }\n /// return collected\n ///\n /// Awaiting on an empty group\n /// immediate returns `nil` without suspending.\n ///\n /// You can also use a `for`-`await`-`in` loop to collect results of a task group:\n ///\n /// for await try value in group {\n /// collected += value\n /// }\n ///\n /// Don't call this method from outside the task\n /// where you created this task group.\n /// In most cases, the Swift type system prevents this mistake.\n /// For example, because the `add(priority:operation:)` method is mutating,\n /// that method can't be called from a concurrent execution context like a child task.\n ///\n /// - Returns: The value returned by the next child task that completes.\n @available(SwiftStdlib 5.1, *)\n #if !hasFeature(Embedded)\n @backDeployed(before: SwiftStdlib 6.0)\n #endif\n public mutating func next(isolation: isolated (any Actor)? = #isolation) async -> ChildTaskResult? {\n // try!-safe because this function only exists for Failure == Never,\n // and as such, it is impossible to spawn a throwing child task.\n return try! await _taskGroupWaitNext(group: _group) // !-safe cannot throw, we're a non-throwing TaskGroup\n }\n\n @available(SwiftStdlib 5.1, *)\n @_disfavoredOverload\n public mutating func next() async -> ChildTaskResult? {\n // try!-safe because this function only exists for Failure == Never,\n // and as such, it is impossible to spawn a throwing child task.\n return try! await _taskGroupWaitNext(group: _group) // !-safe cannot throw, we're a non-throwing TaskGroup\n }\n\n /// Await all of the pending tasks added this group.\n @usableFromInline\n @available(SwiftStdlib 5.1, *)\n #if !hasFeature(Embedded)\n @backDeployed(before: SwiftStdlib 6.0)\n #endif\n internal mutating func awaitAllRemainingTasks(isolation: isolated (any Actor)? = #isolation) async {\n while let _ = await next(isolation: isolation) {}\n }\n\n @usableFromInline\n @available(SwiftStdlib 5.1, *)\n internal mutating func awaitAllRemainingTasks() async {\n while let _ = await next(isolation: nil) {}\n }\n\n /// Wait for all of the group's remaining tasks to complete.\n @_alwaysEmitIntoClient\n public mutating func waitForAll(isolation: isolated (any Actor)? = #isolation) async {\n await awaitAllRemainingTasks(isolation: isolation)\n }\n\n /// A Boolean value that indicates whether the group has any remaining tasks.\n ///\n /// At the start of the body of a `withTaskGroup(of:returning:body:)` call,\n /// the task group is always empty.\n /// It`s guaranteed to be empty when returning from that body\n /// because a task group waits for all child tasks to complete before returning.\n ///\n /// - Returns: `true` if the group has no pending tasks; otherwise `false`.\n public var isEmpty: Bool {\n _taskGroupIsEmpty(_group)\n }\n\n /// Cancel all of the remaining tasks in the group.\n ///\n /// If you add a task to a group after canceling the group,\n /// that task is canceled immediately after being added to the group.\n ///\n /// Immediately cancelled child tasks should therefore cooperatively check for and\n /// react to cancellation, e.g. by throwing an `CancellationError` at their\n /// earliest convenience, or otherwise handling the cancellation.\n ///\n /// There are no restrictions on where you can call this method.\n /// Code inside a child task or even another task can cancel a group,\n /// however one should be very careful to not keep a reference to the\n /// group longer than the `with...TaskGroup(...) { ... }` method body is executing.\n ///\n /// - SeeAlso: `Task.isCancelled`\n /// - SeeAlso: `TaskGroup.isCancelled`\n public func cancelAll() {\n _taskGroupCancelAll(group: _group)\n }\n\n /// A Boolean value that indicates whether the group was canceled.\n ///\n /// To cancel a group, call the `TaskGroup.cancelAll()` method.\n ///\n /// If the task that's currently running this group is canceled,\n /// the group is also implicitly canceled,\n /// which is also reflected in this property's value.\n public var isCancelled: Bool {\n return _taskGroupIsCancelled(group: _group)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable)\nextension TaskGroup: Sendable { }\n\n// Implementation note:\n// We are unable to just™ abstract over Failure == Error / Never because of the\n// complicated relationship between `group.spawn` which dictates if `group.next`\n// AND the AsyncSequence conformances would be throwing or not.\n//\n// We would be able to abstract over TaskGroup<..., Failure> equal to Never\n// or Error, and specifically only add the `spawn` and `next` functions for\n// those two cases. However, we are not able to conform to AsyncSequence "twice"\n// depending on if the Failure is Error or Never, as we'll hit:\n// conflicting conformance of 'TaskGroup<ChildTaskResult, Failure>' to protocol\n// 'AsyncSequence'; there cannot be more than one conformance, even with\n// different conditional bounds\n// So, sadly we're forced to duplicate the entire implementation of TaskGroup\n// to TaskGroup and ThrowingTaskGroup.\n//\n// The throwing task group is parameterized with failure only because of future\n// proofing, in case we'd ever have typed errors, however unlikely this may be.\n// Today the throwing task group failure is simply automatically bound to `Error`.\n\n/// A group that contains throwing, dynamically created child tasks.\n///\n/// To create a throwing task group,\n/// call the `withThrowingTaskGroup(of:returning:body:)` method.\n///\n/// Don't use a task group from outside the task where you created it.\n/// In most cases,\n/// the Swift type system prevents a task group from escaping like that\n/// because adding a child task to a task group is a mutating operation,\n/// and mutation operations can't be performed\n/// from concurrent execution contexts like a child task.\n///\n/// ### Task execution order\n/// Tasks added to a task group execute concurrently, and may be scheduled in\n/// any order.\n///\n/// ### Cancellation behavior\n/// A task group becomes cancelled in one of the following ways:\n///\n/// - when ``cancelAll()`` is invoked on it,\n/// - when an error is thrown out of the `withThrowingTaskGroup(...) { }` closure,\n/// - when the ``Task`` running this task group is cancelled.\n///\n/// Since a `ThrowingTaskGroup` is a structured concurrency primitive, cancellation is\n/// automatically propagated through all of its child-tasks (and their child\n/// tasks).\n///\n/// A cancelled task group can still keep adding tasks, however they will start\n/// being immediately cancelled, and may act accordingly to this. To avoid adding\n/// new tasks to an already cancelled task group, use ``addTaskUnlessCancelled(priority:body:)``\n/// rather than the plain ``addTask(priority:body:)`` which adds tasks unconditionally.\n///\n/// For information about the language-level concurrency model that `ThrowingTaskGroup` is part of,\n/// see [Concurrency][concurrency] in [The Swift Programming Language][tspl].\n///\n/// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html\n/// [tspl]: https://docs.swift.org/swift-book/\n///\n@available(SwiftStdlib 5.1, *)\n@frozen\npublic struct ThrowingTaskGroup<ChildTaskResult: Sendable, Failure: Error> {\n\n /// Group task into which child tasks offer their results,\n /// and the `next()` function polls those results from.\n @usableFromInline\n internal let _group: Builtin.RawPointer\n\n // No public initializers\n @inlinable\n init(group: Builtin.RawPointer) {\n self._group = group\n }\n\n /// Await all the remaining tasks on this group.\n @usableFromInline\n @available(SwiftStdlib 5.1, *)\n #if !hasFeature(Embedded)\n @backDeployed(before: SwiftStdlib 6.0)\n #endif\n internal mutating func awaitAllRemainingTasks(isolation: isolated (any Actor)? = #isolation) async {\n while true {\n do {\n guard let _ = try await next(isolation: isolation) else {\n return\n }\n } catch {}\n }\n }\n\n @usableFromInline\n @available(SwiftStdlib 5.1, *)\n internal mutating func awaitAllRemainingTasks() async {\n await awaitAllRemainingTasks(isolation: nil)\n }\n\n @usableFromInline\n internal mutating func _waitForAll() async throws {\n await self.awaitAllRemainingTasks()\n }\n\n /// Wait for all of the group's remaining tasks to complete.\n ///\n /// If any of the tasks throw, the *first* error thrown is captured\n /// and re-thrown by this method although the task group is *not* cancelled\n /// when this happens.\n ///\n /// ### Cancelling the task group on first error\n ///\n /// If you want to cancel the task group, and all "sibling" tasks,\n /// whenever any of child tasks throws an error, use the following pattern instead:\n ///\n /// ```\n /// while !group.isEmpty {\n /// do {\n /// try await group.next()\n /// } catch is CancellationError {\n /// // we decide that cancellation errors thrown by children,\n /// // should not cause cancellation of the entire group.\n /// continue;\n /// } catch {\n /// // other errors though we print and cancel the group,\n /// // and all of the remaining child tasks within it.\n /// print("Error: \(error)")\n /// group.cancelAll()\n /// }\n /// }\n /// assert(group.isEmpty())\n /// ```\n ///\n /// - Throws: The *first* error that was thrown by a child task during draining all the tasks.\n /// This first error is stored until all other tasks have completed, and is re-thrown afterwards.\n @_alwaysEmitIntoClient\n public mutating func waitForAll(isolation: isolated (any Actor)? = #isolation) async throws {\n var firstError: Error? = nil\n\n // Make sure we loop until all child tasks have completed\n while !isEmpty {\n do {\n while let _ = try await next() {}\n } catch {\n // Upon error throws, capture the first one\n if firstError == nil {\n firstError = error\n }\n }\n }\n\n if let firstError {\n throw firstError\n }\n }\n\n /// Wait for the next child task to complete,\n /// and return the value it returned or rethrow the error it threw.\n ///\n /// The values returned by successive calls to this method\n /// appear in the order that the tasks *completed*,\n /// not in the order that those tasks were added to the task group.\n /// For example:\n ///\n /// group.addTask { 1 }\n /// group.addTask { 2 }\n ///\n /// print(await group.next())\n /// // Prints either "2" or "1".\n ///\n /// If there aren't any pending tasks in the task group,\n /// this method returns `nil`,\n /// which lets you write the following\n /// to wait for a single task to complete:\n ///\n /// if let first = try await group.next() {\n /// return first\n /// }\n ///\n /// It also lets you write code like the following\n /// to wait for all the child tasks to complete,\n /// collecting the values they returned:\n ///\n /// while let first = try await group.next() {\n /// collected += value\n /// }\n /// return collected\n ///\n /// Awaiting on an empty group\n /// immediately returns `nil` without suspending.\n ///\n /// You can also use a `for`-`await`-`in` loop to collect results of a task group:\n ///\n /// for try await value in group {\n /// collected += value\n /// }\n ///\n /// If the next child task throws an error\n /// and you propagate that error from this method\n /// out of the body of a call to the\n /// `ThrowingTaskGroup.withThrowingTaskGroup(of:returning:body:)` method,\n /// then all remaining child tasks in that group are implicitly canceled.\n ///\n /// Don't call this method from outside the task\n /// where this task group was created.\n /// In most cases, the Swift type system prevents this mistake;\n /// for example, because the `add(priority:operation:)` method is mutating,\n /// that method can't be called from a concurrent execution context like a child task.\n ///\n /// - Returns: The value returned by the next child task that completes.\n ///\n /// - Throws: The error thrown by the next child task that completes.\n ///\n /// - SeeAlso: `nextResult()`\n @available(SwiftStdlib 5.1, *)\n #if !hasFeature(Embedded)\n @backDeployed(before: SwiftStdlib 6.0)\n #endif\n public mutating func next(isolation: isolated (any Actor)? = #isolation) async throws -> ChildTaskResult? {\n return try await _taskGroupWaitNext(group: _group)\n }\n\n @available(SwiftStdlib 5.1, *)\n @_disfavoredOverload\n public mutating func next() async throws -> ChildTaskResult? {\n return try await _taskGroupWaitNext(group: _group)\n }\n\n @_silgen_name("$sScg10nextResults0B0Oyxq_GSgyYaKF")\n @usableFromInline\n mutating func nextResultForABI() async throws -> Result<ChildTaskResult, Failure>? {\n do {\n guard let success: ChildTaskResult = try await _taskGroupWaitNext(group: _group) else {\n return nil\n }\n\n return .success(success)\n } catch {\n return .failure(error as! Failure) // as!-safe, because we are only allowed to throw Failure (Error)\n }\n }\n\n /// Wait for the next child task to complete,\n /// and return a result containing either\n /// the value that the child task returned or the error that it threw.\n ///\n /// The values returned by successive calls to this method\n /// appear in the order that the tasks *completed*,\n /// not in the order that those tasks were added to the task group.\n /// For example:\n ///\n /// group.addTask { 1 }\n /// group.addTask { 2 }\n ///\n /// guard let result = await group.nextResult() else {\n /// return // No task to wait on, which won't happen in this example.\n /// }\n ///\n /// switch result {\n /// case .success(let value): print(value)\n /// case .failure(let error): print("Failure: \(error)")\n /// }\n /// // Prints either "2" or "1".\n ///\n /// If the next child task throws an error\n /// and you propagate that error from this method\n /// out of the body of a call to the\n /// `ThrowingTaskGroup.withThrowingTaskGroup(of:returning:body:)` method,\n /// then all remaining child tasks in that group are implicitly canceled.\n ///\n /// - Returns: A `Result.success` value\n /// containing the value that the child task returned,\n /// or a `Result.failure` value\n /// containing the error that the child task threw.\n ///\n /// - SeeAlso: `next()`\n @_alwaysEmitIntoClient\n public mutating func nextResult(isolation: isolated (any Actor)? = #isolation) async -> Result<ChildTaskResult, Failure>? {\n return try! await nextResultForABI()\n }\n\n /// A Boolean value that indicates whether the group has any remaining tasks.\n ///\n /// At the start of the body of a `withThrowingTaskGroup(of:returning:body:)` call,\n /// the task group is always empty.\n ///\n /// It's guaranteed to be empty when returning from that body\n /// because a task group waits for all child tasks to complete before returning.\n ///\n /// - Returns: `true` if the group has no pending tasks; otherwise `false`.\n public var isEmpty: Bool {\n _taskGroupIsEmpty(_group)\n }\n\n /// Cancel all of the remaining tasks in the group.\n ///\n /// If you add a task to a group after canceling the group,\n /// that task is canceled immediately after being added to the group.\n ///\n /// Immediately cancelled child tasks should therefore cooperatively check for and\n /// react to cancellation, e.g. by throwing an `CancellationError` at their\n /// earliest convenience, or otherwise handling the cancellation.\n ///\n /// There are no restrictions on where you can call this method.\n /// Code inside a child task or even another task can cancel a group,\n /// however one should be very careful to not keep a reference to the\n /// group longer than the `with...TaskGroup(...) { ... }` method body is executing.\n ///\n /// - SeeAlso: `Task.isCancelled`\n /// - SeeAlso: `ThrowingTaskGroup.isCancelled`\n public func cancelAll() {\n _taskGroupCancelAll(group: _group)\n }\n\n /// A Boolean value that indicates whether the group was canceled.\n ///\n /// To cancel a group, call the `ThrowingTaskGroup.cancelAll()` method.\n ///\n /// If the task that's currently running this group is canceled,\n /// the group is also implicitly canceled,\n /// which is also reflected in this property's value.\n public var isCancelled: Bool {\n return _taskGroupIsCancelled(group: _group)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable)\nextension ThrowingTaskGroup: Sendable { }\n\n/// ==== TaskGroup: AsyncSequence ----------------------------------------------\n\n@available(SwiftStdlib 5.1, *)\nextension TaskGroup: AsyncSequence {\n public typealias AsyncIterator = Iterator\n public typealias Element = ChildTaskResult\n\n public func makeAsyncIterator() -> Iterator {\n return Iterator(group: self)\n }\n\n /// A type that provides an iteration interface\n /// over the results of tasks added to the group.\n ///\n /// The elements returned by this iterator\n /// appear in the order that the tasks *completed*,\n /// not in the order that those tasks were added to the task group.\n ///\n /// This iterator terminates after all tasks have completed.\n /// After iterating over the results of each task,\n /// it's valid to make a new iterator for the task group,\n /// which you can use to iterate over the results of new tasks you add to the group.\n /// For example:\n ///\n /// group.addTask { 1 }\n /// for await r in group { print(r) }\n ///\n /// // Add a new child task and iterate again.\n /// group.addTask { 2 }\n /// for await r in group { print(r) }\n ///\n /// - SeeAlso: `TaskGroup.next()`\n @available(SwiftStdlib 5.1, *)\n public struct Iterator: AsyncIteratorProtocol {\n public typealias Element = ChildTaskResult\n\n @usableFromInline\n var group: TaskGroup<ChildTaskResult>\n\n @usableFromInline\n var finished: Bool = false\n\n // no public constructors\n init(group: TaskGroup<ChildTaskResult>) {\n self.group = group\n }\n\n /// Advances to and returns the result of the next child task.\n ///\n /// The elements returned from this method\n /// appear in the order that the tasks *completed*,\n /// not in the order that those tasks were added to the task group.\n /// After this method returns `nil`,\n /// this iterator is guaranteed to never produce more values.\n ///\n /// For more information about the iteration order and semantics,\n /// see `TaskGroup.next()`.\n ///\n /// - Returns: The value returned by the next child task that completes,\n /// or `nil` if there are no remaining child tasks,\n public mutating func next() async -> Element? {\n guard !finished else { return nil }\n guard let element = await group.next() else {\n finished = true\n return nil\n }\n return element\n }\n\n /// Advances to and returns the result of the next child task.\n ///\n /// The elements returned from this method\n /// appear in the order that the tasks *completed*,\n /// not in the order that those tasks were added to the task group.\n /// After this method returns `nil`,\n /// this iterator is guaranteed to never produce more values.\n ///\n /// For more information about the iteration order and semantics,\n /// see `TaskGroup.next()`.\n ///\n /// - Returns: The value returned by the next child task that completes,\n /// or `nil` if there are no remaining child tasks,\n @available(SwiftStdlib 6.0, *)\n public mutating func next(isolation actor: isolated (any Actor)?) async -> Element? {\n guard !finished else { return nil }\n guard let element = await group.next(isolation: actor) else {\n finished = true\n return nil\n }\n return element\n }\n\n public mutating func cancel() {\n finished = true\n group.cancelAll()\n }\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension ThrowingTaskGroup: AsyncSequence {\n public typealias AsyncIterator = Iterator\n public typealias Element = ChildTaskResult\n\n public func makeAsyncIterator() -> Iterator {\n return Iterator(group: self)\n }\n\n /// A type that provides an iteration interface\n /// over the results of tasks added to the group.\n ///\n /// The elements returned by this iterator\n /// appear in the order that the tasks *completed*,\n /// not in the order that those tasks were added to the task group.\n ///\n /// This iterator terminates after all tasks have completed successfully,\n /// or after any task completes by throwing an error.\n /// If a task completes by throwing an error,\n /// it doesn't return any further task results.\n /// After iterating over the results of each task,\n /// it's valid to make a new iterator for the task group,\n /// which you can use to iterate over the results of new tasks you add to the group.\n /// You can also make a new iterator to resume iteration\n /// after a child task throws an error.\n /// For example:\n ///\n /// group.addTask { 1 }\n /// group.addTask { throw SomeError }\n /// group.addTask { 2 }\n ///\n /// do {\n /// // Assuming the child tasks complete in order, this prints "1"\n /// // and then throws an error.\n /// for try await r in group { print(r) }\n /// } catch {\n /// // Resolve the error.\n /// }\n ///\n /// // Assuming the child tasks complete in order, this prints "2".\n /// for try await r in group { print(r) }\n ///\n /// - SeeAlso: `ThrowingTaskGroup.next()`\n @available(SwiftStdlib 5.1, *)\n public struct Iterator: AsyncIteratorProtocol {\n public typealias Element = ChildTaskResult\n\n @usableFromInline\n var group: ThrowingTaskGroup<ChildTaskResult, Failure>\n\n @usableFromInline\n var finished: Bool = false\n\n // no public constructors\n init(group: ThrowingTaskGroup<ChildTaskResult, Failure>) {\n self.group = group\n }\n\n /// Advances to and returns the result of the next child task.\n ///\n /// The elements returned from this method\n /// appear in the order that the tasks *completed*,\n /// not in the order that those tasks were added to the task group.\n /// After this method returns `nil`,\n /// this iterator is guaranteed to never produce more values.\n ///\n /// For more information about the iteration order and semantics,\n /// see `ThrowingTaskGroup.next()`\n ///\n /// - Throws: The error thrown by the next child task that completes.\n ///\n /// - Returns: The value returned by the next child task that completes,\n /// or `nil` if there are no remaining child tasks,\n public mutating func next() async throws -> Element? {\n guard !finished else { return nil }\n do {\n guard let element = try await group.next() else {\n finished = true\n return nil\n }\n return element\n } catch {\n finished = true\n throw error\n }\n }\n\n /// Advances to and returns the result of the next child task.\n ///\n /// The elements returned from this method\n /// appear in the order that the tasks *completed*,\n /// not in the order that those tasks were added to the task group.\n /// After this method returns `nil`,\n /// this iterator is guaranteed to never produce more values.\n ///\n /// For more information about the iteration order and semantics,\n /// see `ThrowingTaskGroup.next()`\n ///\n /// - Throws: The error thrown by the next child task that completes.\n ///\n /// - Returns: The value returned by the next child task that completes,\n /// or `nil` if there are no remaining child tasks,\n @available(SwiftStdlib 6.0, *)\n public mutating func next(isolation actor: isolated (any Actor)?) async throws(Failure) -> Element? {\n guard !finished else { return nil }\n do {\n guard let element = try await group.next(isolation: actor) else {\n finished = true\n return nil\n }\n return element\n } catch {\n finished = true\n throw error as! Failure\n }\n }\n \n public mutating func cancel() {\n finished = true\n group.cancelAll()\n }\n }\n}\n\n// ==== -----------------------------------------------------------------------\n// MARK: Runtime functions\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_taskGroup_destroy")\nfunc _taskGroupDestroy(group: __owned Builtin.RawPointer)\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_taskGroup_addPending")\n@usableFromInline\nfunc _taskGroupAddPendingTask(\n group: Builtin.RawPointer,\n unconditionally: Bool\n) -> Bool\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_taskGroup_cancelAll")\nfunc _taskGroupCancelAll(group: Builtin.RawPointer)\n\n/// Checks ONLY if the group was specifically canceled.\n/// The task itself being canceled must be checked separately.\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_taskGroup_isCancelled")\nfunc _taskGroupIsCancelled(group: Builtin.RawPointer) -> Bool\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_taskGroup_wait_next_throwing")\npublic func _taskGroupWaitNext<T>(group: Builtin.RawPointer) async throws -> T?\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_hasTaskGroupStatusRecord")\nfunc _taskHasTaskGroupStatusRecord() -> Bool\n\n@available(SwiftStdlib 6.0, *)\n@_silgen_name("swift_task_hasTaskExecutorStatusRecord")\nfunc _taskHasTaskExecutorStatusRecord() -> Bool\n\n@available(SwiftStdlib 5.1, *)\nenum PollStatus: Int {\n case empty = 0\n case waiting = 1\n case success = 2\n case error = 3\n}\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_taskGroup_isEmpty")\nfunc _taskGroupIsEmpty(\n _ group: Builtin.RawPointer\n) -> Bool\n\n\n// ==== TaskGroup Flags --------------------------------------------------------------\n\n/// Flags for task groups.\n///\n/// This is a port of the C++ FlagSet.\n@available(SwiftStdlib 5.8, *)\nstruct TaskGroupFlags {\n /// The actual bit representation of these flags.\n var bits: Int32 = 0\n\n /// The priority given to the job.\n var discardResults: Bool? {\n get {\n let value = (Int(bits) & 1 << 24)\n\n return value > 0\n }\n\n set {\n if newValue == true {\n bits = bits | 1 << 24\n } else {\n bits = (bits & ~(1 << 23))\n }\n }\n }\n}\n\n// ==== Task Creation Flags --------------------------------------------------\n\n/// Form task creation flags for use with the createAsyncTask builtins.\n@available(SwiftStdlib 5.8, *)\n@_alwaysEmitIntoClient\nfunc taskGroupCreateFlags(\n discardResults: Bool) -> Int {\n var bits = 0\n if discardResults {\n bits |= 1 << 8\n }\n return bits\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_TaskGroup.swift | cpp_apple_swift_stdlib_public_Concurrency_TaskGroup.swift | Swift | 39,562 | 0.95 | 0.110811 | 0.636364 | vue-tools | 500 | 2025-01-16T02:03:47.623261 | MIT | false | bbdf39915bd8fd792c3f0e2bddb8f84f |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n\n// Macros are disabled when Swift is built without swift-syntax.\n#if $Macros && hasAttribute(attached)\n\n/// Macro that introduces a ``TaskLocal-class`` binding.\n///\n/// For information about task-local bindings, see ``TaskLocal-class``.\n///\n/// - SeeAlso: ``TaskLocal-class``\n@available(SwiftStdlib 5.1, *)\n@attached(accessor)\n@attached(peer, names: prefixed(`$`))\npublic macro TaskLocal() =\n #externalMacro(module: "SwiftMacros", type: "TaskLocalMacro")\n\n#endif\n\n/// Wrapper type that defines a task-local value key.\n///\n/// A task-local value is a value that can be bound and read in the context of a\n/// ``Task``. It is implicitly carried with the task, and is accessible by any\n/// child tasks it creates (such as TaskGroup or `async let` created tasks).\n///\n/// ### Task-local declarations\n///\n/// Task locals must be declared as static properties or global properties, like this:\n///\n/// enum Example {\n/// @TaskLocal\n/// static var traceID: TraceID?\n/// }\n///\n/// // Global task local properties are supported since Swift 6.0:\n/// @TaskLocal\n/// var contextualNumber: Int = 12\n///\n/// ### Default values\n/// Reading a task local value when no value was bound to it results in returning\n/// its default value. For a task local declared as optional (such as e.g. `TraceID?`),\n/// this defaults to nil, however a different default value may be defined at declaration\n/// site of the task local, like this:\n///\n/// enum Example { \n/// @TaskLocal\n/// static var traceID: TraceID = TraceID.default\n/// }\n/// \n/// The default value is returned whenever the task-local is read\n/// from a context which either: has no task available to read the value from\n/// (e.g. a synchronous function, called without any asynchronous function in its call stack),\n/// or no value was bound within the scope of the current task or any of its parent tasks.\n///\n/// ### Reading task-local values\n/// Reading task local values is simple and looks the same as-if reading a normal\n/// static property:\n///\n/// guard let traceID = Example.traceID else {\n/// print("no trace id")\n/// return\n/// }\n/// print(traceID)\n///\n/// It is possible to perform task-local value reads from either asynchronous\n/// or synchronous functions. \n///\n/// ### Binding task-local values\n/// Task local values cannot be `set` directly and must instead be bound using\n/// the scoped `$traceID.withValue() { ... }` operation. The value is only bound\n/// for the duration of that scope, and is available to any child tasks which\n/// are created within that scope.\n///\n/// Detached tasks do not inherit task-local values, however tasks created using\n/// the `Task { ... }` initializer do inherit task-locals by copying them to the\n/// new asynchronous task, even though it is an un-structured task.\n///\n/// ### Using task local values outside of tasks\n/// It is possible to bind and read task local values outside of tasks.\n///\n/// This comes in handy within synchronous functions which are not guaranteed \n/// to be called from within a task. When binding a task-local value from \n/// outside of a task, the runtime will set a thread-local in which the same \n/// storage mechanism as used within tasks will be used. This means that you \n/// can reliably bind and read task local values without having to worry\n/// about the specific calling context, e.g.:\n///\n/// func enter() {\n/// Example.$traceID.withValue("1234") {\n/// read() // always "1234", regardless if enter() was called from inside a task or not:\n/// } \n/// }\n/// \n/// func read() -> String {\n/// if let value = Self.traceID {\n/// "\(value)" \n/// } else { \n/// "<no value>"\n/// }\n/// }\n///\n/// // 1) Call `enter` from non-Task code\n/// // e.g. synchronous main() or non-Task thread (e.g. a plain pthread)\n/// enter()\n///\n/// // 2) Call 'enter' from Task\n/// Task { \n/// enter()\n/// }\n///\n/// In either cases listed above, the binding and reading of the task-local value works as expected.\n///\n/// ### Examples\n///\n///\n/// enum Example {\n/// @TaskLocal\n/// static var traceID: TraceID?\n/// }\n/// \n/// func read() -> String {\n/// if let value = Self.traceID {\n/// "\(value)" \n/// } else { \n/// "<no value>"\n/// }\n/// }\n///\n/// await Example.$traceID.withValue(1234) { // bind the value\n/// print("traceID: \(Example.traceID)") // traceID: 1234\n/// read() // traceID: 1234\n///\n/// async let id = read() // async let child task, traceID: 1234\n///\n/// await withTaskGroup(of: String.self) { group in \n/// group.addTask { read() } // task group child task, traceID: 1234\n/// return await group.next()!\n/// }\n///\n/// Task { // unstructured tasks do inherit task locals by copying\n/// read() // traceID: 1234\n/// }\n///\n/// Task.detached { // detached tasks do not inherit task-local values\n/// read() // traceID: nil\n/// }\n/// }\n///\n/// - SeeAlso: ``TaskLocal()-macro``\n@available(SwiftStdlib 5.1, *)\npublic final class TaskLocal<Value: Sendable>: Sendable, CustomStringConvertible {\n let defaultValue: Value\n\n public init(wrappedValue defaultValue: Value) {\n self.defaultValue = defaultValue\n }\n\n @_alwaysEmitIntoClient\n var key: Builtin.RawPointer {\n unsafe unsafeBitCast(self, to: Builtin.RawPointer.self)\n }\n\n /// Gets the value currently bound to this task-local from the current task.\n ///\n /// If no current task is available in the context where this call is made,\n /// or if the task-local has no value bound, this will return the `defaultValue`\n /// of the task local.\n public func get() -> Value {\n guard let rawValue = unsafe _taskLocalValueGet(key: key) else {\n return self.defaultValue\n }\n\n // Take the value; The type should be correct by construction\n let storagePtr =\n unsafe rawValue.bindMemory(to: Value.self, capacity: 1)\n return unsafe UnsafeMutablePointer<Value>(mutating: storagePtr).pointee\n }\n\n /// Binds the task-local to the specific value for the duration of the asynchronous operation.\n ///\n /// The value is available throughout the execution of the operation closure,\n /// including any `get` operations performed by child-tasks created during the\n /// execution of the operation closure.\n ///\n /// If the same task-local is bound multiple times, be it in the same task, or\n /// in specific child tasks, the more specific (i.e. "deeper") binding is\n /// returned when the value is read.\n ///\n /// If the value is a reference type, it will be retained for the duration of\n /// the operation closure.\n @inlinable\n @discardableResult\n @available(SwiftStdlib 5.1, *)\n @backDeployed(before: SwiftStdlib 6.0)\n public func withValue<R>(_ valueDuringOperation: Value,\n operation: () async throws -> R,\n isolation: isolated (any Actor)? = #isolation,\n file: String = #fileID, line: UInt = #line) async rethrows -> R {\n return try await withValueImpl(\n valueDuringOperation,\n operation: operation,\n isolation: isolation,\n file: file, line: line)\n }\n\n // Note: hack to stage out @_unsafeInheritExecutor forms of various functions\n // in favor of #isolation. The _unsafeInheritExecutor_ prefix is meaningful\n // to the type checker.\n //\n // This function also doubles as an ABI-compatibility shim predating the\n // introduction of #isolation.\n @discardableResult\n @_unsafeInheritExecutor // ABI compatibility with Swift 5.1\n @available(SwiftStdlib 5.1, *)\n @_silgen_name("$ss9TaskLocalC9withValue_9operation4file4lineqd__x_qd__yYaKXESSSutYaKlF")\n public func _unsafeInheritExecutor_withValue<R>(\n _ valueDuringOperation: Value,\n operation: () async throws -> R,\n file: String = #fileID, line: UInt = #line\n ) async rethrows -> R {\n return try await withValueImpl(valueDuringOperation, operation: operation, file: file, line: line)\n }\n\n /// Implementation for withValue that consumes valueDuringOperation.\n ///\n /// Because _taskLocalValuePush and _taskLocalValuePop involve calls to\n /// swift_task_alloc/swift_task_dealloc respectively unbeknownst to the\n /// compiler, compiler-emitted calls to swift_task_de/alloc must be avoided\n /// in a function that calls them.\n ///\n /// A copy of valueDuringOperation is required because withValue borrows its\n /// argument but _taskLocalValuePush consumes its. Because\n /// valueDuringOperation is of generic type, its size is not generally known,\n /// so such a copy entails a stack allocation and a copy to that allocation.\n /// That stack traffic gets lowered to calls to\n /// swift_task_alloc/swift_task_deallloc.\n ///\n /// Split the calls _taskLocalValuePush/Pop from the compiler-emitted calls\n /// to swift_task_de/alloc for the copy as follows:\n /// - withValue contains the compiler-emitted calls swift_task_de/alloc.\n /// - withValueImpl contains the calls to _taskLocalValuePush/Pop\n @inlinable\n @discardableResult\n @available(SwiftStdlib 5.1, *)\n @backDeployed(before: SwiftStdlib 6.0)\n internal func withValueImpl<R>(_ valueDuringOperation: __owned Value,\n operation: () async throws -> R,\n isolation: isolated (any Actor)?,\n file: String = #fileID, line: UInt = #line) async rethrows -> R {\n _taskLocalValuePush(key: key, value: consume valueDuringOperation)\n defer { _taskLocalValuePop() }\n\n return try await operation()\n }\n\n @_silgen_name("$ss9TaskLocalC13withValueImpl_9operation4file4lineqd__xn_qd__yYaKXESSSutYaKlF")\n @inlinable\n @discardableResult\n @_unsafeInheritExecutor // internal for backwards compatibility; though may be able to be removed safely?\n @available(SwiftStdlib 5.1, *)\n internal func _unsafeInheritExecutor_withValueImpl<R>(\n _ valueDuringOperation: __owned Value,\n operation: () async throws -> R,\n file: String = #fileID, line: UInt = #line\n ) async rethrows -> R {\n _taskLocalValuePush(key: key, value: consume valueDuringOperation)\n defer { _taskLocalValuePop() }\n\n return try await operation()\n }\n\n\n /// Binds the task-local to the specific value for the duration of the\n /// synchronous operation.\n ///\n /// The value is available throughout the execution of the operation closure,\n /// including any `get` operations performed by child-tasks created during the\n /// execution of the operation closure.\n ///\n /// If the same task-local is bound multiple times, be it in the same task, or\n /// in specific child tasks, the "more specific" binding is returned when the\n /// value is read.\n ///\n /// If the value is a reference type, it will be retained for the duration of\n /// the operation closure.\n @inlinable\n @discardableResult\n public func withValue<R>(_ valueDuringOperation: Value, operation: () throws -> R,\n file: String = #fileID, line: UInt = #line) rethrows -> R {\n _taskLocalValuePush(key: key, value: valueDuringOperation)\n defer { _taskLocalValuePop() }\n\n return try operation()\n }\n\n public var projectedValue: TaskLocal<Value> {\n get {\n self\n }\n\n @available(*, unavailable, message: "use '$myTaskLocal.withValue(_:do:)' instead")\n set {\n fatalError("Illegal attempt to set a TaskLocal value, use `withValue(...) { ... }` instead.")\n }\n }\n\n // This subscript is used to enforce that the property wrapper may only be used\n // on static (or rather, "without enclosing instance") properties.\n // This is done by marking the `_enclosingInstance` as `Never` which informs\n // the type-checker that this property-wrapper never wants to have an enclosing\n // instance (it is impossible to declare a property wrapper inside the `Never`\n // type).\n @available(*, unavailable, message: "property wrappers cannot be instance members")\n public static subscript(\n _enclosingInstance object: Never,\n wrapped wrappedKeyPath: ReferenceWritableKeyPath<Never, Value>,\n storage storageKeyPath: ReferenceWritableKeyPath<Never, TaskLocal<Value>>\n ) -> Value {\n get {\n }\n }\n\n public var wrappedValue: Value {\n self.get()\n }\n\n public var description: String {\n "\(Self.self)(defaultValue: \(self.defaultValue))"\n }\n\n}\n\n// ==== ------------------------------------------------------------------------\n\n@available(SwiftStdlib 5.1, *)\n@usableFromInline\n@_silgen_name("swift_task_localValuePush")\nfunc _taskLocalValuePush<Value>(\n key: Builtin.RawPointer/*: Key*/,\n value: __owned Value\n) // where Key: TaskLocal\n\n@available(SwiftStdlib 5.1, *)\n@usableFromInline\n@_silgen_name("swift_task_localValuePop")\nfunc _taskLocalValuePop()\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_localValueGet")\nfunc _taskLocalValueGet(\n key: Builtin.RawPointer/*Key*/\n) -> UnsafeMutableRawPointer? // where Key: TaskLocal\n\n@available(SwiftStdlib 5.1, *)\n@_silgen_name("swift_task_localsCopyTo")\nfunc _taskLocalsCopy(\n to target: Builtin.NativeObject\n)\n\n// ==== Checks -----------------------------------------------------------------\n\n@usableFromInline\n@available(SwiftStdlib 5.1, *)\n@available(*, deprecated, message: "The situation diagnosed by this is not handled gracefully rather than by crashing")\nfunc _checkIllegalTaskLocalBindingWithinWithTaskGroup(file: String, line: UInt) {\n if _taskHasTaskGroupStatusRecord() {\n unsafe file.withCString { _fileStart in\n unsafe _reportIllegalTaskLocalBindingWithinWithTaskGroup(\n _fileStart, file.count, true, line)\n }\n }\n}\n\n@usableFromInline\n@available(SwiftStdlib 5.1, *)\n@available(*, deprecated, message: "The situation diagnosed by this is not handled gracefully rather than by crashing")\n@_silgen_name("swift_task_reportIllegalTaskLocalBindingWithinWithTaskGroup")\nfunc _reportIllegalTaskLocalBindingWithinWithTaskGroup(\n _ _filenameStart: UnsafePointer<Int8>,\n _ _filenameLength: Int,\n _ _filenameIsASCII: Bool,\n _ _line: UInt)\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_TaskLocal.swift | cpp_apple_swift_stdlib_public_Concurrency_TaskLocal.swift | Swift | 14,697 | 0.95 | 0.076142 | 0.590028 | python-kit | 718 | 2023-12-25T07:50:58.076259 | MIT | false | 065892af19314131cac6af3d9fd476dc |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 5.1, *)\n@_unavailableInEmbedded\nextension Task where Success == Never, Failure == Never {\n @available(*, deprecated, renamed: "Task.sleep(nanoseconds:)")\n /// Suspends the current task for at least the given duration\n /// in nanoseconds.\n ///\n /// This function doesn't block the underlying thread.\n public static func sleep(_ duration: UInt64) async {\n return await Builtin.withUnsafeContinuation {\n (continuation: Builtin.RawUnsafeContinuation) -> Void in\n let job = _taskCreateNullaryContinuationJob(\n priority: Int(Task.currentPriority.rawValue),\n continuation: continuation)\n\n if #available(SwiftStdlib 6.2, *) {\n #if !$Embedded\n if let executor = Task.currentSchedulableExecutor {\n executor.enqueue(ExecutorJob(context: job),\n after: .nanoseconds(duration),\n clock: .continuous)\n return\n }\n #endif\n }\n\n // If there is no current schedulable executor, fall back to\n // _enqueueJobGlobalWithDelay()\n _enqueueJobGlobalWithDelay(duration, job)\n }\n }\n\n /// The type of continuation used in the implementation of\n /// sleep(nanoseconds:).\n typealias SleepContinuation = UnsafeContinuation<(), Error>\n\n /// Describes the state of a sleep() operation.\n @unsafe enum SleepState {\n /// The sleep continuation has not yet begun.\n case notStarted\n\n // The sleep continuation has been created and is available here.\n case activeContinuation(SleepContinuation)\n\n /// The sleep has finished.\n case finished\n\n /// The sleep was canceled.\n case cancelled\n\n /// The sleep was canceled before it even got started.\n case cancelledBeforeStarted\n\n /// Decode sleep state from the word of storage.\n init(word: Builtin.Word) {\n switch UInt(word) & 0x03 {\n case 0:\n let continuationBits = UInt(word) & ~0x03\n if continuationBits == 0 {\n unsafe self = unsafe .notStarted\n } else {\n let continuation = unsafe unsafeBitCast(\n continuationBits, to: SleepContinuation.self)\n unsafe self = unsafe .activeContinuation(continuation)\n }\n\n case 1:\n unsafe self = unsafe .finished\n\n case 2:\n unsafe self = unsafe .cancelled\n\n case 3:\n unsafe self = unsafe .cancelledBeforeStarted\n\n default:\n fatalError("Bitmask failure")\n }\n }\n\n /// Decode sleep state by loading from the given pointer\n init(loading wordPtr: UnsafeMutablePointer<Builtin.Word>) {\n unsafe self.init(word: Builtin.atomicload_seqcst_Word(wordPtr._rawValue))\n }\n\n /// Encode sleep state into a word of storage.\n var word: UInt {\n switch unsafe self {\n case .notStarted:\n return 0\n\n case .activeContinuation(let continuation):\n let continuationBits = unsafe unsafeBitCast(continuation, to: UInt.self)\n return continuationBits\n\n case .finished:\n return 1\n\n case .cancelled:\n return 2\n\n case .cancelledBeforeStarted:\n return 3\n }\n }\n }\n\n /// A simple wrapper for a pointer to heap allocated storage of a `SleepState`\n /// value. This wrapper is `Sendable` because it facilitates atomic load and\n /// exchange operations on the underlying storage. However, this wrapper is also\n /// _unsafe_ because the owner must manually deallocate the token once it is no\n /// longer needed.\n @unsafe struct UnsafeSleepStateToken: @unchecked Sendable {\n let wordPtr: UnsafeMutablePointer<Builtin.Word>\n\n /// Allocates the underlying storage and sets the value to `.notStarted`.\n init() {\n unsafe wordPtr = .allocate(capacity: 1)\n unsafe Builtin.atomicstore_seqcst_Word(\n wordPtr._rawValue, SleepState.notStarted.word._builtinWordValue)\n }\n\n /// Atomically loads the current state.\n func load() -> SleepState {\n return unsafe SleepState(word: Builtin.atomicload_seqcst_Word(wordPtr._rawValue))\n }\n\n /// Attempts to atomically set the stored value to `desired` if the current\n /// value is equal to `expected`. Returns true if the exchange was successful.\n func exchange(expected: SleepState, desired: SleepState) -> Bool {\n let (_, won) = unsafe Builtin.cmpxchg_seqcst_seqcst_Word(\n wordPtr._rawValue,\n expected.word._builtinWordValue,\n desired.word._builtinWordValue)\n return Bool(_builtinBooleanLiteral: won)\n }\n\n /// Deallocates the underlying storage.\n func deallocate() {\n unsafe wordPtr.deallocate()\n }\n }\n\n /// Called when the sleep(nanoseconds:) operation woke up without being\n /// canceled.\n static func onSleepWake(_ token: UnsafeSleepStateToken) {\n while true {\n let state = unsafe token.load()\n switch unsafe state {\n case .notStarted:\n fatalError("Cannot wake before we even started")\n\n case .activeContinuation(let continuation):\n // We have an active continuation, so try to transition to the\n // "finished" state.\n if unsafe token.exchange(expected: state, desired: .finished) {\n // The sleep finished, so invoke the continuation: we're done.\n unsafe continuation.resume()\n return\n }\n\n // Try again!\n continue\n\n case .finished:\n fatalError("Already finished normally, can't do that again")\n\n case .cancelled:\n // The task was cancelled, which means the continuation was\n // called by the cancellation handler. We need to deallocate the token\n // because it was left over for this task to complete.\n unsafe token.deallocate()\n return\n\n case .cancelledBeforeStarted:\n // Nothing to do;\n return\n }\n }\n }\n\n /// Called when the sleep(nanoseconds:) operation has been canceled before\n /// the sleep completed.\n static func onSleepCancel(_ token: UnsafeSleepStateToken) {\n while true {\n let state = unsafe token.load()\n switch unsafe state {\n case .notStarted:\n // We haven't started yet, so try to transition to the cancelled-before\n // started state.\n if unsafe token.exchange(expected: state, desired: .cancelledBeforeStarted) {\n return\n }\n\n // Try again!\n continue\n\n case .activeContinuation(let continuation):\n // We have an active continuation, so try to transition to the\n // "cancelled" state.\n if unsafe token.exchange(expected: state, desired: .cancelled) {\n // We recorded the task cancellation before the sleep finished, so\n // invoke the continuation with the cancellation error.\n unsafe continuation.resume(throwing: _Concurrency.CancellationError())\n return\n }\n\n // Try again!\n continue\n\n case .finished, .cancelled, .cancelledBeforeStarted:\n // The operation already finished, so there is nothing more to do.\n return\n }\n }\n }\n\n /// Suspends the current task for at least the given duration\n /// in nanoseconds.\n ///\n /// If the task is canceled before the time ends,\n /// this function throws `CancellationError`.\n ///\n /// This function doesn't block the underlying thread.\n public static func sleep(nanoseconds duration: UInt64) async throws {\n // Create a token which will initially have the value "not started", which\n // means the continuation has neither been created nor completed.\n let token = unsafe UnsafeSleepStateToken()\n\n do {\n // Install a cancellation handler to resume the continuation by\n // throwing CancellationError.\n try await withTaskCancellationHandler {\n let _: () = try unsafe await withUnsafeThrowingContinuation { continuation in\n while true {\n let state = unsafe token.load()\n switch unsafe state {\n case .notStarted:\n // Try to swap in the continuation state.\n let newState = unsafe SleepState.activeContinuation(continuation)\n if unsafe !token.exchange(expected: state, desired: newState) {\n // Keep trying!\n continue\n }\n\n // Create a task that resumes the continuation normally if it\n // finishes first. Enqueue it directly with the delay, so it fires\n // when we're done sleeping.\n let sleepTaskFlags = taskCreateFlags(\n priority: nil, isChildTask: false, copyTaskLocals: false,\n inheritContext: false, enqueueJob: false,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n let (sleepTask, _) = Builtin.createAsyncTask(sleepTaskFlags) {\n unsafe onSleepWake(token)\n }\n\n let job = Builtin.convertTaskToJob(sleepTask)\n\n if #available(SwiftStdlib 6.2, *) {\n #if !$Embedded\n if let executor = Task.currentSchedulableExecutor {\n executor.enqueue(ExecutorJob(context: job),\n after: .nanoseconds(duration),\n clock: .continuous)\n return\n }\n #endif\n }\n\n // If there is no current schedulable executor, fall back to\n // _enqueueJobGlobalWithDelay()\n _enqueueJobGlobalWithDelay(duration, job)\n return\n\n case .activeContinuation, .finished:\n fatalError("Impossible to have multiple active continuations")\n\n case .cancelled:\n fatalError("Impossible to have cancelled before we began")\n\n case .cancelledBeforeStarted:\n // Finish the continuation normally. We'll throw later, after\n // we clean up.\n unsafe continuation.resume()\n return\n }\n }\n }\n } onCancel: {\n unsafe onSleepCancel(token)\n }\n\n // Determine whether we got cancelled before we even started.\n let cancelledBeforeStarted: Bool\n switch unsafe token.load() {\n case .notStarted, .activeContinuation, .cancelled:\n fatalError("Invalid state for non-cancelled sleep task")\n\n case .cancelledBeforeStarted:\n cancelledBeforeStarted = true\n\n case .finished:\n cancelledBeforeStarted = false\n }\n\n // We got here without being cancelled, so deallocate the storage for\n // the flag word and continuation.\n unsafe token.deallocate()\n\n // If we got cancelled before we even started, through the cancellation\n // error now.\n if cancelledBeforeStarted {\n throw _Concurrency.CancellationError()\n }\n } catch {\n // The task was cancelled; propagate the error. The "on wake" task is\n // responsible for deallocating the flag word and continuation, if it's\n // still running.\n throw error\n }\n }\n}\n#else\n@available(SwiftStdlib 5.1, *)\n@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\nextension Task where Success == Never, Failure == Never {\n @available(SwiftStdlib 5.1, *)\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public static func sleep(_ duration: UInt64) async {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n @available(SwiftStdlib 5.1, *)\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public static func sleep(nanoseconds duration: UInt64) async throws {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n}\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_TaskSleep.swift | cpp_apple_swift_stdlib_public_Concurrency_TaskSleep.swift | Swift | 12,311 | 0.95 | 0.124294 | 0.310231 | python-kit | 124 | 2024-02-27T19:47:45.491716 | GPL-3.0 | false | e55b873febbd2f13a3bd7eefa5c284f2 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Swift\n\n#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY\n@available(SwiftStdlib 5.7, *)\nfileprivate func timestamp<C: Clock>(for instant: C.Instant, clock: C)\n -> (clockID: _ClockID, seconds: Int64, nanoseconds: Int64) {\n var clockID: _ClockID\n if #available(SwiftStdlib 6.2, *) {\n if clock.traits.contains(.continuous) {\n clockID = .continuous\n } else {\n clockID = .suspending\n }\n } else {\n Builtin.unreachable()\n }\n\n var seconds: Int64 = 0\n var nanoseconds: Int64 = 0\n unsafe _getTime(seconds: &seconds,\n nanoseconds: &nanoseconds,\n clock: clockID.rawValue)\n\n let delta: Swift.Duration\n if #available(SwiftStdlib 6.2, *) {\n delta = clock.convert(from: clock.now.duration(to: instant))!\n } else {\n Builtin.unreachable()\n }\n\n let (deltaSeconds, deltaAttoseconds) = delta.components\n let deltaNanoseconds = deltaAttoseconds / 1_000_000_000\n seconds += deltaSeconds\n nanoseconds += deltaNanoseconds\n if nanoseconds > 1_000_000_000 {\n seconds += 1\n nanoseconds -= 1_000_000_000\n }\n\n return (clockID: clockID,\n seconds: Int64(seconds),\n nanoseconds: Int64(nanoseconds))\n}\n\n@available(SwiftStdlib 5.7, *)\n@_unavailableInEmbedded\nextension Task where Success == Never, Failure == Never {\n @available(SwiftStdlib 5.7, *)\n internal static func _sleep<C: Clock>(\n until instant: C.Instant,\n tolerance: C.Duration?,\n clock: C\n ) async throws {\n // Create a token which will initially have the value "not started", which\n // means the continuation has neither been created nor completed.\n let token = unsafe UnsafeSleepStateToken()\n\n do {\n // Install a cancellation handler to resume the continuation by\n // throwing CancellationError.\n try await withTaskCancellationHandler {\n let _: () = try unsafe await withUnsafeThrowingContinuation { continuation in\n while true {\n let state = unsafe token.load()\n switch unsafe state {\n case .notStarted:\n // Try to swap in the continuation word.\n let newState = unsafe SleepState.activeContinuation(continuation)\n if unsafe !token.exchange(expected: state, desired: newState) {\n // Keep trying!\n continue\n }\n\n // Create a task that resumes the continuation normally if it\n // finishes first. Enqueue it directly with the delay, so it fires\n // when we're done sleeping.\n let sleepTaskFlags = taskCreateFlags(\n priority: nil, isChildTask: false, copyTaskLocals: false,\n inheritContext: false, enqueueJob: false,\n addPendingGroupTaskUnconditionally: false,\n isDiscardingTask: false, isSynchronousStart: false)\n let (sleepTask, _) = Builtin.createAsyncTask(sleepTaskFlags) {\n unsafe onSleepWake(token)\n }\n\n let job = Builtin.convertTaskToJob(sleepTask)\n\n if #available(SwiftStdlib 6.2, *) {\n #if !$Embedded\n if let executor = Task.currentSchedulableExecutor {\n executor.enqueue(ExecutorJob(context: job),\n at: instant,\n tolerance: tolerance,\n clock: clock)\n return\n }\n #endif\n } else {\n Builtin.unreachable()\n }\n\n // If there is no current schedulable executor, fall back to\n // calling _enqueueJobGlobalWithDeadline().\n let (clockID, seconds, nanoseconds) = timestamp(for: instant,\n clock: clock)\n let toleranceSeconds: Int64\n let toleranceNanoseconds: Int64\n if #available(SwiftStdlib 6.2, *) {\n if let tolerance = tolerance,\n let components = clock.convert(from: tolerance)?.components {\n toleranceSeconds = components.seconds\n toleranceNanoseconds = components.attoseconds / 1_000_000_000\n } else {\n toleranceSeconds = 0\n toleranceNanoseconds = -1\n }\n } else {\n Builtin.unreachable()\n }\n\n if #available(SwiftStdlib 5.9, *) {\n _enqueueJobGlobalWithDeadline(\n seconds, nanoseconds,\n toleranceSeconds, toleranceNanoseconds,\n clockID.rawValue, UnownedJob(context: job))\n } else {\n Builtin.unreachable()\n }\n return\n\n case .activeContinuation, .finished:\n fatalError("Impossible to have multiple active continuations")\n\n case .cancelled:\n fatalError("Impossible to have cancelled before we began")\n\n case .cancelledBeforeStarted:\n // Finish the continuation normally. We'll throw later, after\n // we clean up.\n unsafe continuation.resume()\n return\n }\n }\n }\n } onCancel: {\n unsafe onSleepCancel(token)\n }\n\n // Determine whether we got cancelled before we even started.\n let cancelledBeforeStarted: Bool\n switch unsafe token.load() {\n case .notStarted, .activeContinuation, .cancelled:\n fatalError("Invalid state for non-cancelled sleep task")\n\n case .cancelledBeforeStarted:\n cancelledBeforeStarted = true\n\n case .finished:\n cancelledBeforeStarted = false\n }\n\n // We got here without being cancelled, so deallocate the storage for\n // the flag word and continuation.\n unsafe token.deallocate()\n\n // If we got cancelled before we even started, through the cancellation\n // error now.\n if cancelledBeforeStarted {\n throw _Concurrency.CancellationError()\n }\n } catch {\n // The task was cancelled; propagate the error. The "on wake" task is\n // responsible for deallocating the flag word and continuation, if it's\n // still running.\n throw error\n }\n }\n\n #if !$Embedded\n /// Suspends the current task until the given deadline within a tolerance.\n ///\n /// If the task is canceled before the time ends, this function throws\n /// `CancellationError`.\n ///\n /// This function doesn't block the underlying thread.\n ///\n /// try await Task.sleep(until: .now + .seconds(3))\n ///\n @available(SwiftStdlib 5.7, *)\n public static func sleep<C: Clock>(\n until deadline: C.Instant,\n tolerance: C.Instant.Duration? = nil,\n clock: C = .continuous\n ) async throws {\n try await clock.sleep(until: deadline, tolerance: tolerance)\n }\n\n /// Suspends the current task for the given duration.\n ///\n /// If the task is cancelled before the time ends, this function throws\n /// `CancellationError`.\n ///\n /// This function doesn't block the underlying thread.\n ///\n /// try await Task.sleep(for: .seconds(3))\n ///\n @available(SwiftStdlib 5.7, *)\n @_alwaysEmitIntoClient\n public static func sleep<C: Clock>(\n for duration: C.Instant.Duration,\n tolerance: C.Instant.Duration? = nil,\n clock: C = .continuous\n ) async throws {\n try await clock.sleep(for: duration, tolerance: tolerance)\n }\n #endif\n}\n#else\n@available(SwiftStdlib 5.7, *)\n@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\nextension Task where Success == Never, Failure == Never {\n @available(SwiftStdlib 5.7, *)\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n public static func sleep<C: Clock>(\n until deadline: C.Instant,\n tolerance: C.Instant.Duration? = nil,\n clock: C = .continuous\n ) async throws {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n @available(SwiftStdlib 5.7, *)\n @available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")\n @_alwaysEmitIntoClient\n public static func sleep<C: Clock>(\n for duration: C.Instant.Duration,\n tolerance: C.Instant.Duration? = nil,\n clock: C = .continuous\n ) async throws {\n fatalError("Unavailable in task-to-thread concurrency model")\n }\n}\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_Concurrency_TaskSleepDuration.swift | cpp_apple_swift_stdlib_public_Concurrency_TaskSleepDuration.swift | Swift | 8,910 | 0.95 | 0.165354 | 0.246753 | vue-tools | 250 | 2025-06-04T15:20:08.556703 | BSD-3-Clause | false | b95bb07fc46e9b7ed219b65d132a7afd |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Returns the lesser of two comparable values.\n///\n/// - Parameters:\n/// - x: A value to compare.\n/// - y: Another value to compare.\n/// - Returns: The lesser of `x` and `y`. If `x` is equal to `y`, returns `x`.\n@inlinable // protocol-only\npublic func min<T: Comparable>(_ x: T, _ y: T) -> T {\n // In case `x == y` we pick `x`.\n // This preserves any pre-existing order in case `T` has identity,\n // which is important for e.g. the stability of sorting algorithms.\n // `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`.\n return y < x ? y : x\n}\n\n/// Returns the least argument passed.\n///\n/// - Parameters:\n/// - x: A value to compare.\n/// - y: Another value to compare.\n/// - z: A third value to compare.\n/// - rest: Zero or more additional values.\n/// - Returns: The least of all the arguments. If there are multiple equal\n/// least arguments, the result is the first one.\n@inlinable // protocol-only\npublic func min<T: Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {\n var minValue = min(min(x, y), z)\n // In case `value == minValue`, we pick `minValue`. See min(_:_:).\n for value in rest where value < minValue {\n minValue = value\n }\n return minValue\n}\n\n/// Returns the greater of two comparable values.\n///\n/// - Parameters:\n/// - x: A value to compare.\n/// - y: Another value to compare.\n/// - Returns: The greater of `x` and `y`. If `x` is equal to `y`, returns `y`.\n@inlinable // protocol-only\npublic func max<T: Comparable>(_ x: T, _ y: T) -> T {\n // In case `x == y`, we pick `y`. See min(_:_:).\n return y >= x ? y : x\n}\n\n/// Returns the greatest argument passed.\n///\n/// - Parameters:\n/// - x: A value to compare.\n/// - y: Another value to compare.\n/// - z: A third value to compare.\n/// - rest: Zero or more additional values.\n/// - Returns: The greatest of all the arguments. If there are multiple equal\n/// greatest arguments, the result is the last one.\n@inlinable // protocol-only\npublic func max<T: Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {\n var maxValue = max(max(x, y), z)\n // In case `value == maxValue`, we pick `value`. See min(_:_:).\n for value in rest where value >= maxValue {\n maxValue = value\n }\n return maxValue\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Algorithm.swift | cpp_apple_swift_stdlib_public_core_Algorithm.swift | Swift | 2,752 | 0.95 | 0.065789 | 0.666667 | awesome-app | 120 | 2025-02-21T14:56:51.408407 | BSD-3-Clause | false | e1b66f81d2091a2adf6e9287e66a42a1 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A value that has a custom representation in `AnyHashable`.\n///\n/// `Self` should also conform to `Hashable`.\n@_unavailableInEmbedded\npublic protocol _HasCustomAnyHashableRepresentation {\n /// Returns a custom representation of `self` as `AnyHashable`.\n /// If returns nil, the default representation is used.\n ///\n /// If your custom representation is a class instance, it\n /// needs to be boxed into `AnyHashable` using the static\n /// type that introduces the `Hashable` conformance.\n ///\n /// class Base: Hashable {}\n /// class Derived1: Base {}\n /// class Derived2: Base, _HasCustomAnyHashableRepresentation {\n /// func _toCustomAnyHashable() -> AnyHashable? {\n /// // `Derived2` is canonicalized to `Derived1`.\n /// let customRepresentation = Derived1()\n ///\n /// // Wrong:\n /// // return AnyHashable(customRepresentation)\n ///\n /// // Correct:\n /// return AnyHashable(customRepresentation as Base)\n /// }\n __consuming func _toCustomAnyHashable() -> AnyHashable?\n}\n\n@usableFromInline\n@_unavailableInEmbedded\ninternal protocol _AnyHashableBox {\n var _canonicalBox: _AnyHashableBox { get }\n\n /// Determine whether values in the boxes are equivalent.\n ///\n /// - Precondition: `self` and `box` are in canonical form.\n /// - Returns: `nil` to indicate that the boxes store different types, so\n /// no comparison is possible. Otherwise, contains the result of `==`.\n func _isEqual(to box: _AnyHashableBox) -> Bool?\n var _hashValue: Int { get }\n func _hash(into hasher: inout Hasher)\n func _rawHashValue(_seed: Int) -> Int\n\n var _base: Any { get }\n func _unbox<T: Hashable>() -> T?\n func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool\n}\n\n@_unavailableInEmbedded\nextension _AnyHashableBox {\n var _canonicalBox: _AnyHashableBox {\n return self\n }\n}\n\n@_unavailableInEmbedded\ninternal struct _ConcreteHashableBox<Base: Hashable>: _AnyHashableBox {\n internal var _baseHashable: Base\n\n internal init(_ base: Base) {\n self._baseHashable = base\n }\n\n internal func _unbox<T: Hashable>() -> T? {\n return (self as _AnyHashableBox as? _ConcreteHashableBox<T>)?._baseHashable\n }\n\n internal func _isEqual(to rhs: _AnyHashableBox) -> Bool? {\n if let rhs: Base = rhs._unbox() {\n return _baseHashable == rhs\n }\n return nil\n }\n\n internal var _hashValue: Int {\n return _baseHashable.hashValue\n }\n\n func _hash(into hasher: inout Hasher) {\n _baseHashable.hash(into: &hasher)\n }\n\n func _rawHashValue(_seed: Int) -> Int {\n return _baseHashable._rawHashValue(seed: _seed)\n }\n\n internal var _base: Any {\n return _baseHashable\n }\n\n internal\n func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool {\n guard let value = _baseHashable as? T else { return false }\n unsafe result.initialize(to: value)\n return true\n }\n}\n\n/// A type-erased hashable value.\n///\n/// The `AnyHashable` type forwards equality comparisons and hashing operations\n/// to an underlying hashable value, hiding the type of the wrapped value.\n///\n/// Where conversion using `as` or `as?` is possible between two types (such as\n/// `Int` and `NSNumber`), `AnyHashable` uses a canonical representation of the\n/// type-erased value so that instances wrapping the same value of either type\n/// compare as equal. For example, `AnyHashable(42)` compares as equal to\n/// `AnyHashable(42 as NSNumber)`.\n///\n/// You can store mixed-type keys in dictionaries and other collections that\n/// require `Hashable` conformance by wrapping mixed-type keys in\n/// `AnyHashable` instances:\n///\n/// let descriptions: [AnyHashable: Any] = [\n/// 42: "an Int",\n/// 43 as Int8: "an Int8",\n/// ["a", "b"] as Set: "a set of strings"\n/// ]\n/// print(descriptions[42]!) // prints "an Int"\n/// print(descriptions[42 as Int8]!) // prints "an Int"\n/// print(descriptions[43 as Int8]!) // prints "an Int8"\n/// print(descriptions[44]) // prints "nil"\n/// print(descriptions[["a", "b"] as Set]!) // prints "a set of strings"\n///\n/// Note that `AnyHashable` does not guarantee that it preserves the hash\n/// encoding of wrapped values. Do not rely on `AnyHashable` generating such\n/// compatible hashes, as the hash encoding that it uses may change between any\n/// two releases of the standard library.\n@frozen\n@_unavailableInEmbedded\npublic struct AnyHashable {\n internal var _box: _AnyHashableBox\n\n internal init(_box box: _AnyHashableBox) {\n self._box = box\n }\n\n /// Creates a type-erased hashable value that wraps the given instance.\n ///\n /// - Parameter base: A hashable value to wrap.\n @_specialize(where H == String)\n @_unavailableInEmbedded\n public init<H: Hashable>(_ base: H) {\n if H.self == String.self {\n self.init(_box: _ConcreteHashableBox(base))\n return\n }\n \n if let custom =\n (base as? _HasCustomAnyHashableRepresentation)?._toCustomAnyHashable() {\n self = custom\n return\n }\n\n self.init(_box: _ConcreteHashableBox(false)) // Dummy value\n unsafe _withUnprotectedUnsafeMutablePointer(to: &self) {\n unsafe _makeAnyHashableUpcastingToHashableBaseType(\n base,\n storingResultInto: $0)\n }\n }\n\n internal init<H: Hashable>(_usingDefaultRepresentationOf base: H) {\n self._box = _ConcreteHashableBox(base)\n }\n\n /// The value wrapped by this instance.\n ///\n /// The `base` property can be cast back to its original type using one of\n /// the type casting operators (`as?`, `as!`, or `as`).\n ///\n /// let anyMessage = AnyHashable("Hello world!")\n /// if let unwrappedMessage = anyMessage.base as? String {\n /// print(unwrappedMessage)\n /// }\n /// // Prints "Hello world!"\n public var base: Any {\n return _box._base\n }\n\n /// Perform a downcast directly on the internal boxed representation.\n ///\n /// This avoids the intermediate re-boxing we would get if we just did\n /// a downcast on `base`.\n internal\n func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool {\n // Attempt the downcast.\n if unsafe _box._downCastConditional(into: result) { return true }\n\n #if _runtime(_ObjC)\n // Bridge to Objective-C and then attempt the cast from there.\n // FIXME: This should also work without the Objective-C runtime.\n if let value = _bridgeAnythingToObjectiveC(_box._base) as? T {\n unsafe result.initialize(to: value)\n return true\n }\n #endif\n\n return false\n }\n}\n\n@available(*, unavailable)\nextension AnyHashable: Sendable {}\n\n@_unavailableInEmbedded\nextension AnyHashable: Equatable {\n /// Returns a Boolean value indicating whether two type-erased hashable\n /// instances wrap the same value.\n ///\n /// `AnyHashable` considers bridged counterparts (such as a `String` and an\n /// `NSString`) of the same value to be equivalent when type-erased. If those\n /// compatible types use different definitions for equality, values that were\n /// originally distinct might compare as equal when they are converted to\n /// `AnyHashable`:\n ///\n /// let string1 = "café"\n /// let string2 = "cafe\u{301}" // U+301 COMBINING ACUTE ACCENT\n /// let nsString1 = string1 as NSString\n /// let nsString2 = string2 as NSString\n /// let typeErased1 = nsString1 as AnyHashable\n /// let typeErased2 = nsString2 as AnyHashable\n /// print(string1 == string2) // prints "true"\n /// print(nsString1 == nsString2) // prints "false"\n /// print(typeErased1 == typeErased2) // prints "true"\n ///\n /// - Parameters:\n /// - lhs: A type-erased hashable value.\n /// - rhs: Another type-erased hashable value.\n public static func == (lhs: AnyHashable, rhs: AnyHashable) -> Bool {\n return lhs._box._canonicalBox._isEqual(to: rhs._box._canonicalBox) ?? false\n }\n}\n\n@_unavailableInEmbedded\nextension AnyHashable: Hashable {\n public var hashValue: Int {\n return _box._canonicalBox._hashValue\n }\n\n public func hash(into hasher: inout Hasher) {\n _box._canonicalBox._hash(into: &hasher)\n }\n\n public func _rawHashValue(seed: Int) -> Int {\n return _box._canonicalBox._rawHashValue(_seed: seed)\n }\n}\n\n@_unavailableInEmbedded\nextension AnyHashable: CustomStringConvertible {\n public var description: String {\n return String(describing: base)\n }\n}\n\n@_unavailableInEmbedded\nextension AnyHashable: CustomDebugStringConvertible {\n public var debugDescription: String {\n return "AnyHashable(" + String(reflecting: base) + ")"\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension AnyHashable: CustomReflectable {\n public var customMirror: Mirror {\n return Mirror(\n self,\n children: ["value": base])\n }\n}\n#endif\n\n@_unavailableInEmbedded\n@available(SwiftStdlib 5.5, *)\nextension AnyHashable: _HasCustomAnyHashableRepresentation {\n}\n\n@_unavailableInEmbedded\nextension AnyHashable {\n @_alwaysEmitIntoClient\n public __consuming func _toCustomAnyHashable() -> AnyHashable? {\n return self\n }\n}\n\n/// Returns a default (non-custom) representation of `self`\n/// as `AnyHashable`.\n///\n/// Completely ignores the `_HasCustomAnyHashableRepresentation`\n/// conformance, if it exists.\n/// Called by AnyHashableSupport.cpp.\n@_silgen_name("_swift_makeAnyHashableUsingDefaultRepresentation")\n@_unavailableInEmbedded\ninternal func _makeAnyHashableUsingDefaultRepresentation<H: Hashable>(\n of value: H,\n storingResultInto result: UnsafeMutablePointer<AnyHashable>\n) {\n unsafe result.pointee = AnyHashable(_usingDefaultRepresentationOf: value)\n}\n\n/// Provided by AnyHashable.cpp.\n@_silgen_name("_swift_makeAnyHashableUpcastingToHashableBaseType")\n@_unavailableInEmbedded\ninternal func _makeAnyHashableUpcastingToHashableBaseType<H: Hashable>(\n _ value: H,\n storingResultInto result: UnsafeMutablePointer<AnyHashable>\n)\n\n@inlinable\n@_unavailableInEmbedded\npublic // COMPILER_INTRINSIC\nfunc _convertToAnyHashable<H: Hashable>(_ value: H) -> AnyHashable {\n return AnyHashable(value)\n}\n\n/// Called by the casting machinery.\n@_silgen_name("_swift_convertToAnyHashableIndirect")\n@_unavailableInEmbedded\ninternal func _convertToAnyHashableIndirect<H: Hashable>(\n _ value: H,\n _ target: UnsafeMutablePointer<AnyHashable>\n) {\n unsafe target.initialize(to: AnyHashable(value))\n}\n\n/// Called by the casting machinery.\n@_silgen_name("_swift_anyHashableDownCastConditionalIndirect")\n@_unavailableInEmbedded\ninternal func _anyHashableDownCastConditionalIndirect<T>(\n _ value: UnsafePointer<AnyHashable>,\n _ target: UnsafeMutablePointer<T>\n) -> Bool {\n return unsafe value.pointee._downCastConditional(into: target)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_AnyHashable.swift | cpp_apple_swift_stdlib_public_core_AnyHashable.swift | Swift | 11,180 | 0.95 | 0.048991 | 0.402597 | awesome-app | 693 | 2023-10-17T10:04:00.618156 | BSD-3-Clause | false | 1635e018ab44baef760e683e75437145 |
//===--- Array.swift ------------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Three generic, mutable array-like types with value semantics.\n//\n// - `Array<Element>` is like `ContiguousArray<Element>` when `Element` is not\n// a reference type or an Objective-C existential. Otherwise, it may use\n// an `NSArray` bridged from Cocoa for storage.\n//\n//===----------------------------------------------------------------------===//\n\n/// An ordered, random-access collection.\n///\n/// Arrays are one of the most commonly used data types in an app. You use\n/// arrays to organize your app's data. Specifically, you use the `Array` type\n/// to hold elements of a single type, the array's `Element` type. An array\n/// can store any kind of elements---from integers to strings to classes.\n///\n/// Swift makes it easy to create arrays in your code using an array literal:\n/// simply surround a comma-separated list of values with square brackets.\n/// Without any other information, Swift creates an array that includes the\n/// specified values, automatically inferring the array's `Element` type. For\n/// example:\n///\n/// // An array of 'Int' elements\n/// let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]\n///\n/// // An array of 'String' elements\n/// let streets = ["Albemarle", "Brandywine", "Chesapeake"]\n///\n/// You can create an empty array by specifying the `Element` type of your\n/// array in the declaration. For example:\n///\n/// // Shortened forms are preferred\n/// var emptyDoubles: [Double] = []\n///\n/// // The full type name is also allowed\n/// var emptyFloats: Array<Float> = Array()\n///\n/// If you need an array that is preinitialized with a fixed number of default\n/// values, use the `Array(repeating:count:)` initializer.\n///\n/// var digitCounts = Array(repeating: 0, count: 10)\n/// print(digitCounts)\n/// // Prints "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]"\n///\n/// Accessing Array Values\n/// ======================\n///\n/// When you need to perform an operation on all of an array's elements, use a\n/// `for`-`in` loop to iterate through the array's contents.\n///\n/// for street in streets {\n/// print("I don't live on \(street).")\n/// }\n/// // Prints "I don't live on Albemarle."\n/// // Prints "I don't live on Brandywine."\n/// // Prints "I don't live on Chesapeake."\n///\n/// Use the `isEmpty` property to check quickly whether an array has any\n/// elements, or use the `count` property to find the number of elements in\n/// the array.\n///\n/// if oddNumbers.isEmpty {\n/// print("I don't know any odd numbers.")\n/// } else {\n/// print("I know \(oddNumbers.count) odd numbers.")\n/// }\n/// // Prints "I know 8 odd numbers."\n///\n/// Use the `first` and `last` properties for safe access to the value of the\n/// array's first and last elements. If the array is empty, these properties\n/// are `nil`.\n///\n/// if let firstElement = oddNumbers.first, let lastElement = oddNumbers.last {\n/// print(firstElement, lastElement, separator: ", ")\n/// }\n/// // Prints "1, 15"\n///\n/// print(emptyDoubles.first, emptyDoubles.last, separator: ", ")\n/// // Prints "nil, nil"\n///\n/// You can access individual array elements through a subscript. The first\n/// element of a nonempty array is always at index zero. You can subscript an\n/// array with any integer from zero up to, but not including, the count of\n/// the array. Using a negative number or an index equal to or greater than\n/// `count` triggers a runtime error. For example:\n///\n/// print(oddNumbers[0], oddNumbers[3], separator: ", ")\n/// // Prints "1, 7"\n///\n/// print(emptyDoubles[0])\n/// // Triggers runtime error: Index out of range\n///\n/// Adding and Removing Elements\n/// ============================\n///\n/// Suppose you need to store a list of the names of students that are signed\n/// up for a class you're teaching. During the registration period, you need\n/// to add and remove names as students add and drop the class.\n///\n/// var students = ["Ben", "Ivy", "Jordell"]\n///\n/// To add single elements to the end of an array, use the `append(_:)` method.\n/// Add multiple elements at the same time by passing another array or a\n/// sequence of any kind to the `append(contentsOf:)` method.\n///\n/// students.append("Maxime")\n/// students.append(contentsOf: ["Shakia", "William"])\n/// // ["Ben", "Ivy", "Jordell", "Maxime", "Shakia", "William"]\n///\n/// You can add new elements in the middle of an array by using the\n/// `insert(_:at:)` method for single elements and by using\n/// `insert(contentsOf:at:)` to insert multiple elements from another\n/// collection or array literal. The elements at that index and later indices\n/// are shifted back to make room.\n///\n/// students.insert("Liam", at: 3)\n/// // ["Ben", "Ivy", "Jordell", "Liam", "Maxime", "Shakia", "William"]\n///\n/// To remove elements from an array, use the `remove(at:)`,\n/// `removeSubrange(_:)`, and `removeLast()` methods.\n///\n/// // Ben's family is moving to another state\n/// students.remove(at: 0)\n/// // ["Ivy", "Jordell", "Liam", "Maxime", "Shakia", "William"]\n///\n/// // William is signing up for a different class\n/// students.removeLast()\n/// // ["Ivy", "Jordell", "Liam", "Maxime", "Shakia"]\n///\n/// You can replace an existing element with a new value by assigning the new\n/// value to the subscript.\n///\n/// if let i = students.firstIndex(of: "Maxime") {\n/// students[i] = "Max"\n/// }\n/// // ["Ivy", "Jordell", "Liam", "Max", "Shakia"]\n///\n/// Growing the Size of an Array\n/// ----------------------------\n///\n/// Every array reserves a specific amount of memory to hold its contents. When\n/// you add elements to an array and that array begins to exceed its reserved\n/// capacity, the array allocates a larger region of memory and copies its\n/// elements into the new storage. The new storage is a multiple of the old\n/// storage's size. This exponential growth strategy means that appending an\n/// element happens in constant time, averaging the performance of many append\n/// operations. Append operations that trigger reallocation have a performance\n/// cost, but they occur less and less often as the array grows larger.\n///\n/// If you know approximately how many elements you will need to store, use the\n/// `reserveCapacity(_:)` method before appending to the array to avoid\n/// intermediate reallocations. Use the `capacity` and `count` properties to\n/// determine how many more elements the array can store without allocating\n/// larger storage.\n///\n/// For arrays of most `Element` types, this storage is a contiguous block of\n/// memory. For arrays with an `Element` type that is a class or `@objc`\n/// protocol type, this storage can be a contiguous block of memory or an\n/// instance of `NSArray`. Because any arbitrary subclass of `NSArray` can\n/// become an `Array`, there are no guarantees about representation or\n/// efficiency in this case.\n///\n/// Modifying Copies of Arrays\n/// ==========================\n///\n/// Each array has an independent value that includes the values of all of its\n/// elements. For simple types such as integers and other structures, this\n/// means that when you change a value in one array, the value of that element\n/// does not change in any copies of the array. For example:\n///\n/// var numbers = [1, 2, 3, 4, 5]\n/// var numbersCopy = numbers\n/// numbers[0] = 100\n/// print(numbers)\n/// // Prints "[100, 2, 3, 4, 5]"\n/// print(numbersCopy)\n/// // Prints "[1, 2, 3, 4, 5]"\n///\n/// If the elements in an array are instances of a class, the semantics are the\n/// same, though they might appear different at first. In this case, the\n/// values stored in the array are references to objects that live outside the\n/// array. If you change a reference to an object in one array, only that\n/// array has a reference to the new object. However, if two arrays contain\n/// references to the same object, you can observe changes to that object's\n/// properties from both arrays. For example:\n///\n/// // An integer type with reference semantics\n/// class IntegerReference {\n/// var value = 10\n/// }\n/// var firstIntegers = [IntegerReference(), IntegerReference()]\n/// var secondIntegers = firstIntegers\n///\n/// // Modifications to an instance are visible from either array\n/// firstIntegers[0].value = 100\n/// print(secondIntegers[0].value)\n/// // Prints "100"\n///\n/// // Replacements, additions, and removals are still visible\n/// // only in the modified array\n/// firstIntegers[0] = IntegerReference()\n/// print(firstIntegers[0].value)\n/// // Prints "10"\n/// print(secondIntegers[0].value)\n/// // Prints "100"\n///\n/// Arrays, like all variable-size collections in the standard library, use\n/// copy-on-write optimization. Multiple copies of an array share the same\n/// storage until you modify one of the copies. When that happens, the array\n/// being modified replaces its storage with a uniquely owned copy of itself,\n/// which is then modified in place. Optimizations are sometimes applied that\n/// can reduce the amount of copying.\n///\n/// This means that if an array is sharing storage with other copies, the first\n/// mutating operation on that array incurs the cost of copying the array. An\n/// array that is the sole owner of its storage can perform mutating\n/// operations in place.\n///\n/// In the example below, a `numbers` array is created along with two copies\n/// that share the same storage. When the original `numbers` array is\n/// modified, it makes a unique copy of its storage before making the\n/// modification. Further modifications to `numbers` are made in place, while\n/// the two copies continue to share the original storage.\n///\n/// var numbers = [1, 2, 3, 4, 5]\n/// var firstCopy = numbers\n/// var secondCopy = numbers\n///\n/// // The storage for 'numbers' is copied here\n/// numbers[0] = 100\n/// numbers[1] = 200\n/// numbers[2] = 300\n/// // 'numbers' is [100, 200, 300, 4, 5]\n/// // 'firstCopy' and 'secondCopy' are [1, 2, 3, 4, 5]\n///\n/// Bridging Between Array and NSArray\n/// ==================================\n///\n/// When you need to access APIs that require data in an `NSArray` instance\n/// instead of `Array`, use the type-cast operator (`as`) to bridge your\n/// instance. For bridging to be possible, the `Element` type of your array\n/// must be a class, an `@objc` protocol (a protocol imported from Objective-C\n/// or marked with the `@objc` attribute), or a type that bridges to a\n/// Foundation type.\n///\n/// The following example shows how you can bridge an `Array` instance to\n/// `NSArray` to use the `write(to:atomically:)` method. In this example, the\n/// `colors` array can be bridged to `NSArray` because the `colors` array's\n/// `String` elements bridge to `NSString`. The compiler prevents bridging the\n/// `moreColors` array, on the other hand, because its `Element` type is\n/// `Optional<String>`, which does *not* bridge to a Foundation type.\n///\n/// let colors = ["periwinkle", "rose", "moss"]\n/// let moreColors: [String?] = ["ochre", "pine"]\n///\n/// let url = URL(fileURLWithPath: "names.plist")\n/// (colors as NSArray).write(to: url, atomically: true)\n/// // true\n///\n/// (moreColors as NSArray).write(to: url, atomically: true)\n/// // error: cannot convert value of type '[String?]' to type 'NSArray'\n///\n/// Bridging from `Array` to `NSArray` takes O(1) time and O(1) space if the\n/// array's elements are already instances of a class or an `@objc` protocol;\n/// otherwise, it takes O(*n*) time and space.\n///\n/// When the destination array's element type is a class or an `@objc`\n/// protocol, bridging from `NSArray` to `Array` first calls the `copy(with:)`\n/// (`- copyWithZone:` in Objective-C) method on the array to get an immutable\n/// copy and then performs additional Swift bookkeeping work that takes O(1)\n/// time. For instances of `NSArray` that are already immutable, `copy(with:)`\n/// usually returns the same array in O(1) time; otherwise, the copying\n/// performance is unspecified. If `copy(with:)` returns the same array, the\n/// instances of `NSArray` and `Array` share storage using the same\n/// copy-on-write optimization that is used when two instances of `Array`\n/// share storage.\n///\n/// When the destination array's element type is a nonclass type that bridges\n/// to a Foundation type, bridging from `NSArray` to `Array` performs a\n/// bridging copy of the elements to contiguous storage in O(*n*) time. For\n/// example, bridging from `NSArray` to `Array<Int>` performs such a copy. No\n/// further bridging is required when accessing elements of the `Array`\n/// instance.\n///\n/// - Note: The `ContiguousArray` and `ArraySlice` types are not bridged;\n/// instances of those types always have a contiguous block of memory as\n/// their storage.\n@frozen\n@_eagerMove\npublic struct Array<Element>: _DestructorSafeContainer {\n #if _runtime(_ObjC)\n @usableFromInline\n internal typealias _Buffer = _ArrayBuffer<Element>\n #else\n @usableFromInline\n internal typealias _Buffer = _ContiguousArrayBuffer<Element>\n #endif\n\n @usableFromInline\n internal var _buffer: _Buffer\n\n /// Initialization from an existing buffer does not have "array.init"\n /// semantics because the caller may retain an alias to buffer.\n @inlinable\n internal init(_buffer: _Buffer) {\n self._buffer = _buffer\n }\n}\n\n//===--- private helpers---------------------------------------------------===//\nextension Array {\n /// Returns `true` if the array is native and does not need a deferred\n /// type check. May be hoisted by the optimizer, which means its\n /// results may be stale by the time they are used if there is an\n /// inout violation in user code.\n @inlinable\n @_semantics("array.props.isNativeTypeChecked")\n @_effects(notEscaping self.**)\n public // @testable\n func _hoistableIsNativeTypeChecked() -> Bool {\n return _buffer.arrayPropertyIsNativeTypeChecked\n }\n\n @inlinable\n @_semantics("array.get_count")\n @_effects(notEscaping self.**)\n internal func _getCount() -> Int {\n return _buffer.immutableCount\n }\n\n @inlinable\n @_semantics("array.get_capacity")\n @_effects(notEscaping self.**)\n internal func _getCapacity() -> Int {\n return _buffer.immutableCapacity\n }\n\n @inlinable\n @_semantics("array.make_mutable")\n @_effects(notEscaping self.**)\n internal mutating func _makeMutableAndUnique() {\n if _slowPath(!_buffer.beginCOWMutation()) {\n _buffer = _buffer._consumeAndCreateNew()\n }\n }\n\n /// Marks the end of an Array mutation.\n ///\n /// After a call to `_endMutation` the buffer must not be mutated until a call\n /// to `_makeMutableAndUnique`.\n @_alwaysEmitIntoClient\n @_semantics("array.end_mutation")\n @_effects(notEscaping self.**)\n internal mutating func _endMutation() {\n _buffer.endCOWMutation()\n }\n\n /// Check that the given `index` is valid for subscripting, i.e.\n /// `0 ≤ index < count`.\n ///\n /// This function is not used anymore, but must stay in the library for ABI\n /// compatibility.\n @inlinable\n @inline(__always)\n internal func _checkSubscript_native(_ index: Int) {\n _ = _checkSubscript(index, wasNativeTypeChecked: true)\n }\n\n /// Check that the given `index` is valid for subscripting, i.e.\n /// `0 ≤ index < count`.\n @inlinable\n @_semantics("array.check_subscript")\n @_effects(notEscaping self.**)\n public // @testable\n func _checkSubscript(\n _ index: Int, wasNativeTypeChecked: Bool\n ) -> _DependenceToken {\n#if _runtime(_ObjC)\n // There is no need to do bounds checking for the non-native case because\n // ObjectiveC arrays do bounds checking by their own.\n // And in the native-non-type-checked case, it's also not needed to do bounds\n // checking here, because it's done in ArrayBuffer._getElementSlowPath.\n if _fastPath(wasNativeTypeChecked) {\n _buffer._native._checkValidSubscript(index)\n }\n#else\n _buffer._checkValidSubscript(index)\n#endif\n return _DependenceToken()\n }\n\n /// Check that the given `index` is valid for subscripting, i.e.\n /// `0 ≤ index < count`.\n ///\n /// - Precondition: The buffer must be uniquely referenced and native.\n @_alwaysEmitIntoClient\n @_semantics("array.check_subscript")\n @_effects(notEscaping self.**)\n internal func _checkSubscript_mutating(_ index: Int) {\n _buffer._checkValidSubscriptMutating(index)\n }\n\n /// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`.\n @inlinable\n @_semantics("array.check_index")\n @_effects(notEscaping self.**)\n internal func _checkIndex(_ index: Int) {\n _precondition(index <= endIndex, "Array index is out of range")\n _precondition(index >= startIndex, "Negative Array index is out of range")\n }\n\n @_semantics("array.get_element")\n @_effects(notEscaping self.value**)\n @_effects(escaping self.value**.class*.value** -> return.value**)\n @inlinable // FIXME(inline-always)\n @inline(__always)\n public // @testable\n func _getElement(\n _ index: Int,\n wasNativeTypeChecked: Bool,\n matchingSubscriptCheck: _DependenceToken\n ) -> Element {\n#if _runtime(_ObjC)\n return _buffer.getElement(index, wasNativeTypeChecked: wasNativeTypeChecked)\n#else\n return _buffer.getElement(index)\n#endif\n }\n\n @inlinable\n @_semantics("array.get_element_address")\n internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> {\n return unsafe _buffer.firstElementAddress + index\n }\n}\n\nextension Array: _ArrayProtocol {\n /// The total number of elements that the array can contain without\n /// allocating new storage.\n ///\n /// Every array reserves a specific amount of memory to hold its contents.\n /// When you add elements to an array and that array begins to exceed its\n /// reserved capacity, the array allocates a larger region of memory and\n /// copies its elements into the new storage. The new storage is a multiple\n /// of the old storage's size. This exponential growth strategy means that\n /// appending an element happens in constant time, averaging the performance\n /// of many append operations. Append operations that trigger reallocation\n /// have a performance cost, but they occur less and less often as the array\n /// grows larger.\n ///\n /// The following example creates an array of integers from an array literal,\n /// then appends the elements of another collection. Before appending, the\n /// array allocates new storage that is large enough store the resulting\n /// elements.\n ///\n /// var numbers = [10, 20, 30, 40, 50]\n /// // numbers.count == 5\n /// // numbers.capacity == 5\n ///\n /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10))\n /// // numbers.count == 10\n /// // numbers.capacity == 10\n @inlinable\n public var capacity: Int {\n return _getCapacity()\n }\n\n #if $Embedded\n public typealias AnyObject = Builtin.NativeObject\n #endif\n\n /// An object that guarantees the lifetime of this array's elements.\n @inlinable\n public // @testable\n var _owner: AnyObject? {\n @inlinable // FIXME(inline-always)\n @inline(__always)\n get {\n return _buffer.owner \n }\n }\n\n /// If the elements are stored contiguously, a pointer to the first\n /// element. Otherwise, `nil`.\n @inlinable\n public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? {\n @inline(__always) // FIXME(TODO: JIRA): Hack around test failure\n get { return unsafe _buffer.firstElementAddressIfContiguous }\n }\n}\n\nextension Array: RandomAccessCollection, MutableCollection {\n /// The index type for arrays, `Int`.\n public typealias Index = Int\n\n /// The type that represents the indices that are valid for subscripting an\n /// array, in ascending order.\n public typealias Indices = Range<Int>\n\n /// The type that allows iteration over an array's elements.\n public typealias Iterator = IndexingIterator<Array>\n\n /// The position of the first element in a nonempty array.\n ///\n /// For an instance of `Array`, `startIndex` is always zero. If the array\n /// is empty, `startIndex` is equal to `endIndex`.\n @inlinable\n public var startIndex: Int {\n return 0\n }\n\n /// The array's "past the end" position---that is, the position one greater\n /// than the last valid subscript argument.\n ///\n /// When you need a range that includes the last element of an array, use the\n /// half-open range operator (`..<`) with `endIndex`. The `..<` operator\n /// creates a range that doesn't include the upper bound, so it's always\n /// safe to use with `endIndex`. For example:\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// if let i = numbers.firstIndex(of: 30) {\n /// print(numbers[i ..< numbers.endIndex])\n /// }\n /// // Prints "[30, 40, 50]"\n ///\n /// If the array is empty, `endIndex` is equal to `startIndex`.\n @inlinable\n public var endIndex: Int {\n @inlinable\n get {\n return _getCount()\n }\n }\n\n /// Returns the position immediately after the given index.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be less than\n /// `endIndex`.\n /// - Returns: The index immediately after `i`.\n @inlinable\n public func index(after i: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return i + 1\n }\n\n /// Replaces the given index with its successor.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be less than\n /// `endIndex`.\n @inlinable\n public func formIndex(after i: inout Int) {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n i += 1\n }\n\n /// Returns the position immediately before the given index.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be greater than\n /// `startIndex`.\n /// - Returns: The index immediately before `i`.\n @inlinable\n public func index(before i: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return i - 1\n }\n\n /// Replaces the given index with its predecessor.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be greater than\n /// `startIndex`.\n @inlinable\n public func formIndex(before i: inout Int) {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n i -= 1\n }\n\n /// Returns an index that is the specified distance from the given index.\n ///\n /// The following example obtains an index advanced four positions from an\n /// array's starting index and then prints the element at that position.\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// let i = numbers.index(numbers.startIndex, offsetBy: 4)\n /// print(numbers[i])\n /// // Prints "50"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection.\n ///\n /// - Parameters:\n /// - i: A valid index of the array.\n /// - distance: The distance to offset `i`.\n /// - Returns: An index offset by `distance` from the index `i`. If\n /// `distance` is positive, this is the same value as the result of\n /// `distance` calls to `index(after:)`. If `distance` is negative, this\n /// is the same value as the result of `abs(distance)` calls to\n /// `index(before:)`.\n @inlinable\n public func index(_ i: Int, offsetBy distance: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return i + distance\n }\n\n /// Returns an index that is the specified distance from the given index,\n /// unless that distance is beyond a given limiting index.\n ///\n /// The following example obtains an index advanced four positions from an\n /// array's starting index and then prints the element at that position. The\n /// operation doesn't require going beyond the limiting `numbers.endIndex`\n /// value, so it succeeds.\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// if let i = numbers.index(numbers.startIndex,\n /// offsetBy: 4,\n /// limitedBy: numbers.endIndex) {\n /// print(numbers[i])\n /// }\n /// // Prints "50"\n ///\n /// The next example attempts to retrieve an index ten positions from\n /// `numbers.startIndex`, but fails, because that distance is beyond the\n /// index passed as `limit`.\n ///\n /// let j = numbers.index(numbers.startIndex,\n /// offsetBy: 10,\n /// limitedBy: numbers.endIndex)\n /// print(j)\n /// // Prints "nil"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection, unless the index passed as `limit` prevents offsetting\n /// beyond those bounds.\n ///\n /// - Parameters:\n /// - i: A valid index of the array.\n /// - distance: The distance to offset `i`.\n /// - limit: A valid index of the collection to use as a limit. If\n /// `distance > 0`, `limit` has no effect if it is less than `i`.\n /// Likewise, if `distance < 0`, `limit` has no effect if it is greater\n /// than `i`.\n /// - Returns: An index offset by `distance` from the index `i`, unless that\n /// index would be beyond `limit` in the direction of movement. In that\n /// case, the method returns `nil`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func index(\n _ i: Int, offsetBy distance: Int, limitedBy limit: Int\n ) -> Int? {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n let l = limit - i\n if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l {\n return nil\n }\n return i + distance\n }\n\n /// Returns the distance between two indices.\n ///\n /// - Parameters:\n /// - start: A valid index of the collection.\n /// - end: Another valid index of the collection. If `end` is equal to\n /// `start`, the result is zero.\n /// - Returns: The distance between `start` and `end`.\n @inlinable\n public func distance(from start: Int, to end: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return end - start\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) {\n // NOTE: This method is a no-op for performance reasons.\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) {\n // NOTE: This method is a no-op for performance reasons.\n }\n\n /// Accesses the element at the specified position.\n ///\n /// The following example uses indexed subscripting to update an array's\n /// second element. After assigning the new value (`"Butler"`) at a specific\n /// position, that value is immediately available at that same position.\n ///\n /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// streets[1] = "Butler"\n /// print(streets[1])\n /// // Prints "Butler"\n ///\n /// - Parameter index: The position of the element to access. `index` must be\n /// greater than or equal to `startIndex` and less than `endIndex`.\n ///\n /// - Complexity: Reading an element from an array is O(1). Writing is O(1)\n /// unless the array's storage is shared with another array or uses a\n /// bridged `NSArray` instance as its storage, in which case writing is\n /// O(*n*), where *n* is the length of the array.\n @inlinable\n public subscript(index: Int) -> Element {\n get {\n // This call may be hoisted or eliminated by the optimizer. If\n // there is an inout violation, this value may be stale so needs to be\n // checked again below.\n let wasNativeTypeChecked = _hoistableIsNativeTypeChecked()\n\n // Make sure the index is in range and wasNativeTypeChecked is\n // still valid.\n let token = _checkSubscript(\n index, wasNativeTypeChecked: wasNativeTypeChecked)\n\n return _getElement(\n index, wasNativeTypeChecked: wasNativeTypeChecked,\n matchingSubscriptCheck: token)\n }\n _modify {\n _makeMutableAndUnique() // makes the array native, too\n _checkSubscript_mutating(index)\n let address = unsafe _buffer.mutableFirstElementAddress + index\n defer { _endMutation() }\n yield unsafe &address.pointee\n }\n }\n\n /// Accesses a contiguous subrange of the array's elements.\n ///\n /// The returned `ArraySlice` instance uses the same indices for the same\n /// elements as the original array. In particular, that slice, unlike an\n /// array, may have a nonzero `startIndex` and an `endIndex` that is not\n /// equal to `count`. Always use the slice's `startIndex` and `endIndex`\n /// properties instead of assuming that its indices start or end at a\n /// particular value.\n ///\n /// This example demonstrates getting a slice of an array of strings, finding\n /// the index of one of the strings in the slice, and then using that index\n /// in the original array.\n ///\n /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// let streetsSlice = streets[2 ..< streets.endIndex]\n /// print(streetsSlice)\n /// // Prints "["Channing", "Douglas", "Evarts"]"\n ///\n /// let i = streetsSlice.firstIndex(of: "Evarts") // 4\n /// print(streets[i!])\n /// // Prints "Evarts"\n ///\n /// - Parameter bounds: A range of integers. The bounds of the range must be\n /// valid indices of the array.\n @inlinable\n public subscript(bounds: Range<Int>) -> ArraySlice<Element> {\n get {\n _checkIndex(bounds.lowerBound)\n _checkIndex(bounds.upperBound)\n return ArraySlice(_buffer: _buffer[bounds])\n }\n set(rhs) {\n _checkIndex(bounds.lowerBound)\n _checkIndex(bounds.upperBound)\n // If the replacement buffer has same identity, and the ranges match,\n // then this was a pinned in-place modification, nothing further needed.\n if unsafe self[bounds]._buffer.identity != rhs._buffer.identity\n || bounds != rhs.startIndex..<rhs.endIndex {\n self.replaceSubrange(bounds, with: rhs)\n }\n }\n }\n \n /// The number of elements in the array.\n @inlinable\n @_semantics("array.get_count")\n public var count: Int {\n return _getCount()\n }\n}\n\nextension Array: ExpressibleByArrayLiteral {\n // Optimized implementation for Array\n /// Creates an array from the given array literal.\n ///\n /// Do not call this initializer directly. It is used by the compiler\n /// when you use an array literal. Instead, create a new array by using an\n /// array literal as its value. To do this, enclose a comma-separated list of\n /// values in square brackets.\n ///\n /// Here, an array of strings is created from an array literal holding\n /// only strings.\n ///\n /// let ingredients = ["cocoa beans", "sugar", "cocoa butter", "salt"]\n ///\n /// - Parameter elements: A variadic list of elements of the new array.\n @inlinable\n public init(arrayLiteral elements: Element...) {\n self = elements\n }\n}\n\nextension Array: RangeReplaceableCollection {\n /// Creates a new, empty array.\n ///\n /// This is equivalent to initializing with an empty array literal.\n /// For example:\n ///\n /// var emptyArray = Array<Int>()\n /// print(emptyArray.isEmpty)\n /// // Prints "true"\n ///\n /// emptyArray = []\n /// print(emptyArray.isEmpty)\n /// // Prints "true"\n @inlinable\n @_semantics("array.init.empty")\n public init() {\n _buffer = _Buffer()\n }\n\n /// Creates an array containing the elements of a sequence.\n ///\n /// You can use this initializer to create an array from any other type that\n /// conforms to the `Sequence` protocol. For example, you might want to\n /// create an array with the integers from 1 through 7. Use this initializer\n /// around a range instead of typing all those numbers in an array literal.\n ///\n /// let numbers = Array(1...7)\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 6, 7]"\n ///\n /// You can also use this initializer to convert a complex sequence or\n /// collection type back to an array. For example, the `keys` property of\n /// a dictionary isn't an array with its own storage, it's a collection\n /// that maps its elements from the dictionary only when they're\n /// accessed, saving the time and space needed to allocate an array. If\n /// you need to pass those keys to a method that takes an array, however,\n /// use this initializer to convert that list from its type of\n /// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple\n /// `[String]`.\n ///\n /// func cacheImages(withNames names: [String]) {\n /// // custom image loading and caching\n /// }\n ///\n /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,\n /// "Gold": 50, "Cerise": 320]\n /// let colorNames = Array(namedHues.keys)\n /// cacheImages(withNames: colorNames)\n ///\n /// print(colorNames)\n /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"\n ///\n /// - Parameter s: The sequence of elements to turn into an array.\n @inlinable\n public init<S: Sequence>(_ s: S) where S.Element == Element {\n self = Array(\n _buffer: _Buffer(\n _buffer: s._copyToContiguousArray()._buffer,\n shiftedToStartIndex: 0))\n }\n\n /// Creates a new array containing the specified number of a single, repeated\n /// value.\n ///\n /// Here's an example of creating an array initialized with five strings\n /// containing the letter *Z*.\n ///\n /// let fiveZs = Array(repeating: "Z", count: 5)\n /// print(fiveZs)\n /// // Prints "["Z", "Z", "Z", "Z", "Z"]"\n ///\n /// - Parameters:\n /// - repeatedValue: The element to repeat.\n /// - count: The number of times to repeat the value passed in the\n /// `repeating` parameter. `count` must be zero or greater.\n @inlinable\n @_semantics("array.init")\n public init(repeating repeatedValue: Element, count: Int) {\n var p: UnsafeMutablePointer<Element>\n unsafe (self, p) = unsafe Array._allocateUninitialized(count)\n for _ in 0..<count {\n unsafe p.initialize(to: repeatedValue)\n unsafe p += 1\n }\n _endMutation()\n }\n\n @inline(never)\n @usableFromInline\n internal static func _allocateBufferUninitialized(\n minimumCapacity: Int\n ) -> _Buffer {\n let newBuffer = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: 0, minimumCapacity: minimumCapacity)\n return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0)\n }\n\n /// Construct an Array of `count` uninitialized elements.\n @inlinable\n internal init(_uninitializedCount count: Int) {\n _precondition(count >= 0, "Can't construct Array with count < 0")\n // Note: Sinking this constructor into an else branch below causes an extra\n // Retain/Release.\n _buffer = _Buffer()\n if count > 0 {\n // Creating a buffer instead of calling reserveCapacity saves doing an\n // unnecessary uniqueness check. We disable inlining here to curb code\n // growth.\n _buffer = Array._allocateBufferUninitialized(minimumCapacity: count)\n _buffer.mutableCount = count\n }\n // Can't store count here because the buffer might be pointing to the\n // shared empty array.\n }\n\n /// Entry point for `Array` literal construction; builds and returns\n /// an Array of `count` uninitialized elements.\n @inlinable\n @_semantics("array.uninitialized")\n internal static func _allocateUninitialized(\n _ count: Int\n ) -> (Array, UnsafeMutablePointer<Element>) {\n let result = Array(_uninitializedCount: count)\n return unsafe (result, result._buffer.firstElementAddress)\n }\n\n\n /// Returns an Array of `count` uninitialized elements using the\n /// given `storage`, and a pointer to uninitialized memory for the\n /// first element.\n ///\n /// - Precondition: `storage is _ContiguousArrayStorage`.\n @inlinable\n @_semantics("array.uninitialized")\n @_effects(escaping storage => return.0.value**)\n @_effects(escaping storage.class*.value** => return.0.value**.class*.value**)\n @_effects(escaping storage.class*.value** => return.1.value**)\n internal static func _adoptStorage(\n _ storage: __owned _ContiguousArrayStorage<Element>, count: Int\n ) -> (Array, UnsafeMutablePointer<Element>) {\n\n let innerBuffer = _ContiguousArrayBuffer<Element>(\n count: count,\n storage: storage)\n\n return unsafe (\n Array(\n _buffer: _Buffer(_buffer: innerBuffer, shiftedToStartIndex: 0)),\n innerBuffer.firstElementAddress)\n }\n\n /// Entry point for aborting literal construction: deallocates\n /// an Array containing only uninitialized elements.\n @inlinable\n internal mutating func _deallocateUninitialized() {\n // Set the count to zero and just release as normal.\n // Somewhat of a hack.\n _buffer.mutableCount = 0\n }\n\n //===--- basic mutations ------------------------------------------------===//\n\n\n /// Reserves enough space to store the specified number of elements.\n ///\n /// If you are adding a known number of elements to an array, use this method\n /// to avoid multiple reallocations. This method ensures that the array has\n /// unique, mutable, contiguous storage, with space allocated for at least\n /// the requested number of elements.\n ///\n /// Calling the `reserveCapacity(_:)` method on an array with bridged storage\n /// triggers a copy to contiguous storage even if the existing storage\n /// has room to store `minimumCapacity` elements.\n ///\n /// For performance reasons, the size of the newly allocated storage might be\n /// greater than the requested capacity. Use the array's `capacity` property\n /// to determine the size of the new storage.\n ///\n /// Preserving an Array's Geometric Growth Strategy\n /// ===============================================\n ///\n /// If you implement a custom data structure backed by an array that grows\n /// dynamically, naively calling the `reserveCapacity(_:)` method can lead\n /// to worse than expected performance. Arrays need to follow a geometric\n /// allocation pattern for appending elements to achieve amortized\n /// constant-time performance. The `Array` type's `append(_:)` and\n /// `append(contentsOf:)` methods take care of this detail for you, but\n /// `reserveCapacity(_:)` allocates only as much space as you tell it to\n /// (padded to a round value), and no more. This avoids over-allocation, but\n /// can result in insertion not having amortized constant-time performance.\n ///\n /// The following code declares `values`, an array of integers, and the\n /// `addTenQuadratic()` function, which adds ten more values to the `values`\n /// array on each call.\n ///\n /// var values: [Int] = [0, 1, 2, 3]\n ///\n /// // Don't use 'reserveCapacity(_:)' like this\n /// func addTenQuadratic() {\n /// let newCount = values.count + 10\n /// values.reserveCapacity(newCount)\n /// for n in values.count..<newCount {\n /// values.append(n)\n /// }\n /// }\n ///\n /// The call to `reserveCapacity(_:)` increases the `values` array's capacity\n /// by exactly 10 elements on each pass through `addTenQuadratic()`, which\n /// is linear growth. Instead of having constant time when averaged over\n /// many calls, the function may decay to performance that is linear in\n /// `values.count`. This is almost certainly not what you want.\n ///\n /// In cases like this, the simplest fix is often to simply remove the call\n /// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array\n /// for you.\n ///\n /// func addTen() {\n /// let newCount = values.count + 10\n /// for n in values.count..<newCount {\n /// values.append(n)\n /// }\n /// }\n ///\n /// If you need more control over the capacity of your array, implement your\n /// own geometric growth strategy, passing the size you compute to\n /// `reserveCapacity(_:)`.\n ///\n /// - Parameter minimumCapacity: The requested number of elements to store.\n ///\n /// - Complexity: O(*n*), where *n* is the number of elements in the array.\n @inlinable\n @_semantics("array.mutate_unknown")\n @_effects(notEscaping self.**)\n public mutating func reserveCapacity(_ minimumCapacity: Int) {\n _reserveCapacityImpl(minimumCapacity: minimumCapacity,\n growForAppend: false)\n _endMutation()\n }\n\n /// Reserves enough space to store `minimumCapacity` elements.\n /// If a new buffer needs to be allocated and `growForAppend` is true,\n /// the new capacity is calculated using `_growArrayCapacity`, but at least\n /// kept at `minimumCapacity`.\n @_alwaysEmitIntoClient\n internal mutating func _reserveCapacityImpl(\n minimumCapacity: Int, growForAppend: Bool\n ) {\n let isUnique = _buffer.beginCOWMutation()\n if _slowPath(!isUnique || _buffer.mutableCapacity < minimumCapacity) {\n _createNewBuffer(bufferIsUnique: isUnique,\n minimumCapacity: Swift.max(minimumCapacity, _buffer.count),\n growForAppend: growForAppend)\n }\n _internalInvariant(_buffer.mutableCapacity >= minimumCapacity)\n _internalInvariant(_buffer.mutableCapacity == 0 ||\n _buffer.isUniquelyReferenced())\n }\n\n /// Creates a new buffer, replacing the current buffer.\n ///\n /// If `bufferIsUnique` is true, the buffer is assumed to be uniquely\n /// referenced by this array and the elements are moved - instead of copied -\n /// to the new buffer.\n /// The `minimumCapacity` is the lower bound for the new capacity.\n /// If `growForAppend` is true, the new capacity is calculated using\n /// `_growArrayCapacity`, but at least kept at `minimumCapacity`.\n @_alwaysEmitIntoClient\n internal mutating func _createNewBuffer(\n bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool\n ) {\n _internalInvariant(!bufferIsUnique || _buffer.isUniquelyReferenced())\n _buffer = _buffer._consumeAndCreateNew(bufferIsUnique: bufferIsUnique,\n minimumCapacity: minimumCapacity,\n growForAppend: growForAppend)\n }\n\n /// Copy the contents of the current buffer to a new unique mutable buffer.\n /// The count of the new buffer is set to `oldCount`, the capacity of the\n /// new buffer is big enough to hold 'oldCount' + 1 elements.\n @inline(never)\n @inlinable // @specializable\n internal mutating func _copyToNewBuffer(oldCount: Int) {\n let newCount = oldCount &+ 1\n var newBuffer = _buffer._forceCreateUniqueMutableBuffer(\n countForNewBuffer: oldCount, minNewCapacity: newCount)\n unsafe _buffer._arrayOutOfPlaceUpdate(&newBuffer, oldCount, 0)\n }\n\n @inlinable\n @_semantics("array.make_mutable")\n @_effects(notEscaping self.**)\n internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() {\n if _slowPath(!_buffer.beginCOWMutation()) {\n _createNewBuffer(bufferIsUnique: false,\n minimumCapacity: count &+ 1,\n growForAppend: true)\n }\n }\n\n @inlinable\n @_semantics("array.mutate_unknown")\n @_effects(notEscaping self.**)\n internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) {\n // Due to make_mutable hoisting the situation can arise where we hoist\n // _makeMutableAndUnique out of loop and use it to replace\n // _makeUniqueAndReserveCapacityIfNotUnique that precedes this call. If the\n // array was empty _makeMutableAndUnique does not replace the empty array\n // buffer by a unique buffer (it just replaces it by the empty array\n // singleton).\n // This specific case is okay because we will make the buffer unique in this\n // function because we request a capacity > 0 and therefore _copyToNewBuffer\n // will be called creating a new buffer.\n let capacity = _buffer.mutableCapacity\n _internalInvariant(capacity == 0 || _buffer.isMutableAndUniquelyReferenced())\n\n if _slowPath(oldCount &+ 1 > capacity) {\n _createNewBuffer(bufferIsUnique: capacity > 0,\n minimumCapacity: oldCount &+ 1,\n growForAppend: true)\n }\n }\n\n @inlinable\n @_semantics("array.mutate_unknown")\n @_effects(notEscaping self.**)\n internal mutating func _appendElementAssumeUniqueAndCapacity(\n _ oldCount: Int,\n newElement: __owned Element\n ) {\n _internalInvariant(_buffer.isMutableAndUniquelyReferenced())\n _internalInvariant(_buffer.mutableCapacity >= _buffer.mutableCount &+ 1)\n\n _buffer.mutableCount = oldCount &+ 1\n unsafe (_buffer.mutableFirstElementAddress + oldCount).initialize(to: newElement)\n }\n\n /// Adds a new element at the end of the array.\n ///\n /// Use this method to append a single element to the end of a mutable array.\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.append(100)\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 100]"\n ///\n /// Because arrays increase their allocated capacity using an exponential\n /// strategy, appending a single element to an array is an O(1) operation\n /// when averaged over many calls to the `append(_:)` method. When an array\n /// has additional capacity and is not sharing its storage with another\n /// instance, appending an element is O(1). When an array needs to\n /// reallocate storage before appending or its storage is shared with\n /// another copy, appending is O(*n*), where *n* is the length of the array.\n ///\n /// - Parameter newElement: The element to append to the array.\n ///\n /// - Complexity: O(1) on average, over many calls to `append(_:)` on the\n /// same array.\n @inlinable\n @_semantics("array.append_element")\n @_effects(notEscaping self.value**)\n public mutating func append(_ newElement: __owned Element) {\n // Separating uniqueness check and capacity check allows hoisting the\n // uniqueness check out of a loop.\n _makeUniqueAndReserveCapacityIfNotUnique()\n let oldCount = _buffer.mutableCount\n _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount)\n _appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement)\n _endMutation()\n }\n\n /// Adds the elements of a sequence to the end of the array.\n ///\n /// Use this method to append the elements of a sequence to the end of this\n /// array. This example appends the elements of a `Range<Int>` instance\n /// to an array of integers.\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.append(contentsOf: 10...15)\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"\n ///\n /// - Parameter newElements: The elements to append to the array.\n ///\n /// - Complexity: O(*m*) on average, where *m* is the length of\n /// `newElements`, over many calls to `append(contentsOf:)` on the same\n /// array.\n @inlinable\n @_semantics("array.append_contentsOf")\n @_effects(notEscaping self.value**)\n public mutating func append<S: Sequence>(contentsOf newElements: __owned S)\n where S.Element == Element {\n\n defer {\n _endMutation()\n }\n\n let newElementsCount = newElements.underestimatedCount\n _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount,\n growForAppend: true)\n\n let oldCount = _buffer.mutableCount\n let startNewElements = unsafe _buffer.mutableFirstElementAddress + oldCount\n let buf = unsafe UnsafeMutableBufferPointer(\n start: startNewElements, \n count: _buffer.mutableCapacity - oldCount)\n\n var (remainder,writtenUpTo) = unsafe buf.initialize(from: newElements)\n \n // trap on underflow from the sequence's underestimate:\n let writtenCount = unsafe buf.distance(from: buf.startIndex, to: writtenUpTo)\n _precondition(newElementsCount <= writtenCount, \n "newElements.underestimatedCount was an overestimate")\n // can't check for overflow as sequences can underestimate\n\n // This check prevents a data race writing to _swiftEmptyArrayStorage\n if writtenCount > 0 {\n _buffer.mutableCount = _buffer.mutableCount + writtenCount\n }\n\n if _slowPath(writtenUpTo == buf.endIndex) {\n\n // A shortcut for appending an Array: If newElements is an Array then it's\n // guaranteed that buf.initialize(from: newElements) already appended all\n // elements. It reduces code size, because the following code\n // can be removed by the optimizer by constant folding this check in a\n // generic specialization.\n if S.self == [Element].self {\n _internalInvariant(remainder.next() == nil)\n return\n }\n\n // there may be elements that didn't fit in the existing buffer,\n // append them in slow sequence-only mode\n var newCount = _buffer.mutableCount\n var nextItem = remainder.next()\n while nextItem != nil {\n _reserveCapacityAssumingUniqueBuffer(oldCount: newCount)\n\n let currentCapacity = _buffer.mutableCapacity\n let base = unsafe _buffer.mutableFirstElementAddress\n\n // fill while there is another item and spare capacity\n while let next = nextItem, newCount < currentCapacity {\n unsafe (base + newCount).initialize(to: next)\n newCount += 1\n nextItem = remainder.next()\n }\n _buffer.mutableCount = newCount\n }\n }\n }\n\n @inlinable\n @_semantics("array.reserve_capacity_for_append")\n @_effects(notEscaping self.**)\n internal mutating func reserveCapacityForAppend(newElementsCount: Int) {\n // Ensure uniqueness, mutability, and sufficient storage. Note that\n // for consistency, we need unique self even if newElements is empty.\n _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount,\n growForAppend: true)\n _endMutation()\n }\n\n @inlinable\n @_semantics("array.mutate_unknown")\n @_effects(notEscaping self.value**)\n @_effects(escaping self.value**.class*.value** -> return.value**)\n public mutating func _customRemoveLast() -> Element? {\n _makeMutableAndUnique()\n let newCount = _buffer.mutableCount - 1\n _precondition(newCount >= 0, "Can't removeLast from an empty Array")\n let pointer = unsafe (_buffer.mutableFirstElementAddress + newCount)\n let element = unsafe pointer.move()\n _buffer.mutableCount = newCount\n _endMutation()\n return element\n }\n\n /// Removes and returns the element at the specified position.\n ///\n /// All the elements following the specified position are moved up to\n /// close the gap.\n ///\n /// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]\n /// let removed = measurements.remove(at: 2)\n /// print(measurements)\n /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]"\n ///\n /// - Parameter index: The position of the element to remove. `index` must\n /// be a valid index of the array.\n /// - Returns: The element at the specified index.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the array.\n @inlinable\n @discardableResult\n @_semantics("array.mutate_unknown")\n @_effects(notEscaping self.value**)\n @_effects(escaping self.value**.class*.value** -> return.value**)\n public mutating func remove(at index: Int) -> Element {\n _makeMutableAndUnique()\n let currentCount = _buffer.mutableCount\n _precondition(index < currentCount, "Index out of range")\n _precondition(index >= 0, "Index out of range")\n let newCount = currentCount - 1\n let pointer = unsafe (_buffer.mutableFirstElementAddress + index)\n let result = unsafe pointer.move()\n unsafe pointer.moveInitialize(from: pointer + 1, count: newCount - index)\n _buffer.mutableCount = newCount\n _endMutation()\n return result\n }\n\n /// Inserts a new element at the specified position.\n ///\n /// The new element is inserted before the element currently at the specified\n /// index. If you pass the array's `endIndex` property as the `index`\n /// parameter, the new element is appended to the array.\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.insert(100, at: 3)\n /// numbers.insert(200, at: numbers.endIndex)\n ///\n /// print(numbers)\n /// // Prints "[1, 2, 3, 100, 4, 5, 200]"\n ///\n /// - Parameter newElement: The new element to insert into the array.\n /// - Parameter i: The position at which to insert the new element.\n /// `index` must be a valid index of the array or equal to its `endIndex`\n /// property.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the array. If\n /// `i == endIndex`, this method is equivalent to `append(_:)`.\n @inlinable\n public mutating func insert(_ newElement: __owned Element, at i: Int) {\n _checkIndex(i)\n self.replaceSubrange(i..<i, with: CollectionOfOne(newElement))\n }\n\n /// Removes all elements from the array.\n ///\n /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of\n /// the array after removing its elements. The default value is\n /// `false`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the array.\n @inlinable\n public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {\n if !keepCapacity {\n _buffer = _Buffer()\n }\n else if _buffer.isMutableAndUniquelyReferenced() {\n self.replaceSubrange(indices, with: EmptyCollection())\n }\n else {\n let buffer = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: 0,\n minimumCapacity: capacity\n )\n _buffer = _Buffer(_buffer: buffer, shiftedToStartIndex: startIndex)\n }\n }\n\n //===--- algorithms -----------------------------------------------------===//\n\n @inlinable\n @available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable")\n public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n return unsafe try withUnsafeMutableBufferPointer {\n (bufferPointer) -> R in\n return try unsafe body(&bufferPointer)\n }\n }\n\n @inlinable\n public mutating func withContiguousMutableStorageIfAvailable<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n return unsafe try withUnsafeMutableBufferPointer {\n (bufferPointer) -> R in\n return try unsafe body(&bufferPointer)\n }\n }\n\n @inlinable\n public func withContiguousStorageIfAvailable<R>(\n _ body: (UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n return unsafe try withUnsafeBufferPointer {\n (bufferPointer) -> R in\n return try unsafe body(bufferPointer)\n }\n }\n \n @inlinable\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n if let n = _buffer.requestNativeBuffer() {\n return ContiguousArray(_buffer: n)\n }\n return _copyCollectionToContiguousArray(self)\n }\n}\n\n// Implementations of + and += for same-type arrays. This combined\n// with the operator declarations for these operators designating this\n// type as a place to prefer this operator help the expression type\n// checker speed up cases where there is a large number of uses of the\n// operator in the same expression.\nextension Array {\n @inlinable\n public static func + (lhs: Array, rhs: Array) -> Array {\n var lhs = lhs\n lhs.append(contentsOf: rhs)\n return lhs\n }\n\n @inlinable\n public static func += (lhs: inout Array, rhs: Array) {\n lhs.append(contentsOf: rhs)\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension Array: CustomReflectable {\n /// A mirror that reflects the array.\n public var customMirror: Mirror {\n return Mirror(\n self,\n unlabeledChildren: self,\n displayStyle: .collection)\n }\n}\n#endif\n\n@_unavailableInEmbedded\nextension Array: CustomStringConvertible, CustomDebugStringConvertible {\n /// A textual representation of the array and its elements.\n public var description: String {\n return _makeCollectionDescription()\n }\n\n /// A textual representation of the array and its elements, suitable for\n /// debugging.\n public var debugDescription: String {\n // Always show sugared representation for Arrays.\n return _makeCollectionDescription()\n }\n}\n\nextension Array {\n @usableFromInline @_transparent\n internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) {\n let p = unsafe _baseAddressIfContiguous\n if unsafe _fastPath(p != nil || isEmpty) {\n return (_owner, UnsafeRawPointer(p))\n }\n let n = ContiguousArray(self._buffer)._buffer\n return unsafe (n.owner, UnsafeRawPointer(n.firstElementAddress))\n }\n}\n\nextension Array {\n /// Implementation for Array(unsafeUninitializedCapacity:initializingWith:)\n /// and ContiguousArray(unsafeUninitializedCapacity:initializingWith:)\n @inlinable\n internal init(\n _unsafeUninitializedCapacity: Int,\n initializingWith initializer: (\n _ buffer: inout UnsafeMutableBufferPointer<Element>,\n _ initializedCount: inout Int) throws -> Void\n ) rethrows {\n var firstElementAddress: UnsafeMutablePointer<Element>\n unsafe (self, firstElementAddress) =\n unsafe Array._allocateUninitialized(_unsafeUninitializedCapacity)\n\n var initializedCount = 0\n var buffer = unsafe UnsafeMutableBufferPointer<Element>(\n start: firstElementAddress, count: _unsafeUninitializedCapacity)\n defer {\n // Update self.count even if initializer throws an error.\n _precondition(\n initializedCount <= _unsafeUninitializedCapacity,\n "Initialized count set to greater than specified capacity."\n )\n unsafe _precondition(\n buffer.baseAddress == firstElementAddress,\n "Can't reassign buffer in Array(unsafeUninitializedCapacity:initializingWith:)"\n )\n self._buffer.mutableCount = initializedCount\n _endMutation()\n }\n try unsafe initializer(&buffer, &initializedCount)\n }\n\n /// Creates an array with the specified capacity, then calls the given\n /// closure with a buffer covering the array's uninitialized memory.\n ///\n /// Inside the closure, set the `initializedCount` parameter to the number of\n /// elements that are initialized by the closure. The memory in the range\n /// `buffer[0..<initializedCount]` must be initialized at the end of the\n /// closure's execution, and the memory in the range\n /// `buffer[initializedCount...]` must be uninitialized. This postcondition\n /// must hold even if the `initializer` closure throws an error.\n ///\n /// - Note: While the resulting array may have a capacity larger than the\n /// requested amount, the buffer passed to the closure will cover exactly\n /// the requested number of elements.\n ///\n /// - Parameters:\n /// - unsafeUninitializedCapacity: The number of elements to allocate\n /// space for in the new array.\n /// - initializer: A closure that initializes elements and sets the count\n /// of the new array.\n /// - Parameters:\n /// - buffer: A buffer covering uninitialized memory with room for the\n /// specified number of elements.\n /// - initializedCount: The count of initialized elements in the array,\n /// which begins as zero. Set `initializedCount` to the number of\n /// elements you initialize.\n @_alwaysEmitIntoClient @inlinable\n public init(\n unsafeUninitializedCapacity: Int,\n initializingWith initializer: (\n _ buffer: inout UnsafeMutableBufferPointer<Element>,\n _ initializedCount: inout Int) throws -> Void\n ) rethrows {\n self = try unsafe Array(\n _unsafeUninitializedCapacity: unsafeUninitializedCapacity,\n initializingWith: initializer)\n }\n\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n @usableFromInline\n @_disfavoredOverload\n func withUnsafeBufferPointer<R>(\n _ body: (UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R {\n return try unsafe _buffer.withUnsafeBufferPointer(body)\n }\n\n /// Calls a closure with a pointer to the array's contiguous storage.\n ///\n /// Often, the optimizer can eliminate bounds checks within an array\n /// algorithm, but when that fails, invoking the same algorithm on the\n /// buffer pointer passed into your closure lets you trade safety for speed.\n ///\n /// The following example shows how you can iterate over the contents of the\n /// buffer pointer:\n ///\n /// let numbers = [1, 2, 3, 4, 5]\n /// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in\n /// var result = 0\n /// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) {\n /// result += buffer[i]\n /// }\n /// return result\n /// }\n /// // 'sum' == 9\n ///\n /// The pointer passed as an argument to `body` is valid only during the\n /// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the\n /// pointer for later use.\n ///\n /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that\n /// points to the contiguous storage for the array. If no such storage exists, it is created. If\n /// `body` has a return value, that value is also used as the return value\n /// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is\n /// valid only for the duration of the method's execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @_alwaysEmitIntoClient\n public func withUnsafeBufferPointer<R, E>(\n _ body: (UnsafeBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n return try unsafe _buffer.withUnsafeBufferPointer(body)\n }\n\n @available(SwiftStdlib 6.2, *)\n public var span: Span<Element> {\n @lifetime(borrow self)\n @_alwaysEmitIntoClient\n borrowing get {\n#if _runtime(_ObjC)\n if _slowPath(!_buffer._isNative) {\n let buffer = _buffer.getOrAllocateAssociatedObjectBuffer()\n let pointer = unsafe buffer.firstElementAddress\n let count = buffer.immutableCount\n let span = unsafe Span(_unsafeStart: pointer, count: count)\n return unsafe _overrideLifetime(span, borrowing: self)\n }\n#endif\n let pointer = unsafe _buffer.firstElementAddress\n let count = _buffer.immutableCount\n let span = unsafe Span(_unsafeStart: pointer, count: count)\n return unsafe _overrideLifetime(span, borrowing: self)\n }\n }\n\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n @_semantics("array.withUnsafeMutableBufferPointer")\n @_effects(notEscaping self.value**)\n @usableFromInline\n @inline(__always)\n @_silgen_name("$sSa30withUnsafeMutableBufferPointeryqd__qd__SryxGzKXEKlF")\n mutating func __abi_withUnsafeMutableBufferPointer<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R {\n _makeMutableAndUnique()\n let count = _buffer.mutableCount\n\n // Create an UnsafeBufferPointer that we can pass to body\n let pointer = unsafe _buffer.mutableFirstElementAddress\n var inoutBufferPointer = unsafe UnsafeMutableBufferPointer(\n start: pointer, count: count)\n\n defer {\n unsafe _precondition(\n inoutBufferPointer.baseAddress == pointer &&\n inoutBufferPointer.count == count,\n "Array withUnsafeMutableBufferPointer: replacing the buffer is not allowed")\n _endMutation()\n _fixLifetime(self)\n }\n\n // Invoke the body.\n return try unsafe body(&inoutBufferPointer)\n }\n\n /// Calls the given closure with a pointer to the array's mutable contiguous\n /// storage.\n ///\n /// Often, the optimizer can eliminate bounds checks within an array\n /// algorithm, but when that fails, invoking the same algorithm on the\n /// buffer pointer passed into your closure lets you trade safety for speed.\n ///\n /// The following example shows how modifying the contents of the\n /// `UnsafeMutableBufferPointer` argument to `body` alters the contents of\n /// the array:\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.withUnsafeMutableBufferPointer { buffer in\n /// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) {\n /// buffer.swapAt(i, i + 1)\n /// }\n /// }\n /// print(numbers)\n /// // Prints "[2, 1, 4, 3, 5]"\n ///\n /// The pointer passed as an argument to `body` is valid only during the\n /// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or\n /// return the pointer for later use.\n ///\n /// - Warning: Do not rely on anything about the array that is the target of\n /// this method during execution of the `body` closure; it might not\n /// appear to have its correct value. Instead, use only the\n /// `UnsafeMutableBufferPointer` argument to `body`.\n ///\n /// - Parameter body: A closure with an `UnsafeMutableBufferPointer`\n /// parameter that points to the contiguous storage for the array.\n /// If no such storage exists, it is created. If `body` has a return value, that value is also\n /// used as the return value for the `withUnsafeMutableBufferPointer(_:)`\n /// method. The pointer argument is valid only for the duration of the\n /// method's execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @_semantics("array.withUnsafeMutableBufferPointer")\n @_effects(notEscaping self.value**)\n @_alwaysEmitIntoClient\n @inline(__always) // Performance: This method should get inlined into the\n // caller such that we can combine the partial apply with the apply in this\n // function saving on allocating a closure context. This becomes unnecessary\n // once we allocate noescape closures on the stack.\n public mutating func withUnsafeMutableBufferPointer<R, E>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n _makeMutableAndUnique()\n let count = _buffer.mutableCount\n\n // Create an UnsafeBufferPointer that we can pass to body\n let pointer = unsafe _buffer.mutableFirstElementAddress\n var inoutBufferPointer = unsafe UnsafeMutableBufferPointer(\n start: pointer, count: count)\n\n defer {\n unsafe _precondition(\n inoutBufferPointer.baseAddress == pointer &&\n inoutBufferPointer.count == count,\n "Array withUnsafeMutableBufferPointer: replacing the buffer is not allowed")\n _endMutation()\n _fixLifetime(self)\n }\n\n // Invoke the body.\n return try unsafe body(&inoutBufferPointer)\n }\n\n @available(SwiftStdlib 6.2, *)\n public var mutableSpan: MutableSpan<Element> {\n @lifetime(&self)\n @_alwaysEmitIntoClient\n mutating get {\n _makeMutableAndUnique()\n // NOTE: We don't have the ability to schedule a call to\n // ContiguousArrayBuffer.endCOWMutation().\n // rdar://146785284 (lifetime analysis for end of mutation)\n let pointer = unsafe _buffer.firstElementAddress\n let count = _buffer.mutableCount\n let span = unsafe MutableSpan(_unsafeStart: pointer, count: count)\n return unsafe _overrideLifetime(span, mutating: &self)\n }\n }\n\n @inlinable\n public __consuming func _copyContents(\n initializing buffer: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {\n\n guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) }\n\n // It is not OK for there to be no pointer/not enough space, as this is\n // a precondition and Array never lies about its count.\n guard var p = buffer.baseAddress\n else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") }\n _precondition(self.count <= buffer.count, \n "Insufficient space allocated to copy array contents")\n\n if let s = unsafe _baseAddressIfContiguous {\n unsafe p.initialize(from: s, count: self.count)\n // Need a _fixLifetime bracketing the _baseAddressIfContiguous getter\n // and all uses of the pointer it returns:\n _fixLifetime(self._owner)\n } else {\n for x in self {\n unsafe p.initialize(to: x)\n unsafe p += 1\n }\n }\n\n var it = IndexingIterator(_elements: self)\n it._position = endIndex\n return (it,unsafe buffer.index(buffer.startIndex, offsetBy: self.count))\n }\n}\n\nextension Array {\n /// Replaces a range of elements with the elements in the specified\n /// collection.\n ///\n /// This method has the effect of removing the specified range of elements\n /// from the array and inserting the new elements at the same location. The\n /// number of new elements need not match the number of elements being\n /// removed.\n ///\n /// In this example, three elements in the middle of an array of integers are\n /// replaced by the five elements of a `Repeated<Int>` instance.\n ///\n /// var nums = [10, 20, 30, 40, 50]\n /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))\n /// print(nums)\n /// // Prints "[10, 1, 1, 1, 1, 1, 50]"\n ///\n /// If you pass a zero-length range as the `subrange` parameter, this method\n /// inserts the elements of `newElements` at `subrange.startIndex`. Calling\n /// the `insert(contentsOf:at:)` method instead is preferred.\n ///\n /// Likewise, if you pass a zero-length collection as the `newElements`\n /// parameter, this method removes the elements in the given subrange\n /// without replacement. Calling the `removeSubrange(_:)` method instead is\n /// preferred.\n ///\n /// - Parameters:\n /// - subrange: The subrange of the array to replace. The start and end of\n /// a subrange must be valid indices of the array.\n /// - newElements: The new elements to add to the array.\n ///\n /// - Complexity: O(*n* + *m*), where *n* is length of the array and\n /// *m* is the length of `newElements`. If the call to this method simply\n /// appends the contents of `newElements` to the array, this method is\n /// equivalent to `append(contentsOf:)`.\n @inlinable\n @_semantics("array.mutate_unknown")\n @_effects(notEscaping self.value**)\n @_effects(notEscaping self.value**.class*.value**)\n public mutating func replaceSubrange<C>(\n _ subrange: Range<Int>,\n with newElements: __owned C\n ) where C: Collection, C.Element == Element {\n _precondition(subrange.lowerBound >= self._buffer.startIndex,\n "Array replace: subrange start is negative")\n\n _precondition(subrange.upperBound <= _buffer.endIndex,\n "Array replace: subrange extends past the end")\n\n let eraseCount = subrange.count\n let insertCount = newElements.count\n let growth = insertCount - eraseCount\n\n _reserveCapacityImpl(minimumCapacity: self.count + growth,\n growForAppend: true)\n _buffer.replaceSubrange(subrange, with: insertCount, elementsOf: newElements)\n _endMutation()\n }\n}\n\nextension Array: Equatable where Element: Equatable {\n /// Returns a Boolean value indicating whether two arrays contain the same\n /// elements in the same order.\n ///\n /// You can use the equal-to operator (`==`) to compare any two arrays\n /// that store the same, `Equatable`-conforming element type.\n ///\n /// - Parameters:\n /// - lhs: An array to compare.\n /// - rhs: Another array to compare.\n @inlinable\n public static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool {\n let lhsCount = lhs.count\n if lhsCount != rhs.count {\n return false\n }\n\n // Test referential equality.\n if unsafe lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity {\n return true\n }\n\n\n _internalInvariant(lhs.startIndex == 0 && rhs.startIndex == 0)\n _internalInvariant(lhs.endIndex == lhsCount && rhs.endIndex == lhsCount)\n\n // We know that lhs.count == rhs.count, compare element wise.\n for idx in 0..<lhsCount {\n if lhs[idx] != rhs[idx] {\n return false\n }\n }\n\n return true\n }\n}\n\nextension Array: Hashable where Element: Hashable {\n /// Hashes the essential components of this value by feeding them into the\n /// given hasher.\n ///\n /// - Parameter hasher: The hasher to use when combining the components\n /// of this instance.\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine(count) // discriminator\n for element in self {\n hasher.combine(element)\n }\n }\n}\n\nextension Array {\n /// Calls the given closure with a pointer to the underlying bytes of the\n /// array's mutable contiguous storage.\n ///\n /// The array's `Element` type must be a *trivial type*, which can be copied\n /// with just a bit-for-bit copy without any indirection or\n /// reference-counting operations. Generally, native Swift types that do not\n /// contain strong or weak references are trivial, as are imported C structs\n /// and enums.\n ///\n /// The following example copies bytes from the `byteValues` array into\n /// `numbers`, an array of `Int32`:\n ///\n /// var numbers: [Int32] = [0, 0]\n /// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00]\n ///\n /// numbers.withUnsafeMutableBytes { destBytes in\n /// byteValues.withUnsafeBytes { srcBytes in\n /// destBytes.copyBytes(from: srcBytes)\n /// }\n /// }\n /// // numbers == [1, 2]\n ///\n /// - Note: This example shows the behavior on a little-endian platform.\n ///\n /// The pointer passed as an argument to `body` is valid only for the\n /// lifetime of the closure. Do not escape it from the closure for later\n /// use.\n ///\n /// - Warning: Do not rely on anything about the array that is the target of\n /// this method during execution of the `body` closure; it might not\n /// appear to have its correct value. Instead, use only the\n /// `UnsafeMutableRawBufferPointer` argument to `body`.\n ///\n /// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer`\n /// parameter that points to the contiguous storage for the array.\n /// If no such storage exists, it is created. If `body` has a return value, that value is also\n /// used as the return value for the `withUnsafeMutableBytes(_:)` method.\n /// The argument is valid only for the duration of the closure's\n /// execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @inlinable\n public mutating func withUnsafeMutableBytes<R>(\n _ body: (UnsafeMutableRawBufferPointer) throws -> R\n ) rethrows -> R {\n return try unsafe self.withUnsafeMutableBufferPointer {\n return try unsafe body(UnsafeMutableRawBufferPointer($0))\n }\n }\n\n /// Calls the given closure with a pointer to the underlying bytes of the\n /// array's contiguous storage.\n ///\n /// The array's `Element` type must be a *trivial type*, which can be copied\n /// with just a bit-for-bit copy without any indirection or\n /// reference-counting operations. Generally, native Swift types that do not\n /// contain strong or weak references are trivial, as are imported C structs\n /// and enums.\n ///\n /// The following example copies the bytes of the `numbers` array into a\n /// buffer of `UInt8`:\n ///\n /// var numbers: [Int32] = [1, 2, 3]\n /// var byteBuffer: [UInt8] = []\n /// numbers.withUnsafeBytes {\n /// byteBuffer.append(contentsOf: $0)\n /// }\n /// // byteBuffer == [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]\n ///\n /// - Note: This example shows the behavior on a little-endian platform.\n ///\n /// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter\n /// that points to the contiguous storage for the array.\n /// If no such storage exists, it is created. If `body` has a return value, that value is also\n /// used as the return value for the `withUnsafeBytes(_:)` method. The\n /// argument is valid only for the duration of the closure's execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @inlinable\n public func withUnsafeBytes<R>(\n _ body: (UnsafeRawBufferPointer) throws -> R\n ) rethrows -> R {\n return try unsafe self.withUnsafeBufferPointer {\n try unsafe body(UnsafeRawBufferPointer($0))\n }\n }\n}\n\n#if INTERNAL_CHECKS_ENABLED\nextension Array {\n // This allows us to test the `_copyContents` implementation in\n // `_ArrayBuffer`. (It's like `_copyToContiguousArray` but it always makes a\n // copy.)\n @_alwaysEmitIntoClient\n public func _copyToNewArray() -> [Element] {\n unsafe Array(unsafeUninitializedCapacity: self.count) { buffer, count in\n var (it, c) = unsafe self._buffer._copyContents(initializing: buffer)\n _precondition(it.next() == nil)\n count = c\n }\n }\n}\n#endif\n\n#if _runtime(_ObjC)\n// We isolate the bridging of the Cocoa Array -> Swift Array here so that\n// in the future, we can eagerly bridge the Cocoa array. We need this function\n// to do the bridging in an ABI safe way. Even though this looks useless,\n// DO NOT DELETE!\n@usableFromInline internal\nfunc _bridgeCocoaArray<T>(_ _immutableCocoaArray: AnyObject) -> Array<T> {\n return Array(_buffer: _ArrayBuffer(nsArray: _immutableCocoaArray))\n}\n\nextension Array {\n @inlinable\n public // @SPI(Foundation)\n func _bridgeToObjectiveCImpl() -> AnyObject {\n return _buffer._asCocoaArray()\n }\n\n /// Tries to downcast the source `NSArray` as our native buffer type.\n /// If it succeeds, creates a new `Array` around it and returns that.\n /// Returns `nil` otherwise.\n // Note: this function exists here so that Foundation doesn't have\n // to know Array's implementation details.\n @inlinable\n public static func _bridgeFromObjectiveCAdoptingNativeStorageOf(\n _ source: AnyObject\n ) -> Array? {\n // If source is deferred, we indirect to get its native storage\n let maybeNative = (source as? __SwiftDeferredNSArray)?._nativeStorage ?? source\n\n return (maybeNative as? _ContiguousArrayStorage<Element>).map {\n Array(_ContiguousArrayBuffer($0))\n }\n }\n\n /// Private initializer used for bridging.\n ///\n /// Only use this initializer when both conditions are true:\n ///\n /// * it is statically known that the given `NSArray` is immutable;\n /// * `Element` is bridged verbatim to Objective-C (i.e.,\n /// is a reference type).\n @inlinable\n public init(_immutableCocoaArray: AnyObject) {\n self = _bridgeCocoaArray(_immutableCocoaArray)\n }\n}\n#endif\n\n@_unavailableInEmbedded\nextension Array: _HasCustomAnyHashableRepresentation\n where Element: Hashable {\n public __consuming func _toCustomAnyHashable() -> AnyHashable? {\n return AnyHashable(_box: _ArrayAnyHashableBox(self))\n }\n}\n\n@_unavailableInEmbedded\ninternal protocol _ArrayAnyHashableProtocol: _AnyHashableBox {\n var count: Int { get }\n subscript(index: Int) -> AnyHashable { get }\n}\n\n@_unavailableInEmbedded\ninternal struct _ArrayAnyHashableBox<Element: Hashable>\n : _ArrayAnyHashableProtocol {\n internal let _value: [Element]\n\n internal init(_ value: [Element]) {\n self._value = value\n }\n\n internal var _base: Any {\n return _value\n }\n\n internal var count: Int {\n return _value.count\n }\n\n internal subscript(index: Int) -> AnyHashable {\n return _value[index] as AnyHashable\n }\n\n func _isEqual(to other: _AnyHashableBox) -> Bool? {\n guard let other = other as? _ArrayAnyHashableProtocol else { return nil }\n guard _value.count == other.count else { return false }\n for i in 0 ..< _value.count {\n if self[i] != other[i] { return false }\n }\n return true\n }\n\n var _hashValue: Int {\n var hasher = Hasher()\n _hash(into: &hasher)\n return hasher.finalize()\n }\n\n func _hash(into hasher: inout Hasher) {\n hasher.combine(_value.count) // discriminator\n for i in 0 ..< _value.count {\n hasher.combine(self[i])\n }\n }\n\n func _rawHashValue(_seed: Int) -> Int {\n var hasher = Hasher(_seed: _seed)\n self._hash(into: &hasher)\n return hasher._finalize()\n }\n\n internal func _unbox<T: Hashable>() -> T? {\n return _value as? T\n }\n\n internal func _downCastConditional<T>(\n into result: UnsafeMutablePointer<T>\n ) -> Bool {\n guard let value = _value as? T else { return false }\n unsafe result.initialize(to: value)\n return true\n }\n}\n\nextension Array: @unchecked Sendable where Element: Sendable { }\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Array.swift | cpp_apple_swift_stdlib_public_core_Array.swift | Swift | 82,086 | 0.75 | 0.090094 | 0.559656 | node-utils | 764 | 2023-10-27T00:58:23.945681 | MIT | false | 615a1d654d852d9028c871ccb2069e65 |
//===--- ArrayBody.swift - Data needed once per array ---------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Array storage begins with a Body and ends with a sequence of\n// contiguous Elements. This struct describes the Body part.\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n@frozen\n@usableFromInline\ninternal struct _ArrayBody {\n @usableFromInline\n internal var _storage: _SwiftArrayBodyStorage\n\n @inlinable\n internal init(\n count: Int, capacity: Int, elementTypeIsBridgedVerbatim: Bool = false\n ) {\n _internalInvariant(count >= 0)\n _internalInvariant(capacity >= 0)\n \n _storage = _SwiftArrayBodyStorage(\n count: count,\n _capacityAndFlags:\n (UInt(truncatingIfNeeded: capacity) &<< 1) |\n (elementTypeIsBridgedVerbatim ? 1 : 0))\n }\n\n /// In principle ArrayBody shouldn't need to be default\n /// constructed, but since we want to claim all the allocated\n /// capacity after a new buffer is allocated, it's typical to want\n /// to update it immediately after construction.\n @inlinable\n internal init() {\n _storage = _SwiftArrayBodyStorage(count: 0, _capacityAndFlags: 0)\n }\n \n /// The number of elements stored in this Array.\n @inlinable\n internal var count: Int {\n get {\n return _assumeNonNegative(_storage.count)\n }\n set(newCount) {\n _storage.count = newCount\n }\n }\n\n /// The number of elements that can be stored in this Array without\n /// reallocation.\n @inlinable\n internal var capacity: Int {\n return Int(_capacityAndFlags &>> 1)\n }\n\n /// Is the Element type bitwise-compatible with some Objective-C\n /// class? The answer is---in principle---statically-knowable, but\n /// I don't expect to be able to get this information to the\n /// optimizer before 1.0 ships, so we store it in a bit here to\n /// avoid the cost of calls into the runtime that compute the\n /// answer.\n @inlinable\n internal var elementTypeIsBridgedVerbatim: Bool {\n get {\n return (_capacityAndFlags & 0x1) != 0\n }\n set {\n _capacityAndFlags\n = newValue ? _capacityAndFlags | 1 : _capacityAndFlags & ~1\n }\n }\n\n /// Storage optimization: compresses capacity and\n /// elementTypeIsBridgedVerbatim together.\n @inlinable\n internal var _capacityAndFlags: UInt {\n get {\n return _storage._capacityAndFlags\n }\n set {\n _storage._capacityAndFlags = newValue\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ArrayBody.swift | cpp_apple_swift_stdlib_public_core_ArrayBody.swift | Swift | 2,861 | 0.95 | 0.031579 | 0.360465 | node-utils | 955 | 2024-05-15T15:07:28.504824 | MIT | false | dc72e889e45dd991e66203d95022c4cb |
//===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// This is the class that implements the storage and object management for\n// Swift Array.\n//\n//===----------------------------------------------------------------------===//\n\n#if _runtime(_ObjC)\nimport SwiftShims\n\n@usableFromInline\ninternal typealias _ArrayBridgeStorage\n = _BridgeStorage<__ContiguousArrayStorageBase>\n\n@usableFromInline\n@frozen\ninternal struct _ArrayBuffer<Element>: _ArrayBufferProtocol {\n @usableFromInline\n internal var _storage: _ArrayBridgeStorage\n\n @inlinable\n internal init(storage: _ArrayBridgeStorage) {\n _storage = storage\n }\n\n /// Create an empty buffer.\n @inlinable\n internal init() {\n _storage = _ArrayBridgeStorage(native: _emptyArrayStorage)\n }\n\n @inlinable\n internal init(nsArray: AnyObject) {\n _internalInvariant(_isClassOrObjCExistential(Element.self))\n _storage = _ArrayBridgeStorage(objC: nsArray)\n }\n\n /// Returns an `_ArrayBuffer<U>` containing the same elements.\n ///\n /// - Precondition: The elements actually have dynamic type `U`, and `U`\n /// is a class or `@objc` existential.\n @inlinable\n __consuming internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> {\n _internalInvariant(_isClassOrObjCExistential(Element.self))\n _internalInvariant(_isClassOrObjCExistential(U.self))\n return _ArrayBuffer<U>(storage: _storage)\n }\n\n /// Returns an `_ArrayBuffer<U>` containing the same elements,\n /// deferring checking each element's `U`-ness until it is accessed.\n ///\n /// - Precondition: `U` is a class or `@objc` existential derived from\n /// `Element`.\n @inlinable\n __consuming internal func downcast<U>(\n toBufferWithDeferredTypeCheckOf _: U.Type\n ) -> _ArrayBuffer<U> {\n _internalInvariant(_isClassOrObjCExistential(Element.self))\n _internalInvariant(_isClassOrObjCExistential(U.self))\n \n // FIXME: can't check that U is derived from Element pending\n // <rdar://problem/20028320> generic metatype casting doesn't work\n // _internalInvariant(U.self is Element.Type)\n\n return _ArrayBuffer<U>(\n storage: _ArrayBridgeStorage(native: _native._storage, isFlagged: true))\n }\n\n @inlinable\n internal var needsElementTypeCheck: Bool {\n // NSArray's need an element typecheck when the element type isn't AnyObject\n return !_isNativeTypeChecked && !(AnyObject.self is Element.Type)\n }\n}\n\nextension _ArrayBuffer {\n /// Adopt the storage of `source`.\n @inlinable\n internal init(_buffer source: NativeBuffer, shiftedToStartIndex: Int) {\n _internalInvariant(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")\n _storage = _ArrayBridgeStorage(native: source._storage)\n }\n\n /// `true`, if the array is native and does not need a deferred type check.\n @inlinable\n internal var arrayPropertyIsNativeTypeChecked: Bool {\n return _isNativeTypeChecked\n }\n\n /// Returns `true` if this buffer's storage is uniquely referenced;\n /// otherwise, returns `false`.\n ///\n /// This function should only be used for internal soundness checks.\n /// To guard a buffer mutation, use `beginCOWMutation`.\n @inlinable\n internal mutating func isUniquelyReferenced() -> Bool {\n if !_isClassOrObjCExistential(Element.self) {\n return _storage.isUniquelyReferencedUnflaggedNative()\n }\n return _storage.isUniquelyReferencedNative()\n }\n \n /// Returns `true` and puts the buffer in a mutable state if the buffer's\n /// storage is uniquely-referenced; otherwise performs no action and\n /// returns `false`.\n ///\n /// - Precondition: The buffer must be immutable.\n ///\n /// - Warning: It's a requirement to call `beginCOWMutation` before the buffer\n /// is mutated.\n @_alwaysEmitIntoClient\n internal mutating func beginCOWMutation() -> Bool {\n let isUnique: Bool\n if !_isClassOrObjCExistential(Element.self) {\n isUnique = _storage.beginCOWMutationUnflaggedNative()\n } else if !_storage.beginCOWMutationNative() {\n return false\n } else {\n isUnique = _isNative\n }\n#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED\n if isUnique {\n _native.isImmutable = false\n }\n#endif\n return isUnique\n }\n \n /// Puts the buffer in an immutable state.\n ///\n /// - Precondition: The buffer must be mutable or the empty array singleton.\n ///\n /// - Warning: After a call to `endCOWMutation` the buffer must not be mutated\n /// until the next call of `beginCOWMutation`.\n @_alwaysEmitIntoClient\n @inline(__always)\n internal mutating func endCOWMutation() {\n#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED\n _native.isImmutable = true\n#endif\n _storage.endCOWMutation()\n }\n\n /// Convert to an NSArray.\n ///\n /// O(1) if the element type is bridged verbatim, O(*n*) otherwise.\n @inlinable\n internal func _asCocoaArray() -> AnyObject {\n return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative.buffer\n }\n\n /// Creates and returns a new uniquely referenced buffer which is a copy of\n /// this buffer.\n ///\n /// This buffer is consumed, i.e. it's released.\n @_alwaysEmitIntoClient\n @inline(never)\n @_semantics("optimize.sil.specialize.owned2guarantee.never")\n internal __consuming func _consumeAndCreateNew() -> _ArrayBuffer {\n return _consumeAndCreateNew(bufferIsUnique: false,\n minimumCapacity: count,\n growForAppend: false)\n }\n\n /// Creates and returns a new uniquely referenced buffer which is a copy of\n /// this buffer.\n ///\n /// If `bufferIsUnique` is true, the buffer is assumed to be uniquely\n /// referenced and the elements are moved - instead of copied - to the new\n /// buffer.\n /// The `minimumCapacity` is the lower bound for the new capacity.\n /// If `growForAppend` is true, the new capacity is calculated using\n /// `_growArrayCapacity`, but at least kept at `minimumCapacity`.\n ///\n /// This buffer is consumed, i.e. it's released.\n @_alwaysEmitIntoClient\n @inline(never)\n @_semantics("optimize.sil.specialize.owned2guarantee.never")\n internal __consuming func _consumeAndCreateNew(\n bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool\n ) -> _ArrayBuffer {\n let newCapacity = _growArrayCapacity(oldCapacity: capacity,\n minimumCapacity: minimumCapacity,\n growForAppend: growForAppend)\n let c = count\n _internalInvariant(newCapacity >= c)\n \n let newBuffer = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: c, minimumCapacity: newCapacity)\n\n if bufferIsUnique {\n // As an optimization, if the original buffer is unique, we can just move\n // the elements instead of copying.\n let dest = unsafe newBuffer.firstElementAddress\n unsafe dest.moveInitialize(from: mutableFirstElementAddress,\n count: c)\n _native.mutableCount = 0\n } else {\n unsafe _copyContents(\n subRange: 0..<c,\n initializing: newBuffer.mutableFirstElementAddress)\n }\n return _ArrayBuffer(_buffer: newBuffer, shiftedToStartIndex: 0)\n }\n\n /// If this buffer is backed by a uniquely-referenced mutable\n /// `_ContiguousArrayBuffer` that can be grown in-place to allow the self\n /// buffer store minimumCapacity elements, returns that buffer.\n /// Otherwise, returns `nil`.\n @inlinable\n internal mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int)\n -> NativeBuffer? {\n if _fastPath(isUniquelyReferenced()) {\n let b = _native\n if _fastPath(b.mutableCapacity >= minimumCapacity) {\n return b\n }\n }\n return nil\n }\n\n @inlinable\n internal mutating func isMutableAndUniquelyReferenced() -> Bool {\n return isUniquelyReferenced()\n }\n\n /// If this buffer is backed by a `_ContiguousArrayBuffer`\n /// containing the same number of elements as `self`, return it.\n /// Otherwise, return `nil`.\n @inlinable\n internal func requestNativeBuffer() -> NativeBuffer? {\n if !_isClassOrObjCExistential(Element.self) {\n return _native\n }\n return _fastPath(_storage.isNative) ? _native : nil\n }\n\n // We have two versions of type check: one that takes a range and the other\n // checks one element. The reason for this is that the ARC optimizer does not\n // handle loops atm. and so can get blocked by the presence of a loop (over\n // the range). This loop is not necessary for a single element access.\n @inline(never)\n @usableFromInline\n internal func _typeCheckSlowPath(_ index: Int) {\n if _fastPath(_isNative) {\n let element: AnyObject = cast(toBufferOf: AnyObject.self)._native[index]\n guard element is Element else {\n _assertionFailure(\n "Fatal error",\n """\n Down-casted Array element failed to match the target type\n Expected \(Element.self) but found \(type(of: element))\n """,\n flags: _fatalErrorFlags()\n )\n }\n }\n else {\n let element = _nonNative[index]\n guard element is Element else {\n _assertionFailure(\n "Fatal error",\n """\n NSArray element failed to match the Swift Array Element type\n Expected \(Element.self) but found \(type(of: element))\n """,\n flags: _fatalErrorFlags()\n )\n }\n }\n }\n\n @inlinable\n internal func _typeCheck(_ subRange: Range<Int>) {\n if !_isClassOrObjCExistential(Element.self) {\n return\n }\n\n if _slowPath(needsElementTypeCheck) {\n // Could be sped up, e.g. by using\n // enumerateObjectsAtIndexes:options:usingBlock: in the\n // non-native case.\n for i in subRange.lowerBound ..< subRange.upperBound {\n _typeCheckSlowPath(i)\n }\n }\n }\n\n /// Copy the elements in `bounds` from this buffer into uninitialized\n /// memory starting at `target`. Return a pointer "past the end" of the\n /// just-initialized memory.\n @inlinable\n @discardableResult\n __consuming internal func _copyContents(\n subRange bounds: Range<Int>,\n initializing target: UnsafeMutablePointer<Element>\n ) -> UnsafeMutablePointer<Element> {\n _typeCheck(bounds)\n if _fastPath(_isNative) {\n return unsafe _native._copyContents(subRange: bounds, initializing: target)\n }\n let buffer = unsafe UnsafeMutableRawPointer(target)\n .assumingMemoryBound(to: AnyObject.self)\n let result = unsafe _nonNative._copyContents(\n subRange: bounds,\n initializing: buffer)\n return unsafe UnsafeMutableRawPointer(result).assumingMemoryBound(to: Element.self)\n }\n\n @inlinable\n internal __consuming func _copyContents(\n initializing buffer: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {\n if _fastPath(_isNative) {\n let (_, c) = unsafe _native._copyContents(initializing: buffer)\n return (IndexingIterator(_elements: self, _position: c), c)\n }\n guard buffer.count > 0 else { return (makeIterator(), 0) }\n let ptr = unsafe UnsafeMutableRawPointer(buffer.baseAddress)?\n .assumingMemoryBound(to: AnyObject.self)\n let (_, c) = unsafe _nonNative._copyContents(\n initializing: UnsafeMutableBufferPointer(start: ptr, count: buffer.count))\n return (IndexingIterator(_elements: self, _position: c), c)\n }\n\n /// Returns a `_SliceBuffer` containing the given sub-range of elements in\n /// `bounds` from this buffer.\n @inlinable\n internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {\n get {\n _typeCheck(bounds)\n if _fastPath(_isNative) {\n return _native[bounds]\n }\n return _nonNative[bounds].unsafeCastElements(to: Element.self)\n }\n set {\n fatalError("not implemented")\n }\n }\n\n /// A pointer to the first element.\n ///\n /// - Precondition: The elements are known to be stored contiguously.\n @inlinable\n internal var firstElementAddress: UnsafeMutablePointer<Element> {\n _internalInvariant(_isNative, "must be a native buffer")\n return unsafe _native.firstElementAddress\n }\n\n /// A mutable pointer to the first element.\n ///\n /// - Precondition: the buffer must be mutable.\n @_alwaysEmitIntoClient\n internal var mutableFirstElementAddress: UnsafeMutablePointer<Element> {\n _internalInvariant(_isNative, "must be a native buffer")\n return unsafe _native.mutableFirstElementAddress\n }\n\n @inlinable\n internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {\n return unsafe _fastPath(_isNative) ? firstElementAddress : nil\n }\n\n /// The number of elements the buffer stores.\n ///\n /// This property is obsolete. It's only used for the ArrayBufferProtocol and\n /// to keep backward compatibility.\n /// Use `immutableCount` or `mutableCount` instead.\n @inlinable\n internal var count: Int {\n @inline(__always)\n get {\n return _fastPath(_isNative) ? _native.count : _nonNative.endIndex\n }\n set {\n _internalInvariant(_isNative, "attempting to update count of Cocoa array")\n _native.count = newValue\n }\n }\n \n /// The number of elements of the buffer.\n ///\n /// - Precondition: The buffer must be immutable.\n @_alwaysEmitIntoClient\n internal var immutableCount: Int {\n return _fastPath(_isNative) ? _native.immutableCount : _nonNative.endIndex\n }\n\n /// The number of elements of the buffer.\n ///\n /// - Precondition: The buffer must be mutable.\n @_alwaysEmitIntoClient\n internal var mutableCount: Int {\n @inline(__always)\n get {\n _internalInvariant(\n _isNative,\n "attempting to get mutating-count of non-native buffer")\n return _native.mutableCount\n }\n @inline(__always)\n set {\n _internalInvariant(_isNative, "attempting to update count of Cocoa array")\n _native.mutableCount = newValue\n }\n }\n\n /// Traps if an inout violation is detected or if the buffer is\n /// native and the subscript is out of range.\n ///\n /// wasNative == _isNative in the absence of inout violations.\n /// Because the optimizer can hoist the original check it might have\n /// been invalidated by illegal user code.\n ///\n /// This function is obsolete but must stay in the library for backward\n /// compatibility.\n @inlinable\n internal func _checkInoutAndNativeBounds(_ index: Int, wasNative: Bool) {\n _precondition(\n _isNative == wasNative,\n "inout rules were violated: the array was overwritten")\n\n if _fastPath(wasNative) {\n _native._checkValidSubscript(index)\n }\n }\n\n /// Traps if an inout violation is detected or if the buffer is\n /// native and typechecked and the subscript is out of range.\n ///\n /// wasNativeTypeChecked == _isNativeTypeChecked in the absence of\n /// inout violations. Because the optimizer can hoist the original\n /// check it might have been invalidated by illegal user code.\n ///\n /// This function is obsolete but must stay in the library for backward\n /// compatibility.\n @inlinable\n internal func _checkInoutAndNativeTypeCheckedBounds(\n _ index: Int, wasNativeTypeChecked: Bool\n ) {\n _precondition(\n _isNativeTypeChecked == wasNativeTypeChecked,\n "inout rules were violated: the array was overwritten")\n\n if _fastPath(wasNativeTypeChecked) {\n _native._checkValidSubscript(index)\n }\n }\n\n /// Traps unless the given `index` is valid for subscripting, i.e.\n /// `0 ≤ index < count`.\n ///\n /// - Precondition: The buffer must be mutable.\n @_alwaysEmitIntoClient\n internal func _checkValidSubscriptMutating(_ index: Int) {\n _native._checkValidSubscriptMutating(index)\n }\n\n /// The number of elements the buffer can store without reallocation.\n ///\n /// This property is obsolete. It's only used for the ArrayBufferProtocol and\n /// to keep backward compatibility.\n /// Use `immutableCapacity` or `mutableCapacity` instead.\n @inlinable\n internal var capacity: Int {\n return _fastPath(_isNative) ? _native.capacity : _nonNative.endIndex\n }\n\n /// The number of elements the buffer can store without reallocation.\n ///\n /// - Precondition: The buffer must be immutable.\n @_alwaysEmitIntoClient\n internal var immutableCapacity: Int {\n return _fastPath(_isNative) ? _native.immutableCapacity : _nonNative.count\n }\n \n /// The number of elements the buffer can store without reallocation.\n ///\n /// - Precondition: The buffer must be mutable.\n @_alwaysEmitIntoClient\n internal var mutableCapacity: Int {\n _internalInvariant(_isNative, "attempting to get mutating-capacity of non-native buffer")\n return _native.mutableCapacity\n }\n\n @inlinable\n @inline(__always)\n internal func getElement(_ i: Int, wasNativeTypeChecked: Bool) -> Element {\n if _fastPath(wasNativeTypeChecked) {\n return _nativeTypeChecked[i]\n }\n return unsafe unsafeBitCast(_getElementSlowPath(i), to: Element.self)\n }\n\n @inline(never)\n @inlinable // @specializable\n @_effects(notEscaping self.value**)\n @_effects(escaping self.value**.class*.value** => return.value**)\n internal func _getElementSlowPath(_ i: Int) -> AnyObject {\n _internalInvariant(\n _isClassOrObjCExistential(Element.self),\n "Only single reference elements can be indexed here.")\n let element: AnyObject\n if _isNative {\n // _checkInoutAndNativeTypeCheckedBounds does no subscript\n // checking for the native un-typechecked case. Therefore we\n // have to do it here.\n _native._checkValidSubscript(i)\n \n element = cast(toBufferOf: AnyObject.self)._native[i]\n guard element is Element else {\n _assertionFailure(\n "Fatal error",\n """\n Down-casted Array element failed to match the target type\n Expected \(Element.self) but found \(type(of: element))\n """,\n flags: _fatalErrorFlags()\n )\n }\n } else {\n // ObjC arrays do their own subscript checking.\n element = _nonNative[i]\n guard element is Element else {\n _assertionFailure(\n "Fatal error",\n """\n NSArray element failed to match the Swift Array Element type\n Expected \(Element.self) but found \(type(of: element))\n """,\n flags: _fatalErrorFlags()\n )\n }\n }\n return element\n }\n\n /// Get or set the value of the ith element.\n @inlinable\n internal subscript(i: Int) -> Element {\n get {\n return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked)\n }\n \n nonmutating set {\n if _fastPath(_isNative) {\n _native[i] = newValue\n }\n else {\n var refCopy = self\n refCopy.replaceSubrange(\n i..<(i + 1),\n with: 1,\n elementsOf: CollectionOfOne(newValue))\n }\n }\n }\n\n @inlinable @_alwaysEmitIntoClient\n static var associationKey: UnsafeRawPointer {\n //We never dereference this, we just need an address to use as a unique key\n unsafe UnsafeRawPointer(Builtin.addressof(&_swiftEmptyArrayStorage))\n }\n \n @inlinable @_alwaysEmitIntoClient\n internal func getAssociatedBuffer() -> _ContiguousArrayBuffer<Element>? {\n let getter = unsafe unsafeBitCast(\n getGetAssociatedObjectPtr(),\n to: (@convention(c)(\n AnyObject,\n UnsafeRawPointer\n ) -> UnsafeRawPointer?).self\n )\n if let assocPtr = unsafe getter(\n _storage.objCInstance,\n _ArrayBuffer.associationKey\n ) {\n let buffer: _ContiguousArrayStorage<Element>\n buffer = unsafe Unmanaged.fromOpaque(assocPtr).takeUnretainedValue()\n return _ContiguousArrayBuffer(buffer)\n }\n return nil\n }\n \n @inlinable @_alwaysEmitIntoClient\n internal func setAssociatedBuffer(_ buffer: _ContiguousArrayBuffer<Element>) {\n let setter = unsafe unsafeBitCast(getSetAssociatedObjectPtr(), to: (@convention(c)(\n AnyObject,\n UnsafeRawPointer,\n AnyObject?,\n UInt\n ) -> Void).self)\n unsafe setter(\n _storage.objCInstance,\n _ArrayBuffer.associationKey,\n buffer._storage,\n 1 //OBJC_ASSOCIATION_RETAIN_NONATOMIC\n )\n }\n\n @_alwaysEmitIntoClient\n internal func getOrAllocateAssociatedObjectBuffer(\n ) -> _ContiguousArrayBuffer<Element> {\n let unwrapped: _ContiguousArrayBuffer<Element>\n // libobjc already provides the necessary memory barriers for\n // double checked locking to be safe, per comments on\n // https://github.com/swiftlang/swift/pull/75148\n if let associatedBuffer = getAssociatedBuffer() {\n unwrapped = associatedBuffer\n } else {\n let lock = _storage.objCInstance\n objc_sync_enter(lock)\n var associatedBuffer = getAssociatedBuffer()\n if let associatedBuffer {\n unwrapped = associatedBuffer\n } else {\n associatedBuffer = ContiguousArray(self)._buffer\n unwrapped = unsafe associatedBuffer.unsafelyUnwrapped\n setAssociatedBuffer(unwrapped)\n }\n defer { _fixLifetime(unwrapped) }\n objc_sync_exit(lock)\n }\n return unwrapped\n }\n\n @_alwaysEmitIntoClient @inline(never)\n internal func withUnsafeBufferPointer_nonNative<R, E>(\n _ body: (UnsafeBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n let buffer = getOrAllocateAssociatedObjectBuffer()\n let (pointer, count) = unsafe (buffer.firstElementAddress, buffer.count)\n return try unsafe body(UnsafeBufferPointer(start: pointer, count: count))\n }\n \n /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the\n /// underlying contiguous storage. If no such storage exists, it is\n /// created on-demand.\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n @usableFromInline\n @_silgen_name("$ss12_ArrayBufferV010withUnsafeB7Pointeryqd__qd__SRyxGKXEKlF")\n internal func __abi_withUnsafeBufferPointer<R>(\n _ body: (UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R {\n if _fastPath(_isNative) {\n defer { _fixLifetime(self) }\n return try unsafe body(\n UnsafeBufferPointer(start: firstElementAddress, count: count))\n }\n return try unsafe ContiguousArray(self).withUnsafeBufferPointer(body)\n }\n\n /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the\n /// underlying contiguous storage. If no such storage exists, it is\n /// created on-demand.\n @_alwaysEmitIntoClient\n internal func withUnsafeBufferPointer<R, E>(\n _ body: (UnsafeBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n if _fastPath(_isNative) {\n defer { _fixLifetime(self) }\n return try unsafe body(\n UnsafeBufferPointer(start: firstElementAddress, count: count))\n }\n return try unsafe withUnsafeBufferPointer_nonNative(body)\n }\n\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n @usableFromInline\n @_silgen_name("$ss12_ArrayBufferV017withUnsafeMutableB7Pointeryqd__qd__SryxGKXEKlF")\n internal mutating func __abi_withUnsafeMutableBufferPointer<R>(\n _ body: (UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R {\n return try unsafe withUnsafeMutableBufferPointer(body)\n }\n\n /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`\n /// over the underlying contiguous storage.\n ///\n /// - Precondition: Such contiguous storage exists or the buffer is empty.\n @_alwaysEmitIntoClient\n internal mutating func withUnsafeMutableBufferPointer<R, E>(\n _ body: (UnsafeMutableBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n _internalInvariant(\n _isNative || count == 0,\n "Array is bridging an opaque NSArray; can't get a pointer to the elements"\n )\n defer { _fixLifetime(self) }\n return try unsafe body(UnsafeMutableBufferPointer(\n start: firstElementAddressIfContiguous, count: count))\n }\n \n /// An object that keeps the elements stored in this buffer alive.\n @inlinable\n internal var owner: AnyObject {\n return _fastPath(_isNative) ? _native._storage : _nonNative.buffer\n }\n \n /// An object that keeps the elements stored in this buffer alive.\n ///\n /// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`.\n @inlinable\n internal var nativeOwner: AnyObject {\n _internalInvariant(_isNative, "Expect a native array")\n return _native._storage\n }\n\n /// A value that identifies the storage used by the buffer. Two\n /// buffers address the same elements when they have the same\n /// identity and count.\n @inlinable\n internal var identity: UnsafeRawPointer {\n if _isNative {\n return unsafe _native.identity\n }\n else {\n return unsafe UnsafeRawPointer(\n Unmanaged.passUnretained(_nonNative.buffer).toOpaque())\n }\n }\n \n //===--- Collection conformance -------------------------------------===//\n /// The position of the first element in a non-empty collection.\n ///\n /// In an empty collection, `startIndex == endIndex`.\n @inlinable\n internal var startIndex: Int {\n return 0\n }\n\n /// The collection's "past the end" position.\n ///\n /// `endIndex` is not a valid argument to `subscript`, and is always\n /// reachable from `startIndex` by zero or more applications of\n /// `index(after:)`.\n @inlinable\n internal var endIndex: Int {\n return count\n }\n\n @usableFromInline\n internal typealias Indices = Range<Int>\n\n //===--- private --------------------------------------------------------===//\n internal typealias Storage = _ContiguousArrayStorage<Element>\n @usableFromInline\n internal typealias NativeBuffer = _ContiguousArrayBuffer<Element>\n\n @inlinable\n internal var _isNative: Bool {\n if !_isClassOrObjCExistential(Element.self) {\n return true\n } else {\n return _storage.isNative\n }\n }\n\n /// `true`, if the array is native and does not need a deferred type check.\n @inlinable\n internal var _isNativeTypeChecked: Bool {\n if !_isClassOrObjCExistential(Element.self) {\n return true\n } else {\n return _storage.isUnflaggedNative\n }\n }\n\n /// Our native representation.\n ///\n /// - Precondition: `_isNative`.\n @inlinable\n internal var _native: NativeBuffer {\n return NativeBuffer(\n _isClassOrObjCExistential(Element.self)\n ? _storage.nativeInstance : _storage.unflaggedNativeInstance)\n }\n\n /// Fast access to the native representation.\n ///\n /// - Precondition: `_isNativeTypeChecked`.\n @inlinable\n internal var _nativeTypeChecked: NativeBuffer {\n return NativeBuffer(_storage.unflaggedNativeInstance)\n }\n\n @inlinable\n internal var _nonNative: _CocoaArrayWrapper {\n get {\n _internalInvariant(_isClassOrObjCExistential(Element.self))\n return _CocoaArrayWrapper(_storage.objCInstance)\n }\n }\n}\n\nextension _ArrayBuffer: @unchecked Sendable\n where Element: Sendable { }\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ArrayBuffer.swift | cpp_apple_swift_stdlib_public_core_ArrayBuffer.swift | Swift | 27,043 | 0.95 | 0.091245 | 0.260811 | awesome-app | 68 | 2023-07-25T23:42:34.844385 | BSD-3-Clause | false | 6b56bde67eee933bd7df7904755f69cd |
//===--- ArrayBufferProtocol.swift ----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// The underlying buffer for an ArrayType conforms to\n/// `_ArrayBufferProtocol`. This buffer does not provide value semantics.\n@usableFromInline\ninternal protocol _ArrayBufferProtocol\n : MutableCollection, RandomAccessCollection \nwhere Indices == Range<Int> {\n\n /// Create an empty buffer.\n init()\n\n /// Adopt the entire buffer, presenting it at the provided `startIndex`.\n init(_buffer: _ContiguousArrayBuffer<Element>, shiftedToStartIndex: Int)\n\n init(copying buffer: Self)\n\n /// Copy the elements in `bounds` from this buffer into uninitialized\n /// memory starting at `target`. Return a pointer "past the end" of the\n /// just-initialized memory.\n @discardableResult\n __consuming func _copyContents(\n subRange bounds: Range<Int>,\n initializing target: UnsafeMutablePointer<Element>\n ) -> UnsafeMutablePointer<Element>\n\n /// If this buffer is backed by a uniquely-referenced mutable\n /// `_ContiguousArrayBuffer` that can be grown in-place to allow the `self`\n /// buffer store `minimumCapacity` elements, returns that buffer.\n /// Otherwise, returns `nil`.\n ///\n /// - Note: The result's firstElementAddress may not match ours, if we are a\n /// _SliceBuffer.\n ///\n /// - Note: This function must remain mutating; otherwise the buffer\n /// may acquire spurious extra references, which will cause\n /// unnecessary reallocation.\n mutating func requestUniqueMutableBackingBuffer(\n minimumCapacity: Int\n ) -> _ContiguousArrayBuffer<Element>?\n\n /// Returns `true` if this buffer is backed by a uniquely-referenced mutable\n /// _ContiguousArrayBuffer; otherwise, returns `false`.\n ///\n /// - Note: This function must remain mutating; otherwise the buffer\n /// may acquire spurious extra references, which will cause\n /// unnecessary reallocation.\n mutating func isMutableAndUniquelyReferenced() -> Bool\n\n /// If this buffer is backed by a `_ContiguousArrayBuffer`\n /// containing the same number of elements as `self`, return it.\n /// Otherwise, return `nil`.\n func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>?\n\n /// Replace the given `subRange` with the first `newCount` elements of\n /// the given collection.\n ///\n /// - Precondition: This buffer is backed by a uniquely-referenced\n /// `_ContiguousArrayBuffer`.\n mutating func replaceSubrange<C>(\n _ subrange: Range<Int>,\n with newCount: Int,\n elementsOf newValues: __owned C\n ) where C: Collection, C.Element == Element\n\n /// Returns a `_SliceBuffer` containing the elements in `bounds`.\n subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get }\n\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n func withUnsafeBufferPointer<R>(\n _ body: (UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R\n\n /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the\n /// underlying contiguous storage. If no such storage exists, it is\n /// created on-demand.\n @available(SwiftStdlib 6.1, *)\n func withUnsafeBufferPointer<R, E>(\n _ body: (UnsafeBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R\n\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n mutating func withUnsafeMutableBufferPointer<R>(\n _ body: (UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R\n\n /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`\n /// over the underlying contiguous storage.\n ///\n /// - Precondition: Such contiguous storage exists or the buffer is empty.\n @available(SwiftStdlib 6.1, *)\n mutating func withUnsafeMutableBufferPointer<R, E>(\n _ body: (UnsafeMutableBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R\n\n /// The number of elements the buffer stores.\n override var count: Int { get set }\n\n /// The number of elements the buffer can store without reallocation.\n var capacity: Int { get }\n\n #if $Embedded\n typealias AnyObject = Builtin.NativeObject\n #endif\n\n /// An object that keeps the elements stored in this buffer alive.\n var owner: AnyObject { get }\n\n /// A pointer to the first element.\n ///\n /// - Precondition: The elements are known to be stored contiguously.\n var firstElementAddress: UnsafeMutablePointer<Element> { get }\n\n /// If the elements are stored contiguously, a pointer to the first\n /// element. Otherwise, `nil`.\n var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { get }\n\n /// Returns a base address to which you can add an index `i` to get the\n /// address of the corresponding element at `i`.\n var subscriptBaseAddress: UnsafeMutablePointer<Element> { get }\n\n /// A value that identifies the storage used by the buffer. Two\n /// buffers address the same elements when they have the same\n /// identity and count.\n var identity: UnsafeRawPointer { get }\n}\n\nextension _ArrayBufferProtocol {\n @inlinable\n internal var subscriptBaseAddress: UnsafeMutablePointer<Element> {\n return unsafe firstElementAddress\n }\n\n // Make sure the compiler does not inline _copyBuffer to reduce code size.\n @inline(never)\n @inlinable // This code should be specializable such that copying an array is\n // fast and does not end up in an unspecialized entry point.\n internal init(copying buffer: Self) {\n let newBuffer = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: buffer.count, minimumCapacity: buffer.count)\n unsafe buffer._copyContents(\n subRange: buffer.indices,\n initializing: newBuffer.firstElementAddress)\n self = Self( _buffer: newBuffer, shiftedToStartIndex: buffer.startIndex)\n }\n\n @inlinable\n internal mutating func replaceSubrange<C>(\n _ subrange: Range<Int>,\n with newCount: Int,\n elementsOf newValues: __owned C\n ) where C: Collection, C.Element == Element {\n _internalInvariant(startIndex == 0, "_SliceBuffer should override this function.")\n let elements = unsafe self.firstElementAddress\n\n // erase all the elements we're replacing to create a hole\n let holeStart = unsafe elements + subrange.lowerBound\n let holeEnd = unsafe holeStart + newCount\n let eraseCount = subrange.count\n unsafe holeStart.deinitialize(count: eraseCount)\n\n let growth = newCount - eraseCount\n\n if growth != 0 {\n let tailStart = unsafe elements + subrange.upperBound\n let tailCount = self.count - subrange.upperBound\n unsafe holeEnd.moveInitialize(from: tailStart, count: tailCount)\n self.count += growth\n }\n\n // don't use UnsafeMutableBufferPointer.initialize(fromContentsOf:)\n // since it behaves differently on collections that misreport count,\n // and breaks validation tests for those usecases / potentially\n // breaks ABI guarantees.\n if newCount > 0 {\n let done: Void? = newValues.withContiguousStorageIfAvailable {\n _precondition(\n $0.count == newCount,\n "invalid Collection: count differed in successive traversals"\n )\n unsafe holeStart.initialize(from: $0.baseAddress!, count: newCount)\n }\n if done == nil {\n var place = unsafe holeStart\n var i = newValues.startIndex\n while unsafe place < holeEnd {\n unsafe place.initialize(to: newValues[i])\n unsafe place += 1\n newValues.formIndex(after: &i)\n }\n _expectEnd(of: newValues, is: i)\n }\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ArrayBufferProtocol.swift | cpp_apple_swift_stdlib_public_core_ArrayBufferProtocol.swift | Swift | 7,871 | 0.95 | 0.086957 | 0.432584 | react-lib | 30 | 2023-10-25T20:36:59.807482 | BSD-3-Clause | false | 6b5b6aeb07049748d0a3fb00a8c36de4 |
//===--- ArrayCast.swift - Casts and conversions for Array ----------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Because NSArray is effectively an [AnyObject], casting [T] -> [U]\n// is an integral part of the bridging process and these two issues\n// are handled together.\n//\n//===----------------------------------------------------------------------===//\n\n/// Called by the casting machinery.\n@_silgen_name("_swift_arrayDownCastIndirect")\ninternal func _arrayDownCastIndirect<SourceValue, TargetValue>(\n _ source: UnsafePointer<Array<SourceValue>>,\n _ target: UnsafeMutablePointer<Array<TargetValue>>) {\n unsafe target.initialize(to: _arrayForceCast(source.pointee))\n}\n\n/// Implements `source as! [TargetElement]`.\n///\n/// - Note: When SourceElement and TargetElement are both bridged verbatim, type\n/// checking is deferred until elements are actually accessed.\n@inlinable //for performance reasons\npublic func _arrayForceCast<SourceElement, TargetElement>(\n _ source: Array<SourceElement>\n) -> Array<TargetElement> {\n#if _runtime(_ObjC)\n if _isClassOrObjCExistential(SourceElement.self)\n && _isClassOrObjCExistential(TargetElement.self) {\n let src = source._buffer\n if let native = src.requestNativeBuffer() {\n if native.storesOnlyElementsOfType(TargetElement.self) {\n // A native buffer that is known to store only elements of the\n // TargetElement can be used directly\n return Array(_buffer: src.cast(toBufferOf: TargetElement.self))\n }\n // Other native buffers must use deferred element type checking\n return Array(_buffer:\n src.downcast(toBufferWithDeferredTypeCheckOf: TargetElement.self))\n }\n return Array(_immutableCocoaArray: source._buffer._asCocoaArray())\n }\n#endif\n return source.map { $0 as! TargetElement }\n}\n\n/// Called by the casting machinery.\n@_silgen_name("_swift_arrayDownCastConditionalIndirect")\ninternal func _arrayDownCastConditionalIndirect<SourceValue, TargetValue>(\n _ source: UnsafePointer<Array<SourceValue>>,\n _ target: UnsafeMutablePointer<Array<TargetValue>>\n) -> Bool {\n if let result: Array<TargetValue> = unsafe _arrayConditionalCast(source.pointee) {\n unsafe target.initialize(to: result)\n return true\n }\n return false\n}\n\n/// Implements `source as? [TargetElement]`: convert each element of\n/// `source` to a `TargetElement` and return the resulting array, or\n/// return `nil` if any element fails to convert.\n///\n/// - Complexity: O(n), because each element must be checked.\n@inlinable //for performance reasons\n@_semantics("array.conditional_cast")\npublic func _arrayConditionalCast<SourceElement, TargetElement>(\n _ source: [SourceElement]\n) -> [TargetElement]? {\n var successfulCasts = ContiguousArray<TargetElement>()\n successfulCasts.reserveCapacity(source.count)\n for element in source {\n if let casted = element as? TargetElement {\n successfulCasts.append(casted)\n } else {\n return nil\n }\n }\n return Array(successfulCasts)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ArrayCast.swift | cpp_apple_swift_stdlib_public_core_ArrayCast.swift | Swift | 3,392 | 0.8 | 0.147727 | 0.392857 | python-kit | 163 | 2024-02-05T02:40:42.024712 | GPL-3.0 | false | 1291b39b6c7b4a356510f68c3db13fd4 |
//===--- ArrayShared.swift ------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n\n/// This type is used as a result of the `_checkSubscript` call to associate the\n/// call with the array access call it guards.\n///\n/// In order for the optimizer see that a call to `_checkSubscript` is semantically\n/// associated with an array access, a value of this type is returned and later passed\n/// to the accessing function. For example, a typical call to `_getElement` looks like\n/// let token = _checkSubscript(index, ...)\n/// return _getElement(index, ... , matchingSubscriptCheck: token)\n@frozen\npublic struct _DependenceToken {\n @inlinable\n public init() {\n }\n}\n\n/// Returns an Array of `_count` uninitialized elements using the\n/// given `storage`, and a pointer to uninitialized memory for the\n/// first element.\n///\n/// This function is referenced by the compiler to allocate array literals.\n///\n/// - Precondition: `storage` is `_ContiguousArrayStorage`.\n@inlinable // FIXME(inline-always)\n@inline(__always)\n@_semantics("array.uninitialized_intrinsic")\npublic // COMPILER_INTRINSIC\nfunc _allocateUninitializedArray<Element>(_ builtinCount: Builtin.Word)\n -> (Array<Element>, Builtin.RawPointer) {\n let count = Int(builtinCount)\n if count > 0 {\n // Doing the actual buffer allocation outside of the array.uninitialized\n // semantics function enables stack propagation of the buffer.\n #if !$Embedded\n let bufferObject = Builtin.allocWithTailElems_1(\n getContiguousArrayStorageType(for: Element.self), builtinCount, Element.self)\n #else\n let bufferObject = Builtin.allocWithTailElems_1(\n _ContiguousArrayStorage<Element>.self, builtinCount, Element.self)\n #endif\n\n let (array, ptr) = unsafe Array<Element>._adoptStorage(bufferObject, count: count)\n return (array, ptr._rawValue)\n }\n // For an empty array no buffer allocation is needed.\n let (array, ptr) = unsafe Array<Element>._allocateUninitialized(count)\n return (array, ptr._rawValue)\n}\n\n// Referenced by the compiler to deallocate array literals on the\n// error path.\n@inlinable\n@_semantics("array.dealloc_uninitialized")\npublic // COMPILER_INTRINSIC\nfunc _deallocateUninitializedArray<Element>(\n _ array: __owned Array<Element>\n) {\n var array = array\n array._deallocateUninitialized()\n}\n\n#if !INTERNAL_CHECKS_ENABLED\n@_alwaysEmitIntoClient\n@_semantics("array.finalize_intrinsic")\n@_effects(readnone)\n@_effects(escaping array.value** => return.value**)\n@_effects(escaping array.value**.class*.value** => return.value**.class*.value**)\npublic // COMPILER_INTRINSIC\nfunc _finalizeUninitializedArray<Element>(\n _ array: __owned Array<Element>\n) -> Array<Element> {\n var mutableArray = array\n mutableArray._endMutation()\n return mutableArray\n}\n#else\n// When asserts are enabled, _endCOWMutation writes to _native.isImmutable\n// So we cannot have @_effects(readnone)\n@_alwaysEmitIntoClient\n@_semantics("array.finalize_intrinsic")\npublic // COMPILER_INTRINSIC\nfunc _finalizeUninitializedArray<Element>(\n _ array: __owned Array<Element>\n) -> Array<Element> {\n var mutableArray = array\n mutableArray._endMutation()\n return mutableArray\n}\n#endif\n\n@_unavailableInEmbedded\nextension Collection { \n // Utility method for collections that wish to implement\n // CustomStringConvertible and CustomDebugStringConvertible using a bracketed\n // list of elements, like an array.\n internal func _makeCollectionDescription(\n withTypeName type: String? = nil\n ) -> String {\n#if !SWIFT_STDLIB_STATIC_PRINT\n var result = ""\n if let type = type {\n result += "\(type)(["\n } else {\n result += "["\n }\n\n var first = true\n for item in self {\n if first {\n first = false\n } else {\n result += ", "\n }\n #if !$Embedded\n debugPrint(item, terminator: "", to: &result)\n #else\n "(cannot print value in embedded Swift)".write(to: &result)\n #endif\n }\n result += type != nil ? "])" : "]"\n return result\n#else\n return "(collection printing not available)"\n#endif\n }\n}\n\nextension _ArrayBufferProtocol {\n @inlinable // FIXME: @useableFromInline (https://github.com/apple/swift/issues/50130).\n @inline(never)\n internal mutating func _arrayOutOfPlaceReplace<C: Collection>(\n _ bounds: Range<Int>,\n with newValues: __owned C,\n count insertCount: Int\n ) where C.Element == Element {\n\n let growth = insertCount - bounds.count\n let newCount = self.count + growth\n var newBuffer = _forceCreateUniqueMutableBuffer(\n newCount: newCount, requiredCapacity: newCount)\n\n unsafe _arrayOutOfPlaceUpdate(\n &newBuffer, bounds.lowerBound - startIndex, insertCount,\n { rawMemory, count in\n var p = unsafe rawMemory\n var q = newValues.startIndex\n for _ in 0..<count {\n unsafe p.initialize(to: newValues[q])\n newValues.formIndex(after: &q)\n unsafe p += 1\n }\n _expectEnd(of: newValues, is: q)\n }\n )\n }\n}\n\n/// A _debugPrecondition check that `i` has exactly reached the end of\n/// `s`. This test is never used to ensure memory safety; that is\n/// always guaranteed by measuring `s` once and re-using that value.\n@inlinable\ninternal func _expectEnd<C: Collection>(of s: C, is i: C.Index) {\n _debugPrecondition(\n i == s.endIndex,\n "invalid Collection: count differed in successive traversals")\n}\n\n@inlinable\ninternal func _growArrayCapacity(_ capacity: Int) -> Int {\n return capacity * 2\n}\n\n@_alwaysEmitIntoClient\ninternal func _growArrayCapacity(\n oldCapacity: Int, minimumCapacity: Int, growForAppend: Bool\n) -> Int {\n if growForAppend {\n if oldCapacity < minimumCapacity {\n // When appending to an array, grow exponentially.\n return Swift.max(minimumCapacity, _growArrayCapacity(oldCapacity))\n }\n return oldCapacity\n }\n // If not for append, just use the specified capacity, ignoring oldCapacity.\n // This means that we "shrink" the buffer in case minimumCapacity is less\n // than oldCapacity.\n return minimumCapacity\n}\n\n//===--- generic helpers --------------------------------------------------===//\n\nextension _ArrayBufferProtocol {\n /// Create a unique mutable buffer that has enough capacity to hold 'newCount'\n /// elements and at least 'requiredCapacity' elements. Set the count of the new\n /// buffer to 'newCount'. The content of the buffer is uninitialized.\n /// The formula used to compute the new buffers capacity is:\n /// max(requiredCapacity, source.capacity) if newCount <= source.capacity\n /// max(requiredCapacity, _growArrayCapacity(source.capacity)) otherwise\n @inline(never)\n @inlinable // @specializable\n internal func _forceCreateUniqueMutableBuffer(\n newCount: Int, requiredCapacity: Int\n ) -> _ContiguousArrayBuffer<Element> {\n return _forceCreateUniqueMutableBufferImpl(\n countForBuffer: newCount, minNewCapacity: newCount,\n requiredCapacity: requiredCapacity)\n }\n\n /// Create a unique mutable buffer that has enough capacity to hold\n /// 'minNewCapacity' elements and set the count of the new buffer to\n /// 'countForNewBuffer'. The content of the buffer uninitialized.\n /// The formula used to compute the new buffers capacity is:\n /// max(minNewCapacity, source.capacity) if minNewCapacity <= source.capacity\n /// max(minNewCapacity, _growArrayCapacity(source.capacity)) otherwise\n @inline(never)\n @inlinable // @specializable\n internal func _forceCreateUniqueMutableBuffer(\n countForNewBuffer: Int, minNewCapacity: Int\n ) -> _ContiguousArrayBuffer<Element> {\n return _forceCreateUniqueMutableBufferImpl(\n countForBuffer: countForNewBuffer, minNewCapacity: minNewCapacity,\n requiredCapacity: minNewCapacity)\n }\n\n /// Create a unique mutable buffer that has enough capacity to hold\n /// 'minNewCapacity' elements and at least 'requiredCapacity' elements and set\n /// the count of the new buffer to 'countForBuffer'. The content of the buffer\n /// uninitialized.\n /// The formula used to compute the new capacity is:\n /// max(requiredCapacity, source.capacity) if minNewCapacity <= source.capacity\n /// max(requiredCapacity, _growArrayCapacity(source.capacity)) otherwise\n @inlinable\n internal func _forceCreateUniqueMutableBufferImpl(\n countForBuffer: Int, minNewCapacity: Int,\n requiredCapacity: Int\n ) -> _ContiguousArrayBuffer<Element> {\n _internalInvariant(countForBuffer >= 0)\n _internalInvariant(requiredCapacity >= countForBuffer)\n _internalInvariant(minNewCapacity >= countForBuffer)\n\n let minimumCapacity = Swift.max(requiredCapacity,\n minNewCapacity > capacity\n ? _growArrayCapacity(capacity) : capacity)\n\n return _ContiguousArrayBuffer(\n _uninitializedCount: countForBuffer, minimumCapacity: minimumCapacity)\n }\n}\n\nextension _ArrayBufferProtocol {\n /// Initialize the elements of dest by copying the first headCount\n /// items from source, calling initializeNewElements on the next\n /// uninitialized element, and finally by copying the last N items\n /// from source into the N remaining uninitialized elements of dest.\n ///\n /// As an optimization, may move elements out of source rather than\n /// copying when it isUniquelyReferenced.\n @inline(never)\n @inlinable // @specializable\n internal mutating func _arrayOutOfPlaceUpdate(\n _ dest: inout _ContiguousArrayBuffer<Element>,\n _ headCount: Int, // Count of initial source elements to copy/move\n _ newCount: Int, // Number of new elements to insert\n _ initializeNewElements: \n ((UnsafeMutablePointer<Element>, _ count: Int) -> ()) = { ptr, count in\n _internalInvariant(count == 0)\n }\n ) {\n\n _internalInvariant(headCount >= 0)\n _internalInvariant(newCount >= 0)\n\n // Count of trailing source elements to copy/move\n let sourceCount = self.count\n let tailCount = dest.count - headCount - newCount\n _internalInvariant(headCount + tailCount <= sourceCount)\n\n let oldCount = sourceCount - headCount - tailCount\n let destStart = unsafe dest.firstElementAddress\n let newStart = unsafe destStart + headCount\n let newEnd = unsafe newStart + newCount\n\n // Check to see if we have storage we can move from\n if let backing = requestUniqueMutableBackingBuffer(\n minimumCapacity: sourceCount) {\n\n let sourceStart = unsafe firstElementAddress\n let oldStart = unsafe sourceStart + headCount\n\n // Destroy any items that may be lurking in a _SliceBuffer before\n // its real first element\n let backingStart = unsafe backing.firstElementAddress\n let sourceOffset = unsafe sourceStart - backingStart\n unsafe backingStart.deinitialize(count: sourceOffset)\n\n // Move the head items\n unsafe destStart.moveInitialize(from: sourceStart, count: headCount)\n\n // Destroy unused source items\n unsafe oldStart.deinitialize(count: oldCount)\n\n unsafe initializeNewElements(newStart, newCount)\n\n // Move the tail items\n unsafe newEnd.moveInitialize(from: oldStart + oldCount, count: tailCount)\n\n // Destroy any items that may be lurking in a _SliceBuffer after\n // its real last element\n let backingEnd = unsafe backingStart + backing.count\n let sourceEnd = unsafe sourceStart + sourceCount\n unsafe sourceEnd.deinitialize(count: backingEnd - sourceEnd)\n backing.count = 0\n }\n else {\n let headStart = startIndex\n let headEnd = headStart + headCount\n let newStart = unsafe _copyContents(\n subRange: headStart..<headEnd,\n initializing: destStart)\n unsafe initializeNewElements(newStart, newCount)\n let tailStart = headEnd + oldCount\n let tailEnd = endIndex\n unsafe _copyContents(subRange: tailStart..<tailEnd, initializing: newEnd)\n }\n self = Self(_buffer: dest, shiftedToStartIndex: startIndex)\n }\n}\n\nextension _ArrayBufferProtocol {\n @inline(never)\n @usableFromInline\n internal mutating func _outlinedMakeUniqueBuffer(bufferCount: Int) {\n\n if _fastPath(\n requestUniqueMutableBackingBuffer(minimumCapacity: bufferCount) != nil) {\n return\n }\n\n var newBuffer = _forceCreateUniqueMutableBuffer(\n newCount: bufferCount, requiredCapacity: bufferCount)\n unsafe _arrayOutOfPlaceUpdate(&newBuffer, bufferCount, 0)\n }\n\n /// Append items from `newItems` to a buffer.\n @inlinable\n internal mutating func _arrayAppendSequence<S: Sequence>(\n _ newItems: __owned S\n ) where S.Element == Element {\n \n // this function is only ever called from append(contentsOf:)\n // which should always have exhausted its capacity before calling\n _internalInvariant(count == capacity)\n var newCount = self.count\n\n // there might not be any elements to append remaining,\n // so check for nil element first, then increase capacity,\n // then inner-loop to fill that capacity with elements\n var stream = newItems.makeIterator()\n var nextItem = stream.next()\n while nextItem != nil {\n\n // grow capacity, first time around and when filled\n var newBuffer = _forceCreateUniqueMutableBuffer(\n countForNewBuffer: newCount, \n // minNewCapacity handles the exponential growth, just\n // need to request 1 more than current count/capacity\n minNewCapacity: newCount + 1)\n\n unsafe _arrayOutOfPlaceUpdate(&newBuffer, newCount, 0)\n\n let currentCapacity = self.capacity\n let base = unsafe self.firstElementAddress\n\n // fill while there is another item and spare capacity\n while let next = nextItem, newCount < currentCapacity {\n unsafe (base + newCount).initialize(to: next)\n newCount += 1\n nextItem = stream.next()\n }\n self.count = newCount\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ArrayShared.swift | cpp_apple_swift_stdlib_public_core_ArrayShared.swift | Swift | 14,043 | 0.95 | 0.086514 | 0.284091 | python-kit | 565 | 2025-01-23T06:37:21.395739 | BSD-3-Clause | false | 749edc43bcf84048bfd31f947f0a557f |
//===--- ArraySlice.swift -------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// - `ArraySlice<Element>` presents an arbitrary subsequence of some\n// contiguous sequence of `Element`s.\n//\n//===----------------------------------------------------------------------===//\n\n/// A slice of an `Array`, `ContiguousArray`, or `ArraySlice` instance.\n///\n/// The `ArraySlice` type makes it fast and efficient for you to perform\n/// operations on sections of a larger array. Instead of copying over the\n/// elements of a slice to new storage, an `ArraySlice` instance presents a\n/// view onto the storage of a larger array. And because `ArraySlice`\n/// presents the same interface as `Array`, you can generally perform the\n/// same operations on a slice as you could on the original array.\n///\n/// For more information about using arrays, see `Array` and `ContiguousArray`,\n/// with which `ArraySlice` shares most properties and methods.\n///\n/// Slices Are Views onto Arrays\n/// ============================\n///\n/// For example, suppose you have an array holding the number of absences\n/// from each class during a session.\n///\n/// let absences = [0, 2, 0, 4, 0, 3, 1, 0]\n///\n/// You want to compare the absences in the first half of the session with\n/// those in the second half. To do so, start by creating two slices of the\n/// `absences` array.\n///\n/// let midpoint = absences.count / 2\n///\n/// let firstHalf = absences[..<midpoint]\n/// let secondHalf = absences[midpoint...]\n///\n/// Neither the `firstHalf` nor `secondHalf` slices allocate any new storage\n/// of their own. Instead, each presents a view onto the storage of the\n/// `absences` array.\n///\n/// You can call any method on the slices that you might have called on the\n/// `absences` array. To learn which half had more absences, use the\n/// `reduce(_:_:)` method to calculate each sum.\n///\n/// let firstHalfSum = firstHalf.reduce(0, +)\n/// let secondHalfSum = secondHalf.reduce(0, +)\n///\n/// if firstHalfSum > secondHalfSum {\n/// print("More absences in the first half.")\n/// } else {\n/// print("More absences in the second half.")\n/// }\n/// // Prints "More absences in the first half."\n///\n/// - Important: Long-term storage of `ArraySlice` instances is discouraged. A\n/// slice holds a reference to the entire storage of a larger array, not\n/// just to the portion it presents, even after the original array's lifetime\n/// ends. Long-term storage of a slice may therefore prolong the lifetime of\n/// elements that are no longer otherwise accessible, which can appear to be\n/// memory and object leakage.\n///\n/// Slices Maintain Indices\n/// =======================\n///\n/// Unlike `Array` and `ContiguousArray`, the starting index for an\n/// `ArraySlice` instance isn't always zero. Slices maintain the same\n/// indices of the larger array for the same elements, so the starting\n/// index of a slice depends on how it was created, letting you perform\n/// index-based operations on either a full array or a slice.\n///\n/// Sharing indices between collections and their subsequences is an important\n/// part of the design of Swift's collection algorithms. Suppose you are\n/// tasked with finding the first two days with absences in the session. To\n/// find the indices of the two days in question, follow these steps:\n///\n/// 1) Call `firstIndex(where:)` to find the index of the first element in the\n/// `absences` array that is greater than zero.\n/// 2) Create a slice of the `absences` array starting after the index found in\n/// step 1.\n/// 3) Call `firstIndex(where:)` again, this time on the slice created in step\n/// 2. Where in some languages you might pass a starting index into an\n/// `indexOf` method to find the second day, in Swift you perform the same\n/// operation on a slice of the original array.\n/// 4) Print the results using the indices found in steps 1 and 3 on the\n/// original `absences` array.\n///\n/// Here's an implementation of those steps:\n///\n/// if let i = absences.firstIndex(where: { $0 > 0 }) { // 1\n/// let absencesAfterFirst = absences[(i + 1)...] // 2\n/// if let j = absencesAfterFirst.firstIndex(where: { $0 > 0 }) { // 3\n/// print("The first day with absences had \(absences[i]).") // 4\n/// print("The second day with absences had \(absences[j]).")\n/// }\n/// }\n/// // Prints "The first day with absences had 2."\n/// // Prints "The second day with absences had 4."\n///\n/// In particular, note that `j`, the index of the second day with absences,\n/// was found in a slice of the original array and then used to access a value\n/// in the original `absences` array itself.\n///\n/// - Note: To safely reference the starting and ending indices of a slice,\n/// always use the `startIndex` and `endIndex` properties instead of\n/// specific values.\n@frozen\npublic struct ArraySlice<Element>: _DestructorSafeContainer {\n @usableFromInline\n internal typealias _Buffer = _SliceBuffer<Element>\n\n @usableFromInline\n internal var _buffer: _Buffer\n\n /// Initialization from an existing buffer does not have "array.init"\n /// semantics because the caller may retain an alias to buffer.\n @inlinable\n internal init(_buffer: _Buffer) {\n self._buffer = _buffer\n }\n\n /// Initialization from an existing buffer does not have "array.init"\n /// semantics because the caller may retain an alias to buffer.\n @inlinable\n internal init(_buffer buffer: _ContiguousArrayBuffer<Element>) {\n self.init(_buffer: _Buffer(_buffer: buffer, shiftedToStartIndex: 0))\n }\n}\n\n//===--- private helpers---------------------------------------------------===//\nextension ArraySlice {\n /// Returns `true` if the array is native and does not need a deferred\n /// type check. May be hoisted by the optimizer, which means its\n /// results may be stale by the time they are used if there is an\n /// inout violation in user code.\n @inlinable\n @_semantics("array.props.isNativeTypeChecked")\n public // @testable\n func _hoistableIsNativeTypeChecked() -> Bool {\n return _buffer.arrayPropertyIsNativeTypeChecked\n }\n\n @inlinable\n @_semantics("array.get_count")\n internal func _getCount() -> Int {\n return _buffer.count\n }\n\n @inlinable\n @_semantics("array.get_capacity")\n internal func _getCapacity() -> Int {\n return _buffer.capacity\n }\n\n @inlinable\n @_semantics("array.make_mutable")\n internal mutating func _makeMutableAndUnique() {\n if _slowPath(!_buffer.beginCOWMutation()) {\n _buffer = _Buffer(copying: _buffer)\n }\n }\n \n /// Marks the end of a mutation.\n ///\n /// After a call to `_endMutation` the buffer must not be mutated until a call\n /// to `_makeMutableAndUnique`.\n @_alwaysEmitIntoClient\n @_semantics("array.end_mutation")\n internal mutating func _endMutation() {\n _buffer.endCOWMutation()\n }\n\n /// Check that the given `index` is valid for subscripting, i.e.\n /// `0 ≤ index < count`.\n @inlinable\n @inline(__always)\n internal func _checkSubscript_native(_ index: Int) {\n _buffer._checkValidSubscript(index)\n }\n\n /// Check that the given `index` is valid for subscripting, i.e.\n /// `0 ≤ index < count`.\n @inlinable\n @_semantics("array.check_subscript")\n public // @testable\n func _checkSubscript(\n _ index: Int, wasNativeTypeChecked: Bool\n ) -> _DependenceToken {\n _buffer._checkValidSubscript(index)\n return _DependenceToken()\n }\n\n /// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`.\n @inlinable\n @_semantics("array.check_index")\n internal func _checkIndex(_ index: Int) {\n _precondition(index <= endIndex, "ArraySlice index is out of range")\n _precondition(index >= startIndex, "ArraySlice index is out of range (before startIndex)")\n }\n\n @_semantics("array.get_element")\n @inlinable // FIXME(inline-always)\n @inline(__always)\n public // @testable\n func _getElement(\n _ index: Int,\n wasNativeTypeChecked: Bool,\n matchingSubscriptCheck: _DependenceToken\n ) -> Element {\n#if false\n return _buffer.getElement(index, wasNativeTypeChecked: wasNativeTypeChecked)\n#else\n return _buffer.getElement(index)\n#endif\n }\n\n @inlinable\n @_semantics("array.get_element_address")\n internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> {\n return unsafe _buffer.subscriptBaseAddress + index\n }\n}\n\nextension ArraySlice: _ArrayProtocol {\n /// The total number of elements that the array can contain without\n /// allocating new storage.\n ///\n /// Every array reserves a specific amount of memory to hold its contents.\n /// When you add elements to an array and that array begins to exceed its\n /// reserved capacity, the array allocates a larger region of memory and\n /// copies its elements into the new storage. The new storage is a multiple\n /// of the old storage's size. This exponential growth strategy means that\n /// appending an element happens in constant time, averaging the performance\n /// of many append operations. Append operations that trigger reallocation\n /// have a performance cost, but they occur less and less often as the array\n /// grows larger.\n ///\n /// The following example creates an array of integers from an array literal,\n /// then appends the elements of another collection. Before appending, the\n /// array allocates new storage that is large enough store the resulting\n /// elements.\n ///\n /// var numbers = [10, 20, 30, 40, 50]\n /// // numbers.count == 5\n /// // numbers.capacity == 5\n ///\n /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10))\n /// // numbers.count == 10\n /// // numbers.capacity == 10\n @inlinable\n public var capacity: Int {\n return _getCapacity()\n }\n\n #if $Embedded\n public typealias AnyObject = Builtin.NativeObject\n #endif\n\n /// An object that guarantees the lifetime of this array's elements.\n @inlinable\n public // @testable\n var _owner: AnyObject? {\n return _buffer.owner\n }\n\n /// If the elements are stored contiguously, a pointer to the first\n /// element. Otherwise, `nil`.\n @inlinable\n public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? {\n @inline(__always) // FIXME(TODO: JIRA): Hack around test failure\n get { return unsafe _buffer.firstElementAddressIfContiguous }\n }\n\n @inlinable\n internal var _baseAddress: UnsafeMutablePointer<Element> {\n return unsafe _buffer.firstElementAddress\n }\n}\n\nextension ArraySlice: RandomAccessCollection, MutableCollection {\n /// The index type for arrays, `Int`.\n ///\n /// `ArraySlice` instances are not always indexed from zero. Use `startIndex`\n /// and `endIndex` as the bounds for any element access, instead of `0` and\n /// `count`.\n public typealias Index = Int\n\n /// The type that represents the indices that are valid for subscripting an\n /// array, in ascending order.\n public typealias Indices = Range<Int>\n\n /// The type that allows iteration over an array's elements.\n public typealias Iterator = IndexingIterator<ArraySlice>\n\n /// The position of the first element in a nonempty array.\n ///\n /// `ArraySlice` instances are not always indexed from zero. Use `startIndex`\n /// and `endIndex` as the bounds for any element access, instead of `0` and\n /// `count`.\n ///\n /// If the array is empty, `startIndex` is equal to `endIndex`.\n @inlinable\n public var startIndex: Int {\n return _buffer.startIndex\n }\n\n /// The array's "past the end" position---that is, the position one greater\n /// than the last valid subscript argument.\n ///\n /// When you need a range that includes the last element of an array, use the\n /// half-open range operator (`..<`) with `endIndex`. The `..<` operator\n /// creates a range that doesn't include the upper bound, so it's always\n /// safe to use with `endIndex`. For example:\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// if let i = numbers.firstIndex(of: 30) {\n /// print(numbers[i ..< numbers.endIndex])\n /// }\n /// // Prints "[30, 40, 50]"\n ///\n /// If the array is empty, `endIndex` is equal to `startIndex`.\n @inlinable\n public var endIndex: Int {\n return _buffer.endIndex\n }\n\n /// Returns the position immediately after the given index.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be less than\n /// `endIndex`.\n /// - Returns: The index immediately after `i`.\n @inlinable\n public func index(after i: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return i + 1\n }\n\n /// Replaces the given index with its successor.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be less than\n /// `endIndex`.\n @inlinable\n public func formIndex(after i: inout Int) {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n i += 1\n }\n\n /// Returns the position immediately before the given index.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be greater than\n /// `startIndex`.\n /// - Returns: The index immediately before `i`.\n @inlinable\n public func index(before i: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return i - 1\n }\n\n /// Replaces the given index with its predecessor.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be greater than\n /// `startIndex`.\n @inlinable\n public func formIndex(before i: inout Int) {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n i -= 1\n }\n\n /// Returns an index that is the specified distance from the given index.\n ///\n /// The following example obtains an index advanced four positions from an\n /// array's starting index and then prints the element at that position.\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// let i = numbers.index(numbers.startIndex, offsetBy: 4)\n /// print(numbers[i])\n /// // Prints "50"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection.\n ///\n /// - Parameters:\n /// - i: A valid index of the array.\n /// - distance: The distance to offset `i`.\n /// - Returns: An index offset by `distance` from the index `i`. If\n /// `distance` is positive, this is the same value as the result of\n /// `distance` calls to `index(after:)`. If `distance` is negative, this\n /// is the same value as the result of `abs(distance)` calls to\n /// `index(before:)`.\n @inlinable\n public func index(_ i: Int, offsetBy distance: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return i + distance\n }\n\n /// Returns an index that is the specified distance from the given index,\n /// unless that distance is beyond a given limiting index.\n ///\n /// The following example obtains an index advanced four positions from an\n /// array's starting index and then prints the element at that position. The\n /// operation doesn't require going beyond the limiting `numbers.endIndex`\n /// value, so it succeeds.\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// if let i = numbers.index(numbers.startIndex,\n /// offsetBy: 4,\n /// limitedBy: numbers.endIndex) {\n /// print(numbers[i])\n /// }\n /// // Prints "50"\n ///\n /// The next example attempts to retrieve an index ten positions from\n /// `numbers.startIndex`, but fails, because that distance is beyond the\n /// index passed as `limit`.\n ///\n /// let j = numbers.index(numbers.startIndex,\n /// offsetBy: 10,\n /// limitedBy: numbers.endIndex)\n /// print(j)\n /// // Prints "nil"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection, unless the index passed as `limit` prevents offsetting\n /// beyond those bounds.\n ///\n /// - Parameters:\n /// - i: A valid index of the array.\n /// - distance: The distance to offset `i`.\n /// - limit: A valid index of the collection to use as a limit. If\n /// `distance > 0`, `limit` has no effect if it is less than `i`.\n /// Likewise, if `distance < 0`, `limit` has no effect if it is greater\n /// than `i`.\n /// - Returns: An index offset by `distance` from the index `i`, unless that\n /// index would be beyond `limit` in the direction of movement. In that\n /// case, the method returns `nil`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func index(\n _ i: Int, offsetBy distance: Int, limitedBy limit: Int\n ) -> Int? {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n let l = limit - i\n if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l {\n return nil\n }\n return i + distance\n }\n\n /// Returns the distance between two indices.\n ///\n /// - Parameters:\n /// - start: A valid index of the collection.\n /// - end: Another valid index of the collection. If `end` is equal to\n /// `start`, the result is zero.\n /// - Returns: The distance between `start` and `end`.\n @inlinable\n public func distance(from start: Int, to end: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return end - start\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) {\n // NOTE: This method is a no-op for performance reasons.\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) {\n // NOTE: This method is a no-op for performance reasons.\n }\n\n /// Accesses the element at the specified position.\n ///\n /// The following example uses indexed subscripting to update an array's\n /// second element. After assigning the new value (`"Butler"`) at a specific\n /// position, that value is immediately available at that same position.\n ///\n /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// streets[1] = "Butler"\n /// print(streets[1])\n /// // Prints "Butler"\n ///\n /// - Parameter index: The position of the element to access. `index` must be\n /// greater than or equal to `startIndex` and less than `endIndex`.\n ///\n /// - Complexity: Reading an element from an array is O(1). Writing is O(1)\n /// unless the array's storage is shared with another array or uses a\n /// bridged `NSArray` instance as its storage, in which case writing is\n /// O(*n*), where *n* is the length of the array.\n @inlinable\n public subscript(index: Int) -> Element {\n get {\n // This call may be hoisted or eliminated by the optimizer. If\n // there is an inout violation, this value may be stale so needs to be\n // checked again below.\n let wasNativeTypeChecked = _hoistableIsNativeTypeChecked()\n\n // Make sure the index is in range and wasNativeTypeChecked is\n // still valid.\n let token = _checkSubscript(\n index, wasNativeTypeChecked: wasNativeTypeChecked)\n\n return _getElement(\n index, wasNativeTypeChecked: wasNativeTypeChecked,\n matchingSubscriptCheck: token)\n }\n _modify {\n _makeMutableAndUnique() // makes the array native, too\n _checkSubscript_native(index)\n let address = unsafe _buffer.subscriptBaseAddress + index\n defer { _endMutation() }\n yield unsafe &address.pointee\n }\n }\n\n /// Accesses a contiguous subrange of the array's elements.\n ///\n /// The returned `ArraySlice` instance uses the same indices for the same\n /// elements as the original array. In particular, that slice, unlike an\n /// array, may have a nonzero `startIndex` and an `endIndex` that is not\n /// equal to `count`. Always use the slice's `startIndex` and `endIndex`\n /// properties instead of assuming that its indices start or end at a\n /// particular value.\n ///\n /// This example demonstrates getting a slice of an array of strings, finding\n /// the index of one of the strings in the slice, and then using that index\n /// in the original array.\n ///\n /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// let streetsSlice = streets[2 ..< streets.endIndex]\n /// print(streetsSlice)\n /// // Prints "["Channing", "Douglas", "Evarts"]"\n ///\n /// let i = streetsSlice.firstIndex(of: "Evarts") // 4\n /// print(streets[i!])\n /// // Prints "Evarts"\n ///\n /// - Parameter bounds: A range of integers. The bounds of the range must be\n /// valid indices of the array.\n @inlinable\n public subscript(bounds: Range<Int>) -> ArraySlice<Element> {\n get {\n _checkIndex(bounds.lowerBound)\n _checkIndex(bounds.upperBound)\n return ArraySlice(_buffer: _buffer[bounds])\n }\n set(rhs) {\n _checkIndex(bounds.lowerBound)\n _checkIndex(bounds.upperBound)\n // If the replacement buffer has same identity, and the ranges match,\n // then this was a pinned in-place modification, nothing further needed.\n if unsafe self[bounds]._buffer.identity != rhs._buffer.identity\n || bounds != rhs.startIndex..<rhs.endIndex {\n self.replaceSubrange(bounds, with: rhs)\n }\n }\n }\n\n /// The number of elements in the array.\n @inlinable\n public var count: Int {\n return _getCount()\n }\n}\n\nextension ArraySlice: ExpressibleByArrayLiteral {\n /// Creates an array from the given array literal.\n ///\n /// Do not call this initializer directly. It is used by the compiler when\n /// you use an array literal. Instead, create a new array by using an array\n /// literal as its value. To do this, enclose a comma-separated list of\n /// values in square brackets.\n ///\n /// Here, an array of strings is created from an array literal holding only\n /// strings:\n ///\n /// let ingredients: ArraySlice =\n /// ["cocoa beans", "sugar", "cocoa butter", "salt"]\n ///\n /// - Parameter elements: A variadic list of elements of the new array.\n @inlinable\n public init(arrayLiteral elements: Element...) {\n self.init(_buffer: ContiguousArray(elements)._buffer)\n }\n}\n\nextension ArraySlice: RangeReplaceableCollection {\n /// Creates a new, empty array.\n ///\n /// This is equivalent to initializing with an empty array literal.\n /// For example:\n ///\n /// var emptyArray = Array<Int>()\n /// print(emptyArray.isEmpty)\n /// // Prints "true"\n ///\n /// emptyArray = []\n /// print(emptyArray.isEmpty)\n /// // Prints "true"\n @inlinable\n @_semantics("array.init.empty")\n public init() {\n _buffer = _Buffer()\n }\n\n /// Creates an array containing the elements of a sequence.\n ///\n /// You can use this initializer to create an array from any other type that\n /// conforms to the `Sequence` protocol. For example, you might want to\n /// create an array with the integers from 1 through 7. Use this initializer\n /// around a range instead of typing all those numbers in an array literal.\n ///\n /// let numbers = Array(1...7)\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 6, 7]"\n ///\n /// You can also use this initializer to convert a complex sequence or\n /// collection type back to an array. For example, the `keys` property of\n /// a dictionary isn't an array with its own storage, it's a collection\n /// that maps its elements from the dictionary only when they're\n /// accessed, saving the time and space needed to allocate an array. If\n /// you need to pass those keys to a method that takes an array, however,\n /// use this initializer to convert that list from its type of\n /// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple\n /// `[String]`.\n ///\n /// func cacheImagesWithNames(names: [String]) {\n /// // custom image loading and caching\n /// }\n ///\n /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,\n /// "Gold": 50, "Cerise": 320]\n /// let colorNames = Array(namedHues.keys)\n /// cacheImagesWithNames(colorNames)\n ///\n /// print(colorNames)\n /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"\n ///\n /// - Parameter s: The sequence of elements to turn into an array.\n @inlinable\n public init<S: Sequence>(_ s: S)\n where S.Element == Element {\n\n self.init(_buffer: s._copyToContiguousArray()._buffer)\n }\n\n /// Creates a new array containing the specified number of a single, repeated\n /// value.\n ///\n /// Here's an example of creating an array initialized with five strings\n /// containing the letter *Z*.\n ///\n /// let fiveZs = Array(repeating: "Z", count: 5)\n /// print(fiveZs)\n /// // Prints "["Z", "Z", "Z", "Z", "Z"]"\n ///\n /// - Parameters:\n /// - repeatedValue: The element to repeat.\n /// - count: The number of times to repeat the value passed in the\n /// `repeating` parameter. `count` must be zero or greater.\n @inlinable\n @_semantics("array.init")\n public init(repeating repeatedValue: Element, count: Int) {\n _precondition(count >= 0, "Can't construct ArraySlice with count < 0")\n if count > 0 {\n _buffer = ArraySlice._allocateBufferUninitialized(minimumCapacity: count)\n _buffer.count = count\n var p = unsafe _buffer.firstElementAddress\n for _ in 0..<count {\n unsafe p.initialize(to: repeatedValue)\n unsafe p += 1\n }\n } else {\n _buffer = _Buffer()\n }\n _endMutation()\n }\n\n @inline(never)\n @usableFromInline\n internal static func _allocateBufferUninitialized(\n minimumCapacity: Int\n ) -> _Buffer {\n let newBuffer = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: 0, minimumCapacity: minimumCapacity)\n return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0)\n }\n\n /// Construct a ArraySlice of `count` uninitialized elements.\n @inlinable\n @_semantics("array.init")\n internal init(_uninitializedCount count: Int) {\n _precondition(count >= 0, "Can't construct ArraySlice with count < 0")\n // Note: Sinking this constructor into an else branch below causes an extra\n // Retain/Release.\n _buffer = _Buffer()\n if count > 0 {\n // Creating a buffer instead of calling reserveCapacity saves doing an\n // unnecessary uniqueness check. We disable inlining here to curb code\n // growth.\n _buffer = ArraySlice._allocateBufferUninitialized(minimumCapacity: count)\n _buffer.count = count\n }\n // Can't store count here because the buffer might be pointing to the\n // shared empty array.\n _endMutation()\n }\n\n /// Entry point for `Array` literal construction; builds and returns\n /// a ArraySlice of `count` uninitialized elements.\n @inlinable\n @_semantics("array.uninitialized")\n internal static func _allocateUninitialized(\n _ count: Int\n ) -> (ArraySlice, UnsafeMutablePointer<Element>) {\n let result = ArraySlice(_uninitializedCount: count)\n return (result, unsafe result._buffer.firstElementAddress)\n }\n\n //===--- basic mutations ------------------------------------------------===//\n\n /// Reserves enough space to store the specified number of elements.\n ///\n /// If you are adding a known number of elements to an array, use this method\n /// to avoid multiple reallocations. This method ensures that the array has\n /// unique, mutable, contiguous storage, with space allocated for at least\n /// the requested number of elements.\n ///\n /// Calling the `reserveCapacity(_:)` method on an array with bridged storage\n /// triggers a copy to contiguous storage even if the existing storage\n /// has room to store `minimumCapacity` elements.\n ///\n /// For performance reasons, the size of the newly allocated storage might be\n /// greater than the requested capacity. Use the array's `capacity` property\n /// to determine the size of the new storage.\n ///\n /// Preserving an Array's Geometric Growth Strategy\n /// ===============================================\n ///\n /// If you implement a custom data structure backed by an array that grows\n /// dynamically, naively calling the `reserveCapacity(_:)` method can lead\n /// to worse than expected performance. Arrays need to follow a geometric\n /// allocation pattern for appending elements to achieve amortized\n /// constant-time performance. The `Array` type's `append(_:)` and\n /// `append(contentsOf:)` methods take care of this detail for you, but\n /// `reserveCapacity(_:)` allocates only as much space as you tell it to\n /// (padded to a round value), and no more. This avoids over-allocation, but\n /// can result in insertion not having amortized constant-time performance.\n ///\n /// The following code declares `values`, an array of integers, and the\n /// `addTenQuadratic()` function, which adds ten more values to the `values`\n /// array on each call.\n ///\n /// var values: [Int] = [0, 1, 2, 3]\n ///\n /// // Don't use 'reserveCapacity(_:)' like this\n /// func addTenQuadratic() {\n /// let newCount = values.count + 10\n /// values.reserveCapacity(newCount)\n /// for n in values.count..<newCount {\n /// values.append(n)\n /// }\n /// }\n ///\n /// The call to `reserveCapacity(_:)` increases the `values` array's capacity\n /// by exactly 10 elements on each pass through `addTenQuadratic()`, which\n /// is linear growth. Instead of having constant time when averaged over\n /// many calls, the function may decay to performance that is linear in\n /// `values.count`. This is almost certainly not what you want.\n ///\n /// In cases like this, the simplest fix is often to simply remove the call\n /// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array\n /// for you.\n ///\n /// func addTen() {\n /// let newCount = values.count + 10\n /// for n in values.count..<newCount {\n /// values.append(n)\n /// }\n /// }\n ///\n /// If you need more control over the capacity of your array, implement your\n /// own geometric growth strategy, passing the size you compute to\n /// `reserveCapacity(_:)`.\n ///\n /// - Parameter minimumCapacity: The requested number of elements to store.\n ///\n /// - Complexity: O(*n*), where *n* is the number of elements in the array.\n @inlinable\n @_semantics("array.mutate_unknown")\n public mutating func reserveCapacity(_ minimumCapacity: Int) {\n if !_buffer.beginCOWMutation() || _buffer.capacity < minimumCapacity {\n let newBuffer = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: count, minimumCapacity: minimumCapacity)\n\n unsafe _buffer._copyContents(\n subRange: _buffer.indices,\n initializing: newBuffer.firstElementAddress)\n _buffer = _Buffer(\n _buffer: newBuffer, shiftedToStartIndex: _buffer.startIndex)\n }\n _internalInvariant(capacity >= minimumCapacity)\n _endMutation()\n }\n\n /// Copy the contents of the current buffer to a new unique mutable buffer.\n /// The count of the new buffer is set to `oldCount`, the capacity of the\n /// new buffer is big enough to hold 'oldCount' + 1 elements.\n @inline(never)\n @inlinable // @specializable\n internal mutating func _copyToNewBuffer(oldCount: Int) {\n let newCount = oldCount &+ 1\n var newBuffer = _buffer._forceCreateUniqueMutableBuffer(\n countForNewBuffer: oldCount, minNewCapacity: newCount)\n unsafe _buffer._arrayOutOfPlaceUpdate(\n &newBuffer, oldCount, 0)\n }\n\n @inlinable\n @_semantics("array.make_mutable")\n internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() {\n if _slowPath(!_buffer.beginCOWMutation()) {\n _copyToNewBuffer(oldCount: _buffer.count)\n }\n }\n\n @inlinable\n @_semantics("array.mutate_unknown")\n internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) {\n // Due to make_mutable hoisting the situation can arise where we hoist\n // _makeMutableAndUnique out of loop and use it to replace\n // _makeUniqueAndReserveCapacityIfNotUnique that precedes this call. If the\n // array was empty _makeMutableAndUnique does not replace the empty array\n // buffer by a unique buffer (it just replaces it by the empty array\n // singleton).\n // This specific case is okay because we will make the buffer unique in this\n // function because we request a capacity > 0 and therefore _copyToNewBuffer\n // will be called creating a new buffer.\n let capacity = _buffer.capacity\n _internalInvariant(capacity == 0 || _buffer.isMutableAndUniquelyReferenced())\n\n if _slowPath(oldCount &+ 1 > capacity) {\n _copyToNewBuffer(oldCount: oldCount)\n }\n }\n\n @inlinable\n @_semantics("array.mutate_unknown")\n internal mutating func _appendElementAssumeUniqueAndCapacity(\n _ oldCount: Int,\n newElement: __owned Element\n ) {\n _internalInvariant(_buffer.isMutableAndUniquelyReferenced())\n _internalInvariant(_buffer.capacity >= _buffer.count &+ 1)\n\n _buffer.count = oldCount &+ 1\n unsafe (_buffer.firstElementAddress + oldCount).initialize(to: newElement)\n }\n\n /// Adds a new element at the end of the array.\n ///\n /// Use this method to append a single element to the end of a mutable array.\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.append(100)\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 100]"\n ///\n /// Because arrays increase their allocated capacity using an exponential\n /// strategy, appending a single element to an array is an O(1) operation\n /// when averaged over many calls to the `append(_:)` method. When an array\n /// has additional capacity and is not sharing its storage with another\n /// instance, appending an element is O(1). When an array needs to\n /// reallocate storage before appending or its storage is shared with\n /// another copy, appending is O(*n*), where *n* is the length of the array.\n ///\n /// - Parameter newElement: The element to append to the array.\n ///\n /// - Complexity: O(1) on average, over many calls to `append(_:)` on the\n /// same array.\n @inlinable\n @_semantics("array.append_element")\n public mutating func append(_ newElement: __owned Element) {\n _makeUniqueAndReserveCapacityIfNotUnique()\n let oldCount = _getCount()\n _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount)\n _appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement)\n _endMutation()\n }\n\n /// Adds the elements of a sequence to the end of the array.\n ///\n /// Use this method to append the elements of a sequence to the end of this\n /// array. This example appends the elements of a `Range<Int>` instance\n /// to an array of integers.\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.append(contentsOf: 10...15)\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"\n ///\n /// - Parameter newElements: The elements to append to the array.\n ///\n /// - Complexity: O(*m*) on average, where *m* is the length of\n /// `newElements`, over many calls to `append(contentsOf:)` on the same\n /// array.\n @inlinable\n @_semantics("array.append_contentsOf")\n public mutating func append<S: Sequence>(contentsOf newElements: __owned S)\n where S.Element == Element {\n\n let newElementsCount = newElements.underestimatedCount\n reserveCapacityForAppend(newElementsCount: newElementsCount)\n _ = _buffer.beginCOWMutation()\n\n let oldCount = self.count\n let startNewElements = unsafe _buffer.firstElementAddress + oldCount\n let buf = unsafe UnsafeMutableBufferPointer(\n start: startNewElements, \n count: self.capacity - oldCount)\n\n let (remainder,writtenUpTo) = unsafe buf.initialize(from: newElements)\n \n // trap on underflow from the sequence's underestimate:\n let writtenCount = unsafe buf.distance(from: buf.startIndex, to: writtenUpTo)\n _precondition(newElementsCount <= writtenCount,\n "newElements.underestimatedCount was an overestimate")\n // can't check for overflow as sequences can underestimate\n\n // This check prevents a data race writing to _swiftEmptyArrayStorage\n if writtenCount > 0 {\n _buffer.count += writtenCount\n }\n\n if writtenUpTo == buf.endIndex {\n // there may be elements that didn't fit in the existing buffer,\n // append them in slow sequence-only mode\n _buffer._arrayAppendSequence(IteratorSequence(remainder))\n }\n _endMutation()\n }\n\n @inlinable\n @_semantics("array.reserve_capacity_for_append")\n internal mutating func reserveCapacityForAppend(newElementsCount: Int) {\n let oldCount = self.count\n let oldCapacity = self.capacity\n let newCount = oldCount + newElementsCount\n\n // Ensure uniqueness, mutability, and sufficient storage. Note that\n // for consistency, we need unique self even if newElements is empty.\n self.reserveCapacity(\n newCount > oldCapacity ?\n Swift.max(newCount, _growArrayCapacity(oldCapacity))\n : newCount)\n }\n\n @inlinable\n public mutating func _customRemoveLast() -> Element? {\n _precondition(count > 0, "Can't removeLast from an empty ArraySlice")\n // FIXME(performance): if `self` is uniquely referenced, we should remove\n // the element as shown below (this will deallocate the element and\n // decrease memory use). If `self` is not uniquely referenced, the code\n // below will make a copy of the storage, which is wasteful. Instead, we\n // should just shrink the view without allocating new storage.\n let i = endIndex\n // We don't check for overflow in `i - 1` because `i` is known to be\n // positive.\n let result = self[i &- 1]\n self.replaceSubrange((i &- 1)..<i, with: EmptyCollection())\n return result\n }\n \n /// Removes and returns the element at the specified position.\n ///\n /// All the elements following the specified position are moved up to\n /// close the gap.\n ///\n /// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]\n /// let removed = measurements.remove(at: 2)\n /// print(measurements)\n /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]"\n ///\n /// - Parameter index: The position of the element to remove. `index` must\n /// be a valid index of the array.\n /// - Returns: The element at the specified index.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the array.\n @inlinable\n @discardableResult\n public mutating func remove(at index: Int) -> Element {\n let result = self[index]\n self.replaceSubrange(index..<(index + 1), with: EmptyCollection())\n return result\n }\n\n\n /// Inserts a new element at the specified position.\n ///\n /// The new element is inserted before the element currently at the specified\n /// index. If you pass the array's `endIndex` property as the `index`\n /// parameter, the new element is appended to the array.\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.insert(100, at: 3)\n /// numbers.insert(200, at: numbers.endIndex)\n ///\n /// print(numbers)\n /// // Prints "[1, 2, 3, 100, 4, 5, 200]"\n ///\n /// - Parameter newElement: The new element to insert into the array.\n /// - Parameter i: The position at which to insert the new element.\n /// `index` must be a valid index of the array or equal to its `endIndex`\n /// property.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the array. If\n /// `i == endIndex`, this method is equivalent to `append(_:)`.\n @inlinable\n public mutating func insert(_ newElement: __owned Element, at i: Int) {\n _checkIndex(i)\n self.replaceSubrange(i..<i, with: CollectionOfOne(newElement))\n }\n\n /// Removes all elements from the array.\n ///\n /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of\n /// the array after removing its elements. The default value is\n /// `false`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the array.\n @inlinable\n public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {\n if !keepCapacity {\n _buffer = _Buffer()\n }\n else if _buffer.isMutableAndUniquelyReferenced() {\n self.replaceSubrange(indices, with: EmptyCollection())\n }\n else {\n let buffer = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: 0,\n minimumCapacity: capacity\n )\n _buffer = _Buffer(_buffer: buffer, shiftedToStartIndex: startIndex)\n }\n }\n\n //===--- algorithms -----------------------------------------------------===//\n\n @inlinable\n @available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable")\n public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n return unsafe try withUnsafeMutableBufferPointer {\n (bufferPointer) -> R in\n return try unsafe body(&bufferPointer)\n }\n }\n\n @inlinable\n public mutating func withContiguousMutableStorageIfAvailable<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n return unsafe try withUnsafeMutableBufferPointer {\n (bufferPointer) -> R in\n return try unsafe body(&bufferPointer)\n }\n }\n\n @inlinable\n public func withContiguousStorageIfAvailable<R>(\n _ body: (UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n return unsafe try withUnsafeBufferPointer {\n (bufferPointer) -> R in\n return try unsafe body(bufferPointer)\n }\n }\n\n @inlinable\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n if let n = _buffer.requestNativeBuffer() {\n return ContiguousArray(_buffer: n)\n }\n return _copyCollectionToContiguousArray(self)\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension ArraySlice: CustomReflectable {\n /// A mirror that reflects the array.\n public var customMirror: Mirror {\n return Mirror(\n self,\n unlabeledChildren: self,\n displayStyle: .collection)\n }\n}\n#endif\n\n@_unavailableInEmbedded\nextension ArraySlice: CustomStringConvertible, CustomDebugStringConvertible {\n /// A textual representation of the array and its elements.\n public var description: String {\n return _makeCollectionDescription()\n }\n\n /// A textual representation of the array and its elements, suitable for\n /// debugging.\n public var debugDescription: String {\n return _makeCollectionDescription(withTypeName: "ArraySlice")\n }\n}\n\nextension ArraySlice {\n @usableFromInline @_transparent\n internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) {\n let p = unsafe _baseAddressIfContiguous\n if unsafe _fastPath(p != nil || isEmpty) {\n return (_owner, UnsafeRawPointer(p))\n }\n let n = ContiguousArray(self._buffer)._buffer\n return unsafe (n.owner, UnsafeRawPointer(n.firstElementAddress))\n }\n}\n\nextension ArraySlice {\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n @usableFromInline\n @_disfavoredOverload\n func withUnsafeBufferPointer<R>(\n _ body: (UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R {\n return try unsafe _buffer.withUnsafeBufferPointer(body)\n }\n\n /// Calls a closure with a pointer to the array's contiguous storage.\n ///\n /// Often, the optimizer can eliminate bounds checks within an array\n /// algorithm, but when that fails, invoking the same algorithm on the\n /// buffer pointer passed into your closure lets you trade safety for speed.\n ///\n /// The following example shows how you can iterate over the contents of the\n /// buffer pointer:\n ///\n /// let numbers = [1, 2, 3, 4, 5]\n /// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in\n /// var result = 0\n /// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) {\n /// result += buffer[i]\n /// }\n /// return result\n /// }\n /// // 'sum' == 9\n ///\n /// The pointer passed as an argument to `body` is valid only during the\n /// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the\n /// pointer for later use.\n ///\n /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that\n /// points to the contiguous storage for the array. If\n /// `body` has a return value, that value is also used as the return value\n /// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is\n /// valid only for the duration of the method's execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @_alwaysEmitIntoClient\n public func withUnsafeBufferPointer<R, E>(\n _ body: (UnsafeBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n return try unsafe _buffer.withUnsafeBufferPointer(body)\n }\n\n @available(SwiftStdlib 6.2, *)\n public var span: Span<Element> {\n @lifetime(borrow self)\n @_alwaysEmitIntoClient\n borrowing get {\n let (pointer, count) = unsafe (_buffer.firstElementAddress, _buffer.count)\n let span = unsafe Span(_unsafeStart: pointer, count: count)\n return unsafe _overrideLifetime(span, borrowing: self)\n }\n }\n\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n @_semantics("array.withUnsafeMutableBufferPointer")\n @usableFromInline\n @inline(__always)\n @_silgen_name("$ss10ArraySliceV30withUnsafeMutableBufferPointeryqd__qd__SryxGzKXEKlF")\n mutating func __abi_withUnsafeMutableBufferPointer<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R {\n return try unsafe withUnsafeMutableBufferPointer(body)\n }\n\n /// Calls the given closure with a pointer to the array's mutable contiguous\n /// storage.\n ///\n /// Often, the optimizer can eliminate bounds checks within an array\n /// algorithm, but when that fails, invoking the same algorithm on the\n /// buffer pointer passed into your closure lets you trade safety for speed.\n ///\n /// The following example shows how modifying the contents of the\n /// `UnsafeMutableBufferPointer` argument to `body` alters the contents of\n /// the array:\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.withUnsafeMutableBufferPointer { buffer in\n /// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) {\n /// buffer.swapAt(i, i + 1)\n /// }\n /// }\n /// print(numbers)\n /// // Prints "[2, 1, 4, 3, 5]"\n ///\n /// The pointer passed as an argument to `body` is valid only during the\n /// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or\n /// return the pointer for later use.\n ///\n /// - Warning: Do not rely on anything about the array that is the target of\n /// this method during execution of the `body` closure; it might not\n /// appear to have its correct value. Instead, use only the\n /// `UnsafeMutableBufferPointer` argument to `body`.\n ///\n /// - Parameter body: A closure with an `UnsafeMutableBufferPointer`\n /// parameter that points to the contiguous storage for the array.\n /// If `body` has a return value, that value is also\n /// used as the return value for the `withUnsafeMutableBufferPointer(_:)`\n /// method. The pointer argument is valid only for the duration of the\n /// method's execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @_semantics("array.withUnsafeMutableBufferPointer")\n @_alwaysEmitIntoClient\n @inline(__always) // Performance: This method should get inlined into the\n // caller such that we can combine the partial apply with the apply in this\n // function saving on allocating a closure context. This becomes unnecessary\n // once we allocate noescape closures on the stack.\n public mutating func withUnsafeMutableBufferPointer<R, E>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n let count = self.count\n // Ensure unique storage\n _makeMutableAndUnique()\n\n // Create an UnsafeBufferPointer that we can pass to body\n let pointer = unsafe _buffer.firstElementAddress\n var inoutBufferPointer = unsafe UnsafeMutableBufferPointer(\n start: pointer, count: count)\n\n defer {\n unsafe _precondition(\n inoutBufferPointer.baseAddress == pointer &&\n inoutBufferPointer.count == count,\n "ArraySlice withUnsafeMutableBufferPointer: replacing the buffer is not allowed")\n _endMutation()\n _fixLifetime(self)\n }\n\n // Invoke the body.\n return try unsafe body(&inoutBufferPointer)\n }\n\n @available(SwiftStdlib 6.2, *)\n public var mutableSpan: MutableSpan<Element> {\n @lifetime(&self)\n @_alwaysEmitIntoClient\n mutating get {\n _makeMutableAndUnique()\n // NOTE: We don't have the ability to schedule a call to\n // ContiguousArrayBuffer.endCOWMutation().\n // rdar://146785284 (lifetime analysis for end of mutation)\n let (pointer, count) = unsafe (_buffer.firstElementAddress, _buffer.count)\n let span = unsafe MutableSpan(_unsafeStart: pointer, count: count)\n return unsafe _overrideLifetime(span, mutating: &self)\n }\n }\n\n @inlinable\n public __consuming func _copyContents(\n initializing buffer: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {\n\n guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) }\n\n // It is not OK for there to be no pointer/not enough space, as this is\n // a precondition and Array never lies about its count.\n guard var p = buffer.baseAddress\n else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") }\n _precondition(self.count <= buffer.count, \n "Insufficient space allocated to copy array contents")\n\n if let s = unsafe _baseAddressIfContiguous {\n unsafe p.initialize(from: s, count: self.count)\n // Need a _fixLifetime bracketing the _baseAddressIfContiguous getter\n // and all uses of the pointer it returns:\n _fixLifetime(self._owner)\n } else {\n for x in self {\n unsafe p.initialize(to: x)\n unsafe p += 1\n }\n }\n\n var it = IndexingIterator(_elements: self)\n it._position = endIndex\n return (it,unsafe buffer.index(buffer.startIndex, offsetBy: self.count))\n }\n}\n\nextension ArraySlice {\n /// Replaces a range of elements with the elements in the specified\n /// collection.\n ///\n /// This method has the effect of removing the specified range of elements\n /// from the array and inserting the new elements at the same location. The\n /// number of new elements need not match the number of elements being\n /// removed.\n ///\n /// In this example, three elements in the middle of an array of integers are\n /// replaced by the five elements of a `Repeated<Int>` instance.\n ///\n /// var nums = [10, 20, 30, 40, 50]\n /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))\n /// print(nums)\n /// // Prints "[10, 1, 1, 1, 1, 1, 50]"\n ///\n /// If you pass a zero-length range as the `subrange` parameter, this method\n /// inserts the elements of `newElements` at `subrange.startIndex`. Calling\n /// the `insert(contentsOf:at:)` method instead is preferred.\n ///\n /// Likewise, if you pass a zero-length collection as the `newElements`\n /// parameter, this method removes the elements in the given subrange\n /// without replacement. Calling the `removeSubrange(_:)` method instead is\n /// preferred.\n ///\n /// - Parameters:\n /// - subrange: The subrange of the array to replace. The start and end of\n /// a subrange must be valid indices of the array.\n /// - newElements: The new elements to add to the array.\n ///\n /// - Complexity: O(*n* + *m*), where *n* is length of the array and\n /// *m* is the length of `newElements`. If the call to this method simply\n /// appends the contents of `newElements` to the array, this method is\n /// equivalent to `append(contentsOf:)`.\n @inlinable\n @_semantics("array.mutate_unknown")\n public mutating func replaceSubrange<C>(\n _ subrange: Range<Int>,\n with newElements: __owned C\n ) where C: Collection, C.Element == Element {\n _precondition(subrange.lowerBound >= _buffer.startIndex,\n "ArraySlice replace: subrange start is before the startIndex")\n\n _precondition(subrange.upperBound <= _buffer.endIndex,\n "ArraySlice replace: subrange extends past the end")\n\n let oldCount = _buffer.count\n let eraseCount = subrange.count\n let insertCount = newElements.count\n let growth = insertCount - eraseCount\n\n if _buffer.beginCOWMutation() && _buffer.capacity >= oldCount + growth {\n _buffer.replaceSubrange(\n subrange, with: insertCount, elementsOf: newElements)\n } else {\n _buffer._arrayOutOfPlaceReplace(subrange, with: newElements, count: insertCount)\n }\n _endMutation()\n }\n}\n\nextension ArraySlice: Equatable where Element: Equatable {\n /// Returns a Boolean value indicating whether two arrays contain the same\n /// elements in the same order.\n ///\n /// You can use the equal-to operator (`==`) to compare any two arrays\n /// that store the same, `Equatable`-conforming element type.\n ///\n /// - Parameters:\n /// - lhs: An array to compare.\n /// - rhs: Another array to compare.\n @inlinable\n public static func ==(lhs: ArraySlice<Element>, rhs: ArraySlice<Element>) -> Bool {\n let lhsCount = lhs.count\n if lhsCount != rhs.count {\n return false\n }\n\n // Test referential equality.\n if unsafe lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity {\n return true\n }\n\n\n var streamLHS = lhs.makeIterator()\n var streamRHS = rhs.makeIterator()\n\n var nextLHS = streamLHS.next()\n while nextLHS != nil {\n let nextRHS = streamRHS.next()\n if nextLHS != nextRHS {\n return false\n }\n nextLHS = streamLHS.next()\n }\n\n\n return true\n }\n}\n\nextension ArraySlice: Hashable where Element: Hashable {\n /// Hashes the essential components of this value by feeding them into the\n /// given hasher.\n ///\n /// - Parameter hasher: The hasher to use when combining the components\n /// of this instance.\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine(count) // discriminator\n for element in self {\n hasher.combine(element)\n }\n }\n}\n\nextension ArraySlice {\n /// Calls the given closure with a pointer to the underlying bytes of the\n /// array's mutable contiguous storage.\n ///\n /// The array's `Element` type must be a *trivial type*, which can be copied\n /// with just a bit-for-bit copy without any indirection or\n /// reference-counting operations. Generally, native Swift types that do not\n /// contain strong or weak references are trivial, as are imported C structs\n /// and enums.\n ///\n /// The following example copies bytes from the `byteValues` array into\n /// `numbers`, an array of `Int32`:\n ///\n /// var numbers: [Int32] = [0, 0]\n /// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00]\n ///\n /// numbers.withUnsafeMutableBytes { destBytes in\n /// byteValues.withUnsafeBytes { srcBytes in\n /// destBytes.copyBytes(from: srcBytes)\n /// }\n /// }\n /// // numbers == [1, 2]\n ///\n /// - Note: This example shows the behavior on a little-endian platform.\n ///\n /// The pointer passed as an argument to `body` is valid only for the\n /// lifetime of the closure. Do not escape it from the closure for later\n /// use.\n ///\n /// - Warning: Do not rely on anything about the array that is the target of\n /// this method during execution of the `body` closure; it might not\n /// appear to have its correct value. Instead, use only the\n /// `UnsafeMutableRawBufferPointer` argument to `body`.\n ///\n /// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer`\n /// parameter that points to the contiguous storage for the array.\n /// If no such storage exists, it is created. If `body` has a return value, that value is also\n /// used as the return value for the `withUnsafeMutableBytes(_:)` method.\n /// The argument is valid only for the duration of the closure's\n /// execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @inlinable\n public mutating func withUnsafeMutableBytes<R>(\n _ body: (UnsafeMutableRawBufferPointer) throws -> R\n ) rethrows -> R {\n return try unsafe self.withUnsafeMutableBufferPointer {\n return try unsafe body(UnsafeMutableRawBufferPointer($0))\n }\n }\n\n /// Calls the given closure with a pointer to the underlying bytes of the\n /// array's contiguous storage.\n ///\n /// The array's `Element` type must be a *trivial type*, which can be copied\n /// with just a bit-for-bit copy without any indirection or\n /// reference-counting operations. Generally, native Swift types that do not\n /// contain strong or weak references are trivial, as are imported C structs\n /// and enums.\n ///\n /// The following example copies the bytes of the `numbers` array into a\n /// buffer of `UInt8`:\n ///\n /// var numbers: [Int32] = [1, 2, 3]\n /// var byteBuffer: [UInt8] = []\n /// numbers.withUnsafeBytes {\n /// byteBuffer.append(contentsOf: $0)\n /// }\n /// // byteBuffer == [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]\n ///\n /// - Note: This example shows the behavior on a little-endian platform.\n ///\n /// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter\n /// that points to the contiguous storage for the array.\n /// If no such storage exists, it is created. If `body` has a return value, that value is also\n /// used as the return value for the `withUnsafeBytes(_:)` method. The\n /// argument is valid only for the duration of the closure's execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @inlinable\n public func withUnsafeBytes<R>(\n _ body: (UnsafeRawBufferPointer) throws -> R\n ) rethrows -> R {\n return try unsafe self.withUnsafeBufferPointer {\n try unsafe body(UnsafeRawBufferPointer($0))\n }\n }\n}\n\nextension ArraySlice {\n @inlinable\n public // @testable\n init(_startIndex: Int) {\n self.init(\n _buffer: _Buffer(\n _buffer: ContiguousArray()._buffer,\n shiftedToStartIndex: _startIndex))\n }\n}\n\nextension ArraySlice: @unchecked Sendable\n where Element: Sendable { }\n\n#if INTERNAL_CHECKS_ENABLED\nextension ArraySlice {\n // This allows us to test the `_copyContents` implementation in\n // `_SliceBuffer`. (It's like `_copyToContiguousArray` but it always makes a\n // copy.)\n @_alwaysEmitIntoClient\n public func _copyToNewArray() -> [Element] {\n unsafe Array(unsafeUninitializedCapacity: self.count) { buffer, count in\n var (it, c) = unsafe self._buffer._copyContents(initializing: buffer)\n _precondition(it.next() == nil)\n count = c\n }\n }\n}\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ArraySlice.swift | cpp_apple_swift_stdlib_public_core_ArraySlice.swift | Swift | 61,052 | 0.75 | 0.087231 | 0.568614 | node-utils | 477 | 2023-07-14T00:10:14.480204 | BSD-3-Clause | false | a186a959583f8e14a1e5196b498804e4 |
//===--- ArrayType.swift - Protocol for Array-like types ------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@usableFromInline\ninternal protocol _ArrayProtocol\n : RangeReplaceableCollection, ExpressibleByArrayLiteral\nwhere Indices == Range<Int> {\n /// The number of elements the Array can store without reallocation.\n var capacity: Int { get }\n\n #if $Embedded\n typealias AnyObject = Builtin.NativeObject\n #endif\n\n /// An object that guarantees the lifetime of this array's elements.\n var _owner: AnyObject? { get }\n\n /// If the elements are stored contiguously, a pointer to the first\n /// element. Otherwise, `nil`.\n var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { get }\n\n //===--- basic mutations ------------------------------------------------===//\n\n /// Reserve enough space to store minimumCapacity elements.\n ///\n /// - Postcondition: `capacity >= minimumCapacity` and the array has\n /// mutable contiguous storage.\n ///\n /// - Complexity: O(`self.count`).\n override mutating func reserveCapacity(_ minimumCapacity: Int)\n\n /// Insert `newElement` at index `i`.\n ///\n /// Invalidates all indices with respect to `self`.\n ///\n /// - Complexity: O(`self.count`).\n ///\n /// - Precondition: `startIndex <= i`, `i <= endIndex`.\n override mutating func insert(_ newElement: __owned Element, at i: Int)\n\n /// Remove and return the element at the given index.\n ///\n /// - returns: The removed element.\n ///\n /// - Complexity: Worst case O(*n*).\n ///\n /// - Precondition: `count > index`.\n @discardableResult\n override mutating func remove(at index: Int) -> Element\n\n //===--- implementation detail -----------------------------------------===//\n\n associatedtype _Buffer: _ArrayBufferProtocol where _Buffer.Element == Element\n init(_ buffer: _Buffer)\n\n // For testing.\n var _buffer: _Buffer { get }\n}\n\nextension _ArrayProtocol {\n // Since RangeReplaceableCollection now has a version of filter that is less\n // efficient, we should make the default implementation coming from Sequence\n // preferred.\n @inlinable\n public __consuming func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _filter(isIncluded)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ArrayType.swift | cpp_apple_swift_stdlib_public_core_ArrayType.swift | Swift | 2,629 | 0.8 | 0.063291 | 0.641791 | vue-tools | 772 | 2024-05-02T01:52:44.017107 | GPL-3.0 | false | e0ef81787956fa4c878a9e61b122dc69 |
//===--- ASCII.swift ------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nextension Unicode {\n @frozen\n public enum ASCII {}\n}\n\nextension Unicode.ASCII: Unicode.Encoding {\n public typealias CodeUnit = UInt8\n public typealias EncodedScalar = CollectionOfOne<CodeUnit>\n\n @inlinable\n public static var encodedReplacementCharacter: EncodedScalar {\n return EncodedScalar(0x1a) // U+001A SUBSTITUTE; best we can do for ASCII\n }\n\n /// Returns whether the given code unit represents an ASCII scalar\n @_alwaysEmitIntoClient\n public static func isASCII(_ x: CodeUnit) -> Bool { return UTF8.isASCII(x) }\n\n @inline(__always)\n @inlinable\n public static func _isScalar(_ x: CodeUnit) -> Bool {\n return true\n }\n\n @inline(__always)\n @inlinable\n public static func decode(_ source: EncodedScalar) -> Unicode.Scalar {\n return Unicode.Scalar(_unchecked: UInt32(\n source.first._unsafelyUnwrappedUnchecked))\n }\n \n @inline(__always)\n @inlinable\n public static func encode(\n _ source: Unicode.Scalar\n ) -> EncodedScalar? {\n guard source.value < (1&<<7) else { return nil }\n return EncodedScalar(UInt8(truncatingIfNeeded: source.value))\n }\n\n @inline(__always)\n @inlinable\n public static func transcode<FromEncoding: Unicode.Encoding>(\n _ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type\n ) -> EncodedScalar? {\n if _fastPath(FromEncoding.self == UTF16.self) {\n let c = _identityCast(content, to: UTF16.EncodedScalar.self)\n guard (c._storage & 0xFF80 == 0) else { return nil }\n return EncodedScalar(CodeUnit(c._storage & 0x7f))\n }\n else if _fastPath(FromEncoding.self == UTF8.self) {\n let c = _identityCast(content, to: UTF8.EncodedScalar.self)\n let first = unsafe c.first.unsafelyUnwrapped\n guard (first < 0x80) else { return nil }\n return EncodedScalar(CodeUnit(first))\n }\n return encode(FromEncoding.decode(content))\n }\n\n @frozen\n public struct Parser {\n @inlinable\n public init() { }\n }\n \n public typealias ForwardParser = Parser\n public typealias ReverseParser = Parser\n}\n\nextension Unicode.ASCII.Parser: Unicode.Parser {\n public typealias Encoding = Unicode.ASCII\n\n /// Parses a single Unicode scalar value from `input`.\n @inlinable\n public mutating func parseScalar<I: IteratorProtocol>(\n from input: inout I\n ) -> Unicode.ParseResult<Encoding.EncodedScalar>\n where I.Element == Encoding.CodeUnit {\n let n = input.next()\n if _fastPath(n != nil), let x = n {\n guard _fastPath(Int8(truncatingIfNeeded: x) >= 0)\n else { return .error(length: 1) }\n return .valid(Unicode.ASCII.EncodedScalar(x))\n }\n return .emptyInput\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ASCII.swift | cpp_apple_swift_stdlib_public_core_ASCII.swift | Swift | 3,115 | 0.8 | 0.061224 | 0.149425 | react-lib | 40 | 2024-10-19T05:17:56.019332 | GPL-3.0 | false | 5c8456696b36cf41492dbc0bf3d0a598 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Performs a traditional C-style assert with an optional message.\n///\n/// Use this function for internal consistency checks that are active during testing\n/// but do not impact performance of shipping code. To check for invalid usage\n/// in Release builds, see `precondition(_:_:file:line:)`.\n///\n/// * In playgrounds and `-Onone` builds (the default for Xcode's Debug\n/// configuration): If `condition` evaluates to `false`, stop program\n/// execution in a debuggable state after printing `message`.\n///\n/// * In `-O` builds (the default for Xcode's Release configuration),\n/// `condition` is not evaluated, and there are no effects.\n///\n/// * In `-Ounchecked` builds, `condition` is not evaluated, but the optimizer\n/// may assume that it *always* evaluates to `true`. Failure to satisfy that\n/// assumption is a serious programming error.\n///\n/// - Parameters:\n/// - condition: The condition to test. `condition` is only evaluated in\n/// playgrounds and `-Onone` builds.\n/// - message: A string to print if `condition` is evaluated to `false`. The\n/// default is an empty string.\n/// - file: The file name to print with `message` if the assertion fails. The\n/// default is the file where `assert(_:_:file:line:)` is called.\n/// - line: The line number to print along with `message` if the assertion\n/// fails. The default is the line number where `assert(_:_:file:line:)`\n/// is called.\n@_transparent\n#if $Embedded\n@_disfavoredOverload\n#endif\npublic func assert(\n _ condition: @autoclosure () -> Bool,\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #file, line: UInt = #line\n) {\n // Only assert in debug mode.\n if _isDebugAssertConfiguration() {\n if !_fastPath(condition()) {\n _assertionFailure("Assertion failed", message(), file: file, line: line,\n flags: _fatalErrorFlags())\n }\n }\n}\n\n#if $Embedded\n@_transparent\npublic func assert(\n _ condition: @autoclosure () -> Bool,\n _ message: @autoclosure () -> StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) {\n // Only assert in debug mode.\n if _isDebugAssertConfiguration() {\n if !_fastPath(condition()) {\n _assertionFailure("Assertion failed", message(), file: file, line: line,\n flags: _fatalErrorFlags())\n }\n }\n}\n#endif\n\n/// Checks a necessary condition for making forward progress.\n///\n/// Use this function to detect conditions that must prevent the program from\n/// proceeding, even in shipping code.\n///\n/// * In playgrounds and `-Onone` builds (the default for Xcode's Debug\n/// configuration): If `condition` evaluates to `false`, stop program\n/// execution in a debuggable state after printing `message`.\n///\n/// * In `-O` builds (the default for Xcode's Release configuration): If\n/// `condition` evaluates to `false`, stop program execution.\n///\n/// * In `-Ounchecked` builds, `condition` is not evaluated, but the optimizer\n/// may assume that it *always* evaluates to `true`. Failure to satisfy that\n/// assumption is a serious programming error.\n///\n/// - Parameters:\n/// - condition: The condition to test. `condition` is not evaluated in\n/// `-Ounchecked` builds.\n/// - message: A string to print if `condition` is evaluated to `false` in a\n/// playground or `-Onone` build. The default is an empty string.\n/// - file: The file name to print with `message` if the precondition fails.\n/// The default is the file where `precondition(_:_:file:line:)` is\n/// called.\n/// - line: The line number to print along with `message` if the assertion\n/// fails. The default is the line number where\n/// `precondition(_:_:file:line:)` is called.\n@_transparent\n#if $Embedded\n@_disfavoredOverload\n#endif\npublic func precondition(\n _ condition: @autoclosure () -> Bool,\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #file, line: UInt = #line\n) {\n // Only check in debug and release mode. In release mode just trap.\n if _isDebugAssertConfiguration() {\n if !_fastPath(condition()) {\n _assertionFailure("Precondition failed", message(), file: file, line: line,\n flags: _fatalErrorFlags())\n }\n } else if _isReleaseAssertConfiguration() {\n let error = !condition()\n Builtin.condfail_message(error._value,\n StaticString("precondition failure").unsafeRawPointer)\n }\n}\n\n#if $Embedded\n@_transparent\npublic func precondition(\n _ condition: @autoclosure () -> Bool,\n _ message: @autoclosure () -> StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) {\n // Only check in debug and release mode. In release mode just trap.\n if _isDebugAssertConfiguration() {\n if !_fastPath(condition()) {\n _assertionFailure("Precondition failed", message(), file: file, line: line,\n flags: _fatalErrorFlags())\n }\n } else if _isReleaseAssertConfiguration() {\n let error = !condition()\n Builtin.condfail_message(error._value,\n StaticString("precondition failure").unsafeRawPointer)\n }\n}\n#endif\n\n/// Indicates that an internal consistency check failed.\n///\n/// This function's effect varies depending on the build flag used:\n///\n/// * In playgrounds and `-Onone` builds (the default for Xcode's Debug\n/// configuration), stop program execution in a debuggable state after\n/// printing `message`.\n///\n/// * In `-O` builds, has no effect.\n///\n/// * In `-Ounchecked` builds, the optimizer may assume that this function is\n/// never called. Failure to satisfy that assumption is a serious\n/// programming error.\n///\n/// - Parameters:\n/// - message: A string to print in a playground or `-Onone` build. The\n/// default is an empty string.\n/// - file: The file name to print with `message`. The default is the file\n/// where `assertionFailure(_:file:line:)` is called.\n/// - line: The line number to print along with `message`. The default is the\n/// line number where `assertionFailure(_:file:line:)` is called.\n@inlinable\n@inline(__always)\n#if $Embedded\n@_disfavoredOverload\n#endif\npublic func assertionFailure(\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #file, line: UInt = #line\n) {\n if _isDebugAssertConfiguration() {\n _assertionFailure("Fatal error", message(), file: file, line: line,\n flags: _fatalErrorFlags())\n }\n else if _isFastAssertConfiguration() {\n _conditionallyUnreachable()\n }\n}\n\n#if $Embedded\n@inlinable\n@inline(__always)\npublic func assertionFailure(\n _ message: @autoclosure () -> StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) {\n if _isDebugAssertConfiguration() {\n _assertionFailure("Fatal error", message(), file: file, line: line,\n flags: _fatalErrorFlags())\n }\n else if _isFastAssertConfiguration() {\n _conditionallyUnreachable()\n }\n}\n#endif\n\n/// Indicates that a precondition was violated.\n///\n/// Use this function to stop the program when control flow can only reach the\n/// call if your API was improperly used and execution flow is not expected to\n/// reach the call---for example, in the `default` case of a `switch` where\n/// you have knowledge that one of the other cases must be satisfied.\n///\n/// This function's effect varies depending on the build flag used:\n///\n/// * In playgrounds and `-Onone` builds (the default for Xcode's Debug\n/// configuration), stops program execution in a debuggable state after\n/// printing `message`.\n///\n/// * In `-O` builds (the default for Xcode's Release configuration), stops\n/// program execution.\n///\n/// * In `-Ounchecked` builds, the optimizer may assume that this function is\n/// never called. Failure to satisfy that assumption is a serious\n/// programming error.\n///\n/// - Parameters:\n/// - message: A string to print in a playground or `-Onone` build. The\n/// default is an empty string.\n/// - file: The file name to print with `message`. The default is the file\n/// where `preconditionFailure(_:file:line:)` is called.\n/// - line: The line number to print along with `message`. The default is the\n/// line number where `preconditionFailure(_:file:line:)` is called.\n@_transparent\n#if $Embedded\n@_disfavoredOverload\n#endif\npublic func preconditionFailure(\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #file, line: UInt = #line\n) -> Never {\n // Only check in debug and release mode. In release mode just trap.\n if _isDebugAssertConfiguration() {\n _assertionFailure("Fatal error", message(), file: file, line: line,\n flags: _fatalErrorFlags())\n } else if _isReleaseAssertConfiguration() {\n Builtin.condfail_message(true._value,\n StaticString("precondition failure").unsafeRawPointer)\n }\n _conditionallyUnreachable()\n}\n\n#if $Embedded\n@_transparent\npublic func preconditionFailure(\n _ message: @autoclosure () -> StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) -> Never {\n // Only check in debug and release mode. In release mode just trap.\n if _isDebugAssertConfiguration() {\n _assertionFailure("Fatal error", message(), file: file, line: line,\n flags: _fatalErrorFlags())\n } else if _isReleaseAssertConfiguration() {\n Builtin.condfail_message(true._value,\n StaticString("precondition failure").unsafeRawPointer)\n }\n _conditionallyUnreachable()\n}\n#endif\n\n/// Unconditionally prints a given message and stops execution.\n///\n/// - Parameters:\n/// - message: The string to print. The default is an empty string.\n/// - file: The file name to print with `message`. The default is the file\n/// where `fatalError(_:file:line:)` is called.\n/// - line: The line number to print along with `message`. The default is the\n/// line number where `fatalError(_:file:line:)` is called.\n@_transparent\n#if $Embedded\n@_disfavoredOverload\n#endif\npublic func fatalError(\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #file, line: UInt = #line\n) -> Never {\n#if !$Embedded\n _assertionFailure("Fatal error", message(), file: file, line: line,\n flags: _fatalErrorFlags())\n#else\n if _isDebugAssertConfiguration() {\n _assertionFailure("Fatal error", message(), file: file, line: line,\n flags: _fatalErrorFlags())\n } else {\n Builtin.condfail_message(true._value,\n StaticString("fatal error").unsafeRawPointer)\n Builtin.unreachable()\n }\n#endif\n}\n\n#if $Embedded\n@_transparent\npublic func fatalError(\n _ message: @autoclosure () -> StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) -> Never {\n if _isDebugAssertConfiguration() {\n _assertionFailure("Fatal error", message(), file: file, line: line,\n flags: _fatalErrorFlags())\n } else {\n Builtin.condfail_message(true._value,\n StaticString("fatal error").unsafeRawPointer)\n Builtin.unreachable()\n }\n}\n#endif\n\n/// Library precondition checks.\n///\n/// Library precondition checks are enabled in debug mode and release mode. When\n/// building in fast mode they are disabled. In release mode they don't print\n/// an error message but just trap. In debug mode they print an error message\n/// and abort.\n@usableFromInline @_transparent\ninternal func _precondition(\n _ condition: @autoclosure () -> Bool, _ message: StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) {\n // Only check in debug and release mode. In release mode just trap.\n if _isDebugAssertConfiguration() {\n if !_fastPath(condition()) {\n _assertionFailure("Fatal error", message, file: file, line: line,\n flags: _fatalErrorFlags())\n }\n } else if _isReleaseAssertConfiguration() {\n let error = !condition()\n Builtin.condfail_message(error._value, message.unsafeRawPointer)\n }\n}\n\n@usableFromInline @_transparent\ninternal func _preconditionFailure(\n _ message: StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) -> Never {\n _precondition(false, message, file: file, line: line)\n _conditionallyUnreachable()\n}\n\n/// If `error` is true, prints an error message in debug mode, traps in release\n/// mode, and returns an undefined error otherwise.\n/// Otherwise returns `result`.\n@_transparent\npublic func _overflowChecked<T>(\n _ args: (T, Bool),\n file: StaticString = #file, line: UInt = #line\n) -> T {\n let (result, error) = args\n if _isDebugAssertConfiguration() {\n if _slowPath(error) {\n _fatalErrorMessage("Fatal error", "Overflow/underflow",\n file: file, line: line, flags: _fatalErrorFlags())\n }\n } else {\n Builtin.condfail_message(error._value,\n StaticString("_overflowChecked failure").unsafeRawPointer)\n }\n return result\n}\n\n\n/// Debug library precondition checks.\n///\n/// Debug library precondition checks are only on in debug mode. In release and\n/// in fast mode they are disabled. In debug mode they print an error message\n/// and abort.\n/// They are meant to be used when the check is not comprehensively checking for\n/// all possible errors.\n@usableFromInline @_transparent\ninternal func _debugPrecondition(\n _ condition: @autoclosure () -> Bool, _ message: StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) {\n#if SWIFT_STDLIB_ENABLE_DEBUG_PRECONDITIONS_IN_RELEASE\n _precondition(condition(), message, file: file, line: line)\n#else\n // Only check in debug mode.\n if _slowPath(_isDebugAssertConfiguration()) {\n if !_fastPath(condition()) {\n _fatalErrorMessage("Fatal error", message, file: file, line: line,\n flags: _fatalErrorFlags())\n }\n }\n#endif\n}\n\n@usableFromInline @_transparent\ninternal func _debugPreconditionFailure(\n _ message: StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) -> Never {\n#if SWIFT_STDLIB_ENABLE_DEBUG_PRECONDITIONS_IN_RELEASE\n _preconditionFailure(message, file: file, line: line)\n#else\n if _slowPath(_isDebugAssertConfiguration()) {\n _precondition(false, message, file: file, line: line)\n }\n _conditionallyUnreachable()\n#endif\n}\n\n/// Internal checks.\n///\n/// Internal checks are to be used for checking correctness conditions in the\n/// standard library. They are only enable when the standard library is built\n/// with the build configuration INTERNAL_CHECKS_ENABLED enabled. Otherwise, the\n/// call to this function is a noop.\n@usableFromInline @_transparent\ninternal func _internalInvariant(\n _ condition: @autoclosure () -> Bool, _ message: StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) {\n#if INTERNAL_CHECKS_ENABLED\n if !_fastPath(condition()) {\n _fatalErrorMessage("Fatal error", message, file: file, line: line,\n flags: _fatalErrorFlags())\n }\n#endif\n}\n\n// Only perform the invariant check on Swift 5.1 and later\n@_alwaysEmitIntoClient // Swift 5.1\n@_transparent\ninternal func _internalInvariant_5_1(\n _ condition: @autoclosure () -> Bool, _ message: StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) {\n#if INTERNAL_CHECKS_ENABLED\n // FIXME: The below won't run the assert on 5.1 stdlib if testing on older\n // OSes, which means that testing may not test the assertion. We need a real\n // solution to this.\n#if !$Embedded\n guard #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) //SwiftStdlib 5.1\n else { return }\n#endif\n _internalInvariant(condition(), message, file: file, line: line)\n#endif\n}\n\n/// Library precondition checks with a linked-on-or-after check, allowing the\n/// addition of new preconditions while maintaining compatibility with older\n/// binaries.\n///\n/// This version of `_precondition` only traps if the condition returns false\n/// **and** the current executable was built with a Swift Standard Library\n/// version equal to or greater than the supplied version.\n@_transparent\ninternal func _precondition(\n ifLinkedOnOrAfter version: _SwiftStdlibVersion,\n _ condition: @autoclosure () -> Bool,\n _ message: StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) {\n // Delay the linked-on-or-after check until after we know we have a failed\n // condition, so that we don't slow down the usual case too much.\n\n // Note: this is an internal function, so `_isDebugAssertConfiguration` is\n // expected to evaluate (at compile time) to true in production builds of the\n // stdlib. The other branches are kept in case the stdlib is built with an\n // unusual configuration.\n if _isDebugAssertConfiguration() {\n if _slowPath(!condition()) {\n #if !$Embedded\n guard _isExecutableLinkedOnOrAfter(version) else { return }\n #endif\n _assertionFailure("Fatal error", message, file: file, line: line,\n flags: _fatalErrorFlags())\n }\n } else if _isReleaseAssertConfiguration() {\n #if !$Embedded\n let error = (!condition() && _isExecutableLinkedOnOrAfter(version))\n #else\n let error = !condition()\n #endif\n Builtin.condfail_message(error._value, message.unsafeRawPointer)\n }\n}\n\n@usableFromInline @_transparent\ninternal func _internalInvariantFailure(\n _ message: StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) -> Never {\n _internalInvariant(false, message, file: file, line: line)\n _conditionallyUnreachable()\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Assert.swift | cpp_apple_swift_stdlib_public_core_Assert.swift | Swift | 17,675 | 0.95 | 0.173116 | 0.442553 | vue-tools | 980 | 2025-06-10T05:19:35.422542 | BSD-3-Clause | false | b724ef44e0f495e8653704c7ccaf3b65 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n// Implementation Note: this file intentionally uses very LOW-LEVEL\n// CONSTRUCTS, so that assert and fatal may be used liberally in\n// building library abstractions without fear of infinite recursion.\n//\n// FIXME: We could go farther with this simplification, e.g. avoiding\n// UnsafeMutablePointer\n\n@_transparent\npublic // @testable\nfunc _isDebugAssertConfiguration() -> Bool {\n // The values for the assert_configuration call are:\n // 0: Debug\n // 1: Release\n // 2: Fast\n return Int32(Builtin.assert_configuration()) == 0\n}\n\n@_transparent\npublic // @testable, used in _Concurrency executor preconditions\nfunc _isReleaseAssertConfiguration() -> Bool {\n // The values for the assert_configuration call are:\n // 0: Debug\n // 1: Release\n // 2: Fast\n return Int32(Builtin.assert_configuration()) == 1\n}\n\n@_transparent\npublic // @testable\nfunc _isFastAssertConfiguration() -> Bool {\n // The values for the assert_configuration call are:\n // 0: Debug\n // 1: Release\n // 2: Fast\n return Int32(Builtin.assert_configuration()) == 2\n}\n\n@_transparent\npublic // @testable\nfunc _isStdlibInternalChecksEnabled() -> Bool {\n#if INTERNAL_CHECKS_ENABLED\n return true\n#else\n return false\n#endif\n}\n\n@_transparent\n@_alwaysEmitIntoClient // Introduced in 5.7\npublic // @testable\nfunc _isStdlibDebugChecksEnabled() -> Bool {\n#if SWIFT_STDLIB_ENABLE_DEBUG_PRECONDITIONS_IN_RELEASE\n return !_isFastAssertConfiguration()\n#else\n return _isDebugAssertConfiguration()\n#endif\n}\n\n@usableFromInline @_transparent\ninternal func _fatalErrorFlags() -> UInt32 {\n // The current flags are:\n // (1 << 0): Report backtrace on fatal error\n#if os(iOS) || os(tvOS) || os(watchOS) || os(visionOS)\n return 0\n#else\n return _isDebugAssertConfiguration() ? 1 : 0\n#endif\n}\n\n/// This function should be used only in the implementation of user-level\n/// assertions.\n///\n/// This function should not be inlined in desktop Swift because it is cold and\n/// inlining just bloats code. In Embedded Swift, we force inlining as this\n/// function is typically just a trap (in release configurations).\n@usableFromInline\n#if !$Embedded\n@inline(never)\n#else\n@inline(__always)\n#endif\n@_semantics("programtermination_point")\ninternal func _assertionFailure(\n _ prefix: StaticString, _ message: StaticString,\n file: StaticString, line: UInt,\n flags: UInt32\n) -> Never {\n#if !$Embedded\n prefix.withUTF8Buffer {\n (prefix) -> Void in\n message.withUTF8Buffer {\n (message) -> Void in\n file.withUTF8Buffer {\n (file) -> Void in\n unsafe _swift_stdlib_reportFatalErrorInFile(\n prefix.baseAddress!, CInt(prefix.count),\n message.baseAddress!, CInt(message.count),\n file.baseAddress!, CInt(file.count), UInt32(line),\n flags)\n Builtin.int_trap()\n }\n }\n }\n#else\n if _isDebugAssertConfiguration() {\n _embeddedReportFatalErrorInFile(prefix: prefix, message: message,\n file: file, line: line)\n }\n#endif\n Builtin.int_trap()\n}\n\n/// This function should be used only in the implementation of user-level\n/// assertions.\n///\n/// This function should not be inlined in desktop Swift because it is cold and\n/// inlining just bloats code. In Embedded Swift, we force inlining as this\n/// function is typically just a trap (in release configurations).\n@usableFromInline\n#if !$Embedded\n@inline(never)\n#else\n@_disfavoredOverload\n@inline(__always)\n#endif\n@_semantics("programtermination_point")\ninternal func _assertionFailure(\n _ prefix: StaticString, _ message: String,\n file: StaticString, line: UInt,\n flags: UInt32\n) -> Never {\n#if !$Embedded\n prefix.withUTF8Buffer {\n (prefix) -> Void in\n var message = message\n message.withUTF8 {\n (messageUTF8) -> Void in\n file.withUTF8Buffer {\n (file) -> Void in\n unsafe _swift_stdlib_reportFatalErrorInFile(\n prefix.baseAddress!, CInt(prefix.count),\n messageUTF8.baseAddress!, CInt(messageUTF8.count),\n file.baseAddress!, CInt(file.count), UInt32(line),\n flags)\n }\n }\n }\n#else\n if _isDebugAssertConfiguration() {\n var message = message\n message.withUTF8 { (messageUTF8) -> Void in\n unsafe _embeddedReportFatalErrorInFile(prefix: prefix, message: messageUTF8, file: file, line: line)\n }\n }\n#endif\n\n Builtin.int_trap()\n}\n\n/// This function should be used only in the implementation of user-level\n/// assertions.\n///\n/// This function should not be inlined in desktop Swift because it is cold and\n/// inlining just bloats code. In Embedded Swift, we force inlining as this\n/// function is typically just a trap (in release configurations).\n@usableFromInline\n#if !$Embedded\n@inline(never)\n#else\n@inline(__always)\n#endif\n@_semantics("programtermination_point")\n@_unavailableInEmbedded\ninternal func _assertionFailure(\n _ prefix: StaticString, _ message: String,\n flags: UInt32\n) -> Never {\n prefix.withUTF8Buffer {\n (prefix) -> Void in\n var message = message\n message.withUTF8 {\n (messageUTF8) -> Void in\n unsafe _swift_stdlib_reportFatalError(\n prefix.baseAddress!, CInt(prefix.count),\n messageUTF8.baseAddress!, CInt(messageUTF8.count),\n flags)\n }\n }\n\n Builtin.int_trap()\n}\n\n#if $Embedded\n@usableFromInline\n@inline(never)\n@_semantics("programtermination_point")\ninternal func _assertionFailure(\n _ prefix: StaticString, _ message: StaticString,\n flags: UInt32\n) -> Never {\n if _isDebugAssertConfiguration() {\n _embeddedReportFatalError(prefix: prefix, message: message)\n }\n\n Builtin.int_trap()\n}\n#endif\n\n/// This function should be used only in the implementation of stdlib\n/// assertions.\n///\n/// This function should not be inlined in desktop Swift because it is cold and\n/// inlining just bloats code. In Embedded Swift, we force inlining as this\n/// function is typically just a trap (in release configurations).\n@usableFromInline\n#if !$Embedded\n@inline(never)\n#else\n@inline(__always)\n#endif\n@_semantics("programtermination_point")\ninternal func _fatalErrorMessage(\n _ prefix: StaticString, _ message: StaticString,\n file: StaticString, line: UInt,\n flags: UInt32\n) -> Never {\n _assertionFailure(prefix, message, file: file, line: line, flags: flags)\n}\n\n/// Prints a fatal error message when an unimplemented initializer gets\n/// called by the Objective-C runtime.\n@_transparent\npublic // COMPILER_INTRINSIC\nfunc _unimplementedInitializer(className: StaticString,\n initName: StaticString = #function,\n file: StaticString = #file,\n line: UInt = #line,\n column: UInt = #column\n) -> Never {\n // This function is marked @_transparent so that it is inlined into the caller\n // (the initializer stub), and, depending on the build configuration,\n // redundant parameter values (#file etc.) are eliminated, and don't leak\n // information about the user's source.\n\n#if !$Embedded\n if _isDebugAssertConfiguration() {\n className.withUTF8Buffer {\n (className) in\n initName.withUTF8Buffer {\n (initName) in\n file.withUTF8Buffer {\n (file) in\n unsafe _swift_stdlib_reportUnimplementedInitializerInFile(\n className.baseAddress!, CInt(className.count),\n initName.baseAddress!, CInt(initName.count),\n file.baseAddress!, CInt(file.count),\n UInt32(line), UInt32(column),\n /*flags:*/ 0)\n }\n }\n }\n } else {\n className.withUTF8Buffer {\n (className) in\n initName.withUTF8Buffer {\n (initName) in\n unsafe _swift_stdlib_reportUnimplementedInitializer(\n className.baseAddress!, CInt(className.count),\n initName.baseAddress!, CInt(initName.count),\n /*flags:*/ 0)\n }\n }\n }\n#endif\n\n Builtin.int_trap()\n}\n\n#if !$Embedded\n\n/// Used to evaluate editor placeholders.\npublic // COMPILER_INTRINSIC\nfunc _undefined<T>(\n _ message: @autoclosure () -> String = String(),\n file: StaticString = #file, line: UInt = #line\n) -> T {\n _assertionFailure("Fatal error", message(), file: file, line: line, flags: 0)\n}\n\n#else\n\n/// Used to evaluate editor placeholders.\npublic // COMPILER_INTRINSIC\nfunc _undefined<T>(\n _ message: @autoclosure () -> StaticString = StaticString(),\n file: StaticString = #file, line: UInt = #line\n) -> T {\n _assertionFailure("Fatal error", message(), file: file, line: line, flags: 0)\n}\n\n#endif\n\n/// Called when falling off the end of a switch and the type can be represented\n/// as a raw value.\n///\n/// This function should not be inlined in desktop Swift because it is cold and\n/// inlining just bloats code. In Embedded Swift, we force inlining as this\n/// function is typically just a trap (in release configurations).\n///\n/// It doesn't take a source location because it's most important\n/// in release builds anyway (old apps that are run on new OSs).\n#if !$Embedded\n@inline(never)\n#else\n@inline(__always)\n#endif\n@usableFromInline // COMPILER_INTRINSIC\ninternal func _diagnoseUnexpectedEnumCaseValue<SwitchedValue, RawValue>(\n type: SwitchedValue.Type,\n rawValue: RawValue\n) -> Never {\n#if !$Embedded\n _assertionFailure("Fatal error",\n "unexpected enum case '\(type)(rawValue: \(rawValue))'",\n flags: _fatalErrorFlags())\n#else\n Builtin.int_trap()\n#endif\n}\n\n/// Called when falling off the end of a switch and the value is not safe to\n/// print.\n///\n/// This function should not be inlined in desktop Swift because it is cold and\n/// inlining just bloats code. In Embedded Swift, we force inlining as this\n/// function is typically just a trap (in release configurations).\n///\n/// It doesn't take a source location because it's most important\n/// in release builds anyway (old apps that are run on new OSs).\n#if !$Embedded\n@inline(never)\n#else\n@inline(__always)\n#endif\n@usableFromInline // COMPILER_INTRINSIC\ninternal func _diagnoseUnexpectedEnumCase<SwitchedValue>(\n type: SwitchedValue.Type\n) -> Never {\n#if !$Embedded\n _assertionFailure(\n "Fatal error",\n "unexpected enum case while switching on value of type '\(type)'",\n flags: _fatalErrorFlags())\n#else\n Builtin.int_trap()\n#endif\n}\n\n/// Called when a function marked `unavailable` with `@available` is invoked\n/// and the module containing the unavailable function was compiled with\n/// `-unavailable-decl-optimization=stub`.\n///\n/// This function should not be inlined in desktop Swift because it is cold and\n/// inlining just bloats code. In Embedded Swift, we force inlining as this\n/// function is typically just a trap (in release configurations).\n@backDeployed(before: SwiftStdlib 5.9)\n#if !$Embedded\n@inline(never)\n#else\n@inline(__always)\n#endif\n@_semantics("unavailable_code_reached")\n@usableFromInline // COMPILER_INTRINSIC\ninternal func _diagnoseUnavailableCodeReached() -> Never {\n _assertionFailure(\n "Fatal error", "Unavailable code reached", flags: _fatalErrorFlags())\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_AssertCommon.swift | cpp_apple_swift_stdlib_public_core_AssertCommon.swift | Swift | 11,465 | 0.95 | 0.130435 | 0.381868 | vue-tools | 924 | 2024-02-19T08:40:01.581825 | Apache-2.0 | false | c2a1826af547e7059b672cd7e5250d73 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n/// Returns 1 if the running OS version is greater than or equal to\n/// major.minor.patchVersion and 0 otherwise.\n///\n/// This is a magic entry point known to the compiler. It is called in\n/// generated code for API availability checking.\n///\n/// This is marked @_transparent on iOS to work around broken availability\n/// checking for iOS apps running on macOS (rdar://83378814). libswiftCore uses\n/// the macOS platform identifier for its version check in that scenario,\n/// causing all queries to return true. When this function is inlined into the\n/// caller, the compiler embeds the correct platform identifier in the client\n/// code, and we get the right answer.\n///\n/// @_transparent breaks the optimizer's ability to remove availability checks\n/// that are unnecessary due to the current deployment target. We call through\n/// to the _stdlib_isOSVersionAtLeast_AEIC function below to work around this,\n/// as the optimizer is able to perform this optimization for a\n/// @_alwaysEmitIntoClient function. We can't use @_alwaysEmitIntoClient\n/// directly on this call because it would break ABI for existing apps.\n///\n/// `@_transparent` breaks the interpreter mode on macOS, as it creates a direct\n/// reference to ___isPlatformVersionAtLeast from compiler-rt, and the\n/// interpreter doesn't currently know how to load symbols from compiler-rt.\n/// Since `@_transparent` is only necessary for iOS apps, we only apply it on\n/// iOS, not any other which would inherit/remap iOS availability.\n#if os(iOS) && !os(visionOS)\n@_effects(readnone)\n@_transparent\n@_noLocks\npublic func _stdlib_isOSVersionAtLeast(\n _ major: Builtin.Word,\n _ minor: Builtin.Word,\n _ patch: Builtin.Word\n) -> Builtin.Int1 {\n return _stdlib_isOSVersionAtLeast_AEIC(major, minor, patch)\n}\n#else\n@_semantics("availability.osversion")\n@_effects(readnone)\n@_unavailableInEmbedded\n#if hasFeature(Macros)\n@_noLocks\n#endif\npublic func _stdlib_isOSVersionAtLeast(\n _ major: Builtin.Word,\n _ minor: Builtin.Word,\n _ patch: Builtin.Word\n) -> Builtin.Int1 {\n return _stdlib_isOSVersionAtLeast_AEIC(major, minor, patch)\n}\n#endif\n\n@_semantics("availability.osversion")\n@_effects(readnone)\n@_alwaysEmitIntoClient\n#if hasFeature(Macros)\n@_noLocks\n#endif\npublic func _stdlib_isOSVersionAtLeast_AEIC(\n _ major: Builtin.Word,\n _ minor: Builtin.Word,\n _ patch: Builtin.Word\n) -> Builtin.Int1 {\n#if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(visionOS)) && SWIFT_RUNTIME_OS_VERSIONING\n if Int(major) == 9999 {\n return true._value\n }\n\n let queryVersion = (Int(major), Int(minor), Int(patch))\n let major32 = Int32(truncatingIfNeeded:Int(queryVersion.0))\n let minor32 = Int32(truncatingIfNeeded:Int(queryVersion.1))\n let patch32 = Int32(truncatingIfNeeded:Int(queryVersion.2))\n\n // Defer to a builtin that calls clang's version checking builtin from\n // compiler-rt.\n let result32 = Int32(Builtin.targetOSVersionAtLeast(major32._value,\n minor32._value,\n patch32._value))\n return (result32 != (0 as Int32))._value\n#else\n // FIXME: As yet, there is no obvious versioning standard for platforms other\n // than Darwin-based OSes, so we just assume false for now. \n // rdar://problem/18881232\n return false._value\n#endif\n}\n\n// Performs an availability check in macCatalyst code to support back\n// deployment. This entry point takes in a variant OS version\n// (i.e, an iOS version).\n//\n// This is not inlinable because we\n// don't want to inline the messy implementation details of the\n// compiler-rt support into apps and expose those as ABI surface.\n//\n// This is a magic entry point known to the compiler. It is called in\n// generated code for API availability checking.\n\n#if (os(macOS) || os(iOS) && targetEnvironment(macCatalyst)) && SWIFT_RUNTIME_OS_VERSIONING\n@_semantics("availability.osversion")\n@_effects(readnone)\n@available(macOS 10.15, iOS 13.0, *)\n#if hasFeature(Macros)\n@_noLocks\n#endif\npublic func _stdlib_isVariantOSVersionAtLeast(\n _ major: Builtin.Word,\n _ minor: Builtin.Word,\n _ patch: Builtin.Word\n ) -> Builtin.Int1 {\n if Int(major) == 9999 {\n return true._value\n }\n let queryVersion = (Int(major), Int(minor), Int(patch))\n let major32 = Int32(truncatingIfNeeded:Int(queryVersion.0))\n let minor32 = Int32(truncatingIfNeeded:Int(queryVersion.1))\n let patch32 = Int32(truncatingIfNeeded:Int(queryVersion.2))\n\n // Defer to a builtin that calls clang's version checking builtin from\n // compiler-rt.\n let result32 = Int32(Builtin.targetVariantOSVersionAtLeast(major32._value,\n minor32._value,\n patch32._value))\n return (result32 != (0 as Int32))._value\n}\n#endif\n\n// Performs an availability check in zippered code to support back\n// deployment. This entry point takes in both a primary OS version\n// (i.e., a macOS version) and a variant OS version (i.e, an iOS version).\n//\n// In a normal macOS process it will return 1 if the running OS version is\n// greater than or equal to major.minor.patchVersion and 0 otherwise. For an\n// macCatalyst process it will return 1 if the running macCatalyst version is greater\n// than or equal to the passed-in variant version.\n//\n// Unlike _stdlib_isOSVersionAtLeast, this is not inlinable because we\n// don't want to inline the messy implementation details of the\n// compiler-rt support into apps and expose those as ABI surface.\n//\n// This is a magic entry point known to the compiler. It is called in\n// generated code for API availability checking.\n\n#if (os(macOS) || os(iOS) && targetEnvironment(macCatalyst)) && SWIFT_RUNTIME_OS_VERSIONING\n@_semantics("availability.osversion")\n@_effects(readnone)\n@_unavailableInEmbedded\n#if hasFeature(Macros)\n@_noLocks\n#endif\npublic func _stdlib_isOSVersionAtLeastOrVariantVersionAtLeast(\n _ major: Builtin.Word,\n _ minor: Builtin.Word,\n _ patch: Builtin.Word,\n _ variantMajor: Builtin.Word,\n _ variantMinor: Builtin.Word,\n _ variantPatch: Builtin.Word\n ) -> Builtin.Int1 {\n if Int(major) == 9999 {\n return true._value\n }\n let queryVersion = (Int(major), Int(minor), Int(patch))\n let queryVariantVersion =\n (Int(variantMajor), Int(variantMinor), Int(variantPatch))\n\n let major32 = UInt32(truncatingIfNeeded:Int(queryVersion.0))\n let minor32 = UInt32(truncatingIfNeeded:Int(queryVersion.1))\n let patch32 = UInt32(truncatingIfNeeded:Int(queryVersion.2))\n\n let variantMajor32 = UInt32(truncatingIfNeeded:Int(queryVariantVersion.0))\n let variantMinor32 = UInt32(truncatingIfNeeded:Int(queryVariantVersion.1))\n let variantPatch32 = UInt32(truncatingIfNeeded:Int(queryVariantVersion.2))\n\n // Defer to a builtin that calls clang's version checking builtin from\n // compiler-rt.\n let result32 = Int32(Builtin.targetOSVersionOrVariantOSVersionAtLeast(\n major32._value, minor32._value, patch32._value,\n variantMajor32._value, variantMinor32._value, variantPatch32._value))\n\n return (result32 != (0 as UInt32))._value\n}\n#endif\n\npublic typealias _SwiftStdlibVersion = SwiftShims._SwiftStdlibVersion\n\n/// Return true if the main executable was linked with an SDK version\n/// corresponding to the given Swift Stdlib release, or later. Otherwise, return\n/// false.\n///\n/// This is useful to maintain compatibility with older binaries after a\n/// behavioral change in the stdlib.\n///\n/// This function must not be called from inlinable code.\n@inline(__always)\n@_unavailableInEmbedded\ninternal func _isExecutableLinkedOnOrAfter(\n _ stdlibVersion: _SwiftStdlibVersion\n) -> Bool {\n#if SWIFT_RUNTIME_OS_VERSIONING\n return _swift_stdlib_isExecutableLinkedOnOrAfter(stdlibVersion)\n#else\n return true\n#endif\n}\n\nextension _SwiftStdlibVersion {\n @_alwaysEmitIntoClient\n public static var v5_6_0: Self { Self(_value: 0x050600) }\n\n @_alwaysEmitIntoClient\n public static var v5_7_0: Self { Self(_value: 0x050700) }\n\n // Note: As of now, there is no bincompat level defined for the versions\n // below. If you need to use one of these in a call to\n // `_isExecutableLinkedOnOrAfter`, then you'll need to define the\n // corresponding version in the runtime.\n @_alwaysEmitIntoClient\n public static var v5_8_0: Self { Self(_value: 0x050800) }\n @_alwaysEmitIntoClient\n public static var v5_9_0: Self { Self(_value: 0x050900) }\n @_alwaysEmitIntoClient\n public static var v5_10_0: Self { Self(_value: 0x050A00) }\n @_alwaysEmitIntoClient\n public static var v6_0_0: Self { Self(_value: 0x060000) }\n @_alwaysEmitIntoClient\n public static var v6_1_0: Self { Self(_value: 0x060100) }\n @_alwaysEmitIntoClient\n public static var v6_2_0: Self { Self(_value: 0x060200) }\n\n @available(SwiftStdlib 5.7, *)\n public static var current: Self { .v6_2_0 }\n}\n\n@available(SwiftStdlib 5.7, *)\n@_unavailableInEmbedded\nextension _SwiftStdlibVersion: CustomStringConvertible {\n @available(SwiftStdlib 5.7, *)\n public var description: String {\n let major = _value >> 16\n let minor = (_value >> 8) & 0xFF\n let patch = _value & 0xFF\n return "\(major).\(minor).\(patch)"\n }\n}\n\n\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Availability.swift | cpp_apple_swift_stdlib_public_core_Availability.swift | Swift | 9,667 | 0.95 | 0.126923 | 0.434599 | vue-tools | 518 | 2023-11-17T16:01:50.528054 | BSD-3-Clause | false | 789c698d9f1a4ab4eb13492fe8637579 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A collection that supports backward as well as forward traversal.\n///\n/// Bidirectional collections offer traversal backward from any valid index,\n/// not including a collection's `startIndex`. Bidirectional collections can\n/// therefore offer additional operations, such as a `last` property that\n/// provides efficient access to the last element and a `reversed()` method\n/// that presents the elements in reverse order. In addition, bidirectional\n/// collections have more efficient implementations of some sequence and\n/// collection methods, such as `suffix(_:)`.\n///\n/// Conforming to the BidirectionalCollection Protocol\n/// ==================================================\n///\n/// To add `BidirectionalProtocol` conformance to your custom types, implement\n/// the `index(before:)` method in addition to the requirements of the\n/// `Collection` protocol.\n///\n/// Indices that are moved forward and backward in a bidirectional collection\n/// move by the same amount in each direction. That is, for any valid index `i`\n/// into a bidirectional collection `c`:\n///\n/// - If `i >= c.startIndex && i < c.endIndex`, then\n/// `c.index(before: c.index(after: i)) == i`.\n/// - If `i > c.startIndex && i <= c.endIndex`, then\n/// `c.index(after: c.index(before: i)) == i`.\n///\n/// Valid indices are exactly those indices that are reachable from the\n/// collection's `startIndex` by repeated applications of `index(after:)`, up\n/// to, and including, the `endIndex`.\npublic protocol BidirectionalCollection<Element>: Collection\nwhere SubSequence: BidirectionalCollection, Indices: BidirectionalCollection {\n // FIXME: Only needed for associated type inference.\n override associatedtype Element\n override associatedtype Index\n override associatedtype SubSequence\n override associatedtype Indices\n\n /// Returns the position immediately before the given index.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be greater than\n /// `startIndex`.\n /// - Returns: The index value immediately before `i`.\n func index(before i: Index) -> Index\n\n /// Replaces the given index with its predecessor.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be greater than\n /// `startIndex`.\n func formIndex(before i: inout Index)\n\n /// Returns the position immediately after the given index.\n ///\n /// The successor of an index must be well defined. For an index `i` into a\n /// collection `c`, calling `c.index(after: i)` returns the same index every\n /// time.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be less than\n /// `endIndex`.\n /// - Returns: The index value immediately after `i`.\n override func index(after i: Index) -> Index\n\n /// Replaces the given index with its successor.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be less than\n /// `endIndex`.\n override func formIndex(after i: inout Index)\n\n /// Returns an index that is the specified distance from the given index.\n ///\n /// The following example obtains an index advanced four positions from a\n /// string's starting index and then prints the character at that position.\n ///\n /// let s = "Swift"\n /// let i = s.index(s.startIndex, offsetBy: 4)\n /// print(s[i])\n /// // Prints "t"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection.\n ///\n /// - Parameters:\n /// - i: A valid index of the collection.\n /// - distance: The distance to offset `i`. `distance` must not be negative\n /// unless the collection conforms to the `BidirectionalCollection`\n /// protocol.\n /// - Returns: An index offset by `distance` from the index `i`. If\n /// `distance` is positive, this is the same value as the result of\n /// `distance` calls to `index(after:)`. If `distance` is negative, this\n /// is the same value as the result of `abs(distance)` calls to\n /// `index(before:)`.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute\n /// value of `distance`.\n @_nonoverride func index(_ i: Index, offsetBy distance: Int) -> Index\n\n /// Returns an index that is the specified distance from the given index,\n /// unless that distance is beyond a given limiting index.\n ///\n /// The following example obtains an index advanced four positions from a\n /// string's starting index and then prints the character at that position.\n /// The operation doesn't require going beyond the limiting `s.endIndex`\n /// value, so it succeeds.\n ///\n /// let s = "Swift"\n /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {\n /// print(s[i])\n /// }\n /// // Prints "t"\n ///\n /// The next example attempts to retrieve an index six positions from\n /// `s.startIndex` but fails, because that distance is beyond the index\n /// passed as `limit`.\n ///\n /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)\n /// print(j)\n /// // Prints "nil"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection, unless the index passed as `limit` prevents offsetting\n /// beyond those bounds.\n ///\n /// - Parameters:\n /// - i: A valid index of the collection.\n /// - distance: The distance to offset `i`. `distance` must not be negative\n /// unless the collection conforms to the `BidirectionalCollection`\n /// protocol.\n /// - limit: A valid index of the collection to use as a limit. If\n /// `distance > 0`, a limit that is less than `i` has no effect.\n /// Likewise, if `distance < 0`, a limit that is greater than `i` has no\n /// effect.\n /// - Returns: An index offset by `distance` from the index `i`, unless that\n /// index would be beyond `limit` in the direction of movement. In that\n /// case, the method returns `nil`.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute\n /// value of `distance`.\n @_nonoverride func index(\n _ i: Index, offsetBy distance: Int, limitedBy limit: Index\n ) -> Index?\n\n /// Returns the distance between two indices.\n ///\n /// Unless the collection conforms to the `BidirectionalCollection` protocol,\n /// `start` must be less than or equal to `end`.\n ///\n /// - Parameters:\n /// - start: A valid index of the collection.\n /// - end: Another valid index of the collection. If `end` is equal to\n /// `start`, the result is zero.\n /// - Returns: The distance between `start` and `end`. The result can be\n /// negative only if the collection conforms to the\n /// `BidirectionalCollection` protocol.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the\n /// resulting distance.\n @_nonoverride func distance(from start: Index, to end: Index) -> Int\n\n /// The indices that are valid for subscripting the collection, in ascending\n /// order.\n ///\n /// A collection's `indices` property can hold a strong reference to the\n /// collection itself, causing the collection to be non-uniquely referenced.\n /// If you mutate the collection while iterating over its indices, a strong\n /// reference can cause an unexpected copy of the collection. To avoid the\n /// unexpected copy, use the `index(after:)` method starting with\n /// `startIndex` to produce indices instead.\n ///\n /// var c = MyFancyCollection([10, 20, 30, 40, 50])\n /// var i = c.startIndex\n /// while i != c.endIndex {\n /// c[i] /= 5\n /// i = c.index(after: i)\n /// }\n /// // c == MyFancyCollection([2, 4, 6, 8, 10])\n override var indices: Indices { get }\n \n /// Accesses a contiguous subrange of the collection's elements.\n ///\n /// The accessed slice uses the same indices for the same elements as the\n /// original collection uses. Always use the slice's `startIndex` property\n /// instead of assuming that its indices start at a particular value.\n ///\n /// This example demonstrates getting a slice of an array of strings, finding\n /// the index of one of the strings in the slice, and then using that index\n /// in the original array.\n ///\n /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// let streetsSlice = streets[2 ..< streets.endIndex]\n /// print(streetsSlice)\n /// // Prints "["Channing", "Douglas", "Evarts"]"\n ///\n /// let index = streetsSlice.firstIndex(of: "Evarts") // 4\n /// print(streets[index!])\n /// // Prints "Evarts"\n ///\n /// - Parameter bounds: A range of the collection's indices. The bounds of\n /// the range must be valid indices of the collection.\n ///\n /// - Complexity: O(1)\n override subscript(bounds: Range<Index>) -> SubSequence { get }\n\n // FIXME: Only needed for associated type inference.\n @_borrowed\n override subscript(position: Index) -> Element { get }\n override var startIndex: Index { get }\n override var endIndex: Index { get }\n}\n\n/// Default implementation for bidirectional collections.\nextension BidirectionalCollection {\n\n @inlinable // protocol-only\n @inline(__always)\n public func formIndex(before i: inout Index) {\n i = index(before: i)\n }\n\n @inlinable // protocol-only\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n return _index(i, offsetBy: distance)\n }\n\n @inlinable // protocol-only\n internal func _index(_ i: Index, offsetBy distance: Int) -> Index {\n if distance >= 0 {\n return _advanceForward(i, by: distance)\n }\n var i = i\n for _ in stride(from: 0, to: distance, by: -1) {\n formIndex(before: &i)\n }\n return i\n }\n\n @inlinable // protocol-only\n public func index(\n _ i: Index, offsetBy distance: Int, limitedBy limit: Index\n ) -> Index? {\n return _index(i, offsetBy: distance, limitedBy: limit)\n }\n\n @inlinable // protocol-only\n internal func _index(\n _ i: Index, offsetBy distance: Int, limitedBy limit: Index\n ) -> Index? {\n if distance >= 0 {\n return _advanceForward(i, by: distance, limitedBy: limit)\n }\n var i = i\n for _ in stride(from: 0, to: distance, by: -1) {\n if i == limit {\n return nil\n }\n formIndex(before: &i)\n }\n return i\n }\n\n @inlinable // protocol-only\n public func distance(from start: Index, to end: Index) -> Int {\n return _distance(from: start, to: end)\n }\n\n @inlinable // protocol-only\n internal func _distance(from start: Index, to end: Index) -> Int {\n var start = start\n var count = 0\n\n if start < end {\n while start != end {\n count += 1\n formIndex(after: &start)\n }\n }\n else if start > end {\n while start != end {\n count -= 1\n formIndex(before: &start)\n }\n }\n\n return count\n }\n}\n\nextension BidirectionalCollection where SubSequence == Self {\n /// Removes and returns the last element of the collection.\n ///\n /// You can use `popLast()` to remove the last element of a collection that\n /// might be empty. The `removeLast()` method must be used only on a\n /// nonempty collection.\n ///\n /// - Returns: The last element of the collection if the collection has one\n /// or more elements; otherwise, `nil`.\n ///\n /// - Complexity: O(1)\n @inlinable // protocol-only\n public mutating func popLast() -> Element? {\n guard !isEmpty else { return nil }\n let element = last!\n self = self[startIndex..<index(before: endIndex)]\n return element\n }\n\n /// Removes and returns the last element of the collection.\n ///\n /// The collection must not be empty. To remove the last element of a\n /// collection that might be empty, use the `popLast()` method instead.\n ///\n /// - Returns: The last element of the collection.\n ///\n /// - Complexity: O(1)\n @inlinable // protocol-only\n @discardableResult\n public mutating func removeLast() -> Element {\n let element = last!\n self = self[startIndex..<index(before: endIndex)]\n return element\n }\n\n /// Removes the given number of elements from the end of the collection.\n ///\n /// - Parameter k: The number of elements to remove. `k` must be greater\n /// than or equal to zero, and must be less than or equal to the number of\n /// elements in the collection.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of\n /// elements to remove.\n @inlinable // protocol-only\n public mutating func removeLast(_ k: Int) {\n if k == 0 { return }\n _precondition(k >= 0, "Number of elements to remove should be non-negative")\n guard let end = index(endIndex, offsetBy: -k, limitedBy: startIndex)\n else {\n _preconditionFailure(\n "Can't remove more items from a collection than it contains")\n }\n self = self[startIndex..<end]\n }\n}\n\nextension BidirectionalCollection {\n /// Returns a subsequence containing all but the specified number of final\n /// elements.\n ///\n /// If the number of elements to drop exceeds the number of elements in the\n /// collection, the result is an empty subsequence.\n ///\n /// let numbers = [1, 2, 3, 4, 5]\n /// print(numbers.dropLast(2))\n /// // Prints "[1, 2, 3]"\n /// print(numbers.dropLast(10))\n /// // Prints "[]"\n ///\n /// - Parameter k: The number of elements to drop off the end of the\n /// collection. `k` must be greater than or equal to zero.\n /// - Returns: A subsequence that leaves off `k` elements from the end.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of\n /// elements to drop.\n @inlinable // protocol-only\n public __consuming func dropLast(_ k: Int) -> SubSequence {\n _precondition(\n k >= 0, "Can't drop a negative number of elements from a collection")\n let end = index(\n endIndex,\n offsetBy: -k,\n limitedBy: startIndex) ?? startIndex\n return self[startIndex..<end]\n }\n\n /// Returns a subsequence, up to the given maximum length, containing the\n /// final elements of the collection.\n ///\n /// If the maximum length exceeds the number of elements in the collection,\n /// the result contains the entire collection.\n ///\n /// let numbers = [1, 2, 3, 4, 5]\n /// print(numbers.suffix(2))\n /// // Prints "[4, 5]"\n /// print(numbers.suffix(10))\n /// // Prints "[1, 2, 3, 4, 5]"\n ///\n /// - Parameter maxLength: The maximum number of elements to return.\n /// `maxLength` must be greater than or equal to zero.\n /// - Returns: A subsequence terminating at the end of the collection with at\n /// most `maxLength` elements.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is equal to\n /// `maxLength`.\n @inlinable // protocol-only\n public __consuming func suffix(_ maxLength: Int) -> SubSequence {\n _precondition(\n maxLength >= 0,\n "Can't take a suffix of negative length from a collection")\n let start = index(\n endIndex,\n offsetBy: -maxLength,\n limitedBy: startIndex) ?? startIndex\n return self[start..<endIndex]\n }\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_BidirectionalCollection.swift | cpp_apple_swift_stdlib_public_core_BidirectionalCollection.swift | Swift | 15,823 | 0.95 | 0.071259 | 0.649746 | awesome-app | 41 | 2023-11-08T02:16:08.206481 | BSD-3-Clause | false | 45113a9046d19ec99a685023e4b15c2e |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A simple bitmap of a fixed number of bits, implementing a sorted set of\n/// small nonnegative Int values.\n///\n/// Because `_UnsafeBitset` implements a flat bit vector, it isn't suitable for\n/// holding arbitrarily large integers. The maximal element a bitset can store\n/// is fixed at its initialization.\n@frozen\n@usableFromInline // @testable\n@unsafe\ninternal struct _UnsafeBitset {\n @usableFromInline\n internal let words: UnsafeMutablePointer<Word>\n\n @usableFromInline\n @safe\n internal let wordCount: Int\n\n @inlinable\n @inline(__always)\n internal init(words: UnsafeMutablePointer<Word>, wordCount: Int) {\n unsafe self.words = unsafe words\n self.wordCount = wordCount\n }\n}\n\n@available(*, unavailable)\nextension _UnsafeBitset: Sendable {}\n\nextension _UnsafeBitset {\n @inlinable\n @inline(__always)\n internal static func word(for element: Int) -> Int {\n _internalInvariant(element >= 0)\n // Note: We perform on UInts to get faster unsigned math (shifts).\n let element = UInt(bitPattern: element)\n let capacity = UInt(bitPattern: Word.capacity)\n return Int(bitPattern: element / capacity)\n }\n\n @inlinable\n @inline(__always)\n internal static func bit(for element: Int) -> Int {\n _internalInvariant(element >= 0)\n // Note: We perform on UInts to get faster unsigned math (masking).\n let element = UInt(bitPattern: element)\n let capacity = UInt(bitPattern: Word.capacity)\n return Int(bitPattern: element % capacity)\n }\n\n @inlinable\n @inline(__always)\n internal static func split(_ element: Int) -> (word: Int, bit: Int) {\n return unsafe (word(for: element), bit(for: element))\n }\n\n @inlinable\n @inline(__always)\n internal static func join(word: Int, bit: Int) -> Int {\n _internalInvariant(bit >= 0 && bit < Word.capacity)\n return word &* Word.capacity &+ bit\n }\n}\n\nextension _UnsafeBitset {\n @inlinable\n @inline(__always)\n internal static func wordCount(forCapacity capacity: Int) -> Int {\n return unsafe word(for: capacity &+ Word.capacity &- 1)\n }\n\n @inlinable\n internal var capacity: Int {\n @inline(__always)\n get {\n return wordCount &* Word.capacity\n }\n }\n\n @inlinable\n @inline(__always)\n internal func isValid(_ element: Int) -> Bool {\n return unsafe element >= 0 && element <= capacity\n }\n\n @inlinable\n @inline(__always)\n internal func uncheckedContains(_ element: Int) -> Bool {\n unsafe _internalInvariant(isValid(element))\n let (word, bit) = unsafe _UnsafeBitset.split(element)\n return unsafe words[word].uncheckedContains(bit)\n }\n\n @inlinable\n @inline(__always)\n @discardableResult\n internal func uncheckedInsert(_ element: Int) -> Bool {\n unsafe _internalInvariant(isValid(element))\n let (word, bit) = unsafe _UnsafeBitset.split(element)\n return unsafe words[word].uncheckedInsert(bit)\n }\n\n @inlinable\n @inline(__always)\n @discardableResult\n internal func uncheckedRemove(_ element: Int) -> Bool {\n unsafe _internalInvariant(isValid(element))\n let (word, bit) = unsafe _UnsafeBitset.split(element)\n return unsafe words[word].uncheckedRemove(bit)\n }\n\n @inlinable\n @inline(__always)\n internal func clear() {\n unsafe words.update(repeating: .empty, count: wordCount)\n }\n}\n\nextension _UnsafeBitset: @unsafe Sequence {\n @usableFromInline\n internal typealias Element = Int\n\n @inlinable\n internal var count: Int {\n var count = 0\n for w in 0 ..< wordCount {\n unsafe count += words[w].count\n }\n return count\n }\n\n @inlinable\n internal var underestimatedCount: Int {\n return unsafe count\n }\n\n @inlinable\n func makeIterator() -> Iterator {\n return unsafe Iterator(self)\n }\n\n @unsafe\n @usableFromInline\n @frozen\n internal struct Iterator: IteratorProtocol {\n @usableFromInline\n internal let bitset: _UnsafeBitset\n @usableFromInline\n internal var index: Int\n @usableFromInline\n internal var word: Word\n\n @inlinable\n internal init(_ bitset: _UnsafeBitset) {\n unsafe self.bitset = unsafe bitset\n unsafe self.index = 0\n unsafe self.word = unsafe bitset.wordCount > 0 ? bitset.words[0] : .empty\n }\n\n @inlinable\n internal mutating func next() -> Int? {\n if let bit = unsafe word.next() {\n return unsafe _UnsafeBitset.join(word: index, bit: bit)\n }\n while unsafe (index + 1) < bitset.wordCount {\n unsafe index += 1\n unsafe word = unsafe bitset.words[index]\n if let bit = unsafe word.next() {\n return unsafe _UnsafeBitset.join(word: index, bit: bit)\n }\n }\n return nil\n }\n }\n}\n\n@available(*, unavailable)\nextension _UnsafeBitset.Iterator: Sendable {}\n\n////////////////////////////////////////////////////////////////////////////////\n\nextension _UnsafeBitset {\n @frozen\n @usableFromInline\n internal struct Word {\n @usableFromInline\n internal var value: UInt\n\n @inlinable\n internal init(_ value: UInt) {\n self.value = value\n }\n }\n}\n\nextension _UnsafeBitset.Word {\n @inlinable\n internal static var capacity: Int {\n @inline(__always)\n get {\n return UInt.bitWidth\n }\n }\n\n @inlinable\n @inline(__always)\n internal func uncheckedContains(_ bit: Int) -> Bool {\n _internalInvariant(bit >= 0 && bit < UInt.bitWidth)\n return value & (1 &<< bit) != 0\n }\n\n @inlinable\n @inline(__always)\n @discardableResult\n internal mutating func uncheckedInsert(_ bit: Int) -> Bool {\n _internalInvariant(bit >= 0 && bit < UInt.bitWidth)\n let mask: UInt = 1 &<< bit\n let inserted = value & mask == 0\n value |= mask\n return inserted\n }\n\n @inlinable\n @inline(__always)\n @discardableResult\n internal mutating func uncheckedRemove(_ bit: Int) -> Bool {\n _internalInvariant(bit >= 0 && bit < UInt.bitWidth)\n let mask: UInt = 1 &<< bit\n let removed = value & mask != 0\n value &= ~mask\n return removed\n }\n}\n\nextension _UnsafeBitset.Word {\n @inlinable\n var minimum: Int? {\n @inline(__always)\n get {\n guard value != 0 else { return nil }\n return value.trailingZeroBitCount\n }\n }\n\n @inlinable\n var maximum: Int? {\n @inline(__always)\n get {\n guard value != 0 else { return nil }\n return _UnsafeBitset.Word.capacity &- 1 &- value.leadingZeroBitCount\n }\n }\n\n @inlinable\n var complement: _UnsafeBitset.Word {\n @inline(__always)\n get {\n return _UnsafeBitset.Word(~value)\n }\n }\n\n @inlinable\n @inline(__always)\n internal func subtracting(elementsBelow bit: Int) -> _UnsafeBitset.Word {\n _internalInvariant(bit >= 0 && bit < _UnsafeBitset.Word.capacity)\n let mask = UInt.max &<< bit\n return _UnsafeBitset.Word(value & mask)\n }\n\n @inlinable\n @inline(__always)\n internal func intersecting(elementsBelow bit: Int) -> _UnsafeBitset.Word {\n _internalInvariant(bit >= 0 && bit < _UnsafeBitset.Word.capacity)\n let mask: UInt = (1 as UInt &<< bit) &- 1\n return _UnsafeBitset.Word(value & mask)\n }\n\n @inlinable\n @inline(__always)\n internal func intersecting(elementsAbove bit: Int) -> _UnsafeBitset.Word {\n _internalInvariant(bit >= 0 && bit < _UnsafeBitset.Word.capacity)\n let mask = (UInt.max &<< bit) &<< 1\n return _UnsafeBitset.Word(value & mask)\n }\n}\n\nextension _UnsafeBitset.Word {\n @inlinable\n internal static var empty: _UnsafeBitset.Word {\n @inline(__always)\n get {\n return _UnsafeBitset.Word(0)\n }\n }\n\n @inlinable\n internal static var allBits: _UnsafeBitset.Word {\n @inline(__always)\n get {\n return _UnsafeBitset.Word(UInt.max)\n }\n }\n}\n\n// Word implements Sequence by using a copy of itself as its Iterator.\n// Iteration with `next()` destroys the word's value; however, this won't cause\n// problems in normal use, because `next()` is usually called on a separate\n// iterator, not the original word.\nextension _UnsafeBitset.Word: @unsafe Sequence, @unsafe IteratorProtocol {\n\n @usableFromInline\n typealias Element = Int\n\n @inlinable\n internal var count: Int {\n return value.nonzeroBitCount\n }\n\n @inlinable\n internal var underestimatedCount: Int {\n return count\n }\n\n @inlinable\n internal var isEmpty: Bool {\n @inline(__always)\n get {\n return value == 0\n }\n }\n\n /// Return the index of the lowest set bit in this word,\n /// and also destructively clear it.\n @inlinable\n internal mutating func next() -> Int? {\n guard value != 0 else { return nil }\n let bit = value.trailingZeroBitCount\n value &= value &- 1 // Clear lowest nonzero bit.\n return bit\n }\n}\n\nextension _UnsafeBitset {\n @_alwaysEmitIntoClient\n @inline(__always)\n internal static func _withTemporaryUninitializedBitset<R>(\n wordCount: Int,\n body: (_UnsafeBitset) throws -> R\n ) rethrows -> R {\n try unsafe withUnsafeTemporaryAllocation(\n of: _UnsafeBitset.Word.self, capacity: wordCount\n ) { buffer in\n let bitset = unsafe _UnsafeBitset(\n words: buffer.baseAddress!, wordCount: buffer.count)\n return try unsafe body(bitset)\n }\n }\n\n @_alwaysEmitIntoClient\n @inline(__always)\n internal static func withTemporaryBitset<R>(\n capacity: Int,\n body: (_UnsafeBitset) throws -> R\n ) rethrows -> R {\n let wordCount = unsafe Swift.max(1, Self.wordCount(forCapacity: capacity))\n return try unsafe _withTemporaryUninitializedBitset(\n wordCount: wordCount\n ) { bitset in\n unsafe bitset.clear()\n return try unsafe body(bitset)\n }\n }\n}\n\nextension _UnsafeBitset {\n @_alwaysEmitIntoClient\n @inline(__always)\n internal static func withTemporaryCopy<R>(\n of original: _UnsafeBitset,\n body: (_UnsafeBitset) throws -> R\n ) rethrows -> R {\n try unsafe _withTemporaryUninitializedBitset(\n wordCount: original.wordCount\n ) { bitset in\n unsafe bitset.words.initialize(from: original.words, count: original.wordCount)\n return try unsafe body(bitset)\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Bitset.swift | cpp_apple_swift_stdlib_public_core_Bitset.swift | Swift | 10,350 | 0.8 | 0.045 | 0.073654 | python-kit | 605 | 2025-02-26T17:13:11.874935 | MIT | false | 42abe7662bf7efc8d9b3bbb1e3f527a0 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n// Bool Datatype and Supporting Operators\n//===----------------------------------------------------------------------===//\n\n/// A value type whose instances are either `true` or `false`.\n///\n/// `Bool` represents Boolean values in Swift. Create instances of `Bool` by\n/// using one of the Boolean literals `true` or `false`, or by assigning the\n/// result of a Boolean method or operation to a variable or constant.\n///\n/// var godotHasArrived = false\n///\n/// let numbers = 1...5\n/// let containsTen = numbers.contains(10)\n/// print(containsTen)\n/// // Prints "false"\n///\n/// let (a, b) = (100, 101)\n/// let aFirst = a < b\n/// print(aFirst)\n/// // Prints "true"\n///\n/// Swift uses only simple Boolean values in conditional contexts to help avoid\n/// accidental programming errors and to help maintain the clarity of each\n/// control statement. Unlike in other programming languages, in Swift, integers\n/// and strings cannot be used where a Boolean value is required.\n///\n/// For example, the following code sample does not compile, because it\n/// attempts to use the integer `i` in a logical context:\n///\n/// var i = 5\n/// while i {\n/// print(i)\n/// i -= 1\n/// }\n/// // error: Cannot convert value of type 'Int' to expected condition type 'Bool'\n///\n/// The correct approach in Swift is to compare the `i` value with zero in the\n/// `while` statement.\n///\n/// while i != 0 {\n/// print(i)\n/// i -= 1\n/// }\n///\n/// Using Imported Boolean values\n/// =============================\n///\n/// The C `bool` and `Boolean` types and the Objective-C `BOOL` type are all\n/// bridged into Swift as `Bool`. The single `Bool` type in Swift guarantees\n/// that functions, methods, and properties imported from C and Objective-C\n/// have a consistent type interface.\n@frozen\npublic struct Bool: Sendable {\n public var _value: Builtin.Int1\n\n /// Creates an instance initialized to `false`.\n ///\n /// Do not call this initializer directly. Instead, use the Boolean literal\n /// `false` to create a new `Bool` instance.\n @_transparent\n public init() {\n let zero: Int8 = 0\n self._value = Builtin.trunc_Int8_Int1(zero._value)\n }\n\n @_transparent\n public init(_ _v: Builtin.Int1) { self._value = _v }\n \n /// Creates an instance equal to the given Boolean value.\n ///\n /// - Parameter value: The Boolean value to copy.\n @inlinable\n public init(_ value: Bool) {\n self = value\n }\n\n /// Returns a random Boolean value, using the given generator as a source for\n /// randomness.\n ///\n /// This method returns `true` and `false` with equal probability. Use this\n /// method to generate a random Boolean value when you are using a custom\n /// random number generator.\n ///\n /// let flippedHeads = Bool.random(using: &myGenerator)\n /// if flippedHeads {\n /// print("Heads, you win!")\n /// } else {\n /// print("Maybe another try?")\n /// }\n ///\n /// - Note: The algorithm used to create random values may change in a future\n /// version of Swift. If you're passing a generator that results in the\n /// same sequence of Boolean values each time you run your program, that\n /// sequence may change when your program is compiled using a different\n /// version of Swift.\n ///\n /// - Parameter generator: The random number generator to use when creating\n /// the new random value.\n /// - Returns: Either `true` or `false`, randomly chosen with equal\n /// probability.\n @inlinable\n public static func random<T: RandomNumberGenerator>(\n using generator: inout T\n ) -> Bool {\n return (generator.next() >> 17) & 1 == 0\n }\n \n /// Returns a random Boolean value.\n ///\n /// This method returns `true` and `false` with equal probability.\n ///\n /// let flippedHeads = Bool.random()\n /// if flippedHeads {\n /// print("Heads, you win!")\n /// } else {\n /// print("Maybe another try?")\n /// }\n ///\n /// This method is equivalent to calling `Bool.random(using:)`, passing in\n /// the system's default random generator.\n ///\n /// - Returns: Either `true` or `false`, randomly chosen with equal\n /// probability.\n @inlinable\n public static func random() -> Bool {\n var g = SystemRandomNumberGenerator()\n return Bool.random(using: &g)\n }\n}\n\nextension Bool: _ExpressibleByBuiltinBooleanLiteral, ExpressibleByBooleanLiteral {\n @_transparent\n @_semantics("bool.literal_init")\n public init(_builtinBooleanLiteral value: Builtin.Int1) {\n self._value = value\n }\n\n /// Creates an instance initialized to the specified Boolean literal.\n ///\n /// Do not call this initializer directly. It is used by the compiler when\n /// you use a Boolean literal. Instead, create a new `Bool` instance by\n /// using one of the Boolean literals `true` or `false`.\n ///\n /// var printedMessage = false\n ///\n /// if !printedMessage {\n /// print("You look nice today!")\n /// printedMessage = true\n /// }\n /// // Prints "You look nice today!"\n ///\n /// In this example, both assignments to the `printedMessage` variable call\n /// this Boolean literal initializer behind the scenes.\n ///\n /// - Parameter value: The value of the new instance.\n @_transparent\n public init(booleanLiteral value: Bool) {\n self = value\n }\n}\n\nextension Bool: CustomStringConvertible {\n /// A textual representation of the Boolean value.\n @inlinable\n public var description: String {\n return self ? "true" : "false"\n }\n}\n\nextension Bool: Equatable {\n @_transparent\n public static func == (lhs: Bool, rhs: Bool) -> Bool {\n return Bool(Builtin.cmp_eq_Int1(lhs._value, rhs._value))\n }\n}\n\nextension Bool: Hashable {\n /// Hashes the essential components of this value by feeding them into the\n /// given hasher.\n ///\n /// - Parameter hasher: The hasher to use when combining the components\n /// of this instance.\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine((self ? 1 : 0) as UInt8)\n }\n}\n\nextension Bool: LosslessStringConvertible {\n /// Creates a new Boolean value from the given string.\n ///\n /// If the `description` value is any string other than `"true"` or\n /// `"false"`, the result is `nil`. This initializer is case sensitive.\n ///\n /// - Parameter description: A string representation of the Boolean value.\n @inlinable\n public init?(_ description: String) {\n if description == "true" {\n self = true\n } else if description == "false" {\n self = false\n } else {\n return nil\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Operators\n//===----------------------------------------------------------------------===//\n\nextension Bool {\n /// Performs a logical NOT operation on a Boolean value.\n ///\n /// The logical NOT operator (`!`) inverts a Boolean value. If the value is\n /// `true`, the result of the operation is `false`; if the value is `false`,\n /// the result is `true`.\n ///\n /// var printedMessage = false\n ///\n /// if !printedMessage {\n /// print("You look nice today!")\n /// printedMessage = true\n /// }\n /// // Prints "You look nice today!"\n ///\n /// - Parameter a: The Boolean value to negate.\n @_transparent\n public static prefix func ! (a: Bool) -> Bool {\n return Bool(Builtin.xor_Int1(a._value, true._value))\n }\n}\n\nextension Bool {\n /// Performs a logical AND operation on two Boolean values.\n ///\n /// The logical AND operator (`&&`) combines two Boolean values and returns\n /// `true` if both of the values are `true`. If either of the values is\n /// `false`, the operator returns `false`.\n ///\n /// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is\n /// evaluated first, and the right-hand side (`rhs`) is evaluated only if\n /// `lhs` evaluates to `true`. For example:\n ///\n /// let measurements = [7.44, 6.51, 4.74, 5.88, 6.27, 6.12, 7.76]\n /// let sum = measurements.reduce(0, +)\n ///\n /// if measurements.count > 0 && sum / Double(measurements.count) < 6.5 {\n /// print("Average measurement is less than 6.5")\n /// }\n /// // Prints "Average measurement is less than 6.5"\n ///\n /// In this example, `lhs` tests whether `measurements.count` is greater than\n /// zero. Evaluation of the `&&` operator is one of the following:\n ///\n /// - When `measurements.count` is equal to zero, `lhs` evaluates to `false`\n /// and `rhs` is not evaluated, preventing a divide-by-zero error in the\n /// expression `sum / Double(measurements.count)`. The result of the\n /// operation is `false`.\n /// - When `measurements.count` is greater than zero, `lhs` evaluates to\n /// `true` and `rhs` is evaluated. The result of evaluating `rhs` is the\n /// result of the `&&` operation.\n ///\n /// - Parameters:\n /// - lhs: The left-hand side of the operation.\n /// - rhs: The right-hand side of the operation.\n @_transparent\n @inline(__always)\n public static func && (lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows\n -> Bool {\n return lhs ? try rhs() : false\n }\n\n /// Performs a logical OR operation on two Boolean values.\n ///\n /// The logical OR operator (`||`) combines two Boolean values and returns\n /// `true` if at least one of the values is `true`. If both values are\n /// `false`, the operator returns `false`.\n ///\n /// This operator uses short-circuit evaluation: The left-hand side (`lhs`) is\n /// evaluated first, and the right-hand side (`rhs`) is evaluated only if\n /// `lhs` evaluates to `false`. For example:\n ///\n /// let majorErrors: Set = ["No first name", "No last name", ...]\n /// let error = ""\n ///\n /// if error.isEmpty || !majorErrors.contains(error) {\n /// print("No major errors detected")\n /// } else {\n /// print("Major error: \(error)")\n /// }\n /// // Prints "No major errors detected"\n ///\n /// In this example, `lhs` tests whether `error` is an empty string.\n /// Evaluation of the `||` operator is one of the following:\n ///\n /// - When `error` is an empty string, `lhs` evaluates to `true` and `rhs` is\n /// not evaluated, skipping the call to `majorErrors.contains(_:)`. The\n /// result of the operation is `true`.\n /// - When `error` is not an empty string, `lhs` evaluates to `false` and\n /// `rhs` is evaluated. The result of evaluating `rhs` is the result of the\n /// `||` operation.\n ///\n /// - Parameters:\n /// - lhs: The left-hand side of the operation.\n /// - rhs: The right-hand side of the operation.\n @_transparent\n @inline(__always)\n public static func || (lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows\n -> Bool {\n return lhs ? true : try rhs()\n }\n}\n\nextension Bool {\n /// Toggles the Boolean variable's value.\n ///\n /// Use this method to toggle a Boolean value from `true` to `false` or from\n /// `false` to `true`.\n ///\n /// var bools = [true, false]\n ///\n /// bools[0].toggle()\n /// // bools == [false, false]\n @inlinable\n public mutating func toggle() {\n self = !self\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Bool.swift | cpp_apple_swift_stdlib_public_core_Bool.swift | Swift | 11,696 | 0.95 | 0.067647 | 0.712074 | node-utils | 125 | 2023-08-04T00:16:13.963046 | MIT | false | 225d72f25d02453149d51d0ea5ce05cf |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A Swift Array or Dictionary of types conforming to\n/// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or\n/// NSDictionary, respectively. The elements of the resulting NSArray\n/// or NSDictionary will be the result of calling `_bridgeToObjectiveC`\n/// on each element of the source container.\npublic protocol _ObjectiveCBridgeable {\n associatedtype _ObjectiveCType: AnyObject\n\n /// Convert `self` to Objective-C.\n func _bridgeToObjectiveC() -> _ObjectiveCType\n\n /// Bridge from an Objective-C object of the bridged class type to a\n /// value of the Self type.\n ///\n /// This bridging operation is used for forced downcasting (e.g.,\n /// via as), and may defer complete checking until later. For\n /// example, when bridging from `NSArray` to `Array<Element>`, we can defer\n /// the checking for the individual elements of the array.\n ///\n /// - parameter result: The location where the result is written. The optional\n /// will always contain a value.\n static func _forceBridgeFromObjectiveC(\n _ source: _ObjectiveCType,\n result: inout Self?\n )\n\n /// Try to bridge from an Objective-C object of the bridged class\n /// type to a value of the Self type.\n ///\n /// This conditional bridging operation is used for conditional\n /// downcasting (e.g., via as?) and therefore must perform a\n /// complete conversion to the value type; it cannot defer checking\n /// to a later time.\n ///\n /// - parameter result: The location where the result is written.\n ///\n /// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant\n /// information is provided for the convenience of the runtime's `dynamic_cast`\n /// implementation, so that it need not look into the optional representation\n /// to determine success.\n @discardableResult\n static func _conditionallyBridgeFromObjectiveC(\n _ source: _ObjectiveCType,\n result: inout Self?\n ) -> Bool\n\n /// Bridge from an Objective-C object of the bridged class type to a\n /// value of the Self type.\n ///\n /// This bridging operation is used for unconditional bridging when\n /// interoperating with Objective-C code, either in the body of an\n /// Objective-C thunk or when calling Objective-C code, and may\n /// defer complete checking until later. For example, when bridging\n /// from `NSArray` to `Array<Element>`, we can defer the checking\n /// for the individual elements of the array.\n ///\n /// \param source The Objective-C object from which we are\n /// bridging. This optional value will only be `nil` in cases where\n /// an Objective-C method has returned a `nil` despite being marked\n /// as `_Nonnull`/`nonnull`. In most such cases, bridging will\n /// generally force the value immediately. However, this gives\n /// bridging the flexibility to substitute a default value to cope\n /// with historical decisions, e.g., an existing Objective-C method\n /// that returns `nil` to for "empty result" rather than (say) an\n /// empty array. In such cases, when `nil` does occur, the\n /// implementation of `Swift.Array`'s conformance to\n /// `_ObjectiveCBridgeable` will produce an empty array rather than\n /// dynamically failing.\n @_effects(readonly)\n static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)\n -> Self\n}\n\n#if _runtime(_ObjC)\n\n// Note: This function is not intended to be called from Swift. The\n// availability information here is perfunctory; this function isn't considered\n// part of the Stdlib's Swift ABI.\n@available(SwiftStdlib 5.2, *)\n@_cdecl("_SwiftCreateBridgedArray")\n@usableFromInline\ninternal func _SwiftCreateBridgedArray_DoNotCall(\n values: UnsafePointer<AnyObject>,\n numValues: Int\n) -> Unmanaged<AnyObject> {\n let bufPtr = unsafe UnsafeBufferPointer(start: values, count: numValues)\n let bridged = unsafe Array(bufPtr)._bridgeToObjectiveCImpl()\n return unsafe Unmanaged<AnyObject>.passRetained(bridged)\n}\n\n// Note: This function is not intended to be called from Swift. The\n// availability information here is perfunctory; this function isn't considered\n// part of the Stdlib's Swift ABI.\n@available(SwiftStdlib 5.2, *)\n@_cdecl("_SwiftCreateBridgedMutableArray")\n@usableFromInline\ninternal func _SwiftCreateBridgedMutableArray_DoNotCall(\n values: UnsafePointer<AnyObject>,\n numValues: Int\n) -> Unmanaged<AnyObject> {\n let bufPtr = unsafe UnsafeBufferPointer(start: values, count: numValues)\n let bridged = unsafe _SwiftNSMutableArray(Array(bufPtr))\n return unsafe Unmanaged<AnyObject>.passRetained(bridged)\n}\n\n@_silgen_name("swift_stdlib_connectNSBaseClasses")\ninternal func _connectNSBaseClasses() -> Bool\n\n\nprivate let _bridgeInitializedSuccessfully = _connectNSBaseClasses()\ninternal var _orphanedFoundationSubclassesReparented: Bool = false\n\n/// Reparents the SwiftNativeNS*Base classes to be subclasses of their respective\n/// Foundation types, or is false if they couldn't be reparented. Must be run\n/// in order to bridge Swift Strings, Arrays, Dictionaries, Sets, or Enumerators to ObjC.\n internal func _connectOrphanedFoundationSubclassesIfNeeded() -> Void {\n let bridgeWorks = _bridgeInitializedSuccessfully\n _debugPrecondition(bridgeWorks)\n _orphanedFoundationSubclassesReparented = true\n}\n\n//===--- Bridging for metatypes -------------------------------------------===//\n\n/// A stand-in for a value of metatype type.\n///\n/// The language and runtime do not yet support protocol conformances for\n/// structural types like metatypes. However, we can use a struct that contains\n/// a metatype, make it conform to _ObjectiveCBridgeable, and its witness table\n/// will be ABI-compatible with one that directly provided conformance to the\n/// metatype type itself.\npublic struct _BridgeableMetatype: _ObjectiveCBridgeable {\n internal var value: AnyObject.Type\n\n internal init(value: AnyObject.Type) {\n self.value = value\n }\n\n public typealias _ObjectiveCType = AnyObject\n\n public func _bridgeToObjectiveC() -> AnyObject {\n return value\n }\n\n public static func _forceBridgeFromObjectiveC(\n _ source: AnyObject,\n result: inout _BridgeableMetatype?\n ) {\n result = _BridgeableMetatype(value: source as! AnyObject.Type)\n }\n\n public static func _conditionallyBridgeFromObjectiveC(\n _ source: AnyObject,\n result: inout _BridgeableMetatype?\n ) -> Bool {\n if let type = source as? AnyObject.Type {\n result = _BridgeableMetatype(value: type)\n return true\n }\n\n result = nil\n return false\n }\n\n @_effects(readonly)\n public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)\n -> _BridgeableMetatype {\n var result: _BridgeableMetatype?\n _forceBridgeFromObjectiveC(source!, result: &result)\n return result!\n }\n}\n\nextension _BridgeableMetatype: Sendable {}\n\n//===--- Bridging facilities written in Objective-C -----------------------===//\n// Functions that must discover and possibly use an arbitrary type's\n// conformance to a given protocol. See ../runtime/Casting.cpp for\n// implementations.\n//===----------------------------------------------------------------------===//\n\n/// Bridge an arbitrary value to an Objective-C object.\n///\n/// - If `T` is a class type, it is always bridged verbatim, the function\n/// returns `x`;\n///\n/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`,\n/// returns the result of `x._bridgeToObjectiveC()`;\n///\n/// - otherwise, we use **boxing** to bring the value into Objective-C.\n/// The value is wrapped in an instance of a private Objective-C class\n/// that is `id`-compatible and dynamically castable back to the type of\n/// the boxed value, but is otherwise opaque.\n///\n// COMPILER_INTRINSIC\n@inlinable\npublic func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject {\n if _fastPath(_isClassOrObjCExistential(T.self)) {\n return unsafe unsafeBitCast(x, to: AnyObject.self)\n }\n return _bridgeAnythingNonVerbatimToObjectiveC(x)\n}\n\n@_silgen_name("")\npublic // @testable\nfunc _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: __owned T) -> AnyObject\n\n/// Convert a purportedly-nonnull `id` value from Objective-C into an Any.\n///\n/// Since Objective-C APIs sometimes get their nullability annotations wrong,\n/// this includes a failsafe against nil `AnyObject`s, wrapping them up as\n/// a nil `AnyObject?`-inside-an-`Any`.\n///\n// COMPILER_INTRINSIC\npublic func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any {\n if let nonnullObject = possiblyNullObject {\n return nonnullObject // AnyObject-in-Any\n }\n return possiblyNullObject as Any\n}\n\n/// Convert `x` from its Objective-C representation to its Swift\n/// representation.\n///\n/// - If `T` is a class type:\n/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged\n/// verbatim, the function returns `x`;\n/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:\n/// + if the dynamic type of `x` is not `T._ObjectiveCType`\n/// or a subclass of it, trap;\n/// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`;\n/// - otherwise, trap.\n@inlinable\npublic func _forceBridgeFromObjectiveC<T>(_ x: AnyObject, _: T.Type) -> T {\n if _fastPath(_isClassOrObjCExistential(T.self)) {\n return x as! T\n }\n\n var result: T?\n _bridgeNonVerbatimFromObjectiveC(x, T.self, &result)\n return result!\n}\n\n/// Convert `x` from its Objective-C representation to its Swift\n/// representation.\n// COMPILER_INTRINSIC\n@inlinable\npublic func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> (\n _ x: T._ObjectiveCType,\n _: T.Type\n) -> T {\n var result: T?\n T._forceBridgeFromObjectiveC(x, result: &result)\n return result!\n}\n\n/// Attempt to convert `x` from its Objective-C representation to its Swift\n/// representation.\n///\n/// - If `T` is a class type:\n/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged\n/// verbatim, the function returns `x`;\n/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:\n/// + otherwise, if the dynamic type of `x` is not `T._ObjectiveCType`\n/// or a subclass of it, the result is empty;\n/// + otherwise, returns the result of\n/// `T._conditionallyBridgeFromObjectiveC(x)`;\n/// - otherwise, the result is empty.\n@inlinable\npublic func _conditionallyBridgeFromObjectiveC<T>(\n _ x: AnyObject,\n _: T.Type\n) -> T? {\n if _fastPath(_isClassOrObjCExistential(T.self)) {\n return x as? T\n }\n\n var result: T?\n _ = _bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result)\n return result\n}\n\n/// Attempt to convert `x` from its Objective-C representation to its Swift\n/// representation.\n// COMPILER_INTRINSIC\n@inlinable\npublic func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(\n _ x: T._ObjectiveCType,\n _: T.Type\n) -> T? {\n var result: T?\n T._conditionallyBridgeFromObjectiveC (x, result: &result)\n return result\n}\n\n@_silgen_name("")\n@usableFromInline\ninternal func _bridgeNonVerbatimFromObjectiveC<T>(\n _ x: AnyObject,\n _ nativeType: T.Type,\n _ result: inout T?\n)\n\n/// Helper stub to upcast to Any and store the result to an inout Any?\n/// on the C++ runtime's behalf.\n@_silgen_name("_bridgeNonVerbatimFromObjectiveCToAny")\ninternal func _bridgeNonVerbatimFromObjectiveCToAny(\n _ x: AnyObject,\n _ result: inout Any?\n) {\n result = x as Any\n}\n\n/// Helper stub to upcast to Optional on the C++ runtime's behalf.\n@_silgen_name("_bridgeNonVerbatimBoxedValue")\ninternal func _bridgeNonVerbatimBoxedValue<NativeType>(\n _ x: UnsafePointer<NativeType>,\n _ result: inout NativeType?\n) {\n result = unsafe x.pointee\n}\n\n/// Runtime optional to conditionally perform a bridge from an object to a value\n/// type.\n///\n/// - parameter result: Will be set to the resulting value if bridging succeeds, and\n/// unchanged otherwise.\n///\n/// - Returns: `true` to indicate success, `false` to indicate failure.\n@_silgen_name("")\npublic func _bridgeNonVerbatimFromObjectiveCConditional<T>(\n _ x: AnyObject,\n _ nativeType: T.Type,\n _ result: inout T?\n) -> Bool\n\n/// Determines if values of a given type can be converted to an Objective-C\n/// representation.\n///\n/// - If `T` is a class type, returns `true`;\n/// - otherwise, returns whether `T` conforms to `_ObjectiveCBridgeable`.\npublic func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool {\n if _fastPath(_isClassOrObjCExistential(T.self)) {\n return true\n }\n return _isBridgedNonVerbatimToObjectiveC(T.self)\n}\n\n@_silgen_name("")\npublic func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool\n\n/// A type that's bridged "verbatim" does not conform to\n/// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an\n/// `AnyObject`. When this function returns true, the storage of an\n/// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`.\n@inlinable // FIXME(sil-serialize-all)\npublic func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool {\n return _isClassOrObjCExistential(T.self)\n}\n\n/// Retrieve the Objective-C type to which the given type is bridged.\n@inlinable // FIXME(sil-serialize-all)\npublic func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? {\n if _fastPath(_isClassOrObjCExistential(T.self)) {\n return T.self\n }\n return _getBridgedNonVerbatimObjectiveCType(T.self)\n}\n\n@_silgen_name("")\npublic func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type?\n\n// -- Pointer argument bridging\n\n/// A mutable pointer addressing an Objective-C reference that doesn't own its\n/// target.\n///\n/// `Pointee` must be a class type or `Optional<C>` where `C` is a class.\n///\n/// This type has implicit conversions to allow passing any of the following\n/// to a C or ObjC API:\n///\n/// - `nil`, which gets passed as a null pointer,\n/// - an inout argument of the referenced type, which gets passed as a pointer\n/// to a writeback temporary with autoreleasing ownership semantics,\n/// - an `UnsafeMutablePointer<Pointee>`, which is passed as-is.\n///\n/// Passing pointers to mutable arrays of ObjC class pointers is not\n/// directly supported. Unlike `UnsafeMutablePointer<Pointee>`,\n/// `AutoreleasingUnsafeMutablePointer<Pointee>` must reference storage that\n/// does not own a reference count to the referenced\n/// value. UnsafeMutablePointer's operations, by contrast, assume that\n/// the referenced storage owns values loaded from or stored to it.\n///\n/// This type does not carry an owner pointer unlike the other C*Pointer types\n/// because it only needs to reference the results of inout conversions, which\n/// already have writeback-scoped lifetime.\n@frozen\n@unsafe\npublic struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */>\n : @unsafe _Pointer {\n\n public let _rawValue: Builtin.RawPointer\n\n @_transparent\n public // COMPILER_INTRINSIC\n init(_ _rawValue: Builtin.RawPointer) {\n unsafe self._rawValue = _rawValue\n }\n\n /// Retrieve or set the `Pointee` instance referenced by `self`.\n ///\n /// `AutoreleasingUnsafeMutablePointer` is assumed to reference a value with\n /// `__autoreleasing` ownership semantics, like `NSFoo **` declarations in\n /// ARC. Setting the pointee autoreleases the new value before trivially\n /// storing it in the referenced memory.\n ///\n /// - Precondition: the pointee has been initialized with an instance of type\n /// `Pointee`.\n @inlinable\n public var pointee: Pointee {\n @_transparent get {\n // The memory addressed by this pointer contains a non-owning reference,\n // therefore we *must not* point an `UnsafePointer<AnyObject>` to\n // it---otherwise we would allow the compiler to assume it has a +1\n // refcount, enabling some optimizations that wouldn't be valid.\n //\n // Instead, we need to load the pointee as a +0 unmanaged reference. For\n // an extra twist, `Pointee` is allowed (but not required) to be an\n // optional type, so we actually need to load it as an optional, and\n // explicitly handle the nil case.\n let unmanaged =\n unsafe UnsafePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee\n return unsafe _unsafeReferenceCast(\n unmanaged?.takeUnretainedValue(),\n to: Pointee.self)\n }\n\n @_transparent nonmutating set {\n // Autorelease the object reference.\n let object = unsafe _unsafeReferenceCast(newValue, to: Optional<AnyObject>.self)\n Builtin.retain(object)\n Builtin.autorelease(object)\n\n // Convert it to an unmanaged reference and trivially assign it to the\n // memory addressed by this pointer.\n let unmanaged: Optional<Unmanaged<AnyObject>>\n if let object = object {\n unsafe unmanaged = unsafe Unmanaged.passUnretained(object)\n } else {\n unsafe unmanaged = nil\n }\n unsafe UnsafeMutablePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee =\n unmanaged\n }\n }\n\n /// Access the `i`th element of the raw array pointed to by\n /// `self`.\n ///\n /// - Precondition: `self != nil`.\n @inlinable // unsafe-performance\n public subscript(i: Int) -> Pointee {\n @_transparent\n get {\n return unsafe self.advanced(by: i).pointee\n }\n }\n\n /// Explicit construction from an UnsafeMutablePointer.\n ///\n /// This is inherently unsafe; UnsafeMutablePointer assumes the\n /// referenced memory has +1 strong ownership semantics, whereas\n /// AutoreleasingUnsafeMutablePointer implies +0 semantics.\n ///\n /// - Warning: Accessing `pointee` as a type that is unrelated to\n /// the underlying memory's bound type is undefined.\n @_transparent\n public init<U>(@_nonEphemeral _ from: UnsafeMutablePointer<U>) {\n unsafe self._rawValue = from._rawValue\n }\n\n /// Explicit construction from an UnsafeMutablePointer.\n ///\n /// Returns nil if `from` is nil.\n ///\n /// This is inherently unsafe; UnsafeMutablePointer assumes the\n /// referenced memory has +1 strong ownership semantics, whereas\n /// AutoreleasingUnsafeMutablePointer implies +0 semantics.\n ///\n /// - Warning: Accessing `pointee` as a type that is unrelated to\n /// the underlying memory's bound type is undefined.\n @_transparent\n public init?<U>(@_nonEphemeral _ from: UnsafeMutablePointer<U>?) {\n guard let unwrapped = unsafe from else { return nil }\n unsafe self.init(unwrapped)\n }\n \n /// Explicit construction from a UnsafePointer.\n ///\n /// This is inherently unsafe because UnsafePointers do not imply\n /// mutability.\n ///\n /// - Warning: Accessing `pointee` as a type that is unrelated to\n /// the underlying memory's bound type is undefined.\n @usableFromInline @_transparent\n internal init<U>(\n @_nonEphemeral _ from: UnsafePointer<U>\n ) {\n unsafe self._rawValue = from._rawValue\n }\n\n /// Explicit construction from a UnsafePointer.\n ///\n /// Returns nil if `from` is nil.\n ///\n /// This is inherently unsafe because UnsafePointers do not imply\n /// mutability.\n ///\n /// - Warning: Accessing `pointee` as a type that is unrelated to\n /// the underlying memory's bound type is undefined.\n @usableFromInline @_transparent\n internal init?<U>(\n @_nonEphemeral _ from: UnsafePointer<U>?\n ) {\n guard let unwrapped = unsafe from else { return nil }\n unsafe self.init(unwrapped)\n }\n}\n\nextension UnsafeMutableRawPointer {\n /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`\n /// instance.\n ///\n /// - Parameter other: The pointer to convert.\n @_transparent\n public init<T>(\n @_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>\n ) {\n _rawValue = unsafe other._rawValue\n }\n\n /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`\n /// instance.\n ///\n /// - Parameter other: The pointer to convert. If `other` is `nil`, the\n /// result is `nil`.\n @_transparent\n public init?<T>(\n @_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>?\n ) {\n guard let unwrapped = unsafe other else { return nil }\n unsafe self.init(unwrapped)\n }\n}\n\nextension UnsafeRawPointer {\n /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`\n /// instance.\n ///\n /// - Parameter other: The pointer to convert.\n @_transparent\n public init<T>(\n @_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>\n ) {\n _rawValue = unsafe other._rawValue\n }\n\n /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`\n /// instance.\n ///\n /// - Parameter other: The pointer to convert. If `other` is `nil`, the\n /// result is `nil`.\n @_transparent\n public init?<T>(\n @_nonEphemeral _ other: AutoreleasingUnsafeMutablePointer<T>?\n ) {\n guard let unwrapped = unsafe other else { return nil }\n unsafe self.init(unwrapped)\n }\n}\n\n@available(*, unavailable)\nextension AutoreleasingUnsafeMutablePointer: Sendable { }\n\n@unsafe\ninternal struct _CocoaFastEnumerationStackBuf {\n // Clang uses 16 pointers. So do we.\n internal var _item0: UnsafeRawPointer?\n internal var _item1: UnsafeRawPointer?\n internal var _item2: UnsafeRawPointer?\n internal var _item3: UnsafeRawPointer?\n internal var _item4: UnsafeRawPointer?\n internal var _item5: UnsafeRawPointer?\n internal var _item6: UnsafeRawPointer?\n internal var _item7: UnsafeRawPointer?\n internal var _item8: UnsafeRawPointer?\n internal var _item9: UnsafeRawPointer?\n internal var _item10: UnsafeRawPointer?\n internal var _item11: UnsafeRawPointer?\n internal var _item12: UnsafeRawPointer?\n internal var _item13: UnsafeRawPointer?\n internal var _item14: UnsafeRawPointer?\n internal var _item15: UnsafeRawPointer?\n\n @_transparent\n internal var count: Int {\n return 16\n }\n\n internal init() {\n unsafe _item0 = nil\n unsafe _item1 = unsafe _item0\n unsafe _item2 = unsafe _item0\n unsafe _item3 = unsafe _item0\n unsafe _item4 = unsafe _item0\n unsafe _item5 = unsafe _item0\n unsafe _item6 = unsafe _item0\n unsafe _item7 = unsafe _item0\n unsafe _item8 = unsafe _item0\n unsafe _item9 = unsafe _item0\n unsafe _item10 = unsafe _item0\n unsafe _item11 = unsafe _item0\n unsafe _item12 = unsafe _item0\n unsafe _item13 = unsafe _item0\n unsafe _item14 = unsafe _item0\n unsafe _item15 = unsafe _item0\n\n unsafe _internalInvariant(MemoryLayout.size(ofValue: self) >=\n MemoryLayout<Optional<UnsafeRawPointer>>.size * count)\n }\n}\n\n/// Get the ObjC type encoding for a type as a pointer to a C string.\n///\n/// This is used by the Foundation overlays. The compiler will error if the\n/// passed-in type is generic or not representable in Objective-C\n@_transparent\npublic func _getObjCTypeEncoding<T>(_ type: T.Type) -> UnsafePointer<Int8> {\n // This must be `@_transparent` because `Builtin.getObjCTypeEncoding` is\n // only supported by the compiler for concrete types that are representable\n // in ObjC.\n return unsafe UnsafePointer(Builtin.getObjCTypeEncoding(type))\n}\n\n#endif\n\n//===--- Bridging without the ObjC runtime --------------------------------===//\n\n#if !_runtime(_ObjC)\n\n/// Convert `x` from its Objective-C representation to its Swift\n/// representation.\n// COMPILER_INTRINSIC\n@inlinable\npublic func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> (\n _ x: T._ObjectiveCType,\n _: T.Type\n) -> T {\n var result: T?\n T._forceBridgeFromObjectiveC(x, result: &result)\n return result!\n}\n\n/// Attempt to convert `x` from its Objective-C representation to its Swift\n/// representation.\n// COMPILER_INTRINSIC\n@inlinable\npublic func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(\n _ x: T._ObjectiveCType,\n _: T.Type\n) -> T? {\n var result: T?\n T._conditionallyBridgeFromObjectiveC (x, result: &result)\n return result\n}\n\npublic // SPI(Foundation)\nprotocol _NSSwiftValue: AnyObject {\n init(_ value: Any)\n var value: Any { get }\n static var null: AnyObject { get }\n}\n\n@usableFromInline\ninternal class __SwiftValue {\n @usableFromInline\n let value: Any\n \n @usableFromInline\n init(_ value: Any) {\n self.value = value\n }\n \n @usableFromInline\n static let null = __SwiftValue(Optional<Any>.none as Any)\n}\n\n// Internal stdlib SPI\n@_silgen_name("swift_unboxFromSwiftValueWithType")\npublic func swift_unboxFromSwiftValueWithType<T>(\n _ source: inout AnyObject,\n _ result: UnsafeMutablePointer<T>\n ) -> Bool {\n\n if source === _nullPlaceholder {\n if let unpacked = Optional<Any>.none as? T {\n result.initialize(to: unpacked)\n return true\n }\n }\n \n if let box = source as? __SwiftValue {\n if let value = box.value as? T {\n result.initialize(to: value)\n return true\n }\n } else if let box = source as? _NSSwiftValue {\n if let value = box.value as? T {\n result.initialize(to: value)\n return true\n }\n }\n \n return false\n}\n\n// Internal stdlib SPI\n@_silgen_name("swift_swiftValueConformsTo")\npublic func _swiftValueConformsTo<T>(_ type: T.Type) -> Bool {\n if let foundationType = _foundationSwiftValueType {\n return foundationType is T.Type\n } else {\n return __SwiftValue.self is T.Type\n }\n}\n\n@_silgen_name("_swift_extractDynamicValue")\npublic func _extractDynamicValue<T>(_ value: T) -> AnyObject?\n\n@_silgen_name("_swift_bridgeToObjectiveCUsingProtocolIfPossible")\npublic func _bridgeToObjectiveCUsingProtocolIfPossible<T>(_ value: T) -> AnyObject?\n\ninternal protocol _Unwrappable {\n func _unwrap() -> Any?\n}\n\nextension Optional: _Unwrappable {\n internal func _unwrap() -> Any? {\n return self\n }\n}\n\nprivate let _foundationSwiftValueType = _typeByName("Foundation.__SwiftValue") as? _NSSwiftValue.Type\n\n@usableFromInline\ninternal var _nullPlaceholder: AnyObject {\n if let foundationType = _foundationSwiftValueType {\n return foundationType.null\n } else {\n return __SwiftValue.null\n }\n}\n\n@usableFromInline\nfunc _makeSwiftValue(_ value: Any) -> AnyObject {\n if let foundationType = _foundationSwiftValueType {\n return foundationType.init(value)\n } else {\n return __SwiftValue(value)\n }\n}\n\n/// Bridge an arbitrary value to an Objective-C object.\n///\n/// - If `T` is a class type, it is always bridged verbatim, the function\n/// returns `x`;\n///\n/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`,\n/// returns the result of `x._bridgeToObjectiveC()`;\n///\n/// - otherwise, we use **boxing** to bring the value into Objective-C.\n/// The value is wrapped in an instance of a private Objective-C class\n/// that is `id`-compatible and dynamically castable back to the type of\n/// the boxed value, but is otherwise opaque.\n///\n// COMPILER_INTRINSIC\npublic func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject {\n var done = false\n var result: AnyObject!\n \n let source: Any = x\n \n if let dynamicSource = _extractDynamicValue(x) {\n result = dynamicSource as AnyObject\n done = true \n }\n \n if !done, let wrapper = source as? _Unwrappable {\n if let value = wrapper._unwrap() {\n result = value as AnyObject\n } else {\n result = _nullPlaceholder\n }\n \n done = true\n }\n\n if !done {\n if type(of: source) as? AnyClass != nil {\n result = unsafeBitCast(x, to: AnyObject.self)\n } else if let object = _bridgeToObjectiveCUsingProtocolIfPossible(source) {\n result = object\n } else {\n result = _makeSwiftValue(source)\n }\n }\n \n return result\n}\n\n#endif // !_runtime(_ObjC)\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_BridgeObjectiveC.swift | cpp_apple_swift_stdlib_public_core_BridgeObjectiveC.swift | Swift | 27,623 | 0.95 | 0.094838 | 0.392713 | python-kit | 38 | 2023-11-15T09:44:31.317407 | GPL-3.0 | false | ef413bf96d367cc1db0a36b44aa915a0 |
//===--- BridgeStorage.swift - Discriminated storage for bridged types ----===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Types that are bridged to Objective-C need to manage an object\n// that may be either some native class or the @objc Cocoa\n// equivalent. _BridgeStorage discriminates between these two\n// possibilities and stores a single extra bit when the stored type is\n// native. It is assumed that the @objc class instance may in fact\n// be a tagged pointer, and thus no extra bits may be available.\n//\n//===----------------------------------------------------------------------===//\nimport SwiftShims\n\n#if !$Embedded\n\n@frozen\n@usableFromInline\ninternal struct _BridgeStorage<NativeClass: AnyObject> {\n @usableFromInline\n internal typealias Native = NativeClass\n\n @usableFromInline\n internal typealias ObjC = AnyObject\n\n // rawValue is passed inout to _isUnique. Although its value\n // is unchanged, it must appear mutable to the optimizer.\n @usableFromInline\n internal var rawValue: Builtin.BridgeObject\n\n @inlinable\n @inline(__always)\n internal init(native: Native, isFlagged flag: Bool) {\n // Note: Some platforms provide more than one spare bit, but the minimum is\n // a single bit.\n\n _internalInvariant(_usesNativeSwiftReferenceCounting(NativeClass.self))\n\n rawValue = _makeNativeBridgeObject(\n native,\n flag ? (1 as UInt) << _objectPointerLowSpareBitShift : 0)\n }\n\n @inlinable\n @inline(__always)\n internal init(objC: ObjC) {\n _internalInvariant(_usesNativeSwiftReferenceCounting(NativeClass.self))\n rawValue = _makeObjCBridgeObject(objC)\n }\n\n @inlinable\n @inline(__always)\n internal init(native: Native) {\n _internalInvariant(_usesNativeSwiftReferenceCounting(NativeClass.self))\n rawValue = Builtin.reinterpretCast(native)\n }\n\n#if _pointerBitWidth(_64)\n @inlinable\n @inline(__always)\n internal init(taggedPayload: UInt) {\n rawValue = _bridgeObject(taggingPayload: taggedPayload)\n }\n#endif\n\n @inlinable\n @inline(__always)\n internal mutating func isUniquelyReferencedNative() -> Bool {\n return isNative && _isUnique(&rawValue)\n }\n\n @_alwaysEmitIntoClient\n @inline(__always)\n internal mutating func beginCOWMutationNative() -> Bool {\n return Bool(Builtin.beginCOWMutation(&rawValue))\n }\n\n @inlinable\n internal var isNative: Bool {\n @inline(__always) get {\n let result = Builtin.classifyBridgeObject(rawValue)\n return !Bool(Builtin.or_Int1(result.isObjCObject,\n result.isObjCTaggedPointer))\n }\n }\n\n @inlinable\n static var flagMask: UInt {\n @inline(__always) get {\n return (1 as UInt) << _objectPointerLowSpareBitShift\n }\n }\n\n @inlinable\n internal var isUnflaggedNative: Bool {\n @inline(__always) get {\n return (_bitPattern(rawValue) &\n (_bridgeObjectTaggedPointerBits | _objCTaggedPointerBits |\n _objectPointerIsObjCBit | _BridgeStorage.flagMask)) == 0\n }\n }\n\n @inlinable\n internal var isObjC: Bool {\n @inline(__always) get {\n return !isNative\n }\n }\n\n @inlinable\n internal var nativeInstance: Native {\n @inline(__always) get {\n _internalInvariant(isNative)\n return Builtin.castReferenceFromBridgeObject(rawValue)\n }\n }\n\n @inlinable\n internal var unflaggedNativeInstance: Native {\n @inline(__always) get {\n _internalInvariant(isNative)\n _internalInvariant(_nonPointerBits(rawValue) == 0)\n return Builtin.reinterpretCast(rawValue)\n }\n }\n\n @inlinable\n @inline(__always)\n internal mutating func isUniquelyReferencedUnflaggedNative() -> Bool {\n _internalInvariant(isNative)\n return _isUnique_native(&rawValue)\n }\n\n @_alwaysEmitIntoClient\n @inline(__always)\n internal mutating func beginCOWMutationUnflaggedNative() -> Bool {\n _internalInvariant(isNative)\n return Bool(Builtin.beginCOWMutation_native(&rawValue))\n }\n\n @_alwaysEmitIntoClient\n @inline(__always)\n internal mutating func endCOWMutation() {\n _internalInvariant(isNative)\n Builtin.endCOWMutation(&rawValue)\n }\n\n @inlinable\n internal var objCInstance: ObjC {\n @inline(__always) get {\n _internalInvariant(isObjC)\n return Builtin.castReferenceFromBridgeObject(rawValue)\n }\n }\n}\n\n#else\n\n@frozen\n@usableFromInline\ninternal struct _BridgeStorage<NativeClass: AnyObject> {\n @usableFromInline\n internal typealias Native = NativeClass\n\n // rawValue is passed inout to _isUnique. Although its value\n // is unchanged, it must appear mutable to the optimizer.\n @usableFromInline\n internal var rawValue: NativeClass\n\n @inlinable\n @inline(__always)\n internal init(native: Native) {\n #if !$Embedded\n _internalInvariant(_usesNativeSwiftReferenceCounting(NativeClass.self))\n #endif\n rawValue = native\n }\n\n @inlinable\n @inline(__always)\n internal mutating func isUniquelyReferencedNative() -> Bool {\n return _isUnique(&rawValue)\n }\n\n @_alwaysEmitIntoClient\n @inline(__always)\n internal mutating func beginCOWMutationNative() -> Bool {\n return Bool(Builtin.beginCOWMutation(&rawValue))\n }\n\n @inlinable\n static var flagMask: UInt {\n @inline(__always) get {\n return (1 as UInt) << _objectPointerLowSpareBitShift\n }\n }\n\n @inlinable\n internal var nativeInstance: Native {\n @inline(__always) get {\n return rawValue\n }\n }\n\n @inlinable\n internal var unflaggedNativeInstance: Native {\n @inline(__always) get {\n return rawValue\n }\n }\n\n @inlinable\n @inline(__always)\n internal mutating func isUniquelyReferencedUnflaggedNative() -> Bool {\n return _isUnique_native(&rawValue)\n }\n\n @_alwaysEmitIntoClient\n @inline(__always)\n internal mutating func beginCOWMutationUnflaggedNative() -> Bool {\n return Bool(Builtin.beginCOWMutation_native(&rawValue))\n }\n\n @_alwaysEmitIntoClient\n @inline(__always)\n internal mutating func endCOWMutation() {\n Builtin.endCOWMutation(&rawValue)\n }\n}\n\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_BridgeStorage.swift | cpp_apple_swift_stdlib_public_core_BridgeStorage.swift | Swift | 6,312 | 0.95 | 0.033473 | 0.161765 | vue-tools | 271 | 2025-05-20T12:27:59.156626 | GPL-3.0 | false | 190be5b1dd2a84547a49a4321ab81d26 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct _BridgingBufferHeader {\n internal var count: Int\n\n internal init(_ count: Int) { self.count = count }\n}\n\n// NOTE: older runtimes called this class _BridgingBufferStorage.\n// The two must coexist without a conflicting ObjC class name, so it\n// was renamed. The old name must not be used in the new runtime.\ninternal final class __BridgingBufferStorage\n : ManagedBuffer<_BridgingBufferHeader, AnyObject> {\n}\n\ninternal typealias _BridgingBuffer\n = ManagedBufferPointer<_BridgingBufferHeader, AnyObject>\n\n@available(OpenBSD, unavailable, message: "malloc_size is unavailable.")\nextension ManagedBufferPointer\nwhere Header == _BridgingBufferHeader, Element == AnyObject {\n internal init(_ count: Int) {\n self.init(\n _uncheckedBufferClass: __BridgingBufferStorage.self,\n minimumCapacity: count)\n unsafe self.withUnsafeMutablePointerToHeader {\n unsafe $0.initialize(to: Header(count))\n }\n }\n\n internal var count: Int {\n @inline(__always)\n get {\n return header.count\n }\n @inline(__always)\n set {\n return header.count = newValue\n }\n }\n\n internal subscript(i: Int) -> Element {\n @inline(__always)\n get {\n return unsafe withUnsafeMutablePointerToElements { unsafe $0[i] }\n }\n }\n\n internal var baseAddress: UnsafeMutablePointer<Element> {\n @inline(__always)\n get {\n return unsafe withUnsafeMutablePointerToElements { unsafe $0 }\n }\n }\n\n internal var storage: AnyObject? {\n @inline(__always)\n get {\n return buffer\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_BridgingBuffer.swift | cpp_apple_swift_stdlib_public_core_BridgingBuffer.swift | Swift | 2,053 | 0.95 | 0.069444 | 0.222222 | vue-tools | 170 | 2025-05-27T22:00:24.257067 | Apache-2.0 | false | 5bea3355e9b8944db1c26bf724b6ba9b |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n// Definitions that make elements of Builtin usable in real code\n// without gobs of boilerplate.\n\n// This function is the implementation of the `_roundUp` overload set. It is\n// marked `@inline(__always)` to make primary `_roundUp` entry points seem\n// cheap enough for the inliner.\n@inlinable\n@inline(__always)\ninternal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt {\n _internalInvariant(alignment > 0)\n _internalInvariant(_isPowerOf2(alignment))\n // Note, given that offset is >= 0, and alignment > 0, we don't\n // need to underflow check the -1, as it can never underflow.\n let x = offset + UInt(bitPattern: alignment) &- 1\n // Note, as alignment is a power of 2, we'll use masking to efficiently\n // get the aligned value\n return x & ~(UInt(bitPattern: alignment) &- 1)\n}\n\n@inlinable\ninternal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt {\n return _roundUpImpl(offset, toAlignment: alignment)\n}\n\n@inlinable\ninternal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int {\n _internalInvariant(offset >= 0)\n let offset = UInt(bitPattern: offset)\n let result = Int(bitPattern: _roundUpImpl(offset, toAlignment: alignment))\n _internalInvariant(result >= 0)\n return result\n}\n\n/// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe.\n@_transparent\npublic // @testable\nfunc _canBeClass<T>(_: T.Type) -> Int8 {\n return Int8(Builtin.canBeClass(T.self))\n}\n\n/// Returns the bits of the given instance, interpreted as having the specified\n/// type.\n///\n/// Use this function only to convert the instance passed as `x` to a\n/// layout-compatible type when conversion through other means is not\n/// possible. Common conversions supported by the Swift standard library\n/// include the following:\n///\n/// - Value conversion from one integer type to another. Use the destination\n/// type's initializer or the `numericCast(_:)` function.\n/// - Bitwise conversion from one integer type to another. Use the destination\n/// type's `init(truncatingIfNeeded:)` or `init(bitPattern:)` initializer.\n/// - Conversion from a pointer to an integer value with the bit pattern of the\n/// pointer's address in memory, or vice versa. Use the `init(bitPattern:)`\n/// initializer for the destination type.\n/// - Casting an instance of a reference type. Use the casting operators (`as`,\n/// `as!`, or `as?`) or the `unsafeDowncast(_:to:)` function. Do not use\n/// `unsafeBitCast(_:to:)` with class or pointer types; doing so may\n/// introduce undefined behavior.\n///\n/// Warning: Calling this function breaks the guarantees of the Swift type\n/// system; use with extreme care.\n///\n/// Warning: Casting from an integer or a pointer type to a reference type\n/// is undefined behavior. It may result in incorrect code in any future\n/// compiler release. To convert a bit pattern to a reference type:\n/// 1. convert the bit pattern to an UnsafeRawPointer.\n/// 2. create an unmanaged reference using Unmanaged.fromOpaque()\n/// 3. obtain a managed reference using Unmanaged.takeUnretainedValue()\n/// The programmer must ensure that the resulting reference has already been\n/// manually retained.\n///\n/// Parameters:\n/// - x: The instance to cast to `type`.\n/// - type: The type to cast `x` to. `type` and the type of `x` must have the\n/// same size of memory representation and compatible memory layout.\n/// Returns: A new instance of type `U`, cast from `x`.\n@inlinable // unsafe-performance\n@_transparent\n@unsafe\npublic func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {\n _precondition(MemoryLayout<T>.size == MemoryLayout<U>.size,\n "Can't unsafeBitCast between types of different sizes")\n return Builtin.reinterpretCast(x)\n}\n\n/// Returns `x` as its concrete type `U`.\n///\n/// This cast can be useful for dispatching to specializations of generic\n/// functions.\n///\n/// - Requires: `x` has type `U`.\n@_transparent\npublic func _identityCast<T, U>(_ x: T, to expectedType: U.Type) -> U {\n _precondition(T.self == expectedType, "_identityCast to wrong type")\n return Builtin.reinterpretCast(x)\n}\n\n/// Returns `x` as its concrete type `U`, or `nil` if `x` has a different\n/// concrete type.\n///\n/// This cast can be useful for dispatching to specializations of generic\n/// functions.\n@_alwaysEmitIntoClient\n@_transparent\npublic func _specialize<T, U>(_ x: T, for: U.Type) -> U? {\n guard T.self == U.self else {\n return nil\n }\n\n let result: U = Builtin.reinterpretCast(x)\n return result\n}\n\n/// `unsafeBitCast` something to `AnyObject`.\n@usableFromInline @_transparent\ninternal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject {\n return unsafe unsafeBitCast(x, to: AnyObject.self)\n}\n\n@usableFromInline @_transparent\ninternal func == (\n lhs: Builtin.NativeObject, rhs: Builtin.NativeObject\n) -> Bool {\n return unsafe unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)\n}\n\n@usableFromInline @_transparent\ninternal func != (\n lhs: Builtin.NativeObject, rhs: Builtin.NativeObject\n) -> Bool {\n return !(lhs == rhs)\n}\n\n@usableFromInline @_transparent\ninternal func == (\n lhs: Builtin.RawPointer, rhs: Builtin.RawPointer\n) -> Bool {\n return unsafe unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)\n}\n\n@usableFromInline @_transparent\ninternal func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {\n return !(lhs == rhs)\n}\n\n/// Returns a Boolean value indicating whether two types are identical.\n///\n/// - Parameters:\n/// - t0: A type to compare.\n/// - t1: Another type to compare.\n/// - Returns: `true` if both `t0` and `t1` are `nil` or if they represent the\n/// same type; otherwise, `false`.\n@_alwaysEmitIntoClient\n@_transparent\npublic func == (\n t0: (any (~Copyable & ~Escapable).Type)?,\n t1: (any (~Copyable & ~Escapable).Type)?\n) -> Bool {\n switch (t0, t1) {\n case (.none, .none):\n return true\n case let (.some(ty0), .some(ty1)):\n return Bool(Builtin.is_same_metatype(ty0, ty1))\n default:\n return false\n }\n}\n\n/// Returns a Boolean value indicating whether two types are not identical.\n///\n/// - Parameters:\n/// - t0: A type to compare.\n/// - t1: Another type to compare.\n/// - Returns: `true` if one, but not both, of `t0` and `t1` are `nil`, or if\n/// they represent different types; otherwise, `false`.\n@_alwaysEmitIntoClient\n@_transparent\npublic func != (\n t0: (any (~Copyable & ~Escapable).Type)?,\n t1: (any (~Copyable & ~Escapable).Type)?\n) -> Bool {\n !(t0 == t1)\n}\n\n#if !$Embedded\n// Embedded Swift is unhappy about conversions from `Any.Type` to\n// `any (~Copyable & ~Escapable).Type` (rdar://145706221)\n@usableFromInline\n@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\ninternal func == (t0: Any.Type?, t1: Any.Type?) -> Bool {\n switch (t0, t1) {\n case (.none, .none): return true\n case let (.some(ty0), .some(ty1)):\n return Bool(Builtin.is_same_metatype(ty0, ty1))\n default: return false\n }\n}\n\n@usableFromInline\n@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\ninternal func != (t0: Any.Type?, t1: Any.Type?) -> Bool {\n !(t0 == t1)\n}\n#endif\n\n/// Tell the optimizer that this code is unreachable if condition is\n/// known at compile-time to be true. If condition is false, or true\n/// but not a compile-time constant, this call has no effect.\n@usableFromInline @_transparent\ninternal func _unreachable(_ condition: Bool = true) {\n if condition {\n // FIXME: use a parameterized version of Builtin.unreachable when\n // <rdar://problem/16806232> is closed.\n Builtin.unreachable()\n }\n}\n\n/// Tell the optimizer that this code is unreachable if this builtin is\n/// reachable after constant folding build configuration builtins.\n@usableFromInline @_transparent\ninternal func _conditionallyUnreachable() -> Never {\n Builtin.conditionallyUnreachable()\n}\n\n@usableFromInline\n@_silgen_name("_swift_isClassOrObjCExistentialType")\ninternal func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool\n\n@available(SwiftStdlib 5.7, *)\n@usableFromInline\n@_silgen_name("_swift_setClassMetadata")\ninternal func _swift_setClassMetadata<T>(_ x: T.Type,\n onObject: AnyObject) -> Bool\n\n/// Returns `true` if `T` is a class type or an `@objc` existential such as\n/// `AnyObject`; otherwise, returns `false`.\n@inlinable\n@inline(__always)\ninternal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool {\n\n switch _canBeClass(x) {\n // Is not a class.\n case 0:\n return false\n // Is a class.\n case 1:\n return true\n // Maybe a class.\n default:\n return _swift_isClassOrObjCExistentialType(x)\n }\n}\n\n/// Converts a reference of type `T` to a reference of type `U` after\n/// unwrapping one level of Optional.\n///\n/// Unwrapped `T` and `U` must be convertible to AnyObject. They may\n/// be either a class or a class protocol. Either T, U, or both may be\n/// optional references.\n@_transparent\n@unsafe\npublic func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U {\n return Builtin.castReference(x)\n}\n\n/// Returns the given instance cast unconditionally to the specified type.\n///\n/// The instance passed as `x` must be an instance of type `T`.\n///\n/// Use this function instead of `unsafeBitcast(_:to:)` because this function\n/// is more restrictive and still performs a check in debug builds. In -O\n/// builds, no test is performed to ensure that `x` actually has the dynamic\n/// type `T`.\n///\n/// - Warning: This function trades safety for performance. Use\n/// `unsafeDowncast(_:to:)` only when you are confident that `x is T` always\n/// evaluates to `true`, and only after `x as! T` has proven to be a\n/// performance problem.\n///\n/// - Parameters:\n/// - x: An instance to cast to type `T`.\n/// - type: The type `T` to which `x` is cast.\n/// - Returns: The instance `x`, cast to type `T`.\n@_transparent\n@unsafe\npublic func unsafeDowncast<T: AnyObject>(_ x: AnyObject, to type: T.Type) -> T {\n _debugPrecondition(x is T, "invalid unsafeDowncast")\n return Builtin.castReference(x)\n}\n\n@_transparent\n@unsafe\npublic func _unsafeUncheckedDowncast<T: AnyObject>(_ x: AnyObject, to type: T.Type) -> T {\n _internalInvariant(x is T, "invalid unsafeDowncast")\n return Builtin.castReference(x)\n}\n\n@inlinable\n@inline(__always)\npublic func _getUnsafePointerToStoredProperties(_ x: AnyObject)\n -> UnsafeMutableRawPointer {\n let storedPropertyOffset = unsafe _roundUp(\n MemoryLayout<SwiftShims.HeapObject>.size,\n toAlignment: MemoryLayout<Optional<AnyObject>>.alignment)\n return unsafe UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) +\n storedPropertyOffset\n}\n\n/// Get the minimum alignment for manually allocated memory.\n///\n/// Memory allocated via UnsafeMutable[Raw][Buffer]Pointer must never pass\n/// an alignment less than this value to Builtin.allocRaw. This\n/// ensures that the memory can be deallocated without specifying the\n/// alignment.\n@inlinable\n@inline(__always)\ninternal func _minAllocationAlignment() -> Int {\n return _swift_MinAllocationAlignment\n}\n\n//===----------------------------------------------------------------------===//\n// Branch hints\n//===----------------------------------------------------------------------===//\n\n// Use @_semantics to indicate that the optimizer recognizes the\n// semantics of these function calls. This won't be necessary with\n// mandatory generic inlining.\n\n/// Optimizer hint that `x` is expected to be `true`.\n@_transparent\n@_semantics("fastpath")\npublic func _fastPath(_ x: Bool) -> Bool {\n return Bool(Builtin.int_expect_Int1(x._value, true._value))\n}\n\n/// Optimizer hint that `x` is expected to be `false`.\n@_transparent\n@_semantics("slowpath")\npublic func _slowPath(_ x: Bool) -> Bool {\n return Bool(Builtin.int_expect_Int1(x._value, false._value))\n}\n\n/// Optimizer hint that the code where this function is called is on the fast\n/// path.\n@_transparent\npublic func _onFastPath() {\n Builtin.onFastPath()\n}\n\n// Optimizer hint that the condition is true. The condition is unchecked.\n// The builtin acts as an opaque instruction with side-effects.\n@usableFromInline @_transparent\n@unsafe\nfunc _uncheckedUnsafeAssume(_ condition: Bool) {\n _ = Builtin.assume_Int1(condition._value)\n}\n\n//===--- Runtime shim wrappers --------------------------------------------===//\n\n/// Returns `true` if the class indicated by `theClass` uses native\n/// Swift reference-counting; otherwise, returns `false`.\n#if _runtime(_ObjC)\n// Declare it here instead of RuntimeShims.h, because we need to specify\n// the type of argument to be AnyClass. This is currently not possible\n// when using RuntimeShims.h\n@usableFromInline\n@_silgen_name("_swift_objcClassUsesNativeSwiftReferenceCounting")\ninternal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool\n\n/// Returns the class of a non-tagged-pointer Objective-C object\n@_effects(readonly)\n@_silgen_name("_swift_classOfObjCHeapObject")\ninternal func _swift_classOfObjCHeapObject(_ object: AnyObject) -> AnyClass\n#else\n@inlinable\n@inline(__always)\ninternal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool {\n return true\n}\n#endif\n\n@usableFromInline\n@_silgen_name("_swift_getSwiftClassInstanceExtents")\ninternal func getSwiftClassInstanceExtents(_ theClass: AnyClass)\n -> (negative: UInt, positive: UInt)\n\n@usableFromInline\n@_silgen_name("_swift_getObjCClassInstanceExtents")\ninternal func getObjCClassInstanceExtents(_ theClass: AnyClass)\n -> (negative: UInt, positive: UInt)\n\n@inlinable\n@inline(__always)\ninternal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int {\n#if _runtime(_ObjC)\n return Int(getObjCClassInstanceExtents(theClass).positive)\n#else\n return Int(getSwiftClassInstanceExtents(theClass).positive)\n#endif\n}\n\n#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED\n@usableFromInline\n@_silgen_name("_swift_isImmutableCOWBuffer")\ninternal func _swift_isImmutableCOWBuffer(_ object: AnyObject) -> Bool\n\n@usableFromInline\n@_silgen_name("_swift_setImmutableCOWBuffer")\ninternal func _swift_setImmutableCOWBuffer(_ object: AnyObject, _ immutable: Bool) -> Bool\n#endif\n\n@inlinable\ninternal func _isValidAddress(_ address: UInt) -> Bool {\n // TODO: define (and use) ABI max valid pointer value\n return address >= _swift_abi_LeastValidPointerValue\n}\n\n//===--- Builtin.BridgeObject ---------------------------------------------===//\n\n// TODO(<rdar://problem/34837023>): Get rid of superfluous UInt constructor\n// calls\n@inlinable\ninternal var _bridgeObjectTaggedPointerBits: UInt {\n @inline(__always) get { return UInt(_swift_BridgeObject_TaggedPointerBits) }\n}\n@inlinable\ninternal var _objCTaggedPointerBits: UInt {\n @inline(__always) get { return UInt(_swift_abi_ObjCReservedBitsMask) }\n}\n@inlinable\ninternal var _objectPointerSpareBits: UInt {\n @inline(__always) get {\n return UInt(_swift_abi_SwiftSpareBitsMask) & ~_bridgeObjectTaggedPointerBits\n }\n}\n@inlinable\ninternal var _objectPointerLowSpareBitShift: UInt {\n @inline(__always) get {\n _internalInvariant(_swift_abi_ObjCReservedLowBits < 2,\n "num bits now differs from num-shift-amount, new platform?")\n return UInt(_swift_abi_ObjCReservedLowBits)\n }\n}\n\n@inlinable\ninternal var _objectPointerIsObjCBit: UInt {\n @inline(__always) get {\n#if _pointerBitWidth(_64)\n return 0x4000_0000_0000_0000\n#elseif _pointerBitWidth(_32)\n return 0x0000_0002\n#elseif _pointerBitWidth(_16)\n return 0x0000\n#else\n#error("Unknown platform")\n#endif\n }\n}\n\n/// Extract the raw bits of `x`.\n@inlinable\n@inline(__always)\ninternal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt {\n return UInt(Builtin.castBitPatternFromBridgeObject(x))\n}\n\n/// Extract the raw spare bits of `x`.\n@inlinable\n@inline(__always)\ninternal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {\n return _bitPattern(x) & _objectPointerSpareBits\n}\n\n@inlinable\n@inline(__always)\ninternal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool {\n return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0\n}\n@inlinable\n@inline(__always)\ninternal func _isObjCTaggedPointer(_ x: UInt) -> Bool {\n return (x & _objCTaggedPointerBits) != 0\n}\n\n/// TODO: describe extras\n\n@inlinable @inline(__always) public // FIXME\nfunc _isTaggedObject(_ x: Builtin.BridgeObject) -> Bool {\n return _bitPattern(x) & _bridgeObjectTaggedPointerBits != 0\n}\n@inlinable @inline(__always) public // FIXME\nfunc _isNativePointer(_ x: Builtin.BridgeObject) -> Bool {\n return (\n _bitPattern(x) & (_bridgeObjectTaggedPointerBits | _objectPointerIsObjCBit)\n ) == 0\n}\n@inlinable @inline(__always) public // FIXME\nfunc _isNonTaggedObjCPointer(_ x: Builtin.BridgeObject) -> Bool {\n return !_isTaggedObject(x) && !_isNativePointer(x)\n}\n\n@inlinable\n@inline(__always)\nfunc _getNonTagBits(_ x: Builtin.BridgeObject) -> UInt {\n // Zero out the tag bits, and leave them all at the top.\n _internalInvariant(_isTaggedObject(x), "not tagged!")\n return (_bitPattern(x) & ~_bridgeObjectTaggedPointerBits)\n >> _objectPointerLowSpareBitShift\n}\n\n// Values -> BridgeObject\n@inline(__always)\n@inlinable\n@_unavailableInEmbedded\npublic func _bridgeObject(fromNative x: AnyObject) -> Builtin.BridgeObject {\n _internalInvariant(!_isObjCTaggedPointer(x))\n let object = Builtin.castToBridgeObject(x, 0._builtinWordValue)\n _internalInvariant(_isNativePointer(object))\n return object\n}\n\n@inline(__always)\n@inlinable\n@_unavailableInEmbedded\npublic func _bridgeObject(\n fromNonTaggedObjC x: AnyObject\n) -> Builtin.BridgeObject {\n _internalInvariant(!_isObjCTaggedPointer(x))\n let object = _makeObjCBridgeObject(x)\n _internalInvariant(_isNonTaggedObjCPointer(object))\n return object\n}\n\n@inline(__always)\n@inlinable\npublic func _bridgeObject(fromTagged x: UInt) -> Builtin.BridgeObject {\n _internalInvariant(x & _bridgeObjectTaggedPointerBits != 0)\n let object: Builtin.BridgeObject = Builtin.valueToBridgeObject(x._value)\n _internalInvariant(_isTaggedObject(object))\n return object\n}\n\n@inline(__always)\n@inlinable\npublic func _bridgeObject(taggingPayload x: UInt) -> Builtin.BridgeObject {\n let shifted = x &<< _objectPointerLowSpareBitShift\n _internalInvariant(x == (shifted &>> _objectPointerLowSpareBitShift),\n "out-of-range: limited bit range requires some zero top bits")\n _internalInvariant(shifted & _bridgeObjectTaggedPointerBits == 0,\n "out-of-range: post-shift use of tag bits")\n return _bridgeObject(fromTagged: shifted | _bridgeObjectTaggedPointerBits)\n}\n\n// BridgeObject -> Values\n@inline(__always)\n@inlinable\npublic func _bridgeObject(toNative x: Builtin.BridgeObject) -> AnyObject {\n _internalInvariant(_isNativePointer(x))\n return Builtin.castReferenceFromBridgeObject(x)\n}\n\n@inline(__always)\n@inlinable\npublic func _bridgeObject(\n toNonTaggedObjC x: Builtin.BridgeObject\n) -> AnyObject {\n _internalInvariant(_isNonTaggedObjCPointer(x))\n return Builtin.castReferenceFromBridgeObject(x)\n}\n\n@inline(__always)\n@inlinable\npublic func _bridgeObject(toTagged x: Builtin.BridgeObject) -> UInt {\n _internalInvariant(_isTaggedObject(x))\n let bits = _bitPattern(x)\n _internalInvariant(bits & _bridgeObjectTaggedPointerBits != 0)\n return bits\n}\n@inline(__always)\n@inlinable\npublic func _bridgeObject(toTagPayload x: Builtin.BridgeObject) -> UInt {\n return _getNonTagBits(x)\n}\n\n@inline(__always)\n@inlinable\n@_unavailableInEmbedded\npublic func _bridgeObject(\n fromNativeObject x: Builtin.NativeObject\n) -> Builtin.BridgeObject {\n return _bridgeObject(fromNative: _nativeObject(toNative: x))\n}\n\n//\n// NativeObject\n//\n\n@inlinable\n@inline(__always)\n@_unavailableInEmbedded\npublic func _nativeObject(fromNative x: AnyObject) -> Builtin.NativeObject {\n _internalInvariant(!_isObjCTaggedPointer(x))\n let native = Builtin.unsafeCastToNativeObject(x)\n // _internalInvariant(native == Builtin.castToNativeObject(x))\n return native\n}\n\n@inlinable\n@inline(__always)\n@_unavailableInEmbedded\npublic func _nativeObject(\n fromBridge x: Builtin.BridgeObject\n) -> Builtin.NativeObject {\n return _nativeObject(fromNative: _bridgeObject(toNative: x))\n}\n\n@inlinable\n@inline(__always)\npublic func _nativeObject(toNative x: Builtin.NativeObject) -> AnyObject {\n return Builtin.castFromNativeObject(x)\n}\n\n// FIXME\nextension ManagedBufferPointer {\n // FIXME: String Guts\n @inline(__always)\n @inlinable\n public init(_nativeObject buffer: Builtin.NativeObject) {\n self._nativeBuffer = buffer\n }\n}\n\n/// Create a `BridgeObject` around the given `nativeObject` with the\n/// given spare bits.\n///\n/// Reference-counting and other operations on this\n/// object will have access to the knowledge that it is native.\n///\n/// - Precondition: `bits & _objectPointerIsObjCBit == 0`,\n/// `bits & _objectPointerSpareBits == bits`.\n@inlinable\n@inline(__always)\n@_unavailableInEmbedded\ninternal func _makeNativeBridgeObject(\n _ nativeObject: AnyObject, _ bits: UInt\n) -> Builtin.BridgeObject {\n _internalInvariant(\n (bits & _objectPointerIsObjCBit) == 0,\n "BridgeObject is treated as non-native when ObjC bit is set"\n )\n return _makeBridgeObject(nativeObject, bits)\n}\n\n/// Create a `BridgeObject` around the given `objCObject`.\n@inlinable\n@inline(__always)\n@_unavailableInEmbedded\npublic // @testable\nfunc _makeObjCBridgeObject(\n _ objCObject: AnyObject\n) -> Builtin.BridgeObject {\n return _makeBridgeObject(\n objCObject,\n _isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit)\n}\n\n/// Create a `BridgeObject` around the given `object` with the\n/// given spare bits.\n///\n/// - Precondition:\n///\n/// 1. `bits & _objectPointerSpareBits == bits`\n/// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise,\n/// `object` is either a native object, or `bits ==\n/// _objectPointerIsObjCBit`.\n@inlinable\n@inline(__always)\n@_unavailableInEmbedded\ninternal func _makeBridgeObject(\n _ object: AnyObject, _ bits: UInt\n) -> Builtin.BridgeObject {\n _internalInvariant(!_isObjCTaggedPointer(object) || bits == 0,\n "Tagged pointers cannot be combined with bits")\n\n _internalInvariant(\n _isObjCTaggedPointer(object)\n || _usesNativeSwiftReferenceCounting(type(of: object))\n || bits == _objectPointerIsObjCBit,\n "All spare bits must be set in non-native, non-tagged bridge objects"\n )\n\n _internalInvariant(\n bits & _objectPointerSpareBits == bits,\n "Can't store non-spare bits into Builtin.BridgeObject")\n\n return Builtin.castToBridgeObject(\n object, bits._builtinWordValue\n )\n}\n\n@_silgen_name("_swift_class_getSuperclass")\ninternal func _swift_class_getSuperclass(_ t: AnyClass) -> AnyClass?\n\n/// Returns the superclass of `t`, if any. The result is `nil` if `t` is\n/// a root class or class protocol.\npublic func _getSuperclass(_ t: AnyClass) -> AnyClass? {\n return _swift_class_getSuperclass(t)\n}\n\n/// Returns the superclass of `t`, if any. The result is `nil` if `t` is\n/// not a class, is a root class, or is a class protocol.\n@inlinable\n@inline(__always)\npublic // @testable\nfunc _getSuperclass(_ t: Any.Type) -> AnyClass? {\n return (t as? AnyClass).flatMap { _getSuperclass($0) }\n}\n\n//===--- Builtin.IsUnique -------------------------------------------------===//\n// _isUnique functions must take an inout object because they rely on\n// Builtin.isUnique which requires an inout reference to preserve\n// source-level copies in the presence of ARC optimization.\n//\n// Taking an inout object makes sense for two additional reasons:\n//\n// 1. You should only call it when about to mutate the object.\n// Doing so otherwise implies a race condition if the buffer is\n// shared across threads.\n//\n// 2. When it is not an inout function, self is passed by\n// value... thus bumping the reference count and disturbing the\n// result we are trying to observe, Dr. Heisenberg!\n//\n// _isUnique cannot be made public or the compiler\n// will attempt to generate generic code for the transparent function\n// and type checking will fail.\n\n/// Returns `true` if `object` is uniquely referenced.\n@usableFromInline @_transparent\ninternal func _isUnique<T>(_ object: inout T) -> Bool {\n return Bool(Builtin.isUnique(&object))\n}\n\n/// Returns `true` if `object` is uniquely referenced.\n/// This provides soundness checks on top of the Builtin.\n@_transparent\npublic // @testable\nfunc _isUnique_native<T>(_ object: inout T) -> Bool {\n // This could be a bridge object, single payload enum, or plain old\n // reference. Any case it's non pointer bits must be zero, so\n // force cast it to BridgeObject and check the spare bits.\n #if !$Embedded\n _internalInvariant(\n (_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)\n == 0)\n _internalInvariant(_usesNativeSwiftReferenceCounting(\n type(of: Builtin.reinterpretCast(object) as AnyObject)))\n #endif\n return Bool(Builtin.isUnique_native(&object))\n}\n\n@_alwaysEmitIntoClient\n@_transparent\npublic // @testable\nfunc _COWBufferForReading<T: AnyObject>(_ object: T) -> T {\n return Builtin.COWBufferForReading(object)\n}\n\n/// Returns `true` if type is a POD type. A POD type is a type that does not\n/// require any special handling on copying or destruction.\n@_transparent\n@_preInverseGenerics\npublic // @testable\nfunc _isPOD<T: ~Copyable & ~Escapable>(_ type: T.Type) -> Bool {\n Bool(Builtin.ispod(type))\n}\n\n/// Returns `true` if `type` is known to refer to a concrete type once all\n/// optimizations and constant folding has occurred at the call site. Otherwise,\n/// this returns `false` if the check has failed.\n///\n/// Note that there may be cases in which, despite `T` being concrete at some\n/// point in the caller chain, this function will return `false`.\n@_alwaysEmitIntoClient\n@_transparent\npublic // @testable\nfunc _isConcrete<T>(_ type: T.Type) -> Bool {\n return Bool(Builtin.isConcrete(type))\n}\n\n/// Returns `true` if type is a bitwise takable. A bitwise takable type can\n/// just be moved to a different address in memory.\n@_transparent\npublic // @testable\nfunc _isBitwiseTakable<T>(_ type: T.Type) -> Bool {\n return Bool(Builtin.isbitwisetakable(type))\n}\n\n/// Returns `true` if type is nominally an Optional type.\n@_transparent\npublic // @testable\nfunc _isOptional<T>(_ type: T.Type) -> Bool {\n return Bool(Builtin.isOptional(type))\n}\n\n/// Test whether a value is computed (i.e. it is not a compile-time constant.)\n///\n/// - Parameters:\n/// - value: The value to test.\n///\n/// - Returns: Whether or not `value` is computed (not known at compile-time.)\n///\n/// Optimizations performed at various stages during compilation may affect the\n/// result of this function.\n@_alwaysEmitIntoClient @inline(__always)\ninternal func _isComputed(_ value: Int) -> Bool {\n return !Bool(Builtin.int_is_constant_Word(value._builtinWordValue))\n}\n\n/// Extract an object reference from an Any known to contain an object.\n@inlinable\n@_unavailableInEmbedded\ninternal func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject {\n _internalInvariant(type(of: any) is AnyObject.Type\n || type(of: any) is AnyObject.Protocol,\n "Any expected to contain object reference")\n // Ideally we would do something like this:\n //\n // func open<T>(object: T) -> AnyObject {\n // return unsafeBitCast(object, to: AnyObject.self)\n // }\n // return _openExistential(any, do: open)\n //\n // Unfortunately, class constrained protocol existentials conform to AnyObject\n // but are not word-sized. As a result, we cannot currently perform the\n // `unsafeBitCast` on them just yet. When they are word-sized, it would be\n // possible to efficiently grab the object reference out of the inline\n // storage.\n return any as AnyObject\n}\n\n// Game the SIL diagnostic pipeline by inlining this into the transparent\n// definitions below after the stdlib's diagnostic passes run, so that the\n// `staticReport`s don't fire while building the standard library, but do\n// fire if they ever show up in code that uses the standard library.\n@inlinable\n@inline(__always)\npublic // internal with availability\nfunc _trueAfterDiagnostics() -> Builtin.Int1 {\n return true._value\n}\n\n/// Returns the dynamic type of a value.\n///\n/// You can use the `type(of:)` function to find the dynamic type of a value,\n/// particularly when the dynamic type is different from the static type. The\n/// *static type* of a value is the known, compile-time type of the value. The\n/// *dynamic type* of a value is the value's actual type at run-time, which\n/// can be a subtype of its concrete type.\n///\n/// In the following code, the `count` variable has the same static and dynamic\n/// type: `Int`. When `count` is passed to the `printInfo(_:)` function,\n/// however, the `value` parameter has a static type of `Any` (the type\n/// declared for the parameter) and a dynamic type of `Int`.\n///\n/// func printInfo(_ value: Any) {\n/// let t = type(of: value)\n/// print("'\(value)' of type '\(t)'")\n/// }\n///\n/// let count: Int = 5\n/// printInfo(count)\n/// // '5' of type 'Int'\n///\n/// The dynamic type returned from `type(of:)` is a *concrete metatype*\n/// (`T.Type`) for a class, structure, enumeration, or other nonprotocol type\n/// `T`, or an *existential metatype* (`P.Type`) for a protocol or protocol\n/// composition `P`. When the static type of the value passed to `type(of:)`\n/// is constrained to a class or protocol, you can use that metatype to access\n/// initializers or other static members of the class or protocol.\n///\n/// For example, the parameter passed as `value` to the `printSmileyInfo(_:)`\n/// function in the example below is an instance of the `Smiley` class or one\n/// of its subclasses. The function uses `type(of:)` to find the dynamic type\n/// of `value`, which itself is an instance of the `Smiley.Type` metatype.\n///\n/// class Smiley {\n/// class var text: String {\n/// return ":)"\n/// }\n/// }\n///\n/// class EmojiSmiley: Smiley {\n/// override class var text: String {\n/// return "😀"\n/// }\n/// }\n///\n/// func printSmileyInfo(_ value: Smiley) {\n/// let smileyType = type(of: value)\n/// print("Smile!", smileyType.text)\n/// }\n///\n/// let emojiSmiley = EmojiSmiley()\n/// printSmileyInfo(emojiSmiley)\n/// // Smile! 😀\n///\n/// In this example, accessing the `text` property of the `smileyType` metatype\n/// retrieves the overridden value from the `EmojiSmiley` subclass, instead of\n/// the `Smiley` class's original definition.\n///\n/// Finding the Dynamic Type in a Generic Context\n/// =============================================\n///\n/// Normally, you don't need to be aware of the difference between concrete and\n/// existential metatypes, but calling `type(of:)` can yield unexpected\n/// results in a generic context with a type parameter bound to a protocol. In\n/// a case like this, where a generic parameter `T` is bound to a protocol\n/// `P`, the type parameter is not statically known to be a protocol type in\n/// the body of the generic function. As a result, `type(of:)` can only\n/// produce the concrete metatype `P.Protocol`.\n///\n/// The following example defines a `printGenericInfo(_:)` function that takes\n/// a generic parameter and declares the `String` type's conformance to a new\n/// protocol `P`. When `printGenericInfo(_:)` is called with a string that has\n/// `P` as its static type, the call to `type(of:)` returns `P.self` instead\n/// of `String.self` (the dynamic type inside the parameter).\n///\n/// func printGenericInfo<T>(_ value: T) {\n/// let t = type(of: value)\n/// print("'\(value)' of type '\(t)'")\n/// }\n///\n/// protocol P {}\n/// extension String: P {}\n///\n/// let stringAsP: P = "Hello!"\n/// printGenericInfo(stringAsP)\n/// // 'Hello!' of type 'P'\n///\n/// This unexpected result occurs because the call to `type(of: value)` inside\n/// `printGenericInfo(_:)` must return a metatype that is an instance of\n/// `T.Type`, but `String.self` (the expected dynamic type) is not an instance\n/// of `P.Type` (the concrete metatype of `value`). To get the dynamic type\n/// inside `value` in this generic context, cast the parameter to `Any` when\n/// calling `type(of:)`.\n///\n/// func betterPrintGenericInfo<T>(_ value: T) {\n/// let t = type(of: value as Any)\n/// print("'\(value)' of type '\(t)'")\n/// }\n///\n/// betterPrintGenericInfo(stringAsP)\n/// // 'Hello!' of type 'String'\n///\n/// - Parameter value: The value for which to find the dynamic type.\n/// - Returns: The dynamic type, which is a metatype instance.\n@_alwaysEmitIntoClient\n@_semantics("typechecker.type(of:)")\npublic func type<T: ~Copyable & ~Escapable, Metatype>(\n of value: borrowing T\n) -> Metatype {\n // This implementation is never used, since calls to `Swift.type(of:)` are\n // resolved as a special case by the type checker.\n unsafe Builtin.staticReport(_trueAfterDiagnostics(), true._value,\n ("internal consistency error: 'type(of:)' operation failed to resolve"\n as StaticString).utf8Start._rawValue)\n Builtin.unreachable()\n}\n\n@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n@_silgen_name("$ss4type2ofq_x_tr0_lF")\n@usableFromInline\nfunc __abi_type<T, Metatype>(of value: T) -> Metatype {\n // This is a legacy entry point for the original definition of `type(of:)`\n // that the stdlib originally exported for no good reason. The current\n // definition no longer exports a symbol, and nothing is expected to link to\n // it, but we keep it around anyway.\n Builtin.unreachable()\n}\n\n/// Allows a nonescaping closure to temporarily be used as if it were allowed\n/// to escape.\n///\n/// You can use this function to call an API that takes an escaping closure in\n/// a way that doesn't allow the closure to escape in practice. The examples\n/// below demonstrate how to use `withoutActuallyEscaping(_:do:)` in\n/// conjunction with two common APIs that use escaping closures: lazy\n/// collection views and asynchronous operations.\n///\n/// The following code declares an `allValues(in:match:)` function that checks\n/// whether all the elements in an array match a predicate. The function won't\n/// compile as written, because a lazy collection's `filter(_:)` method\n/// requires an escaping closure. The lazy collection isn't persisted, so the\n/// `predicate` closure won't actually escape the body of the function;\n/// nevertheless, it can't be used in this way.\n///\n/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {\n/// return array.lazy.filter { !predicate($0) }.isEmpty\n/// }\n/// // error: closure use of non-escaping parameter 'predicate'...\n///\n/// `withoutActuallyEscaping(_:do:)` provides a temporarily escapable copy of\n/// `predicate` that _can_ be used in a call to the lazy view's `filter(_:)`\n/// method. The second version of `allValues(in:match:)` compiles without\n/// error, with the compiler guaranteeing that the `escapablePredicate`\n/// closure doesn't last beyond the call to `withoutActuallyEscaping(_:do:)`.\n///\n/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {\n/// return withoutActuallyEscaping(predicate) { escapablePredicate in\n/// array.lazy.filter { !escapablePredicate($0) }.isEmpty\n/// }\n/// }\n///\n/// Asynchronous calls are another type of API that typically escape their\n/// closure arguments. The following code declares a\n/// `perform(_:simultaneouslyWith:)` function that uses a dispatch queue to\n/// execute two closures concurrently.\n///\n/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {\n/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)\n/// queue.async(execute: f)\n/// queue.async(execute: g)\n/// queue.sync(flags: .barrier) {}\n/// }\n/// // error: passing non-escaping parameter 'f'...\n/// // error: passing non-escaping parameter 'g'...\n///\n/// The `perform(_:simultaneouslyWith:)` function ends with a call to the\n/// `sync(flags:execute:)` method using the `.barrier` flag, which forces the\n/// function to wait until both closures have completed running before\n/// returning. Even though the barrier guarantees that neither closure will\n/// escape the function, the `async(execute:)` method still requires that the\n/// closures passed be marked as `@escaping`, so the first version of the\n/// function does not compile. To resolve these errors, you can use\n/// `withoutActuallyEscaping(_:do:)` to get copies of `f` and `g` that can be\n/// passed to `async(execute:)`.\n///\n/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {\n/// withoutActuallyEscaping(f) { escapableF in\n/// withoutActuallyEscaping(g) { escapableG in\n/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)\n/// queue.async(execute: escapableF)\n/// queue.async(execute: escapableG)\n/// queue.sync(flags: .barrier) {}\n/// }\n/// }\n/// }\n///\n/// - Important: The escapable copy of `closure` passed to `body` is only valid\n/// during the call to `withoutActuallyEscaping(_:do:)`. It is undefined\n/// behavior for the escapable closure to be stored, referenced, or executed\n/// after the function returns.\n///\n/// - Parameters:\n/// - closure: A nonescaping closure value that is made escapable for the\n/// duration of the execution of the `body` closure. If `body` has a\n/// return value, that value is also used as the return value for the\n/// `withoutActuallyEscaping(_:do:)` function.\n/// - body: A closure that is executed immediately with an escapable copy of\n/// `closure` as its argument.\n/// - Returns: The return value, if any, of the `body` closure.\n@_alwaysEmitIntoClient\n@_transparent\n@_semantics("typechecker.withoutActuallyEscaping(_:do:)")\npublic func withoutActuallyEscaping<ClosureType, ResultType, Failure>(\n _ closure: ClosureType,\n do body: (_ escapingClosure: ClosureType) throws(Failure) -> ResultType\n) throws(Failure) -> ResultType {\n // This implementation is never used, since calls to\n // `Swift.withoutActuallyEscaping(_:do:)` are resolved as a special case by\n // the type checker.\n unsafe Builtin.staticReport(_trueAfterDiagnostics(), true._value,\n ("internal consistency error: 'withoutActuallyEscaping(_:do:)' operation failed to resolve"\n as StaticString).utf8Start._rawValue)\n Builtin.unreachable()\n}\n\n@_silgen_name("$ss23withoutActuallyEscaping_2doq_x_q_xKXEtKr0_lF")\n@usableFromInline\nfunc __abi_withoutActuallyEscaping<ClosureType, ResultType>(\n _ closure: ClosureType,\n do body: (_ escapingClosure: ClosureType) throws -> ResultType\n) throws -> ResultType {\n // This implementation is never used, since calls to\n // `Swift.withoutActuallyEscaping(_:do:)` are resolved as a special case by\n // the type checker.\n unsafe Builtin.staticReport(_trueAfterDiagnostics(), true._value,\n ("internal consistency error: 'withoutActuallyEscaping(_:do:)' operation failed to resolve"\n as StaticString).utf8Start._rawValue)\n Builtin.unreachable()\n}\n\n@_alwaysEmitIntoClient\n@_transparent\n@_semantics("typechecker._openExistential(_:do:)")\npublic func _openExistential<ExistentialType, ContainedType, ResultType, Failure>(\n _ existential: ExistentialType,\n do body: (_ escapingClosure: ContainedType) throws(Failure) -> ResultType\n) throws(Failure) -> ResultType {\n // This implementation is never used, since calls to\n // `Swift._openExistential(_:do:)` are resolved as a special case by\n // the type checker.\n unsafe Builtin.staticReport(_trueAfterDiagnostics(), true._value,\n ("internal consistency error: '_openExistential(_:do:)' operation failed to resolve"\n as StaticString).utf8Start._rawValue)\n Builtin.unreachable()\n}\n\n@usableFromInline\n@_silgen_name("$ss16_openExistential_2doq0_x_q0_q_KXEtKr1_lF")\nfunc __abi_openExistential<ExistentialType, ContainedType, ResultType>(\n _ existential: ExistentialType,\n do body: (_ escapingClosure: ContainedType) throws -> ResultType\n) throws -> ResultType {\n // This implementation is never used, since calls to\n // `Swift._openExistential(_:do:)` are resolved as a special case by\n // the type checker.\n unsafe Builtin.staticReport(_trueAfterDiagnostics(), true._value,\n ("internal consistency error: '_openExistential(_:do:)' operation failed to resolve"\n as StaticString).utf8Start._rawValue)\n Builtin.unreachable()\n}\n\n/// Given a string that is constructed from a string literal, return a pointer\n/// to the global string table location that contains the string literal.\n/// This function will trap when it is invoked on strings that are not\n/// constructed from literals or if the construction site of the string is not\n/// in the function containing the call to this SPI.\n@_transparent\n@_alwaysEmitIntoClient\npublic // @SPI(OSLog)\nfunc _getGlobalStringTablePointer(_ constant: String) -> UnsafePointer<CChar> {\n return unsafe UnsafePointer<CChar>(Builtin.globalStringTablePointer(constant));\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Builtin.swift | cpp_apple_swift_stdlib_public_core_Builtin.swift | Swift | 41,361 | 0.95 | 0.09913 | 0.447917 | react-lib | 18 | 2025-03-21T00:29:39.282880 | Apache-2.0 | false | 1fc1779e81d551fadc32d604dba66244 |
//===--- BuiltinMath.swift --------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Each of the following functions is ordered to match math.h\n\n// These functions have a corresponding LLVM intrinsic.\n// Note, keep this up to date with Darwin/tgmath.swift.gyb\n\n// Order of intrinsics: cos, sin, exp, exp2, log, log10, log2, nearbyint, rint\n\n// Float Intrinsics (32 bits)\n\n@_transparent\npublic func _cos(_ x: Float) -> Float {\n return Float(Builtin.int_cos_FPIEEE32(x._value))\n}\n\n@_transparent\npublic func _sin(_ x: Float) -> Float {\n return Float(Builtin.int_sin_FPIEEE32(x._value))\n}\n\n@_transparent\npublic func _exp(_ x: Float) -> Float {\n return Float(Builtin.int_exp_FPIEEE32(x._value))\n}\n\n@_transparent\npublic func _exp2(_ x: Float) -> Float {\n return Float(Builtin.int_exp2_FPIEEE32(x._value))\n}\n\n@_transparent\npublic func _log(_ x: Float) -> Float {\n return Float(Builtin.int_log_FPIEEE32(x._value))\n}\n\n@_transparent\npublic func _log10(_ x: Float) -> Float {\n return Float(Builtin.int_log10_FPIEEE32(x._value))\n}\n\n@_transparent\npublic func _log2(_ x: Float) -> Float {\n return Float(Builtin.int_log2_FPIEEE32(x._value))\n}\n\n@_transparent\npublic func _nearbyint(_ x: Float) -> Float {\n return Float(Builtin.int_nearbyint_FPIEEE32(x._value))\n}\n\n@_transparent\npublic func _rint(_ x: Float) -> Float {\n return Float(Builtin.int_rint_FPIEEE32(x._value))\n}\n\n// Double Intrinsics (64 bits)\n\n@_transparent\npublic func _cos(_ x: Double) -> Double {\n return Double(Builtin.int_cos_FPIEEE64(x._value))\n}\n\n@_transparent\npublic func _sin(_ x: Double) -> Double {\n return Double(Builtin.int_sin_FPIEEE64(x._value))\n}\n\n@_transparent\npublic func _exp(_ x: Double) -> Double {\n return Double(Builtin.int_exp_FPIEEE64(x._value))\n}\n\n@_transparent\npublic func _exp2(_ x: Double) -> Double {\n return Double(Builtin.int_exp2_FPIEEE64(x._value))\n}\n\n@_transparent\npublic func _log(_ x: Double) -> Double {\n return Double(Builtin.int_log_FPIEEE64(x._value))\n}\n\n@_transparent\npublic func _log10(_ x: Double) -> Double {\n return Double(Builtin.int_log10_FPIEEE64(x._value))\n}\n\n@_transparent\npublic func _log2(_ x: Double) -> Double {\n return Double(Builtin.int_log2_FPIEEE64(x._value))\n}\n\n@_transparent\npublic func _nearbyint(_ x: Double) -> Double {\n return Double(Builtin.int_nearbyint_FPIEEE64(x._value))\n}\n\n@_transparent\npublic func _rint(_ x: Double) -> Double {\n return Double(Builtin.int_rint_FPIEEE64(x._value))\n}\n\n// Float80 Intrinsics (80 bits)\n\n#if !(os(Windows) || os(Android) || ($Embedded && !os(Linux) && !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS)))) && (arch(i386) || arch(x86_64))\n@_transparent\npublic func _cos(_ x: Float80) -> Float80 {\n return Float80(Builtin.int_cos_FPIEEE80(x._value))\n}\n\n@_transparent\npublic func _sin(_ x: Float80) -> Float80 {\n return Float80(Builtin.int_sin_FPIEEE80(x._value))\n}\n\n@_transparent\npublic func _exp(_ x: Float80) -> Float80 {\n return Float80(Builtin.int_exp_FPIEEE80(x._value))\n}\n\n@_transparent\npublic func _exp2(_ x: Float80) -> Float80 {\n return Float80(Builtin.int_exp2_FPIEEE80(x._value))\n}\n\n@_transparent\npublic func _log(_ x: Float80) -> Float80 {\n return Float80(Builtin.int_log_FPIEEE80(x._value))\n}\n\n@_transparent\npublic func _log10(_ x: Float80) -> Float80 {\n return Float80(Builtin.int_log10_FPIEEE80(x._value))\n}\n\n@_transparent\npublic func _log2(_ x: Float80) -> Float80 {\n return Float80(Builtin.int_log2_FPIEEE80(x._value))\n}\n\n@_transparent\npublic func _nearbyint(_ x: Float80) -> Float80 {\n return Float80(Builtin.int_nearbyint_FPIEEE80(x._value))\n}\n\n@_transparent\npublic func _rint(_ x: Float80) -> Float80 {\n return Float80(Builtin.int_rint_FPIEEE80(x._value))\n}\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_BuiltinMath.swift | cpp_apple_swift_stdlib_public_core_BuiltinMath.swift | Swift | 4,089 | 0.95 | 0.018634 | 0.15625 | node-utils | 596 | 2024-08-11T05:19:01.151770 | BSD-3-Clause | false | a432e234736d9ca9816bd55086a45607 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A single extended grapheme cluster that approximates a user-perceived\n/// character.\n///\n/// The `Character` type represents a character made up of one or more Unicode\n/// scalar values, grouped by a Unicode boundary algorithm. Generally, a\n/// `Character` instance matches what the reader of a string will perceive as\n/// a single character. Strings are collections of `Character` instances, so\n/// the number of visible characters is generally the most natural way to\n/// count the length of a string.\n///\n/// let greeting = "Hello! 🐥"\n/// print("Length: \(greeting.count)")\n/// // Prints "Length: 8"\n///\n/// Because each character in a string can be made up of one or more Unicode\n/// scalar values, the number of characters in a string may not match the\n/// length of the Unicode scalar value representation or the length of the\n/// string in a particular binary representation.\n///\n/// print("Unicode scalar value count: \(greeting.unicodeScalars.count)")\n/// // Prints "Unicode scalar value count: 8"\n///\n/// print("UTF-8 representation count: \(greeting.utf8.count)")\n/// // Prints "UTF-8 representation count: 11"\n///\n/// Every `Character` instance is composed of one or more Unicode scalar values\n/// that are grouped together as an *extended grapheme cluster*. The way these\n/// scalar values are grouped is defined by a canonical, localized, or\n/// otherwise tailored Unicode segmentation algorithm.\n///\n/// For example, a country's Unicode flag character is made up of two regional\n/// indicator scalar values that correspond to that country's ISO 3166-1\n/// alpha-2 code. The alpha-2 code for The United States is "US", so its flag\n/// character is made up of the Unicode scalar values `"\u{1F1FA}"` (REGIONAL\n/// INDICATOR SYMBOL LETTER U) and `"\u{1F1F8}"` (REGIONAL INDICATOR SYMBOL\n/// LETTER S). When placed next to each other in a string literal, these two\n/// scalar values are combined into a single grapheme cluster, represented by\n/// a `Character` instance in Swift.\n///\n/// let usFlag: Character = "\u{1F1FA}\u{1F1F8}"\n/// print(usFlag)\n/// // Prints "🇺🇸"\n///\n/// For more information about the Unicode terms used in this discussion, see\n/// the [Unicode.org glossary][glossary]. In particular, this discussion\n/// mentions [extended grapheme clusters][clusters] and [Unicode scalar\n/// values][scalars].\n///\n/// [glossary]: http://www.unicode.org/glossary/\n/// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster\n/// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value\n@frozen\npublic struct Character: Sendable {\n @usableFromInline\n internal var _str: String\n\n @inlinable @inline(__always)\n internal init(unchecked str: String) {\n self._str = str\n _invariantCheck()\n }\n}\n\nextension Character {\n #if !INTERNAL_CHECKS_ENABLED\n @inlinable @inline(__always) internal func _invariantCheck() {}\n #else\n @usableFromInline @inline(never) @_effects(releasenone)\n internal func _invariantCheck() {\n _internalInvariant(_str.count == 1)\n _internalInvariant(_str._guts.isFastUTF8)\n\n _internalInvariant(_str._guts._object.isPreferredRepresentation)\n }\n #endif // INTERNAL_CHECKS_ENABLED\n}\n\nextension Character {\n /// A view of a character's contents as a collection of UTF-8 code units. See\n /// String.UTF8View for more information\n public typealias UTF8View = String.UTF8View\n\n /// A UTF-8 encoding of `self`.\n @inlinable\n public var utf8: UTF8View { return _str.utf8 }\n\n /// A view of a character's contents as a collection of UTF-16 code units. See\n /// String.UTF16View for more information\n public typealias UTF16View = String.UTF16View\n\n /// A UTF-16 encoding of `self`.\n @inlinable\n public var utf16: UTF16View { return _str.utf16 }\n\n public typealias UnicodeScalarView = String.UnicodeScalarView\n\n @inlinable\n public var unicodeScalars: UnicodeScalarView { return _str.unicodeScalars }\n}\n\nextension Character :\n _ExpressibleByBuiltinExtendedGraphemeClusterLiteral,\n ExpressibleByExtendedGraphemeClusterLiteral\n{\n /// Creates a character containing the given Unicode scalar value.\n ///\n /// - Parameter content: The Unicode scalar value to convert into a character.\n @inlinable @inline(__always)\n public init(_ content: Unicode.Scalar) {\n self.init(unchecked: String(content))\n }\n\n @inlinable @inline(__always)\n @_effects(readonly)\n public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {\n self.init(Unicode.Scalar(_builtinUnicodeScalarLiteral: value))\n }\n\n // Inlining ensures that the whole constructor can be folded away to a single\n // integer constant in case of small character literals.\n @inlinable @inline(__always)\n @_effects(readonly)\n public init(\n _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,\n utf8CodeUnitCount: Builtin.Word,\n isASCII: Builtin.Int1\n ) {\n self.init(unchecked: String(\n _builtinExtendedGraphemeClusterLiteral: start,\n utf8CodeUnitCount: utf8CodeUnitCount,\n isASCII: isASCII))\n }\n\n /// Creates a character with the specified value.\n ///\n /// Do not call this initializer directly. It is used by the compiler when\n /// you use a string literal to initialize a `Character` instance. For\n /// example:\n ///\n /// let oBreve: Character = "o\u{306}"\n /// print(oBreve)\n /// // Prints "ŏ"\n ///\n /// The assignment to the `oBreve` constant calls this initializer behind the\n /// scenes.\n @inlinable @inline(__always)\n public init(extendedGraphemeClusterLiteral value: Character) {\n self.init(unchecked: value._str)\n }\n\n /// Creates a character from a single-character string.\n ///\n /// The following example creates a new character from the uppercase version\n /// of a string that only holds one character.\n ///\n /// let a = "a"\n /// let capitalA = Character(a.uppercased())\n ///\n /// - Parameter s: The single-character string to convert to a `Character`\n /// instance. `s` must contain exactly one extended grapheme cluster.\n @inlinable @inline(__always)\n public init(_ s: String) {\n _precondition(!s.isEmpty,\n "Can't form a Character from an empty String")\n _debugPrecondition(s.index(after: s.startIndex) == s.endIndex,\n "Can't form a Character from a String containing more than one extended grapheme cluster")\n\n if _fastPath(s._guts._object.isPreferredRepresentation) {\n self.init(unchecked: s)\n return\n }\n self.init(unchecked: String._copying(s))\n }\n}\n\nextension Character: CustomStringConvertible {\n @inlinable\n public var description: String {\n return _str\n }\n}\n\nextension Character: LosslessStringConvertible { }\n\nextension Character: CustomDebugStringConvertible {\n /// A textual representation of the character, suitable for debugging.\n public var debugDescription: String {\n return _str.debugDescription\n }\n}\n\nextension String {\n /// Creates a string containing the given character.\n ///\n /// - Parameter c: The character to convert to a string.\n @inlinable @inline(__always)\n public init(_ c: Character) {\n self.init(c._str._guts)\n }\n}\n\nextension Character: Equatable {\n @inlinable @inline(__always)\n @_effects(readonly)\n public static func == (lhs: Character, rhs: Character) -> Bool {\n return lhs._str == rhs._str\n }\n}\n\nextension Character: Comparable {\n @inlinable @inline(__always)\n @_effects(readonly)\n public static func < (lhs: Character, rhs: Character) -> Bool {\n return lhs._str < rhs._str\n }\n}\n\nextension Character: Hashable {\n // not @inlinable (performance)\n /// Hashes the essential components of this value by feeding them into the\n /// given hasher.\n ///\n /// - Parameter hasher: The hasher to use when combining the components\n /// of this instance.\n @_effects(releasenone)\n public func hash(into hasher: inout Hasher) {\n _str.hash(into: &hasher)\n }\n}\n\nextension Character {\n @usableFromInline // @testable\n internal var _isSmall: Bool {\n return _str._guts.isSmall\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Character.swift | cpp_apple_swift_stdlib_public_core_Character.swift | Swift | 8,505 | 0.8 | 0.032258 | 0.482143 | vue-tools | 184 | 2023-08-21T14:39:22.606956 | BSD-3-Clause | false | 9b2cb1950d2d34d52ac546b56d531b33 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension Character {\n @inlinable\n internal var _firstScalar: Unicode.Scalar {\n return self.unicodeScalars.first!\n }\n @inlinable\n internal var _isSingleScalar: Bool {\n return self.unicodeScalars.index(\n after: self.unicodeScalars.startIndex\n ) == self.unicodeScalars.endIndex\n }\n\n /// A Boolean value indicating whether this is an ASCII character.\n @inlinable\n public var isASCII: Bool {\n return asciiValue != nil\n }\n\n /// The ASCII encoding value of this character, if it is an ASCII character.\n ///\n /// let chars: [Character] = ["a", " ", "™"]\n /// for ch in chars {\n /// print(ch, "-->", ch.asciiValue)\n /// }\n /// // Prints:\n /// // a --> Optional(97)\n /// // --> Optional(32)\n /// // ™ --> nil\n ///\n /// A character with the value "\r\n" (CR-LF) is normalized to "\n" (LF) and\n /// has an `asciiValue` property equal to 10.\n ///\n /// let cr = "\r" as Character\n /// // cr.asciiValue == 13\n /// let lf = "\n" as Character\n /// // lf.asciiValue == 10\n /// let crlf = "\r\n" as Character\n /// // crlf.asciiValue == 10\n @inlinable\n public var asciiValue: UInt8? {\n if _slowPath(self == "\r\n") { return 0x000A /* LINE FEED (LF) */ }\n if _slowPath(!_isSingleScalar || _firstScalar.value >= 0x80) { return nil }\n return UInt8(_firstScalar.value)\n }\n\n /// A Boolean value indicating whether this character represents whitespace,\n /// including newlines.\n ///\n /// For example, the following characters all represent whitespace:\n ///\n /// - "\t" (U+0009 CHARACTER TABULATION)\n /// - " " (U+0020 SPACE)\n /// - U+2029 PARAGRAPH SEPARATOR\n /// - U+3000 IDEOGRAPHIC SPACE\n public var isWhitespace: Bool {\n return _firstScalar.properties.isWhitespace\n }\n\n /// A Boolean value indicating whether this character represents a newline.\n ///\n /// For example, the following characters all represent newlines:\n ///\n /// - "\n" (U+000A): LINE FEED (LF)\n /// - U+000B: LINE TABULATION (VT)\n /// - U+000C: FORM FEED (FF)\n /// - "\r" (U+000D): CARRIAGE RETURN (CR)\n /// - "\r\n" (U+000D U+000A): CR-LF\n /// - U+0085: NEXT LINE (NEL)\n /// - U+2028: LINE SEPARATOR\n /// - U+2029: PARAGRAPH SEPARATOR\n @inlinable\n public var isNewline: Bool {\n switch _firstScalar.value {\n case 0x000A...0x000D /* LF ... CR */: return true\n case 0x0085 /* NEXT LINE (NEL) */: return true\n case 0x2028 /* LINE SEPARATOR */: return true\n case 0x2029 /* PARAGRAPH SEPARATOR */: return true\n default: return false\n }\n }\n\n /// A Boolean value indicating whether this character represents a number.\n ///\n /// For example, the following characters all represent numbers:\n ///\n /// - "7" (U+0037 DIGIT SEVEN)\n /// - "⅚" (U+215A VULGAR FRACTION FIVE SIXTHS)\n /// - "㊈" (U+3288 CIRCLED IDEOGRAPH NINE)\n /// - "𝟠" (U+1D7E0 MATHEMATICAL DOUBLE-STRUCK DIGIT EIGHT)\n /// - "๒" (U+0E52 THAI DIGIT TWO)\n public var isNumber: Bool {\n return _firstScalar.properties.numericType != nil\n }\n\n /// A Boolean value indicating whether this character represents a whole\n /// number.\n ///\n /// For example, the following characters all represent whole numbers:\n ///\n /// - "1" (U+0031 DIGIT ONE) => 1\n /// - "५" (U+096B DEVANAGARI DIGIT FIVE) => 5\n /// - "๙" (U+0E59 THAI DIGIT NINE) => 9\n /// - "万" (U+4E07 CJK UNIFIED IDEOGRAPH-4E07) => 10_000\n @inlinable\n public var isWholeNumber: Bool {\n return wholeNumberValue != nil\n }\n\n /// The numeric value this character represents, if it represents a whole\n /// number.\n ///\n /// If this character does not represent a whole number, or the value is too\n /// large to represent as an `Int`, the value of this property is `nil`.\n ///\n /// let chars: [Character] = ["4", "④", "万", "a"]\n /// for ch in chars {\n /// print(ch, "-->", ch.wholeNumberValue)\n /// }\n /// // Prints:\n /// // 4 --> Optional(4)\n /// // ④ --> Optional(4)\n /// // 万 --> Optional(10000)\n /// // a --> nil\n public var wholeNumberValue: Int? {\n guard _isSingleScalar else { return nil }\n guard let value = _firstScalar.properties.numericValue else { return nil }\n return Int(exactly: value)\n }\n\n /// A Boolean value indicating whether this character represents a\n /// hexadecimal digit.\n ///\n /// Hexadecimal digits include 0-9, Latin letters a-f and A-F, and their\n /// fullwidth compatibility forms. To get the character's value, use the\n /// `hexDigitValue` property.\n @inlinable\n public var isHexDigit: Bool {\n return hexDigitValue != nil\n }\n\n /// The numeric value this character represents, if it is a hexadecimal digit.\n ///\n /// Hexadecimal digits include 0-9, Latin letters a-f and A-F, and their\n /// fullwidth compatibility forms. If the character does not represent a\n /// hexadecimal digit, the value of this property is `nil`.\n ///\n /// let chars: [Character] = ["1", "a", "F", "g"]\n /// for ch in chars {\n /// print(ch, "-->", ch.hexDigitValue)\n /// }\n /// // Prints:\n /// // 1 --> Optional(1)\n /// // a --> Optional(10)\n /// // F --> Optional(15)\n /// // g --> nil\n public var hexDigitValue: Int? {\n guard _isSingleScalar else { return nil }\n let value = _firstScalar.value\n switch value {\n // DIGIT ZERO..DIGIT NINE\n case 0x0030...0x0039: return Int(value &- 0x0030)\n // LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER F\n case 0x0041...0x0046: return Int((value &+ 10) &- 0x0041)\n // LATIN SMALL LETTER A..LATIN SMALL LETTER F\n case 0x0061...0x0066: return Int((value &+ 10) &- 0x0061)\n // FULLWIDTH DIGIT ZERO..FULLWIDTH DIGIT NINE\n case 0xFF10...0xFF19: return Int(value &- 0xFF10)\n // FULLWIDTH LATIN CAPITAL LETTER A..FULLWIDTH LATIN CAPITAL LETTER F\n case 0xFF21...0xFF26: return Int((value &+ 10) &- 0xFF21)\n // FULLWIDTH LATIN SMALL LETTER A..FULLWIDTH LATIN SMALL LETTER F\n case 0xFF41...0xFF46: return Int((value &+ 10) &- 0xFF41)\n\n default: return nil\n }\n }\n\n /// A Boolean value indicating whether this character is a letter.\n ///\n /// For example, the following characters are all letters:\n ///\n /// - "A" (U+0041 LATIN CAPITAL LETTER A)\n /// - "é" (U+0065 LATIN SMALL LETTER E, U+0301 COMBINING ACUTE ACCENT)\n /// - "ϴ" (U+03F4 GREEK CAPITAL THETA SYMBOL)\n /// - "ڈ" (U+0688 ARABIC LETTER DDAL)\n /// - "日" (U+65E5 CJK UNIFIED IDEOGRAPH-65E5)\n /// - "ᚨ" (U+16A8 RUNIC LETTER ANSUZ A)\n public var isLetter: Bool {\n return _firstScalar.properties.isAlphabetic\n }\n\n /// Returns an uppercased version of this character.\n ///\n /// Because case conversion can result in multiple characters, the result\n /// of `uppercased()` is a string.\n ///\n /// let chars: [Character] = ["e", "é", "и", "π", "ß", "1"]\n /// for ch in chars {\n /// print(ch, "-->", ch.uppercased())\n /// }\n /// // Prints:\n /// // e --> E\n /// // é --> É\n /// // и --> И\n /// // π --> Π\n /// // ß --> SS\n /// // 1 --> 1\n public func uppercased() -> String { return String(self).uppercased() }\n\n /// Returns a lowercased version of this character.\n ///\n /// Because case conversion can result in multiple characters, the result\n /// of `lowercased()` is a string.\n ///\n /// let chars: [Character] = ["E", "É", "И", "Π", "1"]\n /// for ch in chars {\n /// print(ch, "-->", ch.lowercased())\n /// }\n /// // Prints:\n /// // E --> e\n /// // É --> é\n /// // И --> и\n /// // Π --> π\n /// // 1 --> 1\n public func lowercased() -> String { return String(self).lowercased() }\n\n @usableFromInline\n internal var _isUppercased: Bool { return String(self) == self.uppercased() }\n @usableFromInline\n internal var _isLowercased: Bool { return String(self) == self.lowercased() }\n\n /// A Boolean value indicating whether this character is considered uppercase.\n ///\n /// Uppercase characters vary under case-conversion to lowercase, but not when\n /// converted to uppercase. The following characters are all uppercase:\n ///\n /// - "É" (U+0045 LATIN CAPITAL LETTER E, U+0301 COMBINING ACUTE ACCENT)\n /// - "И" (U+0418 CYRILLIC CAPITAL LETTER I)\n /// - "Π" (U+03A0 GREEK CAPITAL LETTER PI)\n @inlinable\n public var isUppercase: Bool {\n if _fastPath(_isSingleScalar && _firstScalar.properties.isUppercase) {\n return true\n }\n return _isUppercased && isCased\n }\n\n /// A Boolean value indicating whether this character is considered lowercase.\n ///\n /// Lowercase characters change when converted to uppercase, but not when\n /// converted to lowercase. The following characters are all lowercase:\n ///\n /// - "é" (U+0065 LATIN SMALL LETTER E, U+0301 COMBINING ACUTE ACCENT)\n /// - "и" (U+0438 CYRILLIC SMALL LETTER I)\n /// - "π" (U+03C0 GREEK SMALL LETTER PI)\n @inlinable\n public var isLowercase: Bool {\n if _fastPath(_isSingleScalar && _firstScalar.properties.isLowercase) {\n return true\n }\n return _isLowercased && isCased\n }\n\n /// A Boolean value indicating whether this character changes under any form\n /// of case conversion.\n @inlinable\n public var isCased: Bool {\n if _fastPath(_isSingleScalar && _firstScalar.properties.isCased) {\n return true\n }\n return !_isUppercased || !_isLowercased\n }\n\n /// A Boolean value indicating whether this character represents a symbol.\n ///\n /// This property is `true` only for characters composed of scalars in the\n /// "Math_Symbol", "Currency_Symbol", "Modifier_Symbol", or "Other_Symbol"\n /// categories in the\n /// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).\n ///\n /// For example, the following characters all represent symbols:\n ///\n /// - "®" (U+00AE REGISTERED SIGN)\n /// - "⌹" (U+2339 APL FUNCTIONAL SYMBOL QUAD DIVIDE)\n /// - "⡆" (U+2846 BRAILLE PATTERN DOTS-237)\n public var isSymbol: Bool {\n return _firstScalar.properties.generalCategory._isSymbol\n }\n\n /// A Boolean value indicating whether this character represents a symbol\n /// that naturally appears in mathematical contexts.\n ///\n /// For example, the following characters all represent math symbols:\n ///\n /// - "+" (U+002B PLUS SIGN)\n /// - "∫" (U+222B INTEGRAL)\n /// - "ϰ" (U+03F0 GREEK KAPPA SYMBOL)\n ///\n /// The set of characters that have an `isMathSymbol` value of `true` is not\n /// a strict subset of those for which `isSymbol` is `true`. This includes\n /// characters used both as letters and commonly in mathematical formulas.\n /// For example, "ϰ" (U+03F0 GREEK KAPPA SYMBOL) is considered both a\n /// mathematical symbol and a letter.\n ///\n /// This property corresponds to the "Math" property in the\n /// [Unicode Standard](http://www.unicode.org/versions/latest/).\n public var isMathSymbol: Bool {\n return _firstScalar.properties.isMath\n }\n\n /// A Boolean value indicating whether this character represents a currency\n /// symbol.\n ///\n /// For example, the following characters all represent currency symbols:\n ///\n /// - "$" (U+0024 DOLLAR SIGN)\n /// - "¥" (U+00A5 YEN SIGN)\n /// - "€" (U+20AC EURO SIGN)\n public var isCurrencySymbol: Bool {\n return _firstScalar.properties.generalCategory == .currencySymbol\n }\n\n /// A Boolean value indicating whether this character represents punctuation.\n ///\n /// For example, the following characters all represent punctuation:\n ///\n /// - "!" (U+0021 EXCLAMATION MARK)\n /// - "؟" (U+061F ARABIC QUESTION MARK)\n /// - "…" (U+2026 HORIZONTAL ELLIPSIS)\n /// - "—" (U+2014 EM DASH)\n /// - "“" (U+201C LEFT DOUBLE QUOTATION MARK)\n public var isPunctuation: Bool {\n return _firstScalar.properties.generalCategory._isPunctuation\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_CharacterProperties.swift | cpp_apple_swift_stdlib_public_core_CharacterProperties.swift | Swift | 12,351 | 0.8 | 0.054913 | 0.67284 | python-kit | 44 | 2024-04-06T04:44:47.343424 | Apache-2.0 | false | 6bad50fb6ade0420e7dd6e7bf0dc52b0 |
//===--- ClosedRange.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// FIXME: swift-3-indexing-model: Generalize all tests to check both\n// [Closed]Range.\n\n/// An interval from a lower bound up to, and including, an upper bound.\n///\n/// You create a `ClosedRange` instance by using the closed range\n/// operator (`...`).\n///\n/// let throughFive = 0...5\n///\n/// A `ClosedRange` instance contains both its lower bound and its\n/// upper bound.\n///\n/// throughFive.contains(3)\n/// // true\n/// throughFive.contains(10)\n/// // false\n/// throughFive.contains(5)\n/// // true\n///\n/// Because a closed range includes its upper bound, a closed range whose lower\n/// bound is equal to the upper bound contains that value. Therefore, a\n/// `ClosedRange` instance cannot represent an empty range.\n///\n/// let zeroInclusive = 0...0\n/// zeroInclusive.contains(0)\n/// // true\n/// zeroInclusive.isEmpty\n/// // false\n///\n/// Using a Closed Range as a Collection of Consecutive Values\n/// ----------------------------------------------------------\n///\n/// When a closed range uses integers as its lower and upper bounds, or any\n/// other type that conforms to the `Strideable` protocol with an integer\n/// stride, you can use that range in a `for`-`in` loop or with any sequence or\n/// collection method. The elements of the range are the consecutive values\n/// from its lower bound up to, and including, its upper bound.\n///\n/// for n in 3...5 {\n/// print(n)\n/// }\n/// // Prints "3"\n/// // Prints "4"\n/// // Prints "5"\n///\n/// Because floating-point types such as `Float` and `Double` are their own\n/// `Stride` types, they cannot be used as the bounds of a countable range. If\n/// you need to iterate over consecutive floating-point values, see the\n/// `stride(from:through:by:)` function.\n@frozen\npublic struct ClosedRange<Bound: Comparable> {\n /// The range's lower bound.\n public let lowerBound: Bound\n\n /// The range's upper bound.\n public let upperBound: Bound\n\n // This works around _debugPrecondition() impacting the performance of\n // optimized code. (rdar://72246338)\n @unsafe\n @_alwaysEmitIntoClient @inline(__always)\n internal init(_uncheckedBounds bounds: (lower: Bound, upper: Bound)) {\n self.lowerBound = bounds.lower\n self.upperBound = bounds.upper\n }\n\n /// Creates an instance with the given bounds.\n ///\n /// Because this initializer does not perform any checks, it should be used\n /// as an optimization only when you are absolutely certain that `lower` is\n /// less than or equal to `upper`. Using the closed range operator (`...`)\n /// to form `ClosedRange` instances is preferred.\n ///\n /// - Parameter bounds: A tuple of the lower and upper bounds of the range.\n @inlinable\n @unsafe\n public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) {\n _debugPrecondition(bounds.lower <= bounds.upper,\n "ClosedRange requires lowerBound <= upperBound")\n unsafe self.init(\n _uncheckedBounds: (lower: bounds.lower, upper: bounds.upper)\n )\n }\n}\n\n// define isEmpty, which is available even on an uncountable ClosedRange\nextension ClosedRange {\n /// A Boolean value indicating whether the range contains no elements.\n ///\n /// Because a closed range cannot represent an empty range, this property is\n /// always `false`.\n @inlinable\n public var isEmpty: Bool {\n return false\n }\n}\n\nextension ClosedRange: RangeExpression {\n @inlinable // trivial-implementation\n public func relative<C: Collection>(to collection: C) -> Range<Bound>\n where C.Index == Bound {\n return unsafe Range(\n _uncheckedBounds: (\n lower: lowerBound,\n upper: collection.index(after: self.upperBound)))\n }\n\n /// Returns a Boolean value indicating whether the given element is contained\n /// within the range.\n ///\n /// A `ClosedRange` instance contains both its lower and upper bound.\n /// `element` is contained in the range if it is between the two bounds or\n /// equal to either bound.\n ///\n /// - Parameter element: The element to check for containment.\n /// - Returns: `true` if `element` is contained in the range; otherwise,\n /// `false`.\n @inlinable\n public func contains(_ element: Bound) -> Bool {\n return element >= self.lowerBound && element <= self.upperBound\n }\n}\n\nextension ClosedRange: Sequence\nwhere Bound: Strideable, Bound.Stride: SignedInteger {\n public typealias Element = Bound\n public typealias Iterator = IndexingIterator<ClosedRange<Bound>>\n}\n\nextension ClosedRange where Bound: Strideable, Bound.Stride: SignedInteger {\n @frozen // FIXME(resilience)\n public enum Index {\n case pastEnd\n case inRange(Bound)\n }\n}\n\nextension ClosedRange.Index: Comparable {\n @inlinable\n public static func == (\n lhs: ClosedRange<Bound>.Index,\n rhs: ClosedRange<Bound>.Index\n ) -> Bool {\n switch (lhs, rhs) {\n case (.inRange(let l), .inRange(let r)):\n return l == r\n case (.pastEnd, .pastEnd):\n return true\n default:\n return false\n }\n }\n\n @inlinable\n public static func < (\n lhs: ClosedRange<Bound>.Index,\n rhs: ClosedRange<Bound>.Index\n ) -> Bool {\n switch (lhs, rhs) {\n case (.inRange(let l), .inRange(let r)):\n return l < r\n case (.inRange, .pastEnd):\n return true\n default:\n return false\n }\n }\n}\n\nextension ClosedRange.Index: Hashable\nwhere Bound: Strideable, Bound.Stride: SignedInteger, Bound: Hashable {\n /// Hashes the essential components of this value by feeding them into the\n /// given hasher.\n ///\n /// - Parameter hasher: The hasher to use when combining the components\n /// of this instance.\n @inlinable\n public func hash(into hasher: inout Hasher) {\n switch self {\n case .inRange(let value):\n hasher.combine(0 as Int8)\n hasher.combine(value)\n case .pastEnd:\n hasher.combine(1 as Int8)\n }\n }\n}\n\n// FIXME: this should only be conformance to RandomAccessCollection but\n// the compiler balks without all 3\nextension ClosedRange: Collection, BidirectionalCollection, RandomAccessCollection\nwhere Bound: Strideable, Bound.Stride: SignedInteger\n{\n // while a ClosedRange can't be empty, a _slice_ of a ClosedRange can,\n // so ClosedRange can't be its own self-slice unlike Range\n public typealias SubSequence = Slice<ClosedRange<Bound>>\n\n /// The position of the first element in the range.\n @inlinable\n public var startIndex: Index {\n return .inRange(lowerBound)\n }\n\n /// The range's "past the end" position---that is, the position one greater\n /// than the last valid subscript argument.\n @inlinable\n public var endIndex: Index {\n return .pastEnd\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n switch i {\n case .inRange(let x):\n return x == upperBound\n ? .pastEnd\n : .inRange(x.advanced(by: 1))\n case .pastEnd: \n _preconditionFailure("Incrementing past end index")\n }\n }\n\n @inlinable\n public func index(before i: Index) -> Index {\n switch i {\n case .inRange(let x):\n _precondition(x > lowerBound, "Incrementing past start index")\n return .inRange(x.advanced(by: -1))\n case .pastEnd: \n _precondition(upperBound >= lowerBound, "Incrementing past start index")\n return .inRange(upperBound)\n }\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n switch i {\n case .inRange(let x):\n let d = x.distance(to: upperBound)\n if distance <= d {\n let newPosition = x.advanced(by: numericCast(distance))\n _precondition(newPosition >= lowerBound,\n "Advancing past start index")\n return .inRange(newPosition)\n }\n if d - -1 == distance { return .pastEnd }\n _preconditionFailure("Advancing past end index")\n case .pastEnd:\n if distance == 0 {\n return i\n } \n if distance < 0 {\n return index(.inRange(upperBound), offsetBy: numericCast(distance + 1))\n }\n _preconditionFailure("Advancing past end index")\n }\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n switch (start, end) {\n case let (.inRange(left), .inRange(right)):\n // in range <--> in range\n return numericCast(left.distance(to: right))\n case let (.inRange(left), .pastEnd):\n // in range --> end\n return numericCast(1 + left.distance(to: upperBound))\n case let (.pastEnd, .inRange(right)):\n // in range <-- end\n return numericCast(upperBound.distance(to: right) - 1)\n case (.pastEnd, .pastEnd):\n // end <--> end\n return 0\n }\n }\n\n /// Accesses the element at specified position.\n ///\n /// You can subscript a collection with any valid index other than the\n /// collection's end index. The end index refers to the position one past\n /// the last element of a collection, so it doesn't correspond with an\n /// element.\n ///\n /// - Parameter position: The position of the element to access. `position`\n /// must be a valid index of the range, and must not equal the range's end\n /// index.\n @inlinable\n public subscript(position: Index) -> Bound {\n // FIXME: swift-3-indexing-model: range checks and tests.\n switch position {\n case .inRange(let x): return x\n case .pastEnd: _preconditionFailure("Index out of range")\n }\n }\n\n @inlinable\n public subscript(bounds: Range<Index>)\n -> Slice<ClosedRange<Bound>> {\n return Slice(base: self, bounds: bounds)\n }\n\n @inlinable\n public func _customContainsEquatableElement(_ element: Bound) -> Bool? {\n return lowerBound <= element && element <= upperBound\n }\n\n @inlinable\n public func _customIndexOfEquatableElement(_ element: Bound) -> Index?? {\n return lowerBound <= element && element <= upperBound\n ? .inRange(element) : nil\n }\n\n @inlinable\n public func _customLastIndexOfEquatableElement(_ element: Bound) -> Index?? {\n // The first and last elements are the same because each element is unique.\n return _customIndexOfEquatableElement(element)\n }\n \n /// Returns a Boolean value indicating whether the given range is contained\n /// within this closed range.\n ///\n /// The given range is contained within this closed range if the elements of\n /// the range are all contained within this closed range.\n ///\n /// let range = 0...10\n /// range.contains(5..<7) // true\n /// range.contains(5..<10) // true\n /// range.contains(5..<12) // false\n ///\n /// // Note that `5..<11` contains 5, 6, 7, 8, 9, and 10.\n /// range.contains(5..<11) // true\n ///\n /// Additionally, passing any empty range as `other` results in the value\n /// `true`, even if the empty range's bounds are outside the bounds of this\n /// closed range.\n ///\n /// range.contains(3..<3) // true\n /// range.contains(20..<20) // true\n ///\n /// - Parameter other: A range to check for containment within this closed\n /// range.\n /// - Returns: `true` if `other` is empty or wholly contained within this\n /// closed range; otherwise, `false`.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public func contains(_ other: Range<Bound>) -> Bool {\n if other.isEmpty { return true }\n let otherInclusiveUpper = other.upperBound.advanced(by: -1)\n return lowerBound <= other.lowerBound && upperBound >= otherInclusiveUpper\n }\n}\n\nextension ClosedRange {\n /// Returns a Boolean value indicating whether the given closed range is\n /// contained within this closed range.\n ///\n /// The given closed range is contained within this range if its bounds are\n /// contained within this closed range.\n ///\n /// let range = 0...10\n /// range.contains(2...5) // true\n /// range.contains(2...10) // true\n /// range.contains(2...12) // false\n ///\n /// - Parameter other: A closed range to check for containment within this\n /// closed range.\n /// - Returns: `true` if `other` is wholly contained within this closed range;\n /// otherwise, `false`.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public func contains(_ other: ClosedRange<Bound>) -> Bool {\n lowerBound <= other.lowerBound && upperBound >= other.upperBound\n }\n}\n\nextension Comparable { \n /// Returns a closed range that contains both of its bounds.\n ///\n /// Use the closed range operator (`...`) to create a closed range of any type\n /// that conforms to the `Comparable` protocol. This example creates a\n /// `ClosedRange<Character>` from "a" up to, and including, "z".\n ///\n /// let lowercase = "a"..."z"\n /// print(lowercase.contains("z"))\n /// // Prints "true"\n ///\n /// - Parameters:\n /// - minimum: The lower bound for the range.\n /// - maximum: The upper bound for the range.\n ///\n /// - Precondition: `minimum <= maximum`.\n @_transparent\n public static func ... (minimum: Self, maximum: Self) -> ClosedRange<Self> {\n _precondition(\n minimum <= maximum, "Range requires lowerBound <= upperBound")\n return unsafe ClosedRange(_uncheckedBounds: (lower: minimum, upper: maximum))\n }\n}\n\nextension ClosedRange: Equatable {\n /// Returns a Boolean value indicating whether two ranges are equal.\n ///\n /// Two ranges are equal when they have the same lower and upper bounds.\n ///\n /// let x = 5...15\n /// print(x == 5...15)\n /// // Prints "true"\n /// print(x == 10...20)\n /// // Prints "false"\n ///\n /// - Parameters:\n /// - lhs: A range to compare.\n /// - rhs: Another range to compare.\n @inlinable\n public static func == (\n lhs: ClosedRange<Bound>, rhs: ClosedRange<Bound>\n ) -> Bool {\n return lhs.lowerBound == rhs.lowerBound && lhs.upperBound == rhs.upperBound\n }\n}\n\nextension ClosedRange: Hashable where Bound: Hashable {\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine(lowerBound)\n hasher.combine(upperBound)\n }\n}\n\n@_unavailableInEmbedded\nextension ClosedRange: CustomStringConvertible {\n /// A textual representation of the range.\n @inlinable // trivial-implementation...\n public var description: String {\n return "\(lowerBound)...\(upperBound)"\n }\n}\n\n@_unavailableInEmbedded\nextension ClosedRange: CustomDebugStringConvertible {\n /// A textual representation of the range, suitable for debugging.\n public var debugDescription: String {\n return "ClosedRange(\(String(reflecting: lowerBound))"\n + "...\(String(reflecting: upperBound)))"\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension ClosedRange: CustomReflectable {\n public var customMirror: Mirror {\n return Mirror(\n self, children: ["lowerBound": lowerBound, "upperBound": upperBound])\n }\n}\n#endif\n\nextension ClosedRange {\n /// Returns a copy of this range clamped to the given limiting range.\n ///\n /// The bounds of the result are always limited to the bounds of `limits`.\n /// For example:\n ///\n /// let x: ClosedRange = 0...20\n /// print(x.clamped(to: 10...1000))\n /// // Prints "10...20"\n ///\n /// If the two ranges do not overlap, the result is a single-element range at\n /// the upper or lower bound of `limits`.\n ///\n /// let y: ClosedRange = 0...5\n /// print(y.clamped(to: 10...1000))\n /// // Prints "10...10"\n ///\n /// - Parameter limits: The range to clamp the bounds of this range.\n /// - Returns: A new range clamped to the bounds of `limits`.\n @inlinable // trivial-implementation\n @inline(__always)\n public func clamped(to limits: ClosedRange) -> ClosedRange {\n let lower = \n limits.lowerBound > self.lowerBound ? limits.lowerBound\n : limits.upperBound < self.lowerBound ? limits.upperBound\n : self.lowerBound\n let upper =\n limits.upperBound < self.upperBound ? limits.upperBound\n : limits.lowerBound > self.upperBound ? limits.lowerBound\n : self.upperBound\n return unsafe ClosedRange(_uncheckedBounds: (lower: lower, upper: upper))\n }\n}\n\nextension ClosedRange where Bound: Strideable, Bound.Stride: SignedInteger {\n /// Creates an instance equivalent to the given `Range`.\n ///\n /// - Parameter other: A `Range` to convert to a `ClosedRange` instance.\n ///\n /// An equivalent range must be representable as a closed range.\n /// For example, passing an empty range as `other` triggers a runtime error,\n /// because an empty range cannot be represented by a closed range instance.\n @inlinable\n public init(_ other: Range<Bound>) {\n _precondition(!other.isEmpty, "Can't form an empty closed range")\n let upperBound = other.upperBound.advanced(by: -1)\n unsafe self.init(\n _uncheckedBounds: (lower: other.lowerBound, upper: upperBound)\n )\n }\n}\n\nextension ClosedRange {\n /// Returns a Boolean value indicating whether this range and the given closed\n /// range contain an element in common.\n ///\n /// This example shows two overlapping ranges:\n ///\n /// let x: Range = 0...20\n /// print(x.overlaps(10...1000))\n /// // Prints "true"\n ///\n /// - Parameter other: A range to check for elements in common.\n /// - Returns: `true` if this range and `other` have at least one element in\n /// common; otherwise, `false`.\n @inlinable\n public func overlaps(_ other: ClosedRange<Bound>) -> Bool {\n // Disjoint iff the other range is completely before or after our range.\n // Unlike a `Range`, a `ClosedRange` can *not* be empty, so no check for\n // that case is needed here.\n let isDisjoint = other.upperBound < self.lowerBound\n || self.upperBound < other.lowerBound\n return !isDisjoint\n }\n\n /// Returns a Boolean value indicating whether this range and the given range\n /// contain an element in common.\n ///\n /// This example shows two overlapping ranges:\n ///\n /// let x: Range = 0...20\n /// print(x.overlaps(10..<1000))\n /// // Prints "true"\n ///\n /// Because a closed range includes its upper bound, the ranges in the\n /// following example overlap:\n ///\n /// let y = 20..<30\n /// print(x.overlaps(y))\n /// // Prints "true"\n ///\n /// - Parameter other: A range to check for elements in common.\n /// - Returns: `true` if this range and `other` have at least one element in\n /// common; otherwise, `false`.\n @inlinable\n public func overlaps(_ other: Range<Bound>) -> Bool {\n return other.overlaps(self)\n }\n}\n\n// Note: this is not for compatibility only, it is considered a useful\n// shorthand. TODO: Add documentation\npublic typealias CountableClosedRange<Bound: Strideable> = ClosedRange<Bound>\n where Bound.Stride: SignedInteger\n\n@_unavailableInEmbedded\nextension ClosedRange: Decodable where Bound: Decodable {\n public init(from decoder: Decoder) throws {\n var container = try decoder.unkeyedContainer()\n let lowerBound = try container.decode(Bound.self)\n let upperBound = try container.decode(Bound.self)\n guard lowerBound <= upperBound else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: decoder.codingPath,\n debugDescription: "Cannot initialize \(ClosedRange.self) with a lowerBound (\(lowerBound)) greater than upperBound (\(upperBound))"))\n }\n unsafe self.init(_uncheckedBounds: (lower: lowerBound, upper: upperBound))\n }\n}\n\n@_unavailableInEmbedded\nextension ClosedRange: Encodable where Bound: Encodable {\n public func encode(to encoder: Encoder) throws {\n var container = encoder.unkeyedContainer()\n try container.encode(self.lowerBound)\n try container.encode(self.upperBound)\n }\n}\n\nextension ClosedRange: Sendable where Bound: Sendable { }\nextension ClosedRange.Index: Sendable where Bound: Sendable { }\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ClosedRange.swift | cpp_apple_swift_stdlib_public_core_ClosedRange.swift | Swift | 20,052 | 0.95 | 0.072968 | 0.448399 | python-kit | 21 | 2023-10-03T15:05:44.234519 | GPL-3.0 | false | 3aee497f11323d1d62290351a373f38b |
//===--- CocoaArray.swift - A subset of the NSArray interface -------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// To implement bridging, the core standard library needs to interact\n// a little bit with Cocoa. Because we want to keep the core\n// decoupled from the Foundation module, we can't use NSArray\n// directly. We _can_, however, use an @objc protocol with a\n// compatible API. That's _NSArrayCore.\n//\n//===----------------------------------------------------------------------===//\n\n#if _runtime(_ObjC)\nimport SwiftShims\n\n/// A wrapper around any `_NSArrayCore` (represented as AnyObject) that gives it\n/// `Collection` conformance. Why not make `_NSArrayCore` conform directly?\n/// It's a class, and I don't want to pay for the dynamic dispatch overhead.\n@usableFromInline\n@frozen\ninternal struct _CocoaArrayWrapper: RandomAccessCollection {\n @usableFromInline\n typealias Indices = Range<Int>\n\n @usableFromInline\n internal var buffer: AnyObject\n\n @usableFromInline @_transparent\n internal init(_ buffer: AnyObject) {\n self.buffer = buffer\n }\n\n internal var core: _NSArrayCore {\n @inline(__always) get {\n return unsafe unsafeBitCast(buffer, to: _NSArrayCore.self)\n }\n }\n\n @inlinable\n internal var startIndex: Int {\n return 0\n }\n\n @usableFromInline\n internal var endIndex: Int {\n @_effects(releasenone) get {\n core.count\n }\n }\n\n @usableFromInline\n internal subscript(i: Int) -> AnyObject {\n @_effects(releasenone) get {\n core.objectAt(i)\n }\n }\n\n @usableFromInline\n internal subscript(bounds: Range<Int>) -> _SliceBuffer<AnyObject> {\n let boundsCount = bounds.count\n if boundsCount == 0 {\n return _SliceBuffer(\n _buffer: _ContiguousArrayBuffer<AnyObject>(),\n shiftedToStartIndex: bounds.lowerBound)\n }\n\n // Look for contiguous storage in the NSArray\n let cocoaStorageBaseAddress = unsafe self.contiguousStorage(self.indices)\n\n if let cocoaStorageBaseAddress = unsafe cocoaStorageBaseAddress {\n return unsafe _SliceBuffer(\n owner: self.buffer,\n subscriptBaseAddress: cocoaStorageBaseAddress,\n indices: bounds,\n hasNativeBuffer: false)\n }\n\n // No contiguous storage found; we must allocate\n let result = _ContiguousArrayBuffer<AnyObject>(\n _uninitializedCount: boundsCount,\n minimumCapacity: 0)\n \n let base = unsafe UnsafeMutableRawPointer(result.firstElementAddress)\n .assumingMemoryBound(to: AnyObject.self)\n \n for idx in 0..<boundsCount {\n unsafe (base + idx).initialize(to: core.objectAt(idx + bounds.lowerBound))\n }\n\n return _SliceBuffer(_buffer: result, shiftedToStartIndex: bounds.lowerBound)\n }\n\n /// Returns a pointer to the first element in the given non-empty `subRange`\n /// if the subRange is stored contiguously. Otherwise, return `nil`.\n ///\n /// The "non-empty" condition saves a branch within this method that can\n /// likely be better handled in a caller.\n ///\n /// - Note: This method should only be used as an optimization; it\n /// is sometimes conservative and may return `nil` even when\n /// contiguous storage exists, e.g., if array doesn't have a smart\n /// implementation of countByEnumerating.\n internal func contiguousStorage(\n _ subRange: Range<Int>\n ) -> UnsafeMutablePointer<AnyObject>?\n {\n _internalInvariant(!subRange.isEmpty)\n var enumerationState = unsafe _makeSwiftNSFastEnumerationState()\n\n // This function currently returns nil unless the first\n // subRange.upperBound items are stored contiguously. This is an\n // acceptable conservative behavior, but could potentially be\n // optimized for other cases.\n let contiguousCount = unsafe withUnsafeMutablePointer(to: &enumerationState) {\n unsafe core.countByEnumerating(with: $0, objects: nil, count: 0)\n }\n\n return unsafe contiguousCount >= subRange.upperBound\n ? UnsafeMutableRawPointer(enumerationState.itemsPtr!)\n .assumingMemoryBound(to: AnyObject.self)\n + subRange.lowerBound\n : nil\n }\n\n @usableFromInline\n __consuming internal func _copyContents(\n subRange bounds: Range<Int>,\n initializing target: UnsafeMutablePointer<AnyObject>\n ) -> UnsafeMutablePointer<AnyObject> {\n return unsafe withExtendedLifetime(buffer) {\n let nsSubRange = SwiftShims._SwiftNSRange(\n location: bounds.lowerBound,\n length: bounds.upperBound - bounds.lowerBound)\n\n // Copies the references out of the NSArray without retaining them\n unsafe core.getObjects(target, range: nsSubRange)\n\n // Make another pass to retain the copied objects\n var result = unsafe target\n for _ in bounds {\n unsafe result.initialize(to: result.pointee)\n unsafe result += 1\n }\n return unsafe result\n }\n }\n\n @_alwaysEmitIntoClient\n internal __consuming func _copyContents(\n initializing buffer: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {\n guard buffer.count > 0 else { return (makeIterator(), 0) }\n let start = buffer.baseAddress!\n let c = Swift.min(self.count, buffer.count)\n _ = unsafe _copyContents(subRange: 0 ..< c, initializing: start)\n return (IndexingIterator(_elements: self, _position: c), c)\n }\n}\n\n@available(*, unavailable)\nextension _CocoaArrayWrapper: Sendable {}\n\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_CocoaArray.swift | cpp_apple_swift_stdlib_public_core_CocoaArray.swift | Swift | 5,770 | 0.95 | 0.081871 | 0.285714 | python-kit | 492 | 2023-11-24T17:52:45.759065 | GPL-3.0 | false | 3b8837ff709c3a336654017a1e409d57 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A type that iterates over a collection using its indices.\n///\n/// The `IndexingIterator` type is the default iterator for any collection that\n/// doesn't declare its own. It acts as an iterator by using a collection's\n/// indices to step over each value in the collection. Most collections in the\n/// standard library use `IndexingIterator` as their iterator.\n///\n/// By default, any custom collection type you create will inherit a\n/// `makeIterator()` method that returns an `IndexingIterator` instance,\n/// making it unnecessary to declare your own. When creating a custom\n/// collection type, add the minimal requirements of the `Collection`\n/// protocol: starting and ending indices and a subscript for accessing\n/// elements. With those elements defined, the inherited `makeIterator()`\n/// method satisfies the requirements of the `Sequence` protocol.\n///\n/// Here's an example of a type that declares the minimal requirements for a\n/// collection. The `CollectionOfTwo` structure is a fixed-size collection\n/// that always holds two elements of a specific type.\n///\n/// struct CollectionOfTwo<Element>: Collection {\n/// let elements: (Element, Element)\n///\n/// init(_ first: Element, _ second: Element) {\n/// self.elements = (first, second)\n/// }\n///\n/// var startIndex: Int { return 0 }\n/// var endIndex: Int { return 2 }\n///\n/// subscript(index: Int) -> Element {\n/// switch index {\n/// case 0: return elements.0\n/// case 1: return elements.1\n/// default: fatalError("Index out of bounds.")\n/// }\n/// }\n/// \n/// func index(after i: Int) -> Int {\n/// precondition(i < endIndex, "Can't advance beyond endIndex")\n/// return i + 1\n/// }\n/// }\n///\n/// Because `CollectionOfTwo` doesn't define its own `makeIterator()`\n/// method or `Iterator` associated type, it uses the default iterator type,\n/// `IndexingIterator`. This example shows how a `CollectionOfTwo` instance\n/// can be created holding the values of a point, and then iterated over\n/// using a `for`-`in` loop.\n///\n/// let point = CollectionOfTwo(15.0, 20.0)\n/// for element in point {\n/// print(element)\n/// }\n/// // Prints "15.0"\n/// // Prints "20.0"\n@frozen\npublic struct IndexingIterator<Elements: Collection> {\n @usableFromInline\n internal let _elements: Elements\n @usableFromInline\n internal var _position: Elements.Index\n\n /// Creates an iterator over the given collection.\n @inlinable\n @inline(__always)\n public /// @testable\n init(_elements: Elements) {\n self._elements = _elements\n self._position = _elements.startIndex\n }\n\n /// Creates an iterator over the given collection.\n @inlinable\n @inline(__always)\n public /// @testable\n init(_elements: Elements, _position: Elements.Index) {\n self._elements = _elements\n self._position = _position\n }\n}\n\nextension IndexingIterator: IteratorProtocol, Sequence {\n public typealias Element = Elements.Element\n public typealias Iterator = IndexingIterator<Elements>\n public typealias SubSequence = AnySequence<Element>\n\n /// Advances to the next element and returns it, or `nil` if no next element\n /// exists.\n ///\n /// Repeatedly calling this method returns all the elements of the underlying\n /// sequence in order. As soon as the sequence has run out of elements, all\n /// subsequent calls return `nil`.\n ///\n /// This example shows how an iterator can be used explicitly to emulate a\n /// `for`-`in` loop. First, retrieve a sequence's iterator, and then call\n /// the iterator's `next()` method until it returns `nil`.\n ///\n /// let numbers = [2, 3, 5, 7]\n /// var numbersIterator = numbers.makeIterator()\n ///\n /// while let num = numbersIterator.next() {\n /// print(num)\n /// }\n /// // Prints "2"\n /// // Prints "3"\n /// // Prints "5"\n /// // Prints "7"\n ///\n /// - Returns: The next element in the underlying sequence if a next element\n /// exists; otherwise, `nil`.\n @inlinable\n @inline(__always)\n public mutating func next() -> Elements.Element? {\n if _position == _elements.endIndex { return nil }\n let element = _elements[_position]\n _elements.formIndex(after: &_position)\n return element\n }\n}\n\nextension IndexingIterator: Sendable\n where Elements: Sendable, Elements.Index: Sendable { }\n\n/// A sequence whose elements can be traversed multiple times,\n/// nondestructively, and accessed by an indexed subscript.\n///\n/// Collections are used extensively throughout the standard library. When you\n/// use arrays, dictionaries, and other collections, you benefit from the\n/// operations that the `Collection` protocol declares and implements. In\n/// addition to the operations that collections inherit from the `Sequence`\n/// protocol, you gain access to methods that depend on accessing an element\n/// at a specific position in a collection.\n///\n/// For example, if you want to print only the first word in a string, you can\n/// search for the index of the first space, and then create a substring up to\n/// that position.\n///\n/// let text = "Buffalo buffalo buffalo buffalo."\n/// if let firstSpace = text.firstIndex(of: " ") {\n/// print(text[..<firstSpace])\n/// }\n/// // Prints "Buffalo"\n///\n/// The `firstSpace` constant is an index into the `text` string---the position\n/// of the first space in the string. You can store indices in variables, and\n/// pass them to collection algorithms or use them later to access the\n/// corresponding element. In the example above, `firstSpace` is used to\n/// extract the prefix that contains elements up to that index.\n///\n/// Accessing Individual Elements\n/// =============================\n///\n/// You can access an element of a collection through its subscript by using\n/// any valid index except the collection's `endIndex` property. This property\n/// is a "past the end" index that does not correspond with any element of the\n/// collection.\n///\n/// Here's an example of accessing the first character in a string through its\n/// subscript:\n///\n/// let firstChar = text[text.startIndex]\n/// print(firstChar)\n/// // Prints "B"\n///\n/// The `Collection` protocol declares and provides default implementations for\n/// many operations that depend on elements being accessible by their\n/// subscript. For example, you can also access the first character of `text`\n/// using the `first` property, which has the value of the first element of\n/// the collection, or `nil` if the collection is empty.\n///\n/// print(text.first)\n/// // Prints "Optional("B")"\n///\n/// You can pass only valid indices to collection operations. You can find a\n/// complete set of a collection's valid indices by starting with the\n/// collection's `startIndex` property and finding every successor up to, and\n/// including, the `endIndex` property. All other values of the `Index` type,\n/// such as the `startIndex` property of a different collection, are invalid\n/// indices for this collection.\n///\n/// Saved indices may become invalid as a result of mutating operations. For\n/// more information about index invalidation in mutable collections, see the\n/// reference for the `MutableCollection` and `RangeReplaceableCollection`\n/// protocols, as well as for the specific type you're using.\n///\n/// Accessing Slices of a Collection\n/// ================================\n///\n/// You can access a slice of a collection through its ranged subscript or by\n/// calling methods like `prefix(while:)` or `suffix(_:)`. A slice of a\n/// collection can contain zero or more of the original collection's elements\n/// and shares the original collection's semantics.\n///\n/// The following example creates a `firstWord` constant by using the\n/// `prefix(while:)` method to get a slice of the `text` string.\n///\n/// let firstWord = text.prefix(while: { $0 != " " })\n/// print(firstWord)\n/// // Prints "Buffalo"\n///\n/// You can retrieve the same slice using the string's ranged subscript, which\n/// takes a range expression.\n///\n/// if let firstSpace = text.firstIndex(of: " ") {\n/// print(text[..<firstSpace])\n/// // Prints "Buffalo"\n/// }\n///\n/// The retrieved slice of `text` is equivalent in each of these cases.\n///\n/// Slices Share Indices\n/// --------------------\n///\n/// A collection and its slices share the same indices. An element of a\n/// collection is located under the same index in a slice as in the base\n/// collection, as long as neither the collection nor the slice has been\n/// mutated since the slice was created.\n///\n/// For example, suppose you have an array holding the number of absences from\n/// each class during a session.\n///\n/// var absences = [0, 2, 0, 4, 0, 3, 1, 0]\n///\n/// You're tasked with finding the day with the most absences in the second\n/// half of the session. To find the index of the day in question, follow\n/// these steps:\n///\n/// 1) Create a slice of the `absences` array that holds the second half of the\n/// days.\n/// 2) Use the `max(by:)` method to determine the index of the day with the\n/// most absences.\n/// 3) Print the result using the index found in step 2 on the original\n/// `absences` array.\n///\n/// Here's an implementation of those steps:\n///\n/// let secondHalf = absences.suffix(absences.count / 2)\n/// if let i = secondHalf.indices.max(by: { secondHalf[$0] < secondHalf[$1] }) {\n/// print("Highest second-half absences: \(absences[i])")\n/// }\n/// // Prints "Highest second-half absences: 3"\n///\n/// Slices Inherit Collection Semantics\n/// -----------------------------------\n///\n/// A slice inherits the value or reference semantics of its base collection.\n/// That is, when working with a slice of a mutable collection that has value\n/// semantics, such as an array, mutating the original collection triggers a\n/// copy of that collection and does not affect the contents of the slice.\n///\n/// For example, if you update the last element of the `absences` array from\n/// `0` to `2`, the `secondHalf` slice is unchanged.\n///\n/// absences[7] = 2\n/// print(absences)\n/// // Prints "[0, 2, 0, 4, 0, 3, 1, 2]"\n/// print(secondHalf)\n/// // Prints "[0, 3, 1, 0]"\n///\n/// Traversing a Collection\n/// =======================\n///\n/// Although a sequence can be consumed as it is traversed, a collection is\n/// guaranteed to be *multipass*: Any element can be repeatedly accessed by\n/// saving its index. Moreover, a collection's indices form a finite range of\n/// the positions of the collection's elements. The fact that all collections\n/// are finite guarantees the safety of many sequence operations, such as\n/// using the `contains(_:)` method to test whether a collection includes an\n/// element.\n///\n/// Iterating over the elements of a collection by their positions yields the\n/// same elements in the same order as iterating over that collection using\n/// its iterator. This example demonstrates that the `characters` view of a\n/// string returns the same characters in the same order whether the view's\n/// indices or the view itself is being iterated.\n///\n/// let word = "Swift"\n/// for character in word {\n/// print(character)\n/// }\n/// // Prints "S"\n/// // Prints "w"\n/// // Prints "i"\n/// // Prints "f"\n/// // Prints "t"\n///\n/// for i in word.indices {\n/// print(word[i])\n/// }\n/// // Prints "S"\n/// // Prints "w"\n/// // Prints "i"\n/// // Prints "f"\n/// // Prints "t"\n///\n/// Conforming to the Collection Protocol\n/// =====================================\n///\n/// If you create a custom sequence that can provide repeated access to its\n/// elements, make sure that its type conforms to the `Collection` protocol in\n/// order to give a more useful and more efficient interface for sequence and\n/// collection operations. To add `Collection` conformance to your type, you\n/// must declare at least the following requirements:\n///\n/// - The `startIndex` and `endIndex` properties\n/// - A subscript that provides at least read-only access to your type's\n/// elements\n/// - The `index(after:)` method for advancing an index into your collection\n///\n/// Expected Performance\n/// ====================\n///\n/// Types that conform to `Collection` are expected to provide the `startIndex`\n/// and `endIndex` properties and subscript access to elements as O(1)\n/// operations. Types that are not able to guarantee this performance must\n/// document the departure, because many collection operations depend on O(1)\n/// subscripting performance for their own performance guarantees.\n///\n/// The performance of some collection operations depends on the type of index\n/// that the collection provides. For example, a random-access collection,\n/// which can measure the distance between two indices in O(1) time, can\n/// calculate its `count` property in O(1) time. Conversely, because a forward\n/// or bidirectional collection must traverse the entire collection to count\n/// the number of contained elements, accessing its `count` property is an\n/// O(*n*) operation.\npublic protocol Collection<Element>: Sequence {\n // FIXME: ideally this would be in MigrationSupport.swift, but it needs\n // to be on the protocol instead of as an extension\n @available(*, deprecated/*, obsoleted: 5.0*/, message: "all index distances are now of type Int")\n typealias IndexDistance = Int \n\n // FIXME: Associated type inference requires this.\n override associatedtype Element\n\n // FIXME: <rdar://problem/34142121>\n // This typealias should be removed as it predates the source compatibility\n // guarantees of Swift 3, but it cannot due to a bug.\n @available(swift, deprecated: 3.2, obsoleted: 5.0, renamed: "Element")\n typealias _Element = Element\n\n /// A type that represents a position in the collection.\n ///\n /// Valid indices consist of the position of every element and a\n /// "past the end" position that's not valid for use as a subscript\n /// argument.\n associatedtype Index: Comparable\n\n /// The position of the first element in a nonempty collection.\n ///\n /// If the collection is empty, `startIndex` is equal to `endIndex`.\n var startIndex: Index { get }\n \n /// The collection's "past the end" position---that is, the position one\n /// greater than the last valid subscript argument.\n ///\n /// When you need a range that includes the last element of a collection, use\n /// the half-open range operator (`..<`) with `endIndex`. The `..<` operator\n /// creates a range that doesn't include the upper bound, so it's always\n /// safe to use with `endIndex`. For example:\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// if let index = numbers.firstIndex(of: 30) {\n /// print(numbers[index ..< numbers.endIndex])\n /// }\n /// // Prints "[30, 40, 50]"\n ///\n /// If the collection is empty, `endIndex` is equal to `startIndex`.\n var endIndex: Index { get }\n\n /// A type that provides the collection's iteration interface and\n /// encapsulates its iteration state.\n ///\n /// By default, a collection conforms to the `Sequence` protocol by\n /// supplying `IndexingIterator` as its associated `Iterator`\n /// type.\n associatedtype Iterator = IndexingIterator<Self>\n\n // FIXME: Only needed for associated type inference. Otherwise,\n // we get an `IndexingIterator` rather than properly deducing the\n // Iterator type from makeIterator(). <rdar://problem/21539115>\n /// Returns an iterator over the elements of the collection.\n override __consuming func makeIterator() -> Iterator\n\n /// A collection representing a contiguous subrange of this collection's\n /// elements. The subsequence shares indices with the original collection.\n ///\n /// The default subsequence type for collections that don't define their own\n /// is `Slice`.\n associatedtype SubSequence: Collection = Slice<Self>\n where SubSequence.Index == Index,\n Element == SubSequence.Element,\n SubSequence.SubSequence == SubSequence\n\n /// Accesses the element at the specified position.\n ///\n /// The following example accesses an element of an array through its\n /// subscript to print its value:\n ///\n /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// print(streets[1])\n /// // Prints "Bryant"\n ///\n /// You can subscript a collection with any valid index other than the\n /// collection's end index. The end index refers to the position one past\n /// the last element of a collection, so it doesn't correspond with an\n /// element.\n ///\n /// - Parameter position: The position of the element to access. `position`\n /// must be a valid index of the collection that is not equal to the\n /// `endIndex` property.\n ///\n /// - Complexity: O(1)\n @_borrowed\n subscript(position: Index) -> Element { get }\n\n /// Accesses a contiguous subrange of the collection's elements.\n ///\n /// For example, using a `PartialRangeFrom` range expression with an array\n /// accesses the subrange from the start of the range expression until the\n /// end of the array.\n ///\n /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// let streetsSlice = streets[2..<5]\n /// print(streetsSlice)\n /// // ["Channing", "Douglas", "Evarts"]\n ///\n /// The accessed slice uses the same indices for the same elements as the\n /// original collection. This example searches `streetsSlice` for one of the\n /// strings in the slice, and then uses that index in the original array.\n ///\n /// let index = streetsSlice.firstIndex(of: "Evarts")! // 4\n /// print(streets[index])\n /// // "Evarts"\n ///\n /// Always use the slice's `startIndex` property instead of assuming that its\n /// indices start at a particular value. Attempting to access an element by\n /// using an index outside the bounds of the slice may result in a runtime\n /// error, even if that index is valid for the original collection.\n ///\n /// print(streetsSlice.startIndex)\n /// // 2\n /// print(streetsSlice[2])\n /// // "Channing"\n ///\n /// print(streetsSlice[0])\n /// // error: Index out of bounds\n ///\n /// - Parameter bounds: A range of the collection's indices. The bounds of\n /// the range must be valid indices of the collection.\n ///\n /// - Complexity: O(1)\n subscript(bounds: Range<Index>) -> SubSequence { get }\n\n /// A type that represents the indices that are valid for subscripting the\n /// collection, in ascending order.\n associatedtype Indices: Collection = DefaultIndices<Self>\n where Indices.Element == Index, \n Indices.Index == Index,\n Indices.SubSequence == Indices\n \n /// The indices that are valid for subscripting the collection, in ascending\n /// order.\n ///\n /// A collection's `indices` property can hold a strong reference to the\n /// collection itself, causing the collection to be nonuniquely referenced.\n /// If you mutate the collection while iterating over its indices, a strong\n /// reference can result in an unexpected copy of the collection. To avoid\n /// the unexpected copy, use the `index(after:)` method starting with\n /// `startIndex` to produce indices instead.\n ///\n /// var c = MyFancyCollection([10, 20, 30, 40, 50])\n /// var i = c.startIndex\n /// while i != c.endIndex {\n /// c[i] /= 5\n /// i = c.index(after: i)\n /// }\n /// // c == MyFancyCollection([2, 4, 6, 8, 10])\n var indices: Indices { get }\n\n /// A Boolean value indicating whether the collection is empty.\n ///\n /// When you need to check whether your collection is empty, use the\n /// `isEmpty` property instead of checking that the `count` property is\n /// equal to zero. For collections that don't conform to\n /// `RandomAccessCollection`, accessing the `count` property iterates\n /// through the elements of the collection.\n ///\n /// let horseName = "Silver"\n /// if horseName.isEmpty {\n /// print("My horse has no name.")\n /// } else {\n /// print("Hi ho, \(horseName)!")\n /// }\n /// // Prints "Hi ho, Silver!"\n ///\n /// - Complexity: O(1)\n var isEmpty: Bool { get }\n\n /// The number of elements in the collection.\n ///\n /// To check whether a collection is empty, use its `isEmpty` property\n /// instead of comparing `count` to zero. Unless the collection guarantees\n /// random-access performance, calculating `count` can be an O(*n*)\n /// operation.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length\n /// of the collection.\n var count: Int { get }\n \n // The following requirements enable dispatching for firstIndex(of:) and\n // lastIndex(of:) when the element type is Equatable.\n\n /// Returns `Optional(Optional(index))` if an element was found\n /// or `Optional(nil)` if an element was determined to be missing;\n /// otherwise, `nil`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n func _customIndexOfEquatableElement(_ element: Element) -> Index??\n\n /// Customization point for `Collection.lastIndex(of:)`.\n ///\n /// Define this method if the collection can find an element in less than\n /// O(*n*) by exploiting collection-specific knowledge.\n ///\n /// - Returns: `nil` if a linear search should be attempted instead,\n /// `Optional(nil)` if the element was not found, or\n /// `Optional(Optional(index))` if an element was found.\n ///\n /// - Complexity: Hopefully less than O(`count`).\n func _customLastIndexOfEquatableElement(_ element: Element) -> Index??\n\n /// Returns an index that is the specified distance from the given index.\n ///\n /// The following example obtains an index advanced four positions from a\n /// string's starting index and then prints the character at that position.\n ///\n /// let s = "Swift"\n /// let i = s.index(s.startIndex, offsetBy: 4)\n /// print(s[i])\n /// // Prints "t"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection.\n ///\n /// - Parameters:\n /// - i: A valid index of the collection.\n /// - distance: The distance to offset `i`. `distance` must not be negative\n /// unless the collection conforms to the `BidirectionalCollection`\n /// protocol.\n /// - Returns: An index offset by `distance` from the index `i`. If\n /// `distance` is positive, this is the same value as the result of\n /// `distance` calls to `index(after:)`. If `distance` is negative, this\n /// is the same value as the result of `abs(distance)` calls to\n /// `index(before:)`.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute\n /// value of `distance`.\n func index(_ i: Index, offsetBy distance: Int) -> Index\n\n /// Returns an index that is the specified distance from the given index,\n /// unless that distance is beyond a given limiting index.\n ///\n /// The following example obtains an index advanced four positions from a\n /// string's starting index and then prints the character at that position.\n /// The operation doesn't require going beyond the limiting `s.endIndex`\n /// value, so it succeeds.\n ///\n /// let s = "Swift"\n /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {\n /// print(s[i])\n /// }\n /// // Prints "t"\n ///\n /// The next example attempts to retrieve an index six positions from\n /// `s.startIndex` but fails, because that distance is beyond the index\n /// passed as `limit`.\n ///\n /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)\n /// print(j)\n /// // Prints "nil"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection, unless the index passed as `limit` prevents offsetting\n /// beyond those bounds.\n ///\n /// - Parameters:\n /// - i: A valid index of the collection.\n /// - distance: The distance to offset `i`. `distance` must not be negative\n /// unless the collection conforms to the `BidirectionalCollection`\n /// protocol.\n /// - limit: A valid index of the collection to use as a limit. If\n /// `distance > 0`, a limit that is less than `i` has no effect.\n /// Likewise, if `distance < 0`, a limit that is greater than `i` has no\n /// effect.\n /// - Returns: An index offset by `distance` from the index `i`, unless that\n /// index would be beyond `limit` in the direction of movement. In that\n /// case, the method returns `nil`.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute\n /// value of `distance`.\n func index(\n _ i: Index, offsetBy distance: Int, limitedBy limit: Index\n ) -> Index?\n\n /// Returns the distance between two indices.\n ///\n /// Unless the collection conforms to the `BidirectionalCollection` protocol,\n /// `start` must be less than or equal to `end`.\n ///\n /// - Parameters:\n /// - start: A valid index of the collection.\n /// - end: Another valid index of the collection. If `end` is equal to\n /// `start`, the result is zero.\n /// - Returns: The distance between `start` and `end`. The result can be\n /// negative only if the collection conforms to the\n /// `BidirectionalCollection` protocol.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the\n /// resulting distance.\n func distance(from start: Index, to end: Index) -> Int\n\n /// Performs a range check in O(1), or a no-op when a range check is not\n /// implementable in O(1).\n ///\n /// The range check, if performed, is equivalent to:\n ///\n /// precondition(bounds.contains(index))\n ///\n /// Use this function to perform a cheap range check for QoI purposes when\n /// memory safety is not a concern. Do not rely on this range check for\n /// memory safety.\n ///\n /// The default implementation for forward and bidirectional indices is a\n /// no-op. The default implementation for random access indices performs a\n /// range check.\n ///\n /// - Complexity: O(1).\n func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>)\n\n func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>)\n\n /// Performs a range check in O(1), or a no-op when a range check is not\n /// implementable in O(1).\n ///\n /// The range check, if performed, is equivalent to:\n ///\n /// precondition(\n /// bounds.contains(range.lowerBound) ||\n /// range.lowerBound == bounds.upperBound)\n /// precondition(\n /// bounds.contains(range.upperBound) ||\n /// range.upperBound == bounds.upperBound)\n ///\n /// Use this function to perform a cheap range check for QoI purposes when\n /// memory safety is not a concern. Do not rely on this range check for\n /// memory safety.\n ///\n /// The default implementation for forward and bidirectional indices is a\n /// no-op. The default implementation for random access indices performs a\n /// range check.\n ///\n /// - Complexity: O(1).\n func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>)\n\n /// Returns the position immediately after the given index.\n ///\n /// The successor of an index must be well defined. For an index `i` into a\n /// collection `c`, calling `c.index(after: i)` returns the same index every\n /// time.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be less than\n /// `endIndex`.\n /// - Returns: The index value immediately after `i`.\n func index(after i: Index) -> Index\n\n /// Replaces the given index with its successor.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be less than\n /// `endIndex`.\n func formIndex(after i: inout Index)\n}\n\n/// Default implementation for forward collections.\nextension Collection {\n /// Replaces the given index with its successor.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be less than\n /// `endIndex`.\n @inlinable // protocol-only\n @inline(__always)\n public func formIndex(after i: inout Index) {\n i = index(after: i)\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {\n // FIXME: swift-3-indexing-model: tests.\n _precondition(\n bounds.lowerBound <= index && index < bounds.upperBound,\n "Index out of bounds")\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) {\n // FIXME: swift-3-indexing-model: tests.\n _precondition(\n bounds.lowerBound <= index && index <= bounds.upperBound,\n "Index out of bounds")\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {\n // FIXME: swift-3-indexing-model: tests.\n _precondition(\n bounds.lowerBound <= range.lowerBound &&\n range.upperBound <= bounds.upperBound,\n "Range out of bounds")\n }\n\n /// Returns an index that is the specified distance from the given index.\n ///\n /// The following example obtains an index advanced four positions from a\n /// string's starting index and then prints the character at that position.\n ///\n /// let s = "Swift"\n /// let i = s.index(s.startIndex, offsetBy: 4)\n /// print(s[i])\n /// // Prints "t"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection.\n ///\n /// - Parameters:\n /// - i: A valid index of the collection.\n /// - distance: The distance to offset `i`. `distance` must not be negative\n /// unless the collection conforms to the `BidirectionalCollection`\n /// protocol.\n /// - Returns: An index offset by `distance` from the index `i`. If\n /// `distance` is positive, this is the same value as the result of\n /// `distance` calls to `index(after:)`. If `distance` is negative, this\n /// is the same value as the result of `abs(distance)` calls to\n /// `index(before:)`.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute\n /// value of `distance`.\n @inlinable\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n return self._advanceForward(i, by: distance)\n }\n\n /// Returns an index that is the specified distance from the given index,\n /// unless that distance is beyond a given limiting index.\n ///\n /// The following example obtains an index advanced four positions from a\n /// string's starting index and then prints the character at that position.\n /// The operation doesn't require going beyond the limiting `s.endIndex`\n /// value, so it succeeds.\n ///\n /// let s = "Swift"\n /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {\n /// print(s[i])\n /// }\n /// // Prints "t"\n ///\n /// The next example attempts to retrieve an index six positions from\n /// `s.startIndex` but fails, because that distance is beyond the index\n /// passed as `limit`.\n ///\n /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)\n /// print(j)\n /// // Prints "nil"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection, unless the index passed as `limit` prevents offsetting\n /// beyond those bounds.\n ///\n /// - Parameters:\n /// - i: A valid index of the collection.\n /// - distance: The distance to offset `i`. `distance` must not be negative\n /// unless the collection conforms to the `BidirectionalCollection`\n /// protocol.\n /// - limit: A valid index of the collection to use as a limit. If\n /// `distance > 0`, a limit that is less than `i` has no effect.\n /// Likewise, if `distance < 0`, a limit that is greater than `i` has no\n /// effect.\n /// - Returns: An index offset by `distance` from the index `i`, unless that\n /// index would be beyond `limit` in the direction of movement. In that\n /// case, the method returns `nil`.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute\n /// value of `distance`.\n @inlinable\n public func index(\n _ i: Index, offsetBy distance: Int, limitedBy limit: Index\n ) -> Index? {\n return self._advanceForward(i, by: distance, limitedBy: limit)\n }\n\n /// Offsets the given index by the specified distance.\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection.\n ///\n /// - Parameters:\n /// - i: A valid index of the collection.\n /// - distance: The distance to offset `i`. `distance` must not be negative\n /// unless the collection conforms to the `BidirectionalCollection`\n /// protocol.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute\n /// value of `distance`.\n @inlinable\n public func formIndex(_ i: inout Index, offsetBy distance: Int) {\n i = index(i, offsetBy: distance)\n }\n\n /// Offsets the given index by the specified distance, or so that it equals\n /// the given limiting index.\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection, unless the index passed as `limit` prevents offsetting\n /// beyond those bounds.\n ///\n /// - Parameters:\n /// - i: A valid index of the collection.\n /// - distance: The distance to offset `i`. `distance` must not be negative\n /// unless the collection conforms to the `BidirectionalCollection`\n /// protocol.\n /// - limit: A valid index of the collection to use as a limit. If\n /// `distance > 0`, a limit that is less than `i` has no effect.\n /// Likewise, if `distance < 0`, a limit that is greater than `i` has no\n /// effect.\n /// - Returns: `true` if `i` has been offset by exactly `distance` steps\n /// without going beyond `limit`; otherwise, `false`. When the return\n /// value is `false`, the value of `i` is equal to `limit`.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute\n /// value of `distance`.\n @inlinable\n public func formIndex(\n _ i: inout Index, offsetBy distance: Int, limitedBy limit: Index\n ) -> Bool {\n if let advancedIndex = index(i, offsetBy: distance, limitedBy: limit) {\n i = advancedIndex\n return true\n }\n i = limit\n return false\n }\n\n /// Returns the distance between two indices.\n ///\n /// Unless the collection conforms to the `BidirectionalCollection` protocol,\n /// `start` must be less than or equal to `end`.\n ///\n /// - Parameters:\n /// - start: A valid index of the collection.\n /// - end: Another valid index of the collection. If `end` is equal to\n /// `start`, the result is zero.\n /// - Returns: The distance between `start` and `end`. The result can be\n /// negative only if the collection conforms to the\n /// `BidirectionalCollection` protocol.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the\n /// resulting distance.\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n _precondition(start <= end,\n "Only BidirectionalCollections can have end come before start")\n\n var start = start\n var count = 0\n while start != end {\n count = count + 1\n formIndex(after: &start)\n }\n return count\n }\n\n /// Returns a random element of the collection, using the given generator as\n /// a source for randomness.\n ///\n /// Call `randomElement(using:)` to select a random element from an array or\n /// another collection when you are using a custom random number generator.\n /// This example picks a name at random from an array:\n ///\n /// let names = ["Zoey", "Chloe", "Amani", "Amaia"]\n /// let randomName = names.randomElement(using: &myGenerator)!\n /// // randomName == "Amani"\n ///\n /// - Parameter generator: The random number generator to use when choosing a\n /// random element.\n /// - Returns: A random element from the collection. If the collection is\n /// empty, the method returns `nil`.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length\n /// of the collection.\n /// - Note: The algorithm used to select a random element may change in a\n /// future version of Swift. If you're passing a generator that results in\n /// the same sequence of elements each time you run your program, that\n /// sequence may change when your program is compiled using a different\n /// version of Swift.\n @inlinable\n public func randomElement<T: RandomNumberGenerator>(\n using generator: inout T\n ) -> Element? {\n guard !isEmpty else { return nil }\n let random = Int.random(in: 0 ..< count, using: &generator)\n let idx = index(startIndex, offsetBy: random)\n return self[idx]\n }\n\n /// Returns a random element of the collection.\n ///\n /// Call `randomElement()` to select a random element from an array or\n /// another collection. This example picks a name at random from an array:\n ///\n /// let names = ["Zoey", "Chloe", "Amani", "Amaia"]\n /// let randomName = names.randomElement()!\n /// // randomName == "Amani"\n ///\n /// This method is equivalent to calling `randomElement(using:)`, passing in\n /// the system's default random generator.\n ///\n /// - Returns: A random element from the collection. If the collection is\n /// empty, the method returns `nil`.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length\n /// of the collection.\n @inlinable\n public func randomElement() -> Element? {\n var g = SystemRandomNumberGenerator()\n return randomElement(using: &g)\n }\n\n /// Do not use this method directly; call advanced(by: n) instead.\n @inlinable\n @inline(__always)\n internal func _advanceForward(_ i: Index, by n: Int) -> Index {\n _precondition(n >= 0,\n "Only BidirectionalCollections can be advanced by a negative amount")\n\n var i = i\n for _ in stride(from: 0, to: n, by: 1) {\n formIndex(after: &i)\n }\n return i\n }\n\n /// Do not use this method directly; call advanced(by: n, limit) instead.\n @inlinable\n @inline(__always)\n internal func _advanceForward(\n _ i: Index, by n: Int, limitedBy limit: Index\n ) -> Index? {\n _precondition(n >= 0,\n "Only BidirectionalCollections can be advanced by a negative amount")\n\n var i = i\n for _ in stride(from: 0, to: n, by: 1) {\n if i == limit {\n return nil\n }\n formIndex(after: &i)\n }\n return i\n }\n}\n\n/// Supply the default `makeIterator()` method for `Collection` models\n/// that accept the default associated `Iterator`,\n/// `IndexingIterator<Self>`.\nextension Collection where Iterator == IndexingIterator<Self> {\n /// Returns an iterator over the elements of the collection.\n @inlinable // trivial-implementation\n @inline(__always)\n public __consuming func makeIterator() -> IndexingIterator<Self> {\n return IndexingIterator(_elements: self)\n }\n}\n\n/// Supply the default "slicing" `subscript` for `Collection` models\n/// that accept the default associated `SubSequence`, `Slice<Self>`.\nextension Collection where SubSequence == Slice<Self> {\n /// Accesses a contiguous subrange of the collection's elements.\n ///\n /// The accessed slice uses the same indices for the same elements as the\n /// original collection. Always use the slice's `startIndex` property\n /// instead of assuming that its indices start at a particular value.\n ///\n /// This example demonstrates getting a slice of an array of strings, finding\n /// the index of one of the strings in the slice, and then using that index\n /// in the original array.\n ///\n /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// let streetsSlice = streets[2 ..< streets.endIndex]\n /// print(streetsSlice)\n /// // Prints "["Channing", "Douglas", "Evarts"]"\n ///\n /// let index = streetsSlice.firstIndex(of: "Evarts") // 4\n /// print(streets[index!])\n /// // Prints "Evarts"\n ///\n /// - Parameter bounds: A range of the collection's indices. The bounds of\n /// the range must be valid indices of the collection.\n ///\n /// - Complexity: O(1)\n @inlinable\n public subscript(bounds: Range<Index>) -> Slice<Self> {\n _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)\n return Slice(base: self, bounds: bounds)\n }\n}\n\nextension Collection {\n // This unavailable default implementation of `subscript(bounds: Range<_>)`\n // prevents incomplete Collection implementations from satisfying the\n // protocol through the use of the generic convenience implementation\n // `subscript<R: RangeExpression>(r: R)`. If that were the case, at\n // runtime the generic implementation would call itself\n // in an infinite recursion because of the absence of a better option.\n @available(*, unavailable)\n @_alwaysEmitIntoClient\n public subscript(bounds: Range<Index>) -> SubSequence { fatalError() }\n}\n\nextension Collection where SubSequence == Self {\n /// Removes and returns the first element of the collection.\n ///\n /// - Returns: The first element of the collection if the collection is\n /// not empty; otherwise, `nil`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public mutating func popFirst() -> Element? {\n // TODO: swift-3-indexing-model - review the following\n guard !isEmpty else { return nil }\n let element = first!\n self = self[index(after: startIndex)..<endIndex]\n return element\n }\n}\n\n/// Default implementations of core requirements\nextension Collection {\n /// A Boolean value indicating whether the collection is empty.\n ///\n /// When you need to check whether your collection is empty, use the\n /// `isEmpty` property instead of checking that the `count` property is\n /// equal to zero. For collections that don't conform to\n /// `RandomAccessCollection`, accessing the `count` property iterates\n /// through the elements of the collection.\n ///\n /// let horseName = "Silver"\n /// if horseName.isEmpty {\n /// print("My horse has no name.")\n /// } else {\n /// print("Hi ho, \(horseName)!")\n /// }\n /// // Prints "Hi ho, Silver!")\n ///\n /// - Complexity: O(1)\n @inlinable\n public var isEmpty: Bool {\n return startIndex == endIndex\n }\n\n /// The first element of the collection.\n ///\n /// If the collection is empty, the value of this property is `nil`.\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// if let firstNumber = numbers.first {\n /// print(firstNumber)\n /// }\n /// // Prints "10"\n @inlinable\n public var first: Element? {\n let start = startIndex\n if start != endIndex { return self[start] }\n else { return nil }\n }\n\n /// A value less than or equal to the number of elements in the collection.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length\n /// of the collection.\n @inlinable\n public var underestimatedCount: Int {\n // TODO: swift-3-indexing-model - review the following\n return count\n }\n\n /// The number of elements in the collection.\n ///\n /// To check whether a collection is empty, use its `isEmpty` property\n /// instead of comparing `count` to zero. Unless the collection guarantees\n /// random-access performance, calculating `count` can be an O(*n*)\n /// operation.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length\n /// of the collection.\n @inlinable\n public var count: Int {\n return distance(from: startIndex, to: endIndex)\n }\n\n // TODO: swift-3-indexing-model - rename the following to _customIndexOfEquatable(element)?\n /// Customization point for `Collection.firstIndex(of:)`.\n ///\n /// Define this method if the collection can find an element in less than\n /// O(*n*) by exploiting collection-specific knowledge.\n ///\n /// - Returns: `nil` if a linear search should be attempted instead,\n /// `Optional(nil)` if the element was not found, or\n /// `Optional(Optional(index))` if an element was found.\n ///\n /// - Complexity: Hopefully less than O(`count`).\n @inlinable\n @inline(__always)\n public // dispatching\n func _customIndexOfEquatableElement(_: Element) -> Index?? {\n return nil\n }\n\n /// Customization point for `Collection.lastIndex(of:)`.\n ///\n /// Define this method if the collection can find an element in less than\n /// O(*n*) by exploiting collection-specific knowledge.\n ///\n /// - Returns: `nil` if a linear search should be attempted instead,\n /// `Optional(nil)` if the element was not found, or\n /// `Optional(Optional(index))` if an element was found.\n ///\n /// - Complexity: Hopefully less than O(`count`).\n @inlinable\n @inline(__always)\n public // dispatching\n func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? {\n return nil\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Default implementations for Collection\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns an array containing the results of mapping the given closure\n /// over the sequence's elements.\n ///\n /// In this example, `map` is used first to convert the names in the array\n /// to lowercase strings and then to count their characters.\n ///\n /// let cast = ["Vivien", "Marlon", "Kim", "Karl"]\n /// let lowercaseNames = cast.map { $0.lowercased() }\n /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]\n /// let letterCounts = cast.map { $0.count }\n /// // 'letterCounts' == [6, 6, 3, 4]\n ///\n /// - Parameter transform: A mapping closure. `transform` accepts an\n /// element of this sequence as its parameter and returns a transformed\n /// value of the same or of a different type.\n /// - Returns: An array containing the transformed elements of this\n /// sequence.\n @inlinable\n @_alwaysEmitIntoClient\n public func map<T, E>(\n _ transform: (Element) throws(E) -> T\n ) throws(E) -> [T] {\n // TODO: swift-3-indexing-model - review the following\n let n = self.count\n if n == 0 {\n return []\n }\n\n var result = ContiguousArray<T>()\n result.reserveCapacity(n)\n\n var i = self.startIndex\n\n for _ in 0..<n {\n result.append(try transform(self[i]))\n formIndex(after: &i)\n }\n\n _expectEnd(of: self, is: i)\n return Array(result)\n }\n\n // ABI-only entrypoint for the rethrows version of map, which has been\n // superseded by the typed-throws version. Expressed as "throws", which is\n // ABI-compatible with "rethrows".\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @usableFromInline\n @_silgen_name("$sSlsE3mapySayqd__Gqd__7ElementQzKXEKlF")\n func __rethrows_map<T>(\n _ transform: (Element) throws -> T\n ) throws -> [T] {\n try map(transform)\n }\n\n /// Returns a subsequence containing all but the given number of initial\n /// elements.\n ///\n /// If the number of elements to drop exceeds the number of elements in\n /// the collection, the result is an empty subsequence.\n ///\n /// let numbers = [1, 2, 3, 4, 5]\n /// print(numbers.dropFirst(2))\n /// // Prints "[3, 4, 5]"\n /// print(numbers.dropFirst(10))\n /// // Prints "[]"\n ///\n /// - Parameter k: The number of elements to drop from the beginning of\n /// the collection. `k` must be greater than or equal to zero.\n /// - Returns: A subsequence starting after the specified number of\n /// elements.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of\n /// elements to drop from the beginning of the collection.\n @inlinable\n public __consuming func dropFirst(_ k: Int = 1) -> SubSequence {\n _precondition(k >= 0, "Can't drop a negative number of elements from a collection")\n let start = index(startIndex, offsetBy: k, limitedBy: endIndex) ?? endIndex\n return self[start..<endIndex]\n }\n\n /// Returns a subsequence containing all but the specified number of final\n /// elements.\n ///\n /// If the number of elements to drop exceeds the number of elements in the\n /// collection, the result is an empty subsequence.\n ///\n /// let numbers = [1, 2, 3, 4, 5]\n /// print(numbers.dropLast(2))\n /// // Prints "[1, 2, 3]"\n /// print(numbers.dropLast(10))\n /// // Prints "[]"\n ///\n /// - Parameter k: The number of elements to drop off the end of the\n /// collection. `k` must be greater than or equal to zero.\n /// - Returns: A subsequence that leaves off the specified number of elements\n /// at the end.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length of\n /// the collection.\n @inlinable\n public __consuming func dropLast(_ k: Int = 1) -> SubSequence {\n _precondition(\n k >= 0, "Can't drop a negative number of elements from a collection")\n let amount = Swift.max(0, count - k)\n let end = index(startIndex,\n offsetBy: amount, limitedBy: endIndex) ?? endIndex\n return self[startIndex..<end]\n }\n \n /// Returns a subsequence by skipping elements while `predicate` returns\n /// `true` and returning the remaining elements.\n ///\n /// - Parameter predicate: A closure that takes an element of the\n /// sequence as its argument and returns `true` if the element should\n /// be skipped or `false` if it should be included. Once the predicate\n /// returns `false` it will not be called again.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public __consuming func drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> SubSequence {\n var start = startIndex\n while try start != endIndex && predicate(self[start]) {\n formIndex(after: &start)\n } \n return self[start..<endIndex]\n }\n\n /// Returns a subsequence, up to the specified maximum length, containing\n /// the initial elements of the collection.\n ///\n /// If the maximum length exceeds the number of elements in the collection,\n /// the result contains all the elements in the collection.\n ///\n /// let numbers = [1, 2, 3, 4, 5]\n /// print(numbers.prefix(2))\n /// // Prints "[1, 2]"\n /// print(numbers.prefix(10))\n /// // Prints "[1, 2, 3, 4, 5]"\n ///\n /// - Parameter maxLength: The maximum number of elements to return.\n /// `maxLength` must be greater than or equal to zero.\n /// - Returns: A subsequence starting at the beginning of this collection\n /// with at most `maxLength` elements.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of\n /// elements to select from the beginning of the collection.\n @inlinable\n public __consuming func prefix(_ maxLength: Int) -> SubSequence {\n _precondition(\n maxLength >= 0,\n "Can't take a prefix of negative length from a collection")\n let end = index(startIndex,\n offsetBy: maxLength, limitedBy: endIndex) ?? endIndex\n return self[startIndex..<end]\n }\n \n /// Returns a subsequence containing the initial elements until `predicate`\n /// returns `false` and skipping the remaining elements.\n ///\n /// - Parameter predicate: A closure that takes an element of the\n /// sequence as its argument and returns `true` if the element should\n /// be included or `false` if it should be excluded. Once the predicate\n /// returns `false` it will not be called again.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public __consuming func prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> SubSequence {\n var end = startIndex\n while try end != endIndex && predicate(self[end]) {\n formIndex(after: &end)\n }\n return self[startIndex..<end]\n }\n\n /// Returns a subsequence, up to the given maximum length, containing the\n /// final elements of the collection.\n ///\n /// If the maximum length exceeds the number of elements in the collection,\n /// the result contains all the elements in the collection.\n ///\n /// let numbers = [1, 2, 3, 4, 5]\n /// print(numbers.suffix(2))\n /// // Prints "[4, 5]"\n /// print(numbers.suffix(10))\n /// // Prints "[1, 2, 3, 4, 5]"\n ///\n /// - Parameter maxLength: The maximum number of elements to return. The\n /// value of `maxLength` must be greater than or equal to zero.\n /// - Returns: A subsequence terminating at the end of the collection with at\n /// most `maxLength` elements.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length of\n /// the collection.\n @inlinable\n public __consuming func suffix(_ maxLength: Int) -> SubSequence {\n _precondition(\n maxLength >= 0,\n "Can't take a suffix of negative length from a collection")\n let amount = Swift.max(0, count - maxLength)\n let start = index(startIndex,\n offsetBy: amount, limitedBy: endIndex) ?? endIndex\n return self[start..<endIndex]\n }\n\n /// Returns a subsequence from the start of the collection up to, but not\n /// including, the specified position.\n ///\n /// The resulting subsequence *does not include* the element at the position\n /// `end`. The following example searches for the index of the number `40`\n /// in an array of integers, and then prints the prefix of the array up to,\n /// but not including, that index:\n ///\n /// let numbers = [10, 20, 30, 40, 50, 60]\n /// if let i = numbers.firstIndex(of: 40) {\n /// print(numbers.prefix(upTo: i))\n /// }\n /// // Prints "[10, 20, 30]"\n ///\n /// Passing the collection's starting index as the `end` parameter results in\n /// an empty subsequence.\n ///\n /// print(numbers.prefix(upTo: numbers.startIndex))\n /// // Prints "[]"\n ///\n /// Using the `prefix(upTo:)` method is equivalent to using a partial\n /// half-open range as the collection's subscript. The subscript notation is\n /// preferred over `prefix(upTo:)`.\n ///\n /// if let i = numbers.firstIndex(of: 40) {\n /// print(numbers[..<i])\n /// }\n /// // Prints "[10, 20, 30]"\n ///\n /// - Parameter end: The "past the end" index of the resulting subsequence.\n /// `end` must be a valid index of the collection.\n /// - Returns: A subsequence up to, but not including, the `end` position.\n ///\n /// - Complexity: O(1)\n @inlinable\n public __consuming func prefix(upTo end: Index) -> SubSequence {\n return self[startIndex..<end]\n }\n\n /// Returns a subsequence from the specified position to the end of the\n /// collection.\n ///\n /// The following example searches for the index of the number `40` in an\n /// array of integers, and then prints the suffix of the array starting at\n /// that index:\n ///\n /// let numbers = [10, 20, 30, 40, 50, 60]\n /// if let i = numbers.firstIndex(of: 40) {\n /// print(numbers.suffix(from: i))\n /// }\n /// // Prints "[40, 50, 60]"\n ///\n /// Passing the collection's `endIndex` as the `start` parameter results in\n /// an empty subsequence.\n ///\n /// print(numbers.suffix(from: numbers.endIndex))\n /// // Prints "[]"\n ///\n /// Using the `suffix(from:)` method is equivalent to using a partial range\n /// from the index as the collection's subscript. The subscript notation is\n /// preferred over `suffix(from:)`.\n ///\n /// if let i = numbers.firstIndex(of: 40) {\n /// print(numbers[i...])\n /// }\n /// // Prints "[40, 50, 60]"\n ///\n /// - Parameter start: The index at which to start the resulting subsequence.\n /// `start` must be a valid index of the collection.\n /// - Returns: A subsequence starting at the `start` position.\n ///\n /// - Complexity: O(1)\n @inlinable\n public __consuming func suffix(from start: Index) -> SubSequence {\n return self[start..<endIndex]\n }\n\n /// Returns a subsequence from the start of the collection through the\n /// specified position.\n ///\n /// The resulting subsequence *includes* the element at the position\n /// specified by the `through` parameter.\n /// The following example searches for the index of the number `40` in an\n /// array of integers, and then prints the prefix of the array up to, and\n /// including, that index:\n ///\n /// let numbers = [10, 20, 30, 40, 50, 60]\n /// if let i = numbers.firstIndex(of: 40) {\n /// print(numbers.prefix(through: i))\n /// }\n /// // Prints "[10, 20, 30, 40]"\n ///\n /// Using the `prefix(through:)` method is equivalent to using a partial\n /// closed range as the collection's subscript. The subscript notation is\n /// preferred over `prefix(through:)`.\n ///\n /// if let i = numbers.firstIndex(of: 40) {\n /// print(numbers[...i])\n /// }\n /// // Prints "[10, 20, 30, 40]"\n ///\n /// - Parameter position: The index of the last element to include in the\n /// resulting subsequence. `position` must be a valid index of the collection\n /// that is not equal to the `endIndex` property.\n /// - Returns: A subsequence up to, and including, the given position.\n ///\n /// - Complexity: O(1)\n @inlinable\n public __consuming func prefix(through position: Index) -> SubSequence {\n return prefix(upTo: index(after: position))\n }\n\n /// Returns the longest possible subsequences of the collection, in order,\n /// that don't contain elements satisfying the given predicate.\n ///\n /// The resulting array consists of at most `maxSplits + 1` subsequences.\n /// Elements that are used to split the sequence are not returned as part of\n /// any subsequence.\n ///\n /// The following examples show the effects of the `maxSplits` and\n /// `omittingEmptySubsequences` parameters when splitting a string using a\n /// closure that matches spaces. The first use of `split` returns each word\n /// that was originally separated by one or more spaces.\n ///\n /// let line = "BLANCHE: I don't want realism. I want magic!"\n /// print(line.split(whereSeparator: { $0 == " " }))\n /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"\n ///\n /// The second example passes `1` for the `maxSplits` parameter, so the\n /// original string is split just once, into two new strings.\n ///\n /// print(line.split(maxSplits: 1, whereSeparator: { $0 == " " }))\n /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"\n ///\n /// The final example passes `false` for the `omittingEmptySubsequences`\n /// parameter, so the returned array contains empty strings where spaces\n /// were repeated.\n ///\n /// print(line.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }))\n /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"\n ///\n /// - Parameters:\n /// - maxSplits: The maximum number of times to split the collection, or\n /// one less than the number of subsequences to return. If\n /// `maxSplits + 1` subsequences are returned, the last one is a suffix\n /// of the original collection containing the remaining elements.\n /// `maxSplits` must be greater than or equal to zero. The default value\n /// is `Int.max`.\n /// - omittingEmptySubsequences: If `false`, an empty subsequence is\n /// returned in the result for each pair of consecutive elements\n /// satisfying the `isSeparator` predicate and for each element at the\n /// start or end of the collection satisfying the `isSeparator`\n /// predicate. The default value is `true`.\n /// - isSeparator: A closure that takes an element as an argument and\n /// returns a Boolean value indicating whether the collection should be\n /// split at that element.\n /// - Returns: An array of subsequences, split from this collection's\n /// elements.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public __consuming func split(\n maxSplits: Int = Int.max,\n omittingEmptySubsequences: Bool = true,\n whereSeparator isSeparator: (Element) throws -> Bool\n ) rethrows -> [SubSequence] {\n // TODO: swift-3-indexing-model - review the following\n _precondition(maxSplits >= 0, "Must take zero or more splits")\n\n var result: [SubSequence] = []\n var subSequenceStart: Index = startIndex\n\n func appendSubsequence(end: Index) -> Bool {\n if subSequenceStart == end && omittingEmptySubsequences {\n return false\n }\n result.append(self[subSequenceStart..<end])\n return true\n }\n\n if maxSplits == 0 || isEmpty {\n _ = appendSubsequence(end: endIndex)\n return result\n }\n\n var subSequenceEnd = subSequenceStart\n let cachedEndIndex = endIndex\n while subSequenceEnd != cachedEndIndex {\n if try isSeparator(self[subSequenceEnd]) {\n let didAppend = appendSubsequence(end: subSequenceEnd)\n formIndex(after: &subSequenceEnd)\n subSequenceStart = subSequenceEnd\n if didAppend && result.count == maxSplits {\n break\n }\n continue\n }\n formIndex(after: &subSequenceEnd)\n }\n\n if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences {\n result.append(self[subSequenceStart..<cachedEndIndex])\n }\n\n return result\n }\n}\n\nextension Collection where Element: Equatable {\n /// Returns the longest possible subsequences of the collection, in order,\n /// around elements equal to the given element.\n ///\n /// The resulting array consists of at most `maxSplits + 1` subsequences.\n /// Elements that are used to split the collection are not returned as part\n /// of any subsequence.\n ///\n /// The following examples show the effects of the `maxSplits` and\n /// `omittingEmptySubsequences` parameters when splitting a string at each\n /// space character (" "). The first use of `split` returns each word that\n /// was originally separated by one or more spaces.\n ///\n /// let line = "BLANCHE: I don't want realism. I want magic!"\n /// print(line.split(separator: " "))\n /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"\n ///\n /// The second example passes `1` for the `maxSplits` parameter, so the\n /// original string is split just once, into two new strings.\n ///\n /// print(line.split(separator: " ", maxSplits: 1))\n /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"\n ///\n /// The final example passes `false` for the `omittingEmptySubsequences`\n /// parameter, so the returned array contains empty strings where spaces\n /// were repeated.\n ///\n /// print(line.split(separator: " ", omittingEmptySubsequences: false))\n /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"\n ///\n /// - Parameters:\n /// - separator: The element that should be split upon.\n /// - maxSplits: The maximum number of times to split the collection, or\n /// one less than the number of subsequences to return. If\n /// `maxSplits + 1` subsequences are returned, the last one is a suffix\n /// of the original collection containing the remaining elements.\n /// `maxSplits` must be greater than or equal to zero. The default value\n /// is `Int.max`.\n /// - omittingEmptySubsequences: If `false`, an empty subsequence is\n /// returned in the result for each consecutive pair of `separator`\n /// elements in the collection and for each instance of `separator` at\n /// the start or end of the collection. If `true`, only nonempty\n /// subsequences are returned. The default value is `true`.\n /// - Returns: An array of subsequences, split from this collection's\n /// elements.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public __consuming func split(\n separator: Element,\n maxSplits: Int = Int.max,\n omittingEmptySubsequences: Bool = true\n ) -> [SubSequence] {\n // TODO: swift-3-indexing-model - review the following\n return split(\n maxSplits: maxSplits,\n omittingEmptySubsequences: omittingEmptySubsequences,\n whereSeparator: { $0 == separator })\n }\n}\n\nextension Collection where SubSequence == Self {\n /// Removes and returns the first element of the collection.\n ///\n /// The collection must not be empty.\n ///\n /// - Returns: The first element of the collection.\n ///\n /// - Complexity: O(1)\n @inlinable\n @discardableResult\n public mutating func removeFirst() -> Element {\n // TODO: swift-3-indexing-model - review the following\n _precondition(!isEmpty, "Can't remove items from an empty collection")\n let element = first!\n self = self[index(after: startIndex)..<endIndex]\n return element\n }\n\n /// Removes the specified number of elements from the beginning of the\n /// collection.\n ///\n /// - Parameter k: The number of elements to remove. `k` must be greater than\n /// or equal to zero, and must be less than or equal to the number of\n /// elements in the collection.\n ///\n /// - Complexity: O(1) if the collection conforms to\n /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the specified\n /// number of elements.\n @inlinable\n public mutating func removeFirst(_ k: Int) {\n if k == 0 { return }\n _precondition(k >= 0, "Number of elements to remove should be non-negative")\n guard let idx = index(startIndex, offsetBy: k, limitedBy: endIndex) else {\n _preconditionFailure(\n "Can't remove more items from a collection than it contains")\n }\n self = self[idx..<endIndex]\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Collection.swift | cpp_apple_swift_stdlib_public_core_Collection.swift | Swift | 66,919 | 0.75 | 0.093325 | 0.748291 | react-lib | 143 | 2025-07-01T01:11:33.352063 | BSD-3-Clause | false | 218b9bd628ed7d9061a9127d9a065249 |
//===--- CollectionAlgorithms.swift ---------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// last\n//===----------------------------------------------------------------------===//\n\nextension BidirectionalCollection {\n /// The last element of the collection.\n ///\n /// If the collection is empty, the value of this property is `nil`.\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// if let lastNumber = numbers.last {\n /// print(lastNumber)\n /// }\n /// // Prints "50"\n ///\n /// - Complexity: O(1)\n @inlinable\n public var last: Element? {\n return isEmpty ? nil : self[index(before: endIndex)]\n }\n}\n\n//===----------------------------------------------------------------------===//\n// firstIndex(of:)/firstIndex(where:)\n//===----------------------------------------------------------------------===//\n\nextension Collection where Element: Equatable {\n /// Returns the first index where the specified value appears in the\n /// collection.\n ///\n /// After using `firstIndex(of:)` to find the position of a particular element\n /// in a collection, you can use it to access the element by subscripting.\n /// This example shows how you can modify one of the names in an array of\n /// students.\n ///\n /// var students = ["Ben", "Ivy", "Jordell", "Maxime"]\n /// if let i = students.firstIndex(of: "Maxime") {\n /// students[i] = "Max"\n /// }\n /// print(students)\n /// // Prints "["Ben", "Ivy", "Jordell", "Max"]"\n ///\n /// - Parameter element: An element to search for in the collection.\n /// - Returns: The first index where `element` is found. If `element` is not\n /// found in the collection, returns `nil`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func firstIndex(of element: Element) -> Index? {\n if let result = _customIndexOfEquatableElement(element) {\n return result\n }\n\n var i = self.startIndex\n while i != self.endIndex {\n if self[i] == element {\n return i\n }\n self.formIndex(after: &i)\n }\n return nil\n }\n}\n\nextension Collection {\n /// Returns the first index in which an element of the collection satisfies\n /// the given predicate.\n ///\n /// You can use the predicate to find an element of a type that doesn't\n /// conform to the `Equatable` protocol or to find an element that matches\n /// particular criteria. Here's an example that finds a student name that\n /// begins with the letter "A":\n ///\n /// let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]\n /// if let i = students.firstIndex(where: { $0.hasPrefix("A") }) {\n /// print("\(students[i]) starts with 'A'!")\n /// }\n /// // Prints "Abena starts with 'A'!"\n ///\n /// - Parameter predicate: A closure that takes an element as its argument\n /// and returns a Boolean value that indicates whether the passed element\n /// represents a match.\n /// - Returns: The index of the first element for which `predicate` returns\n /// `true`. If no elements in the collection satisfy the given predicate,\n /// returns `nil`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func firstIndex(\n where predicate: (Element) throws -> Bool\n ) rethrows -> Index? {\n var i = self.startIndex\n while i != self.endIndex {\n if try predicate(self[i]) {\n return i\n }\n self.formIndex(after: &i)\n }\n return nil\n }\n}\n\n//===----------------------------------------------------------------------===//\n// lastIndex(of:)/lastIndex(where:)\n//===----------------------------------------------------------------------===//\n\nextension BidirectionalCollection {\n /// Returns the last element of the sequence that satisfies the given\n /// predicate.\n ///\n /// This example uses the `last(where:)` method to find the last\n /// negative number in an array of integers:\n ///\n /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]\n /// if let lastNegative = numbers.last(where: { $0 < 0 }) {\n /// print("The last negative number is \(lastNegative).")\n /// }\n /// // Prints "The last negative number is -6."\n ///\n /// - Parameter predicate: A closure that takes an element of the sequence as\n /// its argument and returns a Boolean value indicating whether the\n /// element is a match.\n /// - Returns: The last element of the sequence that satisfies `predicate`,\n /// or `nil` if there is no element that satisfies `predicate`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func last(\n where predicate: (Element) throws -> Bool\n ) rethrows -> Element? {\n return try lastIndex(where: predicate).map { self[$0] }\n }\n\n /// Returns the index of the last element in the collection that matches the\n /// given predicate.\n ///\n /// You can use the predicate to find an element of a type that doesn't\n /// conform to the `Equatable` protocol or to find an element that matches\n /// particular criteria. This example finds the index of the last name that\n /// begins with the letter *A:*\n ///\n /// let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]\n /// if let i = students.lastIndex(where: { $0.hasPrefix("A") }) {\n /// print("\(students[i]) starts with 'A'!")\n /// }\n /// // Prints "Akosua starts with 'A'!"\n ///\n /// - Parameter predicate: A closure that takes an element as its argument\n /// and returns a Boolean value that indicates whether the passed element\n /// represents a match.\n /// - Returns: The index of the last element in the collection that matches\n /// `predicate`, or `nil` if no elements match.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func lastIndex(\n where predicate: (Element) throws -> Bool\n ) rethrows -> Index? {\n var i = endIndex\n while i != startIndex {\n formIndex(before: &i)\n if try predicate(self[i]) {\n return i\n }\n }\n return nil\n }\n}\n\nextension BidirectionalCollection where Element: Equatable {\n /// Returns the last index where the specified value appears in the\n /// collection.\n ///\n /// After using `lastIndex(of:)` to find the position of the last instance of\n /// a particular element in a collection, you can use it to access the\n /// element by subscripting. This example shows how you can modify one of\n /// the names in an array of students.\n ///\n /// var students = ["Ben", "Ivy", "Jordell", "Ben", "Maxime"]\n /// if let i = students.lastIndex(of: "Ben") {\n /// students[i] = "Benjamin"\n /// }\n /// print(students)\n /// // Prints "["Ben", "Ivy", "Jordell", "Benjamin", "Max"]"\n ///\n /// - Parameter element: An element to search for in the collection.\n /// - Returns: The last index where `element` is found. If `element` is not\n /// found in the collection, this method returns `nil`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public func lastIndex(of element: Element) -> Index? {\n if let result = _customLastIndexOfEquatableElement(element) {\n return result\n }\n return lastIndex(where: { $0 == element })\n }\n}\n\n//===----------------------------------------------------------------------===//\n// indices(where:) / indices(of:)\n//===----------------------------------------------------------------------===//\n\n#if !$Embedded\nextension Collection {\n /// Returns the indices of all the elements that match the given predicate.\n ///\n /// For example, you can use this method to find all the places that a\n /// vowel occurs in a string.\n ///\n /// let str = "Fresh cheese in a breeze"\n /// let vowels: Set<Character> = ["a", "e", "i", "o", "u"]\n /// let allTheVowels = str.indices(where: { vowels.contains($0) })\n /// // str[allTheVowels].count == 9\n ///\n /// - Parameter predicate: A closure that takes an element as its argument\n /// and returns a Boolean value that indicates whether the passed element\n /// represents a match.\n /// - Returns: A set of the indices of the elements for which `predicate`\n /// returns `true`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @available(SwiftStdlib 6.0, *)\n @inlinable\n public func indices(\n where predicate: (Element) throws -> Bool\n ) rethrows -> RangeSet<Index> {\n var result: [Range<Index>] = []\n var end = startIndex\n while let begin = try self[end...].firstIndex(where: predicate) {\n end = try self[begin...].prefix(while: predicate).endIndex\n result.append(begin ..< end)\n\n guard end < self.endIndex else {\n break\n }\n self.formIndex(after: &end)\n }\n\n return RangeSet(_orderedRanges: result)\n }\n}\n\nextension Collection where Element: Equatable {\n /// Returns the indices of all the elements that are equal to the given\n /// element.\n ///\n /// For example, you can use this method to find all the places that a\n /// particular letter occurs in a string.\n ///\n /// let str = "Fresh cheese in a breeze"\n /// let allTheEs = str.indices(of: "e")\n /// // str[allTheEs].count == 7\n ///\n /// - Parameter element: An element to look for in the collection.\n /// - Returns: A set of the indices of the elements that are equal to\n /// `element`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @available(SwiftStdlib 6.0, *)\n @inlinable\n public func indices(of element: Element) -> RangeSet<Index> {\n indices(where: { $0 == element })\n }\n}\n#endif\n\n//===----------------------------------------------------------------------===//\n// partition(by:)\n//===----------------------------------------------------------------------===//\n\nextension MutableCollection {\n /// Reorders the elements of the collection such that all the elements\n /// that match the given predicate are after all the elements that don't\n /// match.\n ///\n /// After partitioning a collection, there is a pivot index `p` where\n /// no element before `p` satisfies the `belongsInSecondPartition`\n /// predicate and every element at or after `p` satisfies\n /// `belongsInSecondPartition`. This operation isn't guaranteed to be\n /// stable, so the relative ordering of elements within the partitions might\n /// change.\n ///\n /// In the following example, an array of numbers is partitioned by a\n /// predicate that matches elements greater than 30.\n ///\n /// var numbers = [30, 40, 20, 30, 30, 60, 10]\n /// let p = numbers.partition(by: { $0 > 30 })\n /// // p == 5\n /// // numbers == [30, 10, 20, 30, 30, 60, 40]\n ///\n /// The `numbers` array is now arranged in two partitions. The first\n /// partition, `numbers[..<p]`, is made up of the elements that\n /// are not greater than 30. The second partition, `numbers[p...]`,\n /// is made up of the elements that *are* greater than 30.\n ///\n /// let first = numbers[..<p]\n /// // first == [30, 10, 20, 30, 30]\n /// let second = numbers[p...]\n /// // second == [60, 40]\n ///\n /// Note that the order of elements in both partitions changed.\n /// That is, `40` appears before `60` in the original collection,\n /// but, after calling `partition(by:)`, `60` appears before `40`.\n ///\n /// - Parameter belongsInSecondPartition: A predicate used to partition\n /// the collection. All elements satisfying this predicate are ordered\n /// after all elements not satisfying it.\n /// - Returns: The index of the first element in the reordered collection\n /// that matches `belongsInSecondPartition`. If no elements in the\n /// collection match `belongsInSecondPartition`, the returned index is\n /// equal to the collection's `endIndex`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public mutating func partition(\n by belongsInSecondPartition: (Element) throws -> Bool\n ) rethrows -> Index {\n return try _halfStablePartition(isSuffixElement: belongsInSecondPartition)\n }\n\n /// Moves all elements satisfying `isSuffixElement` into a suffix of the\n /// collection, returning the start position of the resulting suffix.\n ///\n /// - Complexity: O(*n*) where n is the length of the collection.\n @inlinable\n internal mutating func _halfStablePartition(\n isSuffixElement: (Element) throws -> Bool\n ) rethrows -> Index {\n guard var i = try firstIndex(where: isSuffixElement)\n else { return endIndex }\n \n var j = index(after: i)\n while j != endIndex {\n if try !isSuffixElement(self[j]) { swapAt(i, j); formIndex(after: &i) }\n formIndex(after: &j)\n }\n return i\n } \n}\n\nextension MutableCollection where Self: BidirectionalCollection {\n /// Reorders the elements of the collection such that all the elements\n /// that match the given predicate are after all the elements that don't\n /// match.\n ///\n /// After partitioning a collection, there is a pivot index `p` where\n /// no element before `p` satisfies the `belongsInSecondPartition`\n /// predicate and every element at or after `p` satisfies\n /// `belongsInSecondPartition`. This operation isn't guaranteed to be\n /// stable, so the relative ordering of elements within the partitions might\n /// change.\n ///\n /// In the following example, an array of numbers is partitioned by a\n /// predicate that matches elements greater than 30.\n ///\n /// var numbers = [30, 40, 20, 30, 30, 60, 10]\n /// let p = numbers.partition(by: { $0 > 30 })\n /// // p == 5\n /// // numbers == [30, 10, 20, 30, 30, 60, 40]\n ///\n /// The `numbers` array is now arranged in two partitions. The first\n /// partition, `numbers[..<p]`, is made up of the elements that\n /// are not greater than 30. The second partition, `numbers[p...]`,\n /// is made up of the elements that *are* greater than 30.\n ///\n /// let first = numbers[..<p]\n /// // first == [30, 10, 20, 30, 30]\n /// let second = numbers[p...]\n /// // second == [60, 40]\n ///\n /// Note that the order of elements in both partitions changed.\n /// That is, `40` appears before `60` in the original collection,\n /// but, after calling `partition(by:)`, `60` appears before `40`.\n ///\n /// - Parameter belongsInSecondPartition: A predicate used to partition\n /// the collection. All elements satisfying this predicate are ordered\n /// after all elements not satisfying it.\n /// - Returns: The index of the first element in the reordered collection\n /// that matches `belongsInSecondPartition`. If no elements in the\n /// collection match `belongsInSecondPartition`, the returned index is\n /// equal to the collection's `endIndex`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public mutating func partition(\n by belongsInSecondPartition: (Element) throws -> Bool\n ) rethrows -> Index {\n let maybeOffset = try unsafe withContiguousMutableStorageIfAvailable {\n (bufferPointer) -> Int in\n let unsafeBufferPivot = try unsafe bufferPointer._partitionImpl(\n by: belongsInSecondPartition)\n return unsafeBufferPivot - bufferPointer.startIndex\n }\n if let offset = maybeOffset {\n return index(startIndex, offsetBy: offset)\n } else {\n return try _partitionImpl(by: belongsInSecondPartition)\n }\n }\n\n @inlinable\n internal mutating func _partitionImpl(\n by belongsInSecondPartition: (Element) throws -> Bool\n ) rethrows -> Index {\n var lo = startIndex\n var hi = endIndex\n while true {\n // Invariants at this point:\n //\n // * `lo <= hi`\n // * all elements in `startIndex ..< lo` belong in the first partition\n // * all elements in `hi ..< endIndex` belong in the second partition\n\n // Find next element from `lo` that may not be in the right place.\n while true {\n guard lo < hi else { return lo }\n if try belongsInSecondPartition(self[lo]) { break }\n formIndex(after: &lo)\n }\n\n // Find next element down from `hi` that we can swap `lo` with.\n while true {\n formIndex(before: &hi)\n guard lo < hi else { return lo }\n if try !belongsInSecondPartition(self[hi]) { break }\n }\n\n swapAt(lo, hi)\n formIndex(after: &lo)\n }\n fatalError()\n }\n}\n\n//===----------------------------------------------------------------------===//\n// _indexedStablePartition / _partitioningIndex\n//===----------------------------------------------------------------------===//\n\nextension MutableCollection {\n /// Moves all elements at the indices satisfying `belongsInSecondPartition`\n /// into a suffix of the collection, preserving their relative order, and\n /// returns the start of the resulting suffix.\n ///\n /// - Complexity: O(*n* log *n*) where *n* is the number of elements.\n /// - Precondition:\n /// `n == distance(from: range.lowerBound, to: range.upperBound)`\n internal mutating func _indexedStablePartition(\n count n: Int,\n range: Range<Index>,\n by belongsInSecondPartition: (Index) throws-> Bool\n ) rethrows -> Index {\n if n == 0 { return range.lowerBound }\n if n == 1 {\n return try belongsInSecondPartition(range.lowerBound)\n ? range.lowerBound\n : range.upperBound\n }\n let h = n / 2, i = index(range.lowerBound, offsetBy: h)\n let j = try _indexedStablePartition(\n count: h,\n range: range.lowerBound..<i,\n by: belongsInSecondPartition)\n let k = try _indexedStablePartition(\n count: n - h,\n range: i..<range.upperBound,\n by: belongsInSecondPartition)\n return _rotate(in: j..<k, shiftingToStart: i)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// _partitioningIndex(where:)\n//===----------------------------------------------------------------------===//\n\nextension Collection {\n /// Returns the index of the first element in the collection that matches\n /// the predicate.\n ///\n /// The collection must already be partitioned according to the predicate.\n /// That is, there should be an index `i` where for every element in\n /// `collection[..<i]` the predicate is `false`, and for every element\n /// in `collection[i...]` the predicate is `true`.\n ///\n /// - Parameter predicate: A predicate that partitions the collection.\n /// - Returns: The index of the first element in the collection for which\n /// `predicate` returns `true`.\n ///\n /// - Complexity: O(log *n*), where *n* is the length of this collection if\n /// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).\n internal func _partitioningIndex(\n where predicate: (Element) throws -> Bool\n ) rethrows -> Index {\n var n = count\n var l = startIndex\n \n while n > 0 {\n let half = n / 2\n let mid = index(l, offsetBy: half)\n if try predicate(self[mid]) {\n n = half\n } else {\n l = index(after: mid)\n n -= half + 1\n }\n }\n return l\n }\n}\n\n//===----------------------------------------------------------------------===//\n// shuffled()/shuffle()\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns the elements of the sequence, shuffled using the given generator\n /// as a source for randomness.\n ///\n /// You use this method to randomize the elements of a sequence when you are\n /// using a custom random number generator. For example, you can shuffle the\n /// numbers between `0` and `9` by calling the `shuffled(using:)` method on\n /// that range:\n ///\n /// let numbers = 0...9\n /// let shuffledNumbers = numbers.shuffled(using: &myGenerator)\n /// // shuffledNumbers == [8, 9, 4, 3, 2, 6, 7, 0, 5, 1]\n ///\n /// - Parameter generator: The random number generator to use when shuffling\n /// the sequence.\n /// - Returns: An array of this sequence's elements in a shuffled order.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n /// - Note: The algorithm used to shuffle a sequence may change in a future\n /// version of Swift. If you're passing a generator that results in the\n /// same shuffled order each time you run your program, that sequence may\n /// change when your program is compiled using a different version of\n /// Swift.\n @inlinable\n public func shuffled<T: RandomNumberGenerator>(\n using generator: inout T\n ) -> [Element] {\n var result = ContiguousArray(self)\n result.shuffle(using: &generator)\n return Array(result)\n }\n \n /// Returns the elements of the sequence, shuffled.\n ///\n /// For example, you can shuffle the numbers between `0` and `9` by calling\n /// the `shuffled()` method on that range:\n ///\n /// let numbers = 0...9\n /// let shuffledNumbers = numbers.shuffled()\n /// // shuffledNumbers == [1, 7, 6, 2, 8, 9, 4, 3, 5, 0]\n ///\n /// This method is equivalent to calling `shuffled(using:)`, passing in the\n /// system's default random generator.\n ///\n /// - Returns: A shuffled array of this sequence's elements.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func shuffled() -> [Element] {\n var g = SystemRandomNumberGenerator()\n return shuffled(using: &g)\n }\n}\n\nextension MutableCollection where Self: RandomAccessCollection {\n /// Shuffles the collection in place, using the given generator as a source\n /// for randomness.\n ///\n /// You use this method to randomize the elements of a collection when you\n /// are using a custom random number generator. For example, you can use the\n /// `shuffle(using:)` method to randomly reorder the elements of an array.\n ///\n /// var names = ["Alejandro", "Camila", "Diego", "Luciana", "Luis", "Sofía"]\n /// names.shuffle(using: &myGenerator)\n /// // names == ["Sofía", "Alejandro", "Camila", "Luis", "Diego", "Luciana"]\n ///\n /// - Parameter generator: The random number generator to use when shuffling\n /// the collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n /// - Note: The algorithm used to shuffle a collection may change in a future\n /// version of Swift. If you're passing a generator that results in the\n /// same shuffled order each time you run your program, that sequence may\n /// change when your program is compiled using a different version of\n /// Swift.\n @inlinable\n public mutating func shuffle<T: RandomNumberGenerator>(\n using generator: inout T\n ) {\n guard count > 1 else { return }\n var amount = count\n var currentIndex = startIndex\n while amount > 1 {\n let random = Int.random(in: 0 ..< amount, using: &generator)\n amount -= 1\n swapAt(\n currentIndex,\n index(currentIndex, offsetBy: random)\n )\n formIndex(after: ¤tIndex)\n }\n }\n \n /// Shuffles the collection in place.\n ///\n /// Use the `shuffle()` method to randomly reorder the elements of an array.\n ///\n /// var names = ["Alejandro", "Camila", "Diego", "Luciana", "Luis", "Sofía"]\n /// names.shuffle()\n /// // names == ["Luis", "Camila", "Luciana", "Sofía", "Alejandro", "Diego"]\n ///\n /// This method is equivalent to calling `shuffle(using:)`, passing in the\n /// system's default random generator.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public mutating func shuffle() {\n var g = SystemRandomNumberGenerator()\n shuffle(using: &g)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_CollectionAlgorithms.swift | cpp_apple_swift_stdlib_public_core_CollectionAlgorithms.swift | Swift | 24,056 | 0.8 | 0.097331 | 0.608624 | awesome-app | 900 | 2024-04-09T16:47:51.533571 | GPL-3.0 | false | b29ff4cc35da1c5839e5ba6569c03e4b |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2015 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A collection of insertions and removals that describe the difference \n/// between two ordered collection states.\n@available(SwiftStdlib 5.1, *)\npublic struct CollectionDifference<ChangeElement> {\n /// A single change to a collection.\n @frozen\n public enum Change {\n /// An insertion.\n ///\n /// The `offset` value is the offset of the inserted element in the final\n /// state of the collection after the difference is fully applied.\n /// A non-`nil` `associatedWith` value is the offset of the complementary \n /// change.\n case insert(offset: Int, element: ChangeElement, associatedWith: Int?)\n \n /// A removal.\n ///\n /// The `offset` value is the offset of the element to be removed in the\n /// original state of the collection. A non-`nil` `associatedWith` value is \n /// the offset of the complementary change.\n case remove(offset: Int, element: ChangeElement, associatedWith: Int?)\n\n // Internal common field accessors\n internal var _offset: Int {\n get {\n switch self {\n case .insert(offset: let o, element: _, associatedWith: _):\n return o\n case .remove(offset: let o, element: _, associatedWith: _):\n return o\n }\n }\n }\n internal var _element: ChangeElement {\n get {\n switch self {\n case .insert(offset: _, element: let e, associatedWith: _):\n return e\n case .remove(offset: _, element: let e, associatedWith: _):\n return e\n }\n }\n }\n internal var _associatedOffset: Int? {\n get {\n switch self {\n case .insert(offset: _, element: _, associatedWith: let o):\n return o\n case .remove(offset: _, element: _, associatedWith: let o):\n return o\n }\n }\n }\n internal var _isRemoval: Bool {\n switch self {\n case .insert: false\n case .remove: true\n }\n }\n }\n\n /// The insertions contained by this difference, from lowest offset to \n /// highest.\n public let insertions: [Change]\n \n /// The removals contained by this difference, from lowest offset to highest.\n public let removals: [Change]\n\n /// Creates a new collection difference from a collection of changes.\n ///\n /// To find the difference between two collections, use the \n /// `difference(from:)` method declared on the `BidirectionalCollection`\n /// protocol.\n ///\n /// The collection of changes passed as `changes` must meet these \n /// requirements:\n ///\n /// - All insertion offsets are unique\n /// - All removal offsets are unique\n /// - All associations between insertions and removals are symmetric\n ///\n /// - Parameter changes: A collection of changes that represent a transition\n /// between two states.\n ///\n /// - Complexity: O(*n* * log(*n*)), where *n* is the length of the\n /// parameter.\n public init?<Changes: Collection>(\n _ changes: Changes\n ) where Changes.Element == Change {\n guard CollectionDifference<ChangeElement>._validateChanges(changes) else {\n return nil\n }\n\n self.init(_validatedChanges: changes)\n }\n\n /// Internal initializer for use by algorithms that cannot produce invalid\n /// collections of changes. These include the Myers' diff algorithm,\n /// self.inverse(), and the move inferencer.\n ///\n /// If parameter validity cannot be guaranteed by the caller then\n /// `CollectionDifference.init?(_:)` should be used instead.\n ///\n /// - Parameter c: A valid collection of changes that represent a transition\n /// between two states.\n ///\n /// - Complexity: O(*n* * log(*n*)), where *n* is the length of the\n /// parameter.\n internal init<Changes: Collection>(\n _validatedChanges changes: Changes\n ) where Changes.Element == Change {\n let sortedChanges = changes.sorted { (a, b) -> Bool in\n switch (a, b) {\n case (.remove(_, _, _), .insert(_, _, _)):\n return true\n case (.insert(_, _, _), .remove(_, _, _)):\n return false\n default:\n return a._offset < b._offset\n }\n }\n\n // Find first insertion via binary search\n let firstInsertIndex: Int\n if sortedChanges.isEmpty {\n firstInsertIndex = 0\n } else {\n var range = 0...sortedChanges.count\n while range.lowerBound != range.upperBound {\n let i = (range.lowerBound + range.upperBound) / 2\n switch sortedChanges[i] {\n case .insert(_, _, _):\n range = range.lowerBound...i\n case .remove(_, _, _):\n range = (i + 1)...range.upperBound\n }\n }\n firstInsertIndex = range.lowerBound\n }\n\n removals = Array(sortedChanges[0..<firstInsertIndex])\n insertions = Array(sortedChanges[firstInsertIndex..<sortedChanges.count])\n }\n\n /// The public initializer calls this function to ensure that its parameter\n /// meets the conditions set in its documentation.\n ///\n /// - Parameter changes: a collection of `CollectionDifference.Change`\n /// instances intended to represent a valid state transition for\n /// `CollectionDifference`.\n ///\n /// - Returns: whether the parameter meets the following criteria:\n ///\n /// 1. All insertion offsets are unique\n /// 2. All removal offsets are unique\n /// 3. All associations between insertions and removals are symmetric\n ///\n /// Complexity: O(`changes.count`)\n private static func _validateChanges<Changes: Collection>(\n _ changes : Changes\n ) -> Bool where Changes.Element == Change {\n if changes.isEmpty { return true }\n\n var insertAssocToOffset = Dictionary<Int,Int>()\n var removeOffsetToAssoc = Dictionary<Int,Int>()\n var insertOffset = Set<Int>()\n var removeOffset = Set<Int>()\n\n for change in changes {\n let offset = change._offset\n if offset < 0 { return false }\n\n switch change {\n case .remove(_, _, _):\n if removeOffset.contains(offset) { return false }\n removeOffset.insert(offset)\n case .insert(_, _, _):\n if insertOffset.contains(offset) { return false }\n insertOffset.insert(offset)\n } \n\n if let assoc = change._associatedOffset {\n if assoc < 0 { return false }\n switch change {\n case .remove(_, _, _):\n if removeOffsetToAssoc[offset] != nil { return false }\n removeOffsetToAssoc[offset] = assoc\n case .insert(_, _, _):\n if insertAssocToOffset[assoc] != nil { return false }\n insertAssocToOffset[assoc] = offset\n }\n }\n }\n\n return removeOffsetToAssoc == insertAssocToOffset\n }\n\n public func inverse() -> Self {\n return CollectionDifference(_validatedChanges: self.map { c in\n switch c {\n case .remove(let o, let e, let a):\n return .insert(offset: o, element: e, associatedWith: a)\n case .insert(let o, let e, let a):\n return .remove(offset: o, element: e, associatedWith: a)\n }\n })\n }\n}\n\n/// A CollectionDifference is itself a Collection.\n///\n/// The enumeration order of `Change` elements is:\n///\n/// 1. `.remove`s, from highest `offset` to lowest\n/// 2. `.insert`s, from lowest `offset` to highest\n///\n/// This guarantees that applicators on compatible base states are safe when\n/// written in the form:\n///\n/// ```\n/// for c in diff {\n/// switch c {\n/// case .remove(offset: let o, element: _, associatedWith: _):\n/// arr.remove(at: o)\n/// case .insert(offset: let o, element: let e, associatedWith: _):\n/// arr.insert(e, at: o)\n/// }\n/// }\n/// ```\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference: Collection {\n public typealias Element = Change\n\n /// The position of a collection difference.\n @frozen\n public struct Index {\n // Opaque index type is isomorphic to Int\n @usableFromInline\n internal let _offset: Int\n\n internal init(_offset offset: Int) {\n _offset = offset\n }\n }\n\n public var startIndex: Index {\n return Index(_offset: 0)\n }\n\n public var endIndex: Index {\n return Index(_offset: removals.count + insertions.count)\n }\n\n public func index(after index: Index) -> Index {\n return Index(_offset: index._offset + 1)\n }\n\n public subscript(position: Index) -> Element {\n if position._offset < removals.count {\n return removals[removals.count - (position._offset + 1)]\n }\n return insertions[position._offset - removals.count]\n }\n\n public func index(before index: Index) -> Index {\n return Index(_offset: index._offset - 1)\n }\n\n public func formIndex(_ index: inout Index, offsetBy distance: Int) {\n index = Index(_offset: index._offset + distance)\n }\n\n public func distance(from start: Index, to end: Index) -> Int {\n return end._offset - start._offset\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference.Index: Equatable {\n @inlinable\n public static func == (\n lhs: CollectionDifference.Index,\n rhs: CollectionDifference.Index\n ) -> Bool {\n return lhs._offset == rhs._offset\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference.Index: Comparable {\n @inlinable\n public static func < (\n lhs: CollectionDifference.Index,\n rhs: CollectionDifference.Index\n ) -> Bool {\n return lhs._offset < rhs._offset\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference.Index: Hashable {\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine(_offset)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference.Change: Equatable where ChangeElement: Equatable {}\n\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference: Equatable where ChangeElement: Equatable {}\n\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference.Change: Hashable where ChangeElement: Hashable {}\n\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference: Hashable where ChangeElement: Hashable {}\n\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference where ChangeElement: Hashable {\n /// Returns a new collection difference with associations between individual\n /// elements that have been removed and inserted only once.\n ///\n /// - Returns: A collection difference with all possible moves inferred.\n ///\n /// - Complexity: O(*n*) where *n* is the number of collection differences.\n public func inferringMoves() -> CollectionDifference<ChangeElement> {\n let uniqueRemovals: [ChangeElement:Int?] = {\n var result = [ChangeElement:Int?](minimumCapacity: Swift.min(removals.count, insertions.count))\n for removal in removals {\n let element = removal._element\n if result[element] != .none {\n result[element] = .some(.none)\n } else {\n result[element] = .some(removal._offset)\n }\n }\n return result.filter { (_, v) -> Bool in v != .none }\n }()\n \n let uniqueInsertions: [ChangeElement:Int?] = {\n var result = [ChangeElement:Int?](minimumCapacity: Swift.min(removals.count, insertions.count))\n for insertion in insertions {\n let element = insertion._element\n if result[element] != .none {\n result[element] = .some(.none)\n } else {\n result[element] = .some(insertion._offset)\n }\n }\n return result.filter { (_, v) -> Bool in v != .none }\n }()\n\n return CollectionDifference(_validatedChanges: map({ (change: Change) -> Change in\n switch change {\n case .remove(offset: let offset, element: let element, associatedWith: _):\n if uniqueRemovals[element] == nil {\n return change\n }\n if let assoc = uniqueInsertions[element] {\n return .remove(offset: offset, element: element, associatedWith: assoc)\n }\n case .insert(offset: let offset, element: let element, associatedWith: _):\n if uniqueInsertions[element] == nil {\n return change\n }\n if let assoc = uniqueRemovals[element] {\n return .insert(offset: offset, element: element, associatedWith: assoc)\n }\n }\n return change\n }))\n }\n}\n\n#if !$Embedded\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference.Change: Codable where ChangeElement: Codable {\n private enum _CodingKeys: String, CodingKey {\n case offset\n case element\n case associatedOffset\n case isRemove\n }\n\n public init(from decoder: Decoder) throws {\n let values = try decoder.container(keyedBy: _CodingKeys.self)\n let offset = try values.decode(Int.self, forKey: .offset)\n let element = try values.decode(ChangeElement.self, forKey: .element)\n let associatedOffset = try values.decode(Int?.self, forKey: .associatedOffset)\n let isRemove = try values.decode(Bool.self, forKey: .isRemove)\n if isRemove {\n self = .remove(offset: offset, element: element, associatedWith: associatedOffset)\n } else {\n self = .insert(offset: offset, element: element, associatedWith: associatedOffset)\n }\n }\n\n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: _CodingKeys.self)\n try container.encode(_isRemoval, forKey: .isRemove)\n try container.encode(_offset, forKey: .offset)\n try container.encode(_element, forKey: .element)\n try container.encode(_associatedOffset, forKey: .associatedOffset)\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference: Codable where ChangeElement: Codable {\n private enum _CodingKeys: String, CodingKey {\n case insertions\n case removals\n }\n \n public init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: _CodingKeys.self)\n var changes = try container.decode([Change].self, forKey: .removals)\n let removalCount = changes.count\n try changes.append(contentsOf: container.decode([Change].self, forKey: .insertions))\n\n guard changes[..<removalCount].allSatisfy({ $0._isRemoval }),\n changes[removalCount...].allSatisfy({ !$0._isRemoval }),\n Self._validateChanges(changes)\n else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: decoder.codingPath,\n debugDescription: "Cannot decode an invalid collection difference"))\n }\n\n self.init(_validatedChanges: changes)\n }\n \n public func encode(to encoder: Encoder) throws {\n var container = encoder.container(keyedBy: _CodingKeys.self)\n try container.encode(insertions, forKey: .insertions)\n try container.encode(removals, forKey: .removals)\n }\n}\n#endif\n\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference: Sendable where ChangeElement: Sendable { }\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference.Change: Sendable where ChangeElement: Sendable { }\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference.Index: Sendable where ChangeElement: Sendable { }\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_CollectionDifference.swift | cpp_apple_swift_stdlib_public_core_CollectionDifference.swift | Swift | 15,193 | 0.95 | 0.115217 | 0.251208 | vue-tools | 803 | 2024-12-02T03:02:25.793742 | Apache-2.0 | false | 20fa7349667911f92e407e8b0d272841 |
//===--- CollectionOfOne.swift - A Collection with one element ------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A collection containing a single element.\n///\n/// You can use a `CollectionOfOne` instance when you need to efficiently\n/// represent a single value as a collection. For example, you can add a\n/// single element to an array by using a `CollectionOfOne` instance with the\n/// concatenation operator (`+`):\n///\n/// let a = [1, 2, 3, 4]\n/// let toAdd = 100\n/// let b = a + CollectionOfOne(toAdd)\n/// // b == [1, 2, 3, 4, 100]\n@frozen // trivial-implementation\n@_addressableForDependencies\npublic struct CollectionOfOne<Element> {\n @usableFromInline // trivial-implementation\n internal var _element: Element\n\n /// Creates an instance containing just the given element.\n ///\n /// - Parameter element: The element to store in the collection.\n @inlinable // trivial-implementation\n public init(_ element: Element) {\n self._element = element\n }\n}\n\nextension CollectionOfOne {\n /// An iterator that produces one or zero instances of an element.\n ///\n /// `IteratorOverOne` is the iterator for the `CollectionOfOne` type.\n @frozen // trivial-implementation\n public struct Iterator {\n @usableFromInline // trivial-implementation\n internal var _elements: Element?\n\n /// Construct an instance that generates `_element!`, or an empty\n /// sequence if `_element == nil`.\n @inlinable // trivial-implementation\n public // @testable\n init(_elements: Element?) {\n self._elements = _elements\n }\n }\n}\n\nextension CollectionOfOne.Iterator: IteratorProtocol {\n /// Advances to the next element and returns it, or `nil` if no next element\n /// exists.\n ///\n /// Once `nil` has been returned, all subsequent calls return `nil`.\n ///\n /// - Returns: The next element in the underlying sequence, if a next element\n /// exists; otherwise, `nil`.\n @inlinable // trivial-implementation\n public mutating func next() -> Element? {\n let result = _elements\n _elements = nil\n return result\n }\n}\n\nextension CollectionOfOne: RandomAccessCollection, MutableCollection {\n\n public typealias Index = Int\n public typealias Indices = Range<Int>\n public typealias SubSequence = Slice<CollectionOfOne<Element>>\n\n /// The position of the first element.\n ///\n /// In a `CollectionOfOne` instance, `startIndex` is always `0`.\n @inlinable // trivial-implementation\n public var startIndex: Index {\n return 0\n }\n\n /// The "past the end" position---that is, the position one greater than the\n /// last valid subscript argument.\n ///\n /// In a `CollectionOfOne` instance, `endIndex` is always `1`.\n @inlinable // trivial-implementation\n public var endIndex: Index {\n return 1\n }\n \n /// Returns the position immediately after the given index.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be `0`.\n /// - Returns: The index value immediately after `i`.\n @inlinable // trivial-implementation\n public func index(after i: Index) -> Index {\n _precondition(i == startIndex)\n return 1\n }\n\n /// Returns the position immediately before the given index.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be `1`.\n /// - Returns: The index value immediately before `i`.\n @inlinable // trivial-implementation\n public func index(before i: Index) -> Index {\n _precondition(i == endIndex)\n return 0\n }\n\n /// Returns an iterator over the elements of this collection.\n ///\n /// - Complexity: O(1)\n @inlinable // trivial-implementation\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_elements: _element)\n }\n\n /// Accesses the element at the specified position.\n ///\n /// - Parameter position: The position of the element to access. The only\n /// valid position in a `CollectionOfOne` instance is `0`.\n @inlinable // trivial-implementation\n public subscript(position: Int) -> Element {\n _read {\n _precondition(position == 0, "Index out of range")\n yield _element\n }\n _modify {\n _precondition(position == 0, "Index out of range")\n yield &_element\n }\n }\n\n @inlinable // trivial-implementation\n public subscript(bounds: Range<Int>) -> SubSequence {\n get {\n _failEarlyRangeCheck(bounds, bounds: 0..<1)\n return Slice(base: self, bounds: bounds)\n }\n set {\n _failEarlyRangeCheck(bounds, bounds: 0..<1)\n let n = newValue.count\n _precondition(bounds.count == n, "CollectionOfOne can't be resized")\n if n == 1 { self = newValue.base }\n }\n }\n\n /// The number of elements in the collection, which is always one.\n @inlinable // trivial-implementation\n public var count: Int {\n return 1\n }\n}\n\nextension CollectionOfOne {\n\n @available(SwiftStdlib 6.2, *)\n public var span: Span<Element> {\n @lifetime(borrow self)\n @_alwaysEmitIntoClient\n get {\n let pointer = unsafe UnsafePointer<Element>(Builtin.addressOfBorrow(self))\n let span = unsafe Span(_unsafeStart: pointer, count: 1)\n return unsafe _overrideLifetime(span, borrowing: self)\n }\n }\n\n @available(SwiftStdlib 6.2, *)\n public var mutableSpan: MutableSpan<Element> {\n @lifetime(&self)\n @_alwaysEmitIntoClient\n mutating get {\n let pointer = unsafe UnsafeMutablePointer<Element>(\n Builtin.addressOfBorrow(self)\n )\n let span = unsafe MutableSpan(_unsafeStart: pointer, count: 1)\n return unsafe _overrideLifetime(span, mutating: &self)\n }\n }\n}\n\n@_unavailableInEmbedded\nextension CollectionOfOne: CustomDebugStringConvertible {\n /// A textual representation of the collection, suitable for debugging.\n public var debugDescription: String {\n return "CollectionOfOne(\(String(reflecting: _element)))"\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension CollectionOfOne: CustomReflectable {\n public var customMirror: Mirror {\n return Mirror(self, children: ["element": _element])\n }\n}\n#endif\n\nextension CollectionOfOne: Sendable where Element: Sendable { }\nextension CollectionOfOne.Iterator: Sendable where Element: Sendable { }\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_CollectionOfOne.swift | cpp_apple_swift_stdlib_public_core_CollectionOfOne.swift | Swift | 6,480 | 0.8 | 0.043689 | 0.340541 | node-utils | 410 | 2023-11-01T20:58:56.444101 | BSD-3-Clause | false | 55887c00009f14a0280391649780c18c |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n#if SWIFT_STDLIB_HAS_COMMANDLINE\n\n@_silgen_name("_swift_stdlib_getUnsafeArgvArgc")\ninternal func _swift_stdlib_getUnsafeArgvArgc(_: UnsafeMutablePointer<Int32>)\n -> UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>\n\n/// Command-line arguments for the current process.\n@frozen // namespace\npublic enum CommandLine: ~BitwiseCopyable {}\n\nextension CommandLine {\n /// The backing static variable for argument count may come either from the\n /// entry point or it may need to be computed e.g. if we're in the REPL.\n @usableFromInline\n internal static var _argc: Int32 = 0\n\n /// The backing static variable for arguments may come either from the\n /// entry point or it may need to be computed e.g. if we're in the REPL.\n ///\n /// Care must be taken to ensure that `_swift_stdlib_getUnsafeArgvArgc` is\n /// not invoked more times than is necessary (at most once).\n @usableFromInline\n internal static var _unsafeArgv:\n UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>\n = unsafe _swift_stdlib_getUnsafeArgvArgc(&_argc)\n\n /// Access to the raw argc value from C.\n public static var argc: Int32 {\n // We intentionally ignore the argc value given to us from\n // '_swift_stdlib_getUnsafeArgvArgc' because argv and argc are mutable, so\n // someone can mutate the contents of argv and never update the argc value.\n // This results in an out of sync argc which can lead to crashes on first\n // access to 'CommandLine.arguments' due to attempting to read '0 ..< argc'\n // strings.\n //\n // Note: It's still entirely possible that someone may update argv after\n // this iteration and before we actually read argv, but we have no control\n // over synchronizing access to argc and argv.\n var argc: Int32 = 0\n\n while let _ = unsafe _unsafeArgv[Int(argc)] {\n argc += 1\n }\n\n return argc\n }\n\n /// Access to the raw argv value from C.\n ///\n /// The value of this property is a `nil`-terminated C array. Including the\n /// trailing `nil`, there are ``argc`` `+ 1` elements in the array.\n ///\n /// - Note: Accessing the argument vector through this pointer is unsafe.\n /// Where possible, use ``arguments`` instead.\n public static var unsafeArgv:\n UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> {\n return unsafe _unsafeArgv\n }\n\n // This is extremely unsafe and allows for concurrent writes with no\n // synchronization to the underlying data. In a future version of Swift you\n // will not be able to write to 'CommandLine.arguments'.\n static nonisolated(unsafe) var _arguments: [String] = (0 ..< Int(argc)).map {\n unsafe String(cString: _unsafeArgv[$0]!)\n }\n\n /// An array that provides access to this program's command line arguments.\n ///\n /// Use `CommandLine.arguments` to access the command line arguments used\n /// when executing the current program. The name of the executed program is\n /// the first argument.\n ///\n /// The following example shows a command line executable that squares the\n /// integer given as an argument.\n ///\n /// if CommandLine.arguments.count == 2,\n /// let number = Int(CommandLine.arguments[1]) {\n /// print("\(number) x \(number) is \(number * number)")\n /// } else {\n /// print(\n /// """\n /// Error: Please provide a number to square.\n /// Usage: command <number>\n /// """\n /// )\n /// }\n ///\n /// Running the program results in the following output:\n ///\n /// $ command 5\n /// 5 x 5 is 25\n /// $ command ZZZ\n /// Error: Please provide a number to square.\n /// Usage: command <number>\n public static var arguments: [String] {\n get {\n _arguments\n }\n\n @available(*, deprecated, message: "Do not modify CommandLine.arguments. It will become read-only in a future version of Swift.")\n @available(swift, obsoleted: 6.0)\n set {\n _arguments = newValue\n }\n }\n}\n\n#endif // SWIFT_STDLIB_HAS_COMMANDLINE\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_CommandLine.swift | cpp_apple_swift_stdlib_public_core_CommandLine.swift | Swift | 4,498 | 0.95 | 0.090164 | 0.648148 | awesome-app | 387 | 2025-05-09T17:47:10.683426 | MIT | false | b96ac7070e8c693f0a86312dd6fa0072 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A type that can be compared using the relational operators `<`, `<=`, `>=`,\n/// and `>`.\n///\n/// The `Comparable` protocol is used for types that have an inherent order,\n/// such as numbers and strings. Many types in the standard library already\n/// conform to the `Comparable` protocol. Add `Comparable` conformance to your\n/// own custom types when you want to be able to compare instances using\n/// relational operators or use standard library methods that are designed for\n/// `Comparable` types.\n///\n/// The most familiar use of relational operators is to compare numbers, as in\n/// the following example:\n///\n/// let currentTemp = 73\n///\n/// if currentTemp >= 90 {\n/// print("It's a scorcher!")\n/// } else if currentTemp < 65 {\n/// print("Might need a sweater today.")\n/// } else {\n/// print("Seems like picnic weather!")\n/// }\n/// // Prints "Seems like picnic weather!"\n///\n/// You can use special versions of some sequence and collection operations\n/// when working with a `Comparable` type. For example, if your array's\n/// elements conform to `Comparable`, you can call the `sort()` method without\n/// using arguments to sort the elements of your array in ascending order.\n///\n/// var measurements = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]\n/// measurements.sort()\n/// print(measurements)\n/// // Prints "[1.1, 1.2, 1.2, 1.3, 1.5, 1.5, 2.9]"\n///\n/// Conforming to the Comparable Protocol\n/// =====================================\n///\n/// Types with Comparable conformance implement the less-than operator (`<`)\n/// and the equal-to operator (`==`). These two operations impose a strict\n/// total order on the values of a type, in which exactly one of the following\n/// must be true for any two values `a` and `b`:\n///\n/// - `a == b`\n/// - `a < b`\n/// - `b < a`\n///\n/// In addition, the following conditions must hold:\n///\n/// - `a < a` is always `false` (Irreflexivity)\n/// - `a < b` implies `!(b < a)` (Asymmetry)\n/// - `a < b` and `b < c` implies `a < c` (Transitivity)\n///\n/// To add `Comparable` conformance to your custom types, define the `<` and\n/// `==` operators as static methods of your types. The `==` operator is a\n/// requirement of the `Equatable` protocol, which `Comparable` extends---see\n/// that protocol's documentation for more information about equality in\n/// Swift. Because default implementations of the remainder of the relational\n/// operators are provided by the standard library, you'll be able to use\n/// `!=`, `>`, `<=`, and `>=` with instances of your type without any further\n/// code.\n///\n/// As an example, here's an implementation of a `Date` structure that stores\n/// the year, month, and day of a date:\n///\n/// struct Date {\n/// let year: Int\n/// let month: Int\n/// let day: Int\n/// }\n///\n/// To add `Comparable` conformance to `Date`, first declare conformance to\n/// `Comparable` and implement the `<` operator function.\n///\n/// extension Date: Comparable {\n/// static func < (lhs: Date, rhs: Date) -> Bool {\n/// if lhs.year != rhs.year {\n/// return lhs.year < rhs.year\n/// } else if lhs.month != rhs.month {\n/// return lhs.month < rhs.month\n/// } else {\n/// return lhs.day < rhs.day\n/// }\n/// }\n///\n/// This function uses the least specific nonmatching property of the date to\n/// determine the result of the comparison. For example, if the two `year`\n/// properties are equal but the two `month` properties are not, the date with\n/// the lesser value for `month` is the lesser of the two dates.\n///\n/// Next, implement the `==` operator function, the requirement inherited from\n/// the `Equatable` protocol.\n///\n/// static func == (lhs: Date, rhs: Date) -> Bool {\n/// return lhs.year == rhs.year && lhs.month == rhs.month\n/// && lhs.day == rhs.day\n/// }\n/// }\n///\n/// Two `Date` instances are equal if each of their corresponding properties is\n/// equal.\n///\n/// Now that `Date` conforms to `Comparable`, you can compare instances of the\n/// type with any of the relational operators. The following example compares\n/// the date of the first moon landing with the release of David Bowie's song\n/// "Space Oddity":\n///\n/// let spaceOddity = Date(year: 1969, month: 7, day: 11) // July 11, 1969\n/// let moonLanding = Date(year: 1969, month: 7, day: 20) // July 20, 1969\n/// if moonLanding > spaceOddity {\n/// print("Major Tom stepped through the door first.")\n/// } else {\n/// print("David Bowie was following in Neil Armstrong's footsteps.")\n/// }\n/// // Prints "Major Tom stepped through the door first."\n///\n/// Note that the `>` operator provided by the standard library is used in this\n/// example, not the `<` operator implemented above.\n///\n/// - Note: A conforming type may contain a subset of values which are treated\n/// as exceptional---that is, values that are outside the domain of\n/// meaningful arguments for the purposes of the `Comparable` protocol. For\n/// example, the special "not a number" value for floating-point types\n/// (`FloatingPoint.nan`) compares as neither less than, greater than, nor\n/// equal to any normal floating-point value. Exceptional values need not\n/// take part in the strict total order.\npublic protocol Comparable: Equatable {\n /// Returns a Boolean value indicating whether the value of the first\n /// argument is less than that of the second argument.\n ///\n /// This function is the only requirement of the `Comparable` protocol. The\n /// remainder of the relational operator functions are implemented by the\n /// standard library for any type that conforms to `Comparable`.\n ///\n /// - Parameters:\n /// - lhs: A value to compare.\n /// - rhs: Another value to compare.\n static func < (lhs: Self, rhs: Self) -> Bool\n\n /// Returns a Boolean value indicating whether the value of the first\n /// argument is less than or equal to that of the second argument.\n ///\n /// - Parameters:\n /// - lhs: A value to compare.\n /// - rhs: Another value to compare.\n static func <= (lhs: Self, rhs: Self) -> Bool\n\n /// Returns a Boolean value indicating whether the value of the first\n /// argument is greater than or equal to that of the second argument.\n ///\n /// - Parameters:\n /// - lhs: A value to compare.\n /// - rhs: Another value to compare.\n static func >= (lhs: Self, rhs: Self) -> Bool\n\n /// Returns a Boolean value indicating whether the value of the first\n /// argument is greater than that of the second argument.\n ///\n /// - Parameters:\n /// - lhs: A value to compare.\n /// - rhs: Another value to compare.\n static func > (lhs: Self, rhs: Self) -> Bool\n}\n\nextension Comparable {\n /// Returns a Boolean value indicating whether the value of the first argument\n /// is greater than that of the second argument.\n ///\n /// This is the default implementation of the greater-than operator (`>`) for\n /// any type that conforms to `Comparable`.\n ///\n /// - Parameters:\n /// - lhs: A value to compare.\n /// - rhs: Another value to compare.\n @inlinable\n public static func > (lhs: Self, rhs: Self) -> Bool {\n return rhs < lhs\n }\n\n /// Returns a Boolean value indicating whether the value of the first argument\n /// is less than or equal to that of the second argument.\n ///\n /// This is the default implementation of the less-than-or-equal-to\n /// operator (`<=`) for any type that conforms to `Comparable`.\n ///\n /// - Parameters:\n /// - lhs: A value to compare.\n /// - rhs: Another value to compare.\n @inlinable\n public static func <= (lhs: Self, rhs: Self) -> Bool {\n return !(rhs < lhs)\n }\n\n /// Returns a Boolean value indicating whether the value of the first argument\n /// is greater than or equal to that of the second argument.\n ///\n /// This is the default implementation of the greater-than-or-equal-to operator\n /// (`>=`) for any type that conforms to `Comparable`.\n ///\n /// - Parameters:\n /// - lhs: A value to compare.\n /// - rhs: Another value to compare.\n /// - Returns: `true` if `lhs` is greater than or equal to `rhs`; otherwise,\n /// `false`.\n @inlinable\n public static func >= (lhs: Self, rhs: Self) -> Bool {\n return !(lhs < rhs)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Comparable.swift | cpp_apple_swift_stdlib_public_core_Comparable.swift | Swift | 8,888 | 0.95 | 0.118182 | 0.906103 | awesome-app | 149 | 2024-06-15T14:34:24.530428 | GPL-3.0 | false | 8c36faa0e6a5fa11bd673d14a1f80162 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n// Intrinsic protocols shared with the compiler\n//===----------------------------------------------------------------------===//\n\n/// A type that can be converted to and from an associated raw value.\n///\n/// With a `RawRepresentable` type, you can switch back and forth between a\n/// custom type and an associated `RawValue` type without losing the value of\n/// the original `RawRepresentable` type. Using the raw value of a conforming\n/// type streamlines interoperation with Objective-C and legacy APIs and\n/// simplifies conformance to other protocols, such as `Equatable`,\n/// `Comparable`, and `Hashable`.\n///\n/// The `RawRepresentable` protocol is seen mainly in two categories of types:\n/// enumerations with raw value types and option sets.\n///\n/// Enumerations with Raw Values\n/// ============================\n///\n/// For any enumeration with a string, integer, or floating-point raw type, the\n/// Swift compiler automatically adds `RawRepresentable` conformance. When\n/// defining your own custom enumeration, you give it a raw type by specifying\n/// the raw type as the first item in the enumeration's type inheritance list.\n/// You can also use literals to specify values for one or more cases.\n///\n/// For example, the `Counter` enumeration defined here has an `Int` raw value\n/// type and gives the first case a raw value of `1`:\n///\n/// enum Counter: Int {\n/// case one = 1, two, three, four, five\n/// }\n///\n/// You can create a `Counter` instance from an integer value between 1 and 5\n/// by using the `init?(rawValue:)` initializer declared in the\n/// `RawRepresentable` protocol. This initializer is failable because although\n/// every case of the `Counter` type has a corresponding `Int` value, there\n/// are many `Int` values that *don't* correspond to a case of `Counter`.\n///\n/// for i in 3...6 {\n/// print(Counter(rawValue: i))\n/// }\n/// // Prints "Optional(Counter.three)"\n/// // Prints "Optional(Counter.four)"\n/// // Prints "Optional(Counter.five)"\n/// // Prints "nil"\n///\n/// Option Sets\n/// ===========\n///\n/// Option sets all conform to `RawRepresentable` by inheritance using the\n/// `OptionSet` protocol. Whether using an option set or creating your own,\n/// you use the raw value of an option set instance to store the instance's\n/// bitfield. The raw value must therefore be of a type that conforms to the\n/// `FixedWidthInteger` protocol, such as `UInt8` or `Int`. For example, the\n/// `Direction` type defines an option set for the four directions you can\n/// move in a game.\n///\n/// struct Directions: OptionSet {\n/// let rawValue: UInt8\n///\n/// static let up = Directions(rawValue: 1 << 0)\n/// static let down = Directions(rawValue: 1 << 1)\n/// static let left = Directions(rawValue: 1 << 2)\n/// static let right = Directions(rawValue: 1 << 3)\n/// }\n///\n/// Unlike enumerations, option sets provide a nonfailable `init(rawValue:)`\n/// initializer to convert from a raw value, because option sets don't have an\n/// enumerated list of all possible cases. Option set values have\n/// a one-to-one correspondence with their associated raw values.\n///\n/// In the case of the `Directions` option set, an instance can contain zero,\n/// one, or more of the four defined directions. This example declares a\n/// constant with three currently allowed moves. The raw value of the\n/// `allowedMoves` instance is the result of the bitwise OR of its three\n/// members' raw values:\n///\n/// let allowedMoves: Directions = [.up, .down, .left]\n/// print(allowedMoves.rawValue)\n/// // Prints "7"\n///\n/// Option sets use bitwise operations on their associated raw values to\n/// implement their mathematical set operations. For example, the `contains()`\n/// method on `allowedMoves` performs a bitwise AND operation to check whether\n/// the option set contains an element.\n///\n/// print(allowedMoves.contains(.right))\n/// // Prints "false"\n/// print(allowedMoves.rawValue & Directions.right.rawValue)\n/// // Prints "0"\npublic protocol RawRepresentable<RawValue> {\n /// The raw type that can be used to represent all values of the conforming\n /// type.\n ///\n /// Every distinct value of the conforming type has a corresponding unique\n /// value of the `RawValue` type, but there may be values of the `RawValue`\n /// type that don't have a corresponding value of the conforming type.\n associatedtype RawValue\n\n /// Creates a new instance with the specified raw value.\n ///\n /// If there is no value of the type that corresponds with the specified raw\n /// value, this initializer returns `nil`. For example:\n ///\n /// enum PaperSize: String {\n /// case A4, A5, Letter, Legal\n /// }\n ///\n /// print(PaperSize(rawValue: "Legal"))\n /// // Prints "Optional(PaperSize.Legal)"\n ///\n /// print(PaperSize(rawValue: "Tabloid"))\n /// // Prints "nil"\n ///\n /// - Parameter rawValue: The raw value to use for the new instance.\n init?(rawValue: RawValue)\n\n /// The corresponding value of the raw type.\n ///\n /// A new instance initialized with `rawValue` will be equivalent to this\n /// instance. For example:\n ///\n /// enum PaperSize: String {\n /// case A4, A5, Letter, Legal\n /// }\n ///\n /// let selectedSize = PaperSize.Letter\n /// print(selectedSize.rawValue)\n /// // Prints "Letter"\n ///\n /// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)\n /// // Prints "true"\n var rawValue: RawValue { get }\n}\n\n/// Returns a Boolean value indicating whether the two arguments are equal.\n///\n/// - Parameters:\n/// - lhs: A raw-representable instance.\n/// - rhs: A second raw-representable instance.\n@inlinable // trivial-implementation\npublic func == <T: RawRepresentable>(lhs: T, rhs: T) -> Bool\n where T.RawValue: Equatable {\n return lhs.rawValue == rhs.rawValue\n}\n\n/// Returns a Boolean value indicating whether the two arguments are not equal.\n///\n/// - Parameters:\n/// - lhs: A raw-representable instance.\n/// - rhs: A second raw-representable instance.\n@inlinable // trivial-implementation\npublic func != <T: RawRepresentable>(lhs: T, rhs: T) -> Bool\n where T.RawValue: Equatable {\n return lhs.rawValue != rhs.rawValue\n}\n\n// This overload is needed for ambiguity resolution against the\n// implementation of != for T: Equatable\n/// Returns a Boolean value indicating whether the two arguments are not equal.\n///\n/// - Parameters:\n/// - lhs: A raw-representable instance.\n/// - rhs: A second raw-representable instance.\n@inlinable // trivial-implementation\npublic func != <T: Equatable>(lhs: T, rhs: T) -> Bool\n where T: RawRepresentable, T.RawValue: Equatable {\n return lhs.rawValue != rhs.rawValue\n}\n\n// Ensure that any RawRepresentable types that conform to Hashable without\n// providing explicit implementations get hashing that's consistent with the ==\n// definition above. (Compiler-synthesized hashing is based on stored properties\n// rather than rawValue; the difference is subtle, but it can be fatal.)\nextension RawRepresentable where RawValue: Hashable, Self: Hashable {\n @inlinable // trivial\n public var hashValue: Int {\n // Note: in Swift 5.5 and below, this used to return `rawValue.hashValue`.\n // The current definition matches the default `hashValue` implementation,\n // so that RawRepresentable types don't need to implement both `hashValue`\n // and `hash(into:)` to customize their hashing.\n _hashValue(for: self)\n }\n\n @inlinable // trivial\n public func hash(into hasher: inout Hasher) {\n hasher.combine(rawValue)\n }\n\n @inlinable // trivial\n public func _rawHashValue(seed: Int) -> Int {\n // In 5.0, this used to return rawValue._rawHashValue(seed: seed). This was\n // slightly faster, but it interfered with conforming types' ability to\n // customize their hashing. The current definition is equivalent to the\n // default implementation; however, we need to keep the definition to remain\n // ABI compatible with code compiled on 5.0.\n //\n // Note that unless a type provides a custom hash(into:) implementation,\n // this new version returns the same values as the original 5.0 definition,\n // so code that used to work in 5.0 remains working whether or not the\n // original definition was inlined.\n //\n // See https://github.com/apple/swift/issues/53126.\n var hasher = Hasher(_seed: seed)\n self.hash(into: &hasher)\n return hasher._finalize()\n }\n}\n\n/// A type that provides a collection of all of its values.\n///\n/// Types that conform to the `CaseIterable` protocol are typically\n/// enumerations without associated values. When using a `CaseIterable` type,\n/// you can access a collection of all of the type's cases by using the type's\n/// `allCases` property.\n///\n/// For example, the `CompassDirection` enumeration declared in this example\n/// conforms to `CaseIterable`. You access the number of cases and the cases\n/// themselves through `CompassDirection.allCases`.\n///\n/// enum CompassDirection: CaseIterable {\n/// case north, south, east, west\n/// }\n///\n/// print("There are \(CompassDirection.allCases.count) directions.")\n/// // Prints "There are 4 directions."\n/// let caseList = CompassDirection.allCases\n/// .map({ "\($0)" })\n/// .joined(separator: ", ")\n/// // caseList == "north, south, east, west"\n///\n/// Conforming to the CaseIterable Protocol\n/// =======================================\n///\n/// The compiler can automatically provide an implementation of the\n/// `CaseIterable` requirements for any enumeration without associated values\n/// or `@available` attributes on its cases. The synthesized `allCases`\n/// collection provides the cases in order of their declaration.\n///\n/// You can take advantage of this compiler support when defining your own\n/// custom enumeration by declaring conformance to `CaseIterable` in the\n/// enumeration's original declaration. The `CompassDirection` example above\n/// demonstrates this automatic implementation.\npublic protocol CaseIterable {\n /// A type that can represent a collection of all values of this type.\n associatedtype AllCases: Collection = [Self]\n where AllCases.Element == Self\n \n /// A collection of all values of this type.\n static var allCases: AllCases { get }\n}\n\n/// A type that can be initialized using the nil literal, `nil`.\n///\n/// `nil` has a specific meaning in Swift---the absence of a value. Only the\n/// `Optional` type conforms to `ExpressibleByNilLiteral`.\n/// `ExpressibleByNilLiteral` conformance for types that use `nil` for other\n/// purposes is discouraged.\npublic protocol ExpressibleByNilLiteral: ~Copyable, ~Escapable {\n /// Creates an instance initialized with `nil`.\n @lifetime(immortal)\n init(nilLiteral: ())\n}\n\npublic protocol _ExpressibleByBuiltinIntegerLiteral {\n init(_builtinIntegerLiteral value: Builtin.IntLiteral)\n}\n\n/// A type that can be initialized with an integer literal.\n///\n/// The standard library integer and floating-point types, such as `Int` and\n/// `Double`, conform to the `ExpressibleByIntegerLiteral` protocol. You can\n/// initialize a variable or constant of any of these types by assigning an\n/// integer literal.\n///\n/// // Type inferred as 'Int'\n/// let cookieCount = 12\n///\n/// // An array of 'Int'\n/// let chipsPerCookie = [21, 22, 25, 23, 24, 19]\n///\n/// // A floating-point value initialized using an integer literal\n/// let redPercentage: Double = 1\n/// // redPercentage == 1.0\n///\n/// Conforming to ExpressibleByIntegerLiteral\n/// =========================================\n///\n/// To add `ExpressibleByIntegerLiteral` conformance to your custom type,\n/// implement the required initializer.\npublic protocol ExpressibleByIntegerLiteral {\n /// A type that represents an integer literal.\n ///\n /// The standard library integer and floating-point types are all valid types\n /// for `IntegerLiteralType`.\n associatedtype IntegerLiteralType: _ExpressibleByBuiltinIntegerLiteral\n\n /// Creates an instance initialized to the specified integer value.\n ///\n /// Do not call this initializer directly. Instead, initialize a variable or\n /// constant using an integer literal. For example:\n ///\n /// let x = 23\n ///\n /// In this example, the assignment to the `x` constant calls this integer\n /// literal initializer behind the scenes.\n ///\n /// - Parameter value: The value to create.\n init(integerLiteral value: IntegerLiteralType)\n}\n\npublic protocol _ExpressibleByBuiltinFloatLiteral {\n init(_builtinFloatLiteral value: _MaxBuiltinFloatType)\n}\n\n/// A type that can be initialized with a floating-point literal.\n///\n/// The standard library floating-point types---`Float`, `Double`, and\n/// `Float80` where available---all conform to the `ExpressibleByFloatLiteral`\n/// protocol. You can initialize a variable or constant of any of these types\n/// by assigning a floating-point literal.\n///\n/// // Type inferred as 'Double'\n/// let threshold = 6.0\n///\n/// // An array of 'Double'\n/// let measurements = [2.2, 4.1, 3.65, 4.2, 9.1]\n///\n/// Conforming to ExpressibleByFloatLiteral\n/// =======================================\n///\n/// To add `ExpressibleByFloatLiteral` conformance to your custom type,\n/// implement the required initializer.\npublic protocol ExpressibleByFloatLiteral {\n /// A type that represents a floating-point literal.\n ///\n /// Valid types for `FloatLiteralType` are `Float`, `Double`, and `Float80`\n /// where available.\n associatedtype FloatLiteralType: _ExpressibleByBuiltinFloatLiteral\n \n /// Creates an instance initialized to the specified floating-point value.\n ///\n /// Do not call this initializer directly. Instead, initialize a variable or\n /// constant using a floating-point literal. For example:\n ///\n /// let x = 21.5\n ///\n /// In this example, the assignment to the `x` constant calls this\n /// floating-point literal initializer behind the scenes.\n ///\n /// - Parameter value: The value to create.\n init(floatLiteral value: FloatLiteralType)\n}\n\npublic protocol _ExpressibleByBuiltinBooleanLiteral {\n init(_builtinBooleanLiteral value: Builtin.Int1)\n}\n\n/// A type that can be initialized with the Boolean literals `true` and\n/// `false`.\n///\n/// `Bool`, `DarwinBoolean`, `ObjCBool`, and `WindowsBool` are treated as\n/// Boolean values. Expanding this set to include types that represent more than\n/// simple Boolean values is discouraged.\n///\n/// To add `ExpressibleByBooleanLiteral` conformance to your custom type,\n/// implement the `init(booleanLiteral:)` initializer that creates an instance\n/// of your type with the given Boolean value.\npublic protocol ExpressibleByBooleanLiteral {\n /// A type that represents a Boolean literal, such as `Bool`.\n associatedtype BooleanLiteralType: _ExpressibleByBuiltinBooleanLiteral\n\n /// Creates an instance initialized to the given Boolean value.\n ///\n /// Do not call this initializer directly. Instead, initialize a variable or\n /// constant using one of the Boolean literals `true` and `false`. For\n /// example:\n ///\n /// let twasBrillig = true\n ///\n /// In this example, the assignment to the `twasBrillig` constant calls this\n /// Boolean literal initializer behind the scenes.\n ///\n /// - Parameter value: The value of the new instance.\n init(booleanLiteral value: BooleanLiteralType)\n}\n\npublic protocol _ExpressibleByBuiltinUnicodeScalarLiteral {\n init(_builtinUnicodeScalarLiteral value: Builtin.Int32)\n}\n\n/// A type that can be initialized with a string literal containing a single\n/// Unicode scalar value.\n///\n/// The `String`, `StaticString`, `Character`, and `Unicode.Scalar` types all\n/// conform to the `ExpressibleByUnicodeScalarLiteral` protocol. You can\n/// initialize a variable of any of these types using a string literal that\n/// holds a single Unicode scalar.\n///\n/// let ñ: Unicode.Scalar = "ñ"\n/// print(ñ)\n/// // Prints "ñ"\n///\n/// Conforming to ExpressibleByUnicodeScalarLiteral\n/// ===============================================\n///\n/// To add `ExpressibleByUnicodeScalarLiteral` conformance to your custom type,\n/// implement the required initializer.\npublic protocol ExpressibleByUnicodeScalarLiteral {\n /// A type that represents a Unicode scalar literal.\n ///\n /// Valid types for `UnicodeScalarLiteralType` are `Unicode.Scalar`,\n /// `Character`, `String`, and `StaticString`.\n associatedtype UnicodeScalarLiteralType: _ExpressibleByBuiltinUnicodeScalarLiteral\n\n /// Creates an instance initialized to the given value.\n ///\n /// - Parameter value: The value of the new instance.\n init(unicodeScalarLiteral value: UnicodeScalarLiteralType)\n}\n\npublic protocol _ExpressibleByBuiltinExtendedGraphemeClusterLiteral\n : _ExpressibleByBuiltinUnicodeScalarLiteral {\n\n init(\n _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,\n utf8CodeUnitCount: Builtin.Word,\n isASCII: Builtin.Int1)\n}\n\n/// A type that can be initialized with a string literal containing a single\n/// extended grapheme cluster.\n///\n/// An *extended grapheme cluster* is a group of one or more Unicode scalar\n/// values that approximates a single user-perceived character. Many\n/// individual characters, such as "é", "김", and "🇮🇳", can be made up of\n/// multiple Unicode scalar values. These code points are combined by\n/// Unicode's boundary algorithms into extended grapheme clusters.\n///\n/// The `String`, `StaticString`, and `Character` types conform to the\n/// `ExpressibleByExtendedGraphemeClusterLiteral` protocol. You can initialize\n/// a variable or constant of any of these types using a string literal that\n/// holds a single character.\n///\n/// let snowflake: Character = "❄︎"\n/// print(snowflake)\n/// // Prints "❄︎"\n///\n/// Conforming to ExpressibleByExtendedGraphemeClusterLiteral\n/// =========================================================\n///\n/// To add `ExpressibleByExtendedGraphemeClusterLiteral` conformance to your\n/// custom type, implement the required initializer.\npublic protocol ExpressibleByExtendedGraphemeClusterLiteral\n : ExpressibleByUnicodeScalarLiteral {\n\n /// A type that represents an extended grapheme cluster literal.\n ///\n /// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`,\n /// `String`, and `StaticString`.\n associatedtype ExtendedGraphemeClusterLiteralType\n : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral\n \n /// Creates an instance initialized to the given value.\n ///\n /// - Parameter value: The value of the new instance.\n init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType)\n}\n\nextension ExpressibleByExtendedGraphemeClusterLiteral\n where ExtendedGraphemeClusterLiteralType == UnicodeScalarLiteralType {\n\n @_transparent\n public init(unicodeScalarLiteral value: ExtendedGraphemeClusterLiteralType) {\n self.init(extendedGraphemeClusterLiteral: value)\n }\n}\n\npublic protocol _ExpressibleByBuiltinStringLiteral\n : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {\n\n init(\n _builtinStringLiteral start: Builtin.RawPointer,\n utf8CodeUnitCount: Builtin.Word,\n isASCII: Builtin.Int1)\n}\n\n/// A type that can be initialized with a string literal.\n///\n/// The `String` and `StaticString` types conform to the\n/// `ExpressibleByStringLiteral` protocol. You can initialize a variable or\n/// constant of either of these types using a string literal of any length.\n///\n/// let picnicGuest = "Deserving porcupine"\n///\n/// Conforming to ExpressibleByStringLiteral\n/// ========================================\n///\n/// To add `ExpressibleByStringLiteral` conformance to your custom type,\n/// implement the required initializer.\npublic protocol ExpressibleByStringLiteral\n : ExpressibleByExtendedGraphemeClusterLiteral {\n \n /// A type that represents a string literal.\n ///\n /// Valid types for `StringLiteralType` are `String` and `StaticString`.\n associatedtype StringLiteralType: _ExpressibleByBuiltinStringLiteral\n \n /// Creates an instance initialized to the given string value.\n ///\n /// - Parameter value: The value of the new instance.\n init(stringLiteral value: StringLiteralType)\n}\n\nextension ExpressibleByStringLiteral\n where StringLiteralType == ExtendedGraphemeClusterLiteralType {\n\n @_transparent\n public init(extendedGraphemeClusterLiteral value: StringLiteralType) {\n self.init(stringLiteral: value)\n }\n}\n\n/// A type that can be initialized using an array literal.\n///\n/// An array literal is a simple way of expressing a list of values. Simply\n/// surround a comma-separated list of values, instances, or literals with\n/// square brackets to create an array literal. You can use an array literal\n/// anywhere an instance of an `ExpressibleByArrayLiteral` type is expected: as\n/// a value assigned to a variable or constant, as a parameter to a method or\n/// initializer, or even as the subject of a nonmutating operation like\n/// `map(_:)` or `filter(_:)`.\n///\n/// Arrays, sets, and option sets all conform to `ExpressibleByArrayLiteral`, \n/// and your own custom types can as well. Here's an example of creating a set \n/// and an array using array literals:\n///\n/// let employeesSet: Set<String> = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]\n/// print(employeesSet)\n/// // Prints "["Amir", "Dave", "Jihye", "Alessia"]"\n///\n/// let employeesArray: [String] = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]\n/// print(employeesArray)\n/// // Prints "["Amir", "Jihye", "Dave", "Alessia", "Dave"]"\n///\n/// The `Set` and `Array` types each handle array literals in their own way to\n/// create new instances. In this case, the newly created set drops the\n/// duplicate value ("Dave") and doesn't maintain the order of the array\n/// literal's elements. The new array, on the other hand, matches the order\n/// and number of elements provided.\n///\n/// - Note: An array literal is not the same as an `Array` instance. You can't\n/// initialize a type that conforms to `ExpressibleByArrayLiteral` simply by\n/// assigning an existing array.\n///\n/// let anotherSet: Set = employeesArray\n/// // error: cannot convert value of type '[String]' to specified type 'Set'\n///\n/// Type Inference of Array Literals\n/// ================================\n///\n/// Whenever possible, Swift's compiler infers the full intended type of your\n/// array literal. Because `Array` is the default type for an array literal,\n/// without writing any other code, you can declare an array with a particular\n/// element type by providing one or more values.\n///\n/// In this example, the compiler infers the full type of each array literal.\n///\n/// let integers = [1, 2, 3]\n/// // 'integers' has type '[Int]'\n///\n/// let strings = ["a", "b", "c"]\n/// // 'strings' has type '[String]'\n///\n/// An empty array literal alone doesn't provide enough information for the\n/// compiler to infer the intended type of the `Array` instance. When using an\n/// empty array literal, specify the type of the variable or constant.\n///\n/// var emptyArray: [Bool] = []\n/// // 'emptyArray' has type '[Bool]'\n///\n/// Because many functions and initializers fully specify the types of their\n/// parameters, you can often use an array literal with or without elements as\n/// a parameter. For example, the `sum(_:)` function shown here takes an `Int`\n/// array as a parameter:\n///\n/// func sum(values: [Int]) -> Int {\n/// return values.reduce(0, +)\n/// }\n///\n/// let sumOfFour = sum([5, 10, 15, 20])\n/// // 'sumOfFour' == 50\n///\n/// let sumOfNone = sum([])\n/// // 'sumOfNone' == 0\n///\n/// When you call a function that does not fully specify its parameters' types,\n/// use the type-cast operator (`as`) to specify the type of an array literal.\n/// For example, the `log(name:value:)` function shown here has an\n/// unconstrained generic `value` parameter.\n///\n/// func log<T>(name name: String, value: T) {\n/// print("\(name): \(value)")\n/// }\n///\n/// log(name: "Four integers", value: [5, 10, 15, 20])\n/// // Prints "Four integers: [5, 10, 15, 20]"\n///\n/// log(name: "Zero integers", value: [] as [Int])\n/// // Prints "Zero integers: []"\n///\n/// Conforming to ExpressibleByArrayLiteral\n/// =======================================\n///\n/// Add the capability to be initialized with an array literal to your own\n/// custom types by declaring an `init(arrayLiteral:)` initializer. The\n/// following example shows the array literal initializer for a hypothetical\n/// `OrderedSet` type, which has setlike semantics but maintains the order of\n/// its elements.\n///\n/// struct OrderedSet<Element: Hashable>: Collection, SetAlgebra {\n/// // implementation details\n/// }\n///\n/// extension OrderedSet: ExpressibleByArrayLiteral {\n/// init(arrayLiteral: Element...) {\n/// self.init()\n/// for element in arrayLiteral {\n/// self.append(element)\n/// }\n/// }\n/// }\npublic protocol ExpressibleByArrayLiteral {\n /// The type of the elements of an array literal.\n associatedtype ArrayLiteralElement\n /// Creates an instance initialized with the given elements.\n init(arrayLiteral elements: ArrayLiteralElement...)\n}\n\n/// A type that can be initialized using a dictionary literal.\n///\n/// A dictionary literal is a simple way of writing a list of key-value pairs.\n/// You write each key-value pair with a colon (`:`) separating the key and\n/// the value. The dictionary literal is made up of one or more key-value\n/// pairs, separated by commas and surrounded with square brackets.\n///\n/// To declare a dictionary, assign a dictionary literal to a variable or\n/// constant:\n///\n/// let countryCodes = ["BR": "Brazil", "GH": "Ghana",\n/// "JP": "Japan", "US": "United States"]\n/// // 'countryCodes' has type '[String: String]'\n///\n/// print(countryCodes["BR"]!)\n/// // Prints "Brazil"\n///\n/// When the context provides enough type information, you can use a special\n/// form of the dictionary literal, square brackets surrounding a single\n/// colon, to initialize an empty dictionary.\n///\n/// var frequencies: [String: Int] = [:]\n/// print(frequencies.count)\n/// // Prints "0"\n///\n/// - Note:\n/// A dictionary literal is *not* the same as an instance of `Dictionary`.\n/// You can't initialize a type that conforms to `ExpressibleByDictionaryLiteral`\n/// simply by assigning an instance of `Dictionary`, `KeyValuePairs`, or similar.\n///\n/// Conforming to the ExpressibleByDictionaryLiteral Protocol\n/// =========================================================\n///\n/// To add the capability to be initialized with a dictionary literal to your\n/// own custom types, declare an `init(dictionaryLiteral:)` initializer. The\n/// following example shows the dictionary literal initializer for a\n/// hypothetical `CountedSet` type, which uses setlike semantics while keeping\n/// track of the count for duplicate elements:\n///\n/// struct CountedSet<Element: Hashable>: Collection, SetAlgebra {\n/// // implementation details\n///\n/// /// Updates the count stored in the set for the given element,\n/// /// adding the element if necessary.\n/// ///\n/// /// - Parameter n: The new count for `element`. `n` must be greater\n/// /// than or equal to zero.\n/// /// - Parameter element: The element to set the new count on.\n/// mutating func updateCount(_ n: Int, for element: Element)\n/// }\n///\n/// extension CountedSet: ExpressibleByDictionaryLiteral {\n/// init(dictionaryLiteral elements: (Element, Int)...) {\n/// self.init()\n/// for (element, count) in elements {\n/// self.updateCount(count, for: element)\n/// }\n/// }\n/// }\npublic protocol ExpressibleByDictionaryLiteral {\n /// The key type of a dictionary literal.\n associatedtype Key\n /// The value type of a dictionary literal.\n associatedtype Value\n /// Creates an instance initialized with the given key-value pairs.\n init(dictionaryLiteral elements: (Key, Value)...)\n}\n\n/// A type that can be initialized by string interpolation with a string\n/// literal that includes expressions.\n///\n/// Use string interpolation to include one or more expressions in a string\n/// literal, wrapped in a set of parentheses and prefixed by a backslash. For\n/// example:\n///\n/// let price = 2\n/// let number = 3\n/// let message = "One cookie: $\(price), \(number) cookies: $\(price * number)."\n/// print(message)\n/// // Prints "One cookie: $2, 3 cookies: $6."\n/// \n/// Extending the Default Interpolation Behavior\n/// ============================================\n/// \n/// Add new interpolation behavior to existing types by extending\n/// `DefaultStringInterpolation`, the type that implements interpolation for\n/// types like `String` and `Substring`, to add an overload of\n/// `appendInterpolation(_:)` with their new behavior.\n///\n/// For more information, see the `DefaultStringInterpolation` and\n/// `StringInterpolationProtocol` documentation.\n/// \n/// Creating a Type That Supports the Default String Interpolation\n/// ==============================================================\n/// \n/// To create a new type that supports string literals and interpolation, but\n/// that doesn't need any custom behavior, conform the type to\n/// `ExpressibleByStringInterpolation` and implement the\n/// `init(stringLiteral: String)` initializer declared by the\n/// `ExpressibleByStringLiteral` protocol. Swift will automatically use\n/// `DefaultStringInterpolation` as the interpolation type and provide an\n/// implementation for `init(stringInterpolation:)` that passes the\n/// interpolated literal's contents to `init(stringLiteral:)`, so you don't\n/// need to implement anything specific to this protocol.\n///\n/// Creating a Type That Supports Custom String Interpolation\n/// =========================================================\n///\n/// If you want a conforming type to differentiate between literal and\n/// interpolated segments, restrict the types that can be interpolated,\n/// support different interpolators from the ones on `String`, or avoid\n/// constructing a `String` containing the data, the type must specify a custom\n/// `StringInterpolation` associated type. This type must conform to\n/// `StringInterpolationProtocol` and have a matching `StringLiteralType`.\n///\n/// For more information, see the `StringInterpolationProtocol` documentation.\npublic protocol ExpressibleByStringInterpolation\n : ExpressibleByStringLiteral {\n \n#if !$Embedded\n /// The type each segment of a string literal containing interpolations\n /// should be appended to.\n ///\n /// The `StringLiteralType` of an interpolation type must match the\n /// `StringLiteralType` of the conforming type.\n associatedtype StringInterpolation: StringInterpolationProtocol\n = DefaultStringInterpolation\n where StringInterpolation.StringLiteralType == StringLiteralType\n#else\n associatedtype StringInterpolation: StringInterpolationProtocol\n where StringInterpolation.StringLiteralType == StringLiteralType\n#endif\n\n /// Creates an instance from a string interpolation.\n /// \n /// Most `StringInterpolation` types will store information about the\n /// literals and interpolations appended to them in one or more properties.\n /// `init(stringInterpolation:)` should use these properties to initialize\n /// the instance.\n /// \n /// - Parameter stringInterpolation: An instance of `StringInterpolation`\n /// which has had each segment of the string literal appended\n /// to it.\n init(stringInterpolation: StringInterpolation)\n}\n\nextension ExpressibleByStringInterpolation\n where StringInterpolation == DefaultStringInterpolation {\n \n /// Creates a new instance from an interpolated string literal.\n /// \n /// Don't call this initializer directly. It's used by the compiler when\n /// you create a string using string interpolation. Instead, use string\n /// interpolation to create a new string by including values, literals,\n /// variables, or expressions enclosed in parentheses, prefixed by a\n /// backslash (`\(`...`)`).\n ///\n /// let price = 2\n /// let number = 3\n /// let message = """\n /// If one cookie costs \(price) dollars, \\n /// \(number) cookies cost \(price * number) dollars.\n /// """\n /// // message == "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."\n public init(stringInterpolation: DefaultStringInterpolation) {\n self.init(stringLiteral: stringInterpolation.make())\n }\n}\n\n/// Represents the contents of a string literal with interpolations while it's\n/// being built up.\n/// \n/// Each `ExpressibleByStringInterpolation` type has an associated\n/// `StringInterpolation` type which conforms to `StringInterpolationProtocol`.\n/// Swift converts an expression like `"The time is \(time)." as MyString` into\n/// a series of statements similar to:\n/// \n/// var interpolation = MyString.StringInterpolation(literalCapacity: 13, \n/// interpolationCount: 1)\n/// \n/// interpolation.appendLiteral("The time is ")\n/// interpolation.appendInterpolation(time)\n/// interpolation.appendLiteral(".")\n///\n/// MyString(stringInterpolation: interpolation)\n/// \n/// The `StringInterpolation` type is responsible for collecting the segments\n/// passed to its `appendLiteral(_:)` and `appendInterpolation` methods and\n/// assembling them into a whole, converting as necessary. Once all of the\n/// segments are appended, the interpolation is passed to an\n/// `init(stringInterpolation:)` initializer on the type being created, which\n/// must extract the accumulated data from the `StringInterpolation`.\n/// \n/// In simple cases, you can use `DefaultStringInterpolation` as the\n/// interpolation type for types that conform to the\n/// `ExpressibleByStringLiteral` protocol. To use the default interpolation,\n/// conform a type to `ExpressibleByStringInterpolation` and implement\n/// `init(stringLiteral: String)`. Values in interpolations are converted to\n/// strings, and then passed to that initializer just like any other string\n/// literal.\n/// \n/// Handling String Interpolations\n/// ==============================\n///\n/// With a custom interpolation type, each interpolated segment is translated\n/// into a call to a special `appendInterpolation` method. The contents of\n/// the interpolation's parentheses are treated as the call's argument list.\n/// That argument list can include multiple arguments and argument labels.\n///\n/// The following examples show how string interpolations are translated into\n/// calls to `appendInterpolation`:\n///\n/// - `\(x)` translates to `appendInterpolation(x)`\n/// - `\(x, y)` translates to `appendInterpolation(x, y)`\n/// - `\(foo: x)` translates to `appendInterpolation(foo: x)`\n/// - `\(x, foo: y)` translates to `appendInterpolation(x, foo: y)`\n///\n/// The `appendInterpolation` methods in your custom type must be mutating\n/// instance methods that return `Void`. This code shows a custom interpolation\n/// type's declaration of an `appendInterpolation` method that provides special\n/// validation for user input:\n///\n/// extension MyString.StringInterpolation {\n/// mutating func appendInterpolation(validating input: String) {\n/// // Perform validation of `input` and store for later use\n/// }\n/// }\n///\n/// To use this interpolation method, create a string literal with an\n/// interpolation using the `validating` parameter label.\n///\n/// let userInput = readLine() ?? ""\n/// let myString = "The user typed '\(validating: userInput)'." as MyString\n///\n/// `appendInterpolation` methods support virtually all features of methods:\n/// they can have any number of parameters, can specify labels for any or all\n/// of their parameters, can provide default values, can have variadic\n/// parameters, and can have parameters with generic types. Most importantly,\n/// they can be overloaded, so a type that conforms to\n/// `StringInterpolationProtocol` can provide several different\n/// `appendInterpolation` methods with different behaviors. An\n/// `appendInterpolation` method can also throw; when a user writes a literal\n/// with one of these interpolations, they must mark the string literal with\n/// `try` or one of its variants.\npublic protocol StringInterpolationProtocol {\n /// The type that should be used for literal segments.\n associatedtype StringLiteralType: _ExpressibleByBuiltinStringLiteral\n\n /// Creates an empty instance ready to be filled with string literal content.\n /// \n /// Don't call this initializer directly. Instead, initialize a variable or\n /// constant using a string literal with interpolated expressions.\n /// \n /// Swift passes this initializer a pair of arguments specifying the size of\n /// the literal segments and the number of interpolated segments. Use this\n /// information to estimate the amount of storage you will need.\n /// \n /// - Parameter literalCapacity: The approximate size of all literal segments\n /// combined. This is meant to be passed to `String.reserveCapacity(_:)`;\n /// it may be slightly larger or smaller than the sum of the counts of each\n /// literal segment.\n /// - Parameter interpolationCount: The number of interpolations which will be\n /// appended. Use this value to estimate how much additional capacity will\n /// be needed for the interpolated segments.\n init(literalCapacity: Int, interpolationCount: Int)\n\n /// Appends a literal segment to the interpolation.\n /// \n /// Don't call this method directly. Instead, initialize a variable or\n /// constant using a string literal with interpolated expressions.\n /// \n /// Interpolated expressions don't pass through this method; instead, Swift\n /// selects an overload of `appendInterpolation`. For more information, see\n /// the top-level `StringInterpolationProtocol` documentation.\n /// \n /// - Parameter literal: A string literal containing the characters\n /// that appear next in the string literal.\n mutating func appendLiteral(_ literal: StringLiteralType)\n\n // Informal requirement: Any desired appendInterpolation overloads, e.g.:\n // \n // mutating func appendInterpolation<T>(_: T)\n // mutating func appendInterpolation(_: Int, radix: Int)\n // mutating func appendInterpolation<T: Encodable>(json: T) throws\n}\n\n/// A type that can be initialized using a color literal (e.g.\n/// `#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)`).\npublic protocol _ExpressibleByColorLiteral {\n /// Creates an instance initialized with the given properties of a color\n /// literal.\n ///\n /// Do not call this initializer directly. Instead, initialize a variable or\n /// constant using a color literal.\n init(_colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float)\n}\n\n/// A type that can be initialized using an image literal (e.g.\n/// `#imageLiteral(resourceName: "hi.png")`).\n@_unavailableInEmbedded\npublic protocol _ExpressibleByImageLiteral {\n /// Creates an instance initialized with the given resource name.\n ///\n /// Do not call this initializer directly. Instead, initialize a variable or\n /// constant using an image literal.\n init(imageLiteralResourceName path: String)\n}\n\n/// A type that can be initialized using a file reference literal (e.g.\n/// `#fileLiteral(resourceName: "resource.txt")`).\n@_unavailableInEmbedded\npublic protocol _ExpressibleByFileReferenceLiteral {\n /// Creates an instance initialized with the given resource name.\n ///\n /// Do not call this initializer directly. Instead, initialize a variable or\n /// constant using a file reference literal.\n init(fileReferenceLiteralResourceName path: String)\n}\n\n/// A container is destructor safe if whether it may store to memory on\n/// destruction only depends on its type parameters destructors.\n/// For example, whether `Array<Element>` may store to memory on destruction\n/// depends only on `Element`.\n/// If `Element` is an `Int` we know the `Array<Int>` does not store to memory\n/// during destruction. If `Element` is an arbitrary class\n/// `Array<MemoryUnsafeDestructorClass>` then the compiler will deduce may\n/// store to memory on destruction because `MemoryUnsafeDestructorClass`'s\n/// destructor may store to memory on destruction.\n/// If in this example during `Array`'s destructor we would call a method on any\n/// type parameter - say `Element.extraCleanup()` - that could store to memory,\n/// then Array would no longer be a _DestructorSafeContainer.\npublic protocol _DestructorSafeContainer {\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_CompilerProtocols.swift | cpp_apple_swift_stdlib_public_core_CompilerProtocols.swift | Swift | 41,378 | 0.95 | 0.04888 | 0.83423 | awesome-app | 144 | 2025-04-07T03:40:53.884524 | MIT | false | 522f60a1eef2b1fa4825e017d5f76b95 |
//===--- ContiguousArray.swift --------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Three generic, mutable array-like types with value semantics.\n//\n// - `ContiguousArray<Element>` is a fast, contiguous array of `Element` with\n// a known backing store.\n//\n//===----------------------------------------------------------------------===//\n\n/// A contiguously stored array.\n///\n/// The `ContiguousArray` type is a specialized array that always stores its\n/// elements in a contiguous region of memory. This contrasts with `Array`,\n/// which can store its elements in either a contiguous region of memory or an\n/// `NSArray` instance if its `Element` type is a class or `@objc` protocol.\n///\n/// If your array's `Element` type is a class or `@objc` protocol and you do\n/// not need to bridge the array to `NSArray` or pass the array to Objective-C\n/// APIs, using `ContiguousArray` may be more efficient and have more\n/// predictable performance than `Array`. If the array's `Element` type is a\n/// struct or enumeration, `Array` and `ContiguousArray` should have similar\n/// efficiency.\n///\n/// For more information about using arrays, see `Array` and `ArraySlice`, with\n/// which `ContiguousArray` shares most properties and methods.\n@frozen\n@_eagerMove\n@safe\npublic struct ContiguousArray<Element>: _DestructorSafeContainer {\n @usableFromInline\n internal typealias _Buffer = _ContiguousArrayBuffer<Element>\n\n @usableFromInline\n internal var _buffer: _Buffer\n\n /// Initialization from an existing buffer does not have "array.init"\n /// semantics because the caller may retain an alias to buffer.\n @inlinable\n internal init(_buffer: _Buffer) {\n self._buffer = _buffer\n }\n}\n\n//===--- private helpers---------------------------------------------------===//\nextension ContiguousArray {\n @inlinable\n @inline(__always)\n @_semantics("array.get_count")\n internal func _getCount() -> Int {\n return _buffer.immutableCount\n }\n\n @inlinable\n @_semantics("array.get_capacity")\n internal func _getCapacity() -> Int {\n return _buffer.immutableCapacity\n }\n\n @inlinable\n @_semantics("array.make_mutable")\n internal mutating func _makeMutableAndUnique() {\n if _slowPath(!_buffer.beginCOWMutation()) {\n _buffer = _buffer._consumeAndCreateNew()\n }\n }\n\n /// Marks the end of an Array mutation.\n ///\n /// After a call to `_endMutation` the buffer must not be mutated until a call\n /// to `_makeMutableAndUnique`.\n @_alwaysEmitIntoClient\n @_semantics("array.end_mutation")\n internal mutating func _endMutation() {\n _buffer.endCOWMutation()\n }\n\n /// Check that the given `index` is valid for subscripting, i.e.\n /// `0 ≤ index < count`.\n @inlinable\n @inline(__always)\n internal func _checkSubscript_native(_ index: Int) {\n _buffer._checkValidSubscript(index)\n }\n\n /// Check that the given `index` is valid for subscripting, i.e.\n /// `0 ≤ index < count`.\n ///\n /// - Precondition: The buffer must be uniquely referenced and native.\n @_alwaysEmitIntoClient\n @_semantics("array.check_subscript")\n internal func _checkSubscript_mutating(_ index: Int) {\n _buffer._checkValidSubscriptMutating(index)\n }\n\n /// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`.\n @inlinable\n @_semantics("array.check_index")\n internal func _checkIndex(_ index: Int) {\n _precondition(index <= endIndex, "ContiguousArray index is out of range")\n _precondition(index >= startIndex, "Negative ContiguousArray index is out of range")\n }\n\n @inlinable\n @_semantics("array.get_element_address")\n internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> {\n return unsafe _buffer.firstElementAddress + index\n }\n}\n\nextension ContiguousArray: _ArrayProtocol {\n /// The total number of elements that the array can contain without\n /// allocating new storage.\n ///\n /// Every array reserves a specific amount of memory to hold its contents.\n /// When you add elements to an array and that array begins to exceed its\n /// reserved capacity, the array allocates a larger region of memory and\n /// copies its elements into the new storage. The new storage is a multiple\n /// of the old storage's size. This exponential growth strategy means that\n /// appending an element happens in constant time, averaging the performance\n /// of many append operations. Append operations that trigger reallocation\n /// have a performance cost, but they occur less and less often as the array\n /// grows larger.\n ///\n /// The following example creates an array of integers from an array literal,\n /// then appends the elements of another collection. Before appending, the\n /// array allocates new storage that is large enough store the resulting\n /// elements.\n ///\n /// var numbers = [10, 20, 30, 40, 50]\n /// // numbers.count == 5\n /// // numbers.capacity == 5\n ///\n /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10))\n /// // numbers.count == 10\n /// // numbers.capacity == 10\n @inlinable\n public var capacity: Int {\n return _getCapacity()\n }\n\n #if $Embedded\n public typealias AnyObject = Builtin.NativeObject\n #endif\n\n /// An object that guarantees the lifetime of this array's elements.\n @inlinable\n public // @testable\n var _owner: AnyObject? {\n return _buffer.owner\n }\n\n /// If the elements are stored contiguously, a pointer to the first\n /// element. Otherwise, `nil`.\n @inlinable\n public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? {\n @inline(__always) // FIXME(TODO: JIRA): Hack around test failure\n get { return unsafe _buffer.firstElementAddressIfContiguous }\n }\n\n @inlinable\n internal var _baseAddress: UnsafeMutablePointer<Element> {\n return unsafe _buffer.firstElementAddress\n }\n}\n\nextension ContiguousArray: RandomAccessCollection, MutableCollection {\n /// The index type for arrays, `Int`.\n public typealias Index = Int\n\n /// The type that represents the indices that are valid for subscripting an\n /// array, in ascending order.\n public typealias Indices = Range<Int>\n\n /// The type that allows iteration over an array's elements.\n public typealias Iterator = IndexingIterator<ContiguousArray>\n\n /// The position of the first element in a nonempty array.\n ///\n /// For an instance of `ContiguousArray`, `startIndex` is always zero. If the array\n /// is empty, `startIndex` is equal to `endIndex`.\n @inlinable\n public var startIndex: Int {\n return 0\n }\n\n /// The array's "past the end" position---that is, the position one greater\n /// than the last valid subscript argument.\n ///\n /// When you need a range that includes the last element of an array, use the\n /// half-open range operator (`..<`) with `endIndex`. The `..<` operator\n /// creates a range that doesn't include the upper bound, so it's always\n /// safe to use with `endIndex`. For example:\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// if let i = numbers.firstIndex(of: 30) {\n /// print(numbers[i ..< numbers.endIndex])\n /// }\n /// // Prints "[30, 40, 50]"\n ///\n /// If the array is empty, `endIndex` is equal to `startIndex`.\n public var endIndex: Int {\n @inlinable\n @inline(__always)\n get {\n return _getCount()\n }\n }\n\n /// Returns the position immediately after the given index.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be less than\n /// `endIndex`.\n /// - Returns: The index immediately after `i`.\n @inlinable\n public func index(after i: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return i + 1\n }\n\n /// Replaces the given index with its successor.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be less than\n /// `endIndex`.\n @inlinable\n public func formIndex(after i: inout Int) {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n i += 1\n }\n\n /// Returns the position immediately before the given index.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be greater than\n /// `startIndex`.\n /// - Returns: The index immediately before `i`.\n @inlinable\n public func index(before i: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return i - 1\n }\n\n /// Replaces the given index with its predecessor.\n ///\n /// - Parameter i: A valid index of the collection. `i` must be greater than\n /// `startIndex`.\n @inlinable\n public func formIndex(before i: inout Int) {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n i -= 1\n }\n\n /// Returns an index that is the specified distance from the given index.\n ///\n /// The following example obtains an index advanced four positions from an\n /// array's starting index and then prints the element at that position.\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// let i = numbers.index(numbers.startIndex, offsetBy: 4)\n /// print(numbers[i])\n /// // Prints "50"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection.\n ///\n /// - Parameters:\n /// - i: A valid index of the array.\n /// - distance: The distance to offset `i`.\n /// - Returns: An index offset by `distance` from the index `i`. If\n /// `distance` is positive, this is the same value as the result of\n /// `distance` calls to `index(after:)`. If `distance` is negative, this\n /// is the same value as the result of `abs(distance)` calls to\n /// `index(before:)`.\n @inlinable\n public func index(_ i: Int, offsetBy distance: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return i + distance\n }\n\n /// Returns an index that is the specified distance from the given index,\n /// unless that distance is beyond a given limiting index.\n ///\n /// The following example obtains an index advanced four positions from an\n /// array's starting index and then prints the element at that position. The\n /// operation doesn't require going beyond the limiting `numbers.endIndex`\n /// value, so it succeeds.\n ///\n /// let numbers = [10, 20, 30, 40, 50]\n /// if let i = numbers.index(numbers.startIndex,\n /// offsetBy: 4,\n /// limitedBy: numbers.endIndex) {\n /// print(numbers[i])\n /// }\n /// // Prints "50"\n ///\n /// The next example attempts to retrieve an index ten positions from\n /// `numbers.startIndex`, but fails, because that distance is beyond the\n /// index passed as `limit`.\n ///\n /// let j = numbers.index(numbers.startIndex,\n /// offsetBy: 10,\n /// limitedBy: numbers.endIndex)\n /// print(j)\n /// // Prints "nil"\n ///\n /// The value passed as `distance` must not offset `i` beyond the bounds of\n /// the collection, unless the index passed as `limit` prevents offsetting\n /// beyond those bounds.\n ///\n /// - Parameters:\n /// - i: A valid index of the array.\n /// - distance: The distance to offset `i`.\n /// - limit: A valid index of the collection to use as a limit. If\n /// `distance > 0`, `limit` has no effect if it is less than `i`.\n /// Likewise, if `distance < 0`, `limit` has no effect if it is greater\n /// than `i`.\n /// - Returns: An index offset by `distance` from the index `i`, unless that\n /// index would be beyond `limit` in the direction of movement. In that\n /// case, the method returns `nil`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func index(\n _ i: Int, offsetBy distance: Int, limitedBy limit: Int\n ) -> Int? {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n let l = limit - i\n if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l {\n return nil\n }\n return i + distance\n }\n\n /// Returns the distance between two indices.\n ///\n /// - Parameters:\n /// - start: A valid index of the collection.\n /// - end: Another valid index of the collection. If `end` is equal to\n /// `start`, the result is zero.\n /// - Returns: The distance between `start` and `end`.\n @inlinable\n public func distance(from start: Int, to end: Int) -> Int {\n // NOTE: this is a manual specialization of index movement for a Strideable\n // index that is required for Array performance. The optimizer is not\n // capable of creating partial specializations yet.\n // NOTE: Range checks are not performed here, because it is done later by\n // the subscript function.\n return end - start\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) {\n // NOTE: This method is a no-op for performance reasons.\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) {\n // NOTE: This method is a no-op for performance reasons.\n }\n\n /// Accesses the element at the specified position.\n ///\n /// The following example uses indexed subscripting to update an array's\n /// second element. After assigning the new value (`"Butler"`) at a specific\n /// position, that value is immediately available at that same position.\n ///\n /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// streets[1] = "Butler"\n /// print(streets[1])\n /// // Prints "Butler"\n ///\n /// - Parameter index: The position of the element to access. `index` must be\n /// greater than or equal to `startIndex` and less than `endIndex`.\n ///\n /// - Complexity: Reading an element from an array is O(1). Writing is O(1)\n /// unless the array's storage is shared with another array, in which case\n /// writing is O(*n*), where *n* is the length of the array.\n @inlinable\n public subscript(index: Int) -> Element {\n get {\n _checkSubscript_native(index)\n return _buffer.getElement(index)\n }\n _modify {\n _makeMutableAndUnique()\n _checkSubscript_mutating(index)\n let address = unsafe _buffer.mutableFirstElementAddress + index\n defer { _endMutation() }\n yield unsafe &address.pointee\n }\n }\n\n /// Accesses a contiguous subrange of the array's elements.\n ///\n /// The returned `ArraySlice` instance uses the same indices for the same\n /// elements as the original array. In particular, that slice, unlike an\n /// array, may have a nonzero `startIndex` and an `endIndex` that is not\n /// equal to `count`. Always use the slice's `startIndex` and `endIndex`\n /// properties instead of assuming that its indices start or end at a\n /// particular value.\n ///\n /// This example demonstrates getting a slice of an array of strings, finding\n /// the index of one of the strings in the slice, and then using that index\n /// in the original array.\n ///\n /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// let streetsSlice = streets[2 ..< streets.endIndex]\n /// print(streetsSlice)\n /// // Prints "["Channing", "Douglas", "Evarts"]"\n ///\n /// let i = streetsSlice.firstIndex(of: "Evarts") // 4\n /// print(streets[i!])\n /// // Prints "Evarts"\n ///\n /// - Parameter bounds: A range of integers. The bounds of the range must be\n /// valid indices of the array.\n @inlinable\n public subscript(bounds: Range<Int>) -> ArraySlice<Element> {\n get {\n _checkIndex(bounds.lowerBound)\n _checkIndex(bounds.upperBound)\n return ArraySlice(_buffer: _buffer[bounds])\n }\n set(rhs) {\n _checkIndex(bounds.lowerBound)\n _checkIndex(bounds.upperBound)\n // If the replacement buffer has same identity, and the ranges match,\n // then this was a pinned in-place modification, nothing further needed.\n if unsafe self[bounds]._buffer.identity != rhs._buffer.identity\n || bounds != rhs.startIndex..<rhs.endIndex {\n self.replaceSubrange(bounds, with: rhs)\n }\n }\n }\n\n /// The number of elements in the array.\n @inlinable\n public var count: Int {\n return _getCount()\n }\n}\n\nextension ContiguousArray: ExpressibleByArrayLiteral {\n /// Creates an array from the given array literal.\n ///\n /// Do not call this initializer directly. It is used by the compiler when\n /// you use an array literal. Instead, create a new array by using an array\n /// literal as its value. To do this, enclose a comma-separated list of\n /// values in square brackets.\n ///\n /// Here, an array of strings is created from an array literal holding only\n /// strings:\n ///\n /// let ingredients: ContiguousArray =\n /// ["cocoa beans", "sugar", "cocoa butter", "salt"]\n ///\n /// - Parameter elements: A variadic list of elements of the new array.\n @inlinable\n public init(arrayLiteral elements: Element...) {\n self.init(_buffer: ContiguousArray(elements)._buffer)\n }\n}\n\n\nextension ContiguousArray: RangeReplaceableCollection {\n /// Creates a new, empty array.\n ///\n /// This is equivalent to initializing with an empty array literal.\n /// For example:\n ///\n /// var emptyArray = Array<Int>()\n /// print(emptyArray.isEmpty)\n /// // Prints "true"\n ///\n /// emptyArray = []\n /// print(emptyArray.isEmpty)\n /// // Prints "true"\n @inlinable\n @_semantics("array.init.empty")\n public init() {\n _buffer = _Buffer()\n }\n\n /// Creates an array containing the elements of a sequence.\n ///\n /// You can use this initializer to create an array from any other type that\n /// conforms to the `Sequence` protocol. For example, you might want to\n /// create an array with the integers from 1 through 7. Use this initializer\n /// around a range instead of typing all those numbers in an array literal.\n ///\n /// let numbers = Array(1...7)\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 6, 7]"\n ///\n /// You can also use this initializer to convert a complex sequence or\n /// collection type back to an array. For example, the `keys` property of\n /// a dictionary isn't an array with its own storage, it's a collection\n /// that maps its elements from the dictionary only when they're\n /// accessed, saving the time and space needed to allocate an array. If\n /// you need to pass those keys to a method that takes an array, however,\n /// use this initializer to convert that list from its type of\n /// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple\n /// `[String]`.\n ///\n /// func cacheImagesWithNames(names: [String]) {\n /// // custom image loading and caching\n /// }\n ///\n /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302,\n /// "Gold": 50, "Cerise": 320]\n /// let colorNames = Array(namedHues.keys)\n /// cacheImagesWithNames(colorNames)\n ///\n /// print(colorNames)\n /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]"\n ///\n /// - Parameter s: The sequence of elements to turn into an array.\n @inlinable\n public init<S: Sequence>(_ s: S) where S.Element == Element {\n self.init(_buffer: s._copyToContiguousArray()._buffer)\n }\n\n /// Creates a new array containing the specified number of a single, repeated\n /// value.\n ///\n /// Here's an example of creating an array initialized with five strings\n /// containing the letter *Z*.\n ///\n /// let fiveZs = Array(repeating: "Z", count: 5)\n /// print(fiveZs)\n /// // Prints "["Z", "Z", "Z", "Z", "Z"]"\n ///\n /// - Parameters:\n /// - repeatedValue: The element to repeat.\n /// - count: The number of times to repeat the value passed in the\n /// `repeating` parameter. `count` must be zero or greater.\n @inlinable\n @_semantics("array.init")\n public init(repeating repeatedValue: Element, count: Int) {\n var p: UnsafeMutablePointer<Element>\n unsafe (self, p) = ContiguousArray._allocateUninitialized(count)\n for _ in 0..<count {\n unsafe p.initialize(to: repeatedValue)\n unsafe p += 1\n }\n _endMutation()\n }\n\n @inline(never)\n @usableFromInline\n internal static func _allocateBufferUninitialized(\n minimumCapacity: Int\n ) -> _Buffer {\n let newBuffer = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: 0, minimumCapacity: minimumCapacity)\n return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0)\n }\n\n /// Construct a ContiguousArray of `count` uninitialized elements.\n @inlinable\n internal init(_uninitializedCount count: Int) {\n _precondition(count >= 0, "Can't construct ContiguousArray with count < 0")\n // Note: Sinking this constructor into an else branch below causes an extra\n // Retain/Release.\n _buffer = _Buffer()\n if count > 0 {\n // Creating a buffer instead of calling reserveCapacity saves doing an\n // unnecessary uniqueness check. We disable inlining here to curb code\n // growth.\n _buffer = ContiguousArray._allocateBufferUninitialized(minimumCapacity: count)\n _buffer.mutableCount = count\n }\n // Can't store count here because the buffer might be pointing to the\n // shared empty array.\n }\n\n /// Entry point for `Array` literal construction; builds and returns\n /// a ContiguousArray of `count` uninitialized elements.\n @inlinable\n @_semantics("array.uninitialized")\n internal static func _allocateUninitialized(\n _ count: Int\n ) -> (ContiguousArray, UnsafeMutablePointer<Element>) {\n let result = ContiguousArray(_uninitializedCount: count)\n return unsafe (result, result._buffer.firstElementAddress)\n }\n\n //===--- basic mutations ------------------------------------------------===//\n\n /// Reserves enough space to store the specified number of elements.\n ///\n /// If you are adding a known number of elements to an array, use this method\n /// to avoid multiple reallocations. This method ensures that the array has\n /// unique, mutable, contiguous storage, with space allocated for at least\n /// the requested number of elements.\n ///\n /// For performance reasons, the size of the newly allocated storage might be\n /// greater than the requested capacity. Use the array's `capacity` property\n /// to determine the size of the new storage.\n ///\n /// Preserving an Array's Geometric Growth Strategy\n /// ===============================================\n ///\n /// If you implement a custom data structure backed by an array that grows\n /// dynamically, naively calling the `reserveCapacity(_:)` method can lead\n /// to worse than expected performance. Arrays need to follow a geometric\n /// allocation pattern for appending elements to achieve amortized\n /// constant-time performance. The `Array` type's `append(_:)` and\n /// `append(contentsOf:)` methods take care of this detail for you, but\n /// `reserveCapacity(_:)` allocates only as much space as you tell it to\n /// (padded to a round value), and no more. This avoids over-allocation, but\n /// can result in insertion not having amortized constant-time performance.\n ///\n /// The following code declares `values`, an array of integers, and the\n /// `addTenQuadratic()` function, which adds ten more values to the `values`\n /// array on each call.\n ///\n /// var values: [Int] = [0, 1, 2, 3]\n ///\n /// // Don't use 'reserveCapacity(_:)' like this\n /// func addTenQuadratic() {\n /// let newCount = values.count + 10\n /// values.reserveCapacity(newCount)\n /// for n in values.count..<newCount {\n /// values.append(n)\n /// }\n /// }\n ///\n /// The call to `reserveCapacity(_:)` increases the `values` array's capacity\n /// by exactly 10 elements on each pass through `addTenQuadratic()`, which\n /// is linear growth. Instead of having constant time when averaged over\n /// many calls, the function may decay to performance that is linear in\n /// `values.count`. This is almost certainly not what you want.\n ///\n /// In cases like this, the simplest fix is often to simply remove the call\n /// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array\n /// for you.\n ///\n /// func addTen() {\n /// let newCount = values.count + 10\n /// for n in values.count..<newCount {\n /// values.append(n)\n /// }\n /// }\n ///\n /// If you need more control over the capacity of your array, implement your\n /// own geometric growth strategy, passing the size you compute to\n /// `reserveCapacity(_:)`.\n ///\n /// - Parameter minimumCapacity: The requested number of elements to store.\n ///\n /// - Complexity: O(*n*), where *n* is the number of elements in the array.\n @inlinable\n @_semantics("array.mutate_unknown")\n public mutating func reserveCapacity(_ minimumCapacity: Int) {\n _reserveCapacityImpl(minimumCapacity: minimumCapacity,\n growForAppend: false)\n _endMutation()\n }\n\n /// Reserves enough space to store `minimumCapacity` elements.\n /// If a new buffer needs to be allocated and `growForAppend` is true,\n /// the new capacity is calculated using `_growArrayCapacity`.\n @_alwaysEmitIntoClient\n internal mutating func _reserveCapacityImpl(\n minimumCapacity: Int, growForAppend: Bool\n ) {\n let isUnique = _buffer.beginCOWMutation()\n if _slowPath(!isUnique || _buffer.mutableCapacity < minimumCapacity) {\n _createNewBuffer(bufferIsUnique: isUnique,\n minimumCapacity: Swift.max(minimumCapacity, _buffer.count),\n growForAppend: growForAppend)\n }\n _internalInvariant(_buffer.mutableCapacity >= minimumCapacity)\n _internalInvariant(_buffer.mutableCapacity == 0 || _buffer.isUniquelyReferenced())\n }\n\n /// Creates a new buffer, replacing the current buffer.\n ///\n /// If `bufferIsUnique` is true, the buffer is assumed to be uniquely\n /// referenced by this array and the elements are moved - instead of copied -\n /// to the new buffer.\n /// The `minimumCapacity` is the lower bound for the new capacity.\n /// If `growForAppend` is true, the new capacity is calculated using\n /// `_growArrayCapacity`.\n @_alwaysEmitIntoClient\n @inline(never)\n internal mutating func _createNewBuffer(\n bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool\n ) {\n _internalInvariant(!bufferIsUnique || _buffer.isUniquelyReferenced())\n _buffer = _buffer._consumeAndCreateNew(bufferIsUnique: bufferIsUnique,\n minimumCapacity: minimumCapacity,\n growForAppend: growForAppend)\n }\n\n /// Copy the contents of the current buffer to a new unique mutable buffer.\n /// The count of the new buffer is set to `oldCount`, the capacity of the\n /// new buffer is big enough to hold 'oldCount' + 1 elements.\n @inline(never)\n @inlinable // @specializable\n internal mutating func _copyToNewBuffer(oldCount: Int) {\n let newCount = oldCount &+ 1\n var newBuffer = _buffer._forceCreateUniqueMutableBuffer(\n countForNewBuffer: oldCount, minNewCapacity: newCount)\n unsafe _buffer._arrayOutOfPlaceUpdate(\n &newBuffer, oldCount, 0)\n }\n\n @inlinable\n @_semantics("array.make_mutable")\n internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() {\n if _slowPath(!_buffer.beginCOWMutation()) {\n _createNewBuffer(bufferIsUnique: false,\n minimumCapacity: count &+ 1,\n growForAppend: true)\n }\n }\n\n @inlinable\n @_semantics("array.mutate_unknown")\n internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) {\n // Due to make_mutable hoisting the situation can arise where we hoist\n // _makeMutableAndUnique out of loop and use it to replace\n // _makeUniqueAndReserveCapacityIfNotUnique that precedes this call. If the\n // array was empty _makeMutableAndUnique does not replace the empty array\n // buffer by a unique buffer (it just replaces it by the empty array\n // singleton).\n // This specific case is okay because we will make the buffer unique in this\n // function because we request a capacity > 0 and therefore _copyToNewBuffer\n // will be called creating a new buffer.\n let capacity = _buffer.mutableCapacity\n _internalInvariant(capacity == 0 || _buffer.isMutableAndUniquelyReferenced())\n\n if _slowPath(oldCount &+ 1 > capacity) {\n _createNewBuffer(bufferIsUnique: capacity > 0,\n minimumCapacity: oldCount &+ 1,\n growForAppend: true)\n }\n }\n\n @inlinable\n @_semantics("array.mutate_unknown")\n internal mutating func _appendElementAssumeUniqueAndCapacity(\n _ oldCount: Int,\n newElement: __owned Element\n ) {\n _internalInvariant(_buffer.isMutableAndUniquelyReferenced())\n _internalInvariant(_buffer.mutableCapacity >= _buffer.mutableCount &+ 1)\n\n _buffer.mutableCount = oldCount &+ 1\n unsafe (_buffer.mutableFirstElementAddress + oldCount).initialize(to: newElement)\n }\n\n /// Adds a new element at the end of the array.\n ///\n /// Use this method to append a single element to the end of a mutable array.\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.append(100)\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 100]"\n ///\n /// Because arrays increase their allocated capacity using an exponential\n /// strategy, appending a single element to an array is an O(1) operation\n /// when averaged over many calls to the `append(_:)` method. When an array\n /// has additional capacity and is not sharing its storage with another\n /// instance, appending an element is O(1). When an array needs to\n /// reallocate storage before appending or its storage is shared with\n /// another copy, appending is O(*n*), where *n* is the length of the array.\n ///\n /// - Parameter newElement: The element to append to the array.\n ///\n /// - Complexity: O(1) on average, over many calls to `append(_:)` on the\n /// same array.\n @inlinable\n @_semantics("array.append_element")\n public mutating func append(_ newElement: __owned Element) {\n // Separating uniqueness check and capacity check allows hoisting the\n // uniqueness check out of a loop.\n _makeUniqueAndReserveCapacityIfNotUnique()\n let oldCount = _buffer.mutableCount\n _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount)\n _appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement)\n _endMutation()\n }\n\n /// Adds the elements of a sequence to the end of the array.\n ///\n /// Use this method to append the elements of a sequence to the end of this\n /// array. This example appends the elements of a `Range<Int>` instance\n /// to an array of integers.\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.append(contentsOf: 10...15)\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"\n ///\n /// - Parameter newElements: The elements to append to the array.\n ///\n /// - Complexity: O(*m*) on average, where *m* is the length of\n /// `newElements`, over many calls to `append(contentsOf:)` on the same\n /// array.\n @inlinable\n @_semantics("array.append_contentsOf")\n public mutating func append<S: Sequence>(contentsOf newElements: __owned S)\n where S.Element == Element {\n\n defer {\n _endMutation()\n }\n\n let newElementsCount = newElements.underestimatedCount\n _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount,\n growForAppend: true)\n\n let oldCount = _buffer.mutableCount\n let startNewElements = unsafe _buffer.mutableFirstElementAddress + oldCount\n let buf = unsafe UnsafeMutableBufferPointer(\n start: startNewElements, \n count: _buffer.mutableCapacity - oldCount)\n\n var (remainder,writtenUpTo) = unsafe buf.initialize(from: newElements)\n \n // trap on underflow from the sequence's underestimate:\n let writtenCount = unsafe buf.distance(from: buf.startIndex, to: writtenUpTo)\n _precondition(newElementsCount <= writtenCount, \n "newElements.underestimatedCount was an overestimate")\n // can't check for overflow as sequences can underestimate\n\n // This check prevents a data race writing to _swiftEmptyArrayStorage\n if writtenCount > 0 {\n _buffer.mutableCount = _buffer.mutableCount + writtenCount\n }\n\n if writtenUpTo == buf.endIndex {\n // there may be elements that didn't fit in the existing buffer,\n // append them in slow sequence-only mode\n var newCount = _buffer.mutableCount\n var nextItem = remainder.next()\n while nextItem != nil {\n _reserveCapacityAssumingUniqueBuffer(oldCount: newCount)\n\n let currentCapacity = _buffer.mutableCapacity\n let base = unsafe _buffer.mutableFirstElementAddress\n\n // fill while there is another item and spare capacity\n while let next = nextItem, newCount < currentCapacity {\n unsafe (base + newCount).initialize(to: next)\n newCount += 1\n nextItem = remainder.next()\n }\n _buffer.mutableCount = newCount\n }\n }\n }\n\n @inlinable\n @_semantics("array.reserve_capacity_for_append")\n internal mutating func reserveCapacityForAppend(newElementsCount: Int) {\n // Ensure uniqueness, mutability, and sufficient storage. Note that\n // for consistency, we need unique self even if newElements is empty.\n _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount,\n growForAppend: true)\n _endMutation()\n }\n\n @inlinable\n @_semantics("array.mutate_unknown")\n public mutating func _customRemoveLast() -> Element? {\n _makeMutableAndUnique()\n let newCount = _buffer.mutableCount - 1\n _precondition(newCount >= 0, "Can't removeLast from an empty ContiguousArray")\n let pointer = unsafe (_buffer.mutableFirstElementAddress + newCount)\n let element = unsafe pointer.move()\n _buffer.mutableCount = newCount\n _endMutation()\n return element\n }\n\n /// Removes and returns the element at the specified position.\n ///\n /// All the elements following the specified position are moved up to\n /// close the gap.\n ///\n /// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]\n /// let removed = measurements.remove(at: 2)\n /// print(measurements)\n /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]"\n ///\n /// - Parameter index: The position of the element to remove. `index` must\n /// be a valid index of the array.\n /// - Returns: The element at the specified index.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the array.\n @inlinable\n @discardableResult\n @_semantics("array.mutate_unknown")\n public mutating func remove(at index: Int) -> Element {\n _makeMutableAndUnique()\n let currentCount = _buffer.mutableCount\n _precondition(index < currentCount, "Index out of range")\n _precondition(index >= 0, "Index out of range")\n let newCount = currentCount - 1\n let pointer = unsafe (_buffer.mutableFirstElementAddress + index)\n let result = unsafe pointer.move()\n unsafe pointer.moveInitialize(from: pointer + 1, count: newCount - index)\n _buffer.mutableCount = newCount\n _endMutation()\n return result\n }\n\n /// Inserts a new element at the specified position.\n ///\n /// The new element is inserted before the element currently at the specified\n /// index. If you pass the array's `endIndex` property as the `index`\n /// parameter, the new element is appended to the array.\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.insert(100, at: 3)\n /// numbers.insert(200, at: numbers.endIndex)\n ///\n /// print(numbers)\n /// // Prints "[1, 2, 3, 100, 4, 5, 200]"\n ///\n /// - Parameter newElement: The new element to insert into the array.\n /// - Parameter i: The position at which to insert the new element.\n /// `index` must be a valid index of the array or equal to its `endIndex`\n /// property.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the array. If\n /// `i == endIndex`, this method is equivalent to `append(_:)`.\n @inlinable\n public mutating func insert(_ newElement: __owned Element, at i: Int) {\n _checkIndex(i)\n self.replaceSubrange(i..<i, with: CollectionOfOne(newElement))\n }\n\n /// Removes all elements from the array.\n ///\n /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of\n /// the array after removing its elements. The default value is\n /// `false`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the array.\n @inlinable\n public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {\n if !keepCapacity {\n _buffer = _Buffer()\n }\n else if _buffer.isMutableAndUniquelyReferenced() {\n self.replaceSubrange(indices, with: EmptyCollection())\n }\n else {\n _buffer = _Buffer(_uninitializedCount: 0, minimumCapacity: capacity)\n }\n }\n\n //===--- algorithms -----------------------------------------------------===//\n\n @inlinable\n @available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable")\n public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n return try unsafe withUnsafeMutableBufferPointer {\n (bufferPointer) -> R in\n return try unsafe body(&bufferPointer)\n }\n }\n\n @inlinable\n public mutating func withContiguousMutableStorageIfAvailable<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n return try unsafe withUnsafeMutableBufferPointer {\n (bufferPointer) -> R in\n return try unsafe body(&bufferPointer)\n }\n }\n \n @inlinable\n public func withContiguousStorageIfAvailable<R>(\n _ body: (UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n return try unsafe withUnsafeBufferPointer {\n (bufferPointer) -> R in\n return try unsafe body(bufferPointer)\n }\n }\n\n @inlinable\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n if let n = _buffer.requestNativeBuffer() {\n return ContiguousArray(_buffer: n)\n }\n return _copyCollectionToContiguousArray(self)\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension ContiguousArray: CustomReflectable {\n /// A mirror that reflects the array.\n public var customMirror: Mirror {\n return Mirror(\n self,\n unlabeledChildren: self,\n displayStyle: .collection)\n }\n}\n#endif\n\n@_unavailableInEmbedded\nextension ContiguousArray: CustomStringConvertible, CustomDebugStringConvertible {\n /// A textual representation of the array and its elements.\n public var description: String {\n return _makeCollectionDescription()\n }\n\n /// A textual representation of the array and its elements, suitable for\n /// debugging.\n public var debugDescription: String {\n return _makeCollectionDescription(withTypeName: "ContiguousArray")\n }\n}\n\nextension ContiguousArray {\n @usableFromInline @_transparent\n internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) {\n let p = unsafe _baseAddressIfContiguous\n if unsafe _fastPath(p != nil || isEmpty) {\n return (_owner, UnsafeRawPointer(p))\n }\n let n = ContiguousArray(self._buffer)._buffer\n return unsafe (n.owner, UnsafeRawPointer(n.firstElementAddress))\n }\n}\n\nextension ContiguousArray {\n /// Creates an array with the specified capacity, then calls the given\n /// closure with a buffer covering the array's uninitialized memory.\n ///\n /// Inside the closure, set the `initializedCount` parameter to the number of\n /// elements that are initialized by the closure. The memory in the range\n /// `buffer[0..<initializedCount]` must be initialized at the end of the\n /// closure's execution, and the memory in the range\n /// `buffer[initializedCount...]` must be uninitialized. This postcondition\n /// must hold even if the `initializer` closure throws an error.\n ///\n /// - Note: While the resulting array may have a capacity larger than the\n /// requested amount, the buffer passed to the closure will cover exactly\n /// the requested number of elements.\n ///\n /// - Parameters:\n /// - unsafeUninitializedCapacity: The number of elements to allocate\n /// space for in the new array.\n /// - initializer: A closure that initializes elements and sets the count\n /// of the new array.\n /// - Parameters:\n /// - buffer: A buffer covering uninitialized memory with room for the\n /// specified number of elements.\n /// - initializedCount: The count of initialized elements in the array,\n /// which begins as zero. Set `initializedCount` to the number of\n /// elements you initialize.\n @_alwaysEmitIntoClient @inlinable\n public init(\n unsafeUninitializedCapacity: Int,\n initializingWith initializer: (\n _ buffer: inout UnsafeMutableBufferPointer<Element>,\n _ initializedCount: inout Int) throws -> Void\n ) rethrows {\n self = try unsafe ContiguousArray(Array(\n _unsafeUninitializedCapacity: unsafeUninitializedCapacity,\n initializingWith: initializer))\n }\n\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n @usableFromInline\n @_disfavoredOverload\n func withUnsafeBufferPointer<R>(\n _ body: (UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R {\n return try unsafe _buffer.withUnsafeBufferPointer(body)\n }\n\n /// Calls a closure with a pointer to the array's contiguous storage.\n ///\n /// Often, the optimizer can eliminate bounds checks within an array\n /// algorithm, but when that fails, invoking the same algorithm on the\n /// buffer pointer passed into your closure lets you trade safety for speed.\n ///\n /// The following example shows how you can iterate over the contents of the\n /// buffer pointer:\n ///\n /// let numbers = [1, 2, 3, 4, 5]\n /// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in\n /// var result = 0\n /// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) {\n /// result += buffer[i]\n /// }\n /// return result\n /// }\n /// // 'sum' == 9\n ///\n /// The pointer passed as an argument to `body` is valid only during the\n /// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the\n /// pointer for later use.\n ///\n /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that\n /// points to the contiguous storage for the array. If\n /// `body` has a return value, that value is also used as the return value\n /// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is\n /// valid only for the duration of the method's execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @_alwaysEmitIntoClient\n public func withUnsafeBufferPointer<R, E>(\n _ body: (UnsafeBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n return try unsafe _buffer.withUnsafeBufferPointer(body)\n }\n\n @available(SwiftStdlib 6.2, *)\n public var span: Span<Element> {\n @lifetime(borrow self)\n @_alwaysEmitIntoClient\n borrowing get {\n let pointer = unsafe _buffer.firstElementAddress\n let count = _buffer.immutableCount\n let span = unsafe Span(_unsafeStart: pointer, count: count)\n return unsafe _overrideLifetime(span, borrowing: self)\n }\n }\n\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n @_semantics("array.withUnsafeMutableBufferPointer")\n @usableFromInline\n @inline(__always)\n @_silgen_name("$ss15ContiguousArrayV30withUnsafeMutableBufferPointeryqd__qd__SryxGzKXEKlF")\n mutating func __abi_withUnsafeMutableBufferPointer<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R {\n return try unsafe withUnsafeMutableBufferPointer(body)\n }\n\n /// Calls the given closure with a pointer to the array's mutable contiguous\n /// storage.\n ///\n /// Often, the optimizer can eliminate bounds checks within an array\n /// algorithm, but when that fails, invoking the same algorithm on the\n /// buffer pointer passed into your closure lets you trade safety for speed.\n ///\n /// The following example shows how modifying the contents of the\n /// `UnsafeMutableBufferPointer` argument to `body` alters the contents of\n /// the array:\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.withUnsafeMutableBufferPointer { buffer in\n /// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) {\n /// buffer.swapAt(i, i + 1)\n /// }\n /// }\n /// print(numbers)\n /// // Prints "[2, 1, 4, 3, 5]"\n ///\n /// The pointer passed as an argument to `body` is valid only during the\n /// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or\n /// return the pointer for later use.\n ///\n /// - Warning: Do not rely on anything about the array that is the target of\n /// this method during execution of the `body` closure; it might not\n /// appear to have its correct value. Instead, use only the\n /// `UnsafeMutableBufferPointer` argument to `body`.\n ///\n /// - Parameter body: A closure with an `UnsafeMutableBufferPointer`\n /// parameter that points to the contiguous storage for the array.\n /// If `body` has a return value, that value is also\n /// used as the return value for the `withUnsafeMutableBufferPointer(_:)`\n /// method. The pointer argument is valid only for the duration of the\n /// method's execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @_semantics("array.withUnsafeMutableBufferPointer")\n @_alwaysEmitIntoClient\n @inline(__always) // Performance: This method should get inlined into the\n // caller such that we can combine the partial apply with the apply in this\n // function saving on allocating a closure context. This becomes unnecessary\n // once we allocate noescape closures on the stack.\n public mutating func withUnsafeMutableBufferPointer<R, E>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n _makeMutableAndUnique()\n let count = _buffer.mutableCount\n\n // Create an UnsafeBufferPointer that we can pass to body\n let pointer = unsafe _buffer.mutableFirstElementAddress\n var inoutBufferPointer = unsafe UnsafeMutableBufferPointer(\n start: pointer, count: count)\n\n defer {\n unsafe _precondition(\n inoutBufferPointer.baseAddress == pointer &&\n inoutBufferPointer.count == count,\n "ContiguousArray withUnsafeMutableBufferPointer: replacing the buffer is not allowed")\n _endMutation()\n _fixLifetime(self)\n }\n\n // Invoke the body.\n return try unsafe body(&inoutBufferPointer)\n }\n\n @available(SwiftStdlib 6.2, *)\n public var mutableSpan: MutableSpan<Element> {\n @lifetime(&self)\n @_alwaysEmitIntoClient\n mutating get {\n _makeMutableAndUnique()\n // NOTE: We don't have the ability to schedule a call to\n // ContiguousArrayBuffer.endCOWMutation().\n // rdar://146785284 (lifetime analysis for end of mutation)\n let pointer = unsafe _buffer.firstElementAddress\n let count = _buffer.mutableCount\n let span = unsafe MutableSpan(_unsafeStart: pointer, count: count)\n return unsafe _overrideLifetime(span, mutating: &self)\n }\n }\n\n @inlinable\n public __consuming func _copyContents(\n initializing buffer: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {\n\n guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) }\n\n // It is not OK for there to be no pointer/not enough space, as this is\n // a precondition and Array never lies about its count.\n guard var p = buffer.baseAddress\n else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") }\n _precondition(self.count <= buffer.count, \n "Insufficient space allocated to copy array contents")\n\n if let s = unsafe _baseAddressIfContiguous {\n unsafe p.initialize(from: s, count: self.count)\n // Need a _fixLifetime bracketing the _baseAddressIfContiguous getter\n // and all uses of the pointer it returns:\n _fixLifetime(self._owner)\n } else {\n for x in self {\n unsafe p.initialize(to: x)\n unsafe p += 1\n }\n }\n\n var it = IndexingIterator(_elements: self)\n it._position = endIndex\n return (it,unsafe buffer.index(buffer.startIndex, offsetBy: self.count))\n }\n}\n\n\nextension ContiguousArray {\n /// Replaces a range of elements with the elements in the specified\n /// collection.\n ///\n /// This method has the effect of removing the specified range of elements\n /// from the array and inserting the new elements at the same location. The\n /// number of new elements need not match the number of elements being\n /// removed.\n ///\n /// In this example, three elements in the middle of an array of integers are\n /// replaced by the five elements of a `Repeated<Int>` instance.\n ///\n /// var nums = [10, 20, 30, 40, 50]\n /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))\n /// print(nums)\n /// // Prints "[10, 1, 1, 1, 1, 1, 50]"\n ///\n /// If you pass a zero-length range as the `subrange` parameter, this method\n /// inserts the elements of `newElements` at `subrange.startIndex`. Calling\n /// the `insert(contentsOf:at:)` method instead is preferred.\n ///\n /// Likewise, if you pass a zero-length collection as the `newElements`\n /// parameter, this method removes the elements in the given subrange\n /// without replacement. Calling the `removeSubrange(_:)` method instead is\n /// preferred.\n ///\n /// - Parameters:\n /// - subrange: The subrange of the array to replace. The start and end of\n /// a subrange must be valid indices of the array.\n /// - newElements: The new elements to add to the array.\n ///\n /// - Complexity: O(*n* + *m*), where *n* is length of the array and\n /// *m* is the length of `newElements`. If the call to this method simply\n /// appends the contents of `newElements` to the array, this method is\n /// equivalent to `append(contentsOf:)`.\n @inlinable\n @_semantics("array.mutate_unknown")\n public mutating func replaceSubrange<C>(\n _ subrange: Range<Int>,\n with newElements: __owned C\n ) where C: Collection, C.Element == Element {\n _precondition(subrange.lowerBound >= self._buffer.startIndex,\n "ContiguousArray replace: subrange start is negative")\n\n _precondition(subrange.upperBound <= _buffer.endIndex,\n "ContiguousArray replace: subrange extends past the end")\n\n let eraseCount = subrange.count\n let insertCount = newElements.count\n let growth = insertCount - eraseCount\n\n _reserveCapacityImpl(minimumCapacity: self.count + growth,\n growForAppend: true)\n _buffer.replaceSubrange(subrange, with: insertCount, elementsOf: newElements)\n _endMutation()\n }\n}\n\nextension ContiguousArray: Equatable where Element: Equatable {\n /// Returns a Boolean value indicating whether two arrays contain the same\n /// elements in the same order.\n ///\n /// You can use the equal-to operator (`==`) to compare any two arrays\n /// that store the same, `Equatable`-conforming element type.\n ///\n /// - Parameters:\n /// - lhs: An array to compare.\n /// - rhs: Another array to compare.\n @inlinable\n public static func ==(lhs: ContiguousArray<Element>, rhs: ContiguousArray<Element>) -> Bool {\n let lhsCount = lhs.count\n if lhsCount != rhs.count {\n return false\n }\n\n // Test referential equality.\n if unsafe lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity {\n return true\n }\n\n\n _internalInvariant(lhs.startIndex == 0 && rhs.startIndex == 0)\n _internalInvariant(lhs.endIndex == lhsCount && rhs.endIndex == lhsCount)\n\n // We know that lhs.count == rhs.count, compare element wise.\n for idx in 0..<lhsCount {\n if lhs[idx] != rhs[idx] {\n return false\n }\n }\n\n return true\n }\n}\n\nextension ContiguousArray: Hashable where Element: Hashable {\n /// Hashes the essential components of this value by feeding them into the\n /// given hasher.\n ///\n /// - Parameter hasher: The hasher to use when combining the components\n /// of this instance.\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine(count) // discriminator\n for element in self {\n hasher.combine(element)\n }\n }\n}\n\nextension ContiguousArray {\n /// Calls the given closure with a pointer to the underlying bytes of the\n /// array's mutable contiguous storage.\n ///\n /// The array's `Element` type must be a *trivial type*, which can be copied\n /// with just a bit-for-bit copy without any indirection or\n /// reference-counting operations. Generally, native Swift types that do not\n /// contain strong or weak references are trivial, as are imported C structs\n /// and enums.\n ///\n /// The following example copies bytes from the `byteValues` array into\n /// `numbers`, an array of `Int32`:\n ///\n /// var numbers: [Int32] = [0, 0]\n /// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00]\n ///\n /// numbers.withUnsafeMutableBytes { destBytes in\n /// byteValues.withUnsafeBytes { srcBytes in\n /// destBytes.copyBytes(from: srcBytes)\n /// }\n /// }\n /// // numbers == [1, 2]\n ///\n /// - Note: This example shows the behavior on a little-endian platform.\n ///\n /// The pointer passed as an argument to `body` is valid only for the\n /// lifetime of the closure. Do not escape it from the closure for later\n /// use.\n ///\n /// - Warning: Do not rely on anything about the array that is the target of\n /// this method during execution of the `body` closure; it might not\n /// appear to have its correct value. Instead, use only the\n /// `UnsafeMutableRawBufferPointer` argument to `body`.\n ///\n /// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer`\n /// parameter that points to the contiguous storage for the array.\n /// If no such storage exists, it is created. If `body` has a return value, that value is also\n /// used as the return value for the `withUnsafeMutableBytes(_:)` method.\n /// The argument is valid only for the duration of the closure's\n /// execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @inlinable\n public mutating func withUnsafeMutableBytes<R>(\n _ body: (UnsafeMutableRawBufferPointer) throws -> R\n ) rethrows -> R {\n return try unsafe self.withUnsafeMutableBufferPointer {\n return try unsafe body(UnsafeMutableRawBufferPointer($0))\n }\n }\n\n /// Calls the given closure with a pointer to the underlying bytes of the\n /// array's contiguous storage.\n ///\n /// The array's `Element` type must be a *trivial type*, which can be copied\n /// with just a bit-for-bit copy without any indirection or\n /// reference-counting operations. Generally, native Swift types that do not\n /// contain strong or weak references are trivial, as are imported C structs\n /// and enums.\n ///\n /// The following example copies the bytes of the `numbers` array into a\n /// buffer of `UInt8`:\n ///\n /// var numbers: [Int32] = [1, 2, 3]\n /// var byteBuffer: [UInt8] = []\n /// numbers.withUnsafeBytes {\n /// byteBuffer.append(contentsOf: $0)\n /// }\n /// // byteBuffer == [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]\n ///\n /// - Note: This example shows the behavior on a little-endian platform.\n ///\n /// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter\n /// that points to the contiguous storage for the array.\n /// If no such storage exists, it is created. If `body` has a return value, that value is also\n /// used as the return value for the `withUnsafeBytes(_:)` method. The\n /// argument is valid only for the duration of the closure's execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @inlinable\n public func withUnsafeBytes<R>(\n _ body: (UnsafeRawBufferPointer) throws -> R\n ) rethrows -> R {\n return try unsafe self.withUnsafeBufferPointer {\n try unsafe body(UnsafeRawBufferPointer($0))\n }\n }\n}\n\nextension ContiguousArray: @unchecked Sendable\n where Element: Sendable { }\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ContiguousArray.swift | cpp_apple_swift_stdlib_public_core_ContiguousArray.swift | Swift | 58,330 | 0.75 | 0.087802 | 0.548341 | python-kit | 276 | 2023-10-28T22:20:53.588955 | Apache-2.0 | false | 04d8eb5a3510a9aabdf6cf33944a9617 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED\n@_silgen_name("swift_COWChecksEnabled")\npublic func _COWChecksEnabled() -> Bool\n#endif\n\n/// Class used whose sole instance is used as storage for empty\n/// arrays. The instance is defined in the runtime and statically\n/// initialized. See stdlib/runtime/GlobalObjects.cpp for details.\n/// Because it's statically referenced, it requires non-lazy realization\n/// by the Objective-C runtime.\n///\n/// NOTE: older runtimes called this _EmptyArrayStorage. The two must\n/// coexist, so it was renamed. The old name must not be used in the new\n/// runtime.\n@_fixed_layout\n@usableFromInline\n@_objc_non_lazy_realization\ninternal final class __EmptyArrayStorage\n : __ContiguousArrayStorageBase {\n\n @inlinable\n @nonobjc\n internal init(_doNotCallMe: ()) {\n _internalInvariantFailure("creating instance of __EmptyArrayStorage")\n }\n \n#if _runtime(_ObjC)\n override internal func _withVerbatimBridgedUnsafeBuffer<R>(\n _ body: (UnsafeBufferPointer<AnyObject>) throws -> R\n ) rethrows -> R? {\n return unsafe try body(UnsafeBufferPointer(start: nil, count: 0))\n }\n\n override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer {\n return _BridgingBuffer(0)\n }\n#endif\n\n @inlinable\n override internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool {\n return false\n }\n\n /// A type that every element in the array is.\n @inlinable\n @_unavailableInEmbedded\n override internal var staticElementType: Any.Type {\n return Void.self\n }\n}\n\n#if $Embedded\n// In embedded Swift, the stdlib is a .swiftmodule only without any .o/.a files,\n// to allow consuming it by clients with different LLVM codegen setting (-mcpu\n// flags, etc.), which means we cannot declare the singleton in a C/C++ file.\n//\n// TODO: We should figure out how to make this a constant so that it's placed in\n// non-writable memory (can't be a let, Builtin.addressof below requires a var).\n@unsafe\npublic var _swiftEmptyArrayStorage: (Int, Int, Int, Int) =\n (/*isa*/0, /*refcount*/-1, /*count*/0, /*flags*/1)\n#endif\n\n/// The storage for static read-only arrays.\n///\n/// In contrast to `_ContiguousArrayStorage` this class is _not_ generic over\n/// the element type, because the metatype for static read-only arrays cannot\n/// be instantiated at runtime.\n///\n/// Static read-only arrays can only contain non-verbatim bridged element types.\n@_fixed_layout\n@usableFromInline\n@_objc_non_lazy_realization\ninternal final class __StaticArrayStorage\n : __ContiguousArrayStorageBase {\n\n @inlinable\n @nonobjc\n internal init(_doNotCallMe: ()) {\n _internalInvariantFailure("creating instance of __StaticArrayStorage")\n }\n\n#if _runtime(_ObjC)\n override internal func _withVerbatimBridgedUnsafeBuffer<R>(\n _ body: (UnsafeBufferPointer<AnyObject>) throws -> R\n ) rethrows -> R? {\n return nil\n }\n\n override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer {\n fatalError("__StaticArrayStorage._withVerbatimBridgedUnsafeBuffer must not be called")\n }\n#endif\n\n @inlinable\n override internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool {\n return false\n }\n\n @inlinable\n @_unavailableInEmbedded\n override internal var staticElementType: Any.Type {\n fatalError("__StaticArrayStorage.staticElementType must not be called")\n }\n}\n\n/// The empty array prototype. We use the same object for all empty\n/// `[Native]Array<Element>`s.\n@inlinable\ninternal var _emptyArrayStorage: __EmptyArrayStorage {\n return unsafe Builtin.bridgeFromRawPointer(\n Builtin.addressof(&_swiftEmptyArrayStorage))\n}\n\n// The class that implements the storage for a ContiguousArray<Element>\n@_fixed_layout\n@usableFromInline\ninternal final class _ContiguousArrayStorage<\n Element\n>: __ContiguousArrayStorageBase {\n\n @inlinable\n deinit {\n unsafe _elementPointer.deinitialize(count: countAndCapacity.count)\n _fixLifetime(self)\n }\n\n#if _runtime(_ObjC)\n \n internal final override func withUnsafeBufferOfObjects<R>(\n _ body: (UnsafeBufferPointer<AnyObject>) throws -> R\n ) rethrows -> R {\n _internalInvariant(_isBridgedVerbatimToObjectiveC(Element.self))\n let count = countAndCapacity.count\n let elements = unsafe UnsafeRawPointer(_elementPointer)\n .assumingMemoryBound(to: AnyObject.self)\n defer { _fixLifetime(self) }\n return try unsafe body(UnsafeBufferPointer(start: elements, count: count))\n }\n \n @objc(countByEnumeratingWithState:objects:count:)\n @_effects(releasenone)\n internal final override func countByEnumerating(\n with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,\n objects: UnsafeMutablePointer<AnyObject>?, count: Int\n ) -> Int {\n var enumerationState = unsafe state.pointee\n \n if unsafe enumerationState.state != 0 {\n return 0\n }\n \n return unsafe withUnsafeBufferOfObjects {\n objects in\n unsafe enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr\n unsafe enumerationState.itemsPtr =\n unsafe AutoreleasingUnsafeMutablePointer(objects.baseAddress)\n unsafe enumerationState.state = 1\n unsafe state.pointee = enumerationState\n return objects.count\n }\n }\n \n @inline(__always)\n @_effects(readonly)\n @nonobjc private func _objectAt(_ index: Int) -> Unmanaged<AnyObject> {\n return unsafe withUnsafeBufferOfObjects {\n objects in\n _precondition(\n _isValidArraySubscript(index, count: objects.count),\n "Array index out of range")\n return unsafe Unmanaged.passUnretained(objects[index])\n }\n }\n \n @objc(objectAtIndexedSubscript:)\n @_effects(readonly)\n final override internal func objectAtSubscript(_ index: Int) -> Unmanaged<AnyObject> {\n return unsafe _objectAt(index)\n }\n \n @objc(objectAtIndex:)\n @_effects(readonly)\n final override internal func objectAt(_ index: Int) -> Unmanaged<AnyObject> {\n return unsafe _objectAt(index)\n }\n \n @objc internal override final var count: Int {\n @_effects(readonly) get {\n return unsafe withUnsafeBufferOfObjects { $0.count }\n }\n }\n\n @_effects(releasenone)\n @objc internal override final func getObjects(\n _ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange\n ) {\n return unsafe withUnsafeBufferOfObjects {\n objects in\n _precondition(\n _isValidArrayIndex(range.location, count: objects.count),\n "Array index out of range")\n\n _precondition(\n _isValidArrayIndex(\n range.location + range.length, count: objects.count),\n "Array index out of range")\n\n if objects.isEmpty { return }\n\n // These objects are "returned" at +0, so treat them as pointer values to\n // avoid retains. Copy bytes via a raw pointer to circumvent reference\n // counting while correctly aliasing with all other pointer types.\n unsafe UnsafeMutableRawPointer(aBuffer).copyMemory(\n from: objects.baseAddress! + range.location,\n byteCount: range.length * MemoryLayout<AnyObject>.stride)\n }\n }\n \n /// If the `Element` is bridged verbatim, invoke `body` on an\n /// `UnsafeBufferPointer` to the elements and return the result.\n /// Otherwise, return `nil`.\n internal final override func _withVerbatimBridgedUnsafeBuffer<R>(\n _ body: (UnsafeBufferPointer<AnyObject>) throws -> R\n ) rethrows -> R? {\n var result: R?\n try unsafe self._withVerbatimBridgedUnsafeBufferImpl {\n result = unsafe try body($0)\n }\n return result\n }\n\n /// If `Element` is bridged verbatim, invoke `body` on an\n /// `UnsafeBufferPointer` to the elements.\n internal final func _withVerbatimBridgedUnsafeBufferImpl(\n _ body: (UnsafeBufferPointer<AnyObject>) throws -> Void\n ) rethrows {\n if _isBridgedVerbatimToObjectiveC(Element.self) {\n let count = countAndCapacity.count\n let elements = unsafe UnsafeRawPointer(_elementPointer)\n .assumingMemoryBound(to: AnyObject.self)\n defer { _fixLifetime(self) }\n try unsafe body(UnsafeBufferPointer(start: elements, count: count))\n }\n }\n\n /// Bridge array elements and return a new buffer that owns them.\n ///\n /// - Precondition: `Element` is bridged non-verbatim.\n override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer {\n _internalInvariant(\n !_isBridgedVerbatimToObjectiveC(Element.self),\n "Verbatim bridging should be handled separately")\n let count = countAndCapacity.count\n let result = _BridgingBuffer(count)\n let resultPtr = unsafe result.baseAddress\n let p = unsafe _elementPointer\n for i in 0..<count {\n unsafe (resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i]))\n }\n _fixLifetime(self)\n return result\n }\n#endif\n\n /// Returns `true` if the `proposedElementType` is `Element` or a subclass of\n /// `Element`. We can't store anything else without violating type\n /// safety; for example, the destructor has static knowledge that\n /// all of the elements can be destroyed as `Element`.\n @inlinable\n internal override func canStoreElements(\n ofDynamicType proposedElementType: Any.Type\n ) -> Bool {\n#if _runtime(_ObjC)\n return proposedElementType is Element.Type\n#else\n // FIXME: Dynamic casts don't currently work without objc. \n // rdar://problem/18801510\n return false\n#endif\n }\n\n /// A type that every element in the array is.\n @inlinable\n @_unavailableInEmbedded\n internal override var staticElementType: Any.Type {\n return Element.self\n }\n\n @inlinable\n internal final var _elementPointer: UnsafeMutablePointer<Element> {\n return unsafe UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self))\n }\n}\n\n@_alwaysEmitIntoClient\n@inline(__always)\ninternal func _uncheckedUnsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {\n return Builtin.reinterpretCast(x)\n}\n\n@_alwaysEmitIntoClient\n@inline(never)\n@_effects(readonly)\n@_semantics("array.getContiguousArrayStorageType")\nfunc getContiguousArrayStorageType<Element>(\n for: Element.Type\n) -> _ContiguousArrayStorage<Element>.Type {\n // We can only reset the type metadata to the correct metadata when bridging\n // on the current OS going forward.\n if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) { // SwiftStdlib 5.7\n if Element.self is AnyObject.Type {\n return _uncheckedUnsafeBitCast(\n _ContiguousArrayStorage<AnyObject>.self,\n to: _ContiguousArrayStorage<Element>.Type.self)\n }\n }\n return _ContiguousArrayStorage<Element>.self\n}\n\n@usableFromInline\n@frozen\ninternal struct _ContiguousArrayBuffer<Element>: _ArrayBufferProtocol {\n @usableFromInline\n internal var _storage: __ContiguousArrayStorageBase\n\n /// Make a buffer with uninitialized elements. After using this\n /// method, you must either initialize the `count` elements at the\n /// result's `.firstElementAddress` or set the result's `.count`\n /// to zero.\n @inlinable\n internal init(\n _uninitializedCount uninitializedCount: Int,\n minimumCapacity: Int\n ) {\n let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity)\n if realMinimumCapacity == 0 {\n self = _ContiguousArrayBuffer<Element>()\n }\n else {\n #if !$Embedded\n _storage = Builtin.allocWithTailElems_1(\n getContiguousArrayStorageType(for: Element.self), realMinimumCapacity._builtinWordValue, Element.self)\n #else\n _storage = Builtin.allocWithTailElems_1(\n _ContiguousArrayStorage<Element>.self, realMinimumCapacity._builtinWordValue, Element.self)\n #endif\n\n let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage))\n let allocSize: Int?\n #if !$Embedded\n allocSize = unsafe _mallocSize(ofAllocation: storageAddr)\n #else\n allocSize = nil\n #endif\n if let allocSize {\n let endAddr = unsafe storageAddr + allocSize\n let realCapacity = unsafe endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress\n _initStorageHeader(\n count: uninitializedCount, capacity: realCapacity)\n } else {\n _initStorageHeader(\n count: uninitializedCount, capacity: realMinimumCapacity)\n }\n }\n }\n\n /// Initialize using the given uninitialized `storage`.\n /// The storage is assumed to be uninitialized. The returned buffer has the\n /// body part of the storage initialized, but not the elements.\n ///\n /// - Warning: The result has uninitialized elements.\n /// \n /// - Warning: storage may have been stack-allocated, so it's\n /// crucial not to call, e.g., `malloc_size` on it.\n @inlinable\n internal init(count: Int, storage: _ContiguousArrayStorage<Element>) {\n _storage = storage\n\n _initStorageHeader(count: count, capacity: count)\n }\n\n @inlinable\n internal init(_ storage: __ContiguousArrayStorageBase) {\n _storage = storage\n }\n\n /// Initialize the body part of our storage.\n ///\n /// - Warning: does not initialize elements\n @inlinable\n internal func _initStorageHeader(count: Int, capacity: Int) {\n#if _runtime(_ObjC)\n let verbatim = _isBridgedVerbatimToObjectiveC(Element.self)\n#else\n let verbatim = false\n#endif\n\n // We can initialize by assignment because _ArrayBody is a trivial type,\n // i.e. contains no references.\n _storage.countAndCapacity = _ArrayBody(\n count: count,\n capacity: capacity,\n elementTypeIsBridgedVerbatim: verbatim)\n }\n\n /// True, if the array is native and does not need a deferred type check.\n @inlinable\n internal var arrayPropertyIsNativeTypeChecked: Bool {\n return true\n }\n\n /// A pointer to the first element.\n @inlinable\n internal var firstElementAddress: UnsafeMutablePointer<Element> {\n return unsafe UnsafeMutablePointer(Builtin.projectTailElems(_storage,\n Element.self))\n }\n\n /// A mutable pointer to the first element.\n ///\n /// - Precondition: The buffer must be mutable.\n @_alwaysEmitIntoClient\n internal var mutableFirstElementAddress: UnsafeMutablePointer<Element> {\n return unsafe UnsafeMutablePointer(Builtin.projectTailElems(mutableOrEmptyStorage,\n Element.self))\n }\n\n @inlinable\n internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {\n return unsafe firstElementAddress\n }\n\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n @usableFromInline\n @_silgen_name("$ss22_ContiguousArrayBufferV010withUnsafeC7Pointeryqd__qd__SRyxGKXEKlF")\n internal func __abi_withUnsafeBufferPointer<R>(\n _ body: (UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R {\n defer { _fixLifetime(self) }\n return try unsafe body(UnsafeBufferPointer(start: firstElementAddress,\n count: count))\n }\n\n /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the\n /// underlying contiguous storage.\n @_alwaysEmitIntoClient\n internal func withUnsafeBufferPointer<R, E>(\n _ body: (UnsafeBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n defer { _fixLifetime(self) }\n return try unsafe body(UnsafeBufferPointer(start: firstElementAddress,\n count: count))\n }\n\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n @usableFromInline\n @_silgen_name("$ss22_ContiguousArrayBufferV017withUnsafeMutableC7Pointeryqd__qd__SryxGKXEKlF")\n internal mutating func __abi_withUnsafeMutableBufferPointer<R>(\n _ body: (UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R {\n defer { _fixLifetime(self) }\n return try unsafe body(\n UnsafeMutableBufferPointer(start: firstElementAddress, count: count))\n }\n\n /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`\n /// over the underlying contiguous storage.\n @_alwaysEmitIntoClient\n internal mutating func withUnsafeMutableBufferPointer<R, E>(\n _ body: (UnsafeMutableBufferPointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n defer { _fixLifetime(self) }\n return try unsafe body(\n UnsafeMutableBufferPointer(start: firstElementAddress, count: count))\n }\n\n //===--- _ArrayBufferProtocol conformance -----------------------------------===//\n /// Create an empty buffer.\n @inlinable\n internal init() {\n _storage = _emptyArrayStorage\n }\n\n @inlinable\n internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) {\n _internalInvariant(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")\n self = buffer\n }\n\n @inlinable\n internal mutating func requestUniqueMutableBackingBuffer(\n minimumCapacity: Int\n ) -> _ContiguousArrayBuffer<Element>? {\n if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) {\n return self\n }\n return nil\n }\n\n @inlinable\n internal mutating func isMutableAndUniquelyReferenced() -> Bool {\n return isUniquelyReferenced()\n }\n\n /// If this buffer is backed by a `_ContiguousArrayBuffer`\n /// containing the same number of elements as `self`, return it.\n /// Otherwise, return `nil`.\n @inlinable\n internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? {\n return self\n }\n\n @inlinable\n @inline(__always)\n internal func getElement(_ i: Int) -> Element {\n _internalInvariant(i >= 0 && i < count, "Array index out of range")\n let addr = unsafe UnsafePointer<Element>(\n Builtin.projectTailElems(immutableStorage, Element.self))\n return unsafe addr[i]\n }\n\n /// The storage of an immutable buffer.\n ///\n /// - Precondition: The buffer must be immutable.\n @_alwaysEmitIntoClient\n @inline(__always)\n internal var immutableStorage : __ContiguousArrayStorageBase {\n#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED\n _internalInvariant(isImmutable, "Array storage is not immutable")\n#endif\n return Builtin.COWBufferForReading(_storage)\n }\n\n /// The storage of a mutable buffer.\n ///\n /// - Precondition: The buffer must be mutable.\n @_alwaysEmitIntoClient\n @inline(__always)\n internal var mutableStorage : __ContiguousArrayStorageBase {\n#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED\n _internalInvariant(isMutable, "Array storage is immutable")\n#endif\n return _storage\n }\n\n /// The storage of a mutable or empty buffer.\n ///\n /// - Precondition: The buffer must be mutable or the empty array singleton.\n @_alwaysEmitIntoClient\n @inline(__always)\n internal var mutableOrEmptyStorage : __ContiguousArrayStorageBase {\n#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED\n _internalInvariant(isMutable || _storage.countAndCapacity.capacity == 0,\n "Array storage is immutable and not empty")\n#endif\n return _storage\n }\n\n#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED\n @_alwaysEmitIntoClient\n internal var isImmutable: Bool {\n get {\n if (_COWChecksEnabled()) {\n return capacity == 0 || _swift_isImmutableCOWBuffer(_storage)\n }\n return true\n }\n nonmutating set {\n if (_COWChecksEnabled()) {\n // Make sure to not modify the empty array singleton (which has a\n // capacity of 0).\n if capacity > 0 {\n let wasImmutable = _swift_setImmutableCOWBuffer(_storage, newValue)\n if newValue {\n _internalInvariant(!wasImmutable,\n "re-setting immutable array buffer to immutable")\n } else {\n _internalInvariant(wasImmutable,\n "re-setting mutable array buffer to mutable")\n }\n }\n }\n }\n }\n \n @_alwaysEmitIntoClient\n internal var isMutable: Bool {\n if (_COWChecksEnabled()) {\n return !_swift_isImmutableCOWBuffer(_storage)\n }\n return true\n }\n#endif\n\n /// Get or set the value of the ith element.\n @inlinable\n internal subscript(i: Int) -> Element {\n @inline(__always)\n get {\n return getElement(i)\n }\n @inline(__always)\n nonmutating set {\n _internalInvariant(i >= 0 && i < count, "Array index out of range")\n\n // FIXME: Manually swap because it makes the ARC optimizer happy. See\n // <rdar://problem/16831852> check retain/release order\n // firstElementAddress[i] = newValue\n var nv = newValue\n let tmp = nv\n nv = unsafe firstElementAddress[i]\n unsafe firstElementAddress[i] = tmp\n }\n }\n\n /// The number of elements the buffer stores.\n ///\n /// This property is obsolete. It's only used for the ArrayBufferProtocol and\n /// to keep backward compatibility.\n /// Use `immutableCount` or `mutableCount` instead.\n @inlinable\n internal var count: Int {\n get {\n return _storage.countAndCapacity.count\n }\n nonmutating set {\n _internalInvariant(newValue >= 0)\n\n _internalInvariant(\n newValue <= mutableCapacity,\n "Can't grow an array buffer past its capacity")\n\n mutableStorage.countAndCapacity.count = newValue\n }\n }\n \n /// The number of elements of the buffer.\n ///\n /// - Precondition: The buffer must be immutable.\n @_alwaysEmitIntoClient\n @inline(__always)\n internal var immutableCount: Int {\n return immutableStorage.countAndCapacity.count\n }\n\n /// The number of elements of the buffer.\n ///\n /// - Precondition: The buffer must be mutable.\n @_alwaysEmitIntoClient\n internal var mutableCount: Int {\n @inline(__always)\n get {\n return mutableOrEmptyStorage.countAndCapacity.count\n }\n @inline(__always)\n nonmutating set {\n _internalInvariant(newValue >= 0)\n\n _internalInvariant(\n newValue <= mutableCapacity,\n "Can't grow an array buffer past its capacity")\n\n mutableStorage.countAndCapacity.count = newValue\n }\n }\n\n /// Traps unless the given `index` is valid for subscripting, i.e.\n /// `0 ≤ index < count`.\n ///\n /// - Precondition: The buffer must be immutable.\n @inlinable\n @inline(__always)\n internal func _checkValidSubscript(_ index: Int) {\n _precondition(\n (index >= 0) && (index < immutableCount),\n "Index out of range"\n )\n }\n\n /// Traps unless the given `index` is valid for subscripting, i.e.\n /// `0 ≤ index < count`.\n ///\n /// - Precondition: The buffer must be mutable.\n @_alwaysEmitIntoClient\n @inline(__always)\n internal func _checkValidSubscriptMutating(_ index: Int) {\n _precondition(\n (index >= 0) && (index < mutableCount),\n "Index out of range"\n )\n }\n\n /// The number of elements the buffer can store without reallocation.\n ///\n /// This property is obsolete. It's only used for the ArrayBufferProtocol and\n /// to keep backward compatibility.\n /// Use `immutableCapacity` or `mutableCapacity` instead.\n @inlinable\n internal var capacity: Int {\n return _storage.countAndCapacity.capacity\n }\n\n /// The number of elements the buffer can store without reallocation.\n ///\n /// - Precondition: The buffer must be immutable.\n @_alwaysEmitIntoClient\n @inline(__always)\n internal var immutableCapacity: Int {\n return immutableStorage.countAndCapacity.capacity\n }\n\n /// The number of elements the buffer can store without reallocation.\n ///\n /// - Precondition: The buffer must be mutable.\n @_alwaysEmitIntoClient\n @inline(__always)\n internal var mutableCapacity: Int {\n return mutableOrEmptyStorage.countAndCapacity.capacity\n }\n\n /// Copy the elements in `bounds` from this buffer into uninitialized\n /// memory starting at `target`. Return a pointer "past the end" of the\n /// just-initialized memory.\n @inlinable\n @discardableResult\n internal __consuming func _copyContents(\n subRange bounds: Range<Int>,\n initializing target: UnsafeMutablePointer<Element>\n ) -> UnsafeMutablePointer<Element> {\n _internalInvariant(bounds.lowerBound >= 0)\n _internalInvariant(bounds.upperBound >= bounds.lowerBound)\n _internalInvariant(bounds.upperBound <= count)\n\n let initializedCount = bounds.upperBound - bounds.lowerBound\n unsafe target.initialize(\n from: firstElementAddress + bounds.lowerBound, count: initializedCount)\n _fixLifetime(owner)\n return unsafe target + initializedCount\n }\n\n @inlinable\n internal __consuming func _copyContents(\n initializing buffer: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {\n guard buffer.count > 0 else { return (makeIterator(), 0) }\n let c = Swift.min(self.count, buffer.count)\n unsafe buffer.baseAddress!.initialize(\n from: firstElementAddress,\n count: c)\n _fixLifetime(owner)\n return (IndexingIterator(_elements: self, _position: c), c)\n }\n\n /// Returns a `_SliceBuffer` containing the given `bounds` of values\n /// from this buffer.\n @inlinable\n internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {\n get {\n #if $Embedded\n let storage = Builtin.castToNativeObject(_storage)\n #else\n let storage = _storage\n #endif\n return unsafe _SliceBuffer(\n owner: storage,\n subscriptBaseAddress: firstElementAddress,\n indices: bounds,\n hasNativeBuffer: true)\n }\n set {\n fatalError("not implemented")\n }\n }\n\n /// Returns `true` if this buffer's storage is uniquely-referenced;\n /// otherwise, returns `false`.\n ///\n /// This function should only be used for internal soundness checks.\n /// To guard a buffer mutation, use `beginCOWMutation`.\n @inlinable\n internal mutating func isUniquelyReferenced() -> Bool {\n return _isUnique(&_storage)\n }\n\n /// Returns `true` and puts the buffer in a mutable state if the buffer's\n /// storage is uniquely-referenced; otherwise, performs no action and returns\n /// `false`.\n ///\n /// - Precondition: The buffer must be immutable.\n ///\n /// - Warning: It's a requirement to call `beginCOWMutation` before the buffer\n /// is mutated.\n @_alwaysEmitIntoClient\n internal mutating func beginCOWMutation() -> Bool {\n if Bool(Builtin.beginCOWMutation(&_storage)) {\n#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED\n isImmutable = false\n#endif\n return true\n }\n return false;\n }\n\n /// Puts the buffer in an immutable state.\n ///\n /// - Precondition: The buffer must be mutable or the empty array singleton.\n ///\n /// - Warning: After a call to `endCOWMutation` the buffer must not be mutated\n /// until the next call of `beginCOWMutation`.\n @_alwaysEmitIntoClient\n @inline(__always)\n internal mutating func endCOWMutation() {\n#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED\n isImmutable = true\n#endif\n Builtin.endCOWMutation(&_storage)\n }\n\n /// Creates and returns a new uniquely referenced buffer which is a copy of\n /// this buffer.\n ///\n /// This buffer is consumed, i.e. it's released.\n @_alwaysEmitIntoClient\n @inline(never)\n @_semantics("optimize.sil.specialize.owned2guarantee.never")\n internal __consuming func _consumeAndCreateNew() -> _ContiguousArrayBuffer {\n return _consumeAndCreateNew(bufferIsUnique: false,\n minimumCapacity: count,\n growForAppend: false)\n }\n\n /// Creates and returns a new uniquely referenced buffer which is a copy of\n /// this buffer.\n ///\n /// If `bufferIsUnique` is true, the buffer is assumed to be uniquely\n /// referenced and the elements are moved - instead of copied - to the new\n /// buffer.\n /// The `minimumCapacity` is the lower bound for the new capacity.\n /// If `growForAppend` is true, the new capacity is calculated using\n /// `_growArrayCapacity`, but at least kept at `minimumCapacity`.\n ///\n /// This buffer is consumed, i.e. it's released.\n @_alwaysEmitIntoClient\n @inline(never)\n @_semantics("optimize.sil.specialize.owned2guarantee.never")\n internal __consuming func _consumeAndCreateNew(\n bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool\n ) -> _ContiguousArrayBuffer {\n let newCapacity = _growArrayCapacity(oldCapacity: capacity,\n minimumCapacity: minimumCapacity,\n growForAppend: growForAppend)\n let c = count\n _internalInvariant(newCapacity >= c)\n \n let newBuffer = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: c, minimumCapacity: newCapacity)\n\n if bufferIsUnique {\n // As an optimization, if the original buffer is unique, we can just move\n // the elements instead of copying.\n let dest = unsafe newBuffer.mutableFirstElementAddress\n unsafe dest.moveInitialize(from: firstElementAddress,\n count: c)\n mutableCount = 0\n } else {\n unsafe _copyContents(\n subRange: 0..<c,\n initializing: newBuffer.mutableFirstElementAddress)\n }\n return newBuffer\n }\n\n#if _runtime(_ObjC)\n \n /// Convert to an NSArray.\n ///\n /// - Precondition: `Element` is bridged to Objective-C.\n ///\n /// - Complexity: O(1).\n @usableFromInline\n internal __consuming func _asCocoaArray() -> AnyObject {\n // _asCocoaArray was @inlinable in Swift 5.0 and 5.1, which means that there\n // are existing apps out there that effectively have the old implementation\n // Be careful with future changes to this function. Here be dragons!\n // The old implementation was\n // if count == 0 {\n // return _emptyArrayStorage\n // }\n // if _isBridgedVerbatimToObjectiveC(Element.self) {\n // return _storage\n // }\n // return __SwiftDeferredNSArray(_nativeStorage: _storage)\n \n _connectOrphanedFoundationSubclassesIfNeeded()\n if count == 0 {\n return _emptyArrayStorage\n }\n if _isBridgedVerbatimToObjectiveC(Element.self) {\n if #available(SwiftStdlib 5.7, *) {\n // We optimize _ContiguousArrayStorage<Element> where Element is any\n // class type to use _ContiguousArrayStorage<AnyObject> when we bridge\n // to objective-c we need to set the correct Element type so that when\n // we bridge back we can use O(1) bridging i.e we can adopt the storage.\n _ = _swift_setClassMetadata(_ContiguousArrayStorage<Element>.self,\n onObject: _storage)\n }\n return _storage\n }\n if _storage is __StaticArrayStorage {\n return __SwiftDeferredStaticNSArray<Element>(_nativeStorage: _storage)\n }\n return __SwiftDeferredNSArray(_nativeStorage: _storage)\n }\n#endif\n\n #if $Embedded\n public typealias AnyObject = Builtin.NativeObject\n #endif\n\n /// An object that keeps the elements stored in this buffer alive.\n @inlinable\n internal var owner: AnyObject {\n #if !$Embedded\n return _storage\n #else\n return Builtin.castToNativeObject(_storage)\n #endif\n }\n\n /// An object that keeps the elements stored in this buffer alive.\n @inlinable\n internal var nativeOwner: AnyObject {\n return owner\n }\n\n /// A value that identifies the storage used by the buffer.\n ///\n /// Two buffers address the same elements when they have the same\n /// identity and count.\n @inlinable\n internal var identity: UnsafeRawPointer {\n return unsafe UnsafeRawPointer(firstElementAddress)\n }\n \n /// Returns `true` if we have storage for elements of the given\n /// `proposedElementType`. If not, we'll be treated as immutable.\n @inlinable\n func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool {\n return _storage.canStoreElements(ofDynamicType: proposedElementType)\n }\n\n /// Returns `true` if the buffer stores only elements of type `U`.\n ///\n /// - Precondition: `U` is a class or `@objc` existential.\n ///\n /// - Complexity: O(*n*)\n @inlinable\n @_unavailableInEmbedded\n internal func storesOnlyElementsOfType<U>(\n _: U.Type\n ) -> Bool {\n _internalInvariant(_isClassOrObjCExistential(U.self))\n\n if _fastPath(_storage.staticElementType is U.Type) {\n // Done in O(1)\n return true\n }\n\n // Check the elements\n for x in self {\n if !(x is U) {\n return false\n }\n }\n return true\n }\n}\n\n/// Append the elements of `rhs` to `lhs`.\n@inlinable\ninternal func += <Element, C: Collection>(\n lhs: inout _ContiguousArrayBuffer<Element>, rhs: __owned C\n) where C.Element == Element {\n\n let oldCount = lhs.count\n let newCount = oldCount + rhs.count\n\n let buf: UnsafeMutableBufferPointer<Element>\n \n if _fastPath(newCount <= lhs.capacity) {\n unsafe buf = unsafe UnsafeMutableBufferPointer(\n start: lhs.firstElementAddress + oldCount,\n count: rhs.count)\n lhs.mutableCount = newCount\n }\n else {\n var newLHS = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: newCount,\n minimumCapacity: _growArrayCapacity(lhs.capacity))\n\n unsafe newLHS.firstElementAddress.moveInitialize(\n from: lhs.firstElementAddress, count: oldCount)\n lhs.mutableCount = 0\n (lhs, newLHS) = (newLHS, lhs)\n unsafe buf = unsafe UnsafeMutableBufferPointer(\n start: lhs.firstElementAddress + oldCount,\n count: rhs.count)\n }\n\n var (remainders,writtenUpTo) = unsafe buf.initialize(from: rhs)\n\n // ensure that exactly rhs.count elements were written\n _precondition(remainders.next() == nil, "rhs underreported its count")\n _precondition(writtenUpTo == buf.endIndex, "rhs overreported its count") \n}\n\nextension _ContiguousArrayBuffer: RandomAccessCollection {\n /// The position of the first element in a non-empty collection.\n ///\n /// In an empty collection, `startIndex == endIndex`.\n @inlinable\n internal var startIndex: Int {\n return 0\n }\n /// The collection's "past the end" position.\n ///\n /// `endIndex` is not a valid argument to `subscript`, and is always\n /// reachable from `startIndex` by zero or more applications of\n /// `index(after:)`.\n @inlinable\n internal var endIndex: Int {\n return count\n }\n\n @usableFromInline\n internal typealias Indices = Range<Int>\n}\n\nextension Sequence {\n @inlinable\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n return _copySequenceToContiguousArray(self)\n }\n}\n\n@inlinable\ninternal func _copySequenceToContiguousArray<\n S: Sequence\n>(_ source: S) -> ContiguousArray<S.Element> {\n let initialCapacity = source.underestimatedCount\n var builder =\n unsafe _UnsafePartiallyInitializedContiguousArrayBuffer<S.Element>(\n initialCapacity: initialCapacity)\n\n var iterator = source.makeIterator()\n\n // FIXME(performance): use _copyContents(initializing:).\n\n // Add elements up to the initial capacity without checking for regrowth.\n for _ in 0..<initialCapacity {\n unsafe builder.addWithExistingCapacity(iterator.next()!)\n }\n\n // Add remaining elements, if any.\n while let element = iterator.next() {\n unsafe builder.add(element)\n }\n\n return unsafe builder.finish()\n}\n\nextension Collection {\n @inlinable\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n return _copyCollectionToContiguousArray(self)\n }\n}\n\nextension _ContiguousArrayBuffer {\n @inlinable\n internal __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n return ContiguousArray(_buffer: self)\n }\n}\n\n/// This is a fast implementation of _copyToContiguousArray() for collections.\n///\n/// It avoids the extra retain, release overhead from storing the\n/// ContiguousArrayBuffer into\n/// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support\n/// ARC loops, the extra retain, release overhead cannot be eliminated which\n/// makes assigning ranges very slow. Once this has been implemented, this code\n/// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer.\n@inlinable\ninternal func _copyCollectionToContiguousArray<\n C: Collection\n>(_ source: C) -> ContiguousArray<C.Element>\n{\n let count = source.count\n if count == 0 {\n return ContiguousArray()\n }\n\n var result = _ContiguousArrayBuffer<C.Element>(\n _uninitializedCount: count,\n minimumCapacity: 0)\n\n let p = unsafe UnsafeMutableBufferPointer(\n start: result.firstElementAddress,\n count: count)\n var (itr, end) = unsafe source._copyContents(initializing: p)\n\n _debugPrecondition(itr.next() == nil,\n "invalid Collection: more than 'count' elements in collection")\n // We also have to check the evil shrink case in release builds, because\n // it can result in uninitialized array elements and therefore undefined\n // behavior.\n _precondition(end == p.endIndex,\n "invalid Collection: less than 'count' elements in collection")\n\n result.endCOWMutation()\n return ContiguousArray(_buffer: result)\n}\n\n/// A "builder" interface for initializing array buffers.\n///\n/// This presents a "builder" interface for initializing an array buffer\n/// element-by-element. The type is unsafe because it cannot be deinitialized\n/// until the buffer has been finalized by a call to `finish`.\n@usableFromInline\n@frozen\n@unsafe\ninternal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> {\n @usableFromInline\n internal var result: _ContiguousArrayBuffer<Element>\n @usableFromInline\n internal var p: UnsafeMutablePointer<Element>\n @usableFromInline\n internal var remainingCapacity: Int\n\n /// Initialize the buffer with an initial size of `initialCapacity`\n /// elements.\n @inlinable\n @inline(__always) // For performance reasons.\n internal init(initialCapacity: Int) {\n if initialCapacity == 0 {\n unsafe result = _ContiguousArrayBuffer()\n } else {\n unsafe result = _ContiguousArrayBuffer(\n _uninitializedCount: initialCapacity,\n minimumCapacity: 0)\n }\n\n unsafe p = unsafe result.firstElementAddress\n unsafe remainingCapacity = unsafe result.capacity\n }\n\n /// Add an element to the buffer, reallocating if necessary.\n @inlinable\n @inline(__always) // For performance reasons.\n internal mutating func add(_ element: Element) {\n if unsafe remainingCapacity == 0 {\n // Reallocate.\n let newCapacity = unsafe max(_growArrayCapacity(result.capacity), 1)\n var newResult = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: newCapacity, minimumCapacity: 0)\n unsafe p = unsafe newResult.firstElementAddress + result.capacity\n unsafe remainingCapacity = unsafe newResult.capacity - result.capacity\n if unsafe !result.isEmpty {\n // This check prevents a data race writing to _swiftEmptyArrayStorage\n // Since count is always 0 there, this code does nothing anyway\n unsafe newResult.firstElementAddress.moveInitialize(\n from: result.firstElementAddress, count: result.capacity)\n unsafe result.mutableCount = 0\n }\n unsafe (result, newResult) = unsafe (newResult, result)\n }\n unsafe addWithExistingCapacity(element)\n }\n\n /// Add an element to the buffer, which must have remaining capacity.\n @inlinable\n @inline(__always) // For performance reasons.\n internal mutating func addWithExistingCapacity(_ element: Element) {\n unsafe _internalInvariant(remainingCapacity > 0,\n "_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity")\n unsafe remainingCapacity -= 1\n\n unsafe p.initialize(to: element)\n unsafe p += 1\n }\n\n /// Finish initializing the buffer, adjusting its count to the final\n /// number of elements.\n ///\n /// Returns the fully-initialized buffer. `self` is reset to contain an\n /// empty buffer and cannot be used afterward.\n @inlinable\n @inline(__always) // For performance reasons.\n internal mutating func finish() -> ContiguousArray<Element> {\n // Adjust the initialized count of the buffer.\n if unsafe (result.capacity != 0) {\n unsafe result.mutableCount = unsafe result.capacity - remainingCapacity\n } else {\n unsafe _internalInvariant(remainingCapacity == 0)\n unsafe _internalInvariant(result.count == 0) \n }\n\n return unsafe finishWithOriginalCount()\n }\n\n /// Finish initializing the buffer, assuming that the number of elements\n /// exactly matches the `initialCount` for which the initialization was\n /// started.\n ///\n /// Returns the fully-initialized buffer. `self` is reset to contain an\n /// empty buffer and cannot be used afterward.\n @inlinable\n @inline(__always) // For performance reasons.\n internal mutating func finishWithOriginalCount() -> ContiguousArray<Element> {\n unsafe _internalInvariant(remainingCapacity == result.capacity - result.count,\n "_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count")\n var finalResult = _ContiguousArrayBuffer<Element>()\n unsafe (finalResult, result) = unsafe (result, finalResult)\n unsafe remainingCapacity = 0\n finalResult.endCOWMutation()\n return ContiguousArray(_buffer: finalResult)\n }\n}\n\n@available(*, unavailable)\nextension _UnsafePartiallyInitializedContiguousArrayBuffer: Sendable {}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ContiguousArrayBuffer.swift | cpp_apple_swift_stdlib_public_core_ContiguousArrayBuffer.swift | Swift | 41,033 | 0.95 | 0.085669 | 0.273788 | react-lib | 246 | 2024-06-05T19:33:34.635437 | BSD-3-Clause | false | f19ae7897fd4e673b2703f1275de1848 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// NOTE: The below is necessary for fast String initialization from untyped\n// memory. When we add Collection.withContiguousRawStorageIfAvailable(), we can\n// deprecate this functionality.\n\n@usableFromInline\ninternal protocol _HasContiguousBytes {\n @safe\n func withUnsafeBytes<R>(\n _ body: (UnsafeRawBufferPointer) throws -> R\n ) rethrows -> R\n\n var _providesContiguousBytesNoCopy: Bool { get }\n}\nextension _HasContiguousBytes {\n @inlinable\n var _providesContiguousBytesNoCopy: Bool {\n @inline(__always) get { return true }\n }\n}\nextension Array: _HasContiguousBytes {\n @inlinable\n var _providesContiguousBytesNoCopy: Bool {\n @inline(__always) get {\n#if _runtime(_ObjC)\n return _buffer._isNative\n#else\n return true\n#endif\n }\n }\n}\nextension ContiguousArray: _HasContiguousBytes {}\nextension UnsafeBufferPointer: @unsafe _HasContiguousBytes {\n @inlinable @inline(__always)\n @safe\n func withUnsafeBytes<R>(\n _ body: (UnsafeRawBufferPointer) throws -> R\n ) rethrows -> R {\n let ptr = unsafe UnsafeRawPointer(self.baseAddress)\n let len = self.count &* MemoryLayout<Element>.stride\n return try unsafe body(UnsafeRawBufferPointer(start: ptr, count: len))\n }\n}\nextension UnsafeMutableBufferPointer: @unsafe _HasContiguousBytes {\n @inlinable @inline(__always)\n @safe\n func withUnsafeBytes<R>(\n _ body: (UnsafeRawBufferPointer) throws -> R\n ) rethrows -> R {\n let ptr = UnsafeRawPointer(self.baseAddress)\n let len = self.count &* MemoryLayout<Element>.stride\n return try unsafe body(UnsafeRawBufferPointer(start: ptr, count: len))\n }\n}\nextension UnsafeRawBufferPointer: @unsafe _HasContiguousBytes {\n @inlinable @inline(__always)\n @safe\n func withUnsafeBytes<R>(\n _ body: (UnsafeRawBufferPointer) throws -> R\n ) rethrows -> R {\n return try unsafe body(self)\n }\n}\nextension UnsafeMutableRawBufferPointer: @unsafe _HasContiguousBytes {\n @inlinable @inline(__always)\n @safe\n func withUnsafeBytes<R>(\n _ body: (UnsafeRawBufferPointer) throws -> R\n ) rethrows -> R {\n return try unsafe body(UnsafeRawBufferPointer(self))\n }\n}\nextension String: _HasContiguousBytes {\n @inlinable\n internal var _providesContiguousBytesNoCopy: Bool {\n @inline(__always) get { return self._guts.isFastUTF8 }\n }\n\n @inlinable @inline(__always)\n @safe\n internal func withUnsafeBytes<R>(\n _ body: (UnsafeRawBufferPointer) throws -> R\n ) rethrows -> R {\n var copy = self\n return try copy.withUTF8 { return try unsafe body(UnsafeRawBufferPointer($0)) }\n }\n}\nextension Substring: _HasContiguousBytes {\n @inlinable\n internal var _providesContiguousBytesNoCopy: Bool {\n @inline(__always) get { return self._wholeGuts.isFastUTF8 }\n }\n\n @inlinable @inline(__always)\n @safe\n internal func withUnsafeBytes<R>(\n _ body: (UnsafeRawBufferPointer) throws -> R\n ) rethrows -> R {\n var copy = self\n return try copy.withUTF8 { return try unsafe body(UnsafeRawBufferPointer($0)) }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ContiguouslyStored.swift | cpp_apple_swift_stdlib_public_core_ContiguouslyStored.swift | Swift | 3,476 | 0.95 | 0.105263 | 0.155963 | python-kit | 312 | 2024-07-06T22:39:54.496955 | BSD-3-Clause | false | a5f1c848dd772c33ac11f81de40e83f5 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n// String interop with C\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\nextension String {\n\n /// Creates a new string by copying the null-terminated UTF-8 data referenced\n /// by the given pointer.\n ///\n /// If `cString` contains ill-formed UTF-8 code unit sequences, this\n /// initializer replaces them with the Unicode replacement character\n /// (`"\u{FFFD}"`).\n ///\n /// The following example calls this initializer with pointers to the\n /// contents of two different `CChar` arrays---the first with well-formed\n /// UTF-8 code unit sequences and the second with an ill-formed sequence at\n /// the end.\n ///\n /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]\n /// validUTF8.withUnsafeBufferPointer { ptr in\n /// let s = String(cString: ptr.baseAddress!)\n /// print(s)\n /// }\n /// // Prints "Café"\n ///\n /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]\n /// invalidUTF8.withUnsafeBufferPointer { ptr in\n /// let s = String(cString: ptr.baseAddress!)\n /// print(s)\n /// }\n /// // Prints "Caf�"\n ///\n /// - Parameter nullTerminatedUTF8:\n /// A pointer to a null-terminated sequence of UTF-8 code units.\n public init(cString nullTerminatedUTF8: UnsafePointer<CChar>) {\n let len = unsafe UTF8._nullCodeUnitOffset(in: nullTerminatedUTF8)\n let buffer = unsafe UnsafeBufferPointer(start: nullTerminatedUTF8, count: len)\n self = unsafe buffer.withMemoryRebound(to: UInt8.self) {\n unsafe String._fromUTF8Repairing($0).0\n }\n }\n\n /// Creates a new string by copying the null-terminated UTF-8 data referenced\n /// by the given array.\n ///\n /// If `cString` contains ill-formed UTF-8 code unit sequences, this\n /// initializer replaces them with the Unicode replacement character\n /// (`"\u{FFFD}"`).\n ///\n /// - Note: This initializer is deprecated. Use the initializer\n /// `String.init(decoding: array, as: UTF8.self)` instead,\n /// remembering that "\0" is a valid character in Swift.\n ///\n /// - Parameter nullTerminatedUTF8:\n /// An array containing a null-terminated sequence of UTF-8 code units.\n @inlinable\n @_alwaysEmitIntoClient\n @available(swift, deprecated: 6, message:\n "Use String(decoding: array, as: UTF8.self) instead, after truncating the null termination."\n )\n public init(cString nullTerminatedUTF8: [CChar]) {\n self = unsafe nullTerminatedUTF8.withUnsafeBufferPointer {\n unsafe $0.withMemoryRebound(to: UInt8.self, String.init(_checkingCString:))\n }\n }\n\n @_alwaysEmitIntoClient\n internal init(_checkingCString bytes: UnsafeBufferPointer<UInt8>) {\n guard let length = unsafe bytes.firstIndex(of: 0) else {\n _preconditionFailure(\n "input of String.init(cString:) must be null-terminated"\n )\n }\n self = unsafe String._fromUTF8Repairing(\n UnsafeBufferPointer(\n start: bytes.baseAddress._unsafelyUnwrappedUnchecked,\n count: length\n )\n ).0\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "Use String(_ scalar: Unicode.Scalar)")\n public init(cString nullTerminatedUTF8: inout CChar) {\n guard nullTerminatedUTF8 == 0 else {\n _preconditionFailure(\n "input of String.init(cString:) must be null-terminated"\n )\n }\n self = ""\n }\n\n /// Creates a new string by copying the null-terminated UTF-8 data referenced\n /// by the given pointer.\n ///\n /// This is identical to `init(cString: UnsafePointer<CChar>)` but operates on\n /// an unsigned sequence of bytes.\n ///\n /// - Parameter nullTerminatedUTF8:\n /// A pointer to a null-terminated sequence of UTF-8 code units.\n public init(cString nullTerminatedUTF8: UnsafePointer<UInt8>) {\n let len = unsafe UTF8._nullCodeUnitOffset(in: nullTerminatedUTF8)\n self = unsafe String._fromUTF8Repairing(\n UnsafeBufferPointer(start: nullTerminatedUTF8, count: len)).0\n }\n\n /// Creates a new string by copying the null-terminated UTF-8 data referenced\n /// by the given array.\n ///\n /// This is identical to `init(cString: [CChar])` but operates on\n /// an unsigned sequence of bytes.\n ///\n /// - Note: This initializer is deprecated. Use the initializer\n /// `String.init(decoding: array, as: UTF8.self)` instead,\n /// remembering that "\0" is a valid character in Swift.\n ///\n /// - Parameter nullTerminatedUTF8:\n /// An array containing a null-terminated UTF-8 code unit sequence.\n @inlinable\n @_alwaysEmitIntoClient\n @available(swift, deprecated: 6, message:\n "Use String(decoding: array, as: UTF8.self) instead, after truncating the null termination."\n )\n public init(cString nullTerminatedUTF8: [UInt8]) {\n self = unsafe nullTerminatedUTF8.withUnsafeBufferPointer {\n unsafe String(_checkingCString: $0)\n }\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "Use a copy of the String argument")\n public init(cString nullTerminatedUTF8: String) {\n self = unsafe nullTerminatedUTF8.withCString(String.init(cString:))\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "Use String(_ scalar: Unicode.Scalar)")\n public init(cString nullTerminatedUTF8: inout UInt8) {\n guard nullTerminatedUTF8 == 0 else {\n _preconditionFailure(\n "input of String.init(cString:) must be null-terminated"\n )\n }\n self = ""\n }\n\n /// Creates a new string by copying and validating the null-terminated UTF-8\n /// data referenced by the given pointer.\n ///\n /// This initializer does not try to repair ill-formed UTF-8 code unit\n /// sequences. If any are found, the result of the initializer is `nil`.\n ///\n /// The following example calls this initializer with pointers to the\n /// contents of two different `CChar` arrays---the first with well-formed\n /// UTF-8 code unit sequences and the second with an ill-formed sequence at\n /// the end.\n ///\n /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]\n /// validUTF8.withUnsafeBufferPointer { ptr in\n /// let s = String(validatingCString: ptr.baseAddress!)\n /// print(s)\n /// }\n /// // Prints "Optional("Café")"\n ///\n /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]\n /// invalidUTF8.withUnsafeBufferPointer { ptr in\n /// let s = String(validatingCString: ptr.baseAddress!)\n /// print(s)\n /// }\n /// // Prints "nil"\n ///\n /// - Parameter nullTerminatedUTF8:\n /// A pointer to a null-terminated sequence of UTF-8 code units.\n @_silgen_name("$sSS14validatingUTF8SSSgSPys4Int8VG_tcfC")\n public init?(validatingCString nullTerminatedUTF8: UnsafePointer<CChar>) {\n let len = unsafe UTF8._nullCodeUnitOffset(in: nullTerminatedUTF8)\n let validated = unsafe nullTerminatedUTF8.withMemoryRebound(\n to: UInt8.self,\n capacity: len,\n { unsafe String._tryFromUTF8(UnsafeBufferPointer(start: $0, count: len)) }\n )\n guard let validated else { return nil }\n self = validated\n }\n\n /// Creates a new string by copying and validating the null-terminated UTF-8\n /// data referenced by the given pointer.\n ///\n /// This initializer does not try to repair ill-formed UTF-8 code unit\n /// sequences. If any are found, the result of the initializer is `nil`.\n ///\n /// The following example calls this initializer with pointers to the\n /// contents of two different `CChar` arrays---the first with well-formed\n /// UTF-8 code unit sequences and the second with an ill-formed sequence at\n /// the end.\n ///\n /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]\n /// validUTF8.withUnsafeBufferPointer { ptr in\n /// let s = String(validatingUTF8: ptr.baseAddress!)\n /// print(s)\n /// }\n /// // Prints "Optional("Café")"\n ///\n /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]\n /// invalidUTF8.withUnsafeBufferPointer { ptr in\n /// let s = String(validatingUTF8: ptr.baseAddress!)\n /// print(s)\n /// }\n /// // Prints "nil"\n ///\n /// - Note: This initializer has been renamed. Use\n /// `String.init?(validatingCString:)` instead.\n ///\n /// - Parameter cString:\n /// A pointer to a null-terminated sequence of UTF-8 code units.\n @inlinable\n @_alwaysEmitIntoClient\n @available(swift, deprecated: 6, renamed: "String.init(validatingCString:)")\n @_silgen_name("_swift_se0405_String_validatingUTF8")\n public init?(validatingUTF8 cString: UnsafePointer<CChar>) {\n unsafe self.init(validatingCString: cString)\n }\n\n /// Creates a new string by copying and validating the null-terminated UTF-8\n /// data referenced by the given array.\n ///\n /// This initializer does not try to repair ill-formed UTF-8 code unit\n /// sequences. If any are found, the result of the initializer is `nil`.\n ///\n /// - Note: This initializer is deprecated. Use the initializer\n /// `String.init?(validating: array, as: UTF8.self)` instead,\n /// remembering that "\0" is a valid character in Swift.\n ///\n /// - Parameter nullTerminatedUTF8:\n /// An array containing a null-terminated sequence of UTF-8 code units.\n @inlinable\n @_alwaysEmitIntoClient\n @available(swift, deprecated: 6, message:\n "Use String(validating: array, as: UTF8.self) instead, after truncating the null termination."\n )\n public init?(validatingCString nullTerminatedUTF8: [CChar]) {\n guard let length = nullTerminatedUTF8.firstIndex(of: 0) else {\n _preconditionFailure(\n "input of String.init(validatingCString:) must be null-terminated"\n )\n }\n let string = unsafe nullTerminatedUTF8.prefix(length).withUnsafeBufferPointer {\n unsafe $0.withMemoryRebound(to: UInt8.self, String._tryFromUTF8(_:))\n }\n guard let string else { return nil }\n self = string\n }\n\n /// Creates a new string by copying and validating the null-terminated UTF-8\n /// data referenced by the given array.\n ///\n /// This initializer does not try to repair ill-formed UTF-8 code unit\n /// sequences. If any are found, the result of the initializer is `nil`.\n ///\n /// - Note: This initializer is deprecated. Use the initializer\n /// `String.init?(validating: array, as: UTF8.self)` instead,\n /// remembering that "\0" is a valid character in Swift.\n ///\n /// - Parameter cString:\n /// An array containing a null-terminated sequence of UTF-8 code units.\n @inlinable\n @_alwaysEmitIntoClient\n @available(swift, deprecated: 6, message:\n "Use String(validating: array, as: UTF8.self) instead, after truncating the null termination."\n )\n public init?(validatingUTF8 cString: [CChar]) {\n self.init(validatingCString: cString)\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "Use a copy of the String argument")\n public init?(validatingCString nullTerminatedUTF8: String) {\n self = unsafe nullTerminatedUTF8.withCString(String.init(cString:))\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "Use a copy of the String argument")\n public init?(validatingUTF8 cString: String) {\n self.init(validatingCString: cString)\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "Use String(_ scalar: Unicode.Scalar)")\n public init?(validatingCString nullTerminatedUTF8: inout CChar) {\n guard nullTerminatedUTF8 == 0 else {\n _preconditionFailure(\n "input of String.init(validatingCString:) must be null-terminated"\n )\n }\n self = ""\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "Use String(_ scalar: Unicode.Scalar)")\n public init?(validatingUTF8 cString: inout CChar) {\n self.init(validatingCString: &cString)\n }\n\n /// Creates a new string by copying the null-terminated data referenced by\n /// the given pointer using the specified encoding.\n ///\n /// When you pass `true` as `isRepairing`, this method replaces ill-formed\n /// sequences with the Unicode replacement character (`"\u{FFFD}"`);\n /// otherwise, an ill-formed sequence causes this method to stop decoding\n /// and return `nil`.\n ///\n /// The following example calls this method with pointers to the contents of\n /// two different `CChar` arrays---the first with well-formed UTF-8 code\n /// unit sequences and the second with an ill-formed sequence at the end.\n ///\n /// let validUTF8: [UInt8] = [67, 97, 102, 195, 169, 0]\n /// validUTF8.withUnsafeBufferPointer { ptr in\n /// let s = String.decodeCString(ptr.baseAddress,\n /// as: UTF8.self,\n /// repairingInvalidCodeUnits: true)\n /// print(s)\n /// }\n /// // Prints "Optional((result: "Café", repairsMade: false))"\n ///\n /// let invalidUTF8: [UInt8] = [67, 97, 102, 195, 0]\n /// invalidUTF8.withUnsafeBufferPointer { ptr in\n /// let s = String.decodeCString(ptr.baseAddress,\n /// as: UTF8.self,\n /// repairingInvalidCodeUnits: true)\n /// print(s)\n /// }\n /// // Prints "Optional((result: "Caf�", repairsMade: true))"\n ///\n /// - Parameters:\n /// - cString: A pointer to a null-terminated sequence of\n /// code units encoded in `encoding`.\n /// - encoding: The Unicode encoding of the data referenced by `cString`.\n /// - isRepairing: Pass `true` to create a new string, even when the data\n /// referenced by `cString` contains ill-formed sequences. Ill-formed\n /// sequences are replaced with the Unicode replacement character\n /// (`"\u{FFFD}"`). Pass `false` to interrupt the creation of the new\n /// string if an ill-formed sequence is detected.\n /// - Returns: A tuple with the new string and a Boolean value that indicates\n /// whether any repairs were made. If `isRepairing` is `false` and an\n /// ill-formed sequence is detected, this method returns `nil`.\n @_specialize(where Encoding == Unicode.UTF8)\n @_specialize(where Encoding == Unicode.UTF16)\n @inlinable // Fold away specializations\n public static func decodeCString<Encoding: _UnicodeEncoding>(\n _ cString: UnsafePointer<Encoding.CodeUnit>?,\n as encoding: Encoding.Type,\n repairingInvalidCodeUnits isRepairing: Bool = true\n ) -> (result: String, repairsMade: Bool)? {\n guard let cPtr = unsafe cString else { return nil }\n\n if _fastPath(encoding == Unicode.UTF8.self) {\n let len = unsafe UTF8._nullCodeUnitOffset(\n in: UnsafeRawPointer(cPtr).assumingMemoryBound(to: UInt8.self)\n )\n let bytes = unsafe UnsafeBufferPointer(start: cPtr, count: len)\n return unsafe bytes.withMemoryRebound(to: UInt8.self) { codeUnits in\n if isRepairing {\n return unsafe String._fromUTF8Repairing(codeUnits)\n }\n else if let str = unsafe String._tryFromUTF8(codeUnits) {\n return (str, false)\n }\n return nil\n }\n }\n\n var end = unsafe cPtr\n while unsafe end.pointee != 0 { unsafe end += 1 }\n let len = unsafe end - cPtr\n let codeUnits = unsafe UnsafeBufferPointer(start: cPtr, count: len)\n return unsafe String._fromCodeUnits(\n codeUnits, encoding: encoding, repair: isRepairing)\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n public static func decodeCString<Encoding: _UnicodeEncoding>(\n _ cString: [Encoding.CodeUnit],\n as encoding: Encoding.Type,\n repairingInvalidCodeUnits isRepairing: Bool = true\n ) -> (result: String, repairsMade: Bool)? {\n guard let length = cString.firstIndex(of: 0) else {\n _preconditionFailure(\n "input of decodeCString(_:as:repairingInvalidCodeUnits:) must be null-terminated"\n )\n }\n\n if _fastPath(encoding == Unicode.UTF8.self) {\n return unsafe cString.prefix(length).withUnsafeBufferPointer {\n buffer -> (result: String, repairsMade: Bool)? in\n return unsafe buffer.withMemoryRebound(to: UInt8.self) { codeUnits in\n if isRepairing {\n return unsafe String._fromUTF8Repairing(codeUnits)\n }\n else if let str = unsafe String._tryFromUTF8(codeUnits) {\n return (str, false)\n }\n return nil\n }\n }\n }\n\n return unsafe cString.prefix(length).withUnsafeBufferPointer {\n buf -> (result: String, repairsMade: Bool)? in\n unsafe String._fromCodeUnits(buf, encoding: encoding, repair: isRepairing)\n }\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "Use a copy of the String argument")\n public static func decodeCString<Encoding: _UnicodeEncoding>(\n _ cString: String,\n as encoding: Encoding.Type,\n repairingInvalidCodeUnits isRepairing: Bool = true\n ) -> (result: String, repairsMade: Bool)? {\n return unsafe cString.withCString(encodedAs: encoding) {\n unsafe String.decodeCString(\n $0, as: encoding, repairingInvalidCodeUnits: isRepairing\n )\n }\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "Use String(_ scalar: Unicode.Scalar)")\n public static func decodeCString<Encoding: _UnicodeEncoding>(\n _ cString: inout Encoding.CodeUnit,\n as encoding: Encoding.Type,\n repairingInvalidCodeUnits isRepairing: Bool = true\n ) -> (result: String, repairsMade: Bool)? {\n guard cString == 0 else {\n _preconditionFailure(\n "input of decodeCString(_:as:repairingInvalidCodeUnits:) must be null-terminated"\n )\n }\n return ("", false)\n }\n\n /// Creates a new string by copying the null-terminated sequence of code units\n /// referenced by the given pointer.\n ///\n /// If `nullTerminatedCodeUnits` contains ill-formed code unit sequences, this\n /// initializer replaces them with the Unicode replacement character\n /// (`"\u{FFFD}"`).\n ///\n /// - Parameters:\n /// - nullTerminatedCodeUnits: A pointer to a null-terminated sequence of\n /// code units encoded in `encoding`.\n /// - encoding: The encoding in which the code units should be\n /// interpreted.\n @_specialize(where Encoding == Unicode.UTF8)\n @_specialize(where Encoding == Unicode.UTF16)\n @inlinable // Fold away specializations\n public init<Encoding: Unicode.Encoding>(\n decodingCString nullTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>,\n as encoding: Encoding.Type\n ) {\n self = unsafe String.decodeCString(nullTerminatedCodeUnits, as: encoding)!.0\n }\n\n /// Creates a new string by copying the null-terminated sequence of code units\n /// referenced by the given array.\n ///\n /// If `nullTerminatedCodeUnits` contains ill-formed code unit sequences, this\n /// initializer replaces them with the Unicode replacement character\n /// (`"\u{FFFD}"`).\n ///\n /// - Note: This initializer is deprecated. Use the initializer\n /// `String.init(decoding: array, as: Encoding.self)` instead,\n /// remembering that "\0" is a valid character in Swift.\n ///\n /// - Parameters:\n /// - nullTerminatedCodeUnits: An array containing a null-terminated\n /// sequence of code units encoded in `encoding`.\n /// - encoding: The encoding in which the code units should be\n /// interpreted.\n @inlinable\n @_alwaysEmitIntoClient\n @available(swift, deprecated: 6, message:\n "Use String(decoding: array, as: Encoding.self) instead, after truncating the null termination."\n )\n public init<Encoding: Unicode.Encoding>(\n decodingCString nullTerminatedCodeUnits: [Encoding.CodeUnit],\n as encoding: Encoding.Type\n ) {\n self = String.decodeCString(nullTerminatedCodeUnits, as: encoding)!.0\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "Use a copy of the String argument")\n public init<Encoding: _UnicodeEncoding>(\n decodingCString nullTerminatedCodeUnits: String,\n as encoding: Encoding.Type\n ) {\n self = unsafe nullTerminatedCodeUnits.withCString(encodedAs: encoding) {\n unsafe String(decodingCString: $0, as: encoding.self)\n }\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n @available(*, deprecated, message: "Use String(_ scalar: Unicode.Scalar)")\n public init<Encoding: Unicode.Encoding>(\n decodingCString nullTerminatedCodeUnits: inout Encoding.CodeUnit,\n as encoding: Encoding.Type\n ) {\n guard nullTerminatedCodeUnits == 0 else {\n _preconditionFailure(\n "input of String.init(decodingCString:as:) must be null-terminated"\n )\n }\n self = ""\n }\n}\n\nextension UnsafePointer where Pointee == UInt8 {\n @inlinable\n internal var _asCChar: UnsafePointer<CChar> {\n @inline(__always) get {\n return unsafe UnsafeRawPointer(self).assumingMemoryBound(to: CChar.self)\n }\n }\n}\nextension UnsafePointer where Pointee == CChar {\n @inlinable\n internal var _asUInt8: UnsafePointer<UInt8> {\n @inline(__always) get {\n return unsafe UnsafeRawPointer(self).assumingMemoryBound(to: UInt8.self)\n }\n }\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_CString.swift | cpp_apple_swift_stdlib_public_core_CString.swift | Swift | 21,485 | 0.95 | 0.02509 | 0.427757 | node-utils | 78 | 2023-12-17T19:53:32.488691 | GPL-3.0 | false | c483d6e70fe99c2d900940c55557c438 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n// C Primitive Types\n//===----------------------------------------------------------------------===//\n\n/// The C 'char' type.\n///\n/// This will be the same as either `CSignedChar` (in the common\n/// case) or `CUnsignedChar`, depending on the platform.\npublic typealias CChar = Int8\n\n/// The C 'unsigned char' type.\npublic typealias CUnsignedChar = UInt8\n\n/// The C 'unsigned short' type.\npublic typealias CUnsignedShort = UInt16\n\n/// The C 'unsigned int' type.\n#if _pointerBitWidth(_16)\npublic typealias CUnsignedInt = UInt\n#else\npublic typealias CUnsignedInt = UInt32\n#endif\n\n/// The C 'unsigned long' type.\n#if (os(Windows) && (arch(x86_64) || arch(arm64))) || _pointerBitWidth(_16)\npublic typealias CUnsignedLong = UInt32\n#else\npublic typealias CUnsignedLong = UInt\n#endif\n\n/// The C 'unsigned long long' type.\npublic typealias CUnsignedLongLong = UInt64\n\n/// The C 'signed char' type.\npublic typealias CSignedChar = Int8\n\n/// The C 'short' type.\npublic typealias CShort = Int16\n\n/// The C 'int' type.\n#if _pointerBitWidth(_16)\npublic typealias CInt = Int\n#else\npublic typealias CInt = Int32\n#endif\n\n/// The C 'long' type.\n#if (os(Windows) && (arch(x86_64) || arch(arm64))) || _pointerBitWidth(_16)\npublic typealias CLong = Int32\n#else\npublic typealias CLong = Int\n#endif\n\n/// The C 'long long' type.\npublic typealias CLongLong = Int64\n\n#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))\n/// The C '_Float16' type.\n@available(SwiftStdlib 5.3, *)\npublic typealias CFloat16 = Float16\n#endif\n\n/// The C 'float' type.\npublic typealias CFloat = Float\n\n/// The C 'double' type.\npublic typealias CDouble = Double\n\n/// The C 'long double' type.\n#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)\n// On Darwin, long double is Float80 on x86, and Double otherwise.\n#if arch(x86_64) || arch(i386)\npublic typealias CLongDouble = Float80\n#else\npublic typealias CLongDouble = Double\n#endif\n#elseif os(Windows)\n// On Windows, long double is always Double.\npublic typealias CLongDouble = Double\n#elseif os(Linux)\n// On Linux/x86, long double is Float80.\n// TODO: Fill in definitions for additional architectures as needed. IIRC\n// armv7 should map to Double, but arm64 and ppc64le should map to Float128,\n// which we don't yet have in Swift.\n#if arch(x86_64) || arch(i386)\npublic typealias CLongDouble = Float80\n#elseif arch(s390x)\n// On s390x '-mlong-double-64' option with size of 64-bits makes the\n// Long Double type equivalent to Double type.\npublic typealias CLongDouble = Double\n#endif\n#elseif os(Android)\n// On Android, long double is Float128 for AAPCS64, which we don't have yet in\n// Swift (https://github.com/apple/swift/issues/51573); and Double for ARMv7.\n#if arch(arm)\npublic typealias CLongDouble = Double\n#endif\n#elseif os(OpenBSD)\n#if arch(x86_64)\npublic typealias CLongDouble = Float80\n#elseif arch(arm64)\npublic typealias CLongDouble = Double\n#else\n#error("CLongDouble needs to be defined for this OpenBSD architecture")\n#endif\n#elseif os(FreeBSD)\n#if arch(x86_64) || arch(i386)\npublic typealias CLongDouble = Float80\n#else\n#error("CLongDouble needs to be defined for this FreeBSD architecture")\n#endif\n#elseif $Embedded\n#if arch(x86_64) || arch(i386)\npublic typealias CLongDouble = Double\n#endif\n#else\n// TODO: define CLongDouble for other OSes\n#endif\n\n// FIXME: Is it actually UTF-32 on Darwin?\n//\n/// The C++ 'wchar_t' type.\n#if os(Windows)\npublic typealias CWideChar = UInt16\n#else\npublic typealias CWideChar = Unicode.Scalar\n#endif\n\n/// The C++20 'char8_t' type, which has UTF-8 encoding.\npublic typealias CChar8 = UInt8\n\n// FIXME: Swift should probably have a UTF-16 type other than UInt16.\n//\n/// The C++11 'char16_t' type, which has UTF-16 encoding.\npublic typealias CChar16 = UInt16\n\n/// The C++11 'char32_t' type, which has UTF-32 encoding.\npublic typealias CChar32 = Unicode.Scalar\n\n/// The C '_Bool' and C++ 'bool' type.\npublic typealias CBool = Bool\n\n/// A wrapper around an opaque C pointer.\n///\n/// Opaque pointers are used to represent C pointers to types that\n/// cannot be represented in Swift, such as incomplete struct types.\n@frozen\n@unsafe\npublic struct OpaquePointer {\n @usableFromInline\n internal var _rawValue: Builtin.RawPointer\n\n @usableFromInline @_transparent\n internal init(_ v: Builtin.RawPointer) {\n unsafe self._rawValue = v\n }\n}\n\n@available(*, unavailable)\nextension OpaquePointer: Sendable {}\n\nextension OpaquePointer {\n /// Creates a new `OpaquePointer` from the given address, specified as a bit\n /// pattern.\n ///\n /// - Parameter bitPattern: A bit pattern to use for the address of the new\n /// pointer. If `bitPattern` is zero, the result is `nil`.\n @_transparent\n public init?(bitPattern: Int) {\n if bitPattern == 0 { return nil }\n unsafe self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)\n }\n\n /// Creates a new `OpaquePointer` from the given address, specified as a bit\n /// pattern.\n ///\n /// - Parameter bitPattern: A bit pattern to use for the address of the new\n /// pointer. If `bitPattern` is zero, the result is `nil`.\n @_transparent\n public init?(bitPattern: UInt) {\n if bitPattern == 0 { return nil }\n unsafe self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)\n }\n}\n\nextension OpaquePointer {\n /// Converts a typed `UnsafePointer` to an opaque C pointer.\n @_transparent\n @_preInverseGenerics\n @safe\n public init<T: ~Copyable>(@_nonEphemeral _ from: UnsafePointer<T>) {\n unsafe self._rawValue = from._rawValue\n }\n\n /// Converts a typed `UnsafePointer` to an opaque C pointer.\n ///\n /// The result is `nil` if `from` is `nil`.\n @_transparent\n @_preInverseGenerics\n @safe\n public init?<T: ~Copyable>(@_nonEphemeral _ from: UnsafePointer<T>?) {\n guard let unwrapped = unsafe from else { return nil }\n self.init(unwrapped)\n }\n}\n\nextension OpaquePointer {\n /// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.\n @_transparent\n @_preInverseGenerics\n @safe\n public init<T: ~Copyable>(@_nonEphemeral _ from: UnsafeMutablePointer<T>) {\n unsafe self._rawValue = from._rawValue\n }\n\n /// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.\n ///\n /// The result is `nil` if `from` is `nil`.\n @_transparent\n @_preInverseGenerics\n @safe\n public init?<T: ~Copyable>(@_nonEphemeral _ from: UnsafeMutablePointer<T>?) {\n guard let unwrapped = unsafe from else { return nil }\n self.init(unwrapped)\n }\n}\n\nextension OpaquePointer: Equatable {\n @inlinable // unsafe-performance\n @safe\n public static func == (lhs: OpaquePointer, rhs: OpaquePointer) -> Bool {\n return unsafe Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))\n }\n}\n\nextension OpaquePointer: @unsafe Hashable {\n /// Hashes the essential components of this value by feeding them into the\n /// given hasher.\n ///\n /// - Parameter hasher: The hasher to use when combining the components\n /// of this instance.\n @inlinable\n @safe\n public func hash(into hasher: inout Hasher) {\n unsafe hasher.combine(Int(Builtin.ptrtoint_Word(_rawValue)))\n }\n}\n\n@_unavailableInEmbedded\nextension OpaquePointer: CustomDebugStringConvertible {\n /// A textual representation of the pointer, suitable for debugging.\n @safe\n public var debugDescription: String {\n return unsafe _rawPointerToString(_rawValue)\n }\n}\n\nextension Int {\n /// Creates a new value with the bit pattern of the given pointer.\n ///\n /// The new value represents the address of the pointer passed as `pointer`.\n /// If `pointer` is `nil`, the result is `0`.\n ///\n /// - Parameter pointer: The pointer to use as the source for the new\n /// integer.\n @inlinable // unsafe-performance\n @safe\n public init(bitPattern pointer: OpaquePointer?) {\n unsafe self.init(bitPattern: UnsafeRawPointer(pointer))\n }\n}\n\nextension UInt {\n /// Creates a new value with the bit pattern of the given pointer.\n ///\n /// The new value represents the address of the pointer passed as `pointer`.\n /// If `pointer` is `nil`, the result is `0`.\n ///\n /// - Parameter pointer: The pointer to use as the source for the new\n /// integer.\n @inlinable // unsafe-performance\n @safe\n public init(bitPattern pointer: OpaquePointer?) {\n unsafe self.init(bitPattern: UnsafeRawPointer(pointer))\n }\n}\n\n/// A wrapper around a C `va_list` pointer.\n#if arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(visionOS) || os(Windows))\n@frozen\n@unsafe\npublic struct CVaListPointer {\n @unsafe @usableFromInline // unsafe-performance\n internal var _value: (__stack: UnsafeMutablePointer<Int>?,\n __gr_top: UnsafeMutablePointer<Int>?,\n __vr_top: UnsafeMutablePointer<Int>?,\n __gr_off: Int32,\n __vr_off: Int32)\n\n @inlinable // unsafe-performance\n public // @testable\n init(__stack: UnsafeMutablePointer<Int>?,\n __gr_top: UnsafeMutablePointer<Int>?,\n __vr_top: UnsafeMutablePointer<Int>?,\n __gr_off: Int32,\n __vr_off: Int32) {\n _value = (__stack, __gr_top, __vr_top, __gr_off, __vr_off)\n }\n}\n\n@_unavailableInEmbedded\nextension CVaListPointer: CustomDebugStringConvertible {\n @safe\n public var debugDescription: String {\n return "(\(_value.__stack.debugDescription), " +\n "\(_value.__gr_top.debugDescription), " +\n "\(_value.__vr_top.debugDescription), " +\n "\(_value.__gr_off), " +\n "\(_value.__vr_off))"\n }\n}\n\n#else\n\n@frozen\n@unsafe\npublic struct CVaListPointer {\n @unsafe @usableFromInline // unsafe-performance\n internal var _value: UnsafeMutableRawPointer\n\n @inlinable // unsafe-performance\n public // @testable\n init(_fromUnsafeMutablePointer from: UnsafeMutableRawPointer) {\n unsafe _value = from\n }\n}\n\n@_unavailableInEmbedded\nextension CVaListPointer: CustomDebugStringConvertible {\n /// A textual representation of the pointer, suitable for debugging.\n @safe\n public var debugDescription: String {\n return unsafe _value.debugDescription\n }\n}\n\n#endif\n\n@available(*, unavailable)\nextension CVaListPointer: Sendable { }\n\n/// Copy `size` bytes of memory from `src` into `dest`.\n///\n/// The memory regions `src..<src + size` and\n/// `dest..<dest + size` should not overlap.\n@inlinable\ninternal func _memcpy(\n dest destination: UnsafeMutableRawPointer,\n src: UnsafeRawPointer,\n size: UInt\n) {\n let dest = destination._rawValue\n let src = src._rawValue\n let size = UInt64(size)._value\n Builtin.int_memcpy_RawPointer_RawPointer_Int64(\n dest, src, size,\n /*volatile:*/ false._value)\n}\n\n/// Copy `size` bytes of memory from `src` into `dest`.\n///\n/// The memory regions `src..<src + size` and\n/// `dest..<dest + size` may overlap.\n@inlinable\ninternal func _memmove(\n dest destination: UnsafeMutableRawPointer,\n src: UnsafeRawPointer,\n size: UInt\n) {\n let dest = destination._rawValue\n let src = src._rawValue\n let size = UInt64(size)._value\n Builtin.int_memmove_RawPointer_RawPointer_Int64(\n dest, src, size,\n /*volatile:*/ false._value)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_CTypes.swift | cpp_apple_swift_stdlib_public_core_CTypes.swift | Swift | 11,536 | 0.8 | 0.080808 | 0.435897 | python-kit | 39 | 2024-09-25T06:19:59.742074 | BSD-3-Clause | false | 6536a1740d146efd668b4c5b04dc2fd6 |
//===--- DebuggerSupport.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n// Macros are disabled when Swift is built without swift-syntax.\n#if $Macros && hasAttribute(attached)\n\n/// Converts description definitions to a debugger Type Summary.\n///\n/// This macro converts compatible description implementations written in Swift\n/// to an LLDB format known as a Type Summary. A Type Summary is LLDB's\n/// equivalent to `debugDescription`, with the distinction that it does not\n/// execute code inside the debugged process. By avoiding code execution,\n/// descriptions can be produced faster, without potential side effects, and\n/// shown in situations where code execution is not performed, such as the\n/// variable list of an IDE.\n///\n/// Consider this an example. This `Team` struct has a `debugDescription` which\n/// summarizes some key details, such as the team's name. The debugger only\n/// computes this string on demand - typically via the `po` command. By applying\n/// the `DebugDescription` macro, a matching Type Summary is constructed. This\n/// allows the user to show a string like "Rams [11-2]", without executing\n/// `debugDescription`. This improves the usability, performance, and\n/// reliability of the debugging experience.\n///\n/// @DebugDescription\n/// struct Team: CustomDebugStringConvertible {\n/// var name: String\n/// var wins, losses: Int\n///\n/// var debugDescription: String {\n/// "\(name) [\(wins)-\(losses)]"\n/// }\n/// }\n///\n/// The `DebugDescription` macro supports both `debugDescription`, `description`,\n/// as well as a third option: a property named `lldbDescription`. The first\n/// two are implemented when conforming to the `CustomDebugStringConvertible`\n/// and `CustomStringConvertible` protocols. The additional `lldbDescription`\n/// property is useful when both `debugDescription` and `description` are\n/// implemented, but don't meet the requirements of the `DebugDescription`\n/// macro. If `lldbDescription` is implemented, `DebugDescription` choose it\n/// over `debugDescription` and `description`. Likewise, `debugDescription` is\n/// preferred over `description`.\n///\n/// ### Description Requirements\n///\n/// The description implementation has the following requirements:\n///\n/// * The body of the description implementation must a single string\n/// expression. String concatenation is not supported, use string interpolation\n/// instead.\n/// * String interpolation can reference stored properties only, functions calls\n/// and other arbitrary computation are not supported. Of note, conditional\n/// logic and computed properties are not supported.\n/// * Overloaded string interpolation cannot be used.\n@attached(member)\n@attached(memberAttribute)\npublic macro DebugDescription() =\n #externalMacro(module: "SwiftMacros", type: "DebugDescriptionMacro")\n\n/// Internal-only macro. See `@DebugDescription`.\n@attached(peer, names: named(_lldb_summary))\npublic macro _DebugDescriptionProperty(_ debugIdentifier: String, _ computedProperties: [String]) =\n #externalMacro(module: "SwiftMacros", type: "_DebugDescriptionPropertyMacro")\n\n#endif\n\n#if SWIFT_ENABLE_REFLECTION\n\n@frozen // namespace\npublic enum _DebuggerSupport {\n private enum CollectionStatus {\n case notACollection\n case collectionOfElements\n case collectionOfPairs\n case element\n case pair\n case elementOfPair\n \n internal var isCollection: Bool {\n return self != .notACollection\n }\n \n internal func getChildStatus(child: Mirror) -> CollectionStatus {\n let disposition = child.displayStyle\n \n if disposition == .collection { return .collectionOfElements }\n if disposition == .dictionary { return .collectionOfPairs }\n if disposition == .set { return .collectionOfElements }\n \n if self == .collectionOfElements { return .element }\n if self == .collectionOfPairs { return .pair }\n if self == .pair { return .elementOfPair }\n \n return .notACollection\n }\n }\n\n private static func isClass(_ value: Any) -> Bool {\n return type(of: value) is AnyClass\n }\n \n private static func checkValue<T>(\n _ value: Any,\n ifClass: (AnyObject) -> T,\n otherwise: () -> T\n ) -> T {\n if isClass(value) {\n return ifClass(_unsafeDowncastToAnyObject(fromAny: value))\n }\n return otherwise()\n }\n\n private static func asObjectIdentifier(_ value: Any) -> ObjectIdentifier? {\n return checkValue(value,\n ifClass: { return ObjectIdentifier($0) },\n otherwise: { return nil })\n }\n\n private static func asObjectAddress(_ value: Any) -> String {\n let address = checkValue(value,\n ifClass: { return unsafe unsafeBitCast($0, to: Int.self) },\n otherwise: { return 0 })\n return String(address, radix: 16, uppercase: false)\n }\n\n private static func asStringRepresentation(\n value: Any?,\n mirror: Mirror,\n count: Int\n ) -> String? {\n switch mirror.displayStyle {\n case .optional? where count > 0:\n return "\(mirror.subjectType)"\n case .optional?:\n return value.map(String.init(reflecting:))\n case .collection?, .dictionary?, .set?, .tuple?:\n return count == 1 ? "1 element" : "\(count) elements"\n case .`struct`?, .`enum`?, nil:\n switch value {\n case let x as CustomDebugStringConvertible:\n return x.debugDescription\n case let x as CustomStringConvertible:\n return x.description\n case _ where count > 0:\n return "\(mirror.subjectType)"\n default:\n return value.map(String.init(reflecting:))\n }\n case .`class`?:\n switch value {\n case let x as CustomDebugStringConvertible:\n return x.debugDescription\n case let x as CustomStringConvertible:\n return x.description\n case let x?:\n // for a Class with no custom summary, mimic the Foundation default\n return "<\(type(of: x)): 0x\(asObjectAddress(x))>"\n default:\n // but if I can't provide a value, just use the type anyway\n return "\(mirror.subjectType)"\n }\n }\n }\n\n private static func ivarCount(mirror: Mirror) -> Int {\n let ivars = mirror.superclassMirror.map(ivarCount) ?? 0\n return ivars + mirror.children.count\n }\n\n private static func shouldExpand(\n mirror: Mirror,\n collectionStatus: CollectionStatus,\n isRoot: Bool\n ) -> Bool {\n if isRoot || collectionStatus.isCollection { return true }\n if !mirror.children.isEmpty { return true }\n if mirror.displayStyle == .`class` { return true }\n if let sc = mirror.superclassMirror { return ivarCount(mirror: sc) > 0 }\n return true\n }\n\n private static func printForDebuggerImpl<StreamType: TextOutputStream>(\n value: Any?,\n mirror: Mirror,\n name: String?,\n indent: Int,\n maxDepth: Int,\n isRoot: Bool,\n parentCollectionStatus: CollectionStatus,\n refsAlreadySeen: inout Set<ObjectIdentifier>,\n maxItemCounter: inout Int,\n target: inout StreamType\n ) { \n guard maxItemCounter > 0 else { return }\n\n guard shouldExpand(mirror: mirror,\n collectionStatus: parentCollectionStatus,\n isRoot: isRoot) \n else { return }\n\n maxItemCounter -= 1\n \n print(String(repeating: " ", count: indent), terminator: "", to: &target)\n\n // do not expand classes with no custom Mirror\n // yes, a type can lie and say it's a class when it's not since we only\n // check the displayStyle - but then the type would have a custom Mirror\n // anyway, so there's that...\n let isNonClass = mirror.displayStyle != .`class`\n let isCustomReflectable: Bool\n if let value = value {\n isCustomReflectable = value is CustomReflectable\n } else {\n isCustomReflectable = true\n }\n let willExpand = isNonClass || isCustomReflectable\n\n let count = mirror.children.count\n let bullet = isRoot && (count == 0 || !willExpand) ? ""\n : count == 0 ? "- "\n : maxDepth <= 0 ? "▹ " : "▿ "\n print(bullet, terminator: "", to: &target)\n \n let collectionStatus = parentCollectionStatus.getChildStatus(child: mirror)\n \n if let name = name {\n print("\(name) : ", terminator: "", to: &target)\n }\n\n if isRoot, let value = value as? String {\n // We don't want to use string's debug desciprtion for 'po' because it\n // escapes the string and prints it raw (e.g. prints "\n" instead of\n // actually printing a newline), but only if its the root value. Otherwise,\n // continue using the debug description.\n print(value, terminator: "", to: &target)\n } else if let str = asStringRepresentation(value: value, mirror: mirror, count: count) {\n print(str, terminator: "", to: &target)\n }\n \n if (maxDepth <= 0) || !willExpand {\n print("", to: &target)\n return\n }\n\n if let valueIdentifier = value.flatMap(asObjectIdentifier) {\n if refsAlreadySeen.contains(valueIdentifier) {\n print(" { ... }", to: &target)\n return\n } else {\n refsAlreadySeen.insert(valueIdentifier)\n }\n }\n\n print("", to: &target)\n \n var printedElements = 0\n \n if let sc = mirror.superclassMirror {\n printForDebuggerImpl(\n value: nil,\n mirror: sc,\n name: "super",\n indent: indent + 2,\n maxDepth: maxDepth - 1,\n isRoot: false,\n parentCollectionStatus: .notACollection,\n refsAlreadySeen: &refsAlreadySeen,\n maxItemCounter: &maxItemCounter,\n target: &target)\n }\n \n for (optionalName,child) in mirror.children {\n let childName = optionalName ?? "\(printedElements)"\n if maxItemCounter <= 0 {\n print(String(repeating: " ", count: indent+4), terminator: "", to: &target)\n let remainder = count - printedElements\n print("(\(remainder)", terminator: "", to: &target)\n if printedElements > 0 {\n print(" more", terminator: "", to: &target)\n }\n print(remainder == 1 ? " child)" : " children)", to: &target)\n return\n }\n \n printForDebuggerImpl(\n value: child,\n mirror: Mirror(reflecting: child),\n name: childName,\n indent: indent + 2,\n maxDepth: maxDepth - 1,\n isRoot: false,\n parentCollectionStatus: collectionStatus,\n refsAlreadySeen: &refsAlreadySeen,\n maxItemCounter: &maxItemCounter,\n target: &target)\n printedElements += 1\n }\n }\n\n public static func stringForPrintObject(_ value: Any) -> String {\n var maxItemCounter = Int.max\n var refs = Set<ObjectIdentifier>()\n var target = ""\n\n printForDebuggerImpl(\n value: value,\n mirror: Mirror(reflecting: value),\n name: nil,\n indent: 0,\n maxDepth: maxItemCounter,\n isRoot: true,\n parentCollectionStatus: .notACollection,\n refsAlreadySeen: &refs,\n maxItemCounter: &maxItemCounter,\n target: &target)\n\n return target\n }\n}\n\npublic func _stringForPrintObject(_ value: Any) -> String {\n return _DebuggerSupport.stringForPrintObject(value)\n}\n\n#endif // SWIFT_ENABLE_REFLECTION\n\npublic func _debuggerTestingCheckExpect(_: String, _: String) { }\n\n@_alwaysEmitIntoClient @_transparent\ninternal func _withHeapObject<R>(\n of object: AnyObject,\n _ body: (UnsafeMutableRawPointer) -> R\n) -> R {\n defer { _fixLifetime(object) }\n let unmanaged = unsafe Unmanaged.passUnretained(object)\n return unsafe body(unmanaged.toOpaque())\n}\n\n@_extern(c, "swift_retainCount") @usableFromInline\ninternal func _swift_retainCount(_: UnsafeMutableRawPointer) -> Int\n@_extern(c, "swift_unownedRetainCount") @usableFromInline\ninternal func _swift_unownedRetainCount(_: UnsafeMutableRawPointer) -> Int\n@_extern(c, "swift_weakRetainCount") @usableFromInline\ninternal func _swift_weakRetainCount(_: UnsafeMutableRawPointer) -> Int\n\n// Utilities to get refcount(s) of class objects.\n@_alwaysEmitIntoClient\npublic func _getRetainCount(_ object: AnyObject) -> UInt {\n let count = unsafe _withHeapObject(of: object) { unsafe _swift_retainCount($0) }\n return UInt(bitPattern: count)\n}\n\n@_alwaysEmitIntoClient\npublic func _getUnownedRetainCount(_ object: AnyObject) -> UInt {\n let count = unsafe _withHeapObject(of: object) { unsafe _swift_unownedRetainCount($0) }\n return UInt(bitPattern: count)\n}\n\n@_alwaysEmitIntoClient\npublic func _getWeakRetainCount(_ object: AnyObject) -> UInt {\n let count = unsafe _withHeapObject(of: object) { unsafe _swift_weakRetainCount($0) }\n return UInt(bitPattern: count)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_DebuggerSupport.swift | cpp_apple_swift_stdlib_public_core_DebuggerSupport.swift | Swift | 12,926 | 0.95 | 0.101333 | 0.240122 | vue-tools | 416 | 2025-01-26T02:47:06.524547 | BSD-3-Clause | false | 70087384a5220ca6277a8e0a431fea0b |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Implementation notes\n// ====================\n//\n// `Dictionary` uses two storage schemes: native storage and Cocoa storage.\n//\n// Native storage is a hash table with open addressing and linear probing. The\n// bucket array forms a logical ring (e.g., a chain can wrap around the end of\n// buckets array to the beginning of it).\n//\n// The logical bucket array is implemented as three arrays: Key, Value, and a\n// bitmap that marks valid entries. An unoccupied entry marks the end of a\n// chain. There is always at least one unoccupied entry among the\n// buckets. `Dictionary` does not use tombstones.\n//\n// In addition to the native storage, `Dictionary` can also wrap an\n// `NSDictionary` in order to allow bridging `NSDictionary` to `Dictionary` in\n// `O(1)`.\n//\n// Native dictionary storage uses a data structure like this::\n//\n// struct Dictionary<K,V>\n// +------------------------------------------------+\n// | enum Dictionary<K,V>._Variant |\n// | +--------------------------------------------+ |\n// | | [struct _NativeDictionary<K,V> | |\n// | +---|----------------------------------------+ |\n// +----/-------------------------------------------+\n// /\n// |\n// V\n// class __RawDictionaryStorage\n// +-----------------------------------------------------------+\n// | <isa> |\n// | <refcount> |\n// | _count |\n// | _capacity |\n// | _scale |\n// | _age |\n// | _seed |\n// | _rawKeys |\n// | _rawValue |\n// | [inline bitset of occupied entries] |\n// | [inline array of keys] |\n// | [inline array of values] |\n// +-----------------------------------------------------------+\n//\n// Cocoa storage uses a data structure like this:\n//\n// struct Dictionary<K,V>\n// +----------------------------------------------+\n// | enum Dictionary<K,V>._Variant |\n// | +----------------------------------------+ |\n// | | [ struct __CocoaDictionary | |\n// | +---|------------------------------------+ |\n// +----/-----------------------------------------+\n// /\n// |\n// V\n// class NSDictionary\n// +--------------+\n// | [refcount#1] |\n// | etc. |\n// +--------------+\n// ^\n// |\n// \ struct __CocoaDictionary.Index\n// +--|------------------------------------+\n// | * base: __CocoaDictionary |\n// | allKeys: array of all keys |\n// | currentKeyIndex: index into allKeys |\n// +---------------------------------------+\n//\n//\n// The Native Kinds of Storage\n// ---------------------------\n//\n// The native backing store is represented by three different classes:\n// * `__RawDictionaryStorage`\n// * `__EmptyDictionarySingleton` (extends Raw)\n// * `_DictionaryStorage<K: Hashable, V>` (extends Raw)\n//\n// (Hereafter `Raw`, `Empty`, and `Storage`, respectively)\n//\n// In a less optimized implementation, `Raw` and `Empty` could be eliminated, as\n// they exist only to provide special-case behaviors.\n//\n// `Empty` is the a type-punned empty singleton storage. Its single instance is\n// created by the runtime during process startup. Because we use the same\n// instance for all empty dictionaries, it cannot declare type parameters.\n//\n// `Storage` provides backing storage for regular native dictionaries. All\n// non-empty native dictionaries use an instance of `Storage` to store their\n// elements. `Storage` is a generic class with a nontrivial deinit.\n//\n// `Raw` is the base class for both `Empty` and `Storage`. It defines a full set\n// of ivars to access dictionary contents. Like `Empty`, `Raw` is also\n// non-generic; the base addresses it stores are represented by untyped raw\n// pointers. The only reason `Raw` exists is to allow `_NativeDictionary` to\n// treat `Empty` and `Storage` in a unified way.\n//\n// Storage classes don't contain much logic; `Raw` in particular is just a\n// collection of ivars. `Storage` provides allocation/deinitialization logic,\n// while `Empty`/`Storage` implement NSDictionary methods. All other operations\n// are actually implemented by the `_NativeDictionary` and `_HashTable` structs.\n//\n// The `_HashTable` struct provides low-level hash table metadata operations.\n// (Lookups, iteration, insertion, removal.) It owns and maintains the\n// tail-allocated bitmap.\n//\n// `_NativeDictionary` implements the actual Dictionary operations. It\n// consists of a reference to a `Raw` instance, to allow for the possibility of\n// the empty singleton.\n//\n//\n// Index Invalidation\n// ------------------\n//\n// FIXME: decide if this guarantee is worth making, as it restricts\n// collision resolution to first-come-first-serve. The most obvious alternative\n// would be robin hood hashing. The Rust code base is the best\n// resource on a *practical* implementation of robin hood hashing I know of:\n// https://github.com/rust-lang/rust/blob/ac919fcd9d4a958baf99b2f2ed5c3d38a2ebf9d0/src/libstd/collections/hash/map.rs#L70-L178\n//\n// Indexing a container, `c[i]`, uses the integral offset stored in the index\n// to access the elements referenced by the container. Generally, an index into\n// one container has no meaning for another. However copy-on-write currently\n// preserves indices under insertion, as long as reallocation doesn't occur:\n//\n// var (i, found) = d.find(k) // i is associated with d's storage\n// if found {\n// var e = d // now d is sharing its data with e\n// e[newKey] = newValue // e now has a unique copy of the data\n// return e[i] // use i to access e\n// }\n//\n// The result should be a set of iterator invalidation rules familiar to anyone\n// familiar with the C++ standard library. Note that because all accesses to a\n// dictionary storage are bounds-checked, this scheme never compromises memory\n// safety.\n//\n// As a safeguard against using invalid indices, Set and Dictionary maintain a\n// mutation counter in their storage header (`_age`). This counter gets bumped\n// every time an element is removed and whenever the contents are\n// rehashed. Native indices include a copy of this counter so that index\n// validation can verify it matches with current storage. This can't catch all\n// misuse, because counters may match by accident; but it does make indexing a\n// lot more reliable.\n//\n// Bridging\n// ========\n//\n// Bridging `NSDictionary` to `Dictionary`\n// ---------------------------------------\n//\n// FIXME(eager-bridging): rewrite this based on modern constraints.\n//\n// `NSDictionary` bridges to `Dictionary<NSObject, AnyObject>` in `O(1)`,\n// without memory allocation.\n//\n// Bridging to `Dictionary<AnyHashable, AnyObject>` takes `O(n)` time, as the\n// keys need to be fully rehashed after conversion to `AnyHashable`.\n//\n// Bridging `NSDictionary` to `Dictionary<Key, Value>` is O(1) if both Key and\n// Value are bridged verbatim.\n//\n// Bridging `Dictionary` to `NSDictionary`\n// ---------------------------------------\n//\n// `Dictionary<K, V>` bridges to `NSDictionary` in O(1)\n// but may incur an allocation depending on the following conditions:\n//\n// * If the Dictionary is freshly allocated without any elements, then it\n// contains the empty singleton Storage which is returned as a toll-free\n// implementation of `NSDictionary`.\n//\n// * If both `K` and `V` are bridged verbatim, then `Dictionary<K, V>` is\n// still toll-free bridged to `NSDictionary` by returning its Storage.\n//\n// * If the Dictionary is actually a lazily bridged NSDictionary, then that\n// NSDictionary is returned.\n//\n// * Otherwise, bridging the `Dictionary` is done by wrapping it in a\n// `_SwiftDeferredNSDictionary<K, V>`. This incurs an O(1)-sized allocation.\n//\n// Complete bridging of the native Storage's elements to another Storage\n// is performed on first access. This is O(n) work, but is hopefully amortized\n// by future accesses.\n//\n// This design ensures that:\n// - Every time keys or values are accessed on the bridged `NSDictionary`,\n// new objects are not created.\n// - Accessing the same element (key or value) multiple times will return\n// the same pointer.\n//\n// Bridging `NSSet` to `Set` and vice versa\n// ----------------------------------------\n//\n// Bridging guarantees for `Set<Element>` are the same as for\n// `Dictionary<Element, NSObject>`.\n//\n\n/// A collection whose elements are key-value pairs.\n///\n/// A dictionary is a type of hash table, providing fast access to the entries\n/// it contains. Each entry in the table is identified using its key, which is\n/// a hashable type such as a string or number. You use that key to retrieve\n/// the corresponding value, which can be any object. In other languages,\n/// similar data types are known as hashes or associated arrays.\n///\n/// Create a new dictionary by using a dictionary literal. A dictionary literal\n/// is a comma-separated list of key-value pairs, in which a colon separates\n/// each key from its associated value, surrounded by square brackets. You can\n/// assign a dictionary literal to a variable or constant or pass it to a\n/// function that expects a dictionary.\n///\n/// Here's how you would create a dictionary of HTTP response codes and their\n/// related messages:\n///\n/// var responseMessages = [200: "OK",\n/// 403: "Access forbidden",\n/// 404: "File not found",\n/// 500: "Internal server error"]\n///\n/// The `responseMessages` variable is inferred to have type `[Int: String]`.\n/// The `Key` type of the dictionary is `Int`, and the `Value` type of the\n/// dictionary is `String`.\n///\n/// To create a dictionary with no key-value pairs, use an empty dictionary\n/// literal (`[:]`).\n///\n/// var emptyDict: [String: String] = [:]\n///\n/// Any type that conforms to the `Hashable` protocol can be used as a\n/// dictionary's `Key` type, including all of Swift's basic types. You can use\n/// your own custom types as dictionary keys by making them conform to the\n/// `Hashable` protocol.\n///\n/// Getting and Setting Dictionary Values\n/// =====================================\n///\n/// The most common way to access values in a dictionary is to use a key as a\n/// subscript. Subscripting with a key takes the following form:\n///\n/// print(responseMessages[200])\n/// // Prints "Optional("OK")"\n///\n/// Subscripting a dictionary with a key returns an optional value, because a\n/// dictionary might not hold a value for the key that you use in the\n/// subscript.\n///\n/// The next example uses key-based subscripting of the `responseMessages`\n/// dictionary with two keys that exist in the dictionary and one that does\n/// not.\n///\n/// let httpResponseCodes = [200, 403, 301]\n/// for code in httpResponseCodes {\n/// if let message = responseMessages[code] {\n/// print("Response \(code): \(message)")\n/// } else {\n/// print("Unknown response \(code)")\n/// }\n/// }\n/// // Prints "Response 200: OK"\n/// // Prints "Response 403: Access forbidden"\n/// // Prints "Unknown response 301"\n///\n/// You can also update, modify, or remove keys and values from a dictionary\n/// using the key-based subscript. To add a new key-value pair, assign a value\n/// to a key that isn't yet a part of the dictionary.\n///\n/// responseMessages[301] = "Moved permanently"\n/// print(responseMessages[301])\n/// // Prints "Optional("Moved permanently")"\n///\n/// Update an existing value by assigning a new value to a key that already\n/// exists in the dictionary. If you assign `nil` to an existing key, the key\n/// and its associated value are removed. The following example updates the\n/// value for the `404` code to be simply "Not found" and removes the\n/// key-value pair for the `500` code entirely.\n///\n/// responseMessages[404] = "Not found"\n/// responseMessages[500] = nil\n/// print(responseMessages)\n/// // Prints "[301: "Moved permanently", 200: "OK", 403: "Access forbidden", 404: "Not found"]"\n///\n/// In a mutable `Dictionary` instance, you can modify in place a value that\n/// you've accessed through a keyed subscript. The code sample below declares a\n/// dictionary called `interestingNumbers` with string keys and values that\n/// are integer arrays, then sorts each array in-place in descending order.\n///\n/// var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 17],\n/// "triangular": [1, 3, 6, 10, 15, 21, 28],\n/// "hexagonal": [1, 6, 15, 28, 45, 66, 91]]\n/// for key in interestingNumbers.keys {\n/// interestingNumbers[key]?.sort(by: >)\n/// }\n///\n/// print(interestingNumbers["primes"]!)\n/// // Prints "[17, 13, 11, 7, 5, 3, 2]"\n///\n/// Iterating Over the Contents of a Dictionary\n/// ===========================================\n///\n/// Every dictionary is an unordered collection of key-value pairs. You can\n/// iterate over a dictionary using a `for`-`in` loop, decomposing each\n/// key-value pair into the elements of a tuple.\n///\n/// let imagePaths = ["star": "/glyphs/star.png",\n/// "portrait": "/images/content/portrait.jpg",\n/// "spacer": "/images/shared/spacer.gif"]\n///\n/// for (name, path) in imagePaths {\n/// print("The path to '\(name)' is '\(path)'.")\n/// }\n/// // Prints "The path to 'star' is '/glyphs/star.png'."\n/// // Prints "The path to 'portrait' is '/images/content/portrait.jpg'."\n/// // Prints "The path to 'spacer' is '/images/shared/spacer.gif'."\n///\n/// The order of key-value pairs in a dictionary is stable between mutations\n/// but is otherwise unpredictable. If you need an ordered collection of\n/// key-value pairs and don't need the fast key lookup that `Dictionary`\n/// provides, see the `KeyValuePairs` type for an alternative.\n///\n/// You can search a dictionary's contents for a particular value using the\n/// `contains(where:)` or `firstIndex(where:)` methods supplied by default\n/// implementation. The following example checks to see if `imagePaths` contains\n/// any paths in the `"/glyphs"` directory:\n///\n/// let glyphIndex = imagePaths.firstIndex(where: { $0.value.hasPrefix("/glyphs") })\n/// if let index = glyphIndex {\n/// print("The '\(imagePaths[index].key)' image is a glyph.")\n/// } else {\n/// print("No glyphs found!")\n/// }\n/// // Prints "The 'star' image is a glyph."\n///\n/// Note that in this example, `imagePaths` is subscripted using a dictionary\n/// index. Unlike the key-based subscript, the index-based subscript returns\n/// the corresponding key-value pair as a non-optional tuple.\n///\n/// print(imagePaths[glyphIndex!])\n/// // Prints "(key: "star", value: "/glyphs/star.png")"\n///\n/// A dictionary's indices stay valid across additions to the dictionary as\n/// long as the dictionary has enough capacity to store the added values\n/// without allocating more buffer. When a dictionary outgrows its buffer,\n/// existing indices may be invalidated without any notification.\n///\n/// When you know how many new values you're adding to a dictionary, use the\n/// `init(minimumCapacity:)` initializer to allocate the correct amount of\n/// buffer.\n///\n/// Bridging Between Dictionary and NSDictionary\n/// ============================================\n///\n/// You can bridge between `Dictionary` and `NSDictionary` using the `as`\n/// operator. For bridging to be possible, the `Key` and `Value` types of a\n/// dictionary must be classes, `@objc` protocols, or types that bridge to\n/// Foundation types.\n///\n/// Bridging from `Dictionary` to `NSDictionary` always takes O(1) time and\n/// space. When the dictionary's `Key` and `Value` types are neither classes\n/// nor `@objc` protocols, any required bridging of elements occurs at the\n/// first access of each element. For this reason, the first operation that\n/// uses the contents of the dictionary may take O(*n*).\n///\n/// Bridging from `NSDictionary` to `Dictionary` first calls the `copy(with:)`\n/// method (`- copyWithZone:` in Objective-C) on the dictionary to get an\n/// immutable copy and then performs additional Swift bookkeeping work that\n/// takes O(1) time. For instances of `NSDictionary` that are already\n/// immutable, `copy(with:)` usually returns the same dictionary in O(1) time;\n/// otherwise, the copying performance is unspecified. The instances of\n/// `NSDictionary` and `Dictionary` share buffer using the same copy-on-write\n/// optimization that is used when two instances of `Dictionary` share\n/// buffer.\n@frozen\n@_eagerMove\npublic struct Dictionary<Key: Hashable, Value> {\n /// The element type of a dictionary: a tuple containing an individual\n /// key-value pair.\n public typealias Element = (key: Key, value: Value)\n\n @usableFromInline\n internal var _variant: _Variant\n\n @inlinable\n internal init(_native: __owned _NativeDictionary<Key, Value>) {\n _variant = _Variant(native: _native)\n }\n\n#if _runtime(_ObjC)\n @inlinable\n internal init(_cocoa: __owned __CocoaDictionary) {\n _variant = _Variant(cocoa: _cocoa)\n }\n\n /// Private initializer used for bridging.\n ///\n /// Only use this initializer when both conditions are true:\n ///\n /// * it is statically known that the given `NSDictionary` is immutable;\n /// * `Key` and `Value` are bridged verbatim to Objective-C (i.e.,\n /// are reference types).\n @inlinable\n public // SPI(Foundation)\n init(_immutableCocoaDictionary: __owned AnyObject) {\n _internalInvariant(\n _isBridgedVerbatimToObjectiveC(Key.self) &&\n _isBridgedVerbatimToObjectiveC(Value.self),\n """\n Dictionary can be backed by NSDictionary buffer only when both Key \\n and Value are bridged verbatim to Objective-C\n """)\n self.init(_cocoa: __CocoaDictionary(_immutableCocoaDictionary))\n }\n#endif\n\n /// Creates an empty dictionary.\n @inlinable\n public init() {\n self.init(_native: _NativeDictionary())\n }\n\n /// Creates an empty dictionary with preallocated space for at least the\n /// specified number of elements.\n ///\n /// Use this initializer to avoid intermediate reallocations of a dictionary's\n /// storage buffer when you know how many key-value pairs you are adding to a\n /// dictionary after creation.\n ///\n /// - Parameter minimumCapacity: The minimum number of key-value pairs that\n /// the newly created dictionary should be able to store without\n /// reallocating its storage buffer.\n public // FIXME(reserveCapacity): Should be inlinable\n init(minimumCapacity: Int) {\n _variant = _Variant(native: _NativeDictionary(capacity: minimumCapacity))\n }\n\n /// Creates a new dictionary from the key-value pairs in the given sequence.\n ///\n /// You use this initializer to create a dictionary when you have a sequence\n /// of key-value tuples with unique keys. Passing a sequence with duplicate\n /// keys to this initializer results in a runtime error. If your\n /// sequence might have duplicate keys, use the\n /// `Dictionary(_:uniquingKeysWith:)` initializer instead.\n ///\n /// The following example creates a new dictionary using an array of strings\n /// as the keys and the integers in a countable range as the values:\n ///\n /// let digitWords = ["one", "two", "three", "four", "five"]\n /// let wordToValue = Dictionary(uniqueKeysWithValues: zip(digitWords, 1...5))\n /// print(wordToValue["three"]!)\n /// // Prints "3"\n /// print(wordToValue)\n /// // Prints "["three": 3, "four": 4, "five": 5, "one": 1, "two": 2]"\n ///\n /// - Parameter keysAndValues: A sequence of key-value pairs to use for\n /// the new dictionary. Every key in `keysAndValues` must be unique.\n /// - Returns: A new dictionary initialized with the elements of\n /// `keysAndValues`.\n /// - Precondition: The sequence must not have duplicate keys.\n @inlinable\n public init<S: Sequence>(\n uniqueKeysWithValues keysAndValues: __owned S\n ) where S.Element == (Key, Value) {\n if let d = keysAndValues as? Dictionary<Key, Value> {\n self = d\n return\n }\n var native = _NativeDictionary<Key, Value>(\n capacity: keysAndValues.underestimatedCount)\n // '_MergeError.keyCollision' is caught and handled with an appropriate\n // error message one level down, inside native.merge(_:...). We throw an\n // error instead of calling fatalError() directly because we want the\n // message to include the duplicate key, and the closure only has access to\n // the conflicting values.\n #if !$Embedded\n try! native.merge(\n keysAndValues,\n isUnique: true,\n uniquingKeysWith: { _, _ in throw _MergeError.keyCollision })\n #else\n native.merge(\n keysAndValues,\n isUnique: true,\n uniquingKeysWith: { _, _ throws(_MergeError) in\n throw _MergeError.keyCollision\n }\n )\n #endif\n self.init(_native: native)\n }\n\n /// Creates a new dictionary from the key-value pairs in the given sequence,\n /// using a combining closure to determine the value for any duplicate keys.\n ///\n /// You use this initializer to create a dictionary when you have a sequence\n /// of key-value tuples that might have duplicate keys. As the dictionary is\n /// built, the initializer calls the `combine` closure with the current and\n /// new values for any duplicate keys. Pass a closure as `combine` that\n /// returns the value to use in the resulting dictionary: The closure can\n /// choose between the two values, combine them to produce a new value, or\n /// even throw an error.\n ///\n /// The following example shows how to choose the first and last values for\n /// any duplicate keys:\n ///\n /// let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]\n ///\n /// let firstValues = Dictionary(pairsWithDuplicateKeys,\n /// uniquingKeysWith: { (first, _) in first })\n /// // ["b": 2, "a": 1]\n ///\n /// let lastValues = Dictionary(pairsWithDuplicateKeys,\n /// uniquingKeysWith: { (_, last) in last })\n /// // ["b": 4, "a": 3]\n ///\n /// - Parameters:\n /// - keysAndValues: A sequence of key-value pairs to use for the new\n /// dictionary.\n /// - combine: A closure that is called with the values for any duplicate\n /// keys that are encountered. The closure returns the desired value for\n /// the final dictionary.\n @inlinable\n public init<S: Sequence>(\n _ keysAndValues: __owned S,\n uniquingKeysWith combine: (Value, Value) throws -> Value\n ) rethrows where S.Element == (Key, Value) {\n var native = _NativeDictionary<Key, Value>(\n capacity: keysAndValues.underestimatedCount)\n try native.merge(keysAndValues, isUnique: true, uniquingKeysWith: combine)\n self.init(_native: native)\n }\n\n /// Creates a new dictionary whose keys are the groupings returned by the\n /// given closure and whose values are arrays of the elements that returned\n /// each key.\n ///\n /// The arrays in the "values" position of the new dictionary each contain at\n /// least one element, with the elements in the same order as the source\n /// sequence.\n ///\n /// The following example declares an array of names, and then creates a\n /// dictionary from that array by grouping the names by first letter:\n ///\n /// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]\n /// let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })\n /// // ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]]\n ///\n /// The new `studentsByLetter` dictionary has three entries, with students'\n /// names grouped by the keys `"E"`, `"K"`, and `"A"`.\n ///\n /// - Parameters:\n /// - values: A sequence of values to group into a dictionary.\n /// - keyForValue: A closure that returns a key for each element in\n /// `values`.\n @inlinable\n public init<S: Sequence>(\n grouping values: __owned S,\n by keyForValue: (S.Element) throws -> Key\n ) rethrows where Value == [S.Element] {\n try self.init(_native: _NativeDictionary(grouping: values, by: keyForValue))\n }\n}\n\n//\n// All APIs below should dispatch to `_variant`, without doing any\n// additional processing.\n//\n\nextension Dictionary: Sequence {\n /// Returns an iterator over the dictionary's key-value pairs.\n ///\n /// Iterating over a dictionary yields the key-value pairs as two-element\n /// tuples. You can decompose the tuple in a `for`-`in` loop, which calls\n /// `makeIterator()` behind the scenes, or when calling the iterator's\n /// `next()` method directly.\n ///\n /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]\n /// for (name, hueValue) in hues {\n /// print("The hue of \(name) is \(hueValue).")\n /// }\n /// // Prints "The hue of Heliotrope is 296."\n /// // Prints "The hue of Coral is 16."\n /// // Prints "The hue of Aquamarine is 156."\n ///\n /// - Returns: An iterator over the dictionary with elements of type\n /// `(key: Key, value: Value)`.\n @inlinable\n @inline(__always)\n public __consuming func makeIterator() -> Iterator {\n return _variant.makeIterator()\n }\n}\n\n// This is not quite Sequence.filter, because that returns [Element], not Self\nextension Dictionary {\n /// Returns a new dictionary containing the key-value pairs of the dictionary\n /// that satisfy the given predicate.\n ///\n /// - Parameter isIncluded: A closure that takes a key-value pair as its\n /// argument and returns a Boolean value indicating whether the pair\n /// should be included in the returned dictionary.\n /// - Returns: A dictionary of the key-value pairs that `isIncluded` allows.\n @inlinable\n @available(swift, introduced: 4.0)\n public __consuming func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Key: Value] {\n #if _runtime(_ObjC)\n guard _variant.isNative else {\n // Slow path for bridged dictionaries\n var result = _NativeDictionary<Key, Value>()\n for element in self {\n if try isIncluded(element) {\n result.insertNew(key: element.key, value: element.value)\n }\n }\n return Dictionary(_native: result)\n }\n #endif\n return Dictionary(_native: try _variant.asNative.filter(isIncluded))\n }\n}\n\nextension Dictionary: Collection {\n public typealias SubSequence = Slice<Dictionary>\n \n /// The position of the first element in a nonempty dictionary.\n ///\n /// If the collection is empty, `startIndex` is equal to `endIndex`.\n ///\n /// - Complexity: Amortized O(1) if the dictionary does not wrap a bridged\n /// `NSDictionary`. If the dictionary wraps a bridged `NSDictionary`, the\n /// performance is unspecified.\n @inlinable\n public var startIndex: Index {\n return _variant.startIndex\n }\n\n /// The dictionary's "past the end" position---that is, the position one\n /// greater than the last valid subscript argument.\n ///\n /// If the collection is empty, `endIndex` is equal to `startIndex`.\n ///\n /// - Complexity: Amortized O(1) if the dictionary does not wrap a bridged\n /// `NSDictionary`; otherwise, the performance is unspecified.\n @inlinable\n public var endIndex: Index {\n return _variant.endIndex\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n return _variant.index(after: i)\n }\n\n @inlinable\n public func formIndex(after i: inout Index) {\n _variant.formIndex(after: &i)\n }\n\n /// Returns the index for the given key.\n ///\n /// If the given key is found in the dictionary, this method returns an index\n /// into the dictionary that corresponds with the key-value pair.\n ///\n /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]\n /// let index = countryCodes.index(forKey: "JP")\n ///\n /// print("Country code for \(countryCodes[index!].value): '\(countryCodes[index!].key)'.")\n /// // Prints "Country code for Japan: 'JP'."\n ///\n /// - Parameter key: The key to find in the dictionary.\n /// - Returns: The index for `key` and its associated value if `key` is in\n /// the dictionary; otherwise, `nil`.\n @inlinable\n @inline(__always)\n public func index(forKey key: Key) -> Index? {\n // Complexity: amortized O(1) for native dictionary, O(*n*) when wrapping an\n // NSDictionary.\n return _variant.index(forKey: key)\n }\n\n /// Accesses the key-value pair at the specified position.\n ///\n /// This subscript takes an index into the dictionary, instead of a key, and\n /// returns the corresponding key-value pair as a tuple. When performing\n /// collection-based operations that return an index into a dictionary, use\n /// this subscript with the resulting value.\n ///\n /// For example, to find the key for a particular value in a dictionary, use\n /// the `firstIndex(where:)` method.\n ///\n /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]\n /// if let index = countryCodes.firstIndex(where: { $0.value == "Japan" }) {\n /// print(countryCodes[index])\n /// print("Japan's country code is '\(countryCodes[index].key)'.")\n /// } else {\n /// print("Didn't find 'Japan' as a value in the dictionary.")\n /// }\n /// // Prints "(key: "JP", value: "Japan")"\n /// // Prints "Japan's country code is 'JP'."\n ///\n /// - Parameter position: The position of the key-value pair to access.\n /// `position` must be a valid index of the dictionary and not equal to\n /// `endIndex`.\n /// - Returns: A two-element tuple with the key and value corresponding to\n /// `position`.\n @inlinable\n public subscript(position: Index) -> Element {\n return _variant.lookup(position)\n }\n\n /// The number of key-value pairs in the dictionary.\n ///\n /// - Complexity: O(1).\n @inlinable\n public var count: Int {\n return _variant.count\n }\n\n //\n // `Sequence` conformance\n //\n\n /// A Boolean value that indicates whether the dictionary is empty.\n ///\n /// Dictionaries are empty when created with an initializer or an empty\n /// dictionary literal.\n ///\n /// var frequencies: [String: Int] = [:]\n /// print(frequencies.isEmpty)\n /// // Prints "true"\n @inlinable\n public var isEmpty: Bool {\n return count == 0\n }\n}\n\nextension Dictionary {\n /// Accesses the value associated with the given key for reading and writing.\n ///\n /// This *key-based* subscript returns the value for the given key if the key\n /// is found in the dictionary, or `nil` if the key is not found.\n ///\n /// The following example creates a new dictionary and prints the value of a\n /// key found in the dictionary (`"Coral"`) and a key not found in the\n /// dictionary (`"Cerise"`).\n ///\n /// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]\n /// print(hues["Coral"])\n /// // Prints "Optional(16)"\n /// print(hues["Cerise"])\n /// // Prints "nil"\n ///\n /// When you assign a value for a key and that key already exists, the\n /// dictionary overwrites the existing value. If the dictionary doesn't\n /// contain the key, the key and value are added as a new key-value pair.\n ///\n /// Here, the value for the key `"Coral"` is updated from `16` to `18` and a\n /// new key-value pair is added for the key `"Cerise"`.\n ///\n /// hues["Coral"] = 18\n /// print(hues["Coral"])\n /// // Prints "Optional(18)"\n ///\n /// hues["Cerise"] = 330\n /// print(hues["Cerise"])\n /// // Prints "Optional(330)"\n ///\n /// If you assign `nil` as the value for the given key, the dictionary\n /// removes that key and its associated value.\n ///\n /// In the following example, the key-value pair for the key `"Aquamarine"`\n /// is removed from the dictionary by assigning `nil` to the key-based\n /// subscript.\n ///\n /// hues["Aquamarine"] = nil\n /// print(hues)\n /// // Prints "["Coral": 18, "Heliotrope": 296, "Cerise": 330]"\n ///\n /// - Parameter key: The key to find in the dictionary.\n /// - Returns: The value associated with `key` if `key` is in the dictionary;\n /// otherwise, `nil`.\n @inlinable\n public subscript(key: Key) -> Value? {\n get {\n return _variant.lookup(key)\n }\n set(newValue) {\n if let x = newValue {\n _variant.setValue(x, forKey: key)\n } else {\n removeValue(forKey: key)\n }\n }\n _modify {\n defer { _fixLifetime(self) }\n yield &_variant[key]\n }\n }\n}\n\nextension Dictionary: ExpressibleByDictionaryLiteral {\n /// Creates a dictionary initialized with a dictionary literal.\n ///\n /// Do not call this initializer directly. It is called by the compiler to\n /// handle dictionary literals. To use a dictionary literal as the initial\n /// value of a dictionary, enclose a comma-separated list of key-value pairs\n /// in square brackets.\n ///\n /// For example, the code sample below creates a dictionary with string keys\n /// and values.\n ///\n /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]\n /// print(countryCodes)\n /// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"\n ///\n /// - Parameter elements: The key-value pairs that will make up the new\n /// dictionary. Each key in `elements` must be unique.\n @inlinable\n @_semantics("optimize.sil.specialize.generic.size.never")\n public init(dictionaryLiteral elements: (Key, Value)...) {\n let native = _NativeDictionary<Key, Value>(capacity: elements.count)\n for (key, value) in elements {\n let (bucket, found) = native.find(key)\n _precondition(!found, "Dictionary literal contains duplicate keys")\n native._insert(at: bucket, key: key, value: value)\n }\n self.init(_native: native)\n }\n}\n\nextension Dictionary {\n /// Accesses the value with the given key, falling back to the given default\n /// value if the key isn't found.\n ///\n /// Use this subscript when you want either the value for a particular key\n /// or, when that key is not present in the dictionary, a default value. This\n /// example uses the subscript with a message to use in case an HTTP response\n /// code isn't recognized:\n ///\n /// var responseMessages = [200: "OK",\n /// 403: "Access forbidden",\n /// 404: "File not found",\n /// 500: "Internal server error"]\n ///\n /// let httpResponseCodes = [200, 403, 301]\n /// for code in httpResponseCodes {\n /// let message = responseMessages[code, default: "Unknown response"]\n /// print("Response \(code): \(message)")\n /// }\n /// // Prints "Response 200: OK"\n /// // Prints "Response 403: Access forbidden"\n /// // Prints "Response 301: Unknown response"\n ///\n /// When a dictionary's `Value` type has value semantics, you can use this\n /// subscript to perform in-place operations on values in the dictionary.\n /// The following example uses this subscript while counting the occurrences\n /// of each letter in a string:\n ///\n /// let message = "Hello, Elle!"\n /// var letterCounts: [Character: Int] = [:]\n /// for letter in message {\n /// letterCounts[letter, default: 0] += 1\n /// }\n /// // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...]\n ///\n /// When `letterCounts[letter, default: 0] += 1` is executed with a\n /// value of `letter` that isn't already a key in `letterCounts`, the\n /// specified default value (`0`) is returned from the subscript,\n /// incremented, and then added to the dictionary under that key.\n ///\n /// - Note: Do not use this subscript to modify dictionary values if the\n /// dictionary's `Value` type is a class. In that case, the default value\n /// and key are not written back to the dictionary after an operation.\n ///\n /// - Parameters:\n /// - key: The key the look up in the dictionary.\n /// - defaultValue: The default value to use if `key` doesn't exist in the\n /// dictionary.\n /// - Returns: The value associated with `key` in the dictionary; otherwise,\n /// `defaultValue`.\n @inlinable\n public subscript(\n key: Key, default defaultValue: @autoclosure () -> Value\n ) -> Value {\n @inline(__always)\n get {\n return _variant.lookup(key) ?? defaultValue()\n }\n @inline(__always)\n _modify {\n let (bucket, found) = _variant.mutatingFind(key)\n let native = _variant.asNative\n if !found {\n let value = defaultValue()\n native._insert(at: bucket, key: key, value: value)\n }\n let address = unsafe native._values + bucket.offset\n defer { _fixLifetime(self) }\n yield unsafe &address.pointee\n }\n }\n\n /// Returns a new dictionary containing the keys of this dictionary with the\n /// values transformed by the given closure.\n ///\n /// - Parameter transform: A closure that transforms a value. `transform`\n /// accepts each value of the dictionary as its parameter and returns a\n /// transformed value of the same or of a different type.\n /// - Returns: A dictionary containing the keys and transformed values of\n /// this dictionary.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the dictionary.\n @inlinable\n public func mapValues<T>(\n _ transform: (Value) throws -> T\n ) rethrows -> Dictionary<Key, T> {\n return try Dictionary<Key, T>(_native: _variant.mapValues(transform))\n }\n\n /// Returns a new dictionary containing only the key-value pairs that have\n /// non-`nil` values as the result of transformation by the given closure.\n ///\n /// Use this method to receive a dictionary with non-optional values when\n /// your transformation produces optional values.\n ///\n /// In this example, note the difference in the result of using `mapValues`\n /// and `compactMapValues` with a transformation that returns an optional\n /// `Int` value.\n ///\n /// let data = ["a": "1", "b": "three", "c": "///4///"]\n ///\n /// let m: [String: Int?] = data.mapValues { str in Int(str) }\n /// // ["a": Optional(1), "b": nil, "c": nil]\n ///\n /// let c: [String: Int] = data.compactMapValues { str in Int(str) }\n /// // ["a": 1]\n ///\n /// - Parameter transform: A closure that transforms a value. `transform`\n /// accepts each value of the dictionary as its parameter and returns an\n /// optional transformed value of the same or of a different type.\n /// - Returns: A dictionary containing the keys and non-`nil` transformed\n /// values of this dictionary.\n ///\n /// - Complexity: O(*m* + *n*), where *n* is the length of the original\n /// dictionary and *m* is the length of the resulting dictionary.\n @inlinable\n public func compactMapValues<T>(\n _ transform: (Value) throws -> T?\n ) rethrows -> Dictionary<Key, T> {\n let result: _NativeDictionary<Key, T> =\n try self.reduce(into: _NativeDictionary<Key, T>()) { (result, element) in\n if let value = try transform(element.value) {\n result.insertNew(key: element.key, value: value)\n }\n }\n return Dictionary<Key, T>(_native: result)\n }\n\n /// Updates the value stored in the dictionary for the given key, or adds a\n /// new key-value pair if the key does not exist.\n ///\n /// Use this method instead of key-based subscripting when you need to know\n /// whether the new value supplants the value of an existing key. If the\n /// value of an existing key is updated, `updateValue(_:forKey:)` returns\n /// the original value.\n ///\n /// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]\n ///\n /// if let oldValue = hues.updateValue(18, forKey: "Coral") {\n /// print("The old value of \(oldValue) was replaced with a new one.")\n /// }\n /// // Prints "The old value of 16 was replaced with a new one."\n ///\n /// If the given key is not present in the dictionary, this method adds the\n /// key-value pair and returns `nil`.\n ///\n /// if let oldValue = hues.updateValue(330, forKey: "Cerise") {\n /// print("The old value of \(oldValue) was replaced with a new one.")\n /// } else {\n /// print("No value was found in the dictionary for that key.")\n /// }\n /// // Prints "No value was found in the dictionary for that key."\n ///\n /// - Parameters:\n /// - value: The new value to add to the dictionary.\n /// - key: The key to associate with `value`. If `key` already exists in\n /// the dictionary, `value` replaces the existing associated value. If\n /// `key` isn't already a key of the dictionary, the `(key, value)` pair\n /// is added.\n /// - Returns: The value that was replaced, or `nil` if a new key-value pair\n /// was added.\n @inlinable\n @discardableResult\n public mutating func updateValue(\n _ value: __owned Value,\n forKey key: Key\n ) -> Value? {\n return _variant.updateValue(value, forKey: key)\n }\n\n /// Merges the key-value pairs in the given sequence into the dictionary,\n /// using a combining closure to determine the value for any duplicate keys.\n ///\n /// Use the `combine` closure to select a value to use in the updated\n /// dictionary, or to combine existing and new values. As the key-value\n /// pairs are merged with the dictionary, the `combine` closure is called\n /// with the current and new values for any duplicate keys that are\n /// encountered.\n ///\n /// This example shows how to choose the current or new values for any\n /// duplicate keys:\n ///\n /// var dictionary = ["a": 1, "b": 2]\n ///\n /// // Keeping existing value for key "a":\n /// dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current }\n /// // ["b": 2, "a": 1, "c": 4]\n ///\n /// // Taking the new value for key "a":\n /// dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new }\n /// // ["b": 2, "a": 5, "c": 4, "d": 6]\n ///\n /// - Parameters:\n /// - other: A sequence of key-value pairs.\n /// - combine: A closure that takes the current and new values for any\n /// duplicate keys. The closure returns the desired value for the final\n /// dictionary.\n @inlinable\n public mutating func merge<S: Sequence>(\n _ other: __owned S,\n uniquingKeysWith combine: (Value, Value) throws -> Value\n ) rethrows where S.Element == (Key, Value) {\n try _variant.merge(other, uniquingKeysWith: combine)\n }\n\n /// Merges the given dictionary into this dictionary, using a combining\n /// closure to determine the value for any duplicate keys.\n ///\n /// Use the `combine` closure to select a value to use in the updated\n /// dictionary, or to combine existing and new values. As the key-values\n /// pairs in `other` are merged with this dictionary, the `combine` closure\n /// is called with the current and new values for any duplicate keys that\n /// are encountered.\n ///\n /// This example shows how to choose the current or new values for any\n /// duplicate keys:\n ///\n /// var dictionary = ["a": 1, "b": 2]\n ///\n /// // Keeping existing value for key "a":\n /// dictionary.merge(["a": 3, "c": 4]) { (current, _) in current }\n /// // ["b": 2, "a": 1, "c": 4]\n ///\n /// // Taking the new value for key "a":\n /// dictionary.merge(["a": 5, "d": 6]) { (_, new) in new }\n /// // ["b": 2, "a": 5, "c": 4, "d": 6]\n ///\n /// - Parameters:\n /// - other: A dictionary to merge.\n /// - combine: A closure that takes the current and new values for any\n /// duplicate keys. The closure returns the desired value for the final\n /// dictionary.\n @inlinable\n public mutating func merge(\n _ other: __owned [Key: Value],\n uniquingKeysWith combine: (Value, Value) throws -> Value\n ) rethrows {\n try _variant.merge(\n other.lazy.map { ($0, $1) }, uniquingKeysWith: combine)\n }\n\n /// Creates a dictionary by merging key-value pairs in a sequence into the\n /// dictionary, using a combining closure to determine the value for\n /// duplicate keys.\n ///\n /// Use the `combine` closure to select a value to use in the returned\n /// dictionary, or to combine existing and new values. As the key-value\n /// pairs are merged with the dictionary, the `combine` closure is called\n /// with the current and new values for any duplicate keys that are\n /// encountered.\n ///\n /// This example shows how to choose the current or new values for any\n /// duplicate keys:\n ///\n /// let dictionary = ["a": 1, "b": 2]\n /// let newKeyValues = zip(["a", "b"], [3, 4])\n ///\n /// let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }\n /// // ["b": 2, "a": 1]\n /// let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }\n /// // ["b": 4, "a": 3]\n ///\n /// - Parameters:\n /// - other: A sequence of key-value pairs.\n /// - combine: A closure that takes the current and new values for any\n /// duplicate keys. The closure returns the desired value for the final\n /// dictionary.\n /// - Returns: A new dictionary with the combined keys and values of this\n /// dictionary and `other`.\n @inlinable\n public __consuming func merging<S: Sequence>(\n _ other: __owned S,\n uniquingKeysWith combine: (Value, Value) throws -> Value\n ) rethrows -> [Key: Value] where S.Element == (Key, Value) {\n var result = self\n try result._variant.merge(other, uniquingKeysWith: combine)\n return result\n }\n\n /// Creates a dictionary by merging the given dictionary into this\n /// dictionary, using a combining closure to determine the value for\n /// duplicate keys.\n ///\n /// Use the `combine` closure to select a value to use in the returned\n /// dictionary, or to combine existing and new values. As the key-value\n /// pairs in `other` are merged with this dictionary, the `combine` closure\n /// is called with the current and new values for any duplicate keys that\n /// are encountered.\n ///\n /// This example shows how to choose the current or new values for any\n /// duplicate keys:\n ///\n /// let dictionary = ["a": 1, "b": 2]\n /// let otherDictionary = ["a": 3, "b": 4]\n ///\n /// let keepingCurrent = dictionary.merging(otherDictionary)\n /// { (current, _) in current }\n /// // ["b": 2, "a": 1]\n /// let replacingCurrent = dictionary.merging(otherDictionary)\n /// { (_, new) in new }\n /// // ["b": 4, "a": 3]\n ///\n /// - Parameters:\n /// - other: A dictionary to merge.\n /// - combine: A closure that takes the current and new values for any\n /// duplicate keys. The closure returns the desired value for the final\n /// dictionary.\n /// - Returns: A new dictionary with the combined keys and values of this\n /// dictionary and `other`.\n @inlinable\n public __consuming func merging(\n _ other: __owned [Key: Value],\n uniquingKeysWith combine: (Value, Value) throws -> Value\n ) rethrows -> [Key: Value] {\n var result = self\n try result.merge(other, uniquingKeysWith: combine)\n return result\n }\n\n /// Removes and returns the key-value pair at the specified index.\n ///\n /// Calling this method invalidates any existing indices for use with this\n /// dictionary.\n ///\n /// - Parameter index: The position of the key-value pair to remove. `index`\n /// must be a valid index of the dictionary, and must not equal the\n /// dictionary's end index.\n /// - Returns: The key-value pair that correspond to `index`.\n ///\n /// - Complexity: O(*n*), where *n* is the number of key-value pairs in the\n /// dictionary.\n @inlinable\n @discardableResult\n public mutating func remove(at index: Index) -> Element {\n return _variant.remove(at: index)\n }\n\n /// Removes the given key and its associated value from the dictionary.\n ///\n /// If the key is found in the dictionary, this method returns the key's\n /// associated value. On removal, this method invalidates all indices with\n /// respect to the dictionary.\n ///\n /// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]\n /// if let value = hues.removeValue(forKey: "Coral") {\n /// print("The value \(value) was removed.")\n /// }\n /// // Prints "The value 16 was removed."\n ///\n /// If the key isn't found in the dictionary, `removeValue(forKey:)` returns\n /// `nil`.\n ///\n /// if let value = hues.removeValue(forKey: "Cerise") {\n /// print("The value \(value) was removed.")\n /// } else {\n /// print("No value found for that key.")\n /// }\n /// // Prints "No value found for that key."\n ///\n /// - Parameter key: The key to remove along with its associated value.\n /// - Returns: The value that was removed, or `nil` if the key was not\n /// present in the dictionary.\n ///\n /// - Complexity: O(*n*), where *n* is the number of key-value pairs in the\n /// dictionary.\n @inlinable\n @discardableResult\n public mutating func removeValue(forKey key: Key) -> Value? {\n return _variant.removeValue(forKey: key)\n }\n\n /// Removes all key-value pairs from the dictionary.\n ///\n /// Calling this method invalidates all indices with respect to the\n /// dictionary.\n ///\n /// - Parameter keepCapacity: Whether the dictionary should keep its\n /// underlying buffer. If you pass `true`, the operation preserves the\n /// buffer capacity that the collection has, otherwise the underlying\n /// buffer is released. The default is `false`.\n ///\n /// - Complexity: O(*n*), where *n* is the number of key-value pairs in the\n /// dictionary.\n @inlinable\n public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {\n // The 'will not decrease' part in the documentation comment is worded very\n // carefully. The capacity can increase if we replace Cocoa dictionary with\n // native dictionary.\n _variant.removeAll(keepingCapacity: keepCapacity)\n }\n}\n\nextension Dictionary {\n /// A collection containing just the keys of the dictionary.\n ///\n /// When iterated over, keys appear in this collection in the same order as\n /// they occur in the dictionary's key-value pairs. Each key in the keys\n /// collection has a unique value.\n ///\n /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]\n /// print(countryCodes)\n /// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"\n ///\n /// for k in countryCodes.keys {\n /// print(k)\n /// }\n /// // Prints "BR"\n /// // Prints "JP"\n /// // Prints "GH"\n @inlinable\n @available(swift, introduced: 4.0)\n public var keys: Keys {\n // FIXME(accessors): Provide a _read\n get {\n return Keys(_dictionary: self)\n }\n }\n\n /// A collection containing just the values of the dictionary.\n ///\n /// When iterated over, values appear in this collection in the same order as\n /// they occur in the dictionary's key-value pairs.\n ///\n /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]\n /// print(countryCodes)\n /// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"\n ///\n /// for v in countryCodes.values {\n /// print(v)\n /// }\n /// // Prints "Brazil"\n /// // Prints "Japan"\n /// // Prints "Ghana"\n @inlinable\n @available(swift, introduced: 4.0)\n public var values: Values {\n // FIXME(accessors): Provide a _read\n get {\n return Values(_dictionary: self)\n }\n _modify {\n var values = Values(_variant: _Variant(dummy: ()))\n swap(&values._variant, &_variant)\n defer { self._variant = values._variant }\n yield &values\n }\n }\n\n /// A view of a dictionary's keys.\n @frozen\n public struct Keys: Collection, Equatable {\n public typealias Element = Key\n public typealias SubSequence = Slice<Dictionary.Keys>\n\n @usableFromInline\n internal var _variant: Dictionary<Key, Value>._Variant\n\n @inlinable\n internal init(_dictionary: __owned Dictionary) {\n self._variant = _dictionary._variant\n }\n\n // Collection Conformance\n // ----------------------\n\n @inlinable\n public var startIndex: Index {\n return _variant.startIndex\n }\n\n @inlinable\n public var endIndex: Index {\n return _variant.endIndex\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n return _variant.index(after: i)\n }\n\n @inlinable\n public func formIndex(after i: inout Index) {\n _variant.formIndex(after: &i)\n }\n\n @inlinable\n public subscript(position: Index) -> Element {\n return _variant.key(at: position)\n }\n\n // Customization\n // -------------\n\n /// The number of keys in the dictionary.\n ///\n /// - Complexity: O(1).\n @inlinable\n public var count: Int {\n return _variant.count\n }\n\n @inlinable\n public var isEmpty: Bool {\n return count == 0\n }\n\n @inlinable\n @inline(__always)\n public func _customContainsEquatableElement(_ element: Element) -> Bool? {\n return _variant.contains(element)\n }\n\n @inlinable\n @inline(__always)\n public func _customIndexOfEquatableElement(_ element: Element) -> Index?? {\n return Optional(_variant.index(forKey: element))\n }\n\n @inlinable\n @inline(__always)\n public func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? {\n // The first and last elements are the same because each element is unique.\n return _customIndexOfEquatableElement(element)\n }\n\n @inlinable\n public static func ==(lhs: Keys, rhs: Keys) -> Bool {\n // Equal if the two dictionaries share storage.\n#if _runtime(_ObjC)\n if\n lhs._variant.isNative,\n rhs._variant.isNative,\n unsafe (lhs._variant.asNative._storage === rhs._variant.asNative._storage)\n {\n return true\n }\n if\n !lhs._variant.isNative,\n !rhs._variant.isNative,\n lhs._variant.asCocoa.object === rhs._variant.asCocoa.object\n {\n return true\n }\n#else\n if unsafe (lhs._variant.asNative._storage === rhs._variant.asNative._storage) {\n return true\n }\n#endif\n\n // Not equal if the dictionaries are different sizes.\n if lhs.count != rhs.count {\n return false\n }\n\n // Perform unordered comparison of keys.\n for key in lhs {\n if !rhs.contains(key) {\n return false\n }\n }\n\n return true\n }\n }\n\n /// A view of a dictionary's values.\n @frozen\n public struct Values: MutableCollection {\n public typealias Element = Value\n\n @usableFromInline\n internal var _variant: Dictionary<Key, Value>._Variant\n\n @inlinable\n internal init(_variant: __owned Dictionary<Key, Value>._Variant) {\n self._variant = _variant\n }\n\n @inlinable\n internal init(_dictionary: __owned Dictionary) {\n self._variant = _dictionary._variant\n }\n\n // Collection Conformance\n // ----------------------\n\n @inlinable\n public var startIndex: Index {\n return _variant.startIndex\n }\n\n @inlinable\n public var endIndex: Index {\n return _variant.endIndex\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n return _variant.index(after: i)\n }\n\n @inlinable\n public func formIndex(after i: inout Index) {\n _variant.formIndex(after: &i)\n }\n\n @inlinable\n public subscript(position: Index) -> Element {\n // FIXME(accessors): Provide a _read\n get {\n return _variant.value(at: position)\n }\n _modify {\n let native = _variant.ensureUniqueNative()\n let bucket = native.validatedBucket(for: position)\n let address = unsafe native._values + bucket.offset\n defer { _fixLifetime(self) }\n yield unsafe &address.pointee\n }\n }\n\n // Customization\n // -------------\n\n /// The number of values in the dictionary.\n ///\n /// - Complexity: O(1).\n @inlinable\n public var count: Int {\n return _variant.count\n }\n\n @inlinable\n public var isEmpty: Bool {\n return count == 0\n }\n\n @inlinable\n public mutating func swapAt(_ i: Index, _ j: Index) {\n guard i != j else { return }\n#if _runtime(_ObjC)\n if !_variant.isNative {\n _variant = .init(native: _NativeDictionary(_variant.asCocoa))\n }\n#endif\n let isUnique = _variant.isUniquelyReferenced()\n let native = _variant.asNative\n let a = native.validatedBucket(for: i)\n let b = native.validatedBucket(for: j)\n _variant.asNative.swapValuesAt(a, b, isUnique: isUnique)\n }\n }\n}\n\n@_unavailableInEmbedded\nextension Dictionary.Keys\n : CustomStringConvertible, CustomDebugStringConvertible {\n public var description: String {\n return _makeCollectionDescription()\n }\n\n public var debugDescription: String {\n return _makeCollectionDescription(withTypeName: "Dictionary.Keys")\n }\n}\n\n@_unavailableInEmbedded\nextension Dictionary.Values\n : CustomStringConvertible, CustomDebugStringConvertible {\n public var description: String {\n return _makeCollectionDescription()\n }\n\n public var debugDescription: String {\n return _makeCollectionDescription(withTypeName: "Dictionary.Values")\n }\n}\n\nextension Dictionary.Keys {\n @frozen\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var _base: Dictionary<Key, Value>.Iterator\n\n @inlinable\n @inline(__always)\n internal init(_ base: Dictionary<Key, Value>.Iterator) {\n self._base = base\n }\n\n @inlinable\n @inline(__always)\n public mutating func next() -> Key? {\n#if _runtime(_ObjC)\n if case .cocoa(let cocoa) = _base._variant {\n _base._cocoaPath()\n guard let cocoaKey = cocoa.nextKey() else { return nil }\n return _forceBridgeFromObjectiveC(cocoaKey, Key.self)\n }\n#endif\n return _base._asNative.nextKey()\n }\n }\n\n @inlinable\n @inline(__always)\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_variant.makeIterator())\n }\n}\n\nextension Dictionary.Values {\n @frozen\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var _base: Dictionary<Key, Value>.Iterator\n\n @inlinable\n @inline(__always)\n internal init(_ base: Dictionary<Key, Value>.Iterator) {\n self._base = base\n }\n\n @inlinable\n @inline(__always)\n public mutating func next() -> Value? {\n#if _runtime(_ObjC)\n if case .cocoa(let cocoa) = _base._variant {\n _base._cocoaPath()\n guard let (_, cocoaValue) = cocoa.next() else { return nil }\n return _forceBridgeFromObjectiveC(cocoaValue, Value.self)\n }\n#endif\n return _base._asNative.nextValue()\n }\n }\n\n @inlinable\n @inline(__always)\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_variant.makeIterator())\n }\n}\n\nextension Dictionary: Equatable where Value: Equatable {\n @inlinable\n public static func == (lhs: [Key: Value], rhs: [Key: Value]) -> Bool {\n#if _runtime(_ObjC)\n switch (lhs._variant.isNative, rhs._variant.isNative) {\n case (true, true):\n return lhs._variant.asNative.isEqual(to: rhs._variant.asNative)\n case (false, false):\n return lhs._variant.asCocoa.isEqual(to: rhs._variant.asCocoa)\n case (true, false):\n return lhs._variant.asNative.isEqual(to: rhs._variant.asCocoa)\n case (false, true):\n return rhs._variant.asNative.isEqual(to: lhs._variant.asCocoa)\n }\n#else\n return lhs._variant.asNative.isEqual(to: rhs._variant.asNative)\n#endif\n }\n}\n\nextension Dictionary: Hashable where Value: Hashable {\n /// Hashes the essential components of this value by feeding them into the\n /// given hasher.\n ///\n /// - Parameter hasher: The hasher to use when combining the components\n /// of this instance.\n @inlinable\n public func hash(into hasher: inout Hasher) {\n var commutativeHash = 0\n for (k, v) in self {\n // Note that we use a copy of our own hasher here. This makes hash values\n // dependent on its state, eliminating static collision patterns.\n var elementHasher = hasher\n elementHasher.combine(k)\n elementHasher.combine(v)\n commutativeHash ^= elementHasher._finalize()\n }\n hasher.combine(commutativeHash)\n }\n}\n\n@_unavailableInEmbedded\nextension Dictionary: _HasCustomAnyHashableRepresentation\nwhere Value: Hashable {\n public __consuming func _toCustomAnyHashable() -> AnyHashable? {\n return AnyHashable(_box: _DictionaryAnyHashableBox(self))\n }\n}\n\n@_unavailableInEmbedded\ninternal struct _DictionaryAnyHashableBox<Key: Hashable, Value: Hashable>\n : _AnyHashableBox {\n internal let _value: Dictionary<Key, Value>\n internal let _canonical: Dictionary<AnyHashable, AnyHashable>\n\n internal init(_ value: __owned Dictionary<Key, Value>) {\n self._value = value\n self._canonical = value as Dictionary<AnyHashable, AnyHashable>\n }\n\n internal var _base: Any {\n return _value\n }\n\n internal var _canonicalBox: _AnyHashableBox {\n return _DictionaryAnyHashableBox<AnyHashable, AnyHashable>(_canonical)\n }\n\n internal func _isEqual(to other: _AnyHashableBox) -> Bool? {\n guard\n let other = other as? _DictionaryAnyHashableBox<AnyHashable, AnyHashable>\n else {\n return nil\n }\n return _canonical == other._value\n }\n\n internal var _hashValue: Int {\n return _canonical.hashValue\n }\n\n internal func _hash(into hasher: inout Hasher) {\n _canonical.hash(into: &hasher)\n }\n\n internal func _rawHashValue(_seed: Int) -> Int {\n return _canonical._rawHashValue(seed: _seed)\n }\n\n internal func _unbox<T: Hashable>() -> T? {\n return _value as? T\n }\n\n internal func _downCastConditional<T>(\n into result: UnsafeMutablePointer<T>\n ) -> Bool {\n guard let value = _value as? T else { return false }\n unsafe result.initialize(to: value)\n return true\n }\n}\n\n@_unavailableInEmbedded\nextension Collection {\n // Utility method for KV collections that wish to implement\n // CustomStringConvertible and CustomDebugStringConvertible using a bracketed\n // list of elements.\n // FIXME: Doesn't use the withTypeName argument yet\n internal func _makeKeyValuePairDescription<K, V>(\n withTypeName type: String? = nil\n ) -> String where Element == (key: K, value: V) {\n#if !SWIFT_STDLIB_STATIC_PRINT\n if self.isEmpty {\n return "[:]"\n }\n \n var result = "["\n var first = true\n for (k, v) in self {\n if first {\n first = false\n } else {\n result += ", "\n }\n #if !$Embedded\n debugPrint(k, terminator: "", to: &result)\n result += ": "\n debugPrint(v, terminator: "", to: &result)\n #else\n "(cannot print value in embedded Swift)".write(to: &result)\n result += ": "\n "(cannot print value in embedded Swift)".write(to: &result)\n #endif\n }\n result += "]"\n return result\n#else\n return "(collection printing not available)"\n#endif\n }\n}\n\n@_unavailableInEmbedded\nextension Dictionary: CustomStringConvertible, CustomDebugStringConvertible {\n /// A string that represents the contents of the dictionary.\n public var description: String {\n return _makeKeyValuePairDescription()\n }\n\n /// A string that represents the contents of the dictionary, suitable for\n /// debugging.\n public var debugDescription: String {\n return _makeKeyValuePairDescription()\n }\n}\n\n@usableFromInline\n@frozen\ninternal enum _MergeError: Error {\n case keyCollision\n}\n\nextension Dictionary {\n /// The position of a key-value pair in a dictionary.\n ///\n /// Dictionary has two subscripting interfaces:\n ///\n /// 1. Subscripting with a key, yielding an optional value:\n ///\n /// v = d[k]!\n ///\n /// 2. Subscripting with an index, yielding a key-value pair:\n ///\n /// (k, v) = d[i]\n @frozen\n public struct Index {\n // Index for native dictionary is efficient. Index for bridged NSDictionary\n // is not, because neither NSEnumerator nor fast enumeration support moving\n // backwards. Even if they did, there is another issue: NSEnumerator does\n // not support NSCopying, and fast enumeration does not document that it is\n // safe to copy the state. So, we cannot implement Index that is a value\n // type for bridged NSDictionary in terms of Cocoa enumeration facilities.\n\n @frozen\n @usableFromInline\n @safe\n internal enum _Variant {\n case native(_HashTable.Index)\n#if _runtime(_ObjC)\n case cocoa(__CocoaDictionary.Index)\n#endif\n }\n\n @usableFromInline\n internal var _variant: _Variant\n\n @inlinable\n @inline(__always)\n internal init(_variant: __owned _Variant) {\n self._variant = _variant\n }\n\n @inlinable\n @inline(__always)\n internal init(_native index: _HashTable.Index) {\n unsafe self.init(_variant: .native(index))\n }\n\n#if _runtime(_ObjC)\n @inlinable\n @inline(__always)\n internal init(_cocoa index: __owned __CocoaDictionary.Index) {\n self.init(_variant: .cocoa(index))\n }\n#endif\n }\n}\n\nextension Dictionary.Index._Variant: @unchecked Sendable {}\n\nextension Dictionary.Index {\n#if _runtime(_ObjC)\n @usableFromInline @_transparent\n internal var _guaranteedNative: Bool {\n return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0\n }\n\n // Allow the optimizer to consider the surrounding code unreachable if Element\n // is guaranteed to be native.\n @usableFromInline @_transparent\n internal func _cocoaPath() {\n if _guaranteedNative {\n _conditionallyUnreachable()\n }\n }\n\n @inlinable\n @inline(__always)\n internal mutating func _isUniquelyReferenced() -> Bool {\n defer { _fixLifetime(self) }\n var handle = _asCocoa.handleBitPattern\n return handle == 0 || _isUnique_native(&handle)\n }\n\n @usableFromInline @_transparent\n internal var _isNative: Bool {\n switch _variant {\n case .native:\n return true\n case .cocoa:\n _cocoaPath()\n return false\n }\n }\n#endif\n\n @usableFromInline @_transparent\n internal var _asNative: _HashTable.Index {\n switch _variant {\n case .native(let nativeIndex):\n return unsafe nativeIndex\n#if _runtime(_ObjC)\n case .cocoa:\n _preconditionFailure(\n "Attempting to access Dictionary elements using an invalid index")\n#endif\n }\n }\n\n#if _runtime(_ObjC)\n @usableFromInline\n internal var _asCocoa: __CocoaDictionary.Index {\n @_transparent\n get {\n switch _variant {\n case .native:\n _preconditionFailure(\n "Attempting to access Dictionary elements using an invalid index")\n case .cocoa(let cocoaIndex):\n return cocoaIndex\n }\n }\n _modify {\n guard case .cocoa(var cocoa) = _variant else {\n _preconditionFailure(\n "Attempting to access Dictionary elements using an invalid index")\n }\n let dummy = unsafe _HashTable.Index(bucket: _HashTable.Bucket(offset: 0), age: 0)\n _variant = unsafe .native(dummy)\n defer { _variant = .cocoa(cocoa) }\n yield &cocoa\n }\n }\n#endif\n}\n\nextension Dictionary.Index: Equatable {\n @inlinable\n public static func == (\n lhs: Dictionary<Key, Value>.Index,\n rhs: Dictionary<Key, Value>.Index\n ) -> Bool {\n switch (lhs._variant, rhs._variant) {\n case (.native(let lhsNative), .native(let rhsNative)):\n return unsafe lhsNative == rhsNative\n #if _runtime(_ObjC)\n case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)):\n lhs._cocoaPath()\n return lhsCocoa == rhsCocoa\n default:\n _preconditionFailure("Comparing indexes from different dictionaries")\n #endif\n }\n }\n}\n\nextension Dictionary.Index: Comparable {\n @inlinable\n public static func < (\n lhs: Dictionary<Key, Value>.Index,\n rhs: Dictionary<Key, Value>.Index\n ) -> Bool {\n switch (lhs._variant, rhs._variant) {\n case (.native(let lhsNative), .native(let rhsNative)):\n return unsafe lhsNative < rhsNative\n #if _runtime(_ObjC)\n case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)):\n lhs._cocoaPath()\n return lhsCocoa < rhsCocoa\n default:\n _preconditionFailure("Comparing indexes from different dictionaries")\n #endif\n }\n }\n}\n\nextension Dictionary.Index: Hashable {\n public // FIXME(cocoa-index): Make inlinable\n func hash(into hasher: inout Hasher) {\n#if _runtime(_ObjC)\n guard _isNative else {\n hasher.combine(1 as UInt8)\n hasher.combine(_asCocoa._offset)\n return\n }\n hasher.combine(0 as UInt8)\n unsafe hasher.combine(_asNative.bucket.offset)\n#else\n unsafe hasher.combine(_asNative.bucket.offset)\n#endif\n }\n}\n\nextension Dictionary {\n /// An iterator over the members of a `Dictionary<Key, Value>`.\n @frozen\n public struct Iterator {\n // Dictionary has a separate IteratorProtocol and Index because of\n // efficiency and implementability reasons.\n //\n // Native dictionaries have efficient indices.\n // Bridged NSDictionary instances don't.\n //\n // Even though fast enumeration is not suitable for implementing\n // Index, which is multi-pass, it is suitable for implementing a\n // IteratorProtocol, which is being consumed as iteration proceeds.\n\n @usableFromInline\n @frozen\n internal enum _Variant {\n case native(_NativeDictionary<Key, Value>.Iterator)\n#if _runtime(_ObjC)\n case cocoa(__CocoaDictionary.Iterator)\n#endif\n }\n\n @usableFromInline\n internal var _variant: _Variant\n\n @inlinable\n internal init(_variant: __owned _Variant) {\n self._variant = _variant\n }\n\n @inlinable\n internal init(_native: __owned _NativeDictionary<Key, Value>.Iterator) {\n self.init(_variant: .native(_native))\n }\n\n#if _runtime(_ObjC)\n @inlinable\n internal init(_cocoa: __owned __CocoaDictionary.Iterator) {\n self.init(_variant: .cocoa(_cocoa))\n }\n#endif\n }\n}\n\nextension Dictionary.Iterator._Variant: @unchecked Sendable\n where Key: Sendable, Value: Sendable {}\n\nextension Dictionary.Iterator {\n#if _runtime(_ObjC)\n @usableFromInline @_transparent\n internal var _guaranteedNative: Bool {\n return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0\n }\n\n /// Allow the optimizer to consider the surrounding code unreachable if\n /// Dictionary<Key, Value> is guaranteed to be native.\n @usableFromInline @_transparent\n internal func _cocoaPath() {\n if _guaranteedNative {\n _conditionallyUnreachable()\n }\n }\n\n @usableFromInline @_transparent\n internal var _isNative: Bool {\n switch _variant {\n case .native:\n return true\n case .cocoa:\n _cocoaPath()\n return false\n }\n }\n#endif\n\n @usableFromInline @_transparent\n internal var _asNative: _NativeDictionary<Key, Value>.Iterator {\n get {\n switch _variant {\n case .native(let nativeIterator):\n return nativeIterator\n#if _runtime(_ObjC)\n case .cocoa:\n _internalInvariantFailure("internal error: does not contain a native index")\n#endif\n }\n }\n set {\n self._variant = .native(newValue)\n }\n }\n\n#if _runtime(_ObjC)\n @usableFromInline @_transparent\n internal var _asCocoa: __CocoaDictionary.Iterator {\n get {\n switch _variant {\n case .native:\n _internalInvariantFailure("internal error: does not contain a Cocoa index")\n case .cocoa(let cocoa):\n return cocoa\n }\n }\n }\n#endif\n\n}\n\nextension Dictionary.Iterator: IteratorProtocol {\n /// Advances to the next element and returns it, or `nil` if no next element\n /// exists.\n ///\n /// Once `nil` has been returned, all subsequent calls return `nil`.\n @inlinable\n @inline(__always)\n public mutating func next() -> (key: Key, value: Value)? {\n#if _runtime(_ObjC)\n guard _isNative else {\n if let (cocoaKey, cocoaValue) = _asCocoa.next() {\n let nativeKey = _forceBridgeFromObjectiveC(cocoaKey, Key.self)\n let nativeValue = _forceBridgeFromObjectiveC(cocoaValue, Value.self)\n return (nativeKey, nativeValue)\n }\n return nil\n }\n#endif\n return _asNative.next()\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension Dictionary.Iterator: CustomReflectable {\n /// A mirror that reflects the iterator.\n public var customMirror: Mirror {\n return Mirror(\n self,\n children: EmptyCollection<(label: String?, value: Any)>())\n }\n}\n\nextension Dictionary: CustomReflectable {\n /// A mirror that reflects the dictionary.\n public var customMirror: Mirror {\n let style = Mirror.DisplayStyle.dictionary\n return Mirror(self, unlabeledChildren: self, displayStyle: style)\n }\n}\n#endif\n\nextension Dictionary {\n /// Removes and returns the first key-value pair of the dictionary if the\n /// dictionary isn't empty.\n ///\n /// The first element of the dictionary is not necessarily the first element\n /// added. Don't expect any particular ordering of key-value pairs.\n ///\n /// - Returns: The first key-value pair of the dictionary if the dictionary\n /// is not empty; otherwise, `nil`.\n ///\n /// - Complexity: Averages to O(1) over many calls to `popFirst()`.\n @inlinable\n public mutating func popFirst() -> Element? {\n guard !isEmpty else { return nil }\n return remove(at: startIndex)\n }\n\n /// The total number of key-value pairs that the dictionary can contain without\n /// allocating new storage.\n @inlinable\n public var capacity: Int {\n return _variant.capacity\n }\n\n /// Reserves enough space to store the specified number of key-value pairs.\n ///\n /// If you are adding a known number of key-value pairs to a dictionary, use this\n /// method to avoid multiple reallocations. This method ensures that the\n /// dictionary has unique, mutable, contiguous storage, with space allocated\n /// for at least the requested number of key-value pairs.\n ///\n /// Calling the `reserveCapacity(_:)` method on a dictionary with bridged\n /// storage triggers a copy to contiguous storage even if the existing\n /// storage has room to store `minimumCapacity` key-value pairs.\n ///\n /// - Parameter minimumCapacity: The requested number of key-value pairs to\n /// store.\n public // FIXME(reserveCapacity): Should be inlinable\n mutating func reserveCapacity(_ minimumCapacity: Int) {\n _variant.reserveCapacity(minimumCapacity)\n _internalInvariant(self.capacity >= minimumCapacity)\n }\n}\n\npublic typealias DictionaryIndex<Key: Hashable, Value> =\n Dictionary<Key, Value>.Index\npublic typealias DictionaryIterator<Key: Hashable, Value> =\n Dictionary<Key, Value>.Iterator\n\nextension Dictionary: @unchecked Sendable\n where Key: Sendable, Value: Sendable {}\nextension Dictionary.Keys: @unchecked Sendable\n where Key: Sendable, Value: Sendable {}\nextension Dictionary.Values: @unchecked Sendable\n where Key: Sendable, Value: Sendable {}\nextension Dictionary.Keys.Iterator: @unchecked Sendable\n where Key: Sendable, Value: Sendable {}\nextension Dictionary.Values.Iterator: @unchecked Sendable\n where Key: Sendable, Value: Sendable {}\nextension Dictionary.Index: @unchecked Sendable\n where Key: Sendable, Value: Sendable {}\nextension Dictionary.Iterator: @unchecked Sendable\n where Key: Sendable, Value: Sendable {}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Dictionary.swift | cpp_apple_swift_stdlib_public_core_Dictionary.swift | Swift | 75,774 | 0.75 | 0.093228 | 0.552801 | react-lib | 54 | 2023-11-05T05:38:23.072700 | GPL-3.0 | false | 955a11f4e656c01167eb70517f498d05 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if _runtime(_ObjC)\n\nimport SwiftShims\n\n/// Equivalent to `NSDictionary.allKeys`, but does not leave objects on the\n/// autorelease pool.\ninternal func _stdlib_NSDictionary_allKeys(\n _ object: AnyObject\n) -> _BridgingBuffer {\n let nsd = unsafe unsafeBitCast(object, to: _NSDictionary.self)\n let count = nsd.count\n let storage = _BridgingBuffer(count)\n unsafe nsd.getObjects(nil, andKeys: storage.baseAddress, count: count)\n return storage\n}\n\nextension _NativeDictionary { // Bridging\n @usableFromInline\n __consuming internal func bridged() -> AnyObject {\n _connectOrphanedFoundationSubclassesIfNeeded()\n // We can zero-cost bridge if our keys are verbatim\n // or if we're the empty singleton.\n\n // Temporary var for SOME type safety.\n let nsDictionary: _NSDictionaryCore\n\n if unsafe _storage === __RawDictionaryStorage.empty || count == 0 {\n unsafe nsDictionary = __RawDictionaryStorage.empty\n } else if _isBridgedVerbatimToObjectiveC(Key.self),\n _isBridgedVerbatimToObjectiveC(Value.self) {\n unsafe nsDictionary = unsafeDowncast(\n _storage,\n to: _DictionaryStorage<Key, Value>.self)\n } else {\n nsDictionary = _SwiftDeferredNSDictionary(self)\n }\n\n return nsDictionary\n }\n}\n\n/// An NSEnumerator that works with any _NativeDictionary of\n/// verbatim bridgeable elements. Used by the various NSDictionary impls.\n@safe\nfinal internal class _SwiftDictionaryNSEnumerator<Key: Hashable, Value>\n : __SwiftNativeNSEnumerator, _NSEnumerator {\n\n @nonobjc internal var base: _NativeDictionary<Key, Value>\n @nonobjc internal var bridgedKeys: __BridgingHashBuffer?\n @nonobjc internal var nextBucket: _NativeDictionary<Key, Value>.Bucket\n @nonobjc internal var endBucket: _NativeDictionary<Key, Value>.Bucket\n\n @objc\n internal override required init() {\n _internalInvariantFailure("don't call this designated initializer")\n }\n\n internal init(_ base: __owned _NativeDictionary<Key, Value>) {\n _internalInvariant(_isBridgedVerbatimToObjectiveC(Key.self))\n _internalInvariant(_orphanedFoundationSubclassesReparented)\n self.base = base\n unsafe self.bridgedKeys = nil\n unsafe self.nextBucket = base.hashTable.startBucket\n unsafe self.endBucket = base.hashTable.endBucket\n super.init()\n }\n\n @nonobjc\n internal init(_ deferred: __owned _SwiftDeferredNSDictionary<Key, Value>) {\n _internalInvariant(!_isBridgedVerbatimToObjectiveC(Key.self))\n _internalInvariant(_orphanedFoundationSubclassesReparented)\n self.base = deferred.native\n unsafe self.bridgedKeys = deferred.bridgeKeys()\n unsafe self.nextBucket = base.hashTable.startBucket\n unsafe self.endBucket = base.hashTable.endBucket\n super.init()\n }\n\n private func bridgedKey(at bucket: _HashTable.Bucket) -> AnyObject {\n unsafe _internalInvariant(base.hashTable.isOccupied(bucket))\n if let bridgedKeys = unsafe self.bridgedKeys {\n return unsafe bridgedKeys[bucket]\n }\n return unsafe _bridgeAnythingToObjectiveC(base.uncheckedKey(at: bucket))\n }\n\n @objc\n internal func nextObject() -> AnyObject? {\n if nextBucket == endBucket {\n return nil\n }\n let bucket = nextBucket\n unsafe nextBucket = base.hashTable.occupiedBucket(after: nextBucket)\n return self.bridgedKey(at: bucket)\n }\n\n @objc(countByEnumeratingWithState:objects:count:)\n internal func countByEnumerating(\n with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,\n objects: UnsafeMutablePointer<AnyObject>,\n count: Int\n ) -> Int {\n var theState = unsafe state.pointee\n if unsafe theState.state == 0 {\n unsafe theState.state = 1 // Arbitrary non-zero value.\n unsafe theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)\n unsafe theState.mutationsPtr = _fastEnumerationStorageMutationsPtr\n }\n\n if nextBucket == endBucket {\n unsafe state.pointee = theState\n return 0\n }\n\n // Return only a single element so that code can start iterating via fast\n // enumeration, terminate it, and continue via NSEnumerator.\n let unmanagedObjects = unsafe _UnmanagedAnyObjectArray(objects)\n unsafe unmanagedObjects[0] = self.bridgedKey(at: nextBucket)\n unsafe nextBucket = base.hashTable.occupiedBucket(after: nextBucket)\n unsafe state.pointee = theState\n return 1\n }\n}\n\n/// This class exists for Objective-C bridging. It holds a reference to a\n/// _NativeDictionary, and can be upcast to NSSelf when bridging is\n/// necessary. This is the fallback implementation for situations where\n/// toll-free bridging isn't possible. On first access, a _NativeDictionary\n/// of AnyObject will be constructed containing all the bridged elements.\nfinal internal class _SwiftDeferredNSDictionary<Key: Hashable, Value>\n : __SwiftNativeNSDictionary, _NSDictionaryCore {\n\n @usableFromInline\n internal typealias Bucket = _HashTable.Bucket\n\n // This stored property must be stored at offset zero. We perform atomic\n // operations on it.\n //\n // Do not access this property directly.\n @nonobjc\n private var _bridgedKeys_DoNotUse: AnyObject?\n\n // This stored property must be stored at offset one. We perform atomic\n // operations on it.\n //\n // Do not access this property directly.\n @nonobjc\n private var _bridgedValues_DoNotUse: AnyObject?\n\n /// The unbridged elements.\n internal var native: _NativeDictionary<Key, Value>\n\n internal init(_ native: __owned _NativeDictionary<Key, Value>) {\n _internalInvariant(native.count > 0)\n _internalInvariant(!_isBridgedVerbatimToObjectiveC(Key.self) ||\n !_isBridgedVerbatimToObjectiveC(Value.self))\n self.native = native\n super.init()\n }\n\n @objc\n internal required init(\n objects: UnsafePointer<AnyObject?>,\n forKeys: UnsafeRawPointer,\n count: Int\n ) {\n _internalInvariantFailure("don't call this designated initializer")\n }\n\n @nonobjc\n private var _bridgedKeysPtr: UnsafeMutablePointer<AnyObject?> {\n return unsafe _getUnsafePointerToStoredProperties(self)\n .assumingMemoryBound(to: Optional<AnyObject>.self)\n }\n\n @nonobjc\n private var _bridgedValuesPtr: UnsafeMutablePointer<AnyObject?> {\n return unsafe _bridgedKeysPtr + 1\n }\n\n /// The buffer for bridged keys, if present.\n @nonobjc\n private var _bridgedKeys: __BridgingHashBuffer? {\n guard let ref = unsafe _stdlib_atomicLoadARCRef(object: _bridgedKeysPtr) else {\n return nil\n }\n return unsafe unsafeDowncast(ref, to: __BridgingHashBuffer.self)\n }\n\n /// The buffer for bridged values, if present.\n @nonobjc\n private var _bridgedValues: __BridgingHashBuffer? {\n guard let ref = unsafe _stdlib_atomicLoadARCRef(object: _bridgedValuesPtr) else {\n return nil\n }\n return unsafe unsafeDowncast(ref, to: __BridgingHashBuffer.self)\n }\n\n /// Attach a buffer for bridged Dictionary keys.\n @nonobjc\n private func _initializeBridgedKeys(_ storage: __BridgingHashBuffer) {\n unsafe _stdlib_atomicInitializeARCRef(object: _bridgedKeysPtr, desired: storage)\n }\n\n /// Attach a buffer for bridged Dictionary values.\n @nonobjc\n private func _initializeBridgedValues(_ storage: __BridgingHashBuffer) {\n unsafe _stdlib_atomicInitializeARCRef(object: _bridgedValuesPtr, desired: storage)\n }\n\n @nonobjc\n internal func bridgeKeys() -> __BridgingHashBuffer? {\n if _isBridgedVerbatimToObjectiveC(Key.self) { return nil }\n if let bridgedKeys = unsafe _bridgedKeys { return unsafe bridgedKeys }\n\n // Allocate and initialize heap storage for bridged keys.\n let bridged = unsafe __BridgingHashBuffer.allocate(\n owner: native._storage,\n hashTable: native.hashTable)\n for unsafe bucket in unsafe native.hashTable {\n let object = unsafe _bridgeAnythingToObjectiveC(\n native.uncheckedKey(at: bucket))\n unsafe bridged.initialize(at: bucket, to: object)\n }\n\n // Atomically put the bridged keys in place.\n unsafe _initializeBridgedKeys(bridged)\n return unsafe _bridgedKeys!\n }\n\n @nonobjc\n internal func bridgeValues() -> __BridgingHashBuffer? {\n if _isBridgedVerbatimToObjectiveC(Value.self) { return nil }\n if let bridgedValues = unsafe _bridgedValues { return unsafe bridgedValues }\n\n // Allocate and initialize heap storage for bridged values.\n let bridged = unsafe __BridgingHashBuffer.allocate(\n owner: native._storage,\n hashTable: native.hashTable)\n for unsafe bucket in unsafe native.hashTable {\n let value = unsafe native.uncheckedValue(at: bucket)\n let cocoaValue = _bridgeAnythingToObjectiveC(value)\n unsafe bridged.initialize(at: bucket, to: cocoaValue)\n }\n\n // Atomically put the bridged values in place.\n unsafe _initializeBridgedValues(bridged)\n return unsafe _bridgedValues!\n }\n\n @objc(copyWithZone:)\n internal func copy(with zone: _SwiftNSZone?) -> AnyObject {\n // Instances of this class should be visible outside of standard library as\n // having `NSDictionary` type, which is immutable.\n return self\n }\n\n @inline(__always)\n private func _key(\n at bucket: Bucket,\n bridgedKeys: __BridgingHashBuffer?\n ) -> AnyObject {\n if let bridgedKeys = unsafe bridgedKeys {\n return unsafe bridgedKeys[bucket]\n }\n return unsafe _bridgeAnythingToObjectiveC(native.uncheckedKey(at: bucket))\n }\n\n @inline(__always)\n private func _value(\n at bucket: Bucket,\n bridgedValues: __BridgingHashBuffer?\n ) -> AnyObject {\n if let bridgedValues = unsafe bridgedValues {\n return unsafe bridgedValues[bucket]\n }\n return unsafe _bridgeAnythingToObjectiveC(native.uncheckedValue(at: bucket))\n }\n\n @objc(objectForKey:)\n internal func object(forKey aKey: AnyObject) -> AnyObject? {\n guard let nativeKey = _conditionallyBridgeFromObjectiveC(aKey, Key.self)\n else { return nil }\n\n let (bucket, found) = native.find(nativeKey)\n guard found else { return nil }\n return unsafe _value(at: bucket, bridgedValues: bridgeValues())\n }\n\n @objc\n internal func keyEnumerator() -> _NSEnumerator {\n if _isBridgedVerbatimToObjectiveC(Key.self) {\n return _SwiftDictionaryNSEnumerator<Key, Value>(native)\n }\n return _SwiftDictionaryNSEnumerator<Key, Value>(self)\n }\n\n @objc(getObjects:andKeys:count:)\n internal func getObjects(\n _ objects: UnsafeMutablePointer<AnyObject>?,\n andKeys keys: UnsafeMutablePointer<AnyObject>?,\n count: Int\n ) {\n _precondition(count >= 0, "Invalid count")\n guard count > 0 else { return }\n let bridgedKeys = unsafe bridgeKeys()\n let bridgedValues = unsafe bridgeValues()\n var i = 0 // Current position in the output buffers\n\n defer { _fixLifetime(self) }\n\n switch unsafe (_UnmanagedAnyObjectArray(keys), _UnmanagedAnyObjectArray(objects)) {\n case (let unmanagedKeys?, let unmanagedObjects?):\n for unsafe bucket in unsafe native.hashTable {\n unsafe unmanagedKeys[i] = unsafe _key(at: bucket, bridgedKeys: bridgedKeys)\n unsafe unmanagedObjects[i] = unsafe _value(at: bucket, bridgedValues: bridgedValues)\n i += 1\n guard i < count else { break }\n }\n case (let unmanagedKeys?, nil):\n for unsafe bucket in unsafe native.hashTable {\n unsafe unmanagedKeys[i] = unsafe _key(at: bucket, bridgedKeys: bridgedKeys)\n i += 1\n guard i < count else { break }\n }\n case (nil, let unmanagedObjects?):\n for unsafe bucket in unsafe native.hashTable {\n unsafe unmanagedObjects[i] = unsafe _value(at: bucket, bridgedValues: bridgedValues)\n i += 1\n guard i < count else { break }\n }\n case (nil, nil):\n // Do nothing\n break\n }\n }\n\n @objc(enumerateKeysAndObjectsWithOptions:usingBlock:)\n internal func enumerateKeysAndObjects(\n options: Int,\n using block: @convention(block) (\n Unmanaged<AnyObject>,\n Unmanaged<AnyObject>,\n UnsafeMutablePointer<UInt8>\n ) -> Void) {\n let bridgedKeys = unsafe bridgeKeys()\n let bridgedValues = unsafe bridgeValues()\n\n defer { _fixLifetime(self) }\n\n var stop: UInt8 = 0\n for unsafe bucket in unsafe native.hashTable {\n let key = unsafe _key(at: bucket, bridgedKeys: bridgedKeys)\n let value = unsafe _value(at: bucket, bridgedValues: bridgedValues)\n unsafe block(\n Unmanaged.passUnretained(key),\n Unmanaged.passUnretained(value),\n &stop)\n if stop != 0 { return }\n }\n }\n\n @objc\n internal var count: Int {\n return native.count\n }\n\n @objc(countByEnumeratingWithState:objects:count:)\n internal func countByEnumerating(\n with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,\n objects: UnsafeMutablePointer<AnyObject>?,\n count: Int\n ) -> Int {\n defer { _fixLifetime(self) }\n let hashTable = unsafe native.hashTable\n\n var theState = unsafe state.pointee\n if unsafe theState.state == 0 {\n unsafe theState.state = 1 // Arbitrary non-zero value.\n unsafe theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)\n unsafe theState.mutationsPtr = _fastEnumerationStorageMutationsPtr\n unsafe theState.extra.0 = CUnsignedLong(hashTable.startBucket.offset)\n }\n\n // Test 'objects' rather than 'count' because (a) this is very rare anyway,\n // and (b) the optimizer should then be able to optimize away the\n // unwrapping check below.\n if unsafe _slowPath(objects == nil) {\n return 0\n }\n\n let unmanagedObjects = unsafe _UnmanagedAnyObjectArray(objects!)\n var bucket = unsafe _HashTable.Bucket(offset: Int(theState.extra.0))\n let endBucket = unsafe hashTable.endBucket\n unsafe _precondition(bucket == endBucket || hashTable.isOccupied(bucket),\n "Invalid fast enumeration state")\n var stored = 0\n\n // Only need to bridge once, so we can hoist it out of the loop.\n let bridgedKeys = unsafe bridgeKeys()\n for i in 0..<count {\n if bucket == endBucket { break }\n\n unsafe unmanagedObjects[i] = unsafe _key(at: bucket, bridgedKeys: bridgedKeys)\n stored += 1\n unsafe bucket = unsafe hashTable.occupiedBucket(after: bucket)\n }\n unsafe theState.extra.0 = CUnsignedLong(bucket.offset)\n unsafe state.pointee = theState\n return stored\n }\n}\n\n// NOTE: older runtimes called this struct _CocoaDictionary. The two\n// must coexist without conflicting ObjC class names from the nested\n// classes, so it was renamed. The old names must not be used in the new\n// runtime.\n@usableFromInline\n@frozen\ninternal struct __CocoaDictionary {\n @usableFromInline\n internal let object: AnyObject\n\n @inlinable\n internal init(_ object: __owned AnyObject) {\n self.object = object\n }\n}\n\n@available(*, unavailable)\nextension __CocoaDictionary: Sendable {}\n\nextension __CocoaDictionary {\n @usableFromInline\n internal func isEqual(to other: __CocoaDictionary) -> Bool {\n return _stdlib_NSObject_isEqual(self.object, other.object)\n }\n}\n\nextension __CocoaDictionary: _DictionaryBuffer {\n @usableFromInline\n internal typealias Key = AnyObject\n @usableFromInline\n internal typealias Value = AnyObject\n\n @usableFromInline // FIXME(cocoa-index): Should be inlinable\n internal var startIndex: Index {\n @_effects(releasenone)\n get {\n let allKeys = _stdlib_NSDictionary_allKeys(self.object)\n return Index(Index.Storage(self, allKeys), offset: 0)\n }\n }\n\n @usableFromInline // FIXME(cocoa-index): Should be inlinable\n internal var endIndex: Index {\n @_effects(releasenone)\n get {\n let allKeys = _stdlib_NSDictionary_allKeys(self.object)\n return Index(Index.Storage(self, allKeys), offset: allKeys.count)\n }\n }\n\n @usableFromInline // FIXME(cocoa-index): Should be inlinable\n @_effects(releasenone)\n internal func index(after index: Index) -> Index {\n validate(index)\n var result = index\n result._offset += 1\n return result\n }\n\n internal func validate(_ index: Index) {\n _precondition(index.storage.base.object === self.object, "Invalid index")\n _precondition(index._offset < index.storage.allKeys.count,\n "Attempt to access endIndex")\n }\n\n @usableFromInline // FIXME(cocoa-index): Should be inlinable\n internal func formIndex(after index: inout Index, isUnique: Bool) {\n validate(index)\n index._offset += 1\n }\n\n @usableFromInline // FIXME(cocoa-index): Should be inlinable\n @_effects(releasenone)\n internal func index(forKey key: Key) -> Index? {\n // Fast path that does not involve creating an array of all keys. In case\n // the key is present, this lookup is a penalty for the slow path, but the\n // potential savings are significant: we could skip a memory allocation and\n // a linear search.\n if lookup(key) == nil {\n return nil\n }\n\n let allKeys = _stdlib_NSDictionary_allKeys(object)\n for i in 0..<allKeys.count {\n if _stdlib_NSObject_isEqual(key, allKeys[i]) {\n return Index(Index.Storage(self, allKeys), offset: i)\n }\n }\n _internalInvariantFailure(\n "An NSDictionary key wasn't listed amongst its enumerated contents")\n }\n\n @usableFromInline\n internal var count: Int {\n let nsd = unsafe unsafeBitCast(object, to: _NSDictionary.self)\n return nsd.count\n }\n\n @usableFromInline\n internal func contains(_ key: Key) -> Bool {\n let nsd = unsafe unsafeBitCast(object, to: _NSDictionary.self)\n return nsd.object(forKey: key) != nil\n }\n\n @usableFromInline\n internal func lookup(_ key: Key) -> Value? {\n let nsd = unsafe unsafeBitCast(object, to: _NSDictionary.self)\n return nsd.object(forKey: key)\n }\n\n @usableFromInline // FIXME(cocoa-index): Should be inlinable\n @_effects(releasenone)\n internal func lookup(_ index: Index) -> (key: Key, value: Value) {\n _precondition(index.storage.base.object === self.object, "Invalid index")\n let key: Key = index.storage.allKeys[index._offset]\n let value: Value = unsafe index.storage.base.object.object(forKey: key)!\n return (key, value)\n }\n\n @usableFromInline // FIXME(cocoa-index): Make inlinable\n @_effects(releasenone)\n func key(at index: Index) -> Key {\n _precondition(index.storage.base.object === self.object, "Invalid index")\n return index.key\n }\n\n @usableFromInline // FIXME(cocoa-index): Make inlinable\n @_effects(releasenone)\n func value(at index: Index) -> Value {\n _precondition(index.storage.base.object === self.object, "Invalid index")\n let key = index.storage.allKeys[index._offset]\n return unsafe index.storage.base.object.object(forKey: key)!\n }\n}\n\nextension __CocoaDictionary {\n @inlinable\n internal func mapValues<Key: Hashable, Value, T>(\n _ transform: (Value) throws -> T\n ) rethrows -> _NativeDictionary<Key, T> {\n var result = _NativeDictionary<Key, T>(capacity: self.count)\n for (cocoaKey, cocoaValue) in self {\n let key = _forceBridgeFromObjectiveC(cocoaKey, Key.self)\n let value = _forceBridgeFromObjectiveC(cocoaValue, Value.self)\n try result.insertNew(key: key, value: transform(value))\n }\n return result\n }\n}\n\nextension __CocoaDictionary {\n @frozen\n @usableFromInline\n internal struct Index {\n internal var _storage: Builtin.BridgeObject\n internal var _offset: Int\n\n internal var storage: Storage {\n @inline(__always)\n get {\n let storage = _bridgeObject(toNative: _storage)\n return unsafe unsafeDowncast(storage, to: Storage.self)\n }\n }\n\n internal init(_ storage: Storage, offset: Int) {\n self._storage = _bridgeObject(fromNative: storage)\n self._offset = offset\n }\n }\n}\n\nextension __CocoaDictionary.Index {\n // FIXME(cocoa-index): Try using an NSEnumerator to speed this up.\n internal class Storage {\n // Assumption: we rely on NSDictionary.getObjects when being\n // repeatedly called on the same NSDictionary, returning items in the same\n // order every time.\n // Similarly, the same assumption holds for NSSet.allObjects.\n\n /// A reference to the NSDictionary, which owns members in `allObjects`,\n /// or `allKeys`, for NSSet and NSDictionary respectively.\n internal let base: __CocoaDictionary\n // FIXME: swift-3-indexing-model: try to remove the cocoa reference, but\n // make sure that we have a safety check for accessing `allKeys`. Maybe\n // move both into the dictionary/set itself.\n\n /// An unowned array of keys.\n internal var allKeys: _BridgingBuffer\n\n internal init(\n _ base: __owned __CocoaDictionary,\n _ allKeys: __owned _BridgingBuffer\n ) {\n self.base = base\n self.allKeys = allKeys\n }\n }\n}\n\nextension __CocoaDictionary.Index {\n @usableFromInline\n internal var handleBitPattern: UInt {\n @_effects(readonly)\n get {\n return unsafe unsafeBitCast(storage, to: UInt.self)\n }\n }\n\n @usableFromInline\n internal var dictionary: __CocoaDictionary {\n @_effects(releasenone)\n get {\n return storage.base\n }\n }\n}\n\nextension __CocoaDictionary.Index {\n @usableFromInline // FIXME(cocoa-index): Make inlinable\n @nonobjc\n internal var key: AnyObject {\n @_effects(readonly)\n get {\n _precondition(_offset < storage.allKeys.count,\n "Attempting to access Dictionary elements using an invalid index")\n return storage.allKeys[_offset]\n }\n }\n\n @usableFromInline // FIXME(cocoa-index): Make inlinable\n @nonobjc\n internal var age: Int32 {\n @_effects(readonly)\n get {\n return unsafe _HashTable.age(for: storage.base.object)\n }\n }\n}\n\nextension __CocoaDictionary.Index: Equatable {\n @usableFromInline // FIXME(cocoa-index): Make inlinable\n @_effects(readonly)\n internal static func == (\n lhs: __CocoaDictionary.Index,\n rhs: __CocoaDictionary.Index\n ) -> Bool {\n _precondition(lhs.storage.base.object === rhs.storage.base.object,\n "Comparing indexes from different dictionaries")\n return lhs._offset == rhs._offset\n }\n}\n\nextension __CocoaDictionary.Index: Comparable {\n @usableFromInline // FIXME(cocoa-index): Make inlinable\n @_effects(readonly)\n internal static func < (\n lhs: __CocoaDictionary.Index,\n rhs: __CocoaDictionary.Index\n ) -> Bool {\n _precondition(lhs.storage.base.object === rhs.storage.base.object,\n "Comparing indexes from different dictionaries")\n return lhs._offset < rhs._offset\n }\n}\n\nextension __CocoaDictionary: Sequence {\n @safe\n @usableFromInline\n final internal class Iterator {\n // Cocoa Dictionary iterator has to be a class, otherwise we cannot\n // guarantee that the fast enumeration struct is pinned to a certain memory\n // location.\n\n // This stored property should be stored at offset zero. There's code below\n // relying on this.\n internal var _fastEnumerationState: _SwiftNSFastEnumerationState =\n unsafe _makeSwiftNSFastEnumerationState()\n\n // This stored property should be stored right after\n // `_fastEnumerationState`. There's code below relying on this.\n internal var _fastEnumerationStackBuf = unsafe _CocoaFastEnumerationStackBuf()\n\n internal let base: __CocoaDictionary\n\n internal var _fastEnumerationStatePtr:\n UnsafeMutablePointer<_SwiftNSFastEnumerationState> {\n return unsafe _getUnsafePointerToStoredProperties(self).assumingMemoryBound(\n to: _SwiftNSFastEnumerationState.self)\n }\n\n internal var _fastEnumerationStackBufPtr:\n UnsafeMutablePointer<_CocoaFastEnumerationStackBuf> {\n return unsafe UnsafeMutableRawPointer(_fastEnumerationStatePtr + 1)\n .assumingMemoryBound(to: _CocoaFastEnumerationStackBuf.self)\n }\n\n // These members have to be word-sized integers, they cannot be limited to\n // Int8 just because our storage holds 16 elements: fast enumeration is\n // allowed to return inner pointers to the container, which can be much\n // larger.\n internal var itemIndex: Int = 0\n internal var itemCount: Int = 0\n\n internal init(_ base: __owned __CocoaDictionary) {\n self.base = base\n }\n }\n\n @usableFromInline\n @_effects(releasenone)\n internal __consuming func makeIterator() -> Iterator {\n return Iterator(self)\n }\n}\n\n@available(*, unavailable)\nextension __CocoaDictionary.Iterator: Sendable {}\n\nextension __CocoaDictionary.Iterator: IteratorProtocol {\n @usableFromInline\n internal typealias Element = (key: AnyObject, value: AnyObject)\n\n @usableFromInline\n internal func nextKey() -> AnyObject? {\n if itemIndex < 0 {\n return nil\n }\n let base = self.base\n if itemIndex == itemCount {\n let stackBufCount = unsafe _fastEnumerationStackBuf.count\n // We can't use `withUnsafeMutablePointer` here to get pointers to\n // properties, because doing so might introduce a writeback storage, but\n // fast enumeration relies on the pointer identity of the enumeration\n // state struct.\n itemCount = unsafe base.object.countByEnumerating(\n with: _fastEnumerationStatePtr,\n objects: UnsafeMutableRawPointer(_fastEnumerationStackBufPtr)\n .assumingMemoryBound(to: AnyObject.self),\n count: stackBufCount)\n if itemCount == 0 {\n itemIndex = -1\n return nil\n }\n itemIndex = 0\n }\n let itemsPtrUP =\n unsafe UnsafeMutableRawPointer(_fastEnumerationState.itemsPtr!)\n .assumingMemoryBound(to: AnyObject.self)\n let itemsPtr = unsafe _UnmanagedAnyObjectArray(itemsPtrUP)\n let key: AnyObject = unsafe itemsPtr[itemIndex]\n itemIndex += 1\n return key\n }\n\n @usableFromInline\n internal func next() -> Element? {\n guard let key = nextKey() else { return nil }\n let value: AnyObject = unsafe base.object.object(forKey: key)!\n return (key, value)\n }\n}\n\n//===--- Bridging ---------------------------------------------------------===//\n\nextension Dictionary {\n @inlinable\n public __consuming func _bridgeToObjectiveCImpl() -> AnyObject {\n guard _variant.isNative else {\n return _variant.asCocoa.object\n }\n return _variant.asNative.bridged()\n }\n\n /// Returns the native Dictionary hidden inside this NSDictionary;\n /// returns nil otherwise.\n public static func _bridgeFromObjectiveCAdoptingNativeStorageOf(\n _ s: __owned AnyObject\n ) -> Dictionary<Key, Value>? {\n\n // Try all three NSDictionary impls that we currently provide.\n\n if let deferred = s as? _SwiftDeferredNSDictionary<Key, Value> {\n return Dictionary(_native: deferred.native)\n }\n\n if let nativeStorage = unsafe s as? _DictionaryStorage<Key, Value> {\n return Dictionary(_native: unsafe _NativeDictionary(nativeStorage))\n }\n\n if unsafe s === __RawDictionaryStorage.empty {\n return Dictionary()\n }\n\n // FIXME: what if `s` is native storage, but for different key/value type?\n return nil\n }\n}\n\n#endif // _runtime(_ObjC)\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_DictionaryBridging.swift | cpp_apple_swift_stdlib_public_core_DictionaryBridging.swift | Swift | 27,041 | 0.95 | 0.082424 | 0.125698 | react-lib | 818 | 2023-08-12T07:09:40.082106 | MIT | false | 437d0ab18c11c5e9af7211b1f6be61f0 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Initializes a `Dictionary` from unique members.\n///\n/// Using a builder can be faster than inserting members into an empty\n/// `Dictionary`.\n@frozen\npublic // SPI(Foundation)\nstruct _DictionaryBuilder<Key: Hashable, Value> {\n @usableFromInline\n internal var _target: _NativeDictionary<Key, Value>\n @usableFromInline\n internal let _requestedCount: Int\n\n @inlinable\n public init(count: Int) {\n _target = _NativeDictionary(capacity: count)\n _requestedCount = count\n }\n\n @inlinable\n public mutating func add(key newKey: Key, value: Value) {\n _precondition(_target.count < _requestedCount,\n "Can't add more members than promised")\n _target._unsafeInsertNew(key: newKey, value: value)\n }\n\n @inlinable\n public __consuming func take() -> Dictionary<Key, Value> {\n _precondition(_target.count == _requestedCount,\n "The number of members added does not match the promised count")\n return Dictionary(_native: _target)\n }\n}\n\n@available(*, unavailable)\nextension _DictionaryBuilder: Sendable {}\n\nextension Dictionary {\n /// Creates a new dictionary with the specified capacity, then calls the given\n /// closure to initialize its contents.\n ///\n /// Foundation uses this initializer to bridge the contents of an NSDictionary\n /// instance without allocating a pair of intermediary buffers. Pass the\n /// required capacity and a closure that can initialize the dictionary's\n /// elements. The closure must return `c`, the number of initialized elements\n /// in both buffers, such that the elements in the range `0..<c` are\n /// initialized and the elements in the range `c..<capacity` are\n /// uninitialized.\n ///\n /// The resulting dictionary has a `count` less than or equal to `c`.\n /// If some of the initialized keys were duplicates, the actual count is less.\n /// This cannot happen for any other reasons or if `allowingDuplicates` is false.\n ///\n /// The buffers passed to the closure are only valid for the duration of the\n /// call. After the closure returns, this initializer moves all initialized\n /// elements into their correct buckets.\n ///\n /// - Parameters:\n /// - capacity: The capacity of the new dictionary.\n /// - allowingDuplicates: If false, then the caller guarantees that all keys\n /// are unique. This promise isn't verified -- if it turns out to be\n /// false, then the resulting dictionary won't be valid.\n /// - body: A closure that can initialize the dictionary's elements. This\n /// closure must return the count of the initialized elements, starting at\n /// the beginning of the buffer.\n @_alwaysEmitIntoClient // Introduced in 5.1\n public // SPI(Foundation)\n init(\n _unsafeUninitializedCapacity capacity: Int,\n allowingDuplicates: Bool,\n initializingWith initializer: (\n _ keys: UnsafeMutableBufferPointer<Key>,\n _ values: UnsafeMutableBufferPointer<Value>\n ) -> Int\n ) {\n self.init(_native: unsafe _NativeDictionary(\n _unsafeUninitializedCapacity: capacity,\n allowingDuplicates: allowingDuplicates,\n initializingWith: initializer))\n }\n}\n\nextension _NativeDictionary {\n @_alwaysEmitIntoClient // Introduced in 5.1\n internal init(\n _unsafeUninitializedCapacity capacity: Int,\n allowingDuplicates: Bool,\n initializingWith initializer: (\n _ keys: UnsafeMutableBufferPointer<Key>,\n _ values: UnsafeMutableBufferPointer<Value>\n ) -> Int\n ) {\n self.init(capacity: capacity)\n\n // If the capacity is 0, then our storage is the empty singleton. Those are\n // read only, so we shouldn't attempt to write to them.\n if capacity == 0 {\n let c = unsafe initializer(\n UnsafeMutableBufferPointer(start: nil, count: 0), \n UnsafeMutableBufferPointer(start: nil, count: 0))\n _precondition(c == 0)\n return\n }\n\n let initializedCount = unsafe initializer(\n UnsafeMutableBufferPointer(start: _keys, count: capacity),\n UnsafeMutableBufferPointer(start: _values, count: capacity))\n _precondition(initializedCount >= 0 && initializedCount <= capacity)\n unsafe _storage._count = initializedCount\n\n // Hash initialized elements and move each of them into their correct\n // buckets.\n //\n // - We have some number of unprocessed elements at the start of the\n // key/value buffers -- buckets up to and including `bucket`. Everything\n // in this region is either unprocessed or in use. There are no\n // uninitialized entries in it.\n //\n // - Everything after `bucket` is either uninitialized or in use. This\n // region works exactly like regular dictionary storage.\n //\n // - "in use" is tracked by the bitmap in `hashTable`, the same way it would\n // be for a working Dictionary.\n //\n // Each iteration of the loop below processes an unprocessed element, and/or\n // reduces the size of the unprocessed region, while ensuring the above\n // invariants.\n var bucket = _HashTable.Bucket(offset: initializedCount - 1)\n while bucket.offset >= 0 {\n if unsafe hashTable._isOccupied(bucket) {\n // We've moved an element here in a previous iteration.\n bucket.offset -= 1\n continue\n }\n // Find the target bucket for this entry and mark it as in use.\n let target: Bucket\n if _isDebugAssertConfiguration() || allowingDuplicates {\n let (b, found) = unsafe find(_keys[bucket.offset])\n if found {\n _internalInvariant(b != bucket)\n _precondition(allowingDuplicates, "Duplicate keys found")\n // Discard duplicate entry.\n unsafe uncheckedDestroy(at: bucket)\n unsafe _storage._count -= 1\n bucket.offset -= 1\n continue\n }\n unsafe hashTable.insert(b)\n target = b\n } else {\n let hashValue = unsafe self.hashValue(for: _keys[bucket.offset])\n unsafe target = unsafe hashTable.insertNew(hashValue: hashValue)\n }\n\n if target > bucket {\n // The target is outside the unprocessed region. We can simply move the\n // entry, leaving behind an uninitialized bucket.\n moveEntry(from: bucket, to: target)\n // Restore invariants by lowering the region boundary.\n bucket.offset -= 1\n } else if target == bucket {\n // Already in place.\n bucket.offset -= 1\n } else {\n // The target bucket is also in the unprocessed region. Swap the current\n // item into place, then try again with the swapped-in value, so that we\n // don't lose it.\n swapEntry(target, with: bucket)\n }\n }\n // When there are no more unprocessed entries, we're left with a valid\n // Dictionary.\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_DictionaryBuilder.swift | cpp_apple_swift_stdlib_public_core_DictionaryBuilder.swift | Swift | 7,212 | 0.95 | 0.097297 | 0.41954 | python-kit | 600 | 2023-08-28T21:38:36.832358 | BSD-3-Clause | false | 08cc8aec08f3aa535b6fe69ae972bd3e |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n//===--- Compiler conversion/casting entry points for Dictionary<K, V> ----===//\n\nextension Dictionary {\n @_alwaysEmitIntoClient @inlinable // Introduced in 5.1\n @inline(__always)\n internal init?<C: Collection>(\n _mapping source: C,\n allowingDuplicates: Bool,\n transform: (C.Element) -> (key: Key, value: Value)?\n ) {\n var target = _NativeDictionary<Key, Value>(capacity: source.count)\n if allowingDuplicates {\n for member in source {\n guard let (key, value) = transform(member) else { return nil }\n target._unsafeUpdate(key: key, value: value)\n }\n } else {\n for member in source {\n guard let (key, value) = transform(member) else { return nil }\n target._unsafeInsertNew(key: key, value: value)\n }\n }\n self.init(_native: target)\n }\n}\n\n/// Perform a non-bridged upcast that always succeeds.\n///\n/// - Precondition: `BaseKey` and `BaseValue` are base classes or base `@objc`\n/// protocols (such as `AnyObject`) of `DerivedKey` and `DerivedValue`,\n/// respectively.\n@inlinable\n@_unavailableInEmbedded\npublic func _dictionaryUpCast<DerivedKey, DerivedValue, BaseKey, BaseValue>(\n _ source: Dictionary<DerivedKey, DerivedValue>\n) -> Dictionary<BaseKey, BaseValue> {\n return Dictionary(\n _mapping: source,\n // String and NSString have different concepts of equality, so\n // NSString-keyed Dictionaries may generate key collisions when "upcasted"\n // to String. See rdar://problem/35995647\n allowingDuplicates: (BaseKey.self == String.self)\n ) { k, v in\n (k as! BaseKey, v as! BaseValue)\n }!\n}\n\n/// Called by the casting machinery.\n@_silgen_name("_swift_dictionaryDownCastIndirect")\n@_unavailableInEmbedded\ninternal func _dictionaryDownCastIndirect<SourceKey, SourceValue,\n TargetKey, TargetValue>(\n _ source: UnsafePointer<Dictionary<SourceKey, SourceValue>>,\n _ target: UnsafeMutablePointer<Dictionary<TargetKey, TargetValue>>) {\n unsafe target.initialize(to: _dictionaryDownCast(source.pointee))\n}\n\n/// Implements a forced downcast. This operation should have O(1) complexity.\n///\n/// The cast can fail if bridging fails. The actual checks and bridging can be\n/// deferred.\n///\n/// - Precondition: `DerivedKey` is a subtype of `BaseKey`, `DerivedValue` is\n/// a subtype of `BaseValue`, and all of these types are reference types.\n@inlinable\n@_unavailableInEmbedded\npublic func _dictionaryDownCast<BaseKey, BaseValue, DerivedKey, DerivedValue>(\n _ source: Dictionary<BaseKey, BaseValue>\n) -> Dictionary<DerivedKey, DerivedValue> {\n\n#if _runtime(_ObjC)\n if _isClassOrObjCExistential(BaseKey.self)\n && _isClassOrObjCExistential(BaseValue.self)\n && _isClassOrObjCExistential(DerivedKey.self)\n && _isClassOrObjCExistential(DerivedValue.self) {\n\n guard source._variant.isNative else {\n return Dictionary(\n _immutableCocoaDictionary: source._variant.asCocoa.object)\n }\n // Note: it is safe to treat the buffer as immutable here because\n // Dictionary will not mutate buffer with reference count greater than 1.\n return Dictionary(\n _immutableCocoaDictionary: source._variant.asNative.bridged())\n }\n#endif\n\n // Note: We can't delegate this call to _dictionaryDownCastConditional,\n // because we rely on as! to generate nice runtime errors when the downcast\n // fails.\n\n return Dictionary(\n _mapping: source,\n // String and NSString have different concepts of equality, so\n // NSString-keyed Dictionaries may generate key collisions when downcasted\n // to String. See rdar://problem/35995647\n allowingDuplicates: (DerivedKey.self == String.self)\n ) { k, v in\n (k as! DerivedKey, v as! DerivedValue)\n }!\n}\n\n/// Called by the casting machinery.\n@_silgen_name("_swift_dictionaryDownCastConditionalIndirect")\n@_unavailableInEmbedded\ninternal func _dictionaryDownCastConditionalIndirect<SourceKey, SourceValue,\n TargetKey, TargetValue>(\n _ source: UnsafePointer<Dictionary<SourceKey, SourceValue>>,\n _ target: UnsafeMutablePointer<Dictionary<TargetKey, TargetValue>>\n) -> Bool {\n if let result: Dictionary<TargetKey, TargetValue>\n = unsafe _dictionaryDownCastConditional(source.pointee) {\n unsafe target.initialize(to: result)\n return true\n }\n return false\n}\n\n/// Implements a conditional downcast.\n///\n/// If the cast fails, the function returns `nil`. All checks should be\n/// performed eagerly.\n///\n/// - Precondition: `DerivedKey` is a subtype of `BaseKey`, `DerivedValue` is\n/// a subtype of `BaseValue`, and all of these types are reference types.\n@inlinable\n@_unavailableInEmbedded\npublic func _dictionaryDownCastConditional<\n BaseKey, BaseValue, DerivedKey, DerivedValue\n>(\n _ source: Dictionary<BaseKey, BaseValue>\n) -> Dictionary<DerivedKey, DerivedValue>? {\n return Dictionary(\n _mapping: source,\n // String and NSString have different concepts of equality, so\n // NSString-keyed Dictionaries may generate key collisions when downcasted\n // to String. See rdar://problem/35995647\n allowingDuplicates: (DerivedKey.self == String.self)\n ) { k, v in\n guard\n let key = k as? DerivedKey,\n let value = v as? DerivedValue\n else {\n return nil\n }\n return (key, value)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_DictionaryCasting.swift | cpp_apple_swift_stdlib_public_core_DictionaryCasting.swift | Swift | 5,811 | 0.95 | 0.06875 | 0.328859 | python-kit | 387 | 2024-05-14T21:10:58.902241 | MIT | false | dcf3509c4b28fda4069f62ab3ddc7c66 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n/// An instance of this class has all `Dictionary` data tail-allocated.\n/// Enough bytes are allocated to hold the bitmap for marking valid entries,\n/// keys, and values. The data layout starts with the bitmap, followed by the\n/// keys, followed by the values.\n// NOTE: older runtimes called this class _RawDictionaryStorage. The two\n// must coexist without a conflicting ObjC class name, so it was\n// renamed. The old name must not be used in the new runtime.\n@_fixed_layout\n@usableFromInline\n@_objc_non_lazy_realization\n@unsafe\ninternal class __RawDictionaryStorage: __SwiftNativeNSDictionary {\n // NOTE: The precise layout of this type is relied on in the runtime to\n // provide a statically allocated empty singleton. See\n // stdlib/public/stubs/GlobalObjects.cpp for details.\n\n /// The current number of occupied entries in this dictionary.\n @usableFromInline\n @nonobjc\n internal final var _count: Int\n\n /// The maximum number of elements that can be inserted into this set without\n /// exceeding the hash table's maximum load factor.\n @usableFromInline\n @nonobjc\n internal final var _capacity: Int\n\n /// The scale of this dictionary. The number of buckets is 2 raised to the\n /// power of `scale`.\n @usableFromInline\n @nonobjc\n internal final var _scale: Int8\n\n /// The scale corresponding to the highest `reserveCapacity(_:)` call so far,\n /// or 0 if there were none. This may be used later to allow removals to\n /// resize storage.\n ///\n /// FIXME: <rdar://problem/18114559> Shrink storage on deletion\n @usableFromInline\n @nonobjc\n internal final var _reservedScale: Int8\n\n // Currently unused, set to zero.\n @nonobjc\n internal final var _extra: Int16\n\n /// A mutation count, enabling stricter index validation.\n @usableFromInline\n @nonobjc\n internal final var _age: Int32\n\n /// The hash seed used to hash elements in this dictionary instance.\n @usableFromInline\n internal final var _seed: Int\n\n /// A raw pointer to the start of the tail-allocated hash buffer holding keys.\n @usableFromInline\n @nonobjc\n internal final var _rawKeys: UnsafeMutableRawPointer\n\n /// A raw pointer to the start of the tail-allocated hash buffer holding\n /// values.\n @usableFromInline\n @nonobjc\n internal final var _rawValues: UnsafeMutableRawPointer\n\n // This type is made with allocWithTailElems, so no init is ever called.\n // But we still need to have an init to satisfy the compiler.\n @nonobjc\n internal init(_doNotCallMe: ()) {\n _internalInvariantFailure("This class cannot be directly initialized")\n }\n\n @inlinable\n @nonobjc\n internal final var _bucketCount: Int {\n @inline(__always) get { return unsafe 1 &<< _scale }\n }\n\n @inlinable\n @nonobjc\n internal final var _metadata: UnsafeMutablePointer<_HashTable.Word> {\n @inline(__always) get {\n let address = unsafe Builtin.projectTailElems(self, _HashTable.Word.self)\n return unsafe UnsafeMutablePointer(address)\n }\n }\n\n // The _HashTable struct contains pointers into tail-allocated storage, so\n // this is unsafe and needs `_fixLifetime` calls in the caller.\n @inlinable\n @nonobjc\n internal final var _hashTable: _HashTable {\n @inline(__always) get {\n return unsafe _HashTable(words: _metadata, bucketCount: _bucketCount)\n }\n }\n}\n\n/// The storage class for the singleton empty set.\n/// The single instance of this class is created by the runtime.\n// NOTE: older runtimes called this class _EmptyDictionarySingleton.\n// The two must coexist without a conflicting ObjC class name, so it was\n// renamed. The old name must not be used in the new runtime.\n@unsafe @_fixed_layout\n@usableFromInline\n@_objc_non_lazy_realization\ninternal class __EmptyDictionarySingleton: __RawDictionaryStorage {\n @nonobjc\n internal override init(_doNotCallMe: ()) {\n _internalInvariantFailure("This class cannot be directly initialized")\n }\n\n#if _runtime(_ObjC)\n @objc\n internal required init(\n objects: UnsafePointer<AnyObject?>,\n forKeys: UnsafeRawPointer,\n count: Int\n ) {\n _internalInvariantFailure("This class cannot be directly initialized")\n }\n#endif\n}\n\n#if _runtime(_ObjC)\nextension __EmptyDictionarySingleton: @unsafe _NSDictionaryCore {\n @objc(copyWithZone:)\n internal func copy(with zone: _SwiftNSZone?) -> AnyObject {\n return unsafe self\n }\n\n @objc\n internal var count: Int {\n return 0\n }\n\n @objc(countByEnumeratingWithState:objects:count:)\n internal func countByEnumerating(\n with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,\n objects: UnsafeMutablePointer<AnyObject>?, count: Int\n ) -> Int {\n // Even though we never do anything in here, we need to update the\n // state so that callers know we actually ran.\n\n var theState = unsafe state.pointee\n if unsafe theState.state == 0 {\n unsafe theState.state = 1 // Arbitrary non-zero value.\n unsafe theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)\n unsafe theState.mutationsPtr = _fastEnumerationStorageMutationsPtr\n }\n unsafe state.pointee = theState\n\n return 0\n }\n\n @objc(objectForKey:)\n internal func object(forKey aKey: AnyObject) -> AnyObject? {\n return nil\n }\n\n @objc(keyEnumerator)\n internal func keyEnumerator() -> _NSEnumerator {\n return __SwiftEmptyNSEnumerator()\n }\n\n @objc(getObjects:andKeys:count:)\n internal func getObjects(\n _ objects: UnsafeMutablePointer<AnyObject>?,\n andKeys keys: UnsafeMutablePointer<AnyObject>?,\n count: Int) {\n // Do nothing, we're empty\n }\n}\n#endif\n\n#if $Embedded\n// In embedded Swift, the stdlib is a .swiftmodule only without any .o/.a files,\n// to allow consuming it by clients with different LLVM codegen setting (-mcpu\n// flags, etc.), which means we cannot declare the singleton in a C/C++ file.\n//\n// TODO: We should figure out how to make this a constant so that it's placed in\n// non-writable memory (can't be a let, Builtin.addressof below requires a var).\n@unsafe\npublic var _swiftEmptyDictionarySingleton: (Int, Int, Int, Int, UInt8, UInt8, UInt16, UInt32, Int, Int, Int, Int) =\n (\n /*isa*/0, /*refcount*/-1, // HeapObject header\n /*count*/0,\n /*capacity*/0,\n /*scale*/0,\n /*reservedScale*/0,\n /*extra*/0,\n /*age*/0,\n /*seed*/0,\n /*rawKeys*/1,\n /*rawValues*/1,\n /*metadata*/~1\n )\n#endif\n\nextension __RawDictionaryStorage {\n /// The empty singleton that is used for every single Dictionary that is\n /// created without any elements. The contents of the storage should never\n /// be mutated.\n @inlinable\n @nonobjc\n internal static var empty: __EmptyDictionarySingleton {\n return unsafe Builtin.bridgeFromRawPointer(\n Builtin.addressof(&_swiftEmptyDictionarySingleton))\n }\n \n @_alwaysEmitIntoClient\n @inline(__always)\n internal final func uncheckedKey<Key: Hashable>(at bucket: _HashTable.Bucket) -> Key {\n defer { unsafe _fixLifetime(self) }\n unsafe _internalInvariant(_hashTable.isOccupied(bucket))\n let keys = unsafe _rawKeys.assumingMemoryBound(to: Key.self)\n return unsafe keys[bucket.offset]\n }\n\n @safe\n @_alwaysEmitIntoClient\n @inline(never)\n internal final func find<Key: Hashable>(_ key: Key) -> (bucket: _HashTable.Bucket, found: Bool) {\n return unsafe find(key, hashValue: key._rawHashValue(seed: _seed))\n }\n\n @safe\n @_alwaysEmitIntoClient\n @inline(never)\n internal final func find<Key: Hashable>(_ key: Key, hashValue: Int) -> (bucket: _HashTable.Bucket, found: Bool) {\n let hashTable = unsafe _hashTable\n var bucket = unsafe hashTable.idealBucket(forHashValue: hashValue)\n while unsafe hashTable._isOccupied(bucket) {\n if unsafe uncheckedKey(at: bucket) == key {\n return (bucket, true)\n }\n unsafe bucket = unsafe hashTable.bucket(wrappedAfter: bucket)\n }\n return (bucket, false)\n }\n}\n\n@unsafe @usableFromInline\nfinal internal class _DictionaryStorage<Key: Hashable, Value>\n : __RawDictionaryStorage, @unsafe _NSDictionaryCore {\n // This type is made with allocWithTailElems, so no init is ever called.\n // But we still need to have an init to satisfy the compiler.\n @nonobjc\n override internal init(_doNotCallMe: ()) {\n _internalInvariantFailure("This class cannot be directly initialized")\n }\n\n deinit {\n guard unsafe _count > 0 else { return }\n if !_isPOD(Key.self) {\n let keys = unsafe self._keys\n for unsafe bucket in unsafe _hashTable {\n unsafe (keys + bucket.offset).deinitialize(count: 1)\n }\n }\n if !_isPOD(Value.self) {\n let values = unsafe self._values\n for unsafe bucket in unsafe _hashTable {\n unsafe (values + bucket.offset).deinitialize(count: 1)\n }\n }\n unsafe _count = 0\n unsafe _fixLifetime(self)\n }\n\n @inlinable\n final internal var _keys: UnsafeMutablePointer<Key> {\n @inline(__always)\n get {\n return unsafe self._rawKeys.assumingMemoryBound(to: Key.self)\n }\n }\n\n @inlinable\n final internal var _values: UnsafeMutablePointer<Value> {\n @inline(__always)\n get {\n return unsafe self._rawValues.assumingMemoryBound(to: Value.self)\n }\n }\n\n internal var asNative: _NativeDictionary<Key, Value> {\n return unsafe _NativeDictionary(self)\n }\n\n#if _runtime(_ObjC)\n @objc\n internal required init(\n objects: UnsafePointer<AnyObject?>,\n forKeys: UnsafeRawPointer,\n count: Int\n ) {\n _internalInvariantFailure("This class cannot be directly initialized")\n }\n\n @objc(copyWithZone:)\n internal func copy(with zone: _SwiftNSZone?) -> AnyObject {\n return unsafe self\n }\n\n @objc\n internal var count: Int {\n return unsafe _count\n }\n\n @objc(keyEnumerator)\n internal func keyEnumerator() -> _NSEnumerator {\n return unsafe _SwiftDictionaryNSEnumerator<Key, Value>(asNative)\n }\n\n @objc(countByEnumeratingWithState:objects:count:)\n internal func countByEnumerating(\n with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,\n objects: UnsafeMutablePointer<AnyObject>?, count: Int\n ) -> Int {\n defer { unsafe _fixLifetime(self) }\n let hashTable = unsafe _hashTable\n\n var theState = unsafe state.pointee\n if unsafe theState.state == 0 {\n unsafe theState.state = 1 // Arbitrary non-zero value.\n unsafe theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects)\n unsafe theState.mutationsPtr = _fastEnumerationStorageMutationsPtr\n unsafe theState.extra.0 = CUnsignedLong(hashTable.startBucket.offset)\n }\n\n // Test 'objects' rather than 'count' because (a) this is very rare anyway,\n // and (b) the optimizer should then be able to optimize away the\n // unwrapping check below.\n if unsafe _slowPath(objects == nil) {\n return 0\n }\n\n let unmanagedObjects = unsafe _UnmanagedAnyObjectArray(objects!)\n var bucket = unsafe _HashTable.Bucket(offset: Int(theState.extra.0))\n let endBucket = unsafe hashTable.endBucket\n unsafe _precondition(bucket == endBucket || hashTable.isOccupied(bucket),\n "Invalid fast enumeration state")\n var stored = 0\n for i in 0..<count {\n if bucket == endBucket { break }\n\n let key = unsafe _keys[bucket.offset]\n unsafe unmanagedObjects[i] = _bridgeAnythingToObjectiveC(key)\n\n stored += 1\n unsafe bucket = unsafe hashTable.occupiedBucket(after: bucket)\n }\n unsafe theState.extra.0 = CUnsignedLong(bucket.offset)\n unsafe state.pointee = theState\n return stored\n }\n\n @objc(objectForKey:)\n internal func object(forKey aKey: AnyObject) -> AnyObject? {\n guard let nativeKey = _conditionallyBridgeFromObjectiveC(aKey, Key.self)\n else { return nil }\n\n let (bucket, found) = unsafe asNative.find(nativeKey)\n guard found else { return nil }\n let value = unsafe asNative.uncheckedValue(at: bucket)\n return _bridgeAnythingToObjectiveC(value)\n }\n\n @objc(getObjects:andKeys:count:)\n internal func getObjects(\n _ objects: UnsafeMutablePointer<AnyObject>?,\n andKeys keys: UnsafeMutablePointer<AnyObject>?,\n count: Int) {\n _precondition(count >= 0, "Invalid count")\n guard count > 0 else { return }\n var i = 0 // Current position in the output buffers\n switch unsafe (_UnmanagedAnyObjectArray(keys), _UnmanagedAnyObjectArray(objects)) {\n case (let unmanagedKeys?, let unmanagedObjects?):\n for (key, value) in unsafe asNative {\n unsafe unmanagedObjects[i] = _bridgeAnythingToObjectiveC(value)\n unsafe unmanagedKeys[i] = _bridgeAnythingToObjectiveC(key)\n i += 1\n guard i < count else { break }\n }\n case (let unmanagedKeys?, nil):\n for (key, _) in unsafe asNative {\n unsafe unmanagedKeys[i] = _bridgeAnythingToObjectiveC(key)\n i += 1\n guard i < count else { break }\n }\n case (nil, let unmanagedObjects?):\n for (_, value) in unsafe asNative {\n unsafe unmanagedObjects[i] = _bridgeAnythingToObjectiveC(value)\n i += 1\n guard i < count else { break }\n }\n case (nil, nil):\n // Do nothing.\n break\n }\n }\n#endif\n}\n\nextension _DictionaryStorage {\n @usableFromInline\n @_effects(releasenone)\n internal static func copy(\n original: __RawDictionaryStorage\n ) -> _DictionaryStorage {\n return unsafe allocate(\n scale: original._scale,\n age: original._age,\n seed: original._seed)\n }\n\n @usableFromInline\n @_effects(releasenone)\n static internal func resize(\n original: __RawDictionaryStorage,\n capacity: Int,\n move: Bool\n ) -> _DictionaryStorage {\n let scale = unsafe _HashTable.scale(forCapacity: capacity)\n return unsafe allocate(scale: scale, age: nil, seed: nil)\n }\n\n @usableFromInline\n @_effects(releasenone)\n static internal func allocate(capacity: Int) -> _DictionaryStorage {\n let scale = unsafe _HashTable.scale(forCapacity: capacity)\n return unsafe allocate(scale: scale, age: nil, seed: nil)\n }\n\n#if _runtime(_ObjC)\n @usableFromInline\n @_effects(releasenone)\n static internal func convert(\n _ cocoa: __CocoaDictionary,\n capacity: Int\n ) -> _DictionaryStorage {\n let scale = unsafe _HashTable.scale(forCapacity: capacity)\n let age = unsafe _HashTable.age(for: cocoa.object)\n return unsafe allocate(scale: scale, age: age, seed: nil)\n }\n#endif\n\n static internal func allocate(\n scale: Int8,\n age: Int32?,\n seed: Int?\n ) -> _DictionaryStorage {\n // The entry count must be representable by an Int value; hence the scale's\n // peculiar upper bound.\n _internalInvariant(scale >= 0 && scale < Int.bitWidth - 1)\n\n let bucketCount = (1 as Int) &<< scale\n let wordCount = unsafe _UnsafeBitset.wordCount(forCapacity: bucketCount)\n let storage = unsafe Builtin.allocWithTailElems_3(\n _DictionaryStorage<Key, Value>.self,\n wordCount._builtinWordValue, _HashTable.Word.self,\n bucketCount._builtinWordValue, Key.self,\n bucketCount._builtinWordValue, Value.self)\n\n let metadataAddr = unsafe Builtin.projectTailElems(storage, _HashTable.Word.self)\n let keysAddr = Builtin.getTailAddr_Word(\n metadataAddr, wordCount._builtinWordValue, _HashTable.Word.self,\n Key.self)\n let valuesAddr = Builtin.getTailAddr_Word(\n keysAddr, bucketCount._builtinWordValue, Key.self,\n Value.self)\n unsafe storage._count = 0\n unsafe storage._capacity = unsafe _HashTable.capacity(forScale: scale)\n unsafe storage._scale = scale\n unsafe storage._reservedScale = 0\n unsafe storage._extra = 0\n\n if let age = age {\n unsafe storage._age = age\n } else {\n // The default mutation count is simply a scrambled version of the storage\n // address.\n unsafe storage._age = Int32(\n truncatingIfNeeded: ObjectIdentifier(storage).hashValue)\n }\n\n unsafe storage._seed = unsafe seed ?? _HashTable.hashSeed(for: Builtin.castToNativeObject(storage), scale: scale)\n unsafe storage._rawKeys = UnsafeMutableRawPointer(keysAddr)\n unsafe storage._rawValues = UnsafeMutableRawPointer(valuesAddr)\n\n // Initialize hash table metadata.\n unsafe storage._hashTable.clear()\n return unsafe storage\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_DictionaryStorage.swift | cpp_apple_swift_stdlib_public_core_DictionaryStorage.swift | Swift | 16,563 | 0.95 | 0.088063 | 0.198675 | python-kit | 815 | 2024-04-01T16:36:45.018930 | BSD-3-Clause | false | eedcd10c40f62c325e5f99fea33699cc |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// This protocol is only used for compile-time checks that\n/// every buffer type implements all required operations.\ninternal protocol _DictionaryBuffer {\n associatedtype Key\n associatedtype Value\n associatedtype Index\n\n var startIndex: Index { get }\n var endIndex: Index { get }\n func index(after i: Index) -> Index\n func index(forKey key: Key) -> Index?\n var count: Int { get }\n\n func contains(_ key: Key) -> Bool\n func lookup(_ key: Key) -> Value?\n func lookup(_ index: Index) -> (key: Key, value: Value)\n func key(at index: Index) -> Key\n func value(at index: Index) -> Value\n}\n\nextension Dictionary {\n @usableFromInline\n @frozen\n @safe\n internal struct _Variant {\n @usableFromInline\n internal var object: _BridgeStorage<__RawDictionaryStorage>\n\n @inlinable\n @inline(__always)\n init(native: __owned _NativeDictionary<Key, Value>) {\n unsafe self.object = _BridgeStorage(native: native._storage)\n }\n\n @inlinable\n @inline(__always)\n init(dummy: Void) {\n#if _pointerBitWidth(_64) && !$Embedded\n unsafe self.object = _BridgeStorage(taggedPayload: 0)\n#elseif _pointerBitWidth(_32) || $Embedded\n self.init(native: _NativeDictionary())\n#else\n#error("Unknown platform")\n#endif\n }\n\n#if _runtime(_ObjC)\n @inlinable\n @inline(__always)\n init(cocoa: __owned __CocoaDictionary) {\n unsafe self.object = _BridgeStorage(objC: cocoa.object)\n }\n#endif\n }\n}\n\nextension Dictionary._Variant {\n#if _runtime(_ObjC)\n @usableFromInline @_transparent\n internal var guaranteedNative: Bool {\n return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0\n }\n#endif\n\n @inlinable\n internal mutating func isUniquelyReferenced() -> Bool {\n return unsafe object.isUniquelyReferencedUnflaggedNative()\n }\n\n#if _runtime(_ObjC)\n @usableFromInline @_transparent\n internal var isNative: Bool {\n if guaranteedNative { return true }\n return unsafe object.isUnflaggedNative\n }\n#endif\n\n @usableFromInline @_transparent\n internal var asNative: _NativeDictionary<Key, Value> {\n get {\n return unsafe _NativeDictionary<Key, Value>(object.unflaggedNativeInstance)\n }\n set {\n self = .init(native: newValue)\n }\n _modify {\n var native = unsafe _NativeDictionary<Key, Value>(object.unflaggedNativeInstance)\n self = .init(dummy: ())\n defer { unsafe object = .init(native: native._storage) }\n yield &native\n }\n }\n\n#if _runtime(_ObjC)\n @inlinable\n internal var asCocoa: __CocoaDictionary {\n return unsafe __CocoaDictionary(object.objCInstance)\n }\n#endif\n\n /// Reserves enough space for the specified number of elements to be stored\n /// without reallocating additional storage.\n internal mutating func reserveCapacity(_ capacity: Int) {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoa = asCocoa\n let capacity = Swift.max(cocoa.count, capacity)\n self = .init(native: _NativeDictionary(cocoa, capacity: capacity))\n return\n }\n#endif\n let isUnique = isUniquelyReferenced()\n asNative.reserveCapacity(capacity, isUnique: isUnique)\n }\n\n /// The number of elements that can be stored without expanding the current\n /// storage.\n ///\n /// For bridged storage, this is equal to the current count of the\n /// collection, since any addition will trigger a copy of the elements into\n /// newly allocated storage. For native storage, this is the element count\n /// at which adding any more elements will exceed the load factor.\n @inlinable\n internal var capacity: Int {\n#if _runtime(_ObjC)\n guard isNative else {\n return asCocoa.count\n }\n#endif\n return asNative.capacity\n }\n}\n\nextension Dictionary._Variant: _DictionaryBuffer {\n @usableFromInline\n internal typealias Element = (key: Key, value: Value)\n @usableFromInline\n internal typealias Index = Dictionary<Key, Value>.Index\n\n @inlinable\n internal var startIndex: Index {\n#if _runtime(_ObjC)\n guard isNative else {\n return Index(_cocoa: asCocoa.startIndex)\n }\n#endif\n return asNative.startIndex\n }\n\n @inlinable\n internal var endIndex: Index {\n#if _runtime(_ObjC)\n guard isNative else {\n return Index(_cocoa: asCocoa.endIndex)\n }\n#endif\n return asNative.endIndex\n }\n\n @inlinable\n internal func index(after index: Index) -> Index {\n#if _runtime(_ObjC)\n guard isNative else {\n return Index(_cocoa: asCocoa.index(after: index._asCocoa))\n }\n#endif\n return asNative.index(after: index)\n }\n\n @inlinable\n internal func formIndex(after index: inout Index) {\n#if _runtime(_ObjC)\n guard isNative else {\n let isUnique = index._isUniquelyReferenced()\n asCocoa.formIndex(after: &index._asCocoa, isUnique: isUnique)\n return\n }\n#endif\n index = asNative.index(after: index)\n }\n\n @inlinable\n @inline(__always)\n internal func index(forKey key: Key) -> Index? {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoaKey = _bridgeAnythingToObjectiveC(key)\n guard let index = asCocoa.index(forKey: cocoaKey) else { return nil }\n return Index(_cocoa: index)\n }\n#endif\n return asNative.index(forKey: key)\n }\n\n @inlinable\n internal var count: Int {\n @inline(__always)\n get {\n#if _runtime(_ObjC)\n guard isNative else {\n return asCocoa.count\n }\n#endif\n return asNative.count\n }\n }\n\n @inlinable\n @inline(__always)\n func contains(_ key: Key) -> Bool {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoaKey = _bridgeAnythingToObjectiveC(key)\n return asCocoa.contains(cocoaKey)\n }\n#endif\n return asNative.contains(key)\n }\n\n @inlinable\n @inline(__always)\n func lookup(_ key: Key) -> Value? {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoaKey = _bridgeAnythingToObjectiveC(key)\n guard let cocoaValue = asCocoa.lookup(cocoaKey) else { return nil }\n return _forceBridgeFromObjectiveC(cocoaValue, Value.self)\n }\n#endif\n return asNative.lookup(key)\n }\n\n @inlinable\n @inline(__always)\n func lookup(_ index: Index) -> (key: Key, value: Value) {\n#if _runtime(_ObjC)\n guard isNative else {\n let (cocoaKey, cocoaValue) = asCocoa.lookup(index._asCocoa)\n let nativeKey = _forceBridgeFromObjectiveC(cocoaKey, Key.self)\n let nativeValue = _forceBridgeFromObjectiveC(cocoaValue, Value.self)\n return (nativeKey, nativeValue)\n }\n#endif\n return asNative.lookup(index)\n }\n\n @inlinable\n @inline(__always)\n func key(at index: Index) -> Key {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoaKey = asCocoa.key(at: index._asCocoa)\n return _forceBridgeFromObjectiveC(cocoaKey, Key.self)\n }\n#endif\n return asNative.key(at: index)\n }\n\n @inlinable\n @inline(__always)\n func value(at index: Index) -> Value {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoaValue = asCocoa.value(at: index._asCocoa)\n return _forceBridgeFromObjectiveC(cocoaValue, Value.self)\n }\n#endif\n return asNative.value(at: index)\n }\n}\n\nextension Dictionary._Variant {\n @inlinable\n internal subscript(key: Key) -> Value? {\n @inline(__always)\n get {\n return lookup(key)\n }\n @inline(__always)\n _modify {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoa = asCocoa\n var native = _NativeDictionary<Key, Value>(\n cocoa, capacity: cocoa.count + 1)\n self = .init(native: native)\n yield &native[key, isUnique: true]\n return\n }\n#endif\n let isUnique = isUniquelyReferenced()\n yield &asNative[key, isUnique: isUnique]\n }\n }\n}\n\nextension Dictionary._Variant {\n /// Same as find(_:), except assume a corresponding key/value pair will be\n /// inserted if it doesn't already exist, and mutated if it does exist. When\n /// this function returns, the storage is guaranteed to be native, uniquely\n /// held, and with enough capacity for a single insertion (if the key isn't\n /// already in the dictionary.)\n @inlinable\n @inline(__always)\n internal mutating func mutatingFind(\n _ key: Key\n ) -> (bucket: _NativeDictionary<Key, Value>.Bucket, found: Bool) {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoa = asCocoa\n var native = _NativeDictionary<Key, Value>(\n cocoa, capacity: cocoa.count + 1)\n let result = native.mutatingFind(key, isUnique: true)\n self = .init(native: native)\n return result\n }\n#endif\n let isUnique = isUniquelyReferenced()\n return asNative.mutatingFind(key, isUnique: isUnique)\n }\n\n @inlinable\n @inline(__always)\n internal mutating func ensureUniqueNative() -> _NativeDictionary<Key, Value> {\n#if _runtime(_ObjC)\n guard isNative else {\n let native = _NativeDictionary<Key, Value>(asCocoa)\n self = .init(native: native)\n return native\n }\n#endif\n let isUnique = isUniquelyReferenced()\n if !isUnique {\n asNative.copy()\n }\n return asNative\n }\n\n @inlinable\n internal mutating func updateValue(\n _ value: __owned Value,\n forKey key: Key\n ) -> Value? {\n#if _runtime(_ObjC)\n guard isNative else {\n // Make sure we have space for an extra element.\n let cocoa = asCocoa\n var native = _NativeDictionary<Key, Value>(\n cocoa,\n capacity: cocoa.count + 1)\n let result = native.updateValue(value, forKey: key, isUnique: true)\n self = .init(native: native)\n return result\n }\n#endif\n let isUnique = self.isUniquelyReferenced()\n return asNative.updateValue(value, forKey: key, isUnique: isUnique)\n }\n\n @inlinable\n internal mutating func setValue(_ value: __owned Value, forKey key: Key) {\n#if _runtime(_ObjC)\n if !isNative {\n // Make sure we have space for an extra element.\n let cocoa = asCocoa\n self = .init(native: _NativeDictionary<Key, Value>(\n cocoa,\n capacity: cocoa.count + 1))\n }\n#endif\n let isUnique = self.isUniquelyReferenced()\n asNative.setValue(value, forKey: key, isUnique: isUnique)\n }\n\n @inlinable\n @_semantics("optimize.sil.specialize.generic.size.never")\n internal mutating func remove(at index: Index) -> Element {\n // FIXME(performance): fuse data migration and element deletion into one\n // operation.\n let native = ensureUniqueNative()\n let bucket = native.validatedBucket(for: index)\n return unsafe asNative.uncheckedRemove(at: bucket, isUnique: true)\n }\n\n @inlinable\n internal mutating func removeValue(forKey key: Key) -> Value? {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoaKey = _bridgeAnythingToObjectiveC(key)\n let cocoa = asCocoa\n guard cocoa.lookup(cocoaKey) != nil else { return nil }\n var native = _NativeDictionary<Key, Value>(cocoa)\n let (bucket, found) = native.find(key)\n _precondition(found, "Bridging did not preserve equality")\n let old = unsafe native.uncheckedRemove(at: bucket, isUnique: true).value\n self = .init(native: native)\n return old\n }\n#endif\n let (bucket, found) = asNative.find(key)\n guard found else { return nil }\n let isUnique = isUniquelyReferenced()\n return unsafe asNative.uncheckedRemove(at: bucket, isUnique: isUnique).value\n }\n\n @inlinable\n @_semantics("optimize.sil.specialize.generic.size.never")\n internal mutating func removeAll(keepingCapacity keepCapacity: Bool) {\n if !keepCapacity {\n self = .init(native: _NativeDictionary())\n return\n }\n guard count > 0 else { return }\n\n#if _runtime(_ObjC)\n guard isNative else {\n self = .init(native: _NativeDictionary(capacity: asCocoa.count))\n return\n }\n#endif\n let isUnique = isUniquelyReferenced()\n asNative.removeAll(isUnique: isUnique)\n }\n}\n\nextension Dictionary._Variant {\n /// Returns an iterator over the `(Key, Value)` pairs.\n ///\n /// - Complexity: O(1).\n @inlinable\n @inline(__always)\n __consuming internal func makeIterator() -> Dictionary<Key, Value>.Iterator {\n#if _runtime(_ObjC)\n guard isNative else {\n return Dictionary.Iterator(_cocoa: asCocoa.makeIterator())\n }\n#endif\n return Dictionary.Iterator(_native: asNative.makeIterator())\n }\n}\n\nextension Dictionary._Variant {\n @inlinable\n internal func mapValues<T>(\n _ transform: (Value) throws -> T\n ) rethrows -> _NativeDictionary<Key, T> {\n#if _runtime(_ObjC)\n guard isNative else {\n return try asCocoa.mapValues(transform)\n }\n#endif\n return try asNative.mapValues(transform)\n }\n\n @inlinable\n internal mutating func merge<S: Sequence>(\n _ keysAndValues: __owned S,\n uniquingKeysWith combine: (Value, Value) throws -> Value\n ) rethrows where S.Element == (Key, Value) {\n#if _runtime(_ObjC)\n guard isNative else {\n var native = _NativeDictionary<Key, Value>(asCocoa)\n try native.merge(\n keysAndValues,\n isUnique: true,\n uniquingKeysWith: combine)\n self = .init(native: native)\n return\n }\n#endif\n let isUnique = isUniquelyReferenced()\n try asNative.merge(\n keysAndValues,\n isUnique: isUnique,\n uniquingKeysWith: combine)\n }\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_DictionaryVariant.swift | cpp_apple_swift_stdlib_public_core_DictionaryVariant.swift | Swift | 13,486 | 0.95 | 0.097959 | 0.206208 | node-utils | 545 | 2023-07-24T01:36:52.505826 | MIT | false | ef2f6c78a15b452e29c62bd38bfbce92 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2015 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// MARK: Diff application to RangeReplaceableCollection\n\n@available(SwiftStdlib 5.1, *)\nextension CollectionDifference {\n fileprivate func _fastEnumeratedApply(\n _ consume: (Change) throws -> Void\n ) rethrows {\n let totalRemoves = removals.count\n let totalInserts = insertions.count\n var enumeratedRemoves = 0\n var enumeratedInserts = 0\n\n while enumeratedRemoves < totalRemoves || enumeratedInserts < totalInserts {\n let change: Change\n if enumeratedRemoves < removals.count && enumeratedInserts < insertions.count {\n let removeOffset = removals[enumeratedRemoves]._offset\n let insertOffset = insertions[enumeratedInserts]._offset\n if removeOffset - enumeratedRemoves <= insertOffset - enumeratedInserts {\n change = removals[enumeratedRemoves]\n } else {\n change = insertions[enumeratedInserts]\n }\n } else if enumeratedRemoves < totalRemoves {\n change = removals[enumeratedRemoves]\n } else if enumeratedInserts < totalInserts {\n change = insertions[enumeratedInserts]\n } else {\n // Not reached, loop should have exited.\n preconditionFailure()\n }\n\n try consume(change)\n\n switch change {\n case .remove(_, _, _):\n enumeratedRemoves += 1\n case .insert(_, _, _):\n enumeratedInserts += 1\n }\n }\n }\n}\n\n// Error type allows the use of throw to unroll state on application failure\nprivate enum _ApplicationError : Error { case failed }\n\nextension RangeReplaceableCollection {\n /// Applies the given difference to this collection.\n ///\n /// - Parameter difference: The difference to be applied.\n ///\n /// - Returns: An instance representing the state of the receiver with the\n /// difference applied, or `nil` if the difference is incompatible with\n /// the receiver's state.\n ///\n /// - Complexity: O(*n* + *c*), where *n* is `self.count` and *c* is the\n /// number of changes contained by the parameter.\n @available(SwiftStdlib 5.1, *)\n public func applying(_ difference: CollectionDifference<Element>) -> Self? {\n\n func append(\n into target: inout Self,\n contentsOf source: Self,\n from index: inout Self.Index, count: Int\n ) throws {\n let start = index\n if !source.formIndex(&index, offsetBy: count, limitedBy: source.endIndex) {\n throw _ApplicationError.failed\n }\n target.append(contentsOf: source[start..<index])\n }\n\n var result = Self()\n do {\n var enumeratedRemoves = 0\n var enumeratedInserts = 0\n var enumeratedOriginals = 0\n var currentIndex = self.startIndex\n try difference._fastEnumeratedApply { change in\n switch change {\n case .remove(offset: let offset, element: _, associatedWith: _):\n let origCount = offset - enumeratedOriginals\n try append(into: &result, contentsOf: self, from: ¤tIndex, count: origCount)\n if currentIndex == self.endIndex {\n // Removing nonexistent element off the end of the collection\n throw _ApplicationError.failed\n }\n enumeratedOriginals += origCount + 1 // Removal consumes an original element\n currentIndex = self.index(after: currentIndex)\n enumeratedRemoves += 1\n case .insert(offset: let offset, element: let element, associatedWith: _):\n let origCount = (offset + enumeratedRemoves - enumeratedInserts) - enumeratedOriginals\n try append(into: &result, contentsOf: self, from: ¤tIndex, count: origCount)\n result.append(element)\n enumeratedOriginals += origCount\n enumeratedInserts += 1\n }\n _internalInvariant(enumeratedOriginals <= self.count)\n }\n if currentIndex < self.endIndex {\n result.append(contentsOf: self[currentIndex...])\n }\n _internalInvariant(result.count == self.count + enumeratedInserts - enumeratedRemoves)\n } catch {\n return nil\n }\n\n return result\n }\n}\n\n// MARK: Definition of API\n\nextension BidirectionalCollection {\n /// Returns the difference needed to produce this collection's ordered\n /// elements from the given collection, using the given predicate as an\n /// equivalence test.\n ///\n /// This function does not infer element moves. If you need to infer moves,\n /// call the `inferringMoves()` method on the resulting difference.\n ///\n /// - Parameters:\n /// - other: The base state.\n /// - areEquivalent: A closure that returns a Boolean value indicating\n /// whether two elements are equivalent.\n ///\n /// - Returns: The difference needed to produce the receiver's state from\n /// the parameter's state.\n ///\n /// - Complexity: Worst case performance is O(*n* * *m*), where *n* is the\n /// count of this collection and *m* is `other.count`. You can expect\n /// faster execution when the collections share many common elements.\n @available(SwiftStdlib 5.1, *)\n public func difference<C: BidirectionalCollection>(\n from other: C,\n by areEquivalent: (C.Element, Element) -> Bool\n ) -> CollectionDifference<Element>\n where C.Element == Self.Element {\n return _myers(from: other, to: self, using: areEquivalent)\n }\n}\n\nextension BidirectionalCollection where Element: Equatable {\n /// Returns the difference needed to produce this collection's ordered\n /// elements from the given collection.\n ///\n /// This function does not infer element moves. If you need to infer moves,\n /// call the `inferringMoves()` method on the resulting difference.\n ///\n /// - Parameters:\n /// - other: The base state.\n ///\n /// - Returns: The difference needed to produce this collection's ordered\n /// elements from the given collection.\n ///\n /// - Complexity: Worst case performance is O(*n* * *m*), where *n* is the\n /// count of this collection and *m* is `other.count`. You can expect\n /// faster execution when the collections share many common elements, or\n /// if `Element` conforms to `Hashable`.\n @available(SwiftStdlib 5.1, *)\n public func difference<C: BidirectionalCollection>(\n from other: C\n ) -> CollectionDifference<Element> where C.Element == Self.Element {\n return difference(from: other, by: ==)\n }\n}\n\n// MARK: Internal implementation\n\n// _V is a rudimentary type made to represent the rows of the triangular matrix\n// type used by the Myer's algorithm.\n//\n// This type is basically an array that only supports indexes in the set\n// `stride(from: -d, through: d, by: 2)` where `d` is the depth of this row in\n// the matrix `d` is always known at allocation-time, and is used to preallocate\n// the structure.\nprivate struct _V {\n\n private var a: [Int]\n#if INTERNAL_CHECKS_ENABLED\n private let isOdd: Bool\n#endif\n\n init(maxIndex largest: Int) {\n#if INTERNAL_CHECKS_ENABLED\n _internalInvariant(largest >= 0)\n isOdd = largest % 2 == 1\n#endif\n a = [Int](repeating: 0, count: largest + 1)\n }\n\n // The way negative indexes are implemented is by interleaving them in the empty slots between the valid positive indexes\n @inline(__always) private static func transform(_ index: Int) -> Int {\n // -3, -1, 1, 3 -> 3, 1, 0, 2 -> 0...3\n // -2, 0, 2 -> 2, 0, 1 -> 0...2\n return (index <= 0 ? -index : index &- 1)\n }\n\n subscript(index: Int) -> Int {\n get {\n#if INTERNAL_CHECKS_ENABLED\n _internalInvariant(isOdd == (index % 2 != 0))\n#endif\n return a[_V.transform(index)]\n }\n set(newValue) {\n#if INTERNAL_CHECKS_ENABLED\n _internalInvariant(isOdd == (index % 2 != 0))\n#endif\n a[_V.transform(index)] = newValue\n }\n }\n}\n\n@available(SwiftStdlib 5.1, *)\nprivate func _myers<C,D>(\n from old: C, to new: D,\n using cmp: (C.Element, D.Element) -> Bool\n) -> CollectionDifference<C.Element>\n where\n C: BidirectionalCollection,\n D: BidirectionalCollection,\n C.Element == D.Element\n{\n\n // Core implementation of the algorithm described at http://www.xmailserver.org/diff2.pdf\n // Variable names match those used in the paper as closely as possible\n func _descent(from a: UnsafeBufferPointer<C.Element>, to b: UnsafeBufferPointer<D.Element>) -> [_V] {\n let n = a.count\n let m = b.count\n let max = n + m\n\n var result = [_V]()\n var v = _V(maxIndex: 1)\n v[1] = 0\n\n var x = 0\n var y = 0\n iterator: for d in 0...max {\n let prev_v = v\n result.append(v)\n v = _V(maxIndex: d)\n\n // The code in this loop is _very_ hot—the loop bounds increases in terms\n // of the iterator of the outer loop!\n for k in stride(from: -d, through: d, by: 2) {\n if k == -d {\n x = prev_v[k &+ 1]\n } else {\n let km = prev_v[k &- 1]\n\n if k != d {\n let kp = prev_v[k &+ 1]\n if km < kp {\n x = kp\n } else {\n x = km &+ 1\n }\n } else {\n x = km &+ 1\n }\n }\n y = x &- k\n\n while x < n && y < m {\n if unsafe !cmp(a[x], b[y]) {\n break;\n }\n x &+= 1\n y &+= 1\n }\n\n v[k] = x\n\n if x >= n && y >= m {\n break iterator\n }\n }\n if x >= n && y >= m {\n break\n }\n }\n\n _internalInvariant(x >= n && y >= m)\n\n return result\n }\n\n // Backtrack through the trace generated by the Myers descent to produce the changes that make up the diff\n func _formChanges(\n from a: UnsafeBufferPointer<C.Element>,\n to b: UnsafeBufferPointer<C.Element>,\n using trace: [_V]\n ) -> [CollectionDifference<C.Element>.Change] {\n var changes = [CollectionDifference<C.Element>.Change]()\n changes.reserveCapacity(trace.count)\n\n var x = a.count\n var y = b.count\n for d in stride(from: trace.count &- 1, to: 0, by: -1) {\n let v = trace[d]\n let k = x &- y\n let prev_k = (k == -d || (k != d && v[k &- 1] < v[k &+ 1])) ? k &+ 1 : k &- 1\n let prev_x = v[prev_k]\n let prev_y = prev_x &- prev_k\n\n while x > prev_x && y > prev_y {\n // No change at this position.\n x &-= 1\n y &-= 1\n }\n\n _internalInvariant((x == prev_x && y > prev_y) || (y == prev_y && x > prev_x))\n if y != prev_y {\n unsafe changes.append(.insert(offset: prev_y, element: b[prev_y], associatedWith: nil))\n } else {\n unsafe changes.append(.remove(offset: prev_x, element: a[prev_x], associatedWith: nil))\n }\n\n x = prev_x\n y = prev_y\n }\n\n return changes\n }\n\n /* Splatting the collections into contiguous storage has two advantages:\n *\n * 1) Subscript access is much faster\n * 2) Subscript index becomes Int, matching the iterator types in the algorithm\n *\n * Combined, these effects dramatically improves performance when\n * collections differ significantly, without unduly degrading runtime when\n * the parameters are very similar.\n *\n * In terms of memory use, the linear cost of creating a ContiguousArray (when\n * necessary) is significantly less than the worst-case n² memory use of the\n * descent algorithm.\n */\n func _withContiguousStorage<Col: Collection, R>(\n for values: Col,\n _ body: (UnsafeBufferPointer<Col.Element>) throws -> R\n ) rethrows -> R {\n if let result = try values.withContiguousStorageIfAvailable(body) { return result }\n let array = ContiguousArray(values)\n return try unsafe array.withUnsafeBufferPointer(body)\n }\n\n return unsafe _withContiguousStorage(for: old) { a in\n return unsafe _withContiguousStorage(for: new) { b in\n return unsafe CollectionDifference(_formChanges(from: a, to: b, using:_descent(from: a, to: b)))!\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Diffing.swift | cpp_apple_swift_stdlib_public_core_Diffing.swift | Swift | 12,151 | 0.95 | 0.117486 | 0.29878 | vue-tools | 802 | 2023-09-01T13:54:32.922218 | GPL-3.0 | false | ac80c6f252796947e088111f2d68a871 |
//===--- DiscontiguousSlice.swift -----------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A collection wrapper that provides access to the elements of a collection,\n/// indexed by a set of indices.\n@available(SwiftStdlib 6.0, *)\npublic struct DiscontiguousSlice<Base: Collection> {\n internal var _base: Base\n \n /// The set of subranges that are available through this discontiguous slice.\n public let subranges: RangeSet<Base.Index>\n\n /// The collection that the indexed collection wraps.\n public var base: Base {\n return _base\n }\n\n @usableFromInline\n internal init(_base: Base, subranges: RangeSet<Base.Index>) {\n self._base = _base\n self.subranges = subranges\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice: Sendable\nwhere Base: Sendable, Base.Index: Sendable {}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice: Equatable where Base.Element: Equatable {\n public static func ==(lhs: Self, rhs: Self) -> Bool {\n lhs.elementsEqual(rhs)\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice: Hashable where Base.Element: Hashable {\n public func hash(into hasher: inout Hasher) {\n hasher.combine(count) // delimiter; do not remove\n for element in self {\n hasher.combine(element)\n }\n }\n}\n\n@available(SwiftStdlib 6.0, *)\n@_unavailableInEmbedded\nextension DiscontiguousSlice: CustomStringConvertible {\n public var description: String {\n _makeCollectionDescription()\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice {\n /// A position in a `DiscontiguousSlice`.\n public struct Index {\n /// The index of the range that contains `base`.\n internal let _rangeOffset: Int\n \n /// The position of this index in the base collection.\n public let base: Base.Index\n\n internal init(_rangeOffset: Int, base: Base.Index) {\n self._rangeOffset = _rangeOffset\n self.base = base\n }\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice.Index: Equatable {\n public static func == (left: Self, right: Self) -> Bool {\n left.base == right.base\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice.Index: Hashable where Base.Index: Hashable {\n public func hash(into hasher: inout Hasher) {\n hasher.combine(base)\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice.Index: Comparable {\n public static func < (left: Self, right: Self) -> Bool {\n left.base < right.base\n }\n}\n\n@available(SwiftStdlib 6.0, *)\n@_unavailableInEmbedded\nextension DiscontiguousSlice.Index: CustomStringConvertible {\n public var description: String {\n "<base: \(String(reflecting: base)), rangeOffset: \(_rangeOffset)>"\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice.Index: Sendable where Base.Index: Sendable {}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice: Sequence {\n public typealias Element = Base.Element\n public typealias Iterator = IndexingIterator<Self>\n\n public func _customContainsEquatableElement(_ element: Element) -> Bool? {\n _customIndexOfEquatableElement(element).map { $0 != nil }\n }\n\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n var result: ContiguousArray<Element> = []\n for range in subranges.ranges {\n result.append(contentsOf: base[range])\n }\n return result\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice: Collection {\n public typealias SubSequence = Self\n public typealias Indices = DefaultIndices<Self>\n \n public var startIndex: Index {\n subranges.isEmpty\n ? endIndex\n : Index(_rangeOffset: 0, base: subranges.ranges[0].lowerBound)\n }\n \n public var endIndex: Index {\n Index(_rangeOffset: subranges.ranges.endIndex, base: _base.endIndex)\n }\n \n public var count: Int {\n var c = 0\n for range in subranges.ranges {\n c += base[range].count\n }\n return c\n }\n\n public var isEmpty: Bool {\n subranges.isEmpty\n }\n\n public func distance(from start: Index, to end: Index) -> Int {\n let ranges = subranges.ranges[start._rangeOffset ... end._rangeOffset]\n guard ranges.count > 1 else {\n return _base[ranges[0]].distance(from: start.base, to: end.base)\n }\n let firstRange = ranges.first!\n let lastRange = ranges.last!\n let head = _base[firstRange].distance(\n from: start.base, to: firstRange.upperBound)\n let tail = _base[lastRange].distance(\n from: lastRange.lowerBound, to: end.base)\n let middle = ranges[1 ..< (ranges.endIndex - 1)].reduce(0) {\n $0 + _base[$1].count\n }\n return head + middle + tail\n }\n \n public func index(after i: Index) -> Index {\n // Note: index validation performed by the underlying collections only\n let currentRange = subranges.ranges[i._rangeOffset]\n let nextIndex = _base[currentRange].index(after: i.base)\n if nextIndex < currentRange.upperBound {\n return Index(_rangeOffset: i._rangeOffset, base: nextIndex)\n }\n \n let nextOffset = i._rangeOffset + 1\n guard nextOffset < subranges.ranges.endIndex else {\n return endIndex\n }\n\n return Index(\n _rangeOffset: nextOffset, base: subranges.ranges[nextOffset].lowerBound)\n }\n\n public subscript(i: Index) -> Base.Element {\n // Note: index validation performed by the base collection only\n _base[subranges.ranges[i._rangeOffset]][i.base]\n }\n \n public subscript(bounds: Range<Index>) -> DiscontiguousSlice<Base> {\n let baseBounds = bounds.lowerBound.base ..< bounds.upperBound.base\n let baseSlice = base[baseBounds]\n let baseAdjustedBounds = baseSlice.startIndex ..< baseSlice.endIndex\n let subset = subranges.intersection(RangeSet(baseAdjustedBounds))\n return DiscontiguousSlice<Base>(_base: base, subranges: subset)\n }\n\n @usableFromInline\n internal func _index(of baseIndex: Base.Index) -> Index? {\n let rangeOffset = subranges.ranges\n ._partitioningIndex { $0.upperBound >= baseIndex }\n let subrange = subranges.ranges[rangeOffset]\n guard subrange.contains(baseIndex) else {\n return nil\n }\n return Index(_rangeOffset: rangeOffset, base: baseIndex)\n }\n\n public func _customIndexOfEquatableElement(_ element: Element) -> Index?? {\n var definite = true\n for (i, range) in subranges.ranges.enumerated() {\n guard let baseResult = _base[range]\n ._customIndexOfEquatableElement(element) else {\n definite = false\n continue\n }\n guard let baseIndex = baseResult else {\n continue\n }\n return Index(_rangeOffset: i, base: baseIndex)\n }\n if definite {\n return .some(nil)\n } else {\n return nil\n }\n }\n\n public func _customLastIndexOfEquatableElement(\n _ element: Element\n ) -> Index?? {\n var definite = true\n for (i, range) in subranges.ranges.enumerated().reversed() {\n guard let baseResult = _base[range]\n ._customLastIndexOfEquatableElement(element) else {\n definite = false\n continue\n }\n guard let baseIndex = baseResult else {\n continue\n }\n return Index(_rangeOffset: i, base: baseIndex)\n }\n if definite {\n return .some(nil)\n } else {\n return nil\n }\n }\n\n public func _failEarlyRangeCheck(\n _ index: Index, bounds: Range<Index>\n ) {\n let baseBounds = bounds.lowerBound.base ..< bounds.upperBound.base\n let offsetBounds = bounds.lowerBound._rangeOffset ..<\n bounds.upperBound._rangeOffset\n _base._failEarlyRangeCheck(index.base, bounds: baseBounds)\n _precondition(offsetBounds.contains(index._rangeOffset))\n if index._rangeOffset == endIndex._rangeOffset {\n _precondition(index.base == _base.endIndex)\n } else {\n _precondition(subranges.ranges[index._rangeOffset].contains(index.base))\n }\n }\n\n public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) {\n let baseBounds = bounds.lowerBound.base ... bounds.upperBound.base\n let offsetBounds = bounds.lowerBound._rangeOffset ...\n bounds.upperBound._rangeOffset\n _base._failEarlyRangeCheck(index.base, bounds: baseBounds)\n _precondition(offsetBounds.contains(index._rangeOffset))\n if index._rangeOffset == endIndex._rangeOffset {\n _precondition(index.base == _base.endIndex)\n } else {\n _precondition(subranges.ranges[index._rangeOffset].contains(index.base))\n }\n }\n\n public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {\n let baseBounds = bounds.lowerBound.base ..< bounds.upperBound.base\n let baseRange = range.lowerBound.base ..< range.upperBound.base\n let offsetBounds = bounds.lowerBound._rangeOffset ..<\n bounds.upperBound._rangeOffset\n let offsetRange = range.lowerBound._rangeOffset ..<\n range.upperBound._rangeOffset\n\n _base._failEarlyRangeCheck(baseRange, bounds: baseBounds)\n _precondition(offsetBounds.contains(offsetRange.lowerBound))\n _precondition(offsetRange.upperBound <= offsetBounds.upperBound)\n\n if offsetRange.lowerBound == endIndex._rangeOffset {\n _precondition(baseRange.lowerBound == _base.endIndex)\n } else {\n _precondition(\n subranges.ranges[offsetRange.lowerBound].contains(baseRange.lowerBound))\n }\n\n if offsetRange.upperBound == endIndex._rangeOffset {\n _precondition(baseRange.upperBound == _base.endIndex)\n } else {\n _precondition(\n subranges.ranges[offsetRange.upperBound].contains(baseRange.upperBound))\n }\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice: BidirectionalCollection\n where Base: BidirectionalCollection\n{\n public func index(before i: Index) -> Index {\n _precondition(i > startIndex, "Can't move index before startIndex")\n\n if i.base == base.endIndex ||\n i.base == subranges.ranges[i._rangeOffset].lowerBound {\n // Go to next subrange\n let nextOffset = i._rangeOffset - 1\n let nextRange = subranges.ranges[nextOffset]\n let nextBase = base[nextRange].index(before: nextRange.upperBound)\n return Index(_rangeOffset: nextOffset, base: nextBase)\n } else {\n // Move within current subrange\n let currentRange = subranges.ranges[i._rangeOffset]\n let nextBase = base[currentRange].index(before: i.base)\n return Index(_rangeOffset: i._rangeOffset, base: nextBase)\n }\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension DiscontiguousSlice where Base: MutableCollection {\n /// Accesses the element at the specified position.\n ///\n /// For example, you can replace an element of an array by using its\n /// subscript.\n ///\n /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// streets[1] = "Butler"\n /// print(streets[1])\n /// // Prints "Butler"\n ///\n /// You can subscript a collection with any valid index other than the\n /// collection's end index. The end index refers to the position one\n /// past the last element of a collection, so it doesn't correspond with an\n /// element.\n ///\n /// - Parameter position: The position of the element to access. `position`\n /// must be a valid index of the collection that is not equal to the\n /// `endIndex` property.\n ///\n /// - Complexity: O(1)\n public subscript(i: Index) -> Base.Element {\n get {\n _base[subranges.ranges[i._rangeOffset]][i.base]\n }\n set {\n _base[subranges.ranges[i._rangeOffset]][i.base] = newValue\n }\n }\n}\n\n// MARK: Accessing DiscontiguousSlices\n\nextension Collection {\n /// Accesses a view of this collection with the elements at the given\n /// indices.\n ///\n /// - Parameter subranges: The indices of the elements to retrieve from this\n /// collection.\n /// - Returns: A collection of the elements at the positions in `subranges`.\n ///\n /// - Complexity: O(1)\n @available(SwiftStdlib 6.0, *)\n public subscript(subranges: RangeSet<Index>) -> DiscontiguousSlice<Self> {\n DiscontiguousSlice(_base: self, subranges: subranges)\n }\n}\n\n\nextension Collection {\n /// Returns a collection of the elements in this collection that are not\n /// represented by the given range set.\n ///\n /// For example, this code sample finds the indices of all the vowel\n /// characters in the string, and then retrieves a collection that omits\n /// those characters.\n ///\n /// let str = "The rain in Spain stays mainly in the plain."\n /// let vowels: Set<Character> = ["a", "e", "i", "o", "u"]\n /// let vowelIndices = str.indices(where: { vowels.contains($0) })\n ///\n /// let disemvoweled = str.removingSubranges(vowelIndices)\n /// print(String(disemvoweled))\n /// // Prints "Th rn n Spn stys mnly n th pln."\n ///\n /// - Parameter subranges: A range set representing the indices of the\n /// elements to remove.\n /// - Returns: A collection of the elements that are not in `subranges`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @available(SwiftStdlib 6.0, *)\n public func removingSubranges(\n _ subranges: RangeSet<Index>\n ) -> DiscontiguousSlice<Self> {\n let inversion = subranges._inverted(within: self)\n return self[inversion]\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_DiscontiguousSlice.swift | cpp_apple_swift_stdlib_public_core_DiscontiguousSlice.swift | Swift | 13,466 | 0.8 | 0.036232 | 0.192935 | node-utils | 261 | 2024-07-04T21:24:57.463427 | MIT | false | 8e1366cdfed292a62c08064377dd03a1 |
//===--- DropWhile.swift - Lazy views for drop(while:) --------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A sequence whose elements consist of the elements that follow the initial\n/// consecutive elements of some base sequence that satisfy a given predicate.\n@frozen // lazy-performance\npublic struct LazyDropWhileSequence<Base: Sequence> {\n public typealias Element = Base.Element\n\n @usableFromInline // lazy-performance\n internal var _base: Base\n @usableFromInline // lazy-performance\n internal let _predicate: (Element) -> Bool\n\n /// Create an instance with elements `transform(x)` for each element\n /// `x` of base.\n @inlinable // lazy-performance\n internal init(_base: Base, predicate: @escaping (Element) -> Bool) {\n self._base = _base\n self._predicate = predicate\n }\n}\n\n@available(*, unavailable)\nextension LazyDropWhileSequence: Sendable {}\n\nextension LazyDropWhileSequence {\n /// An iterator over the elements traversed by a base iterator that follow the\n /// initial consecutive elements that satisfy a given predicate.\n ///\n /// This is the associated iterator for the `LazyDropWhileSequence`,\n /// `LazyDropWhileCollection`, and `LazyDropWhileBidirectionalCollection`\n /// types.\n @frozen // lazy-performance\n public struct Iterator {\n public typealias Element = Base.Element\n\n @usableFromInline // lazy-performance\n internal var _predicateHasFailed = false\n @usableFromInline // lazy-performance\n internal var _base: Base.Iterator\n @usableFromInline // lazy-performance\n internal let _predicate: (Element) -> Bool\n\n @inlinable // lazy-performance\n internal init(_base: Base.Iterator, predicate: @escaping (Element) -> Bool) {\n self._base = _base\n self._predicate = predicate\n }\n }\n}\n\n@available(*, unavailable)\nextension LazyDropWhileSequence.Iterator: Sendable {}\n\nextension LazyDropWhileSequence.Iterator: IteratorProtocol {\n @inlinable // lazy-performance\n public mutating func next() -> Element? {\n // Once the predicate has failed for the first time, the base iterator\n // can be used for the rest of the elements.\n if _predicateHasFailed {\n return _base.next()\n }\n\n // Retrieve and discard elements from the base iterator until one fails\n // the predicate.\n while let nextElement = _base.next() {\n if !_predicate(nextElement) {\n _predicateHasFailed = true\n return nextElement\n }\n }\n return nil\n } \n}\n\nextension LazyDropWhileSequence: Sequence {\n /// Returns an iterator over the elements of this sequence.\n ///\n /// - Complexity: O(1).\n @inlinable // lazy-performance\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_base: _base.makeIterator(), predicate: _predicate)\n }\n}\n\nextension LazyDropWhileSequence: LazySequenceProtocol {\n public typealias Elements = LazyDropWhileSequence\n}\n\nextension LazySequenceProtocol {\n /// Returns a lazy sequence that skips any initial elements that satisfy\n /// `predicate`.\n ///\n /// - Parameter predicate: A closure that takes an element of the sequence as\n /// its argument and returns `true` if the element should be skipped or\n /// `false` otherwise. Once `predicate` returns `false` it will not be\n /// called again.\n @inlinable // lazy-performance\n public __consuming func drop(\n while predicate: @escaping (Elements.Element) -> Bool\n ) -> LazyDropWhileSequence<Self.Elements> {\n return LazyDropWhileSequence(_base: self.elements, predicate: predicate)\n }\n}\n\n/// A lazy wrapper that includes the elements of an underlying\n/// collection after any initial consecutive elements that satisfy a\n/// predicate.\n///\n/// - Note: The performance of accessing `startIndex`, `first`, or any methods\n/// that depend on `startIndex` depends on how many elements satisfy the\n/// predicate at the start of the collection, and may not offer the usual\n/// performance given by the `Collection` protocol. Be aware, therefore,\n/// that general operations on lazy collections may not have the\n/// documented complexity.\npublic typealias LazyDropWhileCollection<T: Collection> = LazyDropWhileSequence<T>\n\nextension LazyDropWhileCollection: Collection {\n public typealias SubSequence = Slice<LazyDropWhileCollection<Base>>\n public typealias Index = Base.Index\n\n @inlinable // lazy-performance\n public var startIndex: Index {\n var index = _base.startIndex\n while index != _base.endIndex && _predicate(_base[index]) {\n _base.formIndex(after: &index)\n }\n return index\n }\n\n @inlinable // lazy-performance\n public var endIndex: Index {\n return _base.endIndex\n }\n\n @inlinable // lazy-performance\n public func index(after i: Index) -> Index {\n _precondition(i < _base.endIndex, "Can't advance past endIndex")\n return _base.index(after: i)\n }\n\n @inlinable // lazy-performance\n public subscript(position: Index) -> Element {\n return _base[position]\n }\n}\n\nextension LazyDropWhileCollection: BidirectionalCollection \nwhere Base: BidirectionalCollection {\n @inlinable // lazy-performance\n public func index(before i: Index) -> Index {\n _precondition(i > startIndex, "Can't move before startIndex")\n return _base.index(before: i)\n }\n}\n\nextension LazyDropWhileCollection: LazyCollectionProtocol { }\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_DropWhile.swift | cpp_apple_swift_stdlib_public_core_DropWhile.swift | Swift | 5,685 | 0.8 | 0.083832 | 0.308219 | node-utils | 647 | 2023-07-30T20:02:53.909029 | BSD-3-Clause | false | 3b14310ffdcc40b19a33a01c0f3953c6 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if SWIFT_ENABLE_REFLECTION\n\n/// Dumps the given object's contents using its mirror to the specified output\n/// stream.\n///\n/// - Parameters:\n/// - value: The value to output to the `target` stream.\n/// - target: The stream to use for writing the contents of `value`.\n/// - name: A label to use when writing the contents of `value`. When `nil`\n/// is passed, the label is omitted. The default is `nil`.\n/// - indent: The number of spaces to use as an indent for each line of the\n/// output. The default is `0`.\n/// - maxDepth: The maximum depth to descend when writing the contents of a\n/// value that has nested components. The default is `Int.max`.\n/// - maxItems: The maximum number of elements for which to write the full\n/// contents. The default is `Int.max`.\n/// - Returns: The instance passed as `value`.\n@discardableResult\n@_semantics("optimize.sil.specialize.generic.never")\npublic func dump<T, TargetStream: TextOutputStream>(\n _ value: T,\n to target: inout TargetStream,\n name: String? = nil,\n indent: Int = 0,\n maxDepth: Int = .max,\n maxItems: Int = .max\n) -> T {\n var maxItemCounter = maxItems\n var visitedItems = [ObjectIdentifier: Int]()\n target._lock()\n defer { target._unlock() }\n _dump_unlocked(\n value,\n to: &target,\n name: name,\n indent: indent,\n maxDepth: maxDepth,\n maxItemCounter: &maxItemCounter,\n visitedItems: &visitedItems)\n return value\n}\n\n/// Dumps the given object's contents using its mirror to standard output.\n///\n/// - Parameters:\n/// - value: The value to output to the `target` stream.\n/// - name: A label to use when writing the contents of `value`. When `nil`\n/// is passed, the label is omitted. The default is `nil`.\n/// - indent: The number of spaces to use as an indent for each line of the\n/// output. The default is `0`.\n/// - maxDepth: The maximum depth to descend when writing the contents of a\n/// value that has nested components. The default is `Int.max`.\n/// - maxItems: The maximum number of elements for which to write the full\n/// contents. The default is `Int.max`.\n/// - Returns: The instance passed as `value`.\n@discardableResult\n@_semantics("optimize.sil.specialize.generic.never")\npublic func dump<T>(\n _ value: T,\n name: String? = nil,\n indent: Int = 0,\n maxDepth: Int = .max,\n maxItems: Int = .max\n) -> T {\n var stdoutStream = _Stdout()\n return dump(\n value,\n to: &stdoutStream,\n name: name,\n indent: indent,\n maxDepth: maxDepth,\n maxItems: maxItems)\n}\n\n/// Dump an object's contents. User code should use dump().\n@_semantics("optimize.sil.specialize.generic.never")\ninternal func _dump_unlocked<TargetStream: TextOutputStream>(\n _ value: Any,\n to target: inout TargetStream,\n name: String?,\n indent: Int,\n maxDepth: Int,\n maxItemCounter: inout Int,\n visitedItems: inout [ObjectIdentifier: Int]\n) {\n guard maxItemCounter > 0 else { return }\n maxItemCounter -= 1\n\n for _ in 0..<indent { target.write(" ") }\n\n let mirror = Mirror(reflecting: value)\n let count = mirror.children.count\n let bullet = count == 0 ? "-"\n : maxDepth <= 0 ? "▹" : "▿"\n target.write(bullet)\n target.write(" ")\n\n if let name = name {\n target.write(name)\n target.write(": ")\n }\n // This takes the place of the old mirror API's 'summary' property\n _dumpPrint_unlocked(value, mirror, &target)\n\n let id: ObjectIdentifier?\n if type(of: value) is AnyObject.Type {\n // Object is a class (but not an ObjC-bridged struct)\n id = ObjectIdentifier(_unsafeDowncastToAnyObject(fromAny: value))\n } else if let metatypeInstance = value as? Any.Type {\n // Object is a metatype\n id = ObjectIdentifier(metatypeInstance)\n } else {\n id = nil\n }\n if let theId = id {\n if let previous = visitedItems[theId] {\n target.write(" #")\n _print_unlocked(previous, &target)\n target.write("\n")\n return\n }\n let identifier = visitedItems.count\n visitedItems[theId] = identifier\n target.write(" #")\n _print_unlocked(identifier, &target)\n }\n\n target.write("\n")\n\n guard maxDepth > 0 else { return }\n\n if let superclassMirror = mirror.superclassMirror {\n _dumpSuperclass_unlocked(\n mirror: superclassMirror,\n to: &target,\n indent: indent + 2,\n maxDepth: maxDepth - 1,\n maxItemCounter: &maxItemCounter,\n visitedItems: &visitedItems)\n }\n\n var currentIndex = mirror.children.startIndex\n for i in 0..<count {\n if maxItemCounter <= 0 {\n for _ in 0..<(indent+4) {\n _print_unlocked(" ", &target)\n }\n let remainder = count - i\n target.write("(")\n _print_unlocked(remainder, &target)\n if i > 0 { target.write(" more") }\n if remainder == 1 {\n target.write(" child)\n")\n } else {\n target.write(" children)\n")\n }\n return\n }\n\n let (name, child) = mirror.children[currentIndex]\n mirror.children.formIndex(after: ¤tIndex)\n _dump_unlocked(\n child,\n to: &target,\n name: name,\n indent: indent + 2,\n maxDepth: maxDepth - 1,\n maxItemCounter: &maxItemCounter,\n visitedItems: &visitedItems)\n }\n}\n\n/// Dump information about an object's superclass, given a mirror reflecting\n/// that superclass.\n@_semantics("optimize.sil.specialize.generic.never")\ninternal func _dumpSuperclass_unlocked<TargetStream: TextOutputStream>(\n mirror: Mirror,\n to target: inout TargetStream,\n indent: Int,\n maxDepth: Int,\n maxItemCounter: inout Int,\n visitedItems: inout [ObjectIdentifier: Int]\n) {\n guard maxItemCounter > 0 else { return }\n maxItemCounter -= 1\n\n for _ in 0..<indent { target.write(" ") }\n\n let count = mirror.children.count\n let bullet = count == 0 ? "-"\n : maxDepth <= 0 ? "▹" : "▿"\n target.write(bullet)\n target.write(" super: ")\n _debugPrint_unlocked(mirror.subjectType, &target)\n target.write("\n")\n\n guard maxDepth > 0 else { return }\n\n if let superclassMirror = mirror.superclassMirror {\n _dumpSuperclass_unlocked(\n mirror: superclassMirror,\n to: &target,\n indent: indent + 2,\n maxDepth: maxDepth - 1,\n maxItemCounter: &maxItemCounter,\n visitedItems: &visitedItems)\n }\n\n var currentIndex = mirror.children.startIndex\n for i in 0..<count {\n if maxItemCounter <= 0 {\n for _ in 0..<(indent+4) {\n target.write(" ")\n }\n let remainder = count - i\n target.write("(")\n _print_unlocked(remainder, &target)\n if i > 0 { target.write(" more") }\n if remainder == 1 {\n target.write(" child)\n")\n } else {\n target.write(" children)\n")\n }\n return\n }\n\n let (name, child) = mirror.children[currentIndex]\n mirror.children.formIndex(after: ¤tIndex)\n _dump_unlocked(\n child,\n to: &target,\n name: name,\n indent: indent + 2,\n maxDepth: maxDepth - 1,\n maxItemCounter: &maxItemCounter,\n visitedItems: &visitedItems)\n }\n}\n\n#endif // SWIFT_ENABLE_REFLECTION\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Dump.swift | cpp_apple_swift_stdlib_public_core_Dump.swift | Swift | 7,511 | 0.95 | 0.111111 | 0.203463 | node-utils | 737 | 2025-04-23T23:46:53.824569 | BSD-3-Clause | false | b89387dcf0a99ac4c2da3e6192bec8c1 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A representation of high precision time.\n///\n/// `Duration` represents an elapsed time value with high precision in an \n/// integral form. It may be used for measurements of varying clock sources. In \n/// those cases it represents the elapsed time measured by that clock. \n/// Calculations using `Duration` may span from a negative value to a positive \n/// value and have a suitable range to at least cover attosecond scale for both\n/// small elapsed durations like sub-second precision to durations that span\n/// centuries.\n///\n/// Typical construction of `Duration` values should be created via the\n/// static methods for specific time values. \n///\n/// var d: Duration = .seconds(3)\n/// d += .milliseconds(33)\n/// print(d) // 3.033 seconds\n///\n/// `Duration` itself does not ferry any additional information other than the \n/// temporal measurement component; specifically leap seconds should be \n/// represented as an additional accessor since that is specific only to certain\n/// clock implementations.\n@available(SwiftStdlib 5.7, *)\n@frozen\npublic struct Duration: Sendable {\n /// The low 64 bits of a 128-bit signed integer value counting attoseconds.\n public var _low: UInt64\n\n /// The high 64 bits of a 128-bit signed integer value counting attoseconds.\n public var _high: Int64\n\n @inlinable\n public init(_high: Int64, low: UInt64) {\n self._low = low\n self._high = _high\n }\n\n internal init(_attoseconds: _Int128) {\n self.init(_high: _attoseconds.high, low: _attoseconds.low)\n }\n\n /// Construct a `Duration` by adding attoseconds to a seconds value.\n ///\n /// This is useful for when an external decomposed components of a `Duration`\n /// has been stored and needs to be reconstituted. Since the values are added\n /// no precondition is expressed for the attoseconds being limited to 1e18.\n ///\n /// let d1 = Duration(\n /// secondsComponent: 3, \n /// attosecondsComponent: 123000000000000000)\n /// print(d1) // 3.123 seconds\n ///\n /// let d2 = Duration(\n /// secondsComponent: 3, \n /// attosecondsComponent: -123000000000000000)\n /// print(d2) // 2.877 seconds\n ///\n /// let d3 = Duration(\n /// secondsComponent: -3, \n /// attosecondsComponent: -123000000000000000)\n /// print(d3) // -3.123 seconds\n ///\n /// - Parameters:\n /// - secondsComponent: The seconds component portion of the `Duration` \n /// value.\n /// - attosecondsComponent: The attosecond component portion of the \n /// `Duration` value.\n public init(secondsComponent: Int64, attosecondsComponent: Int64) {\n self = Duration.seconds(secondsComponent) +\n Duration(_attoseconds: _Int128(attosecondsComponent))\n }\n\n internal var _attoseconds: _Int128 {\n _Int128(high: _high, low: _low)\n }\n}\n\n@available(SwiftStdlib 5.7, *)\nextension Duration {\n /// The composite components of the `Duration`.\n ///\n /// This is intended for facilitating conversions to existing time types. The\n /// attoseconds value will not exceed 1e18 or be lower than -1e18.\n @available(SwiftStdlib 5.7, *)\n public var components: (seconds: Int64, attoseconds: Int64) {\n let (seconds, attoseconds) = _attoseconds.dividedBy1e18()\n return (Int64(seconds), Int64(attoseconds))\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension Duration {\n /// The number of attoseconds represented by this `Duration`.\n ///\n /// This property provides direct access to the underlying number of attoseconds \n /// that the current `Duration` represents.\n ///\n /// let d = Duration.seconds(1)\n /// print(d.attoseconds) // 1_000_000_000_000_000_000\n @available(SwiftStdlib 6.0, *)\n @_alwaysEmitIntoClient\n public var attoseconds: Int128 {\n Int128(_low: _low, _high: _high)\n }\n \n /// Construct a `Duration` from the given number of attoseconds.\n ///\n /// This directly constructs a `Duration` from the given number of attoseconds.\n ///\n /// let d = Duration(attoseconds: 1_000_000_000_000_000_000)\n /// print(d) // 1.0 seconds\n ///\n /// - Parameter attoseconds: The total duration expressed in attoseconds.\n @available(SwiftStdlib 6.0, *)\n @_alwaysEmitIntoClient\n public init(attoseconds: Int128) {\n self.init(_high: attoseconds._high, low: attoseconds._low)\n }\n}\n\n@available(SwiftStdlib 5.7, *)\nextension Duration {\n /// Construct a `Duration` given a number of seconds represented as a \n /// `BinaryInteger`.\n ///\n /// let d: Duration = .seconds(77)\n ///\n /// - Returns: A `Duration` representing a given number of seconds.\n @available(SwiftStdlib 5.7, *)\n @inlinable\n public static func seconds<T: BinaryInteger>(_ seconds: T) -> Duration {\n guard let high = Int64(exactly: seconds >> 64) else { fatalError() }\n let low = UInt64(truncatingIfNeeded: seconds)\n let lowScaled = low.multipliedFullWidth(by: 1_000_000_000_000_000_000)\n let highScaled = high * 1_000_000_000_000_000_000\n return Duration(_high: highScaled + Int64(lowScaled.high), low: lowScaled.low)\n }\n \n /// Construct a `Duration` given a duration and scale, taking care so that\n /// exact integer durations are preserved exactly.\n internal init(_ duration: Double, scale: UInt64) {\n // Split the duration into integral and fractional parts, as we need to\n // handle them slightly differently to ensure that integer values are\n // never rounded if `scale` is representable as Double.\n let integralPart = duration.rounded(.towardZero)\n let fractionalPart = duration - integralPart\n self.init(_attoseconds:\n // This term may trap due to overflow, but it cannot round, so if the\n // input `seconds` is an exact integer, we get an exact integer result.\n _Int128(integralPart).multiplied(by: scale) +\n // This term may round, but cannot overflow.\n _Int128((fractionalPart * Double(scale)).rounded())\n )\n }\n\n /// Construct a `Duration` given a number of seconds represented as a \n /// `Double` by converting the value into the closest attosecond scale value.\n ///\n /// let d: Duration = .seconds(22.93)\n ///\n /// - Returns: A `Duration` representing a given number of seconds.\n @available(SwiftStdlib 5.7, *)\n public static func seconds(_ seconds: Double) -> Duration {\n Duration(seconds, scale: 1_000_000_000_000_000_000)\n }\n\n /// Construct a `Duration` given a number of milliseconds represented as a \n /// `BinaryInteger`.\n ///\n /// let d: Duration = .milliseconds(645)\n ///\n /// - Returns: A `Duration` representing a given number of milliseconds.\n @available(SwiftStdlib 5.7, *)\n @inlinable\n public static func milliseconds<T: BinaryInteger>(\n _ milliseconds: T\n ) -> Duration {\n guard let high = Int64(exactly: milliseconds >> 64) else { fatalError() }\n let low = UInt64(truncatingIfNeeded: milliseconds)\n let lowScaled = low.multipliedFullWidth(by: 1_000_000_000_000_000)\n let highScaled = high * 1_000_000_000_000_000\n return Duration(_high: highScaled + Int64(lowScaled.high), low: lowScaled.low)\n }\n\n /// Construct a `Duration` given a number of seconds milliseconds as a \n /// `Double` by converting the value into the closest attosecond scale value.\n ///\n /// let d: Duration = .milliseconds(88.3)\n ///\n /// - Returns: A `Duration` representing a given number of milliseconds.\n @available(SwiftStdlib 5.7, *)\n public static func milliseconds(_ milliseconds: Double) -> Duration {\n Duration(milliseconds, scale: 1_000_000_000_000_000)\n }\n\n /// Construct a `Duration` given a number of microseconds represented as a \n /// `BinaryInteger`.\n ///\n /// let d: Duration = .microseconds(12)\n ///\n /// - Returns: A `Duration` representing a given number of microseconds.\n @available(SwiftStdlib 5.7, *)\n @inlinable\n public static func microseconds<T: BinaryInteger>(\n _ microseconds: T\n ) -> Duration {\n guard let high = Int64(exactly: microseconds >> 64) else { fatalError() }\n let low = UInt64(truncatingIfNeeded: microseconds)\n let lowScaled = low.multipliedFullWidth(by: 1_000_000_000_000)\n let highScaled = high * 1_000_000_000_000\n return Duration(_high: highScaled + Int64(lowScaled.high), low: lowScaled.low)\n }\n\n /// Construct a `Duration` given a number of seconds microseconds as a \n /// `Double` by converting the value into the closest attosecond scale value.\n ///\n /// let d: Duration = .microseconds(382.9)\n ///\n /// - Returns: A `Duration` representing a given number of microseconds.\n @available(SwiftStdlib 5.7, *)\n public static func microseconds(_ microseconds: Double) -> Duration {\n Duration(microseconds, scale: 1_000_000_000_000)\n }\n\n /// Construct a `Duration` given a number of nanoseconds represented as a \n /// `BinaryInteger`.\n ///\n /// let d: Duration = .nanoseconds(1929)\n ///\n /// - Returns: A `Duration` representing a given number of nanoseconds.\n @available(SwiftStdlib 5.7, *)\n @inlinable\n public static func nanoseconds<T: BinaryInteger>(\n _ nanoseconds: T\n ) -> Duration {\n guard let high = Int64(exactly: nanoseconds >> 64) else { fatalError() }\n let low = UInt64(truncatingIfNeeded: nanoseconds)\n let lowScaled = low.multipliedFullWidth(by: 1_000_000_000)\n let highScaled = high * 1_000_000_000\n return Duration(_high: highScaled + Int64(lowScaled.high), low: lowScaled.low)\n }\n}\n\n@available(SwiftStdlib 5.7, *)\n@_unavailableInEmbedded\nextension Duration: Codable {\n @available(SwiftStdlib 5.7, *)\n public init(from decoder: Decoder) throws {\n var container = try decoder.unkeyedContainer()\n let high = try container.decode(Int64.self)\n let low = try container.decode(UInt64.self)\n self.init(_high: high, low: low)\n }\n\n @available(SwiftStdlib 5.7, *)\n public func encode(to encoder: Encoder) throws {\n var container = encoder.unkeyedContainer()\n try container.encode(_high)\n try container.encode(_low)\n }\n}\n\n@available(SwiftStdlib 5.7, *)\nextension Duration: Hashable {\n @available(SwiftStdlib 5.7, *)\n public func hash(into hasher: inout Hasher) {\n hasher.combine(_attoseconds)\n }\n}\n\n@available(SwiftStdlib 5.7, *)\nextension Duration: Equatable {\n @available(SwiftStdlib 5.7, *)\n public static func == (_ lhs: Duration, _ rhs: Duration) -> Bool {\n return lhs._attoseconds == rhs._attoseconds\n }\n}\n\n@available(SwiftStdlib 5.7, *)\nextension Duration: Comparable {\n @available(SwiftStdlib 5.7, *)\n public static func < (_ lhs: Duration, _ rhs: Duration) -> Bool {\n return lhs._attoseconds < rhs._attoseconds\n }\n}\n\n@available(SwiftStdlib 5.7, *)\nextension Duration: AdditiveArithmetic {\n @available(SwiftStdlib 5.7, *)\n public static var zero: Duration { Duration(_attoseconds: 0) }\n\n @available(SwiftStdlib 5.7, *)\n public static func + (_ lhs: Duration, _ rhs: Duration) -> Duration {\n return Duration(_attoseconds: lhs._attoseconds + rhs._attoseconds)\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func - (_ lhs: Duration, _ rhs: Duration) -> Duration {\n return Duration(_attoseconds: lhs._attoseconds - rhs._attoseconds)\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func += (_ lhs: inout Duration, _ rhs: Duration) {\n lhs = lhs + rhs\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func -= (_ lhs: inout Duration, _ rhs: Duration) {\n lhs = lhs - rhs\n }\n}\n\n@available(SwiftStdlib 5.7, *)\nextension Duration {\n @available(SwiftStdlib 5.7, *)\n public static func / (_ lhs: Duration, _ rhs: Double) -> Duration {\n return Duration(_attoseconds:\n _Int128(Double(lhs._attoseconds) / rhs))\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func /= (_ lhs: inout Duration, _ rhs: Double) {\n lhs = lhs / rhs\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func / <T: BinaryInteger>(\n _ lhs: Duration, _ rhs: T\n ) -> Duration {\n Duration(_attoseconds: lhs._attoseconds / _Int128(rhs))\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func /= <T: BinaryInteger>(_ lhs: inout Duration, _ rhs: T) {\n lhs = lhs / rhs\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func / (_ lhs: Duration, _ rhs: Duration) -> Double {\n Double(lhs._attoseconds) / Double(rhs._attoseconds)\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func * (_ lhs: Duration, _ rhs: Double) -> Duration {\n Duration(_attoseconds: _Int128(Double(lhs._attoseconds) * rhs))\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func * <T: BinaryInteger>(\n _ lhs: Duration, _ rhs: T\n ) -> Duration {\n Duration(_attoseconds: lhs._attoseconds * _Int128(rhs))\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func *= <T: BinaryInteger>(_ lhs: inout Duration, _ rhs: T) {\n lhs = lhs * rhs\n }\n}\n\n@available(SwiftStdlib 5.7, *)\n@_unavailableInEmbedded\nextension Duration: CustomStringConvertible {\n @available(SwiftStdlib 5.7, *)\n public var description: String {\n return (Double(_attoseconds) / 1e18).description + " seconds"\n }\n}\n\n@available(SwiftStdlib 5.7, *)\nextension Duration: DurationProtocol { }\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Duration.swift | cpp_apple_swift_stdlib_public_core_Duration.swift | Swift | 13,562 | 0.8 | 0.039267 | 0.373913 | react-lib | 904 | 2024-11-30T02:12:35.536186 | GPL-3.0 | false | 2c8039ef7f1574f55dc614ad67237128 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A type that defines a duration for a given `InstantProtocol` type.\n@available(SwiftStdlib 5.7, *)\npublic protocol DurationProtocol: Comparable, AdditiveArithmetic, Sendable {\n static func / (_ lhs: Self, _ rhs: Int) -> Self\n static func /= (_ lhs: inout Self, _ rhs: Int)\n static func * (_ lhs: Self, _ rhs: Int) -> Self\n static func *= (_ lhs: inout Self, _ rhs: Int)\n\n static func / (_ lhs: Self, _ rhs: Self) -> Double\n}\n\n@available(SwiftStdlib 5.7, *)\nextension DurationProtocol {\n @available(SwiftStdlib 5.7, *)\n public static func /= (_ lhs: inout Self, _ rhs: Int) {\n lhs = lhs / rhs\n }\n\n @available(SwiftStdlib 5.7, *)\n public static func *= (_ lhs: inout Self, _ rhs: Int) {\n lhs = lhs * rhs\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_DurationProtocol.swift | cpp_apple_swift_stdlib_public_core_DurationProtocol.swift | Swift | 1,247 | 0.8 | 0.085714 | 0.387097 | react-lib | 201 | 2023-10-22T14:26:35.101034 | MIT | false | b78091a776fdda99a8797e330b5cb0ee |
//===--- _EitherSequence.swift - A sequence type-erasing two sequences -----===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Not public stdlib API, currently used in Mirror.children implementation.\n\ninternal enum _Either<Left, Right> {\n case left(Left), right(Right)\n}\n\nextension _Either {\n internal init(_ left: Left, or other: Right.Type) { self = .left(left) }\n internal init(_ left: Left) { self = .left(left) }\n internal init(_ right: Right) { self = .right(right) }\n}\n\nextension _Either: Equatable where Left: Equatable, Right: Equatable {\n internal static func == (lhs: Self, rhs: Self) -> Bool {\n switch (lhs, rhs) {\n case let (.left(l), .left(r)): return l == r\n case let (.right(l), .right(r)): return l == r\n case (.left, .right), (.right, .left): return false\n }\n }\n}\n\nextension _Either: Comparable where Left: Comparable, Right: Comparable {\n internal static func < (lhs: Self, rhs: Self) -> Bool {\n switch (lhs, rhs) {\n case let (.left(l), .left(r)): return l < r\n case let (.right(l), .right(r)): return l < r\n case (.left, .right): return true\n case (.right, .left): return false\n }\n }\n}\n\nextension _Either: Sendable\n where Left: Sendable, Right: Sendable { }\n\n/// A sequence that type erases two sequences. A lighter-weight alternative to\n/// AnySequence when more can be statically known, and which is more easily\n/// specialized.\n///\n/// If you only know about one of the types, the second one can be\n/// AnySequence, giving you a fast path for the known one.\n///\n/// If you have 3+ types to erase, you can nest them.\ntypealias _EitherSequence<L: Sequence, R: Sequence> =\n _Either<L,R> where L.Element == R.Element\n\nextension _EitherSequence {\n internal struct Iterator {\n var left: Left.Iterator?\n var right: Right.Iterator?\n }\n}\n\nextension _Either.Iterator: IteratorProtocol {\n internal typealias Element = Left.Element\n\n internal mutating func next() -> Element? {\n left?.next() ?? right?.next()\n }\n}\n\nextension _EitherSequence: Sequence {\n internal typealias Element = Left.Element\n\n internal func makeIterator() -> Iterator {\n switch self {\n case let .left(l):\n return Iterator(left: l.makeIterator(), right: nil)\n case let .right(r):\n return Iterator(left: nil, right: r.makeIterator())\n }\n }\n}\n\ninternal typealias _EitherCollection<\n T: Collection, U: Collection\n> = _EitherSequence<T,U> where T.Element == U.Element\n\nextension _EitherCollection: Collection {\n internal typealias Index = _Either<Left.Index, Right.Index>\n\n internal var startIndex: Index {\n switch self {\n case let .left(s): return .left(s.startIndex)\n case let .right(s): return .right(s.startIndex)\n }\n }\n\n internal var endIndex: Index {\n switch self {\n case let .left(s): return .left(s.endIndex)\n case let .right(s): return .right(s.endIndex)\n }\n }\n\n internal subscript(position: Index) -> Element {\n switch (self,position) {\n case let (.left(s),.left(i)): return s[i]\n case let (.right(s),.right(i)): return s[i]\n default: fatalError("_EitherCollection: Sequence used with other index type")\n }\n }\n\n internal func index(after i: Index) -> Index {\n switch (self,i) {\n case let (.left(s),.left(i)): return .left(s.index(after: i))\n case let (.right(s),.right(i)): return .right(s.index(after: i))\n default: fatalError("_EitherCollection: wrong type of index used")\n }\n }\n\n internal func index(\n _ i: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n switch (self,i,limit) {\n case let (.left(s),.left(i),.left(limit)):\n return s.index(i, offsetBy: distance, limitedBy: limit).map { .left($0) }\n case let (.right(s),.right(i),.right(limit)):\n return s.index(i, offsetBy: distance, limitedBy: limit).map { .right($0) }\n default: fatalError("_EitherCollection: wrong type of index used")\n }\n }\n\n internal func index(_ i: Index, offsetBy distance: Int) -> Index {\n switch (self,i) {\n case let (.left(s),.left(i)): return .left(s.index(i, offsetBy: distance))\n case let (.right(s),.right(i)): return .right(s.index(i, offsetBy: distance))\n default: fatalError("_EitherCollection: wrong type of index used")\n }\n }\n\n internal func distance(from start: Index, to end: Index) -> Int {\n switch (self,start,end) {\n case let (.left(s),.left(i),.left(j)):\n return s.distance(from: i, to: j)\n case let (.right(s),.right(i),.right(j)):\n return s.distance(from: i, to: j)\n default: fatalError("_EitherCollection: wrong type of index used")\n }\n }\n}\n\ninternal typealias _EitherBidirectionalCollection<\n L: BidirectionalCollection, R: BidirectionalCollection\n> = _Either<L,R> where L.Element == R.Element\n\nextension _EitherBidirectionalCollection: BidirectionalCollection {\n internal func index(before i: Index) -> Index {\n switch (self,i) {\n case let (.left(s),.left(i)): return .left(s.index(before: i))\n case let (.right(s),.right(i)): return .right(s.index(before: i))\n default: fatalError("_EitherCollection: wrong type of index used")\n }\n }\n}\n\ninternal typealias _EitherRandomAccessCollection<\n L: RandomAccessCollection, R: RandomAccessCollection\n> = _Either<L,R> where L.Element == R.Element\n\nextension _EitherRandomAccessCollection: RandomAccessCollection { }\n\nextension _Either {\n init<C: Collection>(\n _ collection: C\n ) where Right == AnyCollection<C.Element> {\n self = .right(AnyCollection(collection))\n }\n}\n\nextension AnyCollection {\n init<L: Collection,R: Collection>(\n _ other: _Either<L,R>\n ) where L.Element == Element, R.Element == Element {\n // Strip away the Either and put the actual collection into the existential,\n // trying to use the custom initializer from another AnyCollection.\n switch other {\n case let .left(l as Self): self = .init(l)\n case let .right(r as Self): self = .init(r)\n case let .left(l): self = .init(l)\n case let .right(r): self = .init(r)\n }\n }\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_EitherSequence.swift | cpp_apple_swift_stdlib_public_core_EitherSequence.swift | Swift | 6,377 | 0.8 | 0.075 | 0.127907 | react-lib | 438 | 2025-02-22T01:42:10.453428 | Apache-2.0 | false | 90e678f766d1baed13e22554d9b0d620 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n// TODO: This is all a stop-gap so that at least some types are printable in\n// embedded Swift, in an embedded-programming friendly way (we mainly need\n// printing to not need to heap allocate).\n\n@_extern(c, "putchar")\n@discardableResult\nfunc putchar(_: CInt) -> CInt\n\npublic func print(_ string: StaticString, terminator: StaticString = "\n") {\n var p = unsafe string.utf8Start\n while unsafe p.pointee != 0 {\n putchar(CInt(unsafe p.pointee))\n unsafe p += 1\n }\n unsafe p = terminator.utf8Start\n while unsafe p.pointee != 0 {\n putchar(CInt(unsafe p.pointee))\n unsafe p += 1\n }\n}\n\n@_disfavoredOverload\npublic func print(_ string: String, terminator: StaticString = "\n") {\n var string = string\n string.withUTF8 { buf in\n for unsafe c in unsafe buf {\n putchar(CInt(c))\n }\n }\n var p = unsafe terminator.utf8Start\n while unsafe p.pointee != 0 {\n putchar(CInt(unsafe p.pointee))\n unsafe p += 1\n }\n}\n\n@_disfavoredOverload\npublic func print(_ object: some CustomStringConvertible, terminator: StaticString = "\n") {\n var string = object.description\n string.withUTF8 { buf in\n for unsafe c in unsafe buf {\n putchar(CInt(c))\n }\n }\n var p = unsafe terminator.utf8Start\n while unsafe p.pointee != 0 {\n putchar(CInt(unsafe p.pointee))\n unsafe p += 1\n }\n}\n\nfunc print(_ buf: UnsafeBufferPointer<UInt8>, terminator: StaticString = "\n") {\n for unsafe c in unsafe buf {\n putchar(CInt(c))\n }\n var p = unsafe terminator.utf8Start\n while unsafe p.pointee != 0 {\n unsafe putchar(CInt(p.pointee))\n unsafe p += 1\n }\n}\n\nfunc printCharacters(_ buf: UnsafeRawBufferPointer) {\n for unsafe c in unsafe buf {\n putchar(CInt(c))\n }\n}\n\nfunc printCharacters(_ buf: UnsafeBufferPointer<UInt8>) {\n unsafe printCharacters(UnsafeRawBufferPointer(buf))\n}\n\nextension BinaryInteger {\n internal func _toStringImpl(\n _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,\n _ bufferLength: UInt,\n _ radix: Int,\n _ uppercase: Bool\n ) -> Int {\n if self == (0 as Self) {\n unsafe buffer[0] = UInt8(("0" as Unicode.Scalar).value)\n return 1\n }\n \n func _ascii(_ digit: UInt8) -> UTF8.CodeUnit {\n if digit < 10 {\n UInt8(("0" as Unicode.Scalar).value) + digit\n } else {\n UInt8(("a" as Unicode.Scalar).value) + (digit - 10)\n }\n }\n let isNegative = Self.isSigned && self < (0 as Self)\n var value = magnitude\n \n var index = Int(bufferLength - 1)\n while value != 0 {\n let (quotient, remainder) = value.quotientAndRemainder(dividingBy: Magnitude(radix))\n unsafe buffer[index] = _ascii(UInt8(truncatingIfNeeded: remainder))\n index -= 1\n value = quotient\n }\n if isNegative {\n unsafe buffer[index] = UInt8(("-" as Unicode.Scalar).value)\n index -= 1\n }\n let start = index + 1\n let end = Int(bufferLength - 1)\n let count = end - start + 1\n \n let intermediate = unsafe UnsafeBufferPointer(start: buffer.advanced(by: start), count: count)\n let destination = unsafe UnsafeMutableRawBufferPointer(start: buffer, count: Int(bufferLength))\n unsafe destination.copyMemory(from: UnsafeRawBufferPointer(intermediate))\n \n return count\n }\n\n func writeToStdout() {\n // Avoid withUnsafeTemporaryAllocation which is not typed-throws ready yet\n let byteCount = 64\n let stackBuffer = Builtin.stackAlloc(byteCount._builtinWordValue,\n 1._builtinWordValue, 1._builtinWordValue)\n let buffer = unsafe UnsafeMutableRawBufferPointer(start: .init(stackBuffer),\n count: byteCount).baseAddress!.assumingMemoryBound(to: UInt8.self)\n\n let count = unsafe _toStringImpl(buffer, 64, 10, false)\n\n unsafe printCharacters(UnsafeBufferPointer(start: buffer, count: count))\n\n Builtin.stackDealloc(stackBuffer)\n }\n}\n\npublic func print(_ integer: some BinaryInteger, terminator: StaticString = "\n") {\n integer.writeToStdout()\n print("", terminator: terminator)\n}\n\npublic func print(_ boolean: Bool, terminator: StaticString = "\n") {\n if boolean {\n print("true", terminator: terminator)\n } else {\n print("false", terminator: terminator)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_EmbeddedPrint.swift | cpp_apple_swift_stdlib_public_core_EmbeddedPrint.swift | Swift | 4,658 | 0.95 | 0.101266 | 0.108696 | vue-tools | 385 | 2024-04-04T05:43:02.143184 | BSD-3-Clause | false | da2916e24b86872bbd179691fcd35dc3 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n/// Class object and class metadata structures\n\n@unsafe\npublic struct ClassMetadata {\n var superclassMetadata: UnsafeMutablePointer<ClassMetadata>?\n\n // There is no way to express the actual calling convention on this\n // function (swiftcc with 'self') currently, so let's use UnsafeRawPointer\n // and a helper function in C (_swift_embedded_invoke_heap_object_destroy).\n var destroy: UnsafeRawPointer\n\n // There is no way to express the actual calling convention on this\n // function (swiftcc with 'self') currently, so let's use UnsafeRawPointer\n // and a helper function in C (_swift_embedded_invoke_heap_object_optional_ivardestroyer).\n var ivarDestroyer: UnsafeRawPointer?\n}\n\n/*\n Embedded Swift Refcounting Scheme\n =================================\n\n The scheme for storing and maintaining a refcount on heap objects is very simple in Embedded Swift, and is much\n simpler than regular Swift's. This is mainly due to the fact that we currently only maintain the regular ("strong")\n refcount and we don't allow weak references, unowned references and we don't track refcount during deinit of the\n object.\n\n The refcount is always stored directly inline in the heap object, in the `refcount` field (see HeapObject struct\n below). This field has the following structure (on 32-bit, and similar on other bitwidths):\n\n ┌──────────────┬──────────────────────────────────────────────┐\n │ b31 │ b30:b0 │\n ├──────────────┼──────────────────────────────────────────────┤\n │ doNotFreeBit │ actual number of references │\n └──────────────┴──────────────────────────────────────────────┘\n\n If the highest bit (doNotFreeBit) is set, the behavior of dropping the last reference (release operation where\n refcount ends up being 0) is altered to avoid calling free() on the object (deinit is still run). This is crutial for\n class instances that are promoted by the compiler from being heap-allocated to instead be located on the stack\n (see swift_initStackObject).\n\n To retrieve the actual number of references from the `refcount` field, refcountMask needs to be applied, which masks\n off the doNotFreeBit.\n\n The actual number of references has one possible value that has a special meaning, immortalRefCount (all bits set,\n i.e. 0x7fff_ffff on 32-bit systems). When used, retain and release operations do nothing, references are not counted,\n and the object can never be deinit'd / free'd. This is used for class instances that are promoted by the compiler to\n be allocated statically in global memory (see swift_initStaticObject). Note that there are two different scenarios for\n this currently:\n\n - In most cases, a class instance that is promoted to a global, is still dynamically initialized with a runtime call\n to swift_initStaticObject. This function will set the refcount field to immortalRefCount | doNotFreeBit.\n - As a special case to allow arrays be fully statically initialized without runtime overhead, instances of\n _ContiguousArrayStorage can be promoted to __StaticArrayStorage with the HeapObject header emitted directly by the\n compiler and refcount field directly set to immortalRefCount | doNotFreeBit (see irgen::emitConstantObject).\n\n Tne immortalRefCount is additionally also used as a placeholder value for objects (heap-allocated or stack-allocated)\n when they're currently inside their deinit(). This is done to prevent further retains and releases inside deinit from\n triggering deinitialization again, without the need to reserve another bit for this purpose. Retains and releases in\n deinit() are allowed, as long as they are balanced at the end, i.e. the object is not escaped (user's responsibility)\n and not over-released (this can only be caused by unsafe code).\n\n The following table summarizes the meaning of the possible combinations of doNotFreeBit and have immortal refcount\n value:\n\n ┌───────────╥──────────╥─────────────────────────────────────────────────┐\n │ doNotFree ║ immortal ║ │\n ╞═══════════╬══════════╬═════════════════════════════════════════════════╡\n │ 0 ║ no ║ regular class instance │\n ├───────────╫──────────╫─────────────────────────────────────────────────┤\n │ 0 ║ yes ║ regular class instance during deinit() │\n ├───────────╫──────────╫─────────────────────────────────────────────────┤\n │ 1 ║ no ║ stack-allocated │\n ├───────────╫──────────╫─────────────────────────────────────────────────┤\n │ 1 ║ yes ║ global-allocated, no need to track references, │\n │ ║ ║ or stack-allocated instance during deinit() │\n └───────────╨──────────╨─────────────────────────────────────────────────┘\n*/\n@unsafe\npublic struct HeapObject {\n // There is no way to express the custom ptrauth signature on the metadata\n // field, so let's use UnsafeRawPointer and a helper function in C instead\n // (_swift_embedded_set_heap_object_metadata_pointer).\n var metadata: UnsafeRawPointer\n\n // TODO: This is just an initial support for strong refcounting only. We need\n // to think about supporting (or banning) weak and/or unowned references.\n var refcount: Int\n\n // Note: The immortalRefCount value is also hard-coded in IRGen in `irgen::emitConstantObject`, and in HeapObject.h.\n#if _pointerBitWidth(_64)\n static let doNotFreeBit = Int(bitPattern: 0x8000_0000_0000_0000)\n static let refcountMask = Int(bitPattern: 0x7fff_ffff_ffff_ffff)\n static let immortalRefCount = Int(bitPattern: 0x7fff_ffff_ffff_ffff) // Make sure we don't have doNotFreeBit set\n#elseif _pointerBitWidth(_32)\n static let doNotFreeBit = Int(bitPattern: 0x8000_0000)\n static let refcountMask = Int(bitPattern: 0x7fff_ffff)\n static let immortalRefCount = Int(bitPattern: 0x7fff_ffff) // Make sure we don't have doNotFreeBit set\n#elseif _pointerBitWidth(_16)\n static let doNotFreeBit = Int(bitPattern: 0x8000)\n static let refcountMask = Int(bitPattern: 0x7fff)\n static let immortalRefCount = Int(bitPattern: 0x7fff) // Make sure we don't have doNotFreeBit set\n#endif\n\n#if _pointerBitWidth(_64)\n static let immortalObjectPointerBit = UInt(0x8000_0000_0000_0000)\n#endif\n\n#if _pointerBitWidth(_64)\n static let bridgeObjectToPlainObjectMask = UInt(0x8fff_ffff_ffff_fff8)\n#elseif _pointerBitWidth(_32)\n static let bridgeObjectToPlainObjectMask = UInt(0xffff_ffff)\n#elseif _pointerBitWidth(_16)\n static let bridgeObjectToPlainObjectMask = UInt(0xffff)\n#endif\n}\n\n\n\n/// Forward declarations of C functions\n\n@_extern(c, "posix_memalign")\nfunc posix_memalign(_: UnsafeMutablePointer<UnsafeMutableRawPointer?>, _: Int, _: Int) -> CInt\n\n@_extern(c, "free")\nfunc free(_ p: UnsafeMutableRawPointer?)\n\n\n\n/// Allocations\n\nfunc alignedAlloc(size: Int, alignment: Int) -> UnsafeMutableRawPointer? {\n let alignment = max(alignment, unsafe MemoryLayout<UnsafeRawPointer>.size)\n var r: UnsafeMutableRawPointer? = nil\n _ = unsafe posix_memalign(&r, alignment, size)\n return unsafe r\n}\n\n@_cdecl("swift_slowAlloc")\npublic func swift_slowAlloc(_ size: Int, _ alignMask: Int) -> UnsafeMutableRawPointer? {\n let alignment: Int\n if alignMask == -1 {\n alignment = _swift_MinAllocationAlignment\n } else {\n alignment = alignMask + 1\n }\n return unsafe alignedAlloc(size: size, alignment: alignment)\n}\n\n@_cdecl("swift_slowDealloc")\npublic func swift_slowDealloc(_ ptr: UnsafeMutableRawPointer, _ size: Int, _ alignMask: Int) {\n unsafe free(ptr)\n}\n\n@_cdecl("swift_allocObject")\npublic func swift_allocObject(metadata: Builtin.RawPointer, requiredSize: Int, requiredAlignmentMask: Int) -> Builtin.RawPointer {\n return unsafe swift_allocObject(metadata: UnsafeMutablePointer<ClassMetadata>(metadata), requiredSize: requiredSize, requiredAlignmentMask: requiredAlignmentMask)._rawValue\n}\n\nfunc swift_allocObject(metadata: UnsafeMutablePointer<ClassMetadata>, requiredSize: Int, requiredAlignmentMask: Int) -> UnsafeMutablePointer<HeapObject> {\n let p = unsafe swift_slowAlloc(requiredSize, requiredAlignmentMask)!\n let object = unsafe p.assumingMemoryBound(to: HeapObject.self)\n unsafe _swift_embedded_set_heap_object_metadata_pointer(object, metadata)\n unsafe object.pointee.refcount = 1\n return unsafe object\n}\n\n@_cdecl("swift_deallocObject")\npublic func swift_deallocObject(object: Builtin.RawPointer, allocatedSize: Int, allocatedAlignMask: Int) {\n unsafe swift_deallocObject(object: UnsafeMutablePointer<HeapObject>(object), allocatedSize: allocatedSize, allocatedAlignMask: allocatedAlignMask)\n}\n\nfunc swift_deallocObject(object: UnsafeMutablePointer<HeapObject>, allocatedSize: Int, allocatedAlignMask: Int) {\n unsafe free(UnsafeMutableRawPointer(object))\n}\n\n@_cdecl("swift_deallocClassInstance")\npublic func swift_deallocClassInstance(object: Builtin.RawPointer, allocatedSize: Int, allocatedAlignMask: Int) {\n unsafe swift_deallocClassInstance(object: UnsafeMutablePointer<HeapObject>(object), allocatedSize: allocatedSize, allocatedAlignMask: allocatedAlignMask)\n}\n\nfunc swift_deallocClassInstance(object: UnsafeMutablePointer<HeapObject>, allocatedSize: Int, allocatedAlignMask: Int) {\n if (unsafe object.pointee.refcount & HeapObject.doNotFreeBit) != 0 {\n return\n }\n\n unsafe free(UnsafeMutableRawPointer(object))\n}\n\n@_cdecl("swift_deallocPartialClassInstance")\npublic func swift_deallocPartialClassInstance(object: Builtin.RawPointer, metadata: Builtin.RawPointer, allocatedSize: Int, allocatedAlignMask: Int) {\n unsafe swift_deallocPartialClassInstance(object: UnsafeMutablePointer<HeapObject>(object), metadata: UnsafeMutablePointer<ClassMetadata>(metadata), allocatedSize: allocatedSize, allocatedAlignMask: allocatedAlignMask)\n}\n\nfunc swift_deallocPartialClassInstance(object: UnsafeMutablePointer<HeapObject>, metadata: UnsafeMutablePointer<ClassMetadata>, allocatedSize: Int, allocatedAlignMask: Int) {\n var classMetadata = unsafe _swift_embedded_get_heap_object_metadata_pointer(object).assumingMemoryBound(to: ClassMetadata.self)\n while unsafe classMetadata != metadata {\n unsafe _swift_embedded_invoke_heap_object_optional_ivardestroyer(object, classMetadata)\n guard let superclassMetadata = unsafe classMetadata.pointee.superclassMetadata else { break }\n unsafe classMetadata = superclassMetadata\n }\n}\n\n@_cdecl("swift_initStaticObject")\npublic func swift_initStaticObject(metadata: Builtin.RawPointer, object: Builtin.RawPointer) -> Builtin.RawPointer {\n return unsafe swift_initStaticObject(metadata: UnsafeMutablePointer<ClassMetadata>(metadata), object: UnsafeMutablePointer<HeapObject>(object))._rawValue\n}\n\nfunc swift_initStaticObject(metadata: UnsafeMutablePointer<ClassMetadata>, object: UnsafeMutablePointer<HeapObject>) -> UnsafeMutablePointer<HeapObject> {\n unsafe _swift_embedded_set_heap_object_metadata_pointer(object, metadata)\n unsafe object.pointee.refcount = HeapObject.immortalRefCount | HeapObject.doNotFreeBit\n return unsafe object\n}\n\n@_cdecl("swift_initStackObject")\npublic func swift_initStackObject(metadata: Builtin.RawPointer, object: Builtin.RawPointer) -> Builtin.RawPointer {\n return unsafe swift_initStackObject(metadata: UnsafeMutablePointer<ClassMetadata>(metadata), object: UnsafeMutablePointer<HeapObject>(object))._rawValue\n}\n\nfunc swift_initStackObject(metadata: UnsafeMutablePointer<ClassMetadata>, object: UnsafeMutablePointer<HeapObject>) -> UnsafeMutablePointer<HeapObject> {\n unsafe _swift_embedded_set_heap_object_metadata_pointer(object, metadata)\n unsafe object.pointee.refcount = 1 | HeapObject.doNotFreeBit\n return unsafe object\n}\n\n@unsafe\npublic var _emptyBoxStorage: (Int, Int) = (/*isa*/0, /*refcount*/-1)\n\n@_cdecl("swift_allocEmptyBox")\npublic func swift_allocEmptyBox() -> Builtin.RawPointer {\n let box = unsafe Builtin.addressof(&_emptyBoxStorage)\n swift_retain(object: box)\n return box\n}\n\n\n/// Refcounting\n\nfunc isValidPointerForNativeRetain(object: Builtin.RawPointer) -> Bool {\n let objectBits = UInt(Builtin.ptrtoint_Word(object))\n if objectBits == 0 { return false }\n\n #if _pointerBitWidth(_64)\n if unsafe (objectBits & HeapObject.immortalObjectPointerBit) != 0 { return false }\n #endif\n \n return true\n}\n\n@_cdecl("swift_setDeallocating")\npublic func swift_setDeallocating(object: Builtin.RawPointer) {\n}\n\n@_cdecl("swift_dynamicCastClass")\npublic func swift_dynamicCastClass(object: UnsafeMutableRawPointer, targetMetadata: UnsafeRawPointer) -> UnsafeMutableRawPointer? {\n let sourceObj = unsafe object.assumingMemoryBound(to: HeapObject.self)\n var type = unsafe _swift_embedded_get_heap_object_metadata_pointer(sourceObj).assumingMemoryBound(to: ClassMetadata.self)\n let targetType = unsafe targetMetadata.assumingMemoryBound(to: ClassMetadata.self)\n while unsafe type != targetType {\n guard let superType = unsafe type.pointee.superclassMetadata else {\n return nil\n }\n unsafe type = UnsafeMutablePointer(superType)\n }\n return unsafe object\n}\n\n@_cdecl("swift_dynamicCastClassUnconditional")\npublic func swift_dynamicCastClassUnconditional(object: UnsafeMutableRawPointer, targetMetadata: UnsafeRawPointer,\n file: UnsafePointer<CChar>, line: CUnsignedInt, column: CUnsignedInt) -> UnsafeMutableRawPointer {\n guard let result = unsafe swift_dynamicCastClass(object: object, targetMetadata: targetMetadata) else {\n fatalError("failed cast")\n }\n return unsafe result\n}\n\n@_cdecl("swift_isEscapingClosureAtFileLocation")\npublic func swift_isEscapingClosureAtFileLocation(object: Builtin.RawPointer, filename: UnsafePointer<CChar>, filenameLength: Int32, line: Int32, column: Int32, verificationType: CUnsignedInt) -> Bool {\n let objectBits = UInt(Builtin.ptrtoint_Word(object))\n if objectBits == 0 { return false }\n\n guard swift_isUniquelyReferenced_native(object: object) else {\n fatalError("non-escaping closure escaped")\n }\n return false\n}\n\n@_cdecl("swift_isUniquelyReferenced_native")\npublic func swift_isUniquelyReferenced_native(object: Builtin.RawPointer) -> Bool {\n if !isValidPointerForNativeRetain(object: object) { return false }\n\n return unsafe swift_isUniquelyReferenced_nonNull_native(object: UnsafeMutablePointer<HeapObject>(object))\n}\n\n@_cdecl("swift_isUniquelyReferenced_nonNull_native")\npublic func swift_isUniquelyReferenced_nonNull_native(object: Builtin.RawPointer) -> Bool {\n return unsafe swift_isUniquelyReferenced_nonNull_native(object: UnsafeMutablePointer<HeapObject>(object))\n}\n\nfunc swift_isUniquelyReferenced_nonNull_native(object: UnsafeMutablePointer<HeapObject>) -> Bool {\n let refcount = unsafe refcountPointer(for: object)\n return unsafe loadAcquire(refcount) == 1\n}\n\n@_cdecl("swift_retain")\npublic func swift_retain(object: Builtin.RawPointer) -> Builtin.RawPointer {\n if !isValidPointerForNativeRetain(object: object) { return object }\n\n let o = unsafe UnsafeMutablePointer<HeapObject>(object)\n return unsafe swift_retain_n_(object: o, n: 1)._rawValue\n}\n\n// Cannot use UnsafeMutablePointer<HeapObject>? directly in the function argument or return value as it causes IRGen crashes\n@_cdecl("swift_retain_n")\npublic func swift_retain_n(object: Builtin.RawPointer, n: UInt32) -> Builtin.RawPointer {\n if !isValidPointerForNativeRetain(object: object) { return object }\n\n let o = unsafe UnsafeMutablePointer<HeapObject>(object)\n return unsafe swift_retain_n_(object: o, n: n)._rawValue\n}\n\nfunc swift_retain_n_(object: UnsafeMutablePointer<HeapObject>, n: UInt32) -> UnsafeMutablePointer<HeapObject> {\n let refcount = unsafe refcountPointer(for: object)\n if unsafe loadRelaxed(refcount) & HeapObject.refcountMask == HeapObject.immortalRefCount {\n return unsafe object\n }\n\n unsafe addRelaxed(refcount, n: Int(n))\n\n return unsafe object\n}\n\n@_cdecl("swift_bridgeObjectRetain")\npublic func swift_bridgeObjectRetain(object: Builtin.RawPointer) -> Builtin.RawPointer {\n return swift_bridgeObjectRetain_n(object: object, n: 1)\n}\n\n@_cdecl("swift_bridgeObjectRetain_n")\npublic func swift_bridgeObjectRetain_n(object: Builtin.RawPointer, n: UInt32) -> Builtin.RawPointer {\n let objectBits = UInt(Builtin.ptrtoint_Word(object))\n let untaggedObject = unsafe Builtin.inttoptr_Word((objectBits & HeapObject.bridgeObjectToPlainObjectMask)._builtinWordValue)\n return swift_retain_n(object: untaggedObject, n: n)\n}\n\n@_cdecl("swift_release")\npublic func swift_release(object: Builtin.RawPointer) {\n if !isValidPointerForNativeRetain(object: object) { return }\n\n let o = unsafe UnsafeMutablePointer<HeapObject>(object)\n unsafe swift_release_n_(object: o, n: 1)\n}\n\n@_cdecl("swift_release_n")\npublic func swift_release_n(object: Builtin.RawPointer, n: UInt32) {\n if !isValidPointerForNativeRetain(object: object) { return }\n\n let o = unsafe UnsafeMutablePointer<HeapObject>(object)\n unsafe swift_release_n_(object: o, n: n)\n}\n\nfunc swift_release_n_(object: UnsafeMutablePointer<HeapObject>?, n: UInt32) {\n guard let object = unsafe object else {\n return\n }\n\n let refcount = unsafe refcountPointer(for: object)\n let loadedRefcount = unsafe loadRelaxed(refcount)\n if unsafe loadedRefcount & HeapObject.refcountMask == HeapObject.immortalRefCount {\n return\n }\n\n let resultingRefcount = unsafe subFetchAcquireRelease(refcount, n: Int(n)) & HeapObject.refcountMask\n if resultingRefcount == 0 {\n // Set the refcount to immortalRefCount before calling the object destroyer\n // to prevent future retains/releases from having any effect. Unlike the\n // full Swift runtime, we don't track the refcount inside deinit, so we\n // won't be able to detect escapes or over-releases of `self` in deinit. We\n // might want to reconsider that in the future.\n //\n // There can only be one thread with a reference at this point (because\n // we're releasing the last existing reference), so a relaxed store is\n // enough.\n let doNotFree = unsafe (loadedRefcount & HeapObject.doNotFreeBit) != 0\n unsafe storeRelaxed(refcount, newValue: HeapObject.immortalRefCount | (doNotFree ? HeapObject.doNotFreeBit : 0))\n\n unsafe _swift_embedded_invoke_heap_object_destroy(object)\n } else if resultingRefcount < 0 {\n fatalError("negative refcount")\n }\n}\n\n@_cdecl("swift_bridgeObjectRelease")\npublic func swift_bridgeObjectRelease(object: Builtin.RawPointer) {\n swift_bridgeObjectRelease_n(object: object, n: 1)\n}\n\n@_cdecl("swift_bridgeObjectRelease_n")\npublic func swift_bridgeObjectRelease_n(object: Builtin.RawPointer, n: UInt32) {\n let objectBits = UInt(Builtin.ptrtoint_Word(object))\n let untaggedObject = unsafe Builtin.inttoptr_Word((objectBits & HeapObject.bridgeObjectToPlainObjectMask)._builtinWordValue)\n swift_release_n(object: untaggedObject, n: n)\n}\n\n@_cdecl("swift_retainCount")\npublic func swift_retainCount(object: Builtin.RawPointer) -> Int {\n if !isValidPointerForNativeRetain(object: object) { return 0 }\n let o = unsafe UnsafeMutablePointer<HeapObject>(object)\n let refcount = unsafe refcountPointer(for: o)\n return unsafe loadAcquire(refcount) & HeapObject.refcountMask\n}\n\n/// Refcount helpers\n\nfileprivate func refcountPointer(for object: UnsafeMutablePointer<HeapObject>) -> UnsafeMutablePointer<Int> {\n // TODO: This should use MemoryLayout<HeapObject>.offset(to: \.refcount) but we don't have KeyPaths yet\n return unsafe UnsafeMutablePointer<Int>(UnsafeRawPointer(object).advanced(by: MemoryLayout<Int>.size)._rawValue)\n}\n\nfileprivate func loadRelaxed(_ atomic: UnsafeMutablePointer<Int>) -> Int {\n Int(Builtin.atomicload_monotonic_Word(atomic._rawValue))\n}\n\nfileprivate func loadAcquire(_ atomic: UnsafeMutablePointer<Int>) -> Int {\n Int(Builtin.atomicload_acquire_Word(atomic._rawValue))\n}\n\nfileprivate func subFetchAcquireRelease(_ atomic: UnsafeMutablePointer<Int>, n: Int) -> Int {\n let oldValue = Int(Builtin.atomicrmw_sub_acqrel_Word(atomic._rawValue, n._builtinWordValue))\n return oldValue - n\n}\n\nfileprivate func addRelaxed(_ atomic: UnsafeMutablePointer<Int>, n: Int) {\n _ = Builtin.atomicrmw_add_monotonic_Word(atomic._rawValue, n._builtinWordValue)\n}\n\nfileprivate func compareExchangeRelaxed(_ atomic: UnsafeMutablePointer<Int>, expectedOldValue: Int, desiredNewValue: Int) -> Bool {\n let (_, won) = Builtin.cmpxchg_monotonic_monotonic_Word(atomic._rawValue, expectedOldValue._builtinWordValue, desiredNewValue._builtinWordValue)\n return Bool(won)\n}\n\nfileprivate func storeRelease(_ atomic: UnsafeMutablePointer<Int>, newValue: Int) {\n Builtin.atomicstore_release_Word(atomic._rawValue, newValue._builtinWordValue)\n}\n\nfileprivate func storeRelaxed(_ atomic: UnsafeMutablePointer<Int>, newValue: Int) {\n Builtin.atomicstore_monotonic_Word(atomic._rawValue, newValue._builtinWordValue)\n}\n\n/// Exclusivity checking\n\n@_cdecl("swift_beginAccess")\npublic func swift_beginAccess(pointer: UnsafeMutableRawPointer, buffer: UnsafeMutableRawPointer, flags: UInt, pc: UnsafeMutableRawPointer) {\n // TODO: Add actual exclusivity checking.\n}\n\n@_cdecl("swift_endAccess")\npublic func swift_endAccess(buffer: UnsafeMutableRawPointer) {\n // TODO: Add actual exclusivity checking.\n}\n\n\n\n// Once\n\n@_cdecl("swift_once")\npublic func swift_once(predicate: UnsafeMutablePointer<Int>, fn: (@convention(c) (UnsafeMutableRawPointer)->()), context: UnsafeMutableRawPointer) {\n let checkedLoadAcquire = { predicate in\n let value = unsafe loadAcquire(predicate)\n assert(value == -1 || value == 0 || value == 1)\n return value\n }\n\n if unsafe checkedLoadAcquire(predicate) < 0 { return }\n\n let won = unsafe compareExchangeRelaxed(predicate, expectedOldValue: 0, desiredNewValue: 1)\n if won {\n unsafe fn(context)\n unsafe storeRelease(predicate, newValue: -1)\n return\n }\n\n // TODO: This should really use an OS provided lock\n while unsafe checkedLoadAcquire(predicate) >= 0 {\n // spin\n }\n}\n\n\n\n// Misc\n\n@_cdecl("swift_deletedMethodError")\npublic func swift_deletedMethodError() -> Never {\n Builtin.int_trap()\n}\n\n@_silgen_name("swift_willThrow") // This is actually expected to be swiftcc (@_silgen_name and not @_cdecl).\npublic func swift_willThrow() throws {\n}\n\n/// Called when a typed error will be thrown.\n@_silgen_name("swift_willThrowTyped")\npublic func _willThrowTyped<E: Error>(_ error: E) {\n}\n\n@_extern(c, "arc4random_buf")\nfunc arc4random_buf(buf: UnsafeMutableRawPointer, nbytes: Int)\n\npublic func swift_stdlib_random(_ buf: UnsafeMutableRawPointer, _ nbytes: Int) {\n unsafe arc4random_buf(buf: buf, nbytes: nbytes)\n}\n\n@_cdecl("swift_clearSensitive")\n@inline(never)\npublic func swift_clearSensitive(buf: UnsafeMutableRawPointer, nbytes: Int) {\n // TODO: use memset_s if available\n // Though, it shouldn't make too much difference because the `@inline(never)` should prevent\n // the optimizer from removing the loop below.\n let bytePtr = unsafe buf.assumingMemoryBound(to: UInt8.self)\n for i in 0..<nbytes {\n unsafe bytePtr[i] = 0\n }\n}\n\n@usableFromInline\n@inline(never)\nfunc _embeddedReportFatalError(prefix: StaticString, message: StaticString) {\n print(prefix, terminator: "")\n if message.utf8CodeUnitCount > 0 { print(": ", terminator: "") }\n print(message)\n}\n\n@usableFromInline\n@inline(never)\nfunc _embeddedReportFatalErrorInFile(prefix: StaticString, message: StaticString, file: StaticString, line: UInt) {\n print(file, terminator: ":")\n print(line, terminator: ": ")\n print(prefix, terminator: "")\n if message.utf8CodeUnitCount > 0 { print(": ", terminator: "") }\n print(message)\n}\n\n@usableFromInline\n@inline(never)\nfunc _embeddedReportFatalErrorInFile(prefix: StaticString, message: UnsafeBufferPointer<UInt8>, file: StaticString, line: UInt) {\n print(file, terminator: ":")\n print(line, terminator: ": ")\n print(prefix, terminator: "")\n if message.count > 0 { print(": ", terminator: "") }\n unsafe print(message)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_EmbeddedRuntime.swift | cpp_apple_swift_stdlib_public_core_EmbeddedRuntime.swift | Swift | 25,621 | 0.95 | 0.099291 | 0.14128 | react-lib | 727 | 2024-08-30T06:29:03.099483 | Apache-2.0 | false | cce7cbc3f4a0a70bfb4e9f71eadbb684 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n/// String\n\n@_unavailableInEmbedded\ninternal func _print_unlocked<T>(_ value: T, _ target: inout String) { fatalError() }\n@_unavailableInEmbedded\npublic func _debugPrint_unlocked<T>(_ value: T, _ target: inout String) { fatalError() }\n\n/// Codable\n\n@_unavailableInEmbedded\npublic protocol Encodable {\n func encode(to encoder: any Encoder) throws\n}\n\n@_unavailableInEmbedded\npublic protocol Decodable {\n init(from decoder: any Decoder) throws\n}\n\n@_unavailableInEmbedded\npublic typealias Codable = Encodable & Decodable\n\n@_unavailableInEmbedded\npublic protocol CodingKey { }\n\n@_unavailableInEmbedded\npublic struct KeyedDecodingContainer<K: CodingKey> { }\n\n@_unavailableInEmbedded\npublic struct KeyedEncodingContainer<K: CodingKey> { }\n\n@_unavailableInEmbedded\npublic protocol UnkeyedDecodingContainer { \n mutating func decode<T>(_ type: T.Type) throws -> T\n}\n\n@_unavailableInEmbedded\npublic protocol UnkeyedEncodingContainer { \n mutating func encode<T>(_ value: T) throws\n}\n\n@_unavailableInEmbedded\npublic protocol SingleValueDecodingContainer { }\n\n@_unavailableInEmbedded\npublic protocol SingleValueEncodingContainer { }\n\n@_unavailableInEmbedded\npublic protocol Encoder {\n var codingPath: [any CodingKey] { get }\n func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key>\n func unkeyedContainer() -> any UnkeyedEncodingContainer\n func singleValueContainer() -> any SingleValueEncodingContainer\n}\n\n@_unavailableInEmbedded\npublic protocol Decoder {\n var codingPath: [any CodingKey] { get }\n func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key>\n func unkeyedContainer() throws -> any UnkeyedDecodingContainer\n func singleValueContainer() throws -> any SingleValueDecodingContainer\n}\n\n@_unavailableInEmbedded\npublic enum DecodingError: Error {\n public struct Context: Sendable {\n public init(codingPath: [any CodingKey], debugDescription: String, underlyingError: Error? = nil) { fatalError() }\n }\n case typeMismatch(Any.Type, Context)\n case valueNotFound(Any.Type, Context)\n case keyNotFound(any CodingKey, Context)\n case dataCorrupted(Context)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_EmbeddedStubs.swift | cpp_apple_swift_stdlib_public_core_EmbeddedStubs.swift | Swift | 2,648 | 0.95 | 0.022989 | 0.185714 | python-kit | 829 | 2025-01-02T16:26:35.549054 | BSD-3-Clause | false | 261142082d576b1a174be8aa5ff5c7f5 |
//===--- EmptyCollection.swift - A collection with no elements ------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// Sometimes an operation is best expressed in terms of some other,\n// larger operation where one of the parameters is an empty\n// collection. For example, we can erase elements from an Array by\n// replacing a subrange with the empty collection.\n//\n//===----------------------------------------------------------------------===//\n\n/// A collection whose element type is `Element` but that is always empty.\n@frozen // trivial-implementation\npublic struct EmptyCollection<Element> {\n // no properties\n\n /// Creates an instance.\n @inlinable // trivial-implementation\n public init() {}\n}\n\nextension EmptyCollection {\n /// An iterator that never produces an element.\n @frozen // trivial-implementation\n public struct Iterator {\n // no properties\n \n /// Creates an instance.\n @inlinable // trivial-implementation\n public init() {}\n } \n}\n\nextension EmptyCollection.Iterator: IteratorProtocol, Sequence {\n /// Returns `nil`, indicating that there are no more elements.\n @inlinable // trivial-implementation\n public mutating func next() -> Element? {\n return nil\n }\n}\n\nextension EmptyCollection: Sequence {\n /// Returns an empty iterator.\n @inlinable // trivial-implementation\n public func makeIterator() -> Iterator {\n return Iterator()\n }\n}\n\nextension EmptyCollection: RandomAccessCollection, MutableCollection {\n /// A type that represents a valid position in the collection.\n ///\n /// Valid indices consist of the position of every element and a\n /// "past the end" position that's not valid for use as a subscript.\n public typealias Index = Int\n public typealias Indices = Range<Int>\n public typealias SubSequence = EmptyCollection<Element>\n\n /// Always zero, just like `endIndex`.\n @inlinable // trivial-implementation\n public var startIndex: Index {\n return 0\n }\n\n /// Always zero, just like `startIndex`.\n @inlinable // trivial-implementation\n public var endIndex: Index {\n return 0\n }\n\n /// Always traps.\n ///\n /// `EmptyCollection` does not have any element indices, so it is not\n /// possible to advance indices.\n @inlinable // trivial-implementation\n public func index(after i: Index) -> Index {\n _preconditionFailure("EmptyCollection can't advance indices")\n }\n\n /// Always traps.\n ///\n /// `EmptyCollection` does not have any element indices, so it is not\n /// possible to advance indices.\n @inlinable // trivial-implementation\n public func index(before i: Index) -> Index {\n _preconditionFailure("EmptyCollection can't advance indices")\n }\n\n /// Accesses the element at the given position.\n ///\n /// Must never be called, since this collection is always empty.\n @inlinable // trivial-implementation\n public subscript(position: Index) -> Element {\n get {\n _preconditionFailure("Index out of range")\n }\n set {\n _preconditionFailure("Index out of range")\n }\n }\n\n @inlinable // trivial-implementation\n public subscript(bounds: Range<Index>) -> SubSequence {\n get {\n _debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,\n "Index out of range")\n return self\n }\n set {\n _debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,\n "Index out of range")\n }\n }\n\n /// The number of elements (always zero).\n @inlinable // trivial-implementation\n public var count: Int {\n return 0\n }\n\n @inlinable // trivial-implementation\n public func index(_ i: Index, offsetBy n: Int) -> Index {\n _debugPrecondition(i == startIndex && n == 0, "Index out of range")\n return i\n }\n\n @inlinable // trivial-implementation\n public func index(\n _ i: Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Index? {\n _debugPrecondition(i == startIndex && limit == startIndex,\n "Index out of range")\n return n == 0 ? i : nil\n }\n\n /// The distance between two indexes (always zero).\n @inlinable // trivial-implementation\n public func distance(from start: Index, to end: Index) -> Int {\n _debugPrecondition(start == 0, "From must be startIndex (or endIndex)")\n _debugPrecondition(end == 0, "To must be endIndex (or startIndex)")\n return 0\n }\n\n @inlinable // trivial-implementation\n public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {\n _debugPrecondition(index == 0, "out of bounds")\n _debugPrecondition(bounds == indices, "invalid bounds for an empty collection")\n }\n\n @inlinable // trivial-implementation\n public func _failEarlyRangeCheck(\n _ range: Range<Index>, bounds: Range<Index>\n ) {\n _debugPrecondition(range == indices, "invalid range for an empty collection")\n _debugPrecondition(bounds == indices, "invalid bounds for an empty collection")\n }\n}\n\nextension EmptyCollection: Equatable {\n @inlinable // trivial-implementation\n public static func == (\n lhs: EmptyCollection<Element>, rhs: EmptyCollection<Element>\n ) -> Bool {\n return true\n }\n}\n\nextension EmptyCollection: Sendable { }\nextension EmptyCollection.Iterator: Sendable { }\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_EmptyCollection.swift | cpp_apple_swift_stdlib_public_core_EmptyCollection.swift | Swift | 5,508 | 0.8 | 0.033898 | 0.288462 | python-kit | 842 | 2024-11-27T18:29:02.960430 | MIT | false | de7a6484187ed55e7e8298249f4b5571 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// An enumeration of the elements of a sequence or collection.\n///\n/// `EnumeratedSequence` is a sequence of pairs (*n*, *x*), where *n*s are\n/// consecutive `Int` values starting at zero, and *x*s are the elements of a\n/// base sequence.\n///\n/// To create an instance of `EnumeratedSequence`, call `enumerated()` on a\n/// sequence or collection. The following example enumerates the elements of\n/// an array.\n///\n/// var s = ["foo", "bar"].enumerated()\n/// for (n, x) in s {\n/// print("\(n): \(x)")\n/// }\n/// // Prints "0: foo"\n/// // Prints "1: bar"\n@frozen\npublic struct EnumeratedSequence<Base: Sequence> {\n @usableFromInline\n internal var _base: Base\n\n /// Construct from a `Base` sequence.\n @inlinable\n internal init(_base: Base) {\n self._base = _base\n }\n}\n\nextension EnumeratedSequence: Sendable where Base: Sendable {}\n\nextension EnumeratedSequence {\n /// The iterator for `EnumeratedSequence`.\n ///\n /// An instance of this iterator wraps a base iterator and yields\n /// successive `Int` values, starting at zero, along with the elements of the\n /// underlying base iterator. The following example enumerates the elements of\n /// an array:\n ///\n /// var iterator = ["foo", "bar"].enumerated().makeIterator()\n /// iterator.next() // (0, "foo")\n /// iterator.next() // (1, "bar")\n /// iterator.next() // nil\n ///\n /// To create an instance, call\n /// `enumerated().makeIterator()` on a sequence or collection.\n @frozen\n public struct Iterator {\n @usableFromInline\n internal var _base: Base.Iterator\n @usableFromInline\n internal var _count: Int\n\n /// Construct from a `Base` iterator.\n @inlinable\n internal init(_base: Base.Iterator) {\n self._base = _base\n self._count = 0\n }\n }\n}\n\nextension EnumeratedSequence.Iterator: Sendable where Base.Iterator: Sendable {}\n\nextension EnumeratedSequence.Iterator: IteratorProtocol, Sequence {\n /// The type of element returned by `next()`.\n public typealias Element = (offset: Int, element: Base.Element)\n\n /// Advances to the next element and returns it, or `nil` if no next element\n /// exists.\n ///\n /// Once `nil` has been returned, all subsequent calls return `nil`.\n @inlinable\n public mutating func next() -> Element? {\n guard let b = _base.next() else { return nil }\n let result = (offset: _count, element: b)\n _count += 1 \n return result\n }\n}\n\nextension EnumeratedSequence: Sequence {\n /// Returns an iterator over the elements of this sequence.\n @inlinable\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_base: _base.makeIterator())\n }\n}\n\n@available(SwiftStdlib 6.2, *)\nextension EnumeratedSequence: Collection where Base: Collection {\n @available(SwiftStdlib 6.2, *)\n @frozen\n public struct Index {\n /// The position in the underlying collection.\n public let base: Base.Index\n\n /// The offset corresponding to this index when `base` is not the end index,\n /// `0` otherwise.\n @usableFromInline\n let _offset: Int\n\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n init(base: Base.Index, offset: Int) {\n self.base = base\n self._offset = offset\n }\n }\n\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public var startIndex: Index {\n Index(base: _base.startIndex, offset: 0)\n }\n\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public var endIndex: Index {\n Index(base: _base.endIndex, offset: 0)\n }\n\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public var count: Int {\n _base.count\n }\n\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public var isEmpty: Bool {\n _base.isEmpty\n }\n\n /// Returns the offset corresponding to `index`.\n ///\n /// - Complexity: O(*n*) if `index == endIndex` and `Base` does not conform to\n /// `RandomAccessCollection`, O(1) otherwise.\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n func _offset(of index: Index) -> Int {\n index.base == _base.endIndex ? _base.count : index._offset\n }\n\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public func distance(from start: Index, to end: Index) -> Int {\n if start.base == _base.endIndex || end.base == _base.endIndex {\n return _base.distance(from: start.base, to: end.base)\n } else {\n return end._offset - start._offset\n }\n }\n\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public func index(after index: Index) -> Index {\n Index(base: _base.index(after: index.base), offset: index._offset + 1)\n }\n\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n let index = _base.index(i.base, offsetBy: distance)\n let offset = distance >= 0 ? i._offset : _offset(of: i)\n return Index(base: index, offset: offset + distance)\n }\n\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public func index(\n _ i: Index,\n offsetBy distance: Int,\n limitedBy limit: Index\n ) -> Index? {\n guard let index = _base.index(\n i.base,\n offsetBy: distance,\n limitedBy: limit.base\n ) else {\n return nil\n }\n\n let offset = distance >= 0 ? i._offset : _offset(of: i)\n return Index(base: index, offset: offset + distance)\n }\n\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public subscript(_ position: Index) -> Element {\n _precondition(\n _base.startIndex <= position.base && position.base < _base.endIndex,\n "Index out of bounds"\n )\n\n return (position._offset, _base[position.base])\n }\n}\n\n@available(SwiftStdlib 6.2, *)\nextension EnumeratedSequence.Index: Comparable {\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public static func ==(lhs: Self, rhs: Self) -> Bool {\n lhs.base == rhs.base\n }\n\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public static func <(lhs: Self, rhs: Self) -> Bool {\n lhs.base < rhs.base\n }\n}\n\n@available(SwiftStdlib 6.2, *)\nextension EnumeratedSequence: BidirectionalCollection where Base: BidirectionalCollection & RandomAccessCollection {\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public func index(before index: Index) -> Index {\n Index(base: _base.index(before: index.base), offset: _offset(of: index) - 1)\n }\n}\n\n@available(SwiftStdlib 6.2, *)\nextension EnumeratedSequence: RandomAccessCollection where Base: RandomAccessCollection {}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_EnumeratedSequence.swift | cpp_apple_swift_stdlib_public_core_EnumeratedSequence.swift | Swift | 6,944 | 0.8 | 0.029661 | 0.269231 | node-utils | 712 | 2023-11-19T04:58:12.934061 | Apache-2.0 | false | 67de7ff1a7d7fcce0ac375b91b2eb432 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// Equatable\n//===----------------------------------------------------------------------===//\n\n/// A type that can be compared for value equality.\n///\n/// Types that conform to the `Equatable` protocol can be compared for equality\n/// using the equal-to operator (`==`) or inequality using the not-equal-to\n/// operator (`!=`). Most basic types in the Swift standard library conform to\n/// `Equatable`.\n///\n/// Some sequence and collection operations can be used more simply when the\n/// elements conform to `Equatable`. For example, to check whether an array\n/// contains a particular value, you can pass the value itself to the\n/// `contains(_:)` method when the array's element conforms to `Equatable`\n/// instead of providing a closure that determines equivalence. The following\n/// example shows how the `contains(_:)` method can be used with an array of\n/// strings.\n///\n/// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]\n///\n/// let nameToCheck = "Kofi"\n/// if students.contains(nameToCheck) {\n/// print("\(nameToCheck) is signed up!")\n/// } else {\n/// print("No record of \(nameToCheck).")\n/// }\n/// // Prints "Kofi is signed up!"\n///\n/// Conforming to the Equatable Protocol\n/// ====================================\n///\n/// Adding `Equatable` conformance to your custom types means that you can use\n/// more convenient APIs when searching for particular instances in a\n/// collection. `Equatable` is also the base protocol for the `Hashable` and\n/// `Comparable` protocols, which allow more uses of your custom type, such as\n/// constructing sets or sorting the elements of a collection.\n///\n/// You can rely on automatic synthesis of the `Equatable` protocol's\n/// requirements for a custom type when you declare `Equatable` conformance in\n/// the type's original declaration and your type meets these criteria:\n///\n/// - For a `struct`, all its stored properties must conform to `Equatable`.\n/// - For an `enum`, all its associated values must conform to `Equatable`. (An\n/// `enum` without associated values has `Equatable` conformance even\n/// without the declaration.)\n///\n/// To customize your type's `Equatable` conformance, to adopt `Equatable` in a\n/// type that doesn't meet the criteria listed above, or to extend an existing\n/// type to conform to `Equatable`, implement the equal-to operator (`==`) as\n/// a static method of your type. The standard library provides an\n/// implementation for the not-equal-to operator (`!=`) for any `Equatable`\n/// type, which calls the custom `==` function and negates its result.\n///\n/// As an example, consider a `StreetAddress` class that holds the parts of a\n/// street address: a house or building number, the street name, and an\n/// optional unit number. Here's the initial declaration of the\n/// `StreetAddress` type:\n///\n/// class StreetAddress {\n/// let number: String\n/// let street: String\n/// let unit: String?\n///\n/// init(_ number: String, _ street: String, unit: String? = nil) {\n/// self.number = number\n/// self.street = street\n/// self.unit = unit\n/// }\n/// }\n///\n/// Now suppose you have an array of addresses that you need to check for a\n/// particular address. To use the `contains(_:)` method without including a\n/// closure in each call, extend the `StreetAddress` type to conform to\n/// `Equatable`.\n///\n/// extension StreetAddress: Equatable {\n/// static func == (lhs: StreetAddress, rhs: StreetAddress) -> Bool {\n/// return\n/// lhs.number == rhs.number &&\n/// lhs.street == rhs.street &&\n/// lhs.unit == rhs.unit\n/// }\n/// }\n///\n/// The `StreetAddress` type now conforms to `Equatable`. You can use `==` to\n/// check for equality between any two instances or call the\n/// `Equatable`-constrained `contains(_:)` method.\n///\n/// let addresses = [StreetAddress("1490", "Grove Street"),\n/// StreetAddress("2119", "Maple Avenue"),\n/// StreetAddress("1400", "16th Street")]\n/// let home = StreetAddress("1400", "16th Street")\n///\n/// print(addresses[0] == home)\n/// // Prints "false"\n/// print(addresses.contains(home))\n/// // Prints "true"\n///\n/// Equality implies substitutability---any two instances that compare equally\n/// can be used interchangeably in any code that depends on their values. To\n/// maintain substitutability, the `==` operator should take into account all\n/// visible aspects of an `Equatable` type. Exposing nonvalue aspects of\n/// `Equatable` types other than class identity is discouraged, and any that\n/// *are* exposed should be explicitly pointed out in documentation.\n///\n/// Since equality between instances of `Equatable` types is an equivalence\n/// relation, any of your custom types that conform to `Equatable` must\n/// satisfy three conditions, for any values `a`, `b`, and `c`:\n///\n/// - `a == a` is always `true` (Reflexivity)\n/// - `a == b` implies `b == a` (Symmetry)\n/// - `a == b` and `b == c` implies `a == c` (Transitivity)\n///\n/// Moreover, inequality is the inverse of equality, so any custom\n/// implementation of the `!=` operator must guarantee that `a != b` implies\n/// `!(a == b)`. The default implementation of the `!=` operator function\n/// satisfies this requirement.\n///\n/// Equality is Separate From Identity\n/// ----------------------------------\n///\n/// The identity of a class instance is not part of an instance's value.\n/// Consider a class called `IntegerRef` that wraps an integer value. Here's\n/// the definition for `IntegerRef` and the `==` function that makes it\n/// conform to `Equatable`:\n///\n/// class IntegerRef: Equatable {\n/// let value: Int\n/// init(_ value: Int) {\n/// self.value = value\n/// }\n///\n/// static func == (lhs: IntegerRef, rhs: IntegerRef) -> Bool {\n/// return lhs.value == rhs.value\n/// }\n/// }\n///\n/// The implementation of the `==` function returns the same value whether its\n/// two arguments are the same instance or are two different instances with\n/// the same integer stored in their `value` properties. For example:\n///\n/// let a = IntegerRef(100)\n/// let b = IntegerRef(100)\n///\n/// print(a == a, a == b, separator: ", ")\n/// // Prints "true, true"\n///\n/// Class instance identity, on the other hand, is compared using the\n/// triple-equals identical-to operator (`===`). For example:\n///\n/// let c = a\n/// print(c === a, c === b, separator: ", ")\n/// // Prints "true, false"\npublic protocol Equatable {\n /// Returns a Boolean value indicating whether two values are equal.\n ///\n /// Equality is the inverse of inequality. For any values `a` and `b`,\n /// `a == b` implies that `a != b` is `false`.\n ///\n /// - Parameters:\n /// - lhs: A value to compare.\n /// - rhs: Another value to compare.\n static func == (lhs: Self, rhs: Self) -> Bool\n}\n\nextension Equatable {\n /// Returns a Boolean value indicating whether two values are not equal.\n ///\n /// Inequality is the inverse of equality. For any values `a` and `b`, `a != b`\n /// implies that `a == b` is `false`.\n ///\n /// This is the default implementation of the not-equal-to operator (`!=`)\n /// for any type that conforms to `Equatable`.\n ///\n /// - Parameters:\n /// - lhs: A value to compare.\n /// - rhs: Another value to compare.\n // transparent because sometimes types that use this generate compile-time\n // warnings, e.g. that an expression always evaluates to true\n @_transparent\n public static func != (lhs: Self, rhs: Self) -> Bool {\n return !(lhs == rhs)\n }\n}\n\n// Called by the SwiftValue implementation.\n@_silgen_name("_swift_stdlib_Equatable_isEqual_indirect")\ninternal func Equatable_isEqual_indirect<T: Equatable>(\n _ lhs: UnsafePointer<T>,\n _ rhs: UnsafePointer<T>\n) -> Bool {\n return unsafe lhs.pointee == rhs.pointee\n}\n\n\n//===----------------------------------------------------------------------===//\n// Reference comparison\n//===----------------------------------------------------------------------===//\n\n/// Returns a Boolean value indicating whether two references point to the same\n/// object instance.\n///\n/// This operator tests whether two instances have the same identity, not the\n/// same value. For value equality, see the equal-to operator (`==`) and the\n/// `Equatable` protocol.\n///\n/// The following example defines an `IntegerRef` type, an integer type with\n/// reference semantics.\n///\n/// class IntegerRef: Equatable {\n/// let value: Int\n/// init(_ value: Int) {\n/// self.value = value\n/// }\n/// }\n///\n/// func == (lhs: IntegerRef, rhs: IntegerRef) -> Bool {\n/// return lhs.value == rhs.value\n/// }\n///\n/// Because `IntegerRef` is a class, its instances can be compared using the\n/// identical-to operator (`===`). In addition, because `IntegerRef` conforms\n/// to the `Equatable` protocol, instances can also be compared using the\n/// equal-to operator (`==`).\n///\n/// let a = IntegerRef(10)\n/// let b = a\n/// print(a == b)\n/// // Prints "true"\n/// print(a === b)\n/// // Prints "true"\n///\n/// The identical-to operator (`===`) returns `false` when comparing two\n/// references to different object instances, even if the two instances have\n/// the same value.\n///\n/// let c = IntegerRef(10)\n/// print(a == c)\n/// // Prints "true"\n/// print(a === c)\n/// // Prints "false"\n///\n/// - Parameters:\n/// - lhs: A reference to compare.\n/// - rhs: Another reference to compare.\n#if !$Embedded\n@inlinable // trivial-implementation\npublic func === (lhs: AnyObject?, rhs: AnyObject?) -> Bool {\n switch (lhs, rhs) {\n case let (l?, r?):\n return ObjectIdentifier(l) == ObjectIdentifier(r)\n case (nil, nil):\n return true\n default:\n return false\n }\n}\n#else\n@inlinable // trivial-implementation\n@safe\npublic func ===<T: AnyObject, U: AnyObject>(lhs: T?, rhs: U?) -> Bool {\n switch (lhs, rhs) {\n case let (l?, r?):\n return Builtin.bridgeToRawPointer(l) == Builtin.bridgeToRawPointer(r)\n case (nil, nil):\n return true\n default:\n return false\n }\n}\n#endif\n\n/// Returns a Boolean value indicating whether two references point to\n/// different object instances.\n///\n/// This operator tests whether two instances have different identities, not\n/// different values. For value inequality, see the not-equal-to operator\n/// (`!=`) and the `Equatable` protocol.\n///\n/// - Parameters:\n/// - lhs: A reference to compare.\n/// - rhs: Another reference to compare.\n#if !$Embedded\n@inlinable // trivial-implementation\npublic func !== (lhs: AnyObject?, rhs: AnyObject?) -> Bool {\n return !(lhs === rhs)\n}\n#else\n@inlinable // trivial-implementation\npublic func !==<T: AnyObject, U: AnyObject>(lhs: T, rhs: U) -> Bool {\n return !(lhs === rhs)\n}\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Equatable.swift | cpp_apple_swift_stdlib_public_core_Equatable.swift | Swift | 11,551 | 0.95 | 0.104575 | 0.842282 | react-lib | 989 | 2024-10-12T22:04:45.838055 | MIT | false | 6e53c0016f544d5a8721e79f7ad00226 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport SwiftShims\n\n/// A type representing an error value that can be thrown.\n///\n/// Any type that declares conformance to the `Error` protocol can be used to\n/// represent an error in Swift's error handling system. Because the `Error`\n/// protocol has no requirements of its own, you can declare conformance on\n/// any custom type you create.\n///\n/// Using Enumerations as Errors\n/// ============================\n///\n/// Swift's enumerations are well suited to represent simple errors. Create an\n/// enumeration that conforms to the `Error` protocol with a case for each\n/// possible error. If there are additional details about the error that could\n/// be helpful for recovery, use associated values to include that\n/// information.\n///\n/// The following example shows an `IntParsingError` enumeration that captures\n/// two different kinds of errors that can occur when parsing an integer from\n/// a string: overflow, where the value represented by the string is too large\n/// for the integer data type, and invalid input, where nonnumeric characters\n/// are found within the input.\n///\n/// enum IntParsingError: Error {\n/// case overflow\n/// case invalidInput(Character)\n/// }\n///\n/// The `invalidInput` case includes the invalid character as an associated\n/// value.\n///\n/// The next code sample shows a possible extension to the `Int` type that\n/// parses the integer value of a `String` instance, throwing an error when\n/// there is a problem during parsing.\n///\n/// extension Int {\n/// init(validating input: String) throws {\n/// // ...\n/// let c = _nextCharacter(from: input)\n/// if !_isValid(c) {\n/// throw IntParsingError.invalidInput(c)\n/// }\n/// // ...\n/// }\n/// }\n///\n/// When calling the new `Int` initializer within a `do` statement, you can use\n/// pattern matching to match specific cases of your custom error type and\n/// access their associated values, as in the example below.\n///\n/// do {\n/// let price = try Int(validating: "$100")\n/// } catch IntParsingError.invalidInput(let invalid) {\n/// print("Invalid character: '\(invalid)'")\n/// } catch IntParsingError.overflow {\n/// print("Overflow error")\n/// } catch {\n/// print("Other error")\n/// }\n/// // Prints "Invalid character: '$'"\n///\n/// Including More Data in Errors\n/// =============================\n///\n/// Sometimes you may want different error states to include the same common\n/// data, such as the position in a file or some of your application's state.\n/// When you do, use a structure to represent errors. The following example\n/// uses a structure to represent an error when parsing an XML document,\n/// including the line and column numbers where the error occurred:\n///\n/// struct XMLParsingError: Error {\n/// enum Kind {\n/// case invalidCharacter\n/// case mismatchedTag\n/// case internalError\n/// }\n///\n/// let line: Int\n/// let column: Int\n/// let kind: Kind\n/// }\n///\n/// func parse(_ source: String) throws -> XMLDoc {\n/// // ...\n/// throw XMLParsingError(line: 19, column: 5, kind: .mismatchedTag)\n/// // ...\n/// }\n///\n/// Once again, use pattern matching to conditionally catch errors. Here's how\n/// you can catch any `XMLParsingError` errors thrown by the `parse(_:)`\n/// function:\n///\n/// do {\n/// let xmlDoc = try parse(myXMLData)\n/// } catch let e as XMLParsingError {\n/// print("Parsing error: \(e.kind) [\(e.line):\(e.column)]")\n/// } catch {\n/// print("Other error: \(error)")\n/// }\n/// // Prints "Parsing error: mismatchedTag [19:5]"\npublic protocol Error: Sendable {\n#if !$Embedded\n var _domain: String { get }\n var _code: Int { get }\n\n // Note: _userInfo is always an NSDictionary, but we cannot use that type here\n // because the standard library cannot depend on Foundation. However, the\n // underscore implies that we control all implementations of this requirement.\n var _userInfo: AnyObject? { get }\n#endif\n\n#if _runtime(_ObjC)\n func _getEmbeddedNSError() -> AnyObject?\n#endif\n}\n\n#if _runtime(_ObjC)\nextension Error {\n /// Default implementation: there is no embedded NSError.\n public func _getEmbeddedNSError() -> AnyObject? { return nil }\n}\n#endif\n\n#if _runtime(_ObjC)\n// Helper functions for the C++ runtime to have easy access to embedded error,\n// domain, code, and userInfo as Objective-C values.\n@_silgen_name("")\ninternal func _getErrorDomainNSString<T: Error>(_ x: UnsafePointer<T>)\n-> AnyObject {\n return unsafe x.pointee._domain._bridgeToObjectiveCImpl()\n}\n\n@_silgen_name("")\ninternal func _getErrorCode<T: Error>(_ x: UnsafePointer<T>) -> Int {\n return unsafe x.pointee._code\n}\n\n@_silgen_name("")\ninternal func _getErrorUserInfoNSDictionary<T: Error>(_ x: UnsafePointer<T>)\n-> AnyObject? {\n return unsafe x.pointee._userInfo.map { $0 }\n}\n\n// Called by the casting machinery to extract an NSError from an Error value.\n@_silgen_name("")\ninternal func _getErrorEmbeddedNSErrorIndirect<T: Error>(\n _ x: UnsafePointer<T>) -> AnyObject? {\n return unsafe x.pointee._getEmbeddedNSError()\n}\n\n/// Called by compiler-generated code to extract an NSError from an Error value.\npublic // COMPILER_INTRINSIC\nfunc _getErrorEmbeddedNSError<T: Error>(_ x: T)\n-> AnyObject? {\n return x._getEmbeddedNSError()\n}\n\n/// Provided by the ErrorObject implementation.\n@_silgen_name("_swift_stdlib_getErrorDefaultUserInfo")\ninternal func _getErrorDefaultUserInfo<T: Error>(_ error: T) -> AnyObject?\n\n/// Provided by the ErrorObject implementation.\n/// Called by the casting machinery and by the Foundation overlay.\n@_silgen_name("_swift_stdlib_bridgeErrorToNSError")\npublic func _bridgeErrorToNSError(_ error: __owned Error) -> AnyObject\n#endif\n\n/// Called to indicate that a typed error will be thrown.\n@_silgen_name("swift_willThrowTypedImpl")\n@available(SwiftStdlib 6.0, *)\n@usableFromInline\n@_noLocks\nfunc _willThrowTypedImpl<E: Error>(_ error: E)\n\n#if !$Embedded\n/// Called when a typed error will be thrown.\n///\n/// On new-enough platforms, this will call through to the runtime to invoke\n/// the thrown error handler (if one is set).\n///\n/// On older platforms, the error will not be passed into the runtime, because\n/// doing so would require memory allocation (to create the 'any Error').\n@inlinable\n@_alwaysEmitIntoClient\n@_silgen_name("swift_willThrowTyped")\npublic func _willThrowTyped<E: Error>(_ error: E) {\n if #available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) {\n _willThrowTypedImpl(error)\n }\n}\n#endif\n\n/// Invoked by the compiler when the subexpression of a `try!` expression\n/// throws an error.\n@_silgen_name("swift_unexpectedError")\npublic func _unexpectedError(\n _ error: __owned Error,\n filenameStart: Builtin.RawPointer,\n filenameLength: Builtin.Word,\n filenameIsASCII: Builtin.Int1,\n line: Builtin.Word\n) {\n #if !$Embedded\n preconditionFailure(\n "'try!' expression unexpectedly raised an error: \(String(reflecting: error))",\n file: StaticString(\n _start: filenameStart,\n utf8CodeUnitCount: filenameLength,\n isASCII: filenameIsASCII),\n line: UInt(line))\n #else\n Builtin.int_trap()\n #endif\n}\n\n/// Invoked by the compiler when the subexpression of a `try!` expression\n/// throws an error.\n@_silgen_name("swift_unexpectedErrorTyped")\n@_alwaysEmitIntoClient\n@inlinable\npublic func _unexpectedErrorTyped<E: Error>(\n _ error: __owned E,\n filenameStart: Builtin.RawPointer,\n filenameLength: Builtin.Word,\n filenameIsASCII: Builtin.Int1,\n line: Builtin.Word\n) {\n #if !$Embedded\n _unexpectedError(\n error, filenameStart: filenameStart, filenameLength: filenameLength,\n filenameIsASCII: filenameIsASCII, line: line\n )\n #else\n Builtin.int_trap()\n #endif\n}\n\n/// Invoked by the compiler when code at top level throws an uncaught error.\n@_silgen_name("swift_errorInMain")\npublic func _errorInMain(_ error: Error) {\n #if !$Embedded\n fatalError("Error raised at top level: \(String(reflecting: error))")\n #else\n Builtin.int_trap()\n #endif\n}\n\n/// Invoked by the compiler when code at top level throws an uncaught, typed error.\n@_alwaysEmitIntoClient\npublic func _errorInMainTyped<Failure: Error>(_ error: Failure) -> Never {\n #if !$Embedded\n fatalError("Error raised at top level: \(String(reflecting: error))")\n #else\n Builtin.int_trap()\n #endif\n}\n\n/// Runtime function to determine the default code for an Error-conforming type.\n/// Called by the Foundation overlay.\n@_silgen_name("_swift_stdlib_getDefaultErrorCode")\npublic func _getDefaultErrorCode<T: Error>(_ error: T) -> Int\n\n#if !$Embedded\nextension Error {\n public var _code: Int {\n return _getDefaultErrorCode(self)\n }\n\n public var _domain: String {\n return _typeName(type(of: self), qualified: true)\n }\n\n public var _userInfo: AnyObject? {\n#if _runtime(_ObjC)\n return _getErrorDefaultUserInfo(self)\n#else\n return nil\n#endif\n }\n}\n#endif\n\nextension Error where Self: RawRepresentable, Self.RawValue: FixedWidthInteger {\n // The error code of Error with integral raw values is the raw value.\n public var _code: Int {\n if Self.RawValue.isSigned {\n return numericCast(self.rawValue)\n }\n\n let uintValue: UInt = numericCast(self.rawValue)\n return Int(bitPattern: uintValue)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ErrorType.swift | cpp_apple_swift_stdlib_public_core_ErrorType.swift | Swift | 9,939 | 0.95 | 0.118033 | 0.585106 | python-kit | 495 | 2023-11-06T22:40:38.749501 | GPL-3.0 | false | e0d322e3c0403fa9fd31dcfb34a23430 |
//===--- ExistentialCollection.swift --------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// TODO: swift-3-indexing-model: perform type erasure on the associated\n// `Indices` type.\n\nimport SwiftShims\n\n@inline(never)\n@usableFromInline\ninternal func _abstract(\n file: StaticString = #file,\n line: UInt = #line\n) -> Never {\n fatalError("Method must be overridden", file: file, line: line)\n}\n\n//===--- Iterator ---------------------------------------------------------===//\n//===----------------------------------------------------------------------===//\n\n/// A type-erased iterator of `Element`.\n///\n/// This iterator forwards its `next()` method to an arbitrary underlying\n/// iterator having the same `Element` type, hiding the specifics of the\n/// underlying `IteratorProtocol`.\n@frozen\npublic struct AnyIterator<Element> {\n @usableFromInline\n internal let _box: _AnyIteratorBoxBase<Element>\n\n /// Creates an iterator that wraps a base iterator but whose type depends\n /// only on the base iterator's element type.\n ///\n /// You can use `AnyIterator` to hide the type signature of a more complex\n /// iterator. For example, the `digits()` function in the following example\n /// creates an iterator over a collection that lazily maps the elements of a\n /// `Range<Int>` instance to strings. Instead of returning an\n /// iterator with a type that encapsulates the implementation of the\n /// collection, the `digits()` function first wraps the iterator in an\n /// `AnyIterator` instance.\n ///\n /// func digits() -> AnyIterator<String> {\n /// let lazyStrings = (0..<10).lazy.map { String($0) }\n /// let iterator:\n /// LazyMapSequence<Range<Int>, String>.Iterator\n /// = lazyStrings.makeIterator()\n ///\n /// return AnyIterator(iterator)\n /// }\n ///\n /// - Parameter base: An iterator to type-erase.\n @inlinable\n public init<I: IteratorProtocol>(_ base: I) where I.Element == Element {\n self._box = _IteratorBox(base)\n }\n\n /// Creates an iterator that wraps the given closure in its `next()` method.\n ///\n /// The following example creates an iterator that counts up from the initial\n /// value of an integer `x` to 15:\n ///\n /// var x = 7\n /// let iterator: AnyIterator<Int> = AnyIterator {\n /// defer { x += 1 }\n /// return x < 15 ? x : nil\n /// }\n /// let a = Array(iterator)\n /// // a == [7, 8, 9, 10, 11, 12, 13, 14]\n ///\n /// - Parameter body: A closure that returns an optional element. `body` is\n /// executed each time the `next()` method is called on the resulting\n /// iterator.\n @inlinable\n public init(_ body: @escaping () -> Element?) {\n self._box = _IteratorBox(_ClosureBasedIterator(body))\n }\n\n @inlinable\n internal init(_box: _AnyIteratorBoxBase<Element>) {\n self._box = _box\n }\n}\n\n@available(*, unavailable)\nextension AnyIterator: Sendable {}\n\nextension AnyIterator: IteratorProtocol {\n /// Advances to the next element and returns it, or `nil` if no next element\n /// exists.\n ///\n /// Once `nil` has been returned, all subsequent calls return `nil`.\n @inlinable\n public func next() -> Element? {\n return _box.next()\n }\n}\n\n/// Every `IteratorProtocol` can also be a `Sequence`. Note that\n/// traversing the sequence consumes the iterator.\nextension AnyIterator: Sequence { }\n\n@usableFromInline\n@frozen\ninternal struct _ClosureBasedIterator<Element>: IteratorProtocol {\n @usableFromInline\n internal let _body: () -> Element?\n\n @inlinable\n internal init(_ body: @escaping () -> Element?) {\n self._body = body\n }\n\n @inlinable\n internal func next() -> Element? { return _body() }\n}\n\n@available(*, unavailable)\nextension _ClosureBasedIterator: Sendable {}\n\n@_fixed_layout\n@usableFromInline\ninternal class _AnyIteratorBoxBase<Element>: IteratorProtocol {\n @inlinable // FIXME(sil-serialize-all)\n internal init() {}\n\n @inlinable // FIXME(sil-serialize-all)\n deinit {}\n\n /// Advances to the next element and returns it, or `nil` if no next element\n /// exists.\n ///\n /// Once `nil` has been returned, all subsequent calls return `nil`.\n ///\n /// - Note: Subclasses must override this method.\n @inlinable // FIXME(sil-serialize-all)\n internal func next() -> Element? { _abstract() }\n}\n\n@available(*, unavailable)\nextension _AnyIteratorBoxBase: Sendable {}\n\n@_fixed_layout\n@usableFromInline\ninternal final class _IteratorBox<Base: IteratorProtocol>\n : _AnyIteratorBoxBase<Base.Element> {\n\n @inlinable\n internal init(_ base: Base) { self._base = base }\n \n @inlinable // FIXME(sil-serialize-all)\n deinit {}\n \n @inlinable\n internal override func next() -> Base.Element? { return _base.next() }\n \n @usableFromInline\n internal var _base: Base\n}\n\n//===--- Sequence ---------------------------------------------------------===//\n//===----------------------------------------------------------------------===//\n\n@_fixed_layout\n@usableFromInline\ninternal class _AnySequenceBox<Element> {\n @inlinable // FIXME(sil-serialize-all)\n internal init() { }\n\n @inlinable\n internal func _makeIterator() -> AnyIterator<Element> { _abstract() }\n\n @inlinable\n internal var _underestimatedCount: Int { _abstract() }\n\n @inlinable\n internal func _map<T>(\n _ transform: (Element) throws -> T\n ) throws -> [T] {\n _abstract()\n }\n\n @inlinable\n internal func _filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n _abstract()\n }\n\n @inlinable\n internal func _forEach(\n _ body: (Element) throws -> Void\n ) rethrows {\n _abstract()\n }\n\n @inlinable\n internal func __customContainsEquatableElement(\n _ element: Element\n ) -> Bool? {\n _abstract()\n }\n\n @inlinable\n internal func __copyToContiguousArray() -> ContiguousArray<Element> {\n _abstract()\n }\n\n @inlinable\n internal func __copyContents(\n initializing buf: UnsafeMutableBufferPointer<Element>\n ) -> (AnyIterator<Element>, UnsafeMutableBufferPointer<Element>.Index) {\n _abstract()\n }\n\n // This deinit has to be present on all the types\n @inlinable // FIXME(sil-serialize-all)\n deinit {}\n\n @inlinable\n internal func _drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnySequenceBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal func _dropFirst(_ n: Int) -> _AnySequenceBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal func _dropLast(_ n: Int) -> [Element] {\n _abstract()\n }\n\n @inlinable\n internal func _prefix(_ maxLength: Int) -> _AnySequenceBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal func _prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> [Element] {\n _abstract()\n }\n\n @inlinable\n internal func _suffix(_ maxLength: Int) -> [Element] {\n _abstract()\n }\n}\n\n@available(*, unavailable)\nextension _AnySequenceBox: Sendable {}\n\n@_fixed_layout\n@usableFromInline\ninternal class _AnyCollectionBox<Element>: _AnySequenceBox<Element> {\n\n // This deinit has to be present on all the types\n @inlinable // FIXME(sil-serialize-all)\n deinit {}\n\n @inlinable\n internal override func _drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _dropFirst(_ n: Int) -> _AnyCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal func _dropLast(_ n: Int) -> _AnyCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _prefix(\n _ maxLength: Int\n ) -> _AnyCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal func _prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal func _suffix(_ maxLength: Int) -> _AnyCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal subscript(i: _AnyIndexBox) -> Element { _abstract() }\n\n @inlinable\n internal func _index(after i: _AnyIndexBox) -> _AnyIndexBox { _abstract() }\n\n @inlinable\n internal func _formIndex(after i: _AnyIndexBox) { _abstract() }\n\n @inlinable\n internal func _index(\n _ i: _AnyIndexBox,\n offsetBy n: Int\n ) -> _AnyIndexBox {\n _abstract()\n }\n\n @inlinable\n internal func _index(\n _ i: _AnyIndexBox,\n offsetBy n: Int,\n limitedBy limit: _AnyIndexBox\n ) -> _AnyIndexBox? {\n _abstract()\n }\n\n @inlinable\n internal func _formIndex(_ i: inout _AnyIndexBox, offsetBy n: Int) {\n _abstract()\n }\n\n @inlinable\n internal func _formIndex(\n _ i: inout _AnyIndexBox,\n offsetBy n: Int,\n limitedBy limit: _AnyIndexBox\n ) -> Bool {\n _abstract()\n }\n\n @inlinable\n internal func _distance(\n from start: _AnyIndexBox,\n to end: _AnyIndexBox\n ) -> Int {\n _abstract()\n }\n\n // TODO: swift-3-indexing-model: forward the following methods.\n /*\n var _indices: Indices\n\n __consuming func prefix(upTo end: Index) -> SubSequence\n\n __consuming func suffix(from start: Index) -> SubSequence\n\n func prefix(through position: Index) -> SubSequence\n\n var isEmpty: Bool { get }\n */\n\n @inlinable // FIXME(sil-serialize-all)\n internal var _count: Int { _abstract() }\n\n // TODO: swift-3-indexing-model: forward the following methods.\n /*\n func _customIndexOfEquatableElement(element: Element) -> Index??\n func _customLastIndexOfEquatableElement(element: Element) -> Index??\n */\n\n @inlinable\n internal init(\n _startIndex: _AnyIndexBox,\n endIndex: _AnyIndexBox\n ) {\n self._startIndex = _startIndex\n self._endIndex = endIndex\n }\n\n @usableFromInline\n internal let _startIndex: _AnyIndexBox\n\n @usableFromInline\n internal let _endIndex: _AnyIndexBox\n\n @inlinable\n internal subscript(\n start start: _AnyIndexBox,\n end end: _AnyIndexBox\n ) -> _AnyCollectionBox<Element> { _abstract() }\n}\n\n@_fixed_layout\n@usableFromInline\ninternal class _AnyBidirectionalCollectionBox<Element>\n : _AnyCollectionBox<Element>\n{\n @inlinable // FIXME(sil-serialize-all)\n deinit {}\n\n @inlinable\n internal override func _drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyBidirectionalCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _dropFirst(\n _ n: Int\n ) -> _AnyBidirectionalCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _dropLast(\n _ n: Int\n ) -> _AnyBidirectionalCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _prefix(\n _ maxLength: Int\n ) -> _AnyBidirectionalCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyBidirectionalCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _suffix(\n _ maxLength: Int\n ) -> _AnyBidirectionalCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override subscript(\n start start: _AnyIndexBox,\n end end: _AnyIndexBox\n ) -> _AnyBidirectionalCollectionBox<Element> { _abstract() }\n\n @inlinable\n internal func _index(before i: _AnyIndexBox) -> _AnyIndexBox { _abstract() }\n\n @inlinable\n internal func _formIndex(before i: _AnyIndexBox) { _abstract() }\n}\n\n@_fixed_layout\n@usableFromInline\ninternal class _AnyRandomAccessCollectionBox<Element>\n : _AnyBidirectionalCollectionBox<Element>\n{\n @inlinable // FIXME(sil-serialize-all)\n deinit {}\n\n @inlinable\n internal override func _drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyRandomAccessCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _dropFirst(\n _ n: Int\n ) -> _AnyRandomAccessCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _dropLast(\n _ n: Int\n ) -> _AnyRandomAccessCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _prefix(\n _ maxLength: Int\n ) -> _AnyRandomAccessCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyRandomAccessCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override func _suffix(\n _ maxLength: Int\n ) -> _AnyRandomAccessCollectionBox<Element> {\n _abstract()\n }\n\n @inlinable\n internal override subscript(\n start start: _AnyIndexBox,\n end end: _AnyIndexBox\n ) -> _AnyRandomAccessCollectionBox<Element> { _abstract() }\n}\n\n@_fixed_layout\n@usableFromInline\ninternal final class _SequenceBox<S: Sequence>: _AnySequenceBox<S.Element> {\n @usableFromInline\n internal typealias Element = S.Element\n\n @inline(__always)\n @inlinable\n internal override func _makeIterator() -> AnyIterator<Element> {\n return AnyIterator(_base.makeIterator())\n }\n @inlinable\n internal override var _underestimatedCount: Int {\n return _base.underestimatedCount\n }\n @inlinable\n internal override func _map<T>(\n _ transform: (Element) throws -> T\n ) throws -> [T] {\n try _base.map(transform)\n }\n @inlinable\n internal override func _filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _base.filter(isIncluded)\n }\n @inlinable\n internal override func _forEach(\n _ body: (Element) throws -> Void\n ) rethrows {\n return try _base.forEach(body)\n }\n @inlinable\n internal override func __customContainsEquatableElement(\n _ element: Element\n ) -> Bool? {\n return _base._customContainsEquatableElement(element)\n }\n @inlinable\n internal override func __copyToContiguousArray() -> ContiguousArray<Element> {\n return _base._copyToContiguousArray()\n }\n @inlinable\n internal override func __copyContents(\n initializing buf: UnsafeMutableBufferPointer<Element>\n ) -> (AnyIterator<Element>,UnsafeMutableBufferPointer<Element>.Index) {\n let (it,idx) = unsafe _base._copyContents(initializing: buf)\n return (AnyIterator(it),idx)\n }\n\n @inlinable\n internal override func _dropFirst(_ n: Int) -> _AnySequenceBox<Element> {\n return _SequenceBox<DropFirstSequence<S>>(_base: _base.dropFirst(n))\n }\n @inlinable\n internal override func _drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnySequenceBox<Element> {\n return try _SequenceBox<DropWhileSequence<S>>(_base: _base.drop(while: predicate))\n }\n @inlinable\n internal override func _dropLast(_ n: Int) -> [Element] {\n return _base.dropLast(n)\n }\n @inlinable\n internal override func _prefix(_ n: Int) -> _AnySequenceBox<Element> {\n return _SequenceBox<PrefixSequence<S>>(_base: _base.prefix(n))\n }\n @inlinable\n internal override func _prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _base.prefix(while: predicate)\n }\n @inlinable\n internal override func _suffix(_ maxLength: Int) -> [Element] {\n return _base.suffix(maxLength)\n }\n\n @inlinable // FIXME(sil-serialize-all)\n deinit {}\n\n @inlinable\n internal init(_base: S) {\n self._base = _base\n }\n\n @usableFromInline\n internal var _base: S\n}\n\n@_fixed_layout\n@usableFromInline\ninternal final class _CollectionBox<S: Collection>: _AnyCollectionBox<S.Element>\n{\n @usableFromInline\n internal typealias Element = S.Element\n\n @inline(__always)\n @inlinable\n internal override func _makeIterator() -> AnyIterator<Element> {\n return AnyIterator(_base.makeIterator())\n }\n @inlinable\n internal override var _underestimatedCount: Int {\n return _base.underestimatedCount\n }\n @inlinable\n internal override func _map<T>(\n _ transform: (Element) throws -> T\n ) throws -> [T] {\n try _base.map(transform)\n }\n @inlinable\n internal override func _filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _base.filter(isIncluded)\n }\n @inlinable\n internal override func _forEach(\n _ body: (Element) throws -> Void\n ) rethrows {\n return try _base.forEach(body)\n }\n @inlinable\n internal override func __customContainsEquatableElement(\n _ element: Element\n ) -> Bool? {\n return _base._customContainsEquatableElement(element)\n }\n @inlinable\n internal override func __copyToContiguousArray() -> ContiguousArray<Element> {\n return _base._copyToContiguousArray()\n }\n @inlinable\n internal override func __copyContents(\n initializing buf: UnsafeMutableBufferPointer<Element>\n ) -> (AnyIterator<Element>,UnsafeMutableBufferPointer<Element>.Index) {\n let (it,idx) = unsafe _base._copyContents(initializing: buf)\n return (AnyIterator(it),idx)\n }\n\n @inline(__always)\n @inlinable\n internal override func _drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyCollectionBox<Element> {\n return try _CollectionBox<S.SubSequence>(_base: _base.drop(while: predicate))\n }\n @inline(__always)\n @inlinable\n internal override func _dropFirst(_ n: Int) -> _AnyCollectionBox<Element> {\n return _CollectionBox<S.SubSequence>(_base: _base.dropFirst(n))\n }\n @inline(__always)\n @inlinable\n internal override func _dropLast(_ n: Int) -> _AnyCollectionBox<Element> {\n return _CollectionBox<S.SubSequence>(_base: _base.dropLast(n))\n }\n @inline(__always)\n @inlinable\n internal override func _prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyCollectionBox<Element> {\n return try _CollectionBox<S.SubSequence>(_base: _base.prefix(while: predicate))\n }\n @inline(__always)\n @inlinable\n internal override func _prefix(\n _ maxLength: Int\n ) -> _AnyCollectionBox<Element> {\n return _CollectionBox<S.SubSequence>(_base: _base.prefix(maxLength))\n }\n @inline(__always)\n @inlinable\n internal override func _suffix(\n _ maxLength: Int\n ) -> _AnyCollectionBox<Element> {\n return _CollectionBox<S.SubSequence>(_base: _base.suffix(maxLength))\n }\n\n @inlinable // FIXME(sil-serialize-all)\n deinit {}\n\n @inlinable\n internal init(_base: S) {\n self._base = _base\n super.init(\n _startIndex: _IndexBox(_base: _base.startIndex),\n endIndex: _IndexBox(_base: _base.endIndex)\n )\n }\n\n @inlinable\n internal func _unbox(\n _ position: _AnyIndexBox, file: StaticString = #file, line: UInt = #line\n ) -> S.Index {\n if let i = position._unbox() as S.Index? {\n return i\n }\n fatalError("Index type mismatch!", file: file, line: line)\n }\n\n @inlinable\n internal override subscript(position: _AnyIndexBox) -> Element {\n return _base[_unbox(position)]\n }\n\n @inlinable\n internal override subscript(start start: _AnyIndexBox, end end: _AnyIndexBox)\n -> _AnyCollectionBox<Element>\n {\n return _CollectionBox<S.SubSequence>(_base:\n _base[_unbox(start)..<_unbox(end)]\n )\n }\n\n @inlinable\n internal override func _index(after position: _AnyIndexBox) -> _AnyIndexBox {\n return _IndexBox(_base: _base.index(after: _unbox(position)))\n }\n\n @inlinable\n internal override func _formIndex(after position: _AnyIndexBox) {\n if let p = position as? _IndexBox<S.Index> {\n return _base.formIndex(after: &p._base)\n }\n fatalError("Index type mismatch!")\n }\n\n @inlinable\n internal override func _index(\n _ i: _AnyIndexBox, offsetBy n: Int\n ) -> _AnyIndexBox {\n return _IndexBox(_base: _base.index(_unbox(i), offsetBy: n))\n }\n\n @inlinable\n internal override func _index(\n _ i: _AnyIndexBox,\n offsetBy n: Int,\n limitedBy limit: _AnyIndexBox\n ) -> _AnyIndexBox? {\n return _base.index(_unbox(i), offsetBy: n, limitedBy: _unbox(limit))\n .map { _IndexBox(_base: $0) }\n }\n\n @inlinable\n internal override func _formIndex(\n _ i: inout _AnyIndexBox, offsetBy n: Int\n ) {\n if let box = i as? _IndexBox<S.Index> {\n return _base.formIndex(&box._base, offsetBy: n)\n }\n fatalError("Index type mismatch!")\n }\n\n @inlinable\n internal override func _formIndex(\n _ i: inout _AnyIndexBox, offsetBy n: Int, limitedBy limit: _AnyIndexBox\n ) -> Bool {\n if let box = i as? _IndexBox<S.Index> {\n return _base.formIndex(&box._base, offsetBy: n, limitedBy: _unbox(limit))\n }\n fatalError("Index type mismatch!")\n }\n\n @inlinable\n internal override func _distance(\n from start: _AnyIndexBox,\n to end: _AnyIndexBox\n ) -> Int {\n return _base.distance(from: _unbox(start), to: _unbox(end))\n }\n\n @inlinable\n internal override var _count: Int {\n return _base.count\n }\n\n @usableFromInline\n internal var _base: S\n}\n\n@_fixed_layout\n@usableFromInline\ninternal final class _BidirectionalCollectionBox<S: BidirectionalCollection>\n : _AnyBidirectionalCollectionBox<S.Element>\n{\n @usableFromInline\n internal typealias Element = S.Element\n\n @inline(__always)\n @inlinable\n internal override func _makeIterator() -> AnyIterator<Element> {\n return AnyIterator(_base.makeIterator())\n }\n @inlinable\n internal override var _underestimatedCount: Int {\n return _base.underestimatedCount\n }\n @inlinable\n internal override func _map<T>(\n _ transform: (Element) throws -> T\n ) throws -> [T] {\n try _base.map(transform)\n }\n @inlinable\n internal override func _filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _base.filter(isIncluded)\n }\n @inlinable\n internal override func _forEach(\n _ body: (Element) throws -> Void\n ) rethrows {\n return try _base.forEach(body)\n }\n @inlinable\n internal override func __customContainsEquatableElement(\n _ element: Element\n ) -> Bool? {\n return _base._customContainsEquatableElement(element)\n }\n @inlinable\n internal override func __copyToContiguousArray() -> ContiguousArray<Element> {\n return _base._copyToContiguousArray()\n }\n @inlinable\n internal override func __copyContents(\n initializing buf: UnsafeMutableBufferPointer<Element>\n ) -> (AnyIterator<Element>,UnsafeMutableBufferPointer<Element>.Index) {\n let (it,idx) = unsafe _base._copyContents(initializing: buf)\n return (AnyIterator(it),idx)\n }\n\n @inline(__always)\n @inlinable\n internal override func _drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyBidirectionalCollectionBox<Element> {\n return try _BidirectionalCollectionBox<S.SubSequence>(_base: _base.drop(while: predicate))\n }\n @inline(__always)\n @inlinable\n internal override func _dropFirst(\n _ n: Int\n ) -> _AnyBidirectionalCollectionBox<Element> {\n return _BidirectionalCollectionBox<S.SubSequence>(_base: _base.dropFirst(n))\n }\n @inline(__always)\n @inlinable\n internal override func _dropLast(\n _ n: Int\n ) -> _AnyBidirectionalCollectionBox<Element> {\n return _BidirectionalCollectionBox<S.SubSequence>(_base: _base.dropLast(n))\n }\n @inline(__always)\n @inlinable\n internal override func _prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyBidirectionalCollectionBox<Element> {\n return try _BidirectionalCollectionBox<S.SubSequence>(_base: _base.prefix(while: predicate))\n }\n @inline(__always)\n @inlinable\n internal override func _prefix(\n _ maxLength: Int\n ) -> _AnyBidirectionalCollectionBox<Element> {\n return _BidirectionalCollectionBox<S.SubSequence>(_base: _base.prefix(maxLength))\n }\n @inline(__always)\n @inlinable\n internal override func _suffix(\n _ maxLength: Int\n ) -> _AnyBidirectionalCollectionBox<Element> {\n return _BidirectionalCollectionBox<S.SubSequence>(_base: _base.suffix(maxLength))\n }\n\n @inlinable // FIXME(sil-serialize-all)\n deinit {}\n\n @inlinable\n internal init(_base: S) {\n self._base = _base\n super.init(\n _startIndex: _IndexBox(_base: _base.startIndex),\n endIndex: _IndexBox(_base: _base.endIndex)\n )\n }\n\n @inlinable\n internal func _unbox(\n _ position: _AnyIndexBox, file: StaticString = #file, line: UInt = #line\n ) -> S.Index {\n if let i = position._unbox() as S.Index? {\n return i\n }\n fatalError("Index type mismatch!", file: file, line: line)\n }\n\n @inlinable\n internal override subscript(position: _AnyIndexBox) -> Element {\n return _base[_unbox(position)]\n }\n\n @inlinable\n internal override subscript(\n start start: _AnyIndexBox,\n end end: _AnyIndexBox\n ) -> _AnyBidirectionalCollectionBox<Element> {\n return _BidirectionalCollectionBox<S.SubSequence>(_base:\n _base[_unbox(start)..<_unbox(end)]\n )\n }\n\n @inlinable\n internal override func _index(after position: _AnyIndexBox) -> _AnyIndexBox {\n return _IndexBox(_base: _base.index(after: _unbox(position)))\n }\n\n @inlinable\n internal override func _formIndex(after position: _AnyIndexBox) {\n if let p = position as? _IndexBox<S.Index> {\n return _base.formIndex(after: &p._base)\n }\n fatalError("Index type mismatch!")\n }\n\n @inlinable\n internal override func _index(\n _ i: _AnyIndexBox, offsetBy n: Int\n ) -> _AnyIndexBox {\n return _IndexBox(_base: _base.index(_unbox(i), offsetBy: n))\n }\n\n @inlinable\n internal override func _index(\n _ i: _AnyIndexBox,\n offsetBy n: Int,\n limitedBy limit: _AnyIndexBox\n ) -> _AnyIndexBox? {\n return _base.index(_unbox(i), offsetBy: n, limitedBy: _unbox(limit))\n .map { _IndexBox(_base: $0) }\n }\n\n @inlinable\n internal override func _formIndex(\n _ i: inout _AnyIndexBox, offsetBy n: Int\n ) {\n if let box = i as? _IndexBox<S.Index> {\n return _base.formIndex(&box._base, offsetBy: n)\n }\n fatalError("Index type mismatch!")\n }\n\n @inlinable\n internal override func _formIndex(\n _ i: inout _AnyIndexBox, offsetBy n: Int, limitedBy limit: _AnyIndexBox\n ) -> Bool {\n if let box = i as? _IndexBox<S.Index> {\n return _base.formIndex(&box._base, offsetBy: n, limitedBy: _unbox(limit))\n }\n fatalError("Index type mismatch!")\n }\n\n @inlinable\n internal override func _distance(\n from start: _AnyIndexBox,\n to end: _AnyIndexBox\n ) -> Int {\n return _base.distance(from: _unbox(start), to: _unbox(end))\n }\n\n @inlinable\n internal override var _count: Int {\n return _base.count\n }\n\n @inlinable\n internal override func _index(before position: _AnyIndexBox) -> _AnyIndexBox {\n return _IndexBox(_base: _base.index(before: _unbox(position)))\n }\n\n @inlinable\n internal override func _formIndex(before position: _AnyIndexBox) {\n if let p = position as? _IndexBox<S.Index> {\n return _base.formIndex(before: &p._base)\n }\n fatalError("Index type mismatch!")\n }\n\n @usableFromInline\n internal var _base: S\n}\n\n@_fixed_layout\n@usableFromInline\ninternal final class _RandomAccessCollectionBox<S: RandomAccessCollection>\n : _AnyRandomAccessCollectionBox<S.Element>\n{\n @usableFromInline\n internal typealias Element = S.Element\n\n @inline(__always)\n @inlinable\n internal override func _makeIterator() -> AnyIterator<Element> {\n return AnyIterator(_base.makeIterator())\n }\n @inlinable\n internal override var _underestimatedCount: Int {\n return _base.underestimatedCount\n }\n @inlinable\n internal override func _map<T>(\n _ transform: (Element) throws -> T\n ) throws -> [T] {\n try _base.map(transform)\n }\n @inlinable\n internal override func _filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _base.filter(isIncluded)\n }\n @inlinable\n internal override func _forEach(\n _ body: (Element) throws -> Void\n ) rethrows {\n return try _base.forEach(body)\n }\n @inlinable\n internal override func __customContainsEquatableElement(\n _ element: Element\n ) -> Bool? {\n return _base._customContainsEquatableElement(element)\n }\n @inlinable\n internal override func __copyToContiguousArray() -> ContiguousArray<Element> {\n return _base._copyToContiguousArray()\n }\n @inlinable\n internal override func __copyContents(\n initializing buf: UnsafeMutableBufferPointer<Element>\n ) -> (AnyIterator<Element>,UnsafeMutableBufferPointer<Element>.Index) {\n let (it,idx) = unsafe _base._copyContents(initializing: buf)\n return (AnyIterator(it),idx)\n }\n\n @inline(__always)\n @inlinable\n internal override func _drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyRandomAccessCollectionBox<Element> {\n return try _RandomAccessCollectionBox<S.SubSequence>(_base: _base.drop(while: predicate))\n }\n @inline(__always)\n @inlinable\n internal override func _dropFirst(\n _ n: Int\n ) -> _AnyRandomAccessCollectionBox<Element> {\n return _RandomAccessCollectionBox<S.SubSequence>(_base: _base.dropFirst(n))\n }\n @inline(__always)\n @inlinable\n internal override func _dropLast(\n _ n: Int\n ) -> _AnyRandomAccessCollectionBox<Element> {\n return _RandomAccessCollectionBox<S.SubSequence>(_base: _base.dropLast(n))\n }\n @inline(__always)\n @inlinable\n internal override func _prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> _AnyRandomAccessCollectionBox<Element> {\n return try _RandomAccessCollectionBox<S.SubSequence>(_base: _base.prefix(while: predicate))\n }\n @inline(__always)\n @inlinable\n internal override func _prefix(\n _ maxLength: Int\n ) -> _AnyRandomAccessCollectionBox<Element> {\n return _RandomAccessCollectionBox<S.SubSequence>(_base: _base.prefix(maxLength))\n }\n @inline(__always)\n @inlinable\n internal override func _suffix(\n _ maxLength: Int\n ) -> _AnyRandomAccessCollectionBox<Element> {\n return _RandomAccessCollectionBox<S.SubSequence>(_base: _base.suffix(maxLength))\n }\n\n @inlinable // FIXME(sil-serialize-all)\n deinit {}\n\n @inlinable\n internal init(_base: S) {\n self._base = _base\n super.init(\n _startIndex: _IndexBox(_base: _base.startIndex),\n endIndex: _IndexBox(_base: _base.endIndex)\n )\n }\n\n @inlinable\n internal func _unbox(\n _ position: _AnyIndexBox, file: StaticString = #file, line: UInt = #line\n ) -> S.Index {\n if let i = position._unbox() as S.Index? {\n return i\n }\n fatalError("Index type mismatch!", file: file, line: line)\n }\n\n @inlinable\n internal override subscript(position: _AnyIndexBox) -> Element {\n return _base[_unbox(position)]\n }\n\n @inlinable\n internal override subscript(start start: _AnyIndexBox, end end: _AnyIndexBox)\n -> _AnyRandomAccessCollectionBox<Element>\n {\n return _RandomAccessCollectionBox<S.SubSequence>(_base:\n _base[_unbox(start)..<_unbox(end)]\n )\n }\n\n @inlinable\n internal override func _index(after position: _AnyIndexBox) -> _AnyIndexBox {\n return _IndexBox(_base: _base.index(after: _unbox(position)))\n }\n\n @inlinable\n internal override func _formIndex(after position: _AnyIndexBox) {\n if let p = position as? _IndexBox<S.Index> {\n return _base.formIndex(after: &p._base)\n }\n fatalError("Index type mismatch!")\n }\n\n @inlinable\n internal override func _index(\n _ i: _AnyIndexBox, offsetBy n: Int\n ) -> _AnyIndexBox {\n return _IndexBox(_base: _base.index(_unbox(i), offsetBy: n))\n }\n\n @inlinable\n internal override func _index(\n _ i: _AnyIndexBox,\n offsetBy n: Int,\n limitedBy limit: _AnyIndexBox\n ) -> _AnyIndexBox? {\n return _base.index(_unbox(i), offsetBy: n, limitedBy: _unbox(limit))\n .map { _IndexBox(_base: $0) }\n }\n\n @inlinable\n internal override func _formIndex(\n _ i: inout _AnyIndexBox, offsetBy n: Int\n ) {\n if let box = i as? _IndexBox<S.Index> {\n return _base.formIndex(&box._base, offsetBy: n)\n }\n fatalError("Index type mismatch!")\n }\n\n @inlinable\n internal override func _formIndex(\n _ i: inout _AnyIndexBox, offsetBy n: Int, limitedBy limit: _AnyIndexBox\n ) -> Bool {\n if let box = i as? _IndexBox<S.Index> {\n return _base.formIndex(&box._base, offsetBy: n, limitedBy: _unbox(limit))\n }\n fatalError("Index type mismatch!")\n }\n\n @inlinable\n internal override func _distance(\n from start: _AnyIndexBox,\n to end: _AnyIndexBox\n ) -> Int {\n return _base.distance(from: _unbox(start), to: _unbox(end))\n }\n\n @inlinable\n internal override var _count: Int {\n return _base.count\n }\n\n @inlinable\n internal override func _index(before position: _AnyIndexBox) -> _AnyIndexBox {\n return _IndexBox(_base: _base.index(before: _unbox(position)))\n }\n\n @inlinable\n internal override func _formIndex(before position: _AnyIndexBox) {\n if let p = position as? _IndexBox<S.Index> {\n return _base.formIndex(before: &p._base)\n }\n fatalError("Index type mismatch!")\n }\n\n @usableFromInline\n internal var _base: S\n}\n\n@usableFromInline\n@frozen\ninternal struct _ClosureBasedSequence<Iterator: IteratorProtocol> {\n @usableFromInline\n internal var _makeUnderlyingIterator: () -> Iterator\n\n @inlinable\n internal init(_ makeUnderlyingIterator: @escaping () -> Iterator) {\n self._makeUnderlyingIterator = makeUnderlyingIterator\n }\n}\n\n@available(*, unavailable)\nextension _ClosureBasedSequence: Sendable {}\n\nextension _ClosureBasedSequence: Sequence {\n public typealias Element = Iterator.Element\n\n @inlinable\n internal func makeIterator() -> Iterator {\n return _makeUnderlyingIterator()\n }\n}\n\n/// A type-erased sequence.\n///\n/// An instance of `AnySequence` forwards its operations to an underlying base\n/// sequence having the same `Element` type, hiding the specifics of the\n/// underlying sequence.\n@frozen\npublic struct AnySequence<Element> {\n @usableFromInline\n internal let _box: _AnySequenceBox<Element>\n \n /// Creates a sequence whose `makeIterator()` method forwards to\n /// `makeUnderlyingIterator`.\n @inlinable\n public init<I: IteratorProtocol>(\n _ makeUnderlyingIterator: @escaping () -> I\n ) where I.Element == Element {\n self.init(_ClosureBasedSequence(makeUnderlyingIterator))\n }\n\n @inlinable\n internal init(_box: _AnySequenceBox<Element>) {\n self._box = _box\n }\n}\n\n@available(*, unavailable)\nextension AnySequence: Sendable {}\n\nextension AnySequence: Sequence {\n public typealias Iterator = AnyIterator<Element>\n\n /// Creates a new sequence that wraps and forwards operations to `base`.\n @inlinable\n public init<S: Sequence>(_ base: S)\n where\n S.Element == Element {\n self._box = _SequenceBox(_base: base)\n }\n}\n\nextension AnySequence {\n\n /// Returns an iterator over the elements of this sequence.\n @inline(__always)\n @inlinable\n public __consuming func makeIterator() -> Iterator {\n return _box._makeIterator()\n }\n @inlinable\n public __consuming func dropLast(_ n: Int = 1) -> [Element] {\n return _box._dropLast(n)\n }\n @inlinable\n public __consuming func prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _box._prefix(while: predicate)\n }\n @inlinable\n public __consuming func suffix(_ maxLength: Int) -> [Element] {\n return _box._suffix(maxLength)\n }\n\n @inlinable\n public var underestimatedCount: Int {\n return _box._underestimatedCount\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n public func map<T, E>(\n _ transform: (Element) throws(E) -> T\n ) throws(E) -> [T] {\n do {\n return try _box._map(transform)\n } catch {\n throw error as! E\n }\n }\n\n // ABI-only entrypoint for the rethrows version of map, which has been\n // superseded by the typed-throws version. Expressed as "throws", which is\n // ABI-compatible with "rethrows".\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @usableFromInline\n @_silgen_name("$ss11AnySequenceV3mapySayqd__Gqd__xKXEKlF")\n func __rethrows_map<T>(\n _ transform: (Element) throws -> T\n ) throws -> [T] {\n try map(transform)\n }\n\n @inlinable\n public __consuming func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _box._filter(isIncluded)\n }\n\n @inlinable\n public __consuming func forEach(\n _ body: (Element) throws -> Void\n ) rethrows {\n return try _box._forEach(body)\n }\n\n @inlinable\n public __consuming func drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> AnySequence<Element> {\n return try AnySequence(_box: _box._drop(while: predicate))\n }\n\n @inlinable\n public __consuming func dropFirst(_ n: Int = 1) -> AnySequence<Element> {\n return AnySequence(_box: _box._dropFirst(n))\n }\n\n @inlinable\n public __consuming func prefix(_ maxLength: Int = 1) -> AnySequence<Element> {\n return AnySequence(_box: _box._prefix(maxLength))\n }\n\n @inlinable\n public func _customContainsEquatableElement(\n _ element: Element\n ) -> Bool? {\n return _box.__customContainsEquatableElement(element)\n }\n\n @inlinable\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n return self._box.__copyToContiguousArray()\n }\n\n @inlinable\n public __consuming func _copyContents(\n initializing buf: UnsafeMutableBufferPointer<Element>\n ) -> (AnyIterator<Element>,UnsafeMutableBufferPointer<Element>.Index) {\n let (it,idx) = unsafe _box.__copyContents(initializing: buf)\n return (AnyIterator(it),idx)\n }\n}\n\n@_unavailableInEmbedded\nextension AnyCollection {\n /// Returns an iterator over the elements of this collection.\n @inline(__always)\n @inlinable\n public __consuming func makeIterator() -> Iterator {\n return _box._makeIterator()\n }\n @inlinable\n public __consuming func dropLast(_ n: Int = 1) -> AnyCollection<Element> {\n return AnyCollection(_box: _box._dropLast(n))\n }\n @inlinable\n public __consuming func prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> AnyCollection<Element> {\n return try AnyCollection(_box: _box._prefix(while: predicate))\n }\n @inlinable\n public __consuming func suffix(_ maxLength: Int) -> AnyCollection<Element> {\n return AnyCollection(_box: _box._suffix(maxLength))\n }\n\n @inlinable\n public var underestimatedCount: Int {\n return _box._underestimatedCount\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n public func map<T, E>(\n _ transform: (Element) throws(E) -> T\n ) throws(E) -> [T] {\n do {\n return try _box._map(transform)\n } catch {\n throw error as! E\n }\n }\n\n // ABI-only entrypoint for the rethrows version of map, which has been\n // superseded by the typed-throws version. Expressed as "throws", which is\n // ABI-compatible with "rethrows".\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @usableFromInline\n @_silgen_name("$ss13AnyCollectionV3mapySayqd__Gqd__xKXEKlF")\n func __rethrows_map<T>(\n _ transform: (Element) throws -> T\n ) throws -> [T] {\n try map(transform)\n }\n\n @inlinable\n public __consuming func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _box._filter(isIncluded)\n }\n\n @inlinable\n public __consuming func forEach(\n _ body: (Element) throws -> Void\n ) rethrows {\n return try _box._forEach(body)\n }\n\n @inlinable\n public __consuming func drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> AnyCollection<Element> {\n return try AnyCollection(_box: _box._drop(while: predicate))\n }\n\n @inlinable\n public __consuming func dropFirst(_ n: Int = 1) -> AnyCollection<Element> {\n return AnyCollection(_box: _box._dropFirst(n))\n }\n\n @inlinable\n public __consuming func prefix(\n _ maxLength: Int = 1\n ) -> AnyCollection<Element> {\n return AnyCollection(_box: _box._prefix(maxLength))\n }\n\n @inlinable\n public func _customContainsEquatableElement(\n _ element: Element\n ) -> Bool? {\n return _box.__customContainsEquatableElement(element)\n }\n\n @inlinable\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n return self._box.__copyToContiguousArray()\n }\n\n @inlinable\n public __consuming func _copyContents(\n initializing buf: UnsafeMutableBufferPointer<Element>\n ) -> (AnyIterator<Element>,UnsafeMutableBufferPointer<Element>.Index) {\n let (it,idx) = unsafe _box.__copyContents(initializing: buf)\n return (AnyIterator(it),idx)\n }\n}\n\n@_unavailableInEmbedded\nextension AnyBidirectionalCollection {\n /// Returns an iterator over the elements of this collection.\n @inline(__always)\n @inlinable\n public __consuming func makeIterator() -> Iterator {\n return _box._makeIterator()\n }\n @inlinable\n public __consuming func dropLast(\n _ n: Int = 1\n ) -> AnyBidirectionalCollection<Element> {\n return AnyBidirectionalCollection(_box: _box._dropLast(n))\n }\n @inlinable\n public __consuming func prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> AnyBidirectionalCollection<Element> {\n return try AnyBidirectionalCollection(_box: _box._prefix(while: predicate))\n }\n @inlinable\n public __consuming func suffix(\n _ maxLength: Int\n ) -> AnyBidirectionalCollection<Element> {\n return AnyBidirectionalCollection(_box: _box._suffix(maxLength))\n }\n\n @inlinable\n public var underestimatedCount: Int {\n return _box._underestimatedCount\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n public func map<T, E>(\n _ transform: (Element) throws(E) -> T\n ) throws(E) -> [T] {\n do {\n return try _box._map(transform)\n } catch {\n throw error as! E\n }\n }\n\n // ABI-only entrypoint for the rethrows version of map, which has been\n // superseded by the typed-throws version. Expressed as "throws", which is\n // ABI-compatible with "rethrows".\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @usableFromInline\n @_silgen_name("$ss26AnyBidirectionalCollectionV3mapySayqd__Gqd__xKXEKlF")\n func __rethrows_map<T>(\n _ transform: (Element) throws -> T\n ) throws -> [T] {\n try map(transform)\n }\n\n @inlinable\n public __consuming func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _box._filter(isIncluded)\n }\n\n @inlinable\n public __consuming func forEach(\n _ body: (Element) throws -> Void\n ) rethrows {\n return try _box._forEach(body)\n }\n\n @inlinable\n public __consuming func drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> AnyBidirectionalCollection<Element> {\n return try AnyBidirectionalCollection(_box: _box._drop(while: predicate))\n }\n\n @inlinable\n public __consuming func dropFirst(\n _ n: Int = 1\n ) -> AnyBidirectionalCollection<Element> {\n return AnyBidirectionalCollection(_box: _box._dropFirst(n))\n }\n\n @inlinable\n public __consuming func prefix(\n _ maxLength: Int = 1\n ) -> AnyBidirectionalCollection<Element> {\n return AnyBidirectionalCollection(_box: _box._prefix(maxLength))\n }\n\n @inlinable\n public func _customContainsEquatableElement(\n _ element: Element\n ) -> Bool? {\n return _box.__customContainsEquatableElement(element)\n }\n\n @inlinable\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n return self._box.__copyToContiguousArray()\n }\n\n @inlinable\n public __consuming func _copyContents(\n initializing buf: UnsafeMutableBufferPointer<Element>\n ) -> (AnyIterator<Element>,UnsafeMutableBufferPointer<Element>.Index) {\n let (it,idx) = unsafe _box.__copyContents(initializing: buf)\n return (AnyIterator(it),idx)\n }\n}\n\n@_unavailableInEmbedded\nextension AnyRandomAccessCollection {\n /// Returns an iterator over the elements of this collection.\n @inline(__always)\n @inlinable\n public __consuming func makeIterator() -> Iterator {\n return _box._makeIterator()\n }\n @inlinable\n public __consuming func dropLast(\n _ n: Int = 1\n ) -> AnyRandomAccessCollection<Element> {\n return AnyRandomAccessCollection(_box: _box._dropLast(n))\n }\n @inlinable\n public __consuming func prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> AnyRandomAccessCollection<Element> {\n return try AnyRandomAccessCollection(_box: _box._prefix(while: predicate))\n }\n @inlinable\n public __consuming func suffix(\n _ maxLength: Int\n ) -> AnyRandomAccessCollection<Element> {\n return AnyRandomAccessCollection(_box: _box._suffix(maxLength))\n }\n\n @inlinable\n public var underestimatedCount: Int {\n return _box._underestimatedCount\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n public func map<T, E>(\n _ transform: (Element) throws(E) -> T\n ) throws(E) -> [T] {\n do {\n return try _box._map(transform)\n } catch {\n throw error as! E\n }\n }\n\n // ABI-only entrypoint for the rethrows version of map, which has been\n // superseded by the typed-throws version. Expressed as "throws", which is\n // ABI-compatible with "rethrows".\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @usableFromInline\n @_silgen_name("$ss25AnyRandomAccessCollectionV3mapySayqd__Gqd__xKXEKlF")\n func __rethrows_map<T>(\n _ transform: (Element) throws -> T\n ) throws -> [T] {\n try map(transform)\n }\n\n @inlinable\n public __consuming func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _box._filter(isIncluded)\n }\n\n @inlinable\n public __consuming func forEach(\n _ body: (Element) throws -> Void\n ) rethrows {\n return try _box._forEach(body)\n }\n\n @inlinable\n public __consuming func drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> AnyRandomAccessCollection<Element> {\n return try AnyRandomAccessCollection(_box: _box._drop(while: predicate))\n }\n\n @inlinable\n public __consuming func dropFirst(\n _ n: Int = 1\n ) -> AnyRandomAccessCollection<Element> {\n return AnyRandomAccessCollection(_box: _box._dropFirst(n))\n }\n\n @inlinable\n public __consuming func prefix(\n _ maxLength: Int = 1\n ) -> AnyRandomAccessCollection<Element> {\n return AnyRandomAccessCollection(_box: _box._prefix(maxLength))\n }\n\n @inlinable\n public func _customContainsEquatableElement(\n _ element: Element\n ) -> Bool? {\n return _box.__customContainsEquatableElement(element)\n }\n\n @inlinable\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n return self._box.__copyToContiguousArray()\n }\n\n @inlinable\n public __consuming func _copyContents(\n initializing buf: UnsafeMutableBufferPointer<Element>\n ) -> (AnyIterator<Element>,UnsafeMutableBufferPointer<Element>.Index) {\n let (it,idx) = unsafe _box.__copyContents(initializing: buf)\n return (AnyIterator(it),idx)\n }\n}\n\n//===--- Index ------------------------------------------------------------===//\n//===----------------------------------------------------------------------===//\n\n@usableFromInline\ninternal protocol _AnyIndexBox: AnyObject {\n var _typeID: ObjectIdentifier { get }\n\n func _unbox<T: Comparable>() -> T?\n\n func _isEqual(to rhs: _AnyIndexBox) -> Bool\n\n func _isLess(than rhs: _AnyIndexBox) -> Bool\n}\n\n@_fixed_layout\n@usableFromInline\ninternal final class _IndexBox<BaseIndex: Comparable>: _AnyIndexBox {\n @usableFromInline\n internal var _base: BaseIndex\n\n @inlinable\n internal init(_base: BaseIndex) {\n self._base = _base\n }\n\n @inlinable\n internal func _unsafeUnbox(_ other: _AnyIndexBox) -> BaseIndex {\n return unsafe unsafeDowncast(other, to: _IndexBox.self)._base\n }\n\n @inlinable\n internal var _typeID: ObjectIdentifier {\n return ObjectIdentifier(type(of: self))\n }\n\n @inlinable\n internal func _unbox<T: Comparable>() -> T? {\n return (self as _AnyIndexBox as? _IndexBox<T>)?._base\n }\n\n @inlinable\n internal func _isEqual(to rhs: _AnyIndexBox) -> Bool {\n return _base == _unsafeUnbox(rhs)\n }\n\n @inlinable\n internal func _isLess(than rhs: _AnyIndexBox) -> Bool {\n return _base < _unsafeUnbox(rhs)\n }\n}\n\n@available(*, unavailable)\nextension _IndexBox: Sendable {}\n\n/// A wrapper over an underlying index that hides the specific underlying type.\n@frozen\n@_unavailableInEmbedded\npublic struct AnyIndex {\n @usableFromInline\n internal var _box: _AnyIndexBox\n\n /// Creates a new index wrapping `base`.\n @inlinable\n public init<BaseIndex: Comparable>(_ base: BaseIndex) {\n self._box = _IndexBox(_base: base)\n }\n\n @inlinable\n internal init(_box: _AnyIndexBox) {\n self._box = _box\n }\n\n @inlinable\n internal var _typeID: ObjectIdentifier {\n return _box._typeID\n }\n}\n\n@available(*, unavailable)\nextension AnyIndex: Sendable {}\n\n@_unavailableInEmbedded\nextension AnyIndex: Comparable {\n /// Returns a Boolean value indicating whether two indices wrap equal\n /// underlying indices.\n ///\n /// The types of the two underlying indices must be identical.\n ///\n /// - Parameters:\n /// - lhs: An index to compare.\n /// - rhs: Another index to compare.\n @inlinable\n public static func == (lhs: AnyIndex, rhs: AnyIndex) -> Bool {\n _precondition(lhs._typeID == rhs._typeID, "Base index types differ")\n return lhs._box._isEqual(to: rhs._box)\n }\n\n /// Returns a Boolean value indicating whether the first argument represents a\n /// position before the second argument.\n ///\n /// The types of the two underlying indices must be identical.\n ///\n /// - Parameters:\n /// - lhs: An index to compare.\n /// - rhs: Another index to compare.\n @inlinable\n public static func < (lhs: AnyIndex, rhs: AnyIndex) -> Bool {\n _precondition(lhs._typeID == rhs._typeID, "Base index types differ")\n return lhs._box._isLess(than: rhs._box)\n }\n}\n\n//===--- Collections ------------------------------------------------------===//\n//===----------------------------------------------------------------------===//\n\npublic // @testable\nprotocol _AnyCollectionProtocol: Collection {\n /// Identifies the underlying collection stored by `self`. Instances\n /// copied or upgraded/downgraded from one another have the same `_boxID`.\n var _boxID: ObjectIdentifier { get }\n}\n\n/// A type-erased wrapper over any collection with indices that\n/// support forward traversal.\n///\n/// An `AnyCollection` instance forwards its operations to a base collection having the\n/// same `Element` type, hiding the specifics of the underlying\n/// collection.\n@frozen\n@_unavailableInEmbedded\npublic struct AnyCollection<Element> {\n @usableFromInline\n internal let _box: _AnyCollectionBox<Element>\n\n @inlinable\n internal init(_box: _AnyCollectionBox<Element>) {\n self._box = _box\n }\n}\n\n@available(*, unavailable)\nextension AnyCollection: Sendable {}\n\n@_unavailableInEmbedded\nextension AnyCollection: Collection {\n public typealias Indices = DefaultIndices<AnyCollection>\n public typealias Iterator = AnyIterator<Element>\n public typealias Index = AnyIndex\n public typealias SubSequence = AnyCollection<Element> \n\n /// Creates a type-erased collection that wraps the given collection.\n ///\n /// - Parameter base: The collection to wrap.\n ///\n /// - Complexity: O(1).\n @inline(__always)\n @inlinable\n public init<C: Collection>(_ base: C) where C.Element == Element {\n // Traversal: Forward\n // SubTraversal: Forward\n self._box = _CollectionBox<C>(\n _base: base)\n }\n\n /// Creates an `AnyCollection` having the same underlying collection as `other`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public init(_ other: AnyCollection<Element>) {\n self._box = other._box\n }\n\n /// Creates a type-erased collection that wraps the given collection.\n ///\n /// - Parameter base: The collection to wrap.\n ///\n /// - Complexity: O(1).\n @inline(__always)\n @inlinable\n public init<C: BidirectionalCollection>(_ base: C) where C.Element == Element {\n // Traversal: Forward\n // SubTraversal: Bidirectional\n self._box = _BidirectionalCollectionBox<C>(\n _base: base)\n }\n\n /// Creates an `AnyCollection` having the same underlying collection as `other`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public init(_ other: AnyBidirectionalCollection<Element>) {\n self._box = other._box\n }\n\n /// Creates a type-erased collection that wraps the given collection.\n ///\n /// - Parameter base: The collection to wrap.\n ///\n /// - Complexity: O(1).\n @inline(__always)\n @inlinable\n public init<C: RandomAccessCollection>(_ base: C) where C.Element == Element {\n // Traversal: Forward\n // SubTraversal: RandomAccess\n self._box = _RandomAccessCollectionBox<C>(\n _base: base)\n }\n\n /// Creates an `AnyCollection` having the same underlying collection as `other`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public init(_ other: AnyRandomAccessCollection<Element>) {\n self._box = other._box\n }\n\n /// The position of the first element in a non-empty collection.\n ///\n /// In an empty collection, `startIndex == endIndex`.\n @inlinable\n public var startIndex: Index {\n return AnyIndex(_box: _box._startIndex)\n }\n\n /// The collection's "past the end" position---that is, the position one\n /// greater than the last valid subscript argument.\n ///\n /// `endIndex` is always reachable from `startIndex` by zero or more\n /// applications of `index(after:)`.\n @inlinable\n public var endIndex: Index {\n return AnyIndex(_box: _box._endIndex)\n }\n\n /// Accesses the element indicated by `position`.\n ///\n /// - Precondition: `position` indicates a valid position in `self` and\n /// `position != endIndex`.\n @inlinable\n public subscript(position: Index) -> Element {\n return _box[position._box]\n }\n\n @inlinable\n public subscript(bounds: Range<Index>) -> SubSequence {\n return AnyCollection(_box:\n _box[start: bounds.lowerBound._box, end: bounds.upperBound._box])\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {\n // Do nothing. Doing a range check would involve unboxing indices,\n // performing dynamic dispatch etc. This seems to be too costly for a fast\n // range check for QoI purposes.\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {\n // Do nothing. Doing a range check would involve unboxing indices,\n // performing dynamic dispatch etc. This seems to be too costly for a fast\n // range check for QoI purposes.\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n return AnyIndex(_box: _box._index(after: i._box))\n }\n\n @inlinable\n public func formIndex(after i: inout Index) {\n if _isUnique(&i._box) {\n _box._formIndex(after: i._box)\n }\n else {\n i = index(after: i)\n }\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy n: Int) -> Index {\n return AnyIndex(_box: _box._index(i._box, offsetBy: n))\n }\n\n @inlinable\n public func index(\n _ i: Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Index? {\n return _box._index(i._box, offsetBy: n, limitedBy: limit._box)\n .map { AnyIndex(_box:$0) }\n }\n\n @inlinable\n public func formIndex(_ i: inout Index, offsetBy n: Int) {\n if _isUnique(&i._box) {\n return _box._formIndex(&i._box, offsetBy: n)\n } else {\n i = index(i, offsetBy: n)\n }\n }\n\n @inlinable\n public func formIndex(\n _ i: inout Index,\n offsetBy n: Int,\n limitedBy limit: Index\n ) -> Bool {\n if _isUnique(&i._box) {\n return _box._formIndex(&i._box, offsetBy: n, limitedBy: limit._box)\n }\n if let advanced = index(i, offsetBy: n, limitedBy: limit) {\n i = advanced\n return true\n }\n i = limit\n return false\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n return _box._distance(from: start._box, to: end._box)\n }\n\n /// The number of elements.\n ///\n /// To check whether a collection is empty, use its `isEmpty` property\n /// instead of comparing `count` to zero. Calculating `count` can be an O(*n*)\n /// operation.\n ///\n /// - Complexity: O(*n*)\n @inlinable\n public var count: Int {\n return _box._count\n }\n}\n\n@_unavailableInEmbedded\nextension AnyCollection: _AnyCollectionProtocol {\n /// Uniquely identifies the stored underlying collection.\n @inlinable\n public // Due to language limitations only\n var _boxID: ObjectIdentifier {\n return ObjectIdentifier(_box)\n }\n}\n\n/// A type-erased wrapper over any collection with indices that\n/// support bidirectional traversal.\n///\n/// An `AnyBidirectionalCollection` instance forwards its operations to a base collection having the\n/// same `Element` type, hiding the specifics of the underlying\n/// collection.\n@frozen\n@_unavailableInEmbedded\npublic struct AnyBidirectionalCollection<Element> {\n @usableFromInline\n internal let _box: _AnyBidirectionalCollectionBox<Element>\n\n @inlinable\n internal init(_box: _AnyBidirectionalCollectionBox<Element>) {\n self._box = _box\n }\n}\n\n@available(*, unavailable)\nextension AnyBidirectionalCollection: Sendable {}\n\n@_unavailableInEmbedded\nextension AnyBidirectionalCollection: BidirectionalCollection {\n public typealias Indices = DefaultIndices<AnyBidirectionalCollection>\n public typealias Iterator = AnyIterator<Element>\n public typealias Index = AnyIndex\n public typealias SubSequence = AnyBidirectionalCollection<Element> \n\n /// Creates a type-erased collection that wraps the given collection.\n ///\n /// - Parameter base: The collection to wrap.\n ///\n /// - Complexity: O(1).\n @inline(__always)\n @inlinable\n public init<C: BidirectionalCollection>(_ base: C) where C.Element == Element {\n // Traversal: Bidirectional\n // SubTraversal: Bidirectional\n self._box = _BidirectionalCollectionBox<C>(\n _base: base)\n }\n\n /// Creates an `AnyBidirectionalCollection` having the same underlying collection as `other`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public init(_ other: AnyBidirectionalCollection<Element>) {\n self._box = other._box\n }\n\n /// Creates a type-erased collection that wraps the given collection.\n ///\n /// - Parameter base: The collection to wrap.\n ///\n /// - Complexity: O(1).\n @inline(__always)\n @inlinable\n public init<C: RandomAccessCollection>(_ base: C) where C.Element == Element {\n // Traversal: Bidirectional\n // SubTraversal: RandomAccess\n self._box = _RandomAccessCollectionBox<C>(\n _base: base)\n }\n\n /// Creates an `AnyBidirectionalCollection` having the same underlying collection as `other`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public init(_ other: AnyRandomAccessCollection<Element>) {\n self._box = other._box\n }\n\n /// Creates an `AnyBidirectionalCollection` having the same underlying collection as `other`.\n ///\n /// If the underlying collection stored by `other` does not satisfy\n /// `BidirectionalCollection`, the result is `nil`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public init?(_ other: AnyCollection<Element>) {\n guard let box =\n other._box as? _AnyBidirectionalCollectionBox<Element> else {\n return nil\n }\n self._box = box\n }\n\n /// The position of the first element in a non-empty collection.\n ///\n /// In an empty collection, `startIndex == endIndex`.\n @inlinable\n public var startIndex: Index {\n return AnyIndex(_box: _box._startIndex)\n }\n\n /// The collection's "past the end" position---that is, the position one\n /// greater than the last valid subscript argument.\n ///\n /// `endIndex` is always reachable from `startIndex` by zero or more\n /// applications of `index(after:)`.\n @inlinable\n public var endIndex: Index {\n return AnyIndex(_box: _box._endIndex)\n }\n\n /// Accesses the element indicated by `position`.\n ///\n /// - Precondition: `position` indicates a valid position in `self` and\n /// `position != endIndex`.\n @inlinable\n public subscript(position: Index) -> Element {\n return _box[position._box]\n }\n\n @inlinable\n public subscript(bounds: Range<Index>) -> SubSequence {\n return AnyBidirectionalCollection(_box:\n _box[start: bounds.lowerBound._box, end: bounds.upperBound._box])\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {\n // Do nothing. Doing a range check would involve unboxing indices,\n // performing dynamic dispatch etc. This seems to be too costly for a fast\n // range check for QoI purposes.\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {\n // Do nothing. Doing a range check would involve unboxing indices,\n // performing dynamic dispatch etc. This seems to be too costly for a fast\n // range check for QoI purposes.\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n return AnyIndex(_box: _box._index(after: i._box))\n }\n\n @inlinable\n public func formIndex(after i: inout Index) {\n if _isUnique(&i._box) {\n _box._formIndex(after: i._box)\n }\n else {\n i = index(after: i)\n }\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy n: Int) -> Index {\n return AnyIndex(_box: _box._index(i._box, offsetBy: n))\n }\n\n @inlinable\n public func index(\n _ i: Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Index? {\n return _box._index(i._box, offsetBy: n, limitedBy: limit._box)\n .map { AnyIndex(_box:$0) }\n }\n\n @inlinable\n public func formIndex(_ i: inout Index, offsetBy n: Int) {\n if _isUnique(&i._box) {\n return _box._formIndex(&i._box, offsetBy: n)\n } else {\n i = index(i, offsetBy: n)\n }\n }\n\n @inlinable\n public func formIndex(\n _ i: inout Index,\n offsetBy n: Int,\n limitedBy limit: Index\n ) -> Bool {\n if _isUnique(&i._box) {\n return _box._formIndex(&i._box, offsetBy: n, limitedBy: limit._box)\n }\n if let advanced = index(i, offsetBy: n, limitedBy: limit) {\n i = advanced\n return true\n }\n i = limit\n return false\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n return _box._distance(from: start._box, to: end._box)\n }\n\n /// The number of elements.\n ///\n /// To check whether a collection is empty, use its `isEmpty` property\n /// instead of comparing `count` to zero. Calculating `count` can be an O(*n*)\n /// operation.\n ///\n /// - Complexity: O(*n*)\n @inlinable\n public var count: Int {\n return _box._count\n }\n\n @inlinable\n public func index(before i: Index) -> Index {\n return AnyIndex(_box: _box._index(before: i._box))\n }\n\n @inlinable\n public func formIndex(before i: inout Index) {\n if _isUnique(&i._box) {\n _box._formIndex(before: i._box)\n }\n else {\n i = index(before: i)\n }\n }\n}\n\n@_unavailableInEmbedded\nextension AnyBidirectionalCollection: _AnyCollectionProtocol {\n /// Uniquely identifies the stored underlying collection.\n @inlinable\n public // Due to language limitations only\n var _boxID: ObjectIdentifier {\n return ObjectIdentifier(_box)\n }\n}\n\n/// A type-erased wrapper over any collection with indices that\n/// support random access traversal.\n///\n/// An `AnyRandomAccessCollection` instance forwards its operations to a base collection having the\n/// same `Element` type, hiding the specifics of the underlying\n/// collection.\n@frozen\n@_unavailableInEmbedded\npublic struct AnyRandomAccessCollection<Element> {\n @usableFromInline\n internal let _box: _AnyRandomAccessCollectionBox<Element>\n\n @inlinable\n internal init(_box: _AnyRandomAccessCollectionBox<Element>) {\n self._box = _box\n }\n}\n\n@available(*, unavailable)\nextension AnyRandomAccessCollection: Sendable {}\n\n@_unavailableInEmbedded\nextension AnyRandomAccessCollection: RandomAccessCollection {\n public typealias Indices = DefaultIndices<AnyRandomAccessCollection>\n public typealias Iterator = AnyIterator<Element>\n public typealias Index = AnyIndex\n public typealias SubSequence = AnyRandomAccessCollection<Element> \n\n /// Creates a type-erased collection that wraps the given collection.\n ///\n /// - Parameter base: The collection to wrap.\n ///\n /// - Complexity: O(1).\n @inline(__always)\n @inlinable\n public init<C: RandomAccessCollection>(_ base: C) where C.Element == Element {\n // Traversal: RandomAccess\n // SubTraversal: RandomAccess\n self._box = _RandomAccessCollectionBox<C>(\n _base: base)\n }\n\n /// Creates an `AnyRandomAccessCollection` having the same underlying collection as `other`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public init(_ other: AnyRandomAccessCollection<Element>) {\n self._box = other._box\n }\n\n /// Creates an `AnyRandomAccessCollection` having the same underlying collection as `other`.\n ///\n /// If the underlying collection stored by `other` does not satisfy\n /// `RandomAccessCollection`, the result is `nil`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public init?(_ other: AnyCollection<Element>) {\n guard let box =\n other._box as? _AnyRandomAccessCollectionBox<Element> else {\n return nil\n }\n self._box = box\n }\n\n /// Creates an `AnyRandomAccessCollection` having the same underlying collection as `other`.\n ///\n /// If the underlying collection stored by `other` does not satisfy\n /// `RandomAccessCollection`, the result is `nil`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public init?(_ other: AnyBidirectionalCollection<Element>) {\n guard let box =\n other._box as? _AnyRandomAccessCollectionBox<Element> else {\n return nil\n }\n self._box = box\n }\n\n /// The position of the first element in a non-empty collection.\n ///\n /// In an empty collection, `startIndex == endIndex`.\n @inlinable\n public var startIndex: Index {\n return AnyIndex(_box: _box._startIndex)\n }\n\n /// The collection's "past the end" position---that is, the position one\n /// greater than the last valid subscript argument.\n ///\n /// `endIndex` is always reachable from `startIndex` by zero or more\n /// applications of `index(after:)`.\n @inlinable\n public var endIndex: Index {\n return AnyIndex(_box: _box._endIndex)\n }\n\n /// Accesses the element indicated by `position`.\n ///\n /// - Precondition: `position` indicates a valid position in `self` and\n /// `position != endIndex`.\n @inlinable\n public subscript(position: Index) -> Element {\n return _box[position._box]\n }\n\n @inlinable\n public subscript(bounds: Range<Index>) -> SubSequence {\n return AnyRandomAccessCollection(_box:\n _box[start: bounds.lowerBound._box, end: bounds.upperBound._box])\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {\n // Do nothing. Doing a range check would involve unboxing indices,\n // performing dynamic dispatch etc. This seems to be too costly for a fast\n // range check for QoI purposes.\n }\n\n @inlinable\n public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {\n // Do nothing. Doing a range check would involve unboxing indices,\n // performing dynamic dispatch etc. This seems to be too costly for a fast\n // range check for QoI purposes.\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n return AnyIndex(_box: _box._index(after: i._box))\n }\n\n @inlinable\n public func formIndex(after i: inout Index) {\n if _isUnique(&i._box) {\n _box._formIndex(after: i._box)\n }\n else {\n i = index(after: i)\n }\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy n: Int) -> Index {\n return AnyIndex(_box: _box._index(i._box, offsetBy: n))\n }\n\n @inlinable\n public func index(\n _ i: Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Index? {\n return _box._index(i._box, offsetBy: n, limitedBy: limit._box)\n .map { AnyIndex(_box:$0) }\n }\n\n @inlinable\n public func formIndex(_ i: inout Index, offsetBy n: Int) {\n if _isUnique(&i._box) {\n return _box._formIndex(&i._box, offsetBy: n)\n } else {\n i = index(i, offsetBy: n)\n }\n }\n\n @inlinable\n public func formIndex(\n _ i: inout Index,\n offsetBy n: Int,\n limitedBy limit: Index\n ) -> Bool {\n if _isUnique(&i._box) {\n return _box._formIndex(&i._box, offsetBy: n, limitedBy: limit._box)\n }\n if let advanced = index(i, offsetBy: n, limitedBy: limit) {\n i = advanced\n return true\n }\n i = limit\n return false\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n return _box._distance(from: start._box, to: end._box)\n }\n\n /// The number of elements.\n ///\n /// - Complexity: O(1)\n @inlinable\n public var count: Int {\n return _box._count\n }\n\n @inlinable\n public func index(before i: Index) -> Index {\n return AnyIndex(_box: _box._index(before: i._box))\n }\n\n @inlinable\n public func formIndex(before i: inout Index) {\n if _isUnique(&i._box) {\n _box._formIndex(before: i._box)\n }\n else {\n i = index(before: i)\n }\n }\n}\n\n@_unavailableInEmbedded\nextension AnyRandomAccessCollection: _AnyCollectionProtocol {\n /// Uniquely identifies the stored underlying collection.\n @inlinable\n public // Due to language limitations only\n var _boxID: ObjectIdentifier {\n return ObjectIdentifier(_box)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ExistentialCollection.swift | cpp_apple_swift_stdlib_public_core_ExistentialCollection.swift | Swift | 68,355 | 0.75 | 0.05901 | 0.133844 | awesome-app | 360 | 2023-08-20T05:04:50.064654 | MIT | false | 32b0cc76964450fb228930fb07287b95 |
//===--- Filter.swift -----------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n\n/// A sequence whose elements consist of the elements of some base\n/// sequence that also satisfy a given predicate.\n///\n/// - Note: `s.lazy.filter { ... }`, for an arbitrary sequence `s`,\n/// is a `LazyFilterSequence`.\n@frozen // lazy-performance\npublic struct LazyFilterSequence<Base: Sequence> {\n @usableFromInline // lazy-performance\n internal var _base: Base\n\n /// The predicate used to determine which elements produced by\n /// `base` are also produced by `self`.\n @usableFromInline // lazy-performance\n internal let _predicate: (Base.Element) -> Bool\n\n /// Creates an instance consisting of the elements `x` of `base` for\n /// which `isIncluded(x) == true`.\n @inlinable // lazy-performance\n public // @testable\n init(_base base: Base, _ isIncluded: @escaping (Base.Element) -> Bool) {\n self._base = base\n self._predicate = isIncluded\n }\n}\n\n@available(*, unavailable)\nextension LazyFilterSequence: Sendable {}\n\nextension LazyFilterSequence {\n /// An iterator over the elements traversed by some base iterator that also\n /// satisfy a given predicate.\n ///\n /// - Note: This is the associated `Iterator` of `LazyFilterSequence`\n /// and `LazyFilterCollection`.\n @frozen // lazy-performance\n public struct Iterator {\n /// The underlying iterator whose elements are being filtered.\n public var base: Base.Iterator { return _base }\n\n @usableFromInline // lazy-performance\n internal var _base: Base.Iterator\n @usableFromInline // lazy-performance\n internal let _predicate: (Base.Element) -> Bool\n\n /// Creates an instance that produces the elements `x` of `base`\n /// for which `isIncluded(x) == true`.\n @inlinable // lazy-performance\n internal init(_base: Base.Iterator, _ isIncluded: @escaping (Base.Element) -> Bool) {\n self._base = _base\n self._predicate = isIncluded\n }\n }\n}\n\n@available(*, unavailable)\nextension LazyFilterSequence.Iterator: Sendable {}\n\nextension LazyFilterSequence.Iterator: IteratorProtocol, Sequence {\n public typealias Element = Base.Element\n \n /// Advances to the next element and returns it, or `nil` if no next element\n /// exists.\n ///\n /// Once `nil` has been returned, all subsequent calls return `nil`.\n ///\n /// - Precondition: `next()` has not been applied to a copy of `self`\n /// since the copy was made.\n @inlinable // lazy-performance\n public mutating func next() -> Element? {\n while let n = _base.next() {\n if _predicate(n) {\n return n\n }\n }\n return nil\n }\n}\n\nextension LazyFilterSequence: Sequence {\n public typealias Element = Base.Element\n /// Returns an iterator over the elements of this sequence.\n ///\n /// - Complexity: O(1).\n @inlinable // lazy-performance\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_base: _base.makeIterator(), _predicate)\n }\n\n @inlinable\n public func _customContainsEquatableElement(_ element: Element) -> Bool? {\n // optimization to check the element first matches the predicate\n guard _predicate(element) else { return false }\n return _base._customContainsEquatableElement(element)\n }\n}\n\nextension LazyFilterSequence: LazySequenceProtocol { }\n\n/// A lazy `Collection` wrapper that includes the elements of an\n/// underlying collection that satisfy a predicate.\n///\n/// - Note: The performance of accessing `startIndex`, `first`, any methods\n/// that depend on `startIndex`, or of advancing an index depends\n/// on how sparsely the filtering predicate is satisfied, and may not offer\n/// the usual performance given by `Collection`. Be aware, therefore, that\n/// general operations on `LazyFilterCollection` instances may not have the\n/// documented complexity.\npublic typealias LazyFilterCollection<T: Collection> = LazyFilterSequence<T>\n\nextension LazyFilterCollection: Collection {\n public typealias SubSequence = LazyFilterCollection<Base.SubSequence>\n\n // https://github.com/apple/swift/issues/46747\n // Any estimate of the number of elements that pass `_predicate` requires\n // iterating the collection and evaluating each element, which can be costly,\n // is unexpected, and usually doesn't pay for itself in saving time through\n // preventing intermediate reallocations.\n @inlinable // lazy-performance\n public var underestimatedCount: Int { return 0 }\n\n /// A type that represents a valid position in the collection.\n ///\n /// Valid indices consist of the position of every element and a\n /// "past the end" position that's not valid for use as a subscript.\n public typealias Index = Base.Index\n\n /// The position of the first element in a non-empty collection.\n ///\n /// In an empty collection, `startIndex == endIndex`.\n ///\n /// - Complexity: O(*n*), where *n* is the ratio between unfiltered and\n /// filtered collection counts.\n @inlinable // lazy-performance\n public var startIndex: Index {\n var index = _base.startIndex\n while index != _base.endIndex && !_predicate(_base[index]) {\n _base.formIndex(after: &index)\n }\n return index\n }\n\n /// The collection's "past the end" position---that is, the position one\n /// greater than the last valid subscript argument.\n ///\n /// `endIndex` is always reachable from `startIndex` by zero or more\n /// applications of `index(after:)`.\n @inlinable // lazy-performance\n public var endIndex: Index {\n return _base.endIndex\n }\n\n // TODO: swift-3-indexing-model - add docs\n @inlinable // lazy-performance\n public func index(after i: Index) -> Index {\n var i = i\n formIndex(after: &i)\n return i\n }\n\n @inlinable // lazy-performance\n public func formIndex(after i: inout Index) {\n // TODO: swift-3-indexing-model: _failEarlyRangeCheck i?\n var index = i\n _precondition(index != _base.endIndex, "Can't advance past endIndex")\n repeat {\n _base.formIndex(after: &index)\n } while index != _base.endIndex && !_predicate(_base[index])\n i = index\n }\n\n @inline(__always)\n @inlinable // lazy-performance\n internal func _advanceIndex(_ i: inout Index, step: Int) {\n repeat {\n _base.formIndex(&i, offsetBy: step)\n } while i != _base.endIndex && !_predicate(_base[i])\n }\n\n @inline(__always)\n @inlinable // lazy-performance\n internal func _ensureBidirectional(step: Int) {\n // FIXME: This seems to be the best way of checking whether _base is\n // forward only without adding an extra protocol requirement.\n // index(_:offsetBy:limitedBy:) is chosen because it is supposed to return\n // nil when the resulting index lands outside the collection boundaries,\n // and therefore likely does not trap in these cases.\n if step < 0 {\n _ = _base.index(\n _base.endIndex, offsetBy: step, limitedBy: _base.startIndex)\n }\n }\n\n @inlinable // lazy-performance\n public func distance(from start: Index, to end: Index) -> Int {\n // The following line makes sure that distance(from:to:) is invoked on the\n // _base at least once, to trigger a _precondition in forward only\n // collections.\n _ = _base.distance(from: start, to: end)\n var _start: Index\n let _end: Index\n let step: Int\n if start > end {\n _start = end\n _end = start\n step = -1\n }\n else {\n _start = start\n _end = end\n step = 1\n }\n var count = 0\n while _start != _end {\n count += step\n formIndex(after: &_start)\n }\n return count\n }\n\n @inlinable // lazy-performance\n public func index(_ i: Index, offsetBy n: Int) -> Index {\n var i = i\n let step = n.signum()\n // The following line makes sure that index(_:offsetBy:) is invoked on the\n // _base at least once, to trigger a _precondition in forward only\n // collections.\n _ensureBidirectional(step: step)\n for _ in 0 ..< abs(n) {\n _advanceIndex(&i, step: step)\n }\n return i\n }\n\n @inlinable // lazy-performance\n public func formIndex(_ i: inout Index, offsetBy n: Int) {\n i = index(i, offsetBy: n)\n }\n\n @inlinable // lazy-performance\n public func index(\n _ i: Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Index? {\n var i = i\n let step = n.signum()\n // The following line makes sure that index(_:offsetBy:limitedBy:) is\n // invoked on the _base at least once, to trigger a _precondition in\n // forward only collections.\n _ensureBidirectional(step: step)\n for _ in 0 ..< abs(n) {\n if i == limit {\n return nil\n }\n _advanceIndex(&i, step: step)\n }\n return i\n }\n\n @inlinable // lazy-performance\n public func formIndex(\n _ i: inout Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Bool {\n if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {\n i = advancedIndex\n return true\n }\n i = limit\n return false\n }\n\n /// Accesses the element at `position`.\n ///\n /// - Precondition: `position` is a valid position in `self` and\n /// `position != endIndex`.\n @inlinable // lazy-performance\n public subscript(position: Index) -> Element {\n return _base[position]\n }\n\n @inlinable // lazy-performance\n public subscript(bounds: Range<Index>) -> SubSequence {\n return SubSequence(_base: _base[bounds], _predicate)\n }\n \n @inlinable\n public func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? {\n guard _predicate(element) else { return .some(nil) }\n return _base._customLastIndexOfEquatableElement(element)\n }\n}\n\nextension LazyFilterCollection: LazyCollectionProtocol { }\n\nextension LazyFilterCollection: BidirectionalCollection\n where Base: BidirectionalCollection {\n\n @inlinable // lazy-performance\n public func index(before i: Index) -> Index {\n var i = i\n formIndex(before: &i)\n return i\n }\n\n @inlinable // lazy-performance\n public func formIndex(before i: inout Index) {\n // TODO: swift-3-indexing-model: _failEarlyRangeCheck i?\n var index = i\n _precondition(index != _base.startIndex, "Can't retreat before startIndex")\n repeat {\n _base.formIndex(before: &index)\n } while !_predicate(_base[index])\n i = index\n }\n}\n\nextension LazySequenceProtocol {\n /// Returns the elements of `self` that satisfy `isIncluded`.\n ///\n /// - Note: The elements of the result are computed on-demand, as\n /// the result is used. No buffering storage is allocated and each\n /// traversal step invokes `predicate` on one or more underlying\n /// elements.\n @inlinable // lazy-performance\n public __consuming func filter(\n _ isIncluded: @escaping (Elements.Element) -> Bool\n ) -> LazyFilterSequence<Self.Elements> {\n return LazyFilterSequence(_base: self.elements, isIncluded)\n }\n}\n\nextension LazyFilterSequence {\n @available(swift, introduced: 5)\n public __consuming func filter(\n _ isIncluded: @escaping (Element) -> Bool\n ) -> LazyFilterSequence<Base> {\n return LazyFilterSequence(_base: _base) {\n self._predicate($0) && isIncluded($0)\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Filter.swift | cpp_apple_swift_stdlib_public_core_Filter.swift | Swift | 11,395 | 0.95 | 0.059659 | 0.302548 | react-lib | 786 | 2025-03-18T06:01:47.287419 | GPL-3.0 | false | 680e7b763a2c07b354d55cd78fa088ec |
//===--- FlatMap.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension LazySequenceProtocol {\n /// Returns the concatenated results of mapping the given transformation over\n /// this sequence.\n ///\n /// Use this method to receive a single-level sequence when your\n /// transformation produces a sequence or collection for each element.\n /// Calling `flatMap(_:)` on a sequence `s` is equivalent to calling\n /// `s.map(transform).joined()`.\n ///\n /// - Complexity: O(1)\n @inlinable // lazy-performance\n public func flatMap<SegmentOfResult>(\n _ transform: @escaping (Elements.Element) -> SegmentOfResult\n ) -> LazySequence<\n FlattenSequence<LazyMapSequence<Elements, SegmentOfResult>>> {\n return self.map(transform).joined()\n }\n\n /// Returns the non-`nil` results of mapping the given transformation over\n /// this sequence.\n ///\n /// Use this method to receive a sequence of non-optional values when your\n /// transformation produces an optional value.\n ///\n /// - Parameter transform: A closure that accepts an element of this sequence\n /// as its argument and returns an optional value.\n ///\n /// - Complexity: O(1)\n @inlinable // lazy-performance\n public func compactMap<ElementOfResult>(\n _ transform: @escaping (Elements.Element) -> ElementOfResult?\n ) -> LazyMapSequence<\n LazyFilterSequence<\n LazyMapSequence<Elements, ElementOfResult?>>,\n ElementOfResult\n > {\n return self.map(transform).filter { $0 != nil }.map { $0! }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_FlatMap.swift | cpp_apple_swift_stdlib_public_core_FlatMap.swift | Swift | 1,948 | 0.8 | 0.058824 | 0.612245 | node-utils | 289 | 2023-10-31T06:58:53.835401 | BSD-3-Clause | false | 37f80d829a6262d501903b31fb1daea7 |
//===--- Flatten.swift ----------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A sequence consisting of all the elements contained in each segment\n/// contained in some `Base` sequence.\n///\n/// The elements of this view are a concatenation of the elements of\n/// each sequence in the base.\n///\n/// The `joined` method is always lazy, but does not implicitly\n/// confer laziness on algorithms applied to its result. In other\n/// words, for ordinary sequences `s`:\n///\n/// * `s.joined()` does not create new storage\n/// * `s.joined().map(f)` maps eagerly and returns a new array\n/// * `s.lazy.joined().map(f)` maps lazily and returns a `LazyMapSequence`\n@frozen // lazy-performance\npublic struct FlattenSequence<Base: Sequence> where Base.Element: Sequence {\n\n @usableFromInline // lazy-performance\n internal var _base: Base\n\n /// Creates a concatenation of the elements of the elements of `base`.\n ///\n /// - Complexity: O(1)\n @inlinable // lazy-performance\n internal init(_base: Base) {\n self._base = _base\n }\n}\n\nextension FlattenSequence: Sendable where Base: Sendable {}\n\nextension FlattenSequence {\n @frozen // lazy-performance\n public struct Iterator {\n @usableFromInline // lazy-performance\n internal var _base: Base.Iterator\n @usableFromInline // lazy-performance\n internal var _inner: Base.Element.Iterator?\n\n /// Construct around a `base` iterator.\n @inlinable // lazy-performance\n internal init(_base: Base.Iterator) {\n self._base = _base\n }\n }\n}\n\nextension FlattenSequence.Iterator: Sendable\n where Base.Iterator: Sendable, Base.Element.Iterator: Sendable {}\n\nextension FlattenSequence.Iterator: IteratorProtocol {\n public typealias Element = Base.Element.Element\n \n /// Advances to the next element and returns it, or `nil` if no next element\n /// exists.\n ///\n /// Once `nil` has been returned, all subsequent calls return `nil`.\n ///\n /// - Precondition: `next()` has not been applied to a copy of `self`\n /// since the copy was made.\n @inlinable // lazy-performance\n public mutating func next() -> Element? {\n repeat {\n if _fastPath(_inner != nil) {\n let ret = _inner!.next()\n if _fastPath(ret != nil) {\n return ret\n }\n }\n let s = _base.next()\n if _slowPath(s == nil) {\n return nil\n }\n _inner = s!.makeIterator()\n }\n while true\n fatalError()\n }\n}\n\nextension FlattenSequence.Iterator: Sequence { }\n\nextension FlattenSequence: Sequence {\n /// Returns an iterator over the elements of this sequence.\n ///\n /// - Complexity: O(1).\n @inlinable // lazy-performance\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_base: _base.makeIterator())\n }\n}\n\nextension Sequence where Element: Sequence {\n /// Returns the elements of this sequence of sequences, concatenated.\n ///\n /// In this example, an array of three ranges is flattened so that the\n /// elements of each range can be iterated in turn.\n ///\n /// let ranges = [0..<3, 8..<10, 15..<17]\n ///\n /// // A for-in loop over 'ranges' accesses each range:\n /// for range in ranges {\n /// print(range)\n /// }\n /// // Prints "0..<3"\n /// // Prints "8..<10"\n /// // Prints "15..<17"\n ///\n /// // Use 'joined()' to access each element of each range:\n /// for index in ranges.joined() {\n /// print(index, terminator: " ")\n /// }\n /// // Prints: "0 1 2 8 9 15 16"\n ///\n /// - Returns: A flattened view of the elements of this\n /// sequence of sequences.\n @inlinable // lazy-performance\n public __consuming func joined() -> FlattenSequence<Self> {\n return FlattenSequence(_base: self)\n }\n}\n\nextension LazySequenceProtocol where Element: Sequence {\n /// Returns a lazy sequence that concatenates the elements of this sequence of\n /// sequences.\n @inlinable // lazy-performance\n public __consuming func joined() -> LazySequence<FlattenSequence<Elements>> {\n return FlattenSequence(_base: elements).lazy\n }\n}\n\npublic typealias FlattenCollection<T: Collection> = FlattenSequence<T> where T.Element: Collection\n\nextension FlattenSequence where Base: Collection, Base.Element: Collection {\n /// A position in a FlattenCollection\n @frozen // lazy-performance\n public struct Index {\n /// The position in the outer collection of collections.\n @usableFromInline // lazy-performance\n internal let _outer: Base.Index\n\n /// The position in the inner collection at `base[_outer]`, or `nil` if\n /// `_outer == base.endIndex`.\n ///\n /// When `_inner != nil`, `_inner!` is a valid subscript of `base[_outer]`;\n /// when `_inner == nil`, `_outer == base.endIndex` and this index is\n /// `endIndex` of the `FlattenCollection`.\n @usableFromInline // lazy-performance\n internal let _inner: Base.Element.Index?\n\n @inlinable // lazy-performance\n internal init(_ _outer: Base.Index, _ inner: Base.Element.Index?) {\n self._outer = _outer\n self._inner = inner\n }\n }\n}\n\nextension FlattenSequence.Index: Sendable\n where Base.Index: Sendable, Base.Element.Index: Sendable {}\n\nextension FlattenSequence.Index: Equatable where Base: Collection, Base.Element: Collection {\n @inlinable // lazy-performance\n public static func == (\n lhs: FlattenCollection<Base>.Index,\n rhs: FlattenCollection<Base>.Index\n ) -> Bool {\n return lhs._outer == rhs._outer && lhs._inner == rhs._inner\n }\n}\n\nextension FlattenSequence.Index: Comparable where Base: Collection, Base.Element: Collection {\n @inlinable // lazy-performance\n public static func < (\n lhs: FlattenCollection<Base>.Index,\n rhs: FlattenCollection<Base>.Index\n ) -> Bool {\n // FIXME: swift-3-indexing-model: tests.\n if lhs._outer != rhs._outer {\n return lhs._outer < rhs._outer\n }\n\n if let lhsInner = lhs._inner, let rhsInner = rhs._inner {\n return lhsInner < rhsInner\n }\n\n // When combined, the two conditions above guarantee that both\n // `_outer` indices are `_base.endIndex` and both `_inner` indices\n // are `nil`, since `_inner` is `nil` iff `_outer == base.endIndex`.\n _precondition(lhs._inner == nil && rhs._inner == nil)\n\n return false\n }\n}\n\nextension FlattenSequence.Index: Hashable\n where Base: Collection, Base.Element: Collection, Base.Index: Hashable, Base.Element.Index: Hashable {\n /// Hashes the essential components of this value by feeding them into the\n /// given hasher.\n ///\n /// - Parameter hasher: The hasher to use when combining the components\n /// of this instance.\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine(_outer)\n hasher.combine(_inner)\n }\n}\n\nextension FlattenCollection: Collection {\n /// The position of the first element in a non-empty collection.\n ///\n /// In an empty collection, `startIndex == endIndex`.\n @inlinable // lazy-performance\n public var startIndex: Index {\n let end = _base.endIndex\n var outer = _base.startIndex\n while outer != end {\n let innerCollection = _base[outer]\n if !innerCollection.isEmpty {\n return Index(outer, innerCollection.startIndex)\n }\n _base.formIndex(after: &outer)\n }\n\n return endIndex\n }\n\n /// The collection's "past the end" position.\n ///\n /// `endIndex` is not a valid argument to `subscript`, and is always\n /// reachable from `startIndex` by zero or more applications of\n /// `index(after:)`.\n @inlinable // lazy-performance\n public var endIndex: Index {\n return Index(_base.endIndex, nil)\n }\n\n @inlinable // lazy-performance\n internal func _index(after i: Index) -> Index {\n let innerCollection = _base[i._outer]\n let nextInner = innerCollection.index(after: i._inner!)\n if _fastPath(nextInner != innerCollection.endIndex) {\n return Index(i._outer, nextInner)\n }\n\n var nextOuter = _base.index(after: i._outer)\n while nextOuter != _base.endIndex {\n let nextInnerCollection = _base[nextOuter]\n if !nextInnerCollection.isEmpty {\n return Index(nextOuter, nextInnerCollection.startIndex)\n }\n _base.formIndex(after: &nextOuter)\n }\n\n return endIndex\n }\n\n @inlinable // lazy-performance\n internal func _index(before i: Index) -> Index {\n var prevOuter = i._outer\n if prevOuter == _base.endIndex {\n prevOuter = _base.index(prevOuter, offsetBy: -1)\n }\n var prevInnerCollection = _base[prevOuter]\n var prevInner = i._inner ?? prevInnerCollection.endIndex\n\n while prevInner == prevInnerCollection.startIndex {\n prevOuter = _base.index(prevOuter, offsetBy: -1)\n prevInnerCollection = _base[prevOuter]\n prevInner = prevInnerCollection.endIndex\n }\n\n return Index(prevOuter, prevInnerCollection.index(prevInner, offsetBy: -1))\n }\n\n // TODO: swift-3-indexing-model - add docs\n @inlinable // lazy-performance\n public func index(after i: Index) -> Index {\n return _index(after: i)\n }\n\n @inlinable // lazy-performance\n public func formIndex(after i: inout Index) {\n i = index(after: i)\n }\n\n @inlinable // lazy-performance\n public func distance(from start: Index, to end: Index) -> Int {\n let distanceIsNegative = start > end\n\n // The following check ensures that distance(from:to:) is invoked on\n // the _base at least once, to trigger a _precondition in forward only\n // collections.\n if distanceIsNegative {\n _ = _base.distance(from: _base.endIndex, to: _base.startIndex)\n }\n\n // This path handles indices belonging to the same collection.\n if start._outer == end._outer {\n guard let i = start._inner, let j = end._inner else { return 0 }\n return _base[start._outer].distance(from: i, to: j)\n }\n\n // The following path combines the distances of three regions.\n let lowerBound: Index\n let upperBound: Index\n\n let step: Int\n var distance: Int\n\n // Note that lowerBound is a valid index because start != end.\n if distanceIsNegative {\n step = -1\n lowerBound = end\n upperBound = start\n let lowest = _base[lowerBound._outer]\n distance = lowest.distance(from: lowest.endIndex, to: lowerBound._inner!)\n } else {\n step = 01\n lowerBound = start\n upperBound = end\n let lowest = _base[lowerBound._outer]\n distance = lowest.distance(from: lowerBound._inner!, to: lowest.endIndex)\n }\n\n // We can use each collection's count in the middle region since the\n // fast path ensures that the other regions cover a nonzero distance,\n // which means that an extra Int.min distance should trap regardless.\n var outer = _base.index(after: lowerBound._outer)\n while outer < upperBound._outer {\n // 0 ... Int.max can always be negated.\n distance += _base[outer].count &* step\n _base.formIndex(after: &outer)\n }\n\n // This unwraps if start != endIndex and end != endIndex. We can use the\n // positive distance for the same reason that we can use the collection's\n // count in the middle region.\n if let inner = upperBound._inner {\n // 0 ... Int.max can always be negated.\n let highest = _base[upperBound._outer]\n distance += highest.distance(from: highest.startIndex, to: inner) &* step\n }\n\n return distance\n }\n\n @inline(__always)\n @inlinable // lazy-performance\n internal func _advanceIndex(_ i: inout Index, step: Int) {\n _internalInvariant(-1...1 ~= step, "step should be within the -1...1 range")\n i = step < 0 ? _index(before: i) : _index(after: i)\n }\n\n @inline(__always)\n @inlinable // lazy-performance\n internal func _ensureBidirectional(step: Int) {\n // FIXME: This seems to be the best way of checking whether _base is\n // forward only without adding an extra protocol requirement.\n // index(_:offsetBy:limitedBy:) is chosen because it is supposed to return\n // nil when the resulting index lands outside the collection boundaries,\n // and therefore likely does not trap in these cases.\n if step < 0 {\n _ = _base.index(\n _base.endIndex, offsetBy: step, limitedBy: _base.startIndex)\n }\n }\n\n @inlinable // lazy-performance\n public func index(_ i: Index, offsetBy n: Int) -> Index {\n var i = i\n let step = n.signum()\n _ensureBidirectional(step: step)\n for _ in 0 ..< abs(n) {\n _advanceIndex(&i, step: step)\n }\n return i\n }\n\n @inlinable // lazy-performance\n public func formIndex(_ i: inout Index, offsetBy n: Int) {\n i = index(i, offsetBy: n)\n }\n\n @inlinable // lazy-performance\n public func index(\n _ i: Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Index? {\n var i = i\n let step = n.signum()\n // The following line makes sure that index(_:offsetBy:limitedBy:) is\n // invoked on the _base at least once, to trigger a _precondition in\n // forward only collections.\n _ensureBidirectional(step: step)\n for _ in 0 ..< abs(n) {\n if i == limit {\n return nil\n }\n _advanceIndex(&i, step: step)\n }\n return i\n }\n\n @inlinable // lazy-performance\n public func formIndex(\n _ i: inout Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Bool {\n if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {\n i = advancedIndex\n return true\n }\n i = limit\n return false\n }\n\n /// Accesses the element at `position`.\n ///\n /// - Precondition: `position` is a valid position in `self` and\n /// `position != endIndex`.\n @inlinable // lazy-performance\n public subscript(position: Index) -> Base.Element.Element {\n return _base[position._outer][position._inner!]\n }\n\n @inlinable // lazy-performance\n public subscript(bounds: Range<Index>) -> Slice<FlattenCollection<Base>> {\n return Slice(base: self, bounds: bounds)\n }\n}\n\nextension FlattenCollection: BidirectionalCollection\n where Base: BidirectionalCollection, Base.Element: BidirectionalCollection {\n\n // FIXME(performance): swift-3-indexing-model: add custom advance/distance\n // methods that skip over inner collections when random-access\n\n // TODO: swift-3-indexing-model - add docs\n @inlinable // lazy-performance\n public func index(before i: Index) -> Index {\n return _index(before: i)\n }\n\n @inlinable // lazy-performance\n public func formIndex(before i: inout Index) {\n i = index(before: i)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Flatten.swift | cpp_apple_swift_stdlib_public_core_Flatten.swift | Swift | 14,691 | 0.95 | 0.071895 | 0.292804 | vue-tools | 860 | 2025-04-18T21:53:22.366575 | Apache-2.0 | false | fc19abeccbbd38808b4da2116f1543ed |
//===--- FloatingPoint.swift ----------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A floating-point numeric type.\n///\n/// Floating-point types are used to represent fractional numbers, like 5.5,\n/// 100.0, or 3.14159274. Each floating-point type has its own possible range\n/// and precision. The floating-point types in the standard library are\n/// `Float`, `Double`, and `Float80` where available.\n///\n/// Create new instances of floating-point types using integer or\n/// floating-point literals. For example:\n///\n/// let temperature = 33.2\n/// let recordHigh = 37.5\n///\n/// The `FloatingPoint` protocol declares common arithmetic operations, so you\n/// can write functions and algorithms that work on any floating-point type.\n/// The following example declares a function that calculates the length of\n/// the hypotenuse of a right triangle given its two perpendicular sides.\n/// Because the `hypotenuse(_:_:)` function uses a generic parameter\n/// constrained to the `FloatingPoint` protocol, you can call it using any\n/// floating-point type.\n///\n/// func hypotenuse<T: FloatingPoint>(_ a: T, _ b: T) -> T {\n/// return (a * a + b * b).squareRoot()\n/// }\n///\n/// let (dx, dy) = (3.0, 4.0)\n/// let distance = hypotenuse(dx, dy)\n/// // distance == 5.0\n///\n/// Floating-point values are represented as a *sign* and a *magnitude*, where\n/// the magnitude is calculated using the type's *radix* and the instance's\n/// *significand* and *exponent*. This magnitude calculation takes the\n/// following form for a floating-point value `x` of type `F`, where `**` is\n/// exponentiation:\n///\n/// x.significand * (F.radix ** x.exponent)\n///\n/// Here's an example of the number -8.5 represented as an instance of the\n/// `Double` type, which defines a radix of 2.\n///\n/// let y = -8.5\n/// // y.sign == .minus\n/// // y.significand == 1.0625\n/// // y.exponent == 3\n///\n/// let magnitude = 1.0625 * Double(2 ** 3)\n/// // magnitude == 8.5\n///\n/// Types that conform to the `FloatingPoint` protocol provide most basic\n/// (clause 5) operations of the [IEEE 754 specification][spec]. The base,\n/// precision, and exponent range are not fixed in any way by this protocol,\n/// but it enforces the basic requirements of any IEEE 754 floating-point\n/// type.\n///\n/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n///\n/// Additional Considerations\n/// =========================\n///\n/// In addition to representing specific numbers, floating-point types also\n/// have special values for working with overflow and nonnumeric results of\n/// calculation.\n///\n/// Infinity\n/// --------\n///\n/// Any value whose magnitude is so great that it would round to a value\n/// outside the range of representable numbers is rounded to *infinity*. For a\n/// type `F`, positive and negative infinity are represented as `F.infinity`\n/// and `-F.infinity`, respectively. Positive infinity compares greater than\n/// every finite value and negative infinity, while negative infinity compares\n/// less than every finite value and positive infinity. Infinite values with\n/// the same sign are equal to each other.\n///\n/// let values: [Double] = [10.0, 25.0, -10.0, .infinity, -.infinity]\n/// print(values.sorted())\n/// // Prints "[-inf, -10.0, 10.0, 25.0, inf]"\n///\n/// Operations with infinite values follow real arithmetic as much as possible:\n/// Adding or subtracting a finite value, or multiplying or dividing infinity\n/// by a nonzero finite value, results in infinity.\n///\n/// NaN ("not a number")\n/// --------------------\n///\n/// Floating-point types represent values that are neither finite numbers nor\n/// infinity as NaN, an abbreviation for "not a number." Comparing a NaN with\n/// any value, including another NaN, results in `false`.\n///\n/// let myNaN = Double.nan\n/// print(myNaN > 0)\n/// // Prints "false"\n/// print(myNaN < 0)\n/// // Prints "false"\n/// print(myNaN == .nan)\n/// // Prints "false"\n///\n/// Because testing whether one NaN is equal to another NaN results in `false`,\n/// use the `isNaN` property to test whether a value is NaN.\n///\n/// print(myNaN.isNaN)\n/// // Prints "true"\n///\n/// NaN propagates through many arithmetic operations. When you are operating\n/// on many values, this behavior is valuable because operations on NaN simply\n/// forward the value and don't cause runtime errors. The following example\n/// shows how NaN values operate in different contexts.\n///\n/// Imagine you have a set of temperature data for which you need to report\n/// some general statistics: the total number of observations, the number of\n/// valid observations, and the average temperature. First, a set of\n/// observations in Celsius is parsed from strings to `Double` values:\n///\n/// let temperatureData = ["21.5", "19.25", "27", "no data", "28.25", "no data", "23"]\n/// let tempsCelsius = temperatureData.map { Double($0) ?? .nan }\n/// print(tempsCelsius)\n/// // Prints "[21.5, 19.25, 27, nan, 28.25, nan, 23.0]"\n///\n///\n/// Note that some elements in the `temperatureData ` array are not valid\n/// numbers. When these invalid strings are parsed by the `Double` failable\n/// initializer, the example uses the nil-coalescing operator (`??`) to\n/// provide NaN as a fallback value.\n///\n/// Next, the observations in Celsius are converted to Fahrenheit:\n///\n/// let tempsFahrenheit = tempsCelsius.map { $0 * 1.8 + 32 }\n/// print(tempsFahrenheit)\n/// // Prints "[70.7, 66.65, 80.6, nan, 82.85, nan, 73.4]"\n///\n/// The NaN values in the `tempsCelsius` array are propagated through the\n/// conversion and remain NaN in `tempsFahrenheit`.\n///\n/// Because calculating the average of the observations involves combining\n/// every value of the `tempsFahrenheit` array, any NaN values cause the\n/// result to also be NaN, as seen in this example:\n///\n/// let badAverage = tempsFahrenheit.reduce(0.0, +) / Double(tempsFahrenheit.count)\n/// // badAverage.isNaN == true\n///\n/// Instead, when you need an operation to have a specific numeric result,\n/// filter out any NaN values using the `isNaN` property.\n///\n/// let validTemps = tempsFahrenheit.filter { !$0.isNaN }\n/// let average = validTemps.reduce(0.0, +) / Double(validTemps.count)\n///\n/// Finally, report the average temperature and observation counts:\n///\n/// print("Average: \(average)°F in \(validTemps.count) " +\n/// "out of \(tempsFahrenheit.count) observations.")\n/// // Prints "Average: 74.84°F in 5 out of 7 observations."\npublic protocol FloatingPoint: SignedNumeric, Strideable, Hashable\n where Magnitude == Self {\n\n /// A type that can represent any written exponent.\n associatedtype Exponent: SignedInteger\n\n /// Creates a new value from the given sign, exponent, and significand.\n ///\n /// The following example uses this initializer to create a new `Double`\n /// instance. `Double` is a binary floating-point type that has a radix of\n /// `2`.\n ///\n /// let x = Double(sign: .plus, exponent: -2, significand: 1.5)\n /// // x == 0.375\n ///\n /// This initializer is equivalent to the following calculation, where `**`\n /// is exponentiation, computed as if by a single, correctly rounded,\n /// floating-point operation:\n ///\n /// let sign: FloatingPointSign = .plus\n /// let exponent = -2\n /// let significand = 1.5\n /// let y = (sign == .minus ? -1 : 1) * significand * Double.radix ** exponent\n /// // y == 0.375\n ///\n /// As with any basic operation, if this value is outside the representable\n /// range of the type, overflow or underflow occurs, and zero, a subnormal\n /// value, or infinity may result. In addition, there are two other edge\n /// cases:\n ///\n /// - If the value you pass to `significand` is zero or infinite, the result\n /// is zero or infinite, regardless of the value of `exponent`.\n /// - If the value you pass to `significand` is NaN, the result is NaN.\n ///\n /// For any floating-point value `x` of type `F`, the result of the following\n /// is equal to `x`, with the distinction that the result is canonicalized\n /// if `x` is in a noncanonical encoding:\n ///\n /// let x0 = F(sign: x.sign, exponent: x.exponent, significand: x.significand)\n ///\n /// This initializer implements the `scaleB` operation defined by the [IEEE\n /// 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameters:\n /// - sign: The sign to use for the new value.\n /// - exponent: The new value's exponent.\n /// - significand: The new value's significand.\n init(sign: FloatingPointSign, exponent: Exponent, significand: Self)\n\n /// Creates a new floating-point value using the sign of one value and the\n /// magnitude of another.\n ///\n /// The following example uses this initializer to create a new `Double`\n /// instance with the sign of `a` and the magnitude of `b`:\n ///\n /// let a = -21.5\n /// let b = 305.15\n /// let c = Double(signOf: a, magnitudeOf: b)\n /// print(c)\n /// // Prints "-305.15"\n ///\n /// This initializer implements the IEEE 754 `copysign` operation.\n ///\n /// - Parameters:\n /// - signOf: A value from which to use the sign. The result of the\n /// initializer has the same sign as `signOf`.\n /// - magnitudeOf: A value from which to use the magnitude. The result of\n /// the initializer has the same magnitude as `magnitudeOf`.\n init(signOf: Self, magnitudeOf: Self)\n \n /// Creates a new value, rounded to the closest possible representation.\n ///\n /// If two representable values are equally close, the result is the value\n /// with more trailing zeros in its significand bit pattern.\n ///\n /// - Parameter value: The integer to convert to a floating-point value.\n init(_ value: Int)\n\n /// Creates a new value, rounded to the closest possible representation.\n ///\n /// If two representable values are equally close, the result is the value\n /// with more trailing zeros in its significand bit pattern.\n ///\n /// - Parameter value: The integer to convert to a floating-point value.\n init<Source: BinaryInteger>(_ value: Source)\n\n /// Creates a new value, if the given integer can be represented exactly.\n ///\n /// If the given integer cannot be represented exactly, the result is `nil`.\n ///\n /// - Parameter value: The integer to convert to a floating-point value.\n init?<Source: BinaryInteger>(exactly value: Source)\n\n /// The radix, or base of exponentiation, for a floating-point type.\n ///\n /// The magnitude of a floating-point value `x` of type `F` can be calculated\n /// by using the following formula, where `**` is exponentiation:\n ///\n /// x.significand * (F.radix ** x.exponent)\n ///\n /// A conforming type may use any integer radix, but values other than 2 (for\n /// binary floating-point types) or 10 (for decimal floating-point types)\n /// are extraordinarily rare in practice.\n static var radix: Int { get }\n\n /// A quiet NaN ("not a number").\n ///\n /// A NaN compares not equal, not greater than, and not less than every\n /// value, including itself. Passing a NaN to an operation generally results\n /// in NaN.\n ///\n /// let x = 1.21\n /// // x > Double.nan == false\n /// // x < Double.nan == false\n /// // x == Double.nan == false\n ///\n /// Because a NaN always compares not equal to itself, to test whether a\n /// floating-point value is NaN, use its `isNaN` property instead of the\n /// equal-to operator (`==`). In the following example, `y` is NaN.\n ///\n /// let y = x + Double.nan\n /// print(y == Double.nan)\n /// // Prints "false"\n /// print(y.isNaN)\n /// // Prints "true"\n static var nan: Self { get }\n\n /// A signaling NaN ("not a number").\n ///\n /// The default IEEE 754 behavior of operations involving a signaling NaN is\n /// to raise the Invalid flag in the floating-point environment and return a\n /// quiet NaN.\n ///\n /// Operations on types conforming to the `FloatingPoint` protocol should\n /// support this behavior, but they might also support other options. For\n /// example, it would be reasonable to implement alternative operations in\n /// which operating on a signaling NaN triggers a runtime error or results\n /// in a diagnostic for debugging purposes. Types that implement alternative\n /// behaviors for a signaling NaN must document the departure.\n ///\n /// Other than these signaling operations, a signaling NaN behaves in the\n /// same manner as a quiet NaN.\n static var signalingNaN: Self { get }\n\n /// Positive infinity.\n ///\n /// Infinity compares greater than all finite numbers and equal to other\n /// infinite values.\n ///\n /// let x = Double.greatestFiniteMagnitude\n /// let y = x * 2\n /// // y == Double.infinity\n /// // y > x\n static var infinity: Self { get }\n\n /// The greatest finite number representable by this type.\n ///\n /// This value compares greater than or equal to all finite numbers, but less\n /// than `infinity`.\n ///\n /// This value corresponds to type-specific C macros such as `FLT_MAX` and\n /// `DBL_MAX`. The naming of those macros is slightly misleading, because\n /// `infinity` is greater than this value.\n static var greatestFiniteMagnitude: Self { get }\n\n /// The mathematical constant pi (π), approximately equal to 3.14159.\n /// \n /// When measuring an angle in radians, π is equivalent to a half-turn.\n ///\n /// This value is rounded toward zero to keep user computations with angles\n /// from inadvertently ending up in the wrong quadrant. A type that conforms\n /// to the `FloatingPoint` protocol provides the value for `pi` at its best\n /// possible precision.\n ///\n /// print(Double.pi)\n /// // Prints "3.14159265358979"\n static var pi: Self { get }\n\n // NOTE: Rationale for "ulp" instead of "epsilon":\n // We do not use that name because it is ambiguous at best and misleading\n // at worst:\n //\n // - Historically several definitions of "machine epsilon" have commonly\n // been used, which differ by up to a factor of two or so. By contrast\n // "ulp" is a term with a specific unambiguous definition.\n //\n // - Some languages have used "epsilon" to refer to wildly different values,\n // such as `leastNonzeroMagnitude`.\n //\n // - Inexperienced users often believe that "epsilon" should be used as a\n // tolerance for floating-point comparisons, because of the name. It is\n // nearly always the wrong value to use for this purpose.\n\n /// The unit in the last place of this value.\n ///\n /// This is the unit of the least significant digit in this value's\n /// significand. For most numbers `x`, this is the difference between `x`\n /// and the next greater (in magnitude) representable number. There are some\n /// edge cases to be aware of:\n ///\n /// - If `x` is not a finite number, then `x.ulp` is NaN.\n /// - If `x` is very small in magnitude, then `x.ulp` may be a subnormal\n /// number. If a type does not support subnormals, `x.ulp` may be rounded\n /// to zero.\n /// - `greatestFiniteMagnitude.ulp` is a finite number, even though the next\n /// greater representable value is `infinity`.\n ///\n /// See also the `ulpOfOne` static property.\n var ulp: Self { get }\n\n /// The unit in the last place of 1.0.\n ///\n /// The positive difference between 1.0 and the next greater representable\n /// number. `ulpOfOne` corresponds to the value represented by the C macros\n /// `FLT_EPSILON`, `DBL_EPSILON`, etc, and is sometimes called *epsilon* or\n /// *machine epsilon*. Swift deliberately avoids using the term "epsilon"\n /// because:\n ///\n /// - Historically "epsilon" has been used to refer to several different\n /// concepts in different languages, leading to confusion and bugs.\n ///\n /// - The name "epsilon" suggests that this quantity is a good tolerance to\n /// choose for approximate comparisons, but it is almost always unsuitable\n /// for that purpose.\n ///\n /// See also the `ulp` member property.\n static var ulpOfOne: Self { get }\n\n /// The least positive normal number.\n ///\n /// This value compares less than or equal to all positive normal numbers.\n /// There may be smaller positive numbers, but they are *subnormal*, meaning\n /// that they are represented with less precision than normal numbers.\n ///\n /// This value corresponds to type-specific C macros such as `FLT_MIN` and\n /// `DBL_MIN`. The naming of those macros is slightly misleading, because\n /// subnormals, zeros, and negative numbers are smaller than this value.\n static var leastNormalMagnitude: Self { get }\n\n /// The least positive number.\n ///\n /// This value compares less than or equal to all positive numbers, but\n /// greater than zero. If the type supports subnormal values,\n /// `leastNonzeroMagnitude` is smaller than `leastNormalMagnitude`;\n /// otherwise they are equal.\n static var leastNonzeroMagnitude: Self { get }\n\n /// The sign of the floating-point value.\n ///\n /// The `sign` property is `.minus` if the value's signbit is set, and\n /// `.plus` otherwise. For example:\n ///\n /// let x = -33.375\n /// // x.sign == .minus\n ///\n /// Don't use this property to check whether a floating point value is\n /// negative. For a value `x`, the comparison `x.sign == .minus` is not\n /// necessarily the same as `x < 0`. In particular, `x.sign == .minus` if\n /// `x` is -0, and while `x < 0` is always `false` if `x` is NaN, `x.sign`\n /// could be either `.plus` or `.minus`.\n var sign: FloatingPointSign { get }\n\n /// The exponent of the floating-point value.\n ///\n /// The *exponent* of a floating-point value is the integer part of the\n /// logarithm of the value's magnitude. For a value `x` of a floating-point\n /// type `F`, the magnitude can be calculated as the following, where `**`\n /// is exponentiation:\n ///\n /// x.significand * (F.radix ** x.exponent)\n ///\n /// In the next example, `y` has a value of `21.5`, which is encoded as\n /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375.\n ///\n /// let y: Double = 21.5\n /// // y.significand == 1.34375\n /// // y.exponent == 4\n /// // Double.radix == 2\n ///\n /// The `exponent` property has the following edge cases:\n ///\n /// - If `x` is zero, then `x.exponent` is `Int.min`.\n /// - If `x` is +/-infinity or NaN, then `x.exponent` is `Int.max`\n ///\n /// This property implements the `logB` operation defined by the [IEEE 754\n /// specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n var exponent: Exponent { get }\n\n /// The significand of the floating-point value.\n ///\n /// The magnitude of a floating-point value `x` of type `F` can be calculated\n /// by using the following formula, where `**` is exponentiation:\n ///\n /// x.significand * (F.radix ** x.exponent)\n ///\n /// In the next example, `y` has a value of `21.5`, which is encoded as\n /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375.\n ///\n /// let y: Double = 21.5\n /// // y.significand == 1.34375\n /// // y.exponent == 4\n /// // Double.radix == 2\n ///\n /// If a type's radix is 2, then for finite nonzero numbers, the significand\n /// is in the range `1.0 ..< 2.0`. For other values of `x`, `x.significand`\n /// is defined as follows:\n ///\n /// - If `x` is zero, then `x.significand` is 0.0.\n /// - If `x` is infinite, then `x.significand` is infinity.\n /// - If `x` is NaN, then `x.significand` is NaN.\n /// - Note: The significand is frequently also called the *mantissa*, but\n /// significand is the preferred terminology in the [IEEE 754\n /// specification][spec], to allay confusion with the use of mantissa for\n /// the fractional part of a logarithm.\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n var significand: Self { get }\n\n /// Adds two values and produces their sum, rounded to a\n /// representable value.\n ///\n /// The addition operator (`+`) calculates the sum of its two arguments. For\n /// example:\n ///\n /// let x = 1.5\n /// let y = x + 2.25\n /// // y == 3.75\n ///\n /// The `+` operator implements the addition operation defined by the\n /// [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameters:\n /// - lhs: The first value to add.\n /// - rhs: The second value to add.\n override static func +(lhs: Self, rhs: Self) -> Self\n\n /// Adds two values and stores the result in the left-hand-side variable,\n /// rounded to a representable value.\n ///\n /// - Parameters:\n /// - lhs: The first value to add.\n /// - rhs: The second value to add.\n override static func +=(lhs: inout Self, rhs: Self)\n\n /// Calculates the additive inverse of a value.\n ///\n /// The unary minus operator (prefix `-`) calculates the negation of its\n /// operand. The result is always exact.\n ///\n /// let x = 21.5\n /// let y = -x\n /// // y == -21.5\n ///\n /// - Parameter operand: The value to negate.\n override static prefix func - (_ operand: Self) -> Self\n\n /// Replaces this value with its additive inverse.\n ///\n /// The result is always exact. This example uses the `negate()` method to\n /// negate the value of the variable `x`:\n ///\n /// var x = 21.5\n /// x.negate()\n /// // x == -21.5\n override mutating func negate()\n\n /// Subtracts one value from another and produces their difference, rounded\n /// to a representable value.\n ///\n /// The subtraction operator (`-`) calculates the difference of its two\n /// arguments. For example:\n ///\n /// let x = 7.5\n /// let y = x - 2.25\n /// // y == 5.25\n ///\n /// The `-` operator implements the subtraction operation defined by the\n /// [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameters:\n /// - lhs: A numeric value.\n /// - rhs: The value to subtract from `lhs`.\n override static func -(lhs: Self, rhs: Self) -> Self\n\n /// Subtracts the second value from the first and stores the difference in\n /// the left-hand-side variable, rounding to a representable value.\n ///\n /// - Parameters:\n /// - lhs: A numeric value.\n /// - rhs: The value to subtract from `lhs`.\n override static func -=(lhs: inout Self, rhs: Self)\n\n /// Multiplies two values and produces their product, rounding to a\n /// representable value.\n ///\n /// The multiplication operator (`*`) calculates the product of its two\n /// arguments. For example:\n ///\n /// let x = 7.5\n /// let y = x * 2.25\n /// // y == 16.875\n ///\n /// The `*` operator implements the multiplication operation defined by the\n /// [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameters:\n /// - lhs: The first value to multiply.\n /// - rhs: The second value to multiply.\n override static func *(lhs: Self, rhs: Self) -> Self\n\n /// Multiplies two values and stores the result in the left-hand-side\n /// variable, rounding to a representable value.\n ///\n /// - Parameters:\n /// - lhs: The first value to multiply.\n /// - rhs: The second value to multiply.\n override static func *=(lhs: inout Self, rhs: Self)\n\n /// Returns the quotient of dividing the first value by the second, rounded\n /// to a representable value.\n ///\n /// The division operator (`/`) calculates the quotient of the division if\n /// `rhs` is nonzero. If `rhs` is zero, the result of the division is\n /// infinity, with the sign of the result matching the sign of `lhs`.\n ///\n /// let x = 16.875\n /// let y = x / 2.25\n /// // y == 7.5\n ///\n /// let z = x / 0\n /// // z.isInfinite == true\n ///\n /// The `/` operator implements the division operation defined by the [IEEE\n /// 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameters:\n /// - lhs: The value to divide.\n /// - rhs: The value to divide `lhs` by.\n static func /(lhs: Self, rhs: Self) -> Self\n\n /// Divides the first value by the second and stores the quotient in the\n /// left-hand-side variable, rounding to a representable value.\n ///\n /// - Parameters:\n /// - lhs: The value to divide.\n /// - rhs: The value to divide `lhs` by.\n static func /=(lhs: inout Self, rhs: Self)\n\n /// Returns the remainder of this value divided by the given value.\n ///\n /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by\n /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to\n /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is\n /// chosen to be even. Note that `q` is *not* `x / y` computed in\n /// floating-point arithmetic, and that `q` may not be representable in any\n /// available integer type.\n ///\n /// The following example calculates the remainder of dividing 8.625 by 0.75:\n ///\n /// let x = 8.625\n /// print(x / 0.75)\n /// // Prints "11.5"\n ///\n /// let q = (x / 0.75).rounded(.toNearestOrEven)\n /// // q == 12.0\n /// let r = x.remainder(dividingBy: 0.75)\n /// // r == -0.375\n ///\n /// let x1 = 0.75 * q + r\n /// // x1 == 8.625\n ///\n /// If this value and `other` are finite numbers, the remainder is in the\n /// closed range `-abs(other / 2)...abs(other / 2)`. The\n /// `remainder(dividingBy:)` method is always exact. This method implements\n /// the remainder operation defined by the [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameter other: The value to use when dividing this value.\n /// - Returns: The remainder of this value divided by `other`.\n func remainder(dividingBy other: Self) -> Self\n\n /// Replaces this value with the remainder of itself divided by the given\n /// value.\n ///\n /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by\n /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to\n /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is\n /// chosen to be even. Note that `q` is *not* `x / y` computed in\n /// floating-point arithmetic, and that `q` may not be representable in any\n /// available integer type.\n ///\n /// The following example calculates the remainder of dividing 8.625 by 0.75:\n ///\n /// var x = 8.625\n /// print(x / 0.75)\n /// // Prints "11.5"\n ///\n /// let q = (x / 0.75).rounded(.toNearestOrEven)\n /// // q == 12.0\n /// x.formRemainder(dividingBy: 0.75)\n /// // x == -0.375\n ///\n /// let x1 = 0.75 * q + x\n /// // x1 == 8.625\n ///\n /// If this value and `other` are finite numbers, the remainder is in the\n /// closed range `-abs(other / 2)...abs(other / 2)`. The\n /// `formRemainder(dividingBy:)` method is always exact.\n ///\n /// - Parameter other: The value to use when dividing this value.\n mutating func formRemainder(dividingBy other: Self)\n\n /// Returns the remainder of this value divided by the given value using\n /// truncating division.\n ///\n /// Performing truncating division with floating-point values results in a\n /// truncated integer quotient and a remainder. For values `x` and `y` and\n /// their truncated integer quotient `q`, the remainder `r` satisfies\n /// `x == y * q + r`.\n ///\n /// The following example calculates the truncating remainder of dividing\n /// 8.625 by 0.75:\n ///\n /// let x = 8.625\n /// print(x / 0.75)\n /// // Prints "11.5"\n ///\n /// let q = (x / 0.75).rounded(.towardZero)\n /// // q == 11.0\n /// let r = x.truncatingRemainder(dividingBy: 0.75)\n /// // r == 0.375\n ///\n /// let x1 = 0.75 * q + r\n /// // x1 == 8.625\n ///\n /// If this value and `other` are both finite numbers, the truncating\n /// remainder has the same sign as this value and is strictly smaller in\n /// magnitude than `other`. The `truncatingRemainder(dividingBy:)` method\n /// is always exact.\n ///\n /// - Parameter other: The value to use when dividing this value.\n /// - Returns: The remainder of this value divided by `other` using\n /// truncating division.\n func truncatingRemainder(dividingBy other: Self) -> Self\n\n /// Replaces this value with the remainder of itself divided by the given\n /// value using truncating division.\n ///\n /// Performing truncating division with floating-point values results in a\n /// truncated integer quotient and a remainder. For values `x` and `y` and\n /// their truncated integer quotient `q`, the remainder `r` satisfies\n /// `x == y * q + r`.\n ///\n /// The following example calculates the truncating remainder of dividing\n /// 8.625 by 0.75:\n ///\n /// var x = 8.625\n /// print(x / 0.75)\n /// // Prints "11.5"\n ///\n /// let q = (x / 0.75).rounded(.towardZero)\n /// // q == 11.0\n /// x.formTruncatingRemainder(dividingBy: 0.75)\n /// // x == 0.375\n ///\n /// let x1 = 0.75 * q + x\n /// // x1 == 8.625\n ///\n /// If this value and `other` are both finite numbers, the truncating\n /// remainder has the same sign as this value and is strictly smaller in\n /// magnitude than `other`. The `formTruncatingRemainder(dividingBy:)`\n /// method is always exact.\n ///\n /// - Parameter other: The value to use when dividing this value.\n mutating func formTruncatingRemainder(dividingBy other: Self)\n\n /// Returns the square root of the value, rounded to a representable value.\n ///\n /// The following example declares a function that calculates the length of\n /// the hypotenuse of a right triangle given its two perpendicular sides.\n ///\n /// func hypotenuse(_ a: Double, _ b: Double) -> Double {\n /// return (a * a + b * b).squareRoot()\n /// }\n ///\n /// let (dx, dy) = (3.0, 4.0)\n /// let distance = hypotenuse(dx, dy)\n /// // distance == 5.0\n ///\n /// - Returns: The square root of the value.\n func squareRoot() -> Self\n\n /// Replaces this value with its square root, rounded to a representable\n /// value.\n mutating func formSquareRoot()\n\n /// Returns the result of adding the product of the two given values to this\n /// value, computed without intermediate rounding.\n ///\n /// This method is equivalent to the C `fma` function and implements the\n /// `fusedMultiplyAdd` operation defined by the [IEEE 754\n /// specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameters:\n /// - lhs: One of the values to multiply before adding to this value.\n /// - rhs: The other value to multiply.\n /// - Returns: The product of `lhs` and `rhs`, added to this value.\n func addingProduct(_ lhs: Self, _ rhs: Self) -> Self\n\n /// Adds the product of the two given values to this value in place, computed\n /// without intermediate rounding.\n ///\n /// - Parameters:\n /// - lhs: One of the values to multiply before adding to this value.\n /// - rhs: The other value to multiply.\n mutating func addProduct(_ lhs: Self, _ rhs: Self)\n\n /// Returns the lesser of the two given values.\n ///\n /// This method returns the minimum of two values, preserving order and\n /// eliminating NaN when possible. For two values `x` and `y`, the result of\n /// `minimum(x, y)` is `x` if `x <= y`, `y` if `y < x`, or whichever of `x`\n /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are\n /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN.\n ///\n /// Double.minimum(10.0, -25.0)\n /// // -25.0\n /// Double.minimum(10.0, .nan)\n /// // 10.0\n /// Double.minimum(.nan, -25.0)\n /// // -25.0\n /// Double.minimum(.nan, .nan)\n /// // nan\n ///\n /// The `minimum` method implements the `minNum` operation defined by the\n /// [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameters:\n /// - x: A floating-point value.\n /// - y: Another floating-point value.\n /// - Returns: The minimum of `x` and `y`, or whichever is a number if the\n /// other is NaN.\n static func minimum(_ x: Self, _ y: Self) -> Self\n\n /// Returns the greater of the two given values.\n ///\n /// This method returns the maximum of two values, preserving order and\n /// eliminating NaN when possible. For two values `x` and `y`, the result of\n /// `maximum(x, y)` is `x` if `x > y`, `y` if `x <= y`, or whichever of `x`\n /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are\n /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN.\n ///\n /// Double.maximum(10.0, -25.0)\n /// // 10.0\n /// Double.maximum(10.0, .nan)\n /// // 10.0\n /// Double.maximum(.nan, -25.0)\n /// // -25.0\n /// Double.maximum(.nan, .nan)\n /// // nan\n ///\n /// The `maximum` method implements the `maxNum` operation defined by the\n /// [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameters:\n /// - x: A floating-point value.\n /// - y: Another floating-point value.\n /// - Returns: The greater of `x` and `y`, or whichever is a number if the\n /// other is NaN.\n static func maximum(_ x: Self, _ y: Self) -> Self\n\n /// Returns the value with lesser magnitude.\n ///\n /// This method returns the value with lesser magnitude of the two given\n /// values, preserving order and eliminating NaN when possible. For two\n /// values `x` and `y`, the result of `minimumMagnitude(x, y)` is `x` if\n /// `x.magnitude <= y.magnitude`, `y` if `y.magnitude < x.magnitude`, or\n /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both\n /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result\n /// is NaN.\n ///\n /// Double.minimumMagnitude(10.0, -25.0)\n /// // 10.0\n /// Double.minimumMagnitude(10.0, .nan)\n /// // 10.0\n /// Double.minimumMagnitude(.nan, -25.0)\n /// // -25.0\n /// Double.minimumMagnitude(.nan, .nan)\n /// // nan\n ///\n /// The `minimumMagnitude` method implements the `minNumMag` operation\n /// defined by the [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameters:\n /// - x: A floating-point value.\n /// - y: Another floating-point value.\n /// - Returns: Whichever of `x` or `y` has lesser magnitude, or whichever is\n /// a number if the other is NaN.\n static func minimumMagnitude(_ x: Self, _ y: Self) -> Self\n\n /// Returns the value with greater magnitude.\n ///\n /// This method returns the value with greater magnitude of the two given\n /// values, preserving order and eliminating NaN when possible. For two\n /// values `x` and `y`, the result of `maximumMagnitude(x, y)` is `x` if\n /// `x.magnitude > y.magnitude`, `y` if `x.magnitude <= y.magnitude`, or\n /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both\n /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result\n /// is NaN.\n ///\n /// Double.maximumMagnitude(10.0, -25.0)\n /// // -25.0\n /// Double.maximumMagnitude(10.0, .nan)\n /// // 10.0\n /// Double.maximumMagnitude(.nan, -25.0)\n /// // -25.0\n /// Double.maximumMagnitude(.nan, .nan)\n /// // nan\n ///\n /// The `maximumMagnitude` method implements the `maxNumMag` operation\n /// defined by the [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameters:\n /// - x: A floating-point value.\n /// - y: Another floating-point value.\n /// - Returns: Whichever of `x` or `y` has greater magnitude, or whichever is\n /// a number if the other is NaN.\n static func maximumMagnitude(_ x: Self, _ y: Self) -> Self\n\n /// Returns this value rounded to an integral value using the specified\n /// rounding rule.\n ///\n /// The following example rounds a value using four different rounding rules:\n ///\n /// let x = 6.5\n ///\n /// // Equivalent to the C 'round' function:\n /// print(x.rounded(.toNearestOrAwayFromZero))\n /// // Prints "7.0"\n ///\n /// // Equivalent to the C 'trunc' function:\n /// print(x.rounded(.towardZero))\n /// // Prints "6.0"\n ///\n /// // Equivalent to the C 'ceil' function:\n /// print(x.rounded(.up))\n /// // Prints "7.0"\n ///\n /// // Equivalent to the C 'floor' function:\n /// print(x.rounded(.down))\n /// // Prints "6.0"\n ///\n /// For more information about the available rounding rules, see the\n /// `FloatingPointRoundingRule` enumeration. To round a value using the\n /// default "schoolbook rounding" of `.toNearestOrAwayFromZero`, you can use\n /// the shorter `rounded()` method instead.\n ///\n /// print(x.rounded())\n /// // Prints "7.0"\n ///\n /// - Parameter rule: The rounding rule to use.\n /// - Returns: The integral value found by rounding using `rule`.\n func rounded(_ rule: FloatingPointRoundingRule) -> Self\n\n /// Rounds the value to an integral value using the specified rounding rule.\n ///\n /// The following example rounds a value using four different rounding rules:\n ///\n /// // Equivalent to the C 'round' function:\n /// var w = 6.5\n /// w.round(.toNearestOrAwayFromZero)\n /// // w == 7.0\n ///\n /// // Equivalent to the C 'trunc' function:\n /// var x = 6.5\n /// x.round(.towardZero)\n /// // x == 6.0\n ///\n /// // Equivalent to the C 'ceil' function:\n /// var y = 6.5\n /// y.round(.up)\n /// // y == 7.0\n ///\n /// // Equivalent to the C 'floor' function:\n /// var z = 6.5\n /// z.round(.down)\n /// // z == 6.0\n ///\n /// For more information about the available rounding rules, see the\n /// `FloatingPointRoundingRule` enumeration. To round a value using the\n /// default "schoolbook rounding" of `.toNearestOrAwayFromZero`, you can use\n /// the shorter `round()` method instead.\n ///\n /// var w1 = 6.5\n /// w1.round()\n /// // w1 == 7.0\n ///\n /// - Parameter rule: The rounding rule to use.\n mutating func round(_ rule: FloatingPointRoundingRule)\n\n /// The least representable value that compares greater than this value.\n ///\n /// For any finite value `x`, `x.nextUp` is greater than `x`. For `nan` or\n /// `infinity`, `x.nextUp` is `x` itself. The following special cases also\n /// apply:\n ///\n /// - If `x` is `-infinity`, then `x.nextUp` is `-greatestFiniteMagnitude`.\n /// - If `x` is `-leastNonzeroMagnitude`, then `x.nextUp` is `-0.0`.\n /// - If `x` is zero, then `x.nextUp` is `leastNonzeroMagnitude`.\n /// - If `x` is `greatestFiniteMagnitude`, then `x.nextUp` is `infinity`.\n var nextUp: Self { get }\n\n /// The greatest representable value that compares less than this value.\n ///\n /// For any finite value `x`, `x.nextDown` is less than `x`. For `nan` or\n /// `-infinity`, `x.nextDown` is `x` itself. The following special cases\n /// also apply:\n ///\n /// - If `x` is `infinity`, then `x.nextDown` is `greatestFiniteMagnitude`.\n /// - If `x` is `leastNonzeroMagnitude`, then `x.nextDown` is `0.0`.\n /// - If `x` is zero, then `x.nextDown` is `-leastNonzeroMagnitude`.\n /// - If `x` is `-greatestFiniteMagnitude`, then `x.nextDown` is `-infinity`.\n var nextDown: Self { get }\n\n /// Returns a Boolean value indicating whether this instance is equal to the\n /// given value.\n ///\n /// This method serves as the basis for the equal-to operator (`==`) for\n /// floating-point values. When comparing two values with this method, `-0`\n /// is equal to `+0`. NaN is not equal to any value, including itself. For\n /// example:\n ///\n /// let x = 15.0\n /// x.isEqual(to: 15.0)\n /// // true\n /// x.isEqual(to: .nan)\n /// // false\n /// Double.nan.isEqual(to: .nan)\n /// // false\n ///\n /// The `isEqual(to:)` method implements the equality predicate defined by\n /// the [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameter other: The value to compare with this value.\n /// - Returns: `true` if `other` has the same value as this instance;\n /// otherwise, `false`. If either this value or `other` is NaN, the result\n /// of this method is `false`.\n func isEqual(to other: Self) -> Bool\n\n /// Returns a Boolean value indicating whether this instance is less than the\n /// given value.\n ///\n /// This method serves as the basis for the less-than operator (`<`) for\n /// floating-point values. Some special cases apply:\n ///\n /// - Because NaN compares not less than nor greater than any value, this\n /// method returns `false` when called on NaN or when NaN is passed as\n /// `other`.\n /// - `-infinity` compares less than all values except for itself and NaN.\n /// - Every value except for NaN and `+infinity` compares less than\n /// `+infinity`.\n ///\n /// The following example shows the behavior of the `isLess(than:)` method\n /// with different kinds of values:\n ///\n /// let x = 15.0\n /// x.isLess(than: 20.0)\n /// // true\n /// x.isLess(than: .nan)\n /// // false\n /// Double.nan.isLess(than: x)\n /// // false\n ///\n /// The `isLess(than:)` method implements the less-than predicate defined by\n /// the [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameter other: The value to compare with this value.\n /// - Returns: `true` if this value is less than `other`; otherwise, `false`.\n /// If either this value or `other` is NaN, the result of this method is\n /// `false`.\n func isLess(than other: Self) -> Bool\n\n /// Returns a Boolean value indicating whether this instance is less than or\n /// equal to the given value.\n ///\n /// This method serves as the basis for the less-than-or-equal-to operator\n /// (`<=`) for floating-point values. Some special cases apply:\n ///\n /// - Because NaN is incomparable with any value, this method returns `false`\n /// when called on NaN or when NaN is passed as `other`.\n /// - `-infinity` compares less than or equal to all values except NaN.\n /// - Every value except NaN compares less than or equal to `+infinity`.\n ///\n /// The following example shows the behavior of the `isLessThanOrEqualTo(_:)`\n /// method with different kinds of values:\n ///\n /// let x = 15.0\n /// x.isLessThanOrEqualTo(20.0)\n /// // true\n /// x.isLessThanOrEqualTo(.nan)\n /// // false\n /// Double.nan.isLessThanOrEqualTo(x)\n /// // false\n ///\n /// The `isLessThanOrEqualTo(_:)` method implements the less-than-or-equal\n /// predicate defined by the [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameter other: The value to compare with this value.\n /// - Returns: `true` if `other` is greater than this value; otherwise,\n /// `false`. If either this value or `other` is NaN, the result of this\n /// method is `false`.\n func isLessThanOrEqualTo(_ other: Self) -> Bool\n\n /// Returns a Boolean value indicating whether this instance should precede\n /// or tie positions with the given value in an ascending sort.\n ///\n /// This relation is a refinement of the less-than-or-equal-to operator\n /// (`<=`) that provides a total order on all values of the type, including\n /// signed zeros and NaNs.\n ///\n /// The following example uses `isTotallyOrdered(belowOrEqualTo:)` to sort an\n /// array of floating-point values, including some that are NaN:\n ///\n /// var numbers = [2.5, 21.25, 3.0, .nan, -9.5]\n /// numbers.sort { !$1.isTotallyOrdered(belowOrEqualTo: $0) }\n /// print(numbers)\n /// // Prints "[-9.5, 2.5, 3.0, 21.25, nan]"\n ///\n /// The `isTotallyOrdered(belowOrEqualTo:)` method implements the total order\n /// relation as defined by the [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameter other: A floating-point value to compare to this value.\n /// - Returns: `true` if this value is ordered below or the same as `other`\n /// in a total ordering of the floating-point type; otherwise, `false`.\n func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool\n\n /// A Boolean value indicating whether this instance is normal.\n ///\n /// A *normal* value is a finite number that uses the full precision\n /// available to values of a type. Zero is neither a normal nor a subnormal\n /// number.\n var isNormal: Bool { get }\n\n /// A Boolean value indicating whether this instance is finite.\n ///\n /// All values other than NaN and infinity are considered finite, whether\n /// normal or subnormal. For NaN, both `isFinite` and `isInfinite` are false.\n var isFinite: Bool { get }\n\n /// A Boolean value indicating whether the instance is equal to zero.\n ///\n /// The `isZero` property of a value `x` is `true` when `x` represents either\n /// `-0.0` or `+0.0`. `x.isZero` is equivalent to the following comparison:\n /// `x == 0.0`.\n ///\n /// let x = -0.0\n /// x.isZero // true\n /// x == 0.0 // true\n var isZero: Bool { get }\n\n /// A Boolean value indicating whether the instance is subnormal.\n ///\n /// A *subnormal* value is a nonzero number that has a lesser magnitude than\n /// the smallest normal number. Subnormal values don't use the full\n /// precision available to values of a type.\n ///\n /// Zero is neither a normal nor a subnormal number. Subnormal numbers are\n /// often called *denormal* or *denormalized*---these are different names\n /// for the same concept.\n var isSubnormal: Bool { get }\n\n /// A Boolean value indicating whether the instance is infinite.\n ///\n /// For NaN, both `isFinite` and `isInfinite` are false.\n var isInfinite: Bool { get }\n\n /// A Boolean value indicating whether the instance is NaN ("not a number").\n ///\n /// Because NaN is not equal to any value, including NaN, use this property\n /// instead of the equal-to operator (`==`) or not-equal-to operator (`!=`)\n /// to test whether a value is or is not NaN. For example:\n ///\n /// let x = 0.0\n /// let y = x * .infinity\n /// // y is a NaN\n ///\n /// // Comparing with the equal-to operator never returns 'true'\n /// print(x == Double.nan)\n /// // Prints "false"\n /// print(y == Double.nan)\n /// // Prints "false"\n ///\n /// // Test with the 'isNaN' property instead\n /// print(x.isNaN)\n /// // Prints "false"\n /// print(y.isNaN)\n /// // Prints "true"\n ///\n /// This property is `true` for both quiet and signaling NaNs.\n var isNaN: Bool { get }\n\n /// A Boolean value indicating whether the instance is a signaling NaN.\n ///\n /// Signaling NaNs typically raise the Invalid flag when used in general\n /// computing operations.\n var isSignalingNaN: Bool { get }\n\n /// The classification of this value.\n ///\n /// A value's `floatingPointClass` property describes its "class" as\n /// described by the [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n var floatingPointClass: FloatingPointClassification { get }\n\n /// A Boolean value indicating whether the instance's representation is in\n /// its canonical form.\n ///\n /// The [IEEE 754 specification][spec] defines a *canonical*, or preferred,\n /// encoding of a floating-point value. On platforms that fully support\n /// IEEE 754, every `Float` or `Double` value is canonical, but\n /// non-canonical values can exist on other platforms or for other types.\n /// Some examples:\n ///\n /// - On platforms that flush subnormal numbers to zero (such as armv7\n /// with the default floating-point environment), Swift interprets\n /// subnormal `Float` and `Double` values as non-canonical zeros.\n /// (In Swift 5.1 and earlier, `isCanonical` is `true` for these\n /// values, which is the incorrect value.)\n ///\n /// - On i386 and x86_64, `Float80` has a number of non-canonical\n /// encodings. "Pseudo-NaNs", "pseudo-infinities", and "unnormals" are\n /// interpreted as non-canonical NaN encodings. "Pseudo-denormals" are\n /// interpreted as non-canonical encodings of subnormal values.\n ///\n /// - Decimal floating-point types admit a large number of non-canonical\n /// encodings. Consult the IEEE 754 standard for additional details.\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n var isCanonical: Bool { get }\n}\n\n/// The sign of a floating-point value.\n@frozen\npublic enum FloatingPointSign: Int, Sendable {\n /// The sign for a positive value.\n case plus\n\n /// The sign for a negative value.\n case minus\n\n // Explicit declarations of otherwise-synthesized members to make them\n // @inlinable, promising that we will never change the implementation.\n\n @inlinable\n public init?(rawValue: Int) {\n switch rawValue {\n case 0: self = .plus\n case 1: self = .minus\n default: return nil\n }\n }\n\n @inlinable\n public var rawValue: Int {\n switch self {\n case .plus: return 0\n case .minus: return 1\n }\n }\n\n @_transparent\n @inlinable\n public static func ==(a: FloatingPointSign, b: FloatingPointSign) -> Bool {\n return a.rawValue == b.rawValue\n }\n\n @inlinable\n public var hashValue: Int { return rawValue.hashValue }\n\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine(rawValue)\n }\n\n @inlinable\n public func _rawHashValue(seed: Int) -> Int {\n return rawValue._rawHashValue(seed: seed)\n }\n}\n\n/// The IEEE 754 floating-point classes.\n@frozen\npublic enum FloatingPointClassification: Sendable {\n /// A signaling NaN ("not a number").\n ///\n /// A signaling NaN sets the floating-point exception status when used in\n /// many floating-point operations.\n case signalingNaN\n\n /// A silent NaN ("not a number") value.\n case quietNaN\n\n /// A value equal to `-infinity`.\n case negativeInfinity\n\n /// A negative value that uses the full precision of the floating-point type.\n case negativeNormal\n\n /// A negative, nonzero number that does not use the full precision of the\n /// floating-point type.\n case negativeSubnormal\n\n /// A value equal to zero with a negative sign.\n case negativeZero\n\n /// A value equal to zero with a positive sign.\n case positiveZero\n\n /// A positive, nonzero number that does not use the full precision of the\n /// floating-point type.\n case positiveSubnormal\n\n /// A positive value that uses the full precision of the floating-point type.\n case positiveNormal\n\n /// A value equal to `+infinity`.\n case positiveInfinity\n}\n\n/// A rule for rounding a floating-point number.\npublic enum FloatingPointRoundingRule: Sendable {\n /// Round to the closest allowed value; if two values are equally close, the\n /// one with greater magnitude is chosen.\n ///\n /// This rounding rule is also known as "schoolbook rounding." The following\n /// example shows the results of rounding numbers using this rule:\n ///\n /// (5.2).rounded(.toNearestOrAwayFromZero)\n /// // 5.0\n /// (5.5).rounded(.toNearestOrAwayFromZero)\n /// // 6.0\n /// (-5.2).rounded(.toNearestOrAwayFromZero)\n /// // -5.0\n /// (-5.5).rounded(.toNearestOrAwayFromZero)\n /// // -6.0\n ///\n /// This rule is equivalent to the C `round` function and implements the\n /// `roundToIntegralTiesToAway` operation defined by the [IEEE 754\n /// specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n case toNearestOrAwayFromZero\n\n /// Round to the closest allowed value; if two values are equally close, the\n /// even one is chosen.\n ///\n /// This rounding rule is also known as "bankers rounding," and is the\n /// default IEEE 754 rounding mode for arithmetic. The following example\n /// shows the results of rounding numbers using this rule:\n ///\n /// (5.2).rounded(.toNearestOrEven)\n /// // 5.0\n /// (5.5).rounded(.toNearestOrEven)\n /// // 6.0\n /// (4.5).rounded(.toNearestOrEven)\n /// // 4.0\n ///\n /// This rule implements the `roundToIntegralTiesToEven` operation defined by\n /// the [IEEE 754 specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n case toNearestOrEven\n\n /// Round to the closest allowed value that is greater than or equal to the\n /// source.\n ///\n /// The following example shows the results of rounding numbers using this\n /// rule:\n ///\n /// (5.2).rounded(.up)\n /// // 6.0\n /// (5.5).rounded(.up)\n /// // 6.0\n /// (-5.2).rounded(.up)\n /// // -5.0\n /// (-5.5).rounded(.up)\n /// // -5.0\n ///\n /// This rule is equivalent to the C `ceil` function and implements the\n /// `roundToIntegralTowardPositive` operation defined by the [IEEE 754\n /// specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n case up\n\n /// Round to the closest allowed value that is less than or equal to the\n /// source.\n ///\n /// The following example shows the results of rounding numbers using this\n /// rule:\n ///\n /// (5.2).rounded(.down)\n /// // 5.0\n /// (5.5).rounded(.down)\n /// // 5.0\n /// (-5.2).rounded(.down)\n /// // -6.0\n /// (-5.5).rounded(.down)\n /// // -6.0\n ///\n /// This rule is equivalent to the C `floor` function and implements the\n /// `roundToIntegralTowardNegative` operation defined by the [IEEE 754\n /// specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n case down\n\n /// Round to the closest allowed value whose magnitude is less than or equal\n /// to that of the source.\n ///\n /// The following example shows the results of rounding numbers using this\n /// rule:\n ///\n /// (5.2).rounded(.towardZero)\n /// // 5.0\n /// (5.5).rounded(.towardZero)\n /// // 5.0\n /// (-5.2).rounded(.towardZero)\n /// // -5.0\n /// (-5.5).rounded(.towardZero)\n /// // -5.0\n ///\n /// This rule is equivalent to the C `trunc` function and implements the\n /// `roundToIntegralTowardZero` operation defined by the [IEEE 754\n /// specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n case towardZero\n\n /// Round to the closest allowed value whose magnitude is greater than or\n /// equal to that of the source.\n ///\n /// The following example shows the results of rounding numbers using this\n /// rule:\n ///\n /// (5.2).rounded(.awayFromZero)\n /// // 6.0\n /// (5.5).rounded(.awayFromZero)\n /// // 6.0\n /// (-5.2).rounded(.awayFromZero)\n /// // -6.0\n /// (-5.5).rounded(.awayFromZero)\n /// // -6.0\n case awayFromZero\n}\n\nextension FloatingPoint {\n @_transparent\n public static func == (lhs: Self, rhs: Self) -> Bool {\n return lhs.isEqual(to: rhs)\n }\n\n @_transparent\n public static func < (lhs: Self, rhs: Self) -> Bool {\n return lhs.isLess(than: rhs)\n }\n\n @_transparent\n public static func <= (lhs: Self, rhs: Self) -> Bool {\n return lhs.isLessThanOrEqualTo(rhs)\n }\n\n @_transparent\n public static func > (lhs: Self, rhs: Self) -> Bool {\n return rhs.isLess(than: lhs)\n }\n\n @_transparent\n public static func >= (lhs: Self, rhs: Self) -> Bool {\n return rhs.isLessThanOrEqualTo(lhs)\n }\n}\n\n/// A radix-2 (binary) floating-point type.\n///\n/// The `BinaryFloatingPoint` protocol extends the `FloatingPoint` protocol\n/// with operations specific to floating-point binary types, as defined by the\n/// [IEEE 754 specification][spec]. `BinaryFloatingPoint` is implemented in\n/// the standard library by `Float`, `Double`, and `Float80` where available.\n///\n/// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\npublic protocol BinaryFloatingPoint: FloatingPoint, ExpressibleByFloatLiteral {\n\n /// A type that represents the encoded significand of a value.\n associatedtype RawSignificand: UnsignedInteger\n\n /// A type that represents the encoded exponent of a value.\n associatedtype RawExponent: UnsignedInteger\n\n /// Creates a new instance from the specified sign and bit patterns.\n ///\n /// The values passed as `exponentBitPattern` and `significandBitPattern` are\n /// interpreted in the binary interchange format defined by the [IEEE 754\n /// specification][spec].\n ///\n /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933\n ///\n /// - Parameters:\n /// - sign: The sign of the new value.\n /// - exponentBitPattern: The bit pattern to use for the exponent field of\n /// the new value.\n /// - significandBitPattern: The bit pattern to use for the significand\n /// field of the new value.\n init(sign: FloatingPointSign,\n exponentBitPattern: RawExponent,\n significandBitPattern: RawSignificand)\n\n /// Creates a new instance from the given value, rounded to the closest\n /// possible representation.\n ///\n /// - Parameter value: A floating-point value to be converted.\n init(_ value: Float)\n\n /// Creates a new instance from the given value, rounded to the closest\n /// possible representation.\n ///\n /// - Parameter value: A floating-point value to be converted.\n init(_ value: Double)\n\n#if !(os(Windows) || os(Android) || ($Embedded && !os(Linux) && !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS)))) && (arch(i386) || arch(x86_64))\n /// Creates a new instance from the given value, rounded to the closest\n /// possible representation.\n ///\n /// - Parameter value: A floating-point value to be converted.\n init(_ value: Float80)\n#endif\n\n /// Creates a new instance from the given value, rounded to the closest\n /// possible representation.\n ///\n /// If two representable values are equally close, the result is the value\n /// with more trailing zeros in its significand bit pattern.\n ///\n /// - Parameter value: A floating-point value to be converted.\n init<Source: BinaryFloatingPoint>(_ value: Source)\n\n /// Creates a new instance from the given value, if it can be represented\n /// exactly.\n ///\n /// If the given floating-point value cannot be represented exactly, the\n /// result is `nil`. A value that is NaN ("not a number") cannot be\n /// represented exactly if its payload cannot be encoded exactly.\n ///\n /// - Parameter value: A floating-point value to be converted.\n init?<Source: BinaryFloatingPoint>(exactly value: Source)\n\n /// The number of bits used to represent the type's exponent.\n ///\n /// A binary floating-point type's `exponentBitCount` imposes a limit on the\n /// range of the exponent for normal, finite values. The *exponent bias* of\n /// a type `F` can be calculated as the following, where `**` is\n /// exponentiation:\n ///\n /// let bias = 2 ** (F.exponentBitCount - 1) - 1\n ///\n /// The least normal exponent for values of the type `F` is `1 - bias`, and\n /// the largest finite exponent is `bias`. An all-zeros exponent is reserved\n /// for subnormals and zeros, and an all-ones exponent is reserved for\n /// infinity and NaN.\n ///\n /// For example, the `Float` type has an `exponentBitCount` of 8, which gives\n /// an exponent bias of `127` by the calculation above.\n ///\n /// let bias = 2 ** (Float.exponentBitCount - 1) - 1\n /// // bias == 127\n /// print(Float.greatestFiniteMagnitude.exponent)\n /// // Prints "127"\n /// print(Float.leastNormalMagnitude.exponent)\n /// // Prints "-126"\n static var exponentBitCount: Int { get }\n\n /// The available number of fractional significand bits.\n ///\n /// For fixed-width floating-point types, this is the actual number of\n /// fractional significand bits.\n ///\n /// For extensible floating-point types, `significandBitCount` should be the\n /// maximum allowed significand width (without counting any leading integral\n /// bit of the significand). If there is no upper limit, then\n /// `significandBitCount` should be `Int.max`.\n ///\n /// Note that `Float80.significandBitCount` is 63, even though 64 bits are\n /// used to store the significand in the memory representation of a\n /// `Float80` (unlike other floating-point types, `Float80` explicitly\n /// stores the leading integral significand bit, but the\n /// `BinaryFloatingPoint` APIs provide an abstraction so that users don't\n /// need to be aware of this detail).\n static var significandBitCount: Int { get }\n\n /// The raw encoding of the value's exponent field.\n ///\n /// This value is unadjusted by the type's exponent bias.\n var exponentBitPattern: RawExponent { get }\n\n /// The raw encoding of the value's significand field.\n ///\n /// The `significandBitPattern` property does not include the leading\n /// integral bit of the significand, even for types like `Float80` that\n /// store it explicitly.\n var significandBitPattern: RawSignificand { get }\n\n /// The floating-point value with the same sign and exponent as this value,\n /// but with a significand of 1.0.\n ///\n /// A *binade* is a set of binary floating-point values that all have the\n /// same sign and exponent. The `binade` property is a member of the same\n /// binade as this value, but with a unit significand.\n ///\n /// In this example, `x` has a value of `21.5`, which is stored as\n /// `1.34375 * 2**4`, where `**` is exponentiation. Therefore, `x.binade` is\n /// equal to `1.0 * 2**4`, or `16.0`.\n ///\n /// let x = 21.5\n /// // x.significand == 1.34375\n /// // x.exponent == 4\n ///\n /// let y = x.binade\n /// // y == 16.0\n /// // y.significand == 1.0\n /// // y.exponent == 4\n var binade: Self { get }\n\n /// The number of bits required to represent the value's significand.\n ///\n /// If this value is a finite nonzero number, `significandWidth` is the\n /// number of fractional bits required to represent the value of\n /// `significand`; otherwise, `significandWidth` is -1. The value of\n /// `significandWidth` is always -1 or between zero and\n /// `significandBitCount`. For example:\n ///\n /// - For any representable power of two, `significandWidth` is zero, because\n /// `significand` is `1.0`.\n /// - If `x` is 10, `x.significand` is `1.01` in binary, so\n /// `x.significandWidth` is 2.\n /// - If `x` is Float.pi, `x.significand` is `1.10010010000111111011011` in\n /// binary, and `x.significandWidth` is 23.\n var significandWidth: Int { get }\n}\n\nextension FloatingPoint {\n\n @inlinable // FIXME(sil-serialize-all)\n public static var ulpOfOne: Self {\n return (1 as Self).ulp\n }\n\n @_transparent\n public func rounded(_ rule: FloatingPointRoundingRule) -> Self {\n var lhs = self\n lhs.round(rule)\n return lhs\n }\n\n @_transparent\n public func rounded() -> Self {\n return rounded(.toNearestOrAwayFromZero)\n }\n\n @_transparent\n public mutating func round() {\n round(.toNearestOrAwayFromZero)\n }\n\n @inlinable // FIXME(inline-always)\n public var nextDown: Self {\n @inline(__always)\n get {\n return -(-self).nextUp\n }\n }\n\n @inlinable // FIXME(inline-always)\n @inline(__always)\n public func truncatingRemainder(dividingBy other: Self) -> Self {\n var lhs = self\n lhs.formTruncatingRemainder(dividingBy: other)\n return lhs\n }\n\n @inlinable // FIXME(inline-always)\n @inline(__always)\n public func remainder(dividingBy other: Self) -> Self {\n var lhs = self\n lhs.formRemainder(dividingBy: other)\n return lhs\n }\n\n @_transparent\n public func squareRoot( ) -> Self {\n var lhs = self\n lhs.formSquareRoot( )\n return lhs\n }\n\n @_transparent\n public func addingProduct(_ lhs: Self, _ rhs: Self) -> Self {\n var addend = self\n addend.addProduct(lhs, rhs)\n return addend\n }\n\n @inlinable\n public static func minimum(_ x: Self, _ y: Self) -> Self {\n if x <= y || y.isNaN { return x }\n return y\n }\n\n @inlinable\n public static func maximum(_ x: Self, _ y: Self) -> Self {\n if x > y || y.isNaN { return x }\n return y\n }\n\n @inlinable\n public static func minimumMagnitude(_ x: Self, _ y: Self) -> Self {\n if x.magnitude <= y.magnitude || y.isNaN { return x }\n return y\n }\n\n @inlinable\n public static func maximumMagnitude(_ x: Self, _ y: Self) -> Self {\n if x.magnitude > y.magnitude || y.isNaN { return x }\n return y\n }\n\n @inlinable\n public var floatingPointClass: FloatingPointClassification {\n if isSignalingNaN { return .signalingNaN }\n if isNaN { return .quietNaN }\n if isInfinite { return sign == .minus ? .negativeInfinity : .positiveInfinity }\n if isNormal { return sign == .minus ? .negativeNormal : .positiveNormal }\n if isSubnormal { return sign == .minus ? .negativeSubnormal : .positiveSubnormal }\n return sign == .minus ? .negativeZero : .positiveZero\n }\n}\n\nextension BinaryFloatingPoint {\n\n @inlinable @inline(__always)\n public static var radix: Int { return 2 }\n\n @inlinable\n public init(signOf: Self, magnitudeOf: Self) {\n self.init(\n sign: signOf.sign,\n exponentBitPattern: magnitudeOf.exponentBitPattern,\n significandBitPattern: magnitudeOf.significandBitPattern\n )\n }\n\n public // @testable\n static func _convert<Source: BinaryFloatingPoint>(\n from source: Source\n ) -> (value: Self, exact: Bool) {\n guard _fastPath(!source.isZero) else {\n return (source.sign == .minus ? -0.0 : 0, true)\n }\n\n guard _fastPath(source.isFinite) else {\n if source.isInfinite {\n return (source.sign == .minus ? -.infinity : .infinity, true)\n }\n // IEEE 754 requires that any NaN payload be propagated, if possible.\n let payload_ =\n source.significandBitPattern &\n ~(Source.nan.significandBitPattern |\n Source.signalingNaN.significandBitPattern)\n let mask =\n Self.greatestFiniteMagnitude.significandBitPattern &\n ~(Self.nan.significandBitPattern |\n Self.signalingNaN.significandBitPattern)\n let payload = Self.RawSignificand(truncatingIfNeeded: payload_) & mask\n // Although .signalingNaN.exponentBitPattern == .nan.exponentBitPattern,\n // we do not *need* to rely on this relation, and therefore we do not.\n let value = source.isSignalingNaN\n ? Self(\n sign: source.sign,\n exponentBitPattern: Self.signalingNaN.exponentBitPattern,\n significandBitPattern: payload |\n Self.signalingNaN.significandBitPattern)\n : Self(\n sign: source.sign,\n exponentBitPattern: Self.nan.exponentBitPattern,\n significandBitPattern: payload | Self.nan.significandBitPattern)\n // We define exactness by equality after roundtripping; since NaN is never\n // equal to itself, it can never be converted exactly.\n return (value, false)\n }\n\n let exponent = source.exponent\n var exemplar = Self.leastNormalMagnitude\n let exponentBitPattern: Self.RawExponent\n let leadingBitIndex: Int\n let shift: Int\n let significandBitPattern: Self.RawSignificand\n\n if exponent < exemplar.exponent {\n // The floating-point result is either zero or subnormal.\n exemplar = Self.leastNonzeroMagnitude\n let minExponent = exemplar.exponent\n if exponent + 1 < minExponent {\n return (source.sign == .minus ? -0.0 : 0, false)\n }\n if _slowPath(exponent + 1 == minExponent) {\n // Although the most significant bit (MSB) of a subnormal source\n // significand is explicit, Swift BinaryFloatingPoint APIs actually\n // omit any explicit MSB from the count represented in\n // significandWidth. For instance:\n //\n // Double.leastNonzeroMagnitude.significandWidth == 0\n //\n // Therefore, we do not need to adjust our work here for a subnormal\n // source.\n return source.significandWidth == 0\n ? (source.sign == .minus ? -0.0 : 0, false)\n : (source.sign == .minus ? -exemplar : exemplar, false)\n }\n\n exponentBitPattern = 0 as Self.RawExponent\n leadingBitIndex = Int(Self.Exponent(exponent) - minExponent)\n shift =\n leadingBitIndex &-\n (source.significandWidth &+\n source.significandBitPattern.trailingZeroBitCount)\n let leadingBit = source.isNormal\n ? (1 as Self.RawSignificand) << leadingBitIndex\n : 0\n significandBitPattern = leadingBit | (shift >= 0\n ? Self.RawSignificand(source.significandBitPattern) << shift\n : Self.RawSignificand(source.significandBitPattern >> -shift))\n } else {\n // The floating-point result is either normal or infinite.\n exemplar = Self.greatestFiniteMagnitude\n if exponent > exemplar.exponent {\n return (source.sign == .minus ? -.infinity : .infinity, false)\n }\n\n exponentBitPattern = exponent < 0\n ? (1 as Self).exponentBitPattern - Self.RawExponent(-exponent)\n : (1 as Self).exponentBitPattern + Self.RawExponent(exponent)\n leadingBitIndex = exemplar.significandWidth\n shift =\n leadingBitIndex &-\n (source.significandWidth &+\n source.significandBitPattern.trailingZeroBitCount)\n let sourceLeadingBit = source.isSubnormal\n ? (1 as Source.RawSignificand) <<\n (source.significandWidth &+\n source.significandBitPattern.trailingZeroBitCount)\n : 0\n significandBitPattern = shift >= 0\n ? Self.RawSignificand(\n sourceLeadingBit ^ source.significandBitPattern) << shift\n : Self.RawSignificand(\n (sourceLeadingBit ^ source.significandBitPattern) >> -shift)\n }\n\n let value = Self(\n sign: source.sign,\n exponentBitPattern: exponentBitPattern,\n significandBitPattern: significandBitPattern)\n\n if source.significandWidth <= leadingBitIndex {\n return (value, true)\n }\n // We promise to round to the closest representation. Therefore, we must\n // take a look at the bits that we've just truncated.\n let ulp = (1 as Source.RawSignificand) << -shift\n let truncatedBits = source.significandBitPattern & (ulp - 1)\n if truncatedBits < ulp / 2 {\n return (value, false)\n }\n let rounded = source.sign == .minus ? value.nextDown : value.nextUp\n if _fastPath(truncatedBits > ulp / 2) {\n return (rounded, false)\n }\n // If two representable values are equally close, we return the value with\n // more trailing zeros in its significand bit pattern.\n return\n significandBitPattern.trailingZeroBitCount >\n rounded.significandBitPattern.trailingZeroBitCount\n ? (value, false)\n : (rounded, false)\n }\n\n /// Creates a new instance from the given value, rounded to the closest\n /// possible representation.\n ///\n /// If two representable values are equally close, the result is the value\n /// with more trailing zeros in its significand bit pattern.\n ///\n /// - Parameter value: A floating-point value to be converted.\n @inlinable\n public init<Source: BinaryFloatingPoint>(_ value: Source) {\n // If two IEEE 754 binary interchange formats share the same exponent bit\n // count and significand bit count, then they must share the same encoding\n // for finite and infinite values.\n switch (Source.exponentBitCount, Source.significandBitCount) {\n#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))\n case (5, 10):\n guard #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) //SwiftStdlib 5.3\n else {\n // Convert signaling NaN to quiet NaN by multiplying by 1.\n self = Self._convert(from: value).value * 1\n break\n }\n let value_ = value as? Float16 ?? Float16(\n sign: value.sign,\n exponentBitPattern:\n UInt(truncatingIfNeeded: value.exponentBitPattern),\n significandBitPattern:\n UInt16(truncatingIfNeeded: value.significandBitPattern))\n self = Self(Float(value_))\n#endif\n case (8, 23):\n let value_ = value as? Float ?? Float(\n sign: value.sign,\n exponentBitPattern:\n UInt(truncatingIfNeeded: value.exponentBitPattern),\n significandBitPattern:\n UInt32(truncatingIfNeeded: value.significandBitPattern))\n self = Self(value_)\n case (11, 52):\n let value_ = value as? Double ?? Double(\n sign: value.sign,\n exponentBitPattern:\n UInt(truncatingIfNeeded: value.exponentBitPattern),\n significandBitPattern:\n UInt64(truncatingIfNeeded: value.significandBitPattern))\n self = Self(value_)\n#if !(os(Windows) || os(Android) || ($Embedded && !os(Linux) && !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS)))) && (arch(i386) || arch(x86_64))\n case (15, 63):\n let value_ = value as? Float80 ?? Float80(\n sign: value.sign,\n exponentBitPattern:\n UInt(truncatingIfNeeded: value.exponentBitPattern),\n significandBitPattern:\n UInt64(truncatingIfNeeded: value.significandBitPattern))\n self = Self(value_)\n#endif\n default:\n // Convert signaling NaN to quiet NaN by multiplying by 1.\n self = Self._convert(from: value).value * 1\n }\n }\n\n /// Creates a new instance from the given value, if it can be represented\n /// exactly.\n ///\n /// If the given floating-point value cannot be represented exactly, the\n /// result is `nil`.\n ///\n /// - Parameter value: A floating-point value to be converted.\n @inlinable\n public init?<Source: BinaryFloatingPoint>(exactly value: Source) {\n // We define exactness by equality after roundtripping; since NaN is never\n // equal to itself, it can never be converted exactly.\n if value.isNaN { return nil }\n \n if (Source.exponentBitCount > Self.exponentBitCount\n || Source.significandBitCount > Self.significandBitCount)\n && value.isFinite && !value.isZero {\n let exponent = value.exponent\n if exponent < Self.leastNormalMagnitude.exponent {\n if exponent < Self.leastNonzeroMagnitude.exponent { return nil }\n if value.significandWidth >\n Int(Self.Exponent(exponent) - Self.leastNonzeroMagnitude.exponent) {\n return nil\n }\n } else {\n if exponent > Self.greatestFiniteMagnitude.exponent { return nil }\n if value.significandWidth >\n Self.greatestFiniteMagnitude.significandWidth {\n return nil\n }\n }\n }\n \n self = Self(value)\n }\n \n @inlinable\n public func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool {\n // Quick return when possible.\n if self < other { return true }\n if other > self { return false }\n // Self and other are either equal or unordered.\n // Every negative-signed value (even NaN) is less than every positive-\n // signed value, so if the signs do not match, we simply return the\n // sign bit of self.\n if sign != other.sign { return sign == .minus }\n // Sign bits match; look at exponents.\n if exponentBitPattern > other.exponentBitPattern { return sign == .minus }\n if exponentBitPattern < other.exponentBitPattern { return sign == .plus }\n // Signs and exponents match, look at significands.\n if significandBitPattern > other.significandBitPattern {\n return sign == .minus\n }\n if significandBitPattern < other.significandBitPattern {\n return sign == .plus\n }\n // Sign, exponent, and significand all match.\n return true\n }\n}\n\nextension BinaryFloatingPoint where Self.RawSignificand: FixedWidthInteger {\n \n public // @testable\n static func _convert<Source: BinaryInteger>(\n from source: Source\n ) -> (value: Self, exact: Bool) {\n // Useful constants:\n let exponentBias = (1 as Self).exponentBitPattern\n let significandMask = ((1 as RawSignificand) << Self.significandBitCount) &- 1\n // Zero is really extra simple, and saves us from trying to normalize a\n // value that cannot be normalized.\n if _fastPath(source == 0) { return (0, true) }\n // We now have a non-zero value; convert it to a strictly positive value\n // by taking the magnitude.\n let magnitude = source.magnitude\n var exponent = magnitude._binaryLogarithm()\n // If the exponent would be larger than the largest representable\n // exponent, the result is just an infinity of the appropriate sign.\n guard exponent <= Self.greatestFiniteMagnitude.exponent else {\n return (Source.isSigned && source < 0 ? -.infinity : .infinity, false)\n }\n // If exponent <= significandBitCount, we don't need to round it to\n // construct the significand; we just need to left-shift it into place;\n // the result is always exact as we've accounted for exponent-too-large\n // already and no rounding can occur.\n if exponent <= Self.significandBitCount {\n let shift = Self.significandBitCount &- exponent\n let significand = RawSignificand(magnitude) &<< shift\n let value = Self(\n sign: Source.isSigned && source < 0 ? .minus : .plus,\n exponentBitPattern: exponentBias + RawExponent(exponent),\n significandBitPattern: significand\n )\n return (value, true)\n }\n // exponent > significandBitCount, so we need to do a rounding right\n // shift, and adjust exponent if needed\n let shift = exponent &- Self.significandBitCount\n let halfway = (1 as Source.Magnitude) << (shift - 1)\n let mask = 2 * halfway - 1\n let fraction = magnitude & mask\n var significand = RawSignificand(truncatingIfNeeded: magnitude >> shift) & significandMask\n if fraction > halfway || (fraction == halfway && significand & 1 == 1) {\n var carry = false\n (significand, carry) = significand.addingReportingOverflow(1)\n if carry || significand > significandMask {\n exponent += 1\n guard exponent <= Self.greatestFiniteMagnitude.exponent else {\n return (Source.isSigned && source < 0 ? -.infinity : .infinity, false)\n }\n }\n }\n return (Self(\n sign: Source.isSigned && source < 0 ? .minus : .plus,\n exponentBitPattern: exponentBias + RawExponent(exponent),\n significandBitPattern: significand\n ), fraction == 0)\n }\n \n /// Creates a new value, rounded to the closest possible representation.\n ///\n /// If two representable values are equally close, the result is the value\n /// with more trailing zeros in its significand bit pattern.\n ///\n /// - Parameter value: The integer to convert to a floating-point value.\n @inlinable\n public init<Source: BinaryInteger>(_ value: Source) {\n self = Self._convert(from: value).value\n }\n \n /// Creates a new value, if the given integer can be represented exactly.\n ///\n /// If the given integer cannot be represented exactly, the result is `nil`.\n ///\n /// - Parameter value: The integer to convert to a floating-point value.\n @inlinable\n public init?<Source: BinaryInteger>(exactly value: Source) {\n let (value_, exact) = Self._convert(from: value)\n guard exact else { return nil }\n self = value_\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_FloatingPoint.swift | cpp_apple_swift_stdlib_public_core_FloatingPoint.swift | Swift | 79,708 | 0.75 | 0.068801 | 0.746544 | node-utils | 417 | 2025-04-14T00:46:32.652984 | BSD-3-Clause | false | fc12f9d3b33e0df7cd2554a6cd49b69b |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension BinaryFloatingPoint where Self.RawSignificand: FixedWidthInteger {\n\n /// Returns a random value within the specified range, using the given\n /// generator as a source for randomness.\n ///\n /// Use this method to generate a floating-point value within a specific\n /// range when you are using a custom random number generator. This example\n /// creates three new values in the range `10.0 ..< 20.0`.\n ///\n /// for _ in 1...3 {\n /// print(Double.random(in: 10.0 ..< 20.0, using: &myGenerator))\n /// }\n /// // Prints "18.1900709259179"\n /// // Prints "14.2286325689993"\n /// // Prints "13.1485686260762"\n ///\n /// The `random(in:using:)` static method chooses a random value from a\n /// continuous uniform distribution in `range`, and then converts that value\n /// to the nearest representable value in this type. Depending on the size\n /// and span of `range`, some concrete values may be represented more\n /// frequently than others.\n ///\n /// - Note: The algorithm used to create random values may change in a future\n /// version of Swift. If you're passing a generator that results in the\n /// same sequence of floating-point values each time you run your program,\n /// that sequence may change when your program is compiled using a\n /// different version of Swift.\n ///\n /// - Parameters:\n /// - range: The range in which to create a random value.\n /// `range` must be finite and non-empty.\n /// - generator: The random number generator to use when creating the\n /// new random value.\n /// - Returns: A random value within the bounds of `range`.\n @inlinable\n public static func random<T: RandomNumberGenerator>(\n in range: Range<Self>,\n using generator: inout T\n ) -> Self {\n _precondition(\n !range.isEmpty,\n "Can't get random value with an empty range"\n )\n let delta = range.upperBound - range.lowerBound\n // TODO: this still isn't quite right, because the computation of delta\n // can overflow (e.g. if .upperBound = .maximumFiniteMagnitude and\n // .lowerBound = -.upperBound); this should be re-written with an\n // algorithm that handles that case correctly, but this precondition\n // is an acceptable short-term fix.\n _precondition(\n delta.isFinite,\n "There is no uniform distribution on an infinite range"\n )\n let rand: Self.RawSignificand\n if Self.RawSignificand.bitWidth == Self.significandBitCount + 1 {\n rand = generator.next()\n } else {\n let significandCount = Self.significandBitCount + 1\n let maxSignificand: Self.RawSignificand = 1 << significandCount\n // Rather than use .next(upperBound:), which has to work with arbitrary\n // upper bounds, and therefore does extra work to avoid bias, we can take\n // a shortcut because we know that maxSignificand is a power of two.\n rand = generator.next() & (maxSignificand - 1)\n }\n let unitRandom = Self.init(rand) * (Self.ulpOfOne / 2)\n let randFloat = delta * unitRandom + range.lowerBound\n if randFloat == range.upperBound {\n return Self.random(in: range, using: &generator)\n }\n return randFloat\n }\n\n /// Returns a random value within the specified range.\n ///\n /// Use this method to generate a floating-point value within a specific\n /// range. This example creates three new values in the range\n /// `10.0 ..< 20.0`.\n ///\n /// for _ in 1...3 {\n /// print(Double.random(in: 10.0 ..< 20.0))\n /// }\n /// // Prints "18.1900709259179"\n /// // Prints "14.2286325689993"\n /// // Prints "13.1485686260762"\n ///\n /// The `random()` static method chooses a random value from a continuous\n /// uniform distribution in `range`, and then converts that value to the\n /// nearest representable value in this type. Depending on the size and span\n /// of `range`, some concrete values may be represented more frequently than\n /// others.\n ///\n /// This method is equivalent to calling `random(in:using:)`, passing in the\n /// system's default random generator.\n ///\n /// - Parameter range: The range in which to create a random value.\n /// `range` must be finite and non-empty.\n /// - Returns: A random value within the bounds of `range`.\n @inlinable\n public static func random(in range: Range<Self>) -> Self {\n var g = SystemRandomNumberGenerator()\n return Self.random(in: range, using: &g)\n }\n \n /// Returns a random value within the specified range, using the given\n /// generator as a source for randomness.\n ///\n /// Use this method to generate a floating-point value within a specific\n /// range when you are using a custom random number generator. This example\n /// creates three new values in the range `10.0 ... 20.0`.\n ///\n /// for _ in 1...3 {\n /// print(Double.random(in: 10.0 ... 20.0, using: &myGenerator))\n /// }\n /// // Prints "18.1900709259179"\n /// // Prints "14.2286325689993"\n /// // Prints "13.1485686260762"\n ///\n /// The `random(in:using:)` static method chooses a random value from a\n /// continuous uniform distribution in `range`, and then converts that value\n /// to the nearest representable value in this type. Depending on the size\n /// and span of `range`, some concrete values may be represented more\n /// frequently than others.\n ///\n /// - Note: The algorithm used to create random values may change in a future\n /// version of Swift. If you're passing a generator that results in the\n /// same sequence of floating-point values each time you run your program,\n /// that sequence may change when your program is compiled using a\n /// different version of Swift.\n ///\n /// - Parameters:\n /// - range: The range in which to create a random value. Must be finite.\n /// - generator: The random number generator to use when creating the\n /// new random value.\n /// - Returns: A random value within the bounds of `range`.\n @inlinable\n public static func random<T: RandomNumberGenerator>(\n in range: ClosedRange<Self>,\n using generator: inout T\n ) -> Self {\n _precondition(\n !range.isEmpty,\n "Can't get random value with an empty range"\n )\n let delta = range.upperBound - range.lowerBound\n // TODO: this still isn't quite right, because the computation of delta\n // can overflow (e.g. if .upperBound = .maximumFiniteMagnitude and\n // .lowerBound = -.upperBound); this should be re-written with an\n // algorithm that handles that case correctly, but this precondition\n // is an acceptable short-term fix.\n _precondition(\n delta.isFinite,\n "There is no uniform distribution on an infinite range"\n )\n let rand: Self.RawSignificand\n if Self.RawSignificand.bitWidth == Self.significandBitCount + 1 {\n rand = generator.next()\n let tmp: UInt8 = generator.next() & 1\n if rand == Self.RawSignificand.max && tmp == 1 {\n return range.upperBound\n }\n } else {\n let significandCount = Self.significandBitCount + 1\n let maxSignificand: Self.RawSignificand = 1 << significandCount\n rand = generator.next(upperBound: maxSignificand + 1)\n if rand == maxSignificand {\n return range.upperBound\n }\n }\n let unitRandom = Self.init(rand) * (Self.ulpOfOne / 2)\n let randFloat = delta * unitRandom + range.lowerBound\n return randFloat\n }\n \n /// Returns a random value within the specified range.\n ///\n /// Use this method to generate a floating-point value within a specific\n /// range. This example creates three new values in the range\n /// `10.0 ... 20.0`.\n ///\n /// for _ in 1...3 {\n /// print(Double.random(in: 10.0 ... 20.0))\n /// }\n /// // Prints "18.1900709259179"\n /// // Prints "14.2286325689993"\n /// // Prints "13.1485686260762"\n ///\n /// The `random()` static method chooses a random value from a continuous\n /// uniform distribution in `range`, and then converts that value to the\n /// nearest representable value in this type. Depending on the size and span\n /// of `range`, some concrete values may be represented more frequently than\n /// others.\n ///\n /// This method is equivalent to calling `random(in:using:)`, passing in the\n /// system's default random generator.\n ///\n /// - Parameter range: The range in which to create a random value. Must be finite.\n /// - Returns: A random value within the bounds of `range`.\n @inlinable\n public static func random(in range: ClosedRange<Self>) -> Self {\n var g = SystemRandomNumberGenerator()\n return Self.random(in: range, using: &g)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_FloatingPointRandom.swift | cpp_apple_swift_stdlib_public_core_FloatingPointRandom.swift | Swift | 9,129 | 0.8 | 0.069767 | 0.647619 | awesome-app | 983 | 2023-12-03T13:15:31.033652 | MIT | false | 45d6ce044498c1bb33c43afa2a814839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.