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) 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 hashed into a `Hasher` to produce an integer hash value.\n///\n/// You can use any type that conforms to the `Hashable` protocol in a set or as\n/// a dictionary key. Many types in the standard library conform to `Hashable`:\n/// Strings, integers, floating-point and Boolean values, and even sets are\n/// hashable by default. Some other types, such as optionals, arrays and ranges\n/// automatically become hashable when their type arguments implement the same.\n///\n/// Your own custom types can be hashable as well. When you define an\n/// enumeration without associated values, it gains `Hashable` conformance\n/// automatically, and you can add `Hashable` conformance to your other custom\n/// types by implementing the `hash(into:)` method. For structs whose stored\n/// properties are all `Hashable`, and for enum types that have all-`Hashable`\n/// associated values, the compiler is able to provide an implementation of\n/// `hash(into:)` automatically.\n///\n/// Hashing a value means feeding its essential components into a hash function,\n/// represented by the `Hasher` type. Essential components are those that\n/// contribute to the type's implementation of `Equatable`. Two instances that\n/// are equal must feed the same values to `Hasher` in `hash(into:)`, in the\n/// same order.\n///\n/// Conforming to the Hashable Protocol\n/// ===================================\n///\n/// To use your own custom type in a set or as the key type of a dictionary,\n/// add `Hashable` conformance to your type. The `Hashable` protocol inherits\n/// from the `Equatable` protocol, so you must also satisfy that protocol's\n/// requirements.\n///\n/// The compiler automatically synthesizes your custom type's `Hashable` and\n/// requirements when you declare `Hashable` conformance in the type's original\n/// declaration and your type meets these criteria:\n///\n/// - For a `struct`, all its stored properties must conform to `Hashable`.\n/// - For an `enum`, all its associated values must conform to `Hashable`. (An\n/// `enum` without associated values has `Hashable` conformance even without\n/// the declaration.)\n///\n/// To customize your type's `Hashable` conformance, to adopt `Hashable` in a\n/// type that doesn't meet the criteria listed above, or to extend an existing\n/// type to conform to `Hashable`, implement the `hash(into:)` method in your\n/// custom type.\n///\n/// In your `hash(into:)` implementation, call `combine(_:)` on the provided\n/// `Hasher` instance with the essential components of your type. To ensure\n/// that your type meets the semantic requirements of the `Hashable` and\n/// `Equatable` protocols, it's a good idea to also customize your type's\n/// `Equatable` conformance to match.\n///\n/// As an example, consider a `GridPoint` type that describes a location in a\n/// grid of buttons. Here's the initial declaration of the `GridPoint` type:\n///\n/// /// A point in an x-y coordinate system.\n/// struct GridPoint {\n/// var x: Int\n/// var y: Int\n/// }\n///\n/// You'd like to create a set of the grid points where a user has already\n/// tapped. Because the `GridPoint` type is not hashable yet, it can't be used\n/// in a set. To add `Hashable` conformance, provide an `==` operator function\n/// and implement the `hash(into:)` method.\n///\n/// extension GridPoint: Hashable {\n/// static func == (lhs: GridPoint, rhs: GridPoint) -> Bool {\n/// return lhs.x == rhs.x && lhs.y == rhs.y\n/// }\n///\n/// func hash(into hasher: inout Hasher) {\n/// hasher.combine(x)\n/// hasher.combine(y)\n/// }\n/// }\n///\n/// The `hash(into:)` method in this example feeds the grid point's `x` and `y`\n/// properties into the provided hasher. These properties are the same ones\n/// used to test for equality in the `==` operator function.\n///\n/// Now that `GridPoint` conforms to the `Hashable` protocol, you can create a\n/// set of previously tapped grid points.\n///\n/// var tappedPoints: Set = [GridPoint(x: 2, y: 3), GridPoint(x: 4, y: 1)]\n/// let nextTap = GridPoint(x: 0, y: 1)\n/// if tappedPoints.contains(nextTap) {\n/// print("Already tapped at (\(nextTap.x), \(nextTap.y)).")\n/// } else {\n/// tappedPoints.insert(nextTap)\n/// print("New tap detected at (\(nextTap.x), \(nextTap.y)).")\n/// }\n/// // Prints "New tap detected at (0, 1).")\npublic protocol Hashable: Equatable {\n /// The hash value.\n ///\n /// Hash values are not guaranteed to be equal across different executions of\n /// your program. Do not save hash values to use during a future execution.\n ///\n /// - Important: `hashValue` is deprecated as a `Hashable` requirement. To\n /// conform to `Hashable`, implement the `hash(into:)` requirement instead.\n /// The compiler provides an implementation for `hashValue` for you.\n var hashValue: Int { get }\n\n /// Hashes the essential components of this value by feeding them into the\n /// given hasher.\n ///\n /// Implement this method to conform to the `Hashable` protocol. The\n /// components used for hashing must be the same as the components compared\n /// in your type's `==` operator implementation. Call `hasher.combine(_:)`\n /// with each of these components.\n ///\n /// - Important: In your implementation of `hash(into:)`,\n /// don't call `finalize()` on the `hasher` instance provided,\n /// or replace it with a different instance.\n /// Doing so may become a compile-time error in the future.\n ///\n /// - Parameter hasher: The hasher to use when combining the components\n /// of this instance.\n func hash(into hasher: inout Hasher)\n\n // Raw top-level hashing interface. Some standard library types (mostly\n // primitives) specialize this to eliminate small resiliency overheads. (This\n // only matters for tiny keys.)\n func _rawHashValue(seed: Int) -> Int\n}\n\nextension Hashable {\n @inlinable\n @inline(__always)\n public func _rawHashValue(seed: Int) -> Int {\n var hasher = Hasher(_seed: seed)\n hasher.combine(self)\n return hasher._finalize()\n }\n}\n\n// Called by synthesized `hashValue` implementations.\n@inlinable\n@inline(__always)\npublic func _hashValue<H: Hashable>(for value: H) -> Int {\n return value._rawHashValue(seed: 0)\n}\n\n// Called by the SwiftValue implementation.\n@_silgen_name("_swift_stdlib_Hashable_isEqual_indirect")\ninternal func Hashable_isEqual_indirect<T: Hashable>(\n _ lhs: UnsafePointer<T>,\n _ rhs: UnsafePointer<T>\n) -> Bool {\n return unsafe lhs.pointee == rhs.pointee\n}\n\n// Called by the SwiftValue implementation.\n@_silgen_name("_swift_stdlib_Hashable_hashValue_indirect")\ninternal func Hashable_hashValue_indirect<T: Hashable>(\n _ value: UnsafePointer<T>\n) -> Int {\n return unsafe value.pointee.hashValue\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Hashable.swift
cpp_apple_swift_stdlib_public_core_Hashable.swift
Swift
7,284
0.95
0.076471
0.803681
python-kit
499
2023-11-27T15:02:56.197308
GPL-3.0
false
678989438f289c6a5de2818609eee2fc
//===----------------------------------------------------------------------===//\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// Defines the Hasher struct, representing Swift's standard hash function.\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n@inline(__always)\ninternal func _loadPartialUnalignedUInt64LE(\n _ p: UnsafeRawPointer,\n byteCount: Int\n) -> UInt64 {\n var result: UInt64 = 0\n switch byteCount {\n case 7:\n unsafe result |= UInt64(p.load(fromByteOffset: 6, as: UInt8.self)) &<< 48\n fallthrough\n case 6:\n unsafe result |= UInt64(p.load(fromByteOffset: 5, as: UInt8.self)) &<< 40\n fallthrough\n case 5:\n unsafe result |= UInt64(p.load(fromByteOffset: 4, as: UInt8.self)) &<< 32\n fallthrough\n case 4:\n unsafe result |= UInt64(p.load(fromByteOffset: 3, as: UInt8.self)) &<< 24\n fallthrough\n case 3:\n unsafe result |= UInt64(p.load(fromByteOffset: 2, as: UInt8.self)) &<< 16\n fallthrough\n case 2:\n unsafe result |= UInt64(p.load(fromByteOffset: 1, as: UInt8.self)) &<< 8\n fallthrough\n case 1:\n unsafe result |= UInt64(p.load(fromByteOffset: 0, as: UInt8.self))\n fallthrough\n case 0:\n return result\n default:\n _internalInvariantFailure()\n }\n}\n\nextension Hasher {\n /// This is a buffer for segmenting arbitrary data into 8-byte chunks. Buffer\n /// storage is represented by a single 64-bit value in the format used by the\n /// finalization step of SipHash. (The least significant 56 bits hold the\n /// trailing bytes, while the most significant 8 bits hold the count of bytes\n /// appended so far, modulo 256. The count of bytes currently stored in the\n /// buffer is in the lower three bits of the byte count.)\n // FIXME: Remove @usableFromInline and @frozen once Hasher is resilient.\n // rdar://problem/38549901\n @usableFromInline @frozen\n internal struct _TailBuffer {\n // msb lsb\n // +---------+-------+-------+-------+-------+-------+-------+-------+\n // |byteCount| tail (<= 56 bits) |\n // +---------+-------+-------+-------+-------+-------+-------+-------+\n internal var value: UInt64\n\n @inline(__always)\n internal init() {\n self.value = 0\n }\n\n @inline(__always)\n internal init(tail: UInt64, byteCount: UInt64) {\n // byteCount can be any value, but we only keep the lower 8 bits. (The\n // lower three bits specify the count of bytes stored in this buffer.)\n // FIXME: This should be a single expression, but it causes exponential\n // behavior in the expression type checker <rdar://problem/42672946>.\n let shiftedByteCount: UInt64 = ((byteCount & 7) << 3)\n let mask: UInt64 = (1 << shiftedByteCount - 1)\n _internalInvariant(tail & ~mask == 0)\n self.value = (byteCount &<< 56 | tail)\n }\n\n @inline(__always)\n internal init(tail: UInt64, byteCount: Int) {\n self.init(tail: tail, byteCount: UInt64(truncatingIfNeeded: byteCount))\n }\n\n internal var tail: UInt64 {\n @inline(__always)\n get { return value & ~(0xFF &<< 56) }\n }\n\n internal var byteCount: UInt64 {\n @inline(__always)\n get { return value &>> 56 }\n }\n\n @inline(__always)\n internal mutating func append(_ bytes: UInt64) -> UInt64 {\n let c = byteCount & 7\n if c == 0 {\n value = value &+ (8 &<< 56)\n return bytes\n }\n let shift = c &<< 3\n let chunk = tail | (bytes &<< shift)\n value = (((value &>> 56) &+ 8) &<< 56) | (bytes &>> (64 - shift))\n return chunk\n }\n\n @inline(__always)\n internal\n mutating func append(_ bytes: UInt64, count: UInt64) -> UInt64? {\n _internalInvariant(count >= 0 && count < 8)\n _internalInvariant(bytes & ~((1 &<< (count &<< 3)) &- 1) == 0)\n let c = byteCount & 7\n let shift = c &<< 3\n if c + count < 8 {\n value = (value | (bytes &<< shift)) &+ (count &<< 56)\n return nil\n }\n let chunk = tail | (bytes &<< shift)\n value = ((value &>> 56) &+ count) &<< 56\n if c + count > 8 {\n value |= bytes &>> (64 - shift)\n }\n return chunk\n }\n }\n}\n\nextension Hasher {\n // FIXME: Remove @usableFromInline and @frozen once Hasher is resilient.\n // rdar://problem/38549901\n @usableFromInline @frozen\n internal struct _Core {\n private var _buffer: _TailBuffer\n private var _state: Hasher._State\n\n @inline(__always)\n internal init(state: Hasher._State) {\n self._buffer = _TailBuffer()\n self._state = state\n }\n\n @inline(__always)\n internal init() {\n self.init(state: _State())\n }\n\n @inline(__always)\n internal init(seed: Int) {\n self.init(state: _State(seed: seed))\n }\n\n @inline(__always)\n internal mutating func combine(_ value: UInt) {\n#if _pointerBitWidth(_64)\n combine(UInt64(truncatingIfNeeded: value))\n#elseif _pointerBitWidth(_32)\n combine(UInt32(truncatingIfNeeded: value))\n#elseif _pointerBitWidth(_16)\n combine(UInt16(truncatingIfNeeded: value))\n#else\n#error("Unknown platform")\n#endif\n }\n\n @inline(__always)\n internal mutating func combine(_ value: UInt64) {\n _state.compress(_buffer.append(value))\n }\n\n @inline(__always)\n internal mutating func combine(_ value: UInt32) {\n let value = UInt64(truncatingIfNeeded: value)\n if let chunk = _buffer.append(value, count: 4) {\n _state.compress(chunk)\n }\n }\n\n @inline(__always)\n internal mutating func combine(_ value: UInt16) {\n let value = UInt64(truncatingIfNeeded: value)\n if let chunk = _buffer.append(value, count: 2) {\n _state.compress(chunk)\n }\n }\n\n @inline(__always)\n internal mutating func combine(_ value: UInt8) {\n let value = UInt64(truncatingIfNeeded: value)\n if let chunk = _buffer.append(value, count: 1) {\n _state.compress(chunk)\n }\n }\n\n @inline(__always)\n internal mutating func combine(bytes: UInt64, count: Int) {\n _internalInvariant(count >= 0 && count < 8)\n let count = UInt64(truncatingIfNeeded: count)\n if let chunk = _buffer.append(bytes, count: count) {\n _state.compress(chunk)\n }\n }\n\n @inline(__always)\n internal mutating func combine(bytes: UnsafeRawBufferPointer) {\n var remaining = bytes.count\n guard remaining > 0 else { return }\n var data = bytes.baseAddress!\n\n // Load first unaligned partial word of data\n do {\n let start = UInt(bitPattern: data)\n let end = _roundUp(start, toAlignment: MemoryLayout<UInt64>.alignment)\n let c = min(remaining, Int(end - start))\n if c > 0 {\n let chunk = unsafe _loadPartialUnalignedUInt64LE(data, byteCount: c)\n combine(bytes: chunk, count: c)\n unsafe data += c\n remaining -= c\n }\n }\n _internalInvariant(\n remaining == 0 ||\n Int(bitPattern: data) & (MemoryLayout<UInt64>.alignment - 1) == 0)\n\n // Load as many aligned words as there are in the input buffer\n while remaining >= MemoryLayout<UInt64>.size {\n unsafe combine(UInt64(littleEndian: data.load(as: UInt64.self)))\n unsafe data += MemoryLayout<UInt64>.size\n remaining -= MemoryLayout<UInt64>.size\n }\n\n // Load last partial word of data\n _internalInvariant(remaining >= 0 && remaining < 8)\n if remaining > 0 {\n let chunk = unsafe _loadPartialUnalignedUInt64LE(data, byteCount: remaining)\n combine(bytes: chunk, count: remaining)\n }\n }\n\n @inline(__always)\n internal mutating func finalize() -> UInt64 {\n return _state.finalize(tailAndByteCount: _buffer.value)\n }\n }\n}\n\n#if $Embedded\n@usableFromInline\nvar _swift_stdlib_Hashing_parameters: _SwiftHashingParameters = {\n var seed0: UInt64 = 0, seed1: UInt64 = 0\n unsafe swift_stdlib_random(&seed0, MemoryLayout<UInt64>.size)\n unsafe swift_stdlib_random(&seed1, MemoryLayout<UInt64>.size)\n return .init(seed0: seed0, seed1: seed1, deterministic: false)\n}()\n#endif\n\n/// The universal hash function used by `Set` and `Dictionary`.\n///\n/// `Hasher` can be used to map an arbitrary sequence of bytes to an integer\n/// hash value. You can feed data to the hasher using a series of calls to\n/// mutating `combine` methods. When you've finished feeding the hasher, the\n/// hash value can be retrieved by calling `finalize()`:\n///\n/// var hasher = Hasher()\n/// hasher.combine(23)\n/// hasher.combine("Hello")\n/// let hashValue = hasher.finalize()\n///\n/// Within the execution of a Swift program, `Hasher` guarantees that finalizing\n/// it will always produce the same hash value as long as it is fed the exact\n/// same sequence of bytes. However, the underlying hash algorithm is designed\n/// to exhibit avalanche effects: slight changes to the seed or the input byte\n/// sequence will typically produce drastic changes in the generated hash value.\n///\n/// - Note: Do not save or otherwise reuse hash values across executions of your\n/// program. `Hasher` is usually randomly seeded, which means it will return\n/// different values on every new execution of your program. The hash\n/// algorithm implemented by `Hasher` may itself change between any two\n/// versions of the standard library.\n@frozen // FIXME: Should be resilient (rdar://problem/38549901)\npublic struct Hasher {\n internal var _core: _Core\n\n /// Creates a new hasher.\n ///\n /// The hasher uses a per-execution seed value that is set during process\n /// startup, usually from a high-quality random source.\n @_effects(releasenone)\n public init() {\n self._core = _Core()\n }\n\n /// Initialize a new hasher using the specified seed value.\n /// The provided seed is mixed in with the global execution seed.\n @usableFromInline\n @_effects(releasenone)\n internal init(_seed: Int) {\n self._core = _Core(seed: _seed)\n }\n\n /// Initialize a new hasher using the specified seed value.\n @usableFromInline // @testable\n @_effects(releasenone)\n internal init(_rawSeed: (UInt64, UInt64)) {\n self._core = _Core(state: _State(rawSeed: _rawSeed))\n }\n\n /// Indicates whether we're running in an environment where hashing needs to\n /// be deterministic. If this is true, the hash seed is not random, and hash\n /// tables do not apply per-instance perturbation that is not repeatable.\n /// This is not recommended for production use, but it is useful in certain\n /// test environments where randomization may lead to unwanted nondeterminism\n /// of test results.\n @inlinable\n internal static var _isDeterministic: Bool {\n @inline(__always)\n get {\n return _swift_stdlib_Hashing_parameters.deterministic\n }\n }\n\n /// The 128-bit hash seed used to initialize the hasher state. Initialized\n /// once during process startup.\n @inlinable // @testable\n internal static var _executionSeed: (UInt64, UInt64) {\n @inline(__always)\n get {\n // The seed itself is defined in C++ code so that it is initialized during\n // static construction. Almost every Swift program uses hash tables, so\n // initializing the seed during the startup seems to be the right\n // trade-off.\n return (\n _swift_stdlib_Hashing_parameters.seed0,\n _swift_stdlib_Hashing_parameters.seed1)\n }\n }\n\n /// Adds the given value to this hasher, mixing its essential parts into the\n /// hasher state.\n ///\n /// - Parameter value: A value to add to the hasher.\n @inlinable\n @inline(__always)\n public mutating func combine<H: Hashable>(_ value: H) {\n value.hash(into: &self)\n }\n\n @_effects(releasenone)\n @usableFromInline\n internal mutating func _combine(_ value: UInt) {\n _core.combine(value)\n }\n\n @_effects(releasenone)\n @usableFromInline\n internal mutating func _combine(_ value: UInt64) {\n _core.combine(value)\n }\n\n @_effects(releasenone)\n @usableFromInline\n internal mutating func _combine(_ value: UInt32) {\n _core.combine(value)\n }\n\n @_effects(releasenone)\n @usableFromInline\n internal mutating func _combine(_ value: UInt16) {\n _core.combine(value)\n }\n\n @_effects(releasenone)\n @usableFromInline\n internal mutating func _combine(_ value: UInt8) {\n _core.combine(value)\n }\n\n @_effects(releasenone)\n @usableFromInline\n internal mutating func _combine(bytes value: UInt64, count: Int) {\n _core.combine(bytes: value, count: count)\n }\n\n /// Adds the contents of the given buffer to this hasher, mixing it into the\n /// hasher state.\n ///\n /// - Parameter bytes: A raw memory buffer.\n @_effects(releasenone)\n public mutating func combine(bytes: UnsafeRawBufferPointer) {\n unsafe _core.combine(bytes: bytes)\n }\n\n /// Finalize the hasher state and return the hash value.\n /// Finalizing invalidates the hasher; additional bits cannot be combined\n /// into it, and it cannot be finalized again.\n @_effects(releasenone)\n @usableFromInline\n internal mutating func _finalize() -> Int {\n return Int(truncatingIfNeeded: _core.finalize())\n }\n\n /// Finalizes the hasher state and returns the hash value.\n ///\n /// Finalizing consumes the hasher: it is illegal to finalize a hasher you\n /// don't own, or to perform operations on a finalized hasher. (These may\n /// become compile-time errors in the future.)\n ///\n /// Hash values are not guaranteed to be equal across different executions of\n /// your program. Do not save hash values to use during a future execution.\n ///\n /// - Returns: The hash value calculated by the hasher.\n @_effects(releasenone)\n public __consuming func finalize() -> Int {\n var core = _core\n return Int(truncatingIfNeeded: core.finalize())\n }\n\n @_effects(readnone)\n @usableFromInline\n internal static func _hash(seed: Int, _ value: UInt64) -> Int {\n var state = _State(seed: seed)\n state.compress(value)\n let tbc = _TailBuffer(tail: 0, byteCount: 8)\n return Int(truncatingIfNeeded: state.finalize(tailAndByteCount: tbc.value))\n }\n\n @_effects(readnone)\n @usableFromInline\n internal static func _hash(seed: Int, _ value: UInt) -> Int {\n var state = _State(seed: seed)\n#if _pointerBitWidth(_64)\n _internalInvariant(UInt.bitWidth == UInt64.bitWidth)\n state.compress(UInt64(truncatingIfNeeded: value))\n let tbc = _TailBuffer(tail: 0, byteCount: 8)\n#elseif _pointerBitWidth(_32) || _pointerBitWidth(_16)\n _internalInvariant(UInt.bitWidth < UInt64.bitWidth)\n let tbc = _TailBuffer(\n tail: UInt64(truncatingIfNeeded: value),\n byteCount: UInt.bitWidth &>> 3)\n#else\n#error("Unknown platform")\n#endif\n return Int(truncatingIfNeeded: state.finalize(tailAndByteCount: tbc.value))\n }\n\n @_effects(readnone)\n @usableFromInline\n internal static func _hash(\n seed: Int,\n bytes value: UInt64,\n count: Int) -> Int {\n _internalInvariant(count >= 0 && count < 8)\n var state = _State(seed: seed)\n let tbc = _TailBuffer(tail: value, byteCount: count)\n return Int(truncatingIfNeeded: state.finalize(tailAndByteCount: tbc.value))\n }\n\n @_effects(readnone)\n @usableFromInline\n internal static func _hash(\n seed: Int,\n bytes: UnsafeRawBufferPointer) -> Int {\n var core = _Core(seed: seed)\n unsafe core.combine(bytes: bytes)\n return Int(truncatingIfNeeded: core.finalize())\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Hasher.swift
cpp_apple_swift_stdlib_public_core_Hasher.swift
Swift
15,686
0.95
0.044118
0.260465
vue-tools
539
2024-03-20T08:58:40.480501
BSD-3-Clause
false
1407ece7732ee567ebc0c5f6c56a8bbc
//===----------------------------------------------------------------------===//\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// This file implements helpers for hashing collections.\n//\n\nimport SwiftShims\n\n/// The inverse of the default hash table load factor. Factored out so that it\n/// can be used in multiple places in the implementation and stay consistent.\n/// Should not be used outside `Dictionary` implementation.\n@usableFromInline @_transparent\ninternal var _hashContainerDefaultMaxLoadFactorInverse: Double {\n return 1.0 / 0.75\n}\n\n#if _runtime(_ObjC)\n/// Call `[lhs isEqual: rhs]`.\n///\n/// This function is part of the runtime because `Bool` type is bridged to\n/// `ObjCBool`, which is in Foundation overlay.\n@_silgen_name("swift_stdlib_NSObject_isEqual")\ninternal func _stdlib_NSObject_isEqual(_ lhs: AnyObject, _ rhs: AnyObject) -> Bool\n#endif\n\n\n/// A temporary view of an array of AnyObject as an array of Unmanaged<AnyObject>\n/// for fast iteration and transformation of the elements.\n///\n/// Accesses the underlying raw memory as Unmanaged<AnyObject> using untyped\n/// memory accesses. The memory remains bound to managed AnyObjects.\n@unsafe\ninternal struct _UnmanagedAnyObjectArray {\n /// Underlying pointer.\n internal var value: UnsafeMutableRawPointer\n\n internal init(_ up: UnsafeMutablePointer<AnyObject>) {\n unsafe self.value = UnsafeMutableRawPointer(up)\n }\n\n internal init?(_ up: UnsafeMutablePointer<AnyObject>?) {\n guard let unwrapped = unsafe up else { return nil }\n unsafe self.init(unwrapped)\n }\n\n internal subscript(i: Int) -> AnyObject {\n get {\n let unmanaged = unsafe value.load(\n fromByteOffset: i * MemoryLayout<AnyObject>.stride,\n as: Unmanaged<AnyObject>.self)\n return unsafe unmanaged.takeUnretainedValue()\n }\n nonmutating set(newValue) {\n let unmanaged = unsafe Unmanaged.passUnretained(newValue)\n unsafe value.storeBytes(of: unmanaged,\n toByteOffset: i * MemoryLayout<AnyObject>.stride,\n as: Unmanaged<AnyObject>.self)\n }\n }\n}\n\n#if _runtime(_ObjC)\n/// An NSEnumerator implementation returning zero elements. This is useful when\n/// a concrete element type is not recoverable from the empty singleton.\n// NOTE: older runtimes called this class _SwiftEmptyNSEnumerator. The two\n// must coexist without conflicting ObjC class names, so it was\n// renamed. The old name must not be used in the new runtime.\nfinal internal class __SwiftEmptyNSEnumerator\n : __SwiftNativeNSEnumerator, _NSEnumerator {\n internal override required init() {\n super.init()\n _internalInvariant(_orphanedFoundationSubclassesReparented)\n }\n\n @objc\n internal func nextObject() -> AnyObject? {\n return nil\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 // Even though we never do anything in here, we need to update the\n // state so that callers know we actually ran.\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 return 0\n }\n}\n#endif\n\n#if _runtime(_ObjC)\n/// This is a minimal class holding a single tail-allocated flat buffer,\n/// representing hash table storage for AnyObject elements. This is used to\n/// store bridged elements in deferred bridging scenarios.\n///\n/// Using a dedicated class for this rather than a _BridgingBuffer makes it easy\n/// to recognize these in heap dumps etc.\n// NOTE: older runtimes called this class _BridgingHashBuffer.\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.\n@unsafe\ninternal final class __BridgingHashBuffer\n : ManagedBuffer<__BridgingHashBuffer.Header, AnyObject> {\n @unsafe\n struct Header {\n internal var owner: AnyObject\n internal var hashTable: _HashTable\n\n init(owner: AnyObject, hashTable: _HashTable) {\n unsafe self.owner = owner\n unsafe self.hashTable = unsafe hashTable\n }\n }\n\n internal static func allocate(\n owner: AnyObject,\n hashTable: _HashTable\n ) -> __BridgingHashBuffer {\n let buffer = unsafe self.create(minimumCapacity: hashTable.bucketCount) { _ in\n unsafe Header(owner: owner, hashTable: hashTable)\n }\n return unsafe unsafeDowncast(buffer, to: __BridgingHashBuffer.self)\n }\n\n deinit {\n for unsafe bucket in unsafe header.hashTable {\n unsafe (firstElementAddress + bucket.offset).deinitialize(count: 1)\n }\n unsafe _fixLifetime(self)\n }\n\n internal subscript(bucket: _HashTable.Bucket) -> AnyObject {\n @inline(__always) get {\n unsafe _internalInvariant(header.hashTable.isOccupied(bucket))\n defer { unsafe _fixLifetime(self) }\n return unsafe firstElementAddress[bucket.offset]\n }\n }\n\n @inline(__always)\n internal func initialize(at bucket: _HashTable.Bucket, to object: AnyObject) {\n unsafe _internalInvariant(header.hashTable.isOccupied(bucket))\n unsafe (firstElementAddress + bucket.offset).initialize(to: object)\n unsafe _fixLifetime(self)\n }\n}\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Hashing.swift
cpp_apple_swift_stdlib_public_core_Hashing.swift
Swift
5,781
0.95
0.120482
0.331081
node-utils
963
2023-10-07T04:55:44.251821
GPL-3.0
false
c34a0575804ad4de3eb6baf7cd78a8b0
//===----------------------------------------------------------------------===//\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@usableFromInline\ninternal protocol _HashTableDelegate {\n func hashValue(at bucket: _HashTable.Bucket) -> Int\n func moveEntry(from source: _HashTable.Bucket, to target: _HashTable.Bucket)\n}\n\n@usableFromInline\n@frozen\n@unsafe\ninternal struct _HashTable {\n @usableFromInline\n internal typealias Word = _UnsafeBitset.Word\n\n @usableFromInline\n internal var words: UnsafeMutablePointer<Word>\n\n @usableFromInline\n internal let bucketMask: Int\n\n @inlinable\n @inline(__always)\n internal init(words: UnsafeMutablePointer<Word>, bucketCount: Int) {\n _internalInvariant(bucketCount > 0 && bucketCount & (bucketCount - 1) == 0,\n "bucketCount must be a power of two")\n unsafe self.words = unsafe words\n // The bucket count is a power of two, so subtracting 1 will never overflow\n // and get us a nice mask.\n unsafe self.bucketMask = bucketCount &- 1\n }\n\n @inlinable\n internal var bucketCount: Int {\n @inline(__always) get {\n return unsafe _assumeNonNegative(bucketMask &+ 1)\n }\n }\n\n @inlinable\n internal var wordCount: Int {\n @inline(__always) get {\n return unsafe _UnsafeBitset.wordCount(forCapacity: bucketCount)\n }\n }\n\n /// Return a bitset representation of the occupied buckets in this table.\n ///\n /// Note that if we have only a single partial word in the hash table's\n /// bitset, then its out-of-bounds bits are guaranteed to be all set. These\n /// filler bits are there to speed up finding holes -- they don't correspond\n /// to occupied buckets in the table.\n @_alwaysEmitIntoClient\n internal var bitset: _UnsafeBitset {\n unsafe _UnsafeBitset(words: words, wordCount: wordCount)\n }\n}\n\n@available(*, unavailable)\nextension _HashTable: Sendable {}\n\nextension _HashTable {\n /// The inverse of the maximum hash table load factor.\n private static var maxLoadFactor: Double {\n @inline(__always) get { return 3 / 4 }\n }\n\n internal static func capacity(forScale scale: Int8) -> Int {\n let bucketCount = (1 as Int) &<< scale\n return unsafe Int(Double(bucketCount) * maxLoadFactor)\n }\n\n internal static func scale(forCapacity capacity: Int) -> Int8 {\n let capacity = Swift.max(capacity, 1)\n // Calculate the minimum number of entries we need to allocate to satisfy\n // the maximum load factor. `capacity + 1` below ensures that we always\n // leave at least one hole.\n let minimumEntries = unsafe Swift.max(\n Int((Double(capacity) / maxLoadFactor).rounded(.up)),\n capacity + 1)\n // The actual number of entries we need to allocate is the lowest power of\n // two greater than or equal to the minimum entry count. Calculate its\n // exponent.\n let exponent = (Swift.max(minimumEntries, 2) - 1)._binaryLogarithm() + 1\n _internalInvariant(exponent >= 0 && exponent < Int.bitWidth)\n // The scale is the exponent corresponding to the bucket count.\n let scale = Int8(truncatingIfNeeded: exponent)\n unsafe _internalInvariant(self.capacity(forScale: scale) >= capacity)\n return scale\n }\n\n // The initial age to use for native copies of a Cocoa NSSet/NSDictionary.\n internal static func age(for cocoa: AnyObject) -> Int32 {\n let hash = ObjectIdentifier(cocoa).hashValue\n return Int32(truncatingIfNeeded: hash)\n }\n\n internal static func hashSeed(\n for object: Builtin.NativeObject,\n scale: Int8\n ) -> Int {\n // We generate a new hash seed whenever a new hash table is allocated and\n // whenever an existing table is resized, so that we avoid certain copy\n // operations becoming quadratic. For background details, see\n // https://github.com/apple/swift/issues/45856.\n //\n // Note that we do reuse the existing seed when making copy-on-write copies\n // so that we avoid breaking value semantics.\n if Hasher._isDeterministic {\n // When we're using deterministic hashing, the scale value as the seed is\n // still allowed, and it covers most cases. (Unfortunately some operations\n // that merge two similar-sized hash tables will still be quadratic.)\n return Int(scale)\n }\n // Use the object address as the hash seed. This is cheaper than\n // SystemRandomNumberGenerator, while it has the same practical effect.\n // Addresses aren't entirely random, but that's not the goal here -- the\n // 128-bit execution seed takes care of randomization. We only need to\n // guarantee that no two tables with the same seed can coexist at the same\n // time (apart from copy-on-write derivatives of the same table).\n return unsafe unsafeBitCast(object, to: Int.self)\n }\n}\n\nextension _HashTable {\n @frozen\n @usableFromInline\n internal struct Bucket {\n @usableFromInline\n internal var offset: Int\n\n @inlinable\n @inline(__always)\n internal init(offset: Int) {\n self.offset = offset\n }\n\n @inlinable\n @inline(__always)\n internal init(word: Int, bit: Int) {\n unsafe self.offset = unsafe _UnsafeBitset.join(word: word, bit: bit)\n }\n\n @inlinable\n internal var word: Int {\n @inline(__always) get {\n return unsafe _UnsafeBitset.word(for: offset)\n }\n }\n\n @inlinable\n internal var bit: Int {\n @inline(__always) get {\n return unsafe _UnsafeBitset.bit(for: offset)\n }\n }\n }\n}\n\nextension _HashTable.Bucket: Equatable {\n @inlinable\n @inline(__always)\n internal\n static func == (lhs: _HashTable.Bucket, rhs: _HashTable.Bucket) -> Bool {\n return lhs.offset == rhs.offset\n }\n}\n\nextension _HashTable.Bucket: Comparable {\n @inlinable\n @inline(__always)\n internal\n static func < (lhs: _HashTable.Bucket, rhs: _HashTable.Bucket) -> Bool {\n return lhs.offset < rhs.offset\n }\n}\n\nextension _HashTable {\n @unsafe\n @usableFromInline\n @frozen\n internal struct Index {\n @usableFromInline\n let bucket: Bucket\n\n @usableFromInline\n let age: Int32\n\n @inlinable\n @inline(__always)\n internal init(bucket: Bucket, age: Int32) {\n unsafe self.bucket = bucket\n unsafe self.age = age\n }\n }\n}\n\nextension _HashTable.Index: Equatable {\n @inlinable\n @inline(__always)\n internal static func ==(\n lhs: _HashTable.Index,\n rhs: _HashTable.Index\n ) -> Bool {\n unsafe _precondition(lhs.age == rhs.age,\n "Can't compare indices belonging to different collections")\n return unsafe lhs.bucket == rhs.bucket\n }\n}\n\nextension _HashTable.Index: Comparable {\n @inlinable\n @inline(__always)\n internal static func <(\n lhs: _HashTable.Index,\n rhs: _HashTable.Index\n ) -> Bool {\n unsafe _precondition(lhs.age == rhs.age,\n "Can't compare indices belonging to different collections")\n return unsafe lhs.bucket < rhs.bucket\n }\n}\n\nextension _HashTable: @unsafe Sequence {\n @unsafe\n @usableFromInline\n @frozen\n internal struct Iterator: @unsafe IteratorProtocol {\n @usableFromInline\n let hashTable: _HashTable\n @usableFromInline\n var wordIndex: Int\n @usableFromInline\n var word: Word\n\n @inlinable\n @inline(__always)\n init(_ hashTable: _HashTable) {\n unsafe self.hashTable = unsafe hashTable\n unsafe self.wordIndex = 0\n unsafe self.word = unsafe hashTable.words[0]\n if unsafe hashTable.bucketCount < Word.capacity {\n unsafe self.word = unsafe self.word.intersecting(elementsBelow: hashTable.bucketCount)\n }\n }\n\n @inlinable\n @inline(__always)\n internal mutating func next() -> Bucket? {\n if let bit = unsafe word.next() {\n return unsafe Bucket(word: wordIndex, bit: bit)\n }\n while unsafe wordIndex + 1 < hashTable.wordCount {\n unsafe wordIndex += 1\n unsafe word = unsafe hashTable.words[wordIndex]\n if let bit = unsafe word.next() {\n return unsafe Bucket(word: wordIndex, bit: bit)\n }\n }\n return nil\n }\n }\n\n @inlinable\n @inline(__always)\n internal func makeIterator() -> Iterator {\n return unsafe Iterator(self)\n }\n}\n\n@available(*, unavailable)\nextension _HashTable.Iterator: Sendable {}\n\nextension _HashTable {\n @safe\n @inlinable\n @inline(__always)\n internal func isValid(_ bucket: Bucket) -> Bool {\n return unsafe bucket.offset >= 0 && bucket.offset < bucketCount\n }\n\n @inlinable\n @inline(__always)\n internal func _isOccupied(_ bucket: Bucket) -> Bool {\n _internalInvariant(isValid(bucket))\n return unsafe words[bucket.word].uncheckedContains(bucket.bit)\n }\n\n @inlinable\n @inline(__always)\n internal func isOccupied(_ bucket: Bucket) -> Bool {\n return unsafe isValid(bucket) && _isOccupied(bucket)\n }\n\n @inlinable\n @inline(__always)\n internal func checkOccupied(_ bucket: Bucket) {\n unsafe _precondition(isOccupied(bucket),\n "Attempting to access Collection elements using an invalid Index")\n }\n\n @inlinable\n @inline(__always)\n internal func _firstOccupiedBucket(fromWord word: Int) -> Bucket {\n unsafe _internalInvariant(word >= 0 && word <= wordCount)\n var word = word\n while unsafe word < wordCount {\n if let bit = unsafe words[word].minimum {\n return Bucket(word: word, bit: bit)\n }\n word += 1\n }\n return unsafe endBucket\n }\n\n @inlinable\n internal func occupiedBucket(after bucket: Bucket) -> Bucket {\n _internalInvariant(isValid(bucket))\n let word = bucket.word\n if let bit = unsafe words[word].intersecting(elementsAbove: bucket.bit).minimum {\n return Bucket(word: word, bit: bit)\n }\n return unsafe _firstOccupiedBucket(fromWord: word + 1)\n }\n\n @inlinable\n internal var startBucket: Bucket {\n return unsafe _firstOccupiedBucket(fromWord: 0)\n }\n\n @inlinable\n internal var endBucket: Bucket {\n @inline(__always)\n get {\n return unsafe Bucket(offset: bucketCount)\n }\n }\n}\n\nextension _HashTable {\n @inlinable\n @inline(__always)\n internal func idealBucket(forHashValue hashValue: Int) -> Bucket {\n return unsafe Bucket(offset: hashValue & bucketMask)\n }\n\n /// The next bucket after `bucket`, with wraparound at the end of the table.\n @inlinable\n @inline(__always)\n internal func bucket(wrappedAfter bucket: Bucket) -> Bucket {\n // The bucket is less than bucketCount, which is power of two less than\n // Int.max. Therefore adding 1 does not overflow.\n return unsafe Bucket(offset: (bucket.offset &+ 1) & bucketMask)\n }\n}\n\nextension _HashTable {\n @inlinable\n internal func previousHole(before bucket: Bucket) -> Bucket {\n _internalInvariant(isValid(bucket))\n // Note that if we have only a single partial word, its out-of-bounds bits\n // are guaranteed to be all set, so the formula below gives correct results.\n var word = bucket.word\n if let bit =\n unsafe words[word]\n .complement\n .intersecting(elementsBelow: bucket.bit)\n .maximum {\n return Bucket(word: word, bit: bit)\n }\n var wrap = false\n while true {\n word -= 1\n if word < 0 {\n _precondition(!wrap, "Hash table has no holes")\n wrap = true\n word = unsafe wordCount - 1\n }\n if let bit = unsafe words[word].complement.maximum {\n return Bucket(word: word, bit: bit)\n }\n }\n fatalError()\n }\n\n @inlinable\n internal func nextHole(atOrAfter bucket: Bucket) -> Bucket {\n _internalInvariant(isValid(bucket))\n // Note that if we have only a single partial word, its out-of-bounds bits\n // are guaranteed to be all set, so the formula below gives correct results.\n var word = bucket.word\n if let bit =\n unsafe words[word]\n .complement\n .subtracting(elementsBelow: bucket.bit)\n .minimum {\n return Bucket(word: word, bit: bit)\n }\n var wrap = false\n while true {\n word &+= 1\n if unsafe word == wordCount {\n _precondition(!wrap, "Hash table has no holes")\n wrap = true\n word = 0\n }\n if let bit = unsafe words[word].complement.minimum {\n return Bucket(word: word, bit: bit)\n }\n }\n fatalError()\n }\n}\n\nextension _HashTable {\n @inlinable\n @inline(__always)\n @_effects(releasenone)\n internal func copyContents(of other: _HashTable) {\n unsafe _internalInvariant(bucketCount == other.bucketCount)\n unsafe self.words.update(from: other.words, count: wordCount)\n }\n\n /// Insert a new entry with the specified hash value into the table.\n /// The entry must not already exist in the table -- duplicates are ignored.\n @inlinable\n @inline(__always)\n internal func insertNew(hashValue: Int) -> Bucket {\n let hole = unsafe nextHole(atOrAfter: idealBucket(forHashValue: hashValue))\n unsafe insert(hole)\n return hole\n }\n\n /// Insert a new entry for an element at `index`.\n @inlinable\n @inline(__always)\n internal func insert(_ bucket: Bucket) {\n unsafe _internalInvariant(!isOccupied(bucket))\n unsafe words[bucket.word].uncheckedInsert(bucket.bit)\n }\n\n @inlinable\n @inline(__always)\n internal func clear() {\n if unsafe bucketCount < Word.capacity {\n // We have only a single partial word. Set all out of bounds bits, so that\n // `occupiedBucket(after:)` and `nextHole(atOrAfter:)` works correctly\n // without a special case.\n unsafe words[0] = Word.allBits.subtracting(elementsBelow: bucketCount)\n } else {\n unsafe words.update(repeating: .empty, count: wordCount)\n }\n }\n\n @inline(__always)\n @inlinable\n internal func delete<D: _HashTableDelegate>(\n at bucket: Bucket,\n with delegate: D\n ) {\n unsafe _internalInvariant(isOccupied(bucket))\n\n // If we've put a hole in a chain of contiguous elements, some element after\n // the hole may belong where the new hole is.\n\n var hole = bucket\n var candidate = unsafe self.bucket(wrappedAfter: hole)\n\n guard unsafe _isOccupied(candidate) else {\n // Fast path: Don't get the first bucket when there's nothing to do.\n unsafe words[hole.word].uncheckedRemove(hole.bit)\n return\n }\n\n // Find the first bucket in the contiguous chain that contains the entry\n // we've just deleted.\n let start = unsafe self.bucket(wrappedAfter: previousHole(before: bucket))\n\n // Relocate out-of-place elements in the chain, repeating until we get to\n // the end of the chain.\n while unsafe _isOccupied(candidate) {\n let candidateHash = delegate.hashValue(at: candidate)\n let ideal = unsafe idealBucket(forHashValue: candidateHash)\n\n // Does this element belong between start and hole? We need two\n // separate tests depending on whether [start, hole] wraps around the\n // end of the storage.\n let c0 = ideal >= start\n let c1 = ideal <= hole\n if start <= hole ? (c0 && c1) : (c0 || c1) {\n delegate.moveEntry(from: candidate, to: hole)\n hole = candidate\n }\n unsafe candidate = unsafe self.bucket(wrappedAfter: candidate)\n }\n\n unsafe words[hole.word].uncheckedRemove(hole.bit)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_HashTable.swift
cpp_apple_swift_stdlib_public_core_HashTable.swift
Swift
15,293
0.8
0.060904
0.147577
node-utils
148
2024-02-27T06:26:37.041718
GPL-3.0
false
10fc460bde439bca10423260d9dabe82
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 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 class of types whose instances hold the value of an entity with stable\n/// identity.\n///\n/// Use the `Identifiable` protocol to provide a stable notion of identity to a \n/// class or value type. For example, you could define a `User` type with an `id`\n/// property that is stable across your app and your app's database storage. \n/// You could use the `id` property to identify a particular user even if other \n/// data fields change, such as the user's name.\n///\n/// `Identifiable` leaves the duration and scope of the identity unspecified.\n/// Identities can have any of the following characteristics:\n///\n/// - Guaranteed always unique, like UUIDs.\n/// - Persistently unique per environment, like database record keys.\n/// - Unique for the lifetime of a process, like global incrementing integers.\n/// - Unique for the lifetime of an object, like object identifiers.\n/// - Unique within the current collection, like collection indices.\n///\n/// It's up to both the conformer and the receiver of the protocol to document\n/// the nature of the identity.\n///\n/// Conforming to the Identifiable Protocol\n/// =======================================\n///\n/// `Identifiable` provides a default implementation for class types (using\n/// `ObjectIdentifier`), which is only guaranteed to remain unique for the\n/// lifetime of an object. If an object has a stronger notion of identity, it\n/// may be appropriate to provide a custom implementation.\n@available(SwiftStdlib 5.1, *)\npublic protocol Identifiable<ID> {\n\n /// A type representing the stable identity of the entity associated with\n /// an instance.\n associatedtype ID: Hashable\n\n /// The stable identity of the entity associated with this instance.\n var id: ID { get }\n}\n\n@available(SwiftStdlib 5.1, *)\nextension Identifiable where Self: AnyObject {\n public var id: ObjectIdentifier {\n return ObjectIdentifier(self)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Identifiable.swift
cpp_apple_swift_stdlib_public_core_Identifiable.swift
Swift
2,399
0.95
0.175439
0.792453
awesome-app
706
2023-09-28T15:19:28.576049
Apache-2.0
false
68fc922f7ba449b647d930b33e0a8c2e
//===----------------------------------------------------------------------===//\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 of indices for an arbitrary collection\n@frozen\npublic struct DefaultIndices<Elements: Collection> {\n @usableFromInline\n internal var _elements: Elements\n @usableFromInline\n internal var _startIndex: Elements.Index\n @usableFromInline\n internal var _endIndex: Elements.Index\n\n @inlinable\n internal init(\n _elements: Elements,\n startIndex: Elements.Index,\n endIndex: Elements.Index\n ) {\n self._elements = _elements\n self._startIndex = startIndex\n self._endIndex = endIndex\n }\n}\n\nextension DefaultIndices: Collection {\n\n public typealias Index = Elements.Index\n public typealias Element = Elements.Index\n public typealias Indices = DefaultIndices<Elements>\n public typealias SubSequence = DefaultIndices<Elements>\n public typealias Iterator = IndexingIterator<DefaultIndices<Elements>>\n\n @inlinable\n public var startIndex: Index {\n return _startIndex\n }\n\n @inlinable\n public var endIndex: Index {\n return _endIndex\n }\n\n @inlinable\n public subscript(i: Index) -> Elements.Index {\n // FIXME: swift-3-indexing-model: range check.\n return i\n }\n\n @inlinable\n public subscript(bounds: Range<Index>) -> DefaultIndices<Elements> {\n // FIXME: swift-3-indexing-model: range check.\n return DefaultIndices(\n _elements: _elements,\n startIndex: bounds.lowerBound,\n endIndex: bounds.upperBound)\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n // FIXME: swift-3-indexing-model: range check.\n return _elements.index(after: i)\n }\n\n @inlinable\n public func formIndex(after i: inout Index) {\n // FIXME: swift-3-indexing-model: range check.\n _elements.formIndex(after: &i)\n }\n\n @inlinable\n public var indices: Indices {\n return self\n }\n \n @_alwaysEmitIntoClient\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n return _elements.index(i, offsetBy: distance)\n }\n\n @_alwaysEmitIntoClient\n public func index(\n _ i: Index, offsetBy distance: Int, limitedBy limit: Index\n ) -> Index? {\n return _elements.index(i, offsetBy: distance, limitedBy: limit)\n }\n\n @_alwaysEmitIntoClient\n public func distance(from start: Index, to end: Index) -> Int {\n return _elements.distance(from: start, to: end)\n }\n}\n\nextension DefaultIndices: BidirectionalCollection\nwhere Elements: BidirectionalCollection {\n @inlinable\n public func index(before i: Index) -> Index {\n // FIXME: swift-3-indexing-model: range check.\n return _elements.index(before: i)\n }\n\n @inlinable\n public func formIndex(before i: inout Index) {\n // FIXME: swift-3-indexing-model: range check.\n _elements.formIndex(before: &i)\n }\n}\n\nextension DefaultIndices: RandomAccessCollection\nwhere Elements: RandomAccessCollection { }\n\nextension Collection where Indices == DefaultIndices<Self> {\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 @inlinable // trivial-implementation\n public var indices: DefaultIndices<Self> {\n return DefaultIndices(\n _elements: self,\n startIndex: self.startIndex,\n endIndex: self.endIndex)\n }\n}\n\nextension DefaultIndices: Sendable\n where Elements: Sendable, Elements.Index: Sendable { }\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Indices.swift
cpp_apple_swift_stdlib_public_core_Indices.swift
Swift
4,396
0.8
0.040268
0.269231
react-lib
90
2025-02-26T23:02:13.657019
MIT
false
9009c220d2e6b216d64a1978156aa012
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 - 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 fixed-size array.\n///\n/// The `InlineArray` type is a specialized array that stores its elements\n/// contiguously inline, rather than allocating an out-of-line region of memory\n/// with copy-on-write optimization.\n///\n/// Memory Layout\n/// -------------\n///\n/// An *empty* array's size is zero. Its stride and alignment are one byte.\n///\n/// A *nonempty* array's size and stride are equal to the element's stride\n/// multiplied by the number of elements. Its alignment is equal to the\n/// element's alignment.\n///\n/// MemoryLayout<InlineArray<3, UInt16>>.size //-> 6\n/// MemoryLayout<InlineArray<3, UInt16>>.stride //-> 6\n/// MemoryLayout<InlineArray<3, UInt16>>.alignment //-> 2\n///\n/// Literal Initialization\n/// ----------------------\n///\n/// Array literal syntax can be used to initialize an `InlineArray` instance.\n/// A stack-allocated array will do in-place initialization of each element.\n/// The `count` and/or `Element` can be inferred from the array literal.\n///\n/// let a: InlineArray<4, Int> = [1, 2, 4, 8]\n/// let b: InlineArray<_, Int> = [1, 2, 4, 8]\n/// let c: InlineArray<4, _> = [1, 2, 4, 8]\n/// let d: InlineArray = [1, 2, 4, 8]\n@available(SwiftStdlib 6.2, *)\n@frozen\n@safe\n@_addressableForDependencies\npublic struct InlineArray<let count: Int, Element: ~Copyable>: ~Copyable {\n @usableFromInline\n internal let _storage: Builtin.FixedArray<count, Element>\n}\n\n@available(SwiftStdlib 6.2, *)\nextension InlineArray: Copyable where Element: Copyable {}\n\n@available(SwiftStdlib 6.2, *)\nextension InlineArray: BitwiseCopyable where Element: BitwiseCopyable {}\n\n@available(SwiftStdlib 6.2, *)\nextension InlineArray: @unchecked Sendable where Element: Sendable & ~Copyable {}\n\n//===----------------------------------------------------------------------===//\n// MARK: - Address & Buffer\n//===----------------------------------------------------------------------===//\n\n@available(SwiftStdlib 6.2, *)\nextension InlineArray where Element: ~Copyable {\n /// Returns a pointer to the first element in the array.\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n internal var _address: UnsafePointer<Element> {\n unsafe UnsafePointer<Element>(Builtin.unprotectedAddressOfBorrow(self))\n }\n\n /// Returns a buffer pointer over the entire array.\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n internal var _buffer: UnsafeBufferPointer<Element> {\n unsafe UnsafeBufferPointer<Element>(start: _address, count: count)\n }\n\n /// Returns a mutable pointer to the first element in the array.\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n internal var _mutableAddress: UnsafeMutablePointer<Element> {\n mutating get {\n unsafe UnsafeMutablePointer<Element>(Builtin.unprotectedAddressOf(&self))\n }\n }\n\n /// Returns a mutable buffer pointer over the entire array.\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n internal var _mutableBuffer: UnsafeMutableBufferPointer<Element> {\n mutating get {\n unsafe UnsafeMutableBufferPointer<Element>(\n start: _mutableAddress,\n count: count\n )\n }\n }\n\n /// Converts the given raw pointer, which points at an uninitialized array\n /// instance, to a mutable buffer suitable for initialization.\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n internal static func _initializationBuffer(\n start: Builtin.RawPointer\n ) -> UnsafeMutableBufferPointer<Element> {\n unsafe UnsafeMutableBufferPointer<Element>(\n start: UnsafeMutablePointer<Element>(start),\n count: count\n )\n }\n}\n\n//===----------------------------------------------------------------------===//\n// MARK: - Initialization APIs\n//===----------------------------------------------------------------------===//\n\n@available(SwiftStdlib 6.2, *)\nextension InlineArray where Element: ~Copyable {\n /// Initializes every element in this array, by calling the given closure\n /// with each index.\n ///\n /// This will call the closure `count` times, where `count` is the static\n /// count of the array, to initialize every element by passing the closure\n /// the index of the current element being initialized.\n ///\n /// InlineArray<4, Int> { 1 << $0 } //-> [1, 2, 4, 8]\n ///\n /// The closure is allowed to throw an error at any point during\n /// initialization at which point the array will stop initialization,\n /// deinitialize every currently initialized element, and throw the given\n /// error back out to the caller.\n ///\n /// - Parameter body: A closure that returns an owned `Element` to emplace at\n /// the passed in index.\n ///\n /// - Complexity: O(*n*), where *n* is the number of elements in the array.\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public init<E: Error>(_ body: (Index) throws(E) -> Element) throws(E) {\n#if $BuiltinEmplaceTypedThrows\n self = try Builtin.emplace { (rawPtr) throws(E) -> () in\n let buffer = unsafe Self._initializationBuffer(start: rawPtr)\n\n for i in 0 ..< count {\n do throws(E) {\n try unsafe buffer.initializeElement(at: i, to: body(i))\n } catch {\n // The closure threw an error. We need to deinitialize every element\n // we've initialized up to this point.\n for j in 0 ..< i {\n unsafe buffer.deinitializeElement(at: j)\n }\n\n // Throw the error we were given back out to the caller.\n throw error\n }\n }\n }\n#else\n fatalError()\n#endif\n }\n\n /// Initializes every element in this array, by calling the given closure\n /// with each preceding element.\n ///\n /// This will call the closure `count - 1` times, where `count` is the static\n /// count of the array, to initialize every element by passing the closure an\n /// immutable borrow reference to the preceding element.\n ///\n /// InlineArray<4, Int>(first: 1) { $0 << 1 } //-> [1, 2, 4, 8]\n ///\n /// The closure is allowed to throw an error at any point during\n /// initialization at which point the array will stop initialization,\n /// deinitialize every currently initialized element, and throw the given\n /// error back out to the caller.\n ///\n /// - Parameters:\n /// - first: The first value to emplace into the array.\n /// - next: A closure that takes an immutable borrow reference to the\n /// preceding element, and returns an owned `Element` instance to emplace\n /// into the array.\n ///\n /// - Complexity: O(*n*), where *n* is the number of elements in the array.\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public init<E: Error>(\n first: consuming Element,\n next: (borrowing Element) throws(E) -> Element\n ) throws(E) {\n#if $BuiltinEmplaceTypedThrows\n // FIXME: We should be able to mark 'Builtin.emplace' as '@once' or something\n // to give the compiler enough information to know we will only run\n // it once so it can consume the capture. For now, we use an optional\n // and take the underlying value within the closure.\n var o: Element? = first\n\n self = try Builtin.emplace { (rawPtr) throws(E) -> () in\n let buffer = unsafe Self._initializationBuffer(start: rawPtr)\n\n guard Self.count > 0 else {\n return\n }\n\n unsafe buffer.initializeElement(\n at: 0,\n to: o.take()._consumingUncheckedUnwrapped()\n )\n\n for i in 1 ..< count {\n do throws(E) {\n try unsafe buffer.initializeElement(at: i, to: next(buffer[i &- 1]))\n } catch {\n // The closure threw an error. We need to deinitialize every element\n // we've initialized up to this point.\n for j in 0 ..< i {\n unsafe buffer.deinitializeElement(at: j)\n }\n\n // Throw the error we were given back out to the caller.\n throw error\n }\n }\n }\n#else\n fatalError()\n#endif\n }\n}\n\n@available(SwiftStdlib 6.2, *)\nextension InlineArray where Element: Copyable {\n /// Initializes every element in this array to a copy of the given value.\n ///\n /// - Parameter value: The instance to initialize this array with.\n ///\n /// - Complexity: O(*n*), where *n* is the number of elements in the array.\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public init(repeating value: Element) {\n self = Builtin.emplace {\n let buffer = unsafe Self._initializationBuffer(start: $0)\n\n unsafe buffer.initialize(repeating: value)\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// MARK: - Collection APIs\n//===----------------------------------------------------------------------===//\n\n@available(SwiftStdlib 6.2, *)\nextension InlineArray where Element: ~Copyable {\n /// The type of the array's elements.\n @available(SwiftStdlib 6.2, *)\n public typealias Element = Element\n\n /// A type that represents a position in the array.\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 @available(SwiftStdlib 6.2, *)\n public typealias Index = Int\n\n /// The number of elements in the array.\n ///\n /// - Complexity: O(1)\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_semantics("fixed_storage.get_count")\n @inline(__always)\n public var count: Int {\n count\n }\n\n /// A Boolean value indicating whether the array is empty.\n ///\n /// - Complexity: O(1)\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n public var isEmpty: Bool {\n count == 0\n }\n\n /// The position of the first element in a nonempty array.\n ///\n /// If the array is empty, `startIndex` is equal to `endIndex`.\n ///\n /// - Complexity: O(1)\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n public var startIndex: Index {\n 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 /// If the array is empty, `endIndex` is equal to `startIndex`.\n ///\n /// - Complexity: O(1)\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n public var endIndex: Index {\n count\n }\n\n /// The indices that are valid for subscripting the array, in ascending order.\n ///\n /// - Complexity: O(1)\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n public var indices: Range<Index> {\n unsafe Range(_uncheckedBounds: (0, count))\n }\n\n /// Returns the position immediately after the given index.\n ///\n /// - Parameter i: A valid index of the array. `i` must be less than\n /// `endIndex`.\n /// - Returns: The index immediately after `i`.\n ///\n /// - Complexity: O(1)\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n public borrowing func index(after i: Index) -> Index {\n i &+ 1\n }\n\n /// Returns the position immediately before the given index.\n ///\n /// - Parameter i: A valid index of the array. `i` must be greater than\n /// `startIndex`.\n /// - Returns: The index value immediately before `i`.\n ///\n /// - Complexity: O(1)\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n public borrowing func index(before i: Index) -> Index {\n i &- 1\n }\n\n @_alwaysEmitIntoClient\n @_semantics("fixed_storage.check_index")\n @inline(__always)\n internal func _checkIndex(_ i: Index) {\n _precondition(indices.contains(i), "Index out of bounds")\n }\n\n /// Accesses the element at the specified position.\n ///\n /// - Parameter i: The position of the element to access. `i` must be a valid\n /// index of the array that is not equal to the `endIndex` property.\n ///\n /// - Complexity: O(1)\n @available(SwiftStdlib 6.2, *)\n @_addressableSelf\n @_alwaysEmitIntoClient\n public subscript(_ i: Index) -> Element {\n @_transparent\n unsafeAddress {\n _checkIndex(i)\n return unsafe _address + i\n }\n\n @_transparent\n unsafeMutableAddress {\n _checkIndex(i)\n return unsafe _mutableAddress + i\n }\n }\n\n /// Accesses the element at the specified position.\n ///\n /// - Warning: This subscript trades safety for performance. Using an invalid\n /// index results in undefined behavior.\n ///\n /// - Parameter i: The position of the element to access. `i` must be a valid\n /// index of the array that is not equal to the `endIndex` property.\n ///\n /// - Complexity: O(1)\n @available(SwiftStdlib 6.2, *)\n @_addressableSelf\n @_alwaysEmitIntoClient\n @unsafe\n public subscript(unchecked i: Index) -> Element {\n @_transparent\n unsafeAddress {\n unsafe _address + i\n }\n\n @_transparent\n unsafeMutableAddress {\n unsafe _mutableAddress + i\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// MARK: - MutableCollection APIs\n//===----------------------------------------------------------------------===//\n\n@available(SwiftStdlib 6.2, *)\nextension InlineArray where Element: ~Copyable {\n /// Exchanges the values at the specified indices of the array.\n ///\n /// Both parameters must be valid indices of the array and not equal to\n /// `endIndex`. Passing the same index as both `i` and `j` has no effect.\n ///\n /// - Parameters:\n /// - i: The index of the first value to swap.\n /// - j: The index of the second value to swap.\n ///\n /// - Complexity: O(1)\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n public mutating func swapAt(\n _ i: Index,\n _ j: Index\n ) {\n guard i != j else {\n return\n }\n\n _checkIndex(i)\n _checkIndex(j)\n\n let ithElement = unsafe _mutableBuffer.moveElement(from: i)\n let jthElement = unsafe _mutableBuffer.moveElement(from: j)\n unsafe _mutableBuffer.initializeElement(at: i, to: jthElement)\n unsafe _mutableBuffer.initializeElement(at: j, to: ithElement)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// MARK: Span\n//===----------------------------------------------------------------------===//\n\n@available(SwiftStdlib 6.2, *)\nextension InlineArray where Element: ~Copyable {\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 _address\n let span = unsafe Span(_unsafeStart: pointer, count: count)\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 _mutableAddress\n let span = unsafe MutableSpan(_unsafeStart: pointer, count: count)\n return unsafe _overrideLifetime(span, mutating: &self)\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// MARK: - Unsafe APIs\n//===----------------------------------------------------------------------===//\n\n@available(SwiftStdlib 6.2, *)\nextension InlineArray where Element: ~Copyable {\n // FIXME: @available(*, deprecated, renamed: "span.withUnsafeBufferPointer(_:)")\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n public borrowing func _withUnsafeBufferPointer<Result: ~Copyable, E: Error>(\n _ body: (UnsafeBufferPointer<Element>) throws(E) -> Result\n ) throws(E) -> Result {\n try unsafe body(_buffer)\n }\n\n // FIXME: @available(*, deprecated, renamed: "mutableSpan.withUnsafeMutableBufferPointer(_:)")\n @available(SwiftStdlib 6.2, *)\n @_alwaysEmitIntoClient\n @_transparent\n public mutating func _withUnsafeMutableBufferPointer<Result: ~Copyable, E: Error>(\n _ body: (UnsafeMutableBufferPointer<Element>) throws(E) -> Result\n ) throws(E) -> Result {\n try unsafe body(_mutableBuffer)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_InlineArray.swift
cpp_apple_swift_stdlib_public_core_InlineArray.swift
Swift
16,387
0.8
0.039526
0.419214
vue-tools
225
2024-10-29T12:54:18.789783
Apache-2.0
false
666e87b7c29eac7a9812f1aaea5b295e
//===----------------------------------------------------------------------===//\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\nimport SwiftShims\n\n#if SWIFT_STDLIB_HAS_STDIN\n\n/// Returns a string read from standard input through the end of the current\n/// line or until EOF is reached.\n///\n/// Standard input is interpreted as `UTF-8`. Invalid bytes are replaced by\n/// Unicode [replacement characters][rc].\n///\n/// [rc]:\n/// https://unicode.org/glossary/#replacement_character\n///\n/// - Parameter strippingNewline: If `true`, newline characters and character\n/// combinations are stripped from the result; otherwise, newline characters\n/// or character combinations are preserved. The default is `true`.\n/// - Returns: The string of characters read from standard input. If EOF has\n/// already been reached when `readLine()` is called, the result is `nil`.\npublic func readLine(strippingNewline: Bool = true) -> String? {\n var utf8Start: UnsafeMutablePointer<UInt8>?\n let utf8Count = unsafe swift_stdlib_readLine_stdin(&utf8Start)\n defer {\n unsafe _swift_stdlib_free(utf8Start)\n }\n guard utf8Count > 0 else {\n return nil\n }\n let utf8Buffer = unsafe UnsafeBufferPointer(start: utf8Start, count: utf8Count)\n var result = unsafe String._fromUTF8Repairing(utf8Buffer).result\n if strippingNewline, result.last == "\n" || result.last == "\r\n" {\n _ = result.removeLast()\n }\n return result\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_InputStream.swift
cpp_apple_swift_stdlib_public_core_InputStream.swift
Swift
1,811
0.95
0.083333
0.613636
react-lib
521
2023-10-09T09:44:44.606297
BSD-3-Clause
false
1479e4b0fe526736ceb0494c1ddf912e
//===----------------------------------------------------------------------===//\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 specific point in time for a given `Clock`.\n@available(SwiftStdlib 5.7, *)\npublic protocol InstantProtocol<Duration>: Comparable, Hashable, Sendable {\n associatedtype Duration: DurationProtocol\n func advanced(by duration: Duration) -> Self\n func duration(to other: Self) -> Duration\n}\n\n/*\ndisabled for now - this perturbs operator resolution\nextension InstantProtocol {\n @_alwaysEmitIntoClient\n @inlinable\n public static func + (_ lhs: Self, _ rhs: Duration) -> Self {\n lhs.advanced(by: rhs)\n }\n\n @_alwaysEmitIntoClient\n @inlinable\n public static func += (_ lhs: inout Self, _ rhs: Duration) {\n lhs = lhs.advanced(by: rhs)\n }\n\n @_alwaysEmitIntoClient\n @inlinable\n public static func - (_ lhs: Self, _ rhs: Duration) -> Self {\n lhs.advanced(by: .zero - rhs)\n }\n\n @_alwaysEmitIntoClient\n @inlinable\n public static func -= (_ lhs: inout Self, _ rhs: Duration) {\n lhs = lhs.advanced(by: .zero - rhs)\n }\n\n @_alwaysEmitIntoClient\n @inlinable\n public static func - (_ lhs: Self, _ rhs: Self) -> Duration {\n rhs.duration(to: lhs)\n }\n}\n*/\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Instant.swift
cpp_apple_swift_stdlib_public_core_Instant.swift
Swift
1,613
0.8
0.074074
0.291667
awesome-app
823
2023-10-16T10:06:58.341379
Apache-2.0
false
04a1802b179d4190b3f255da89334f0d
//===----------------------------------------------------------------------===//\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// MARK: Memory layout\n\n/// A 128-bit signed integer value type.\n@available(SwiftStdlib 6.0, *)\n@frozen\npublic struct Int128: Sendable {\n#if _pointerBitWidth(_64) || arch(arm64_32)\n // On 64-bit platforms (including arm64_32 and any similar targets with\n // 32b pointers but HW-backed 64b integers), the layout is simply that\n // of `Builtin.Int128`.\n public var _value: Builtin.Int128\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public init(_ _value: Builtin.Int128) {\n self._value = _value\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public var _low: UInt64 {\n UInt64(Builtin.trunc_Int128_Int64(_value))\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public var _high: Int64 {\n let shifted: Int128 = self &>> 64\n return Int64(Builtin.trunc_Int128_Int64(shifted._value))\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public init(_low: UInt64, _high: Int64) {\n#if _endian(little)\n self = unsafe unsafeBitCast((_low, _high), to: Self.self)\n#else\n self = unsafeBitCast((_high, _low), to: Self.self)\n#endif\n }\n \n#else\n // On 32-bit platforms, we don't want to use Builtin.Int128 for layout\n // because it would be 16B aligned, which is excessive for such targets\n // (and generally incompatible with C's `_BitInt(128)`). Instead we lay\n // out the type as two `{U}Int64` fields--note that we have to be careful\n // about endianness in this case.\n#if _endian(little)\n public var _low: UInt64\n public var _high: Int64\n#else\n public var _high: Int64\n public var _low: UInt64\n#endif\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public init(_low: UInt64, _high: Int64) {\n self._low = _low\n self._high = _high\n }\n\n @available(SwiftStdlib 6.0, *)\n public var _value: Builtin.Int128 {\n @_transparent\n get {\n unsafeBitCast(self, to: Builtin.Int128.self)\n }\n\n @_transparent\n set {\n self = Self(newValue)\n }\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public init(_ _value: Builtin.Int128) {\n self = unsafeBitCast(_value, to: Self.self)\n }\n#endif\n\n /// Creates a new instance with the same memory representation as the given\n /// value.\n ///\n /// This initializer does not perform any range or overflow checking. The\n /// resulting instance may not have the same numeric value as\n /// `bitPattern`---it is only guaranteed to use the same pattern of bits in\n /// its binary representation.\n ///\n /// - Parameter bitPattern: A value to use as the source of the new instance's\n /// binary representation.\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public init(bitPattern: UInt128) {\n self.init(bitPattern._value)\n }\n}\n\n// MARK: - Constants\n@available(SwiftStdlib 6.0, *)\nextension Int128 {\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static var zero: Self {\n Self(Builtin.zeroInitializer())\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static var min: Self {\n Self(_low: .zero, _high: .min)\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static var max: Self {\n Self(_low: .max, _high: .max)\n }\n}\n\n// MARK: - Conversions from other integers\n@available(SwiftStdlib 6.0, *)\nextension Int128: ExpressibleByIntegerLiteral,\n _ExpressibleByBuiltinIntegerLiteral {\n @available(SwiftStdlib 6.0, *)\n public typealias IntegerLiteralType = Self\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public init(_builtinIntegerLiteral x: Builtin.IntLiteral) {\n self.init(Builtin.s_to_s_checked_trunc_IntLiteral_Int128(x).0)\n }\n\n @available(SwiftStdlib 6.0, *)\n @inlinable\n public init?<T>(exactly source: T) where T: BinaryInteger {\n guard let high = Int64(exactly: source >> 64) else { return nil }\n let low = UInt64(truncatingIfNeeded: source)\n self.init(_low: low, _high: high)\n }\n\n @available(SwiftStdlib 6.0, *)\n @inlinable\n public init<T>(_ source: T) where T: BinaryInteger {\n guard let value = Self(exactly: source) else {\n fatalError("value cannot be converted to Int128 because it is outside the representable range")\n }\n self = value\n }\n\n @available(SwiftStdlib 6.0, *)\n @inlinable\n public init<T>(clamping source: T) where T: BinaryInteger {\n guard let value = Self(exactly: source) else {\n self = source < .zero ? .min : .max\n return\n }\n self = value\n }\n\n @available(SwiftStdlib 6.0, *)\n @inlinable\n public init<T>(truncatingIfNeeded source: T) where T: BinaryInteger {\n let high = Int64(truncatingIfNeeded: source >> 64)\n let low = UInt64(truncatingIfNeeded: source)\n self.init(_low: low, _high: high)\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public init(_truncatingBits source: UInt) {\n self.init(_low: UInt64(source), _high: .zero)\n }\n}\n\n// MARK: - Conversions from Binary floating-point\n@available(SwiftStdlib 6.0, *)\nextension Int128 {\n @available(SwiftStdlib 6.0, *)\n @inlinable\n public init?<T>(exactly source: T) where T: BinaryFloatingPoint {\n if source.magnitude < 0x1.0p64 {\n guard let magnitude = UInt64(exactly: source.magnitude) else {\n return nil\n }\n self = Int128(_low: magnitude, _high: 0)\n if source < 0 { self = -self }\n } else {\n let highAsFloat = (source * 0x1.0p-64).rounded(.down)\n guard let high = Int64(exactly: highAsFloat) else { return nil }\n // Because we already ruled out |source| < 0x1.0p64, we know that\n // high contains at least one value bit, and so Sterbenz' lemma\n // allows us to compute an exact residual:\n guard let low = UInt64(exactly: source - 0x1.0p64*highAsFloat) else {\n return nil\n }\n self.init(_low: low, _high: high)\n }\n }\n\n @available(SwiftStdlib 6.0, *)\n @inlinable\n public init<T>(_ source: T) where T: BinaryFloatingPoint {\n guard let value = Self(exactly: source.rounded(.towardZero)) else {\n fatalError("value cannot be converted to Int128 because it is outside the representable range")\n }\n self = value\n }\n}\n\n// MARK: - Non-arithmetic utility conformances\n@available(SwiftStdlib 6.0, *)\nextension Int128: Equatable {\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func ==(a: Self, b: Self) -> Bool {\n Bool(Builtin.cmp_eq_Int128(a._value, b._value))\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension Int128: Comparable {\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func <(a: Self, b: Self) -> Bool {\n Bool(Builtin.cmp_slt_Int128(a._value, b._value))\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension Int128: Hashable {\n @available(SwiftStdlib 6.0, *)\n @inlinable\n public func hash(into hasher: inout Hasher) {\n hasher.combine(_low)\n hasher.combine(_high)\n }\n}\n\n// MARK: - Overflow-reporting arithmetic\n@available(SwiftStdlib 6.0, *)\nextension Int128 {\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public func addingReportingOverflow(\n _ other: Self\n ) -> (partialValue: Self, overflow: Bool) {\n let (result, overflow) = Builtin.sadd_with_overflow_Int128(\n self._value, other._value, Builtin.zeroInitializer()\n )\n return (Self(result), Bool(overflow))\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public func subtractingReportingOverflow(\n _ other: Self\n ) -> (partialValue: Self, overflow: Bool) {\n let (result, overflow) = Builtin.ssub_with_overflow_Int128(\n self._value, other._value, Builtin.zeroInitializer()\n )\n return (Self(result), Bool(overflow))\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public func multipliedReportingOverflow(\n by other: Self\n ) -> (partialValue: Self, overflow: Bool) {\n let a = self.magnitude\n let b = other.magnitude\n let (magnitude, overflow) = a.multipliedReportingOverflow(by: b)\n if (self < 0) != (other < 0) {\n let partialValue = Self(bitPattern: 0 &- magnitude)\n return (partialValue, overflow || partialValue > 0)\n } else {\n let partialValue = Self(bitPattern: magnitude)\n return (partialValue, overflow || partialValue < 0)\n }\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public func dividedReportingOverflow(\n by other: Self\n ) -> (partialValue: Self, overflow: Bool) {\n if _slowPath(other == .zero) {\n return (self, true)\n }\n if _slowPath(self == .min && other == (-1 as Self)) {\n return (.min, true)\n }\n return (Self(Builtin.sdiv_Int128(self._value, other._value)), false)\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public func remainderReportingOverflow(\n dividingBy other: Self\n ) -> (partialValue: Self, overflow: Bool) {\n if _slowPath(other == .zero) {\n return (self, true)\n }\n // This case is interesting because the remainder does not overflow; the\n // analogous division does. Counting it as overflowing is consistent with\n // documented behavior.\n if _slowPath(self == .min && other == (-1 as Self)) {\n return (0, true)\n }\n return (Self(Builtin.srem_Int128(self._value, other._value)), false)\n }\n}\n\n// MARK: - AdditiveArithmetic conformance\n@available(SwiftStdlib 6.0, *)\nextension Int128: AdditiveArithmetic {\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func +(a: Self, b: Self) -> Self {\n let (result, overflow) = a.addingReportingOverflow(b)\n // On arm64, this check materializes the carryout in register, then does\n // a TBNZ, where we should get a b.cs instead. I filed rdar://115387277\n // to track this, but it only costs us one extra instruction, so we'll\n // keep it as is for now.\n Builtin.condfail_message(\n overflow._value,\n StaticString("arithmetic overflow").unsafeRawPointer\n )\n return result\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func -(a: Self, b: Self) -> Self {\n let (result, overflow) = a.subtractingReportingOverflow(b)\n Builtin.condfail_message(\n overflow._value,\n StaticString("arithmetic overflow").unsafeRawPointer\n )\n return result\n }\n}\n\n// MARK: - Multiplication and division\n@available(SwiftStdlib 6.0, *)\nextension Int128 {\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func *(a: Self, b: Self) -> Self {\n let (result, overflow) = a.multipliedReportingOverflow(by: b)\n Builtin.condfail_message(\n overflow._value,\n StaticString("arithmetic overflow").unsafeRawPointer\n )\n return result\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func *=(a: inout Self, b: Self) {\n a = a * b\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func /(a: Self, b: Self) -> Self {\n if _slowPath(b == .zero) {\n _preconditionFailure("Division by zero")\n }\n if _slowPath(a == .min && b == (-1 as Self)) {\n _preconditionFailure("Division results in an overflow")\n }\n return Self(Builtin.sdiv_Int128(a._value, b._value))\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func /=(a: inout Self, b: Self) {\n a = a / b\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func %(a: Self, b: Self) -> Self {\n if _slowPath(b == .zero) {\n _preconditionFailure("Division by zero in remainder operation")\n }\n // This case is interesting because the remainder does not overflow; the\n // analogous division does. Counting it as overflowing is consistent with\n // documented behavior.\n if _slowPath(a == .min && b == (-1 as Self)) {\n _preconditionFailure("Division results in an overflow in remainder operation")\n }\n return Self(Builtin.srem_Int128(a._value, b._value))\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func %=(a: inout Self, b: Self) {\n a = a % b\n }\n}\n\n// MARK: - Numeric conformance\n@available(SwiftStdlib 6.0, *)\nextension Int128: SignedNumeric {\n @available(SwiftStdlib 6.0, *)\n public typealias Magnitude = UInt128\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public var magnitude: Magnitude {\n let unsignedSelf = UInt128(_value)\n return self < 0 ? 0 &- unsignedSelf : unsignedSelf\n }\n}\n\n// MARK: - BinaryInteger conformance\n@available(SwiftStdlib 6.0, *)\nextension Int128: BinaryInteger {\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public var words: UInt128.Words {\n Words(_value: UInt128(_value))\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func &=(a: inout Self, b: Self) {\n a._value = Builtin.and_Int128(a._value, b._value)\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func |=(a: inout Self, b: Self) {\n a._value = Builtin.or_Int128(a._value, b._value)\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func ^=(a: inout Self, b: Self) {\n a._value = Builtin.xor_Int128(a._value, b._value)\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func &>>=(a: inout Self, b: Self) {\n let masked = b & 127\n a._value = Builtin.ashr_Int128(a._value, masked._value)\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func &<<=(a: inout Self, b: Self) {\n let masked = b & 127\n a._value = Builtin.shl_Int128(a._value, masked._value)\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public var trailingZeroBitCount: Int {\n _low == 0 ? 64 + _high.trailingZeroBitCount : _low.trailingZeroBitCount\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public var _lowWord: UInt {\n#if _pointerBitWidth(_64)\n UInt(Builtin.trunc_Int128_Int64(_value))\n#elseif _pointerBitWidth(_32)\n UInt(Builtin.trunc_Int128_Int32(_value))\n#elseif _pointerBitWidth(_16)\n UInt(Builtin.trunc_Int128_Int16(_value))\n#else\n#error("Unsupported platform")\n#endif\n }\n}\n\n// MARK: - FixedWidthInteger conformance\n@available(SwiftStdlib 6.0, *)\nextension Int128: FixedWidthInteger, SignedInteger {\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static var bitWidth: Int { 128 }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public var nonzeroBitCount: Int {\n _high.nonzeroBitCount &+ _low.nonzeroBitCount\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public var leadingZeroBitCount: Int {\n _high == 0 ? 64 + _low.leadingZeroBitCount : _high.leadingZeroBitCount\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public var byteSwapped: Self {\n return Self(_low: UInt64(bitPattern: _high.byteSwapped),\n _high: Int64(bitPattern: _low.byteSwapped))\n }\n\n @available(SwiftStdlib 6.0, *)\n @_transparent\n public static func &*(lhs: Self, rhs: Self) -> Self {\n // The default &* on FixedWidthInteger calls multipliedReportingOverflow,\n // which we want to avoid here, since the overflow check is expensive\n // enough that we wouldn't want to inline it into most callers.\n Self(Builtin.mul_Int128(lhs._value, rhs._value))\n }\n}\n\n// MARK: - Integer comparison type inference\n@available(SwiftStdlib 6.0, *)\nextension Int128 {\n // IMPORTANT: The following four apparently unnecessary overloads of\n // comparison operations are necessary for literal comparands to be\n // inferred as the desired type.\n @_transparent @_alwaysEmitIntoClient\n public static func != (lhs: Self, rhs: Self) -> Bool {\n return !(lhs == rhs)\n }\n\n @_transparent @_alwaysEmitIntoClient\n public static func <= (lhs: Self, rhs: Self) -> Bool {\n return !(rhs < lhs)\n }\n\n @_transparent @_alwaysEmitIntoClient\n public static func >= (lhs: Self, rhs: Self) -> Bool {\n return !(lhs < rhs)\n }\n\n @_transparent @_alwaysEmitIntoClient\n public static func > (lhs: Self, rhs: Self) -> Bool {\n return rhs < lhs\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Int128.swift
cpp_apple_swift_stdlib_public_core_Int128.swift
Swift
16,020
0.8
0.037906
0.153535
node-utils
750
2024-04-29T02:43:53.580271
GPL-3.0
false
71232cc1a4a0ad8c29f49950e0565d0d
//===----------------------------------------------------------------------===//\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@_alwaysEmitIntoClient\ninternal func _parseIntegerDigits<Result: FixedWidthInteger>(\n ascii codeUnits: UnsafeBufferPointer<UInt8>, radix: Int, isNegative: Bool\n) -> Result? {\n _internalInvariant(radix >= 2 && radix <= 36)\n guard _fastPath(!codeUnits.isEmpty) else { return nil }\n \n // ASCII constants, named for clarity:\n let _0 = 48 as UInt8, _A = 65 as UInt8, _a = 97 as UInt8\n \n let numericalUpperBound: UInt8\n let uppercaseUpperBound: UInt8\n let lowercaseUpperBound: UInt8\n if radix <= 10 {\n numericalUpperBound = _0 &+ UInt8(truncatingIfNeeded: radix)\n uppercaseUpperBound = _A\n lowercaseUpperBound = _a\n } else {\n numericalUpperBound = _0 &+ 10\n uppercaseUpperBound = _A &+ UInt8(truncatingIfNeeded: radix &- 10)\n lowercaseUpperBound = _a &+ UInt8(truncatingIfNeeded: radix &- 10)\n }\n let multiplicand = Result(truncatingIfNeeded: radix)\n var result = 0 as Result\n for unsafe digit in unsafe codeUnits {\n let digitValue: Result\n if _fastPath(digit >= _0 && digit < numericalUpperBound) {\n digitValue = Result(truncatingIfNeeded: digit &- _0)\n } else if _fastPath(digit >= _A && digit < uppercaseUpperBound) {\n digitValue = Result(truncatingIfNeeded: digit &- _A &+ 10)\n } else if _fastPath(digit >= _a && digit < lowercaseUpperBound) {\n digitValue = Result(truncatingIfNeeded: digit &- _a &+ 10)\n } else {\n return nil\n }\n let overflow1: Bool\n (result, overflow1) = result.multipliedReportingOverflow(by: multiplicand)\n let overflow2: Bool\n (result, overflow2) = isNegative\n ? result.subtractingReportingOverflow(digitValue)\n : result.addingReportingOverflow(digitValue)\n guard _fastPath(!overflow1 && !overflow2) else { return nil }\n }\n return result\n}\n\n@_alwaysEmitIntoClient\n@inline(__always)\ninternal func _parseInteger<Result: FixedWidthInteger>(\n ascii codeUnits: UnsafeBufferPointer<UInt8>, radix: Int\n) -> Result? {\n _internalInvariant(!codeUnits.isEmpty)\n \n // ASCII constants, named for clarity:\n let _plus = 43 as UInt8, _minus = 45 as UInt8\n \n let first = unsafe codeUnits[0]\n if first == _minus {\n return unsafe _parseIntegerDigits(\n ascii: UnsafeBufferPointer(rebasing: codeUnits[1...]),\n radix: radix, isNegative: true)\n }\n if first == _plus {\n return unsafe _parseIntegerDigits(\n ascii: UnsafeBufferPointer(rebasing: codeUnits[1...]),\n radix: radix, isNegative: false)\n }\n return unsafe _parseIntegerDigits(ascii: codeUnits, radix: radix, isNegative: false)\n}\n\n@_alwaysEmitIntoClient\n@inline(never)\ninternal func _parseInteger<S: StringProtocol, Result: FixedWidthInteger>(\n ascii text: S, radix: Int\n) -> Result? {\n var str = String(text)\n return str.withUTF8 { unsafe _parseInteger(ascii: $0, radix: radix) }\n}\n\nextension FixedWidthInteger {\n /// Creates a new integer value from the given string and radix.\n ///\n /// The string passed as `text` may begin with a plus or minus sign character\n /// (`+` or `-`), followed by one or more numeric digits (`0-9`) or letters\n /// (`a-z` or `A-Z`). Parsing of the string is case insensitive.\n ///\n /// let x = Int("123")\n /// // x == 123\n ///\n /// let y = Int("-123", radix: 8)\n /// // y == -83\n /// let y = Int("+123", radix: 8)\n /// // y == +83\n ///\n /// let z = Int("07b", radix: 16)\n /// // z == 123\n ///\n /// If `text` is in an invalid format or contains characters that are out of\n /// bounds for the given `radix`, or if the value it denotes in the given\n /// `radix` is not representable, the result is `nil`. For example, the\n /// following conversions result in `nil`:\n ///\n /// Int(" 100") // Includes whitespace\n /// Int("21-50") // Invalid format\n /// Int("ff6600") // Characters out of bounds\n /// Int("zzzzzzzzzzzzz", radix: 36) // Out of range\n ///\n /// - Parameters:\n /// - text: The ASCII representation of a number in the radix passed as\n /// `radix`.\n /// - radix: The radix, or base, to use for converting `text` to an integer\n /// value. `radix` must be in the range `2...36`. The default is 10.\n @inlinable\n @inline(__always)\n public init?<S: StringProtocol>(_ text: S, radix: Int = 10) {\n _precondition(2...36 ~= radix, "Radix not in range 2...36")\n guard _fastPath(!text.isEmpty) else { return nil }\n let result: Self? =\n text.utf8.withContiguousStorageIfAvailable {\n unsafe _parseInteger(ascii: $0, radix: radix)\n } ?? _parseInteger(ascii: text, radix: radix)\n guard let result_ = result else { return nil }\n self = result_\n }\n\n /// Creates a new integer value from the given string.\n ///\n /// The string passed as `description` may begin with a plus or minus sign\n /// character (`+` or `-`), followed by one or more numeric digits (`0-9`).\n ///\n /// let x = Int("123")\n /// // x == 123\n ///\n /// If `description` is in an invalid format, or if the value it denotes in\n /// base 10 is not representable, the result is `nil`. For example, the\n /// following conversions result in `nil`:\n ///\n /// Int(" 100") // Includes whitespace\n /// Int("21-50") // Invalid format\n /// Int("ff6600") // Characters out of bounds\n /// Int("10000000000000000000000000") // Out of range\n ///\n /// - Parameter description: The ASCII representation of a number.\n @inlinable\n @inline(__always)\n public init?(_ description: String) {\n self.init(description, radix: 10)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Old entry points preserved for ABI compatibility.\n//===----------------------------------------------------------------------===//\n\n/// Returns c as a UTF16.CodeUnit. Meant to be used as _ascii16("x").\n@usableFromInline // Previously '@inlinable'.\ninternal func _ascii16(_ c: Unicode.Scalar) -> UTF16.CodeUnit {\n _internalInvariant(c.value >= 0 && c.value <= 0x7F, "not ASCII")\n return UTF16.CodeUnit(c.value)\n}\n\n@usableFromInline // Previously '@inlinable @inline(__always)'.\ninternal func _asciiDigit<CodeUnit: UnsignedInteger, Result: BinaryInteger>(\n codeUnit u_: CodeUnit, radix: Result\n) -> Result? {\n let digit = _ascii16("0")..._ascii16("9")\n let lower = _ascii16("a")..._ascii16("z")\n let upper = _ascii16("A")..._ascii16("Z")\n\n let u = UInt16(truncatingIfNeeded: u_)\n let d: UInt16\n if _fastPath(digit ~= u) { d = u &- digit.lowerBound }\n else if _fastPath(upper ~= u) { d = u &- upper.lowerBound &+ 10 }\n else if _fastPath(lower ~= u) { d = u &- lower.lowerBound &+ 10 }\n else { return nil }\n guard _fastPath(d < radix) else { return nil }\n return Result(truncatingIfNeeded: d)\n}\n\n@usableFromInline // Previously '@inlinable @inline(__always)'.\ninternal func _parseUnsignedASCII<\n Rest: IteratorProtocol, Result: FixedWidthInteger\n>(\n first: Rest.Element, rest: inout Rest, radix: Result, positive: Bool\n) -> Result?\nwhere Rest.Element: UnsignedInteger {\n let r0 = _asciiDigit(codeUnit: first, radix: radix)\n guard _fastPath(r0 != nil), var result = r0 else { return nil }\n if !positive {\n let (result0, overflow0)\n = (0 as Result).subtractingReportingOverflow(result)\n guard _fastPath(!overflow0) else { return nil }\n result = result0\n }\n\n while let u = rest.next() {\n let d0 = _asciiDigit(codeUnit: u, radix: radix)\n guard _fastPath(d0 != nil), let d = d0 else { return nil }\n let (result1, overflow1) = result.multipliedReportingOverflow(by: radix)\n let (result2, overflow2) = positive\n ? result1.addingReportingOverflow(d)\n : result1.subtractingReportingOverflow(d)\n guard _fastPath(!overflow1 && !overflow2)\n else { return nil }\n result = result2\n }\n return result\n}\n\n// This function has been superseded because it is about 20KB of previously\n// always-inline code, most of which are MOV instructions.\n\n@usableFromInline // Previously '@inlinable @inline(__always)'.\ninternal func _parseASCII<\n CodeUnits: IteratorProtocol, Result: FixedWidthInteger\n>(\n codeUnits: inout CodeUnits, radix: Result\n) -> Result?\nwhere CodeUnits.Element: UnsignedInteger {\n let c0_ = codeUnits.next()\n guard _fastPath(c0_ != nil), let c0 = c0_ else { return nil }\n if _fastPath(c0 != _ascii16("+") && c0 != _ascii16("-")) {\n return _parseUnsignedASCII(\n first: c0, rest: &codeUnits, radix: radix, positive: true)\n }\n let c1_ = codeUnits.next()\n guard _fastPath(c1_ != nil), let c1 = c1_ else { return nil }\n if _fastPath(c0 == _ascii16("-")) {\n return _parseUnsignedASCII(\n first: c1, rest: &codeUnits, radix: radix, positive: false)\n }\n else {\n return _parseUnsignedASCII(\n first: c1, rest: &codeUnits, radix: radix, positive: true)\n }\n}\n\nextension FixedWidthInteger {\n // _parseASCII function thunk that prevents inlining used as an implementation\n // detail for FixedWidthInteger.init(_: radix:) on the slow path to save code\n // size.\n @_semantics("optimize.sil.specialize.generic.partial.never")\n @inline(never)\n @usableFromInline\n internal static func _parseASCIISlowPath<\n CodeUnits: IteratorProtocol, Result: FixedWidthInteger\n >(\n codeUnits: inout CodeUnits, radix: Result\n ) -> Result?\n where CodeUnits.Element: UnsignedInteger {\n return _parseASCII(codeUnits: &codeUnits, radix: radix)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_IntegerParsing.swift
cpp_apple_swift_stdlib_public_core_IntegerParsing.swift
Swift
9,918
0.95
0.098113
0.291498
react-lib
77
2025-06-09T14:44:30.814731
BSD-3-Clause
false
9a339d816e66420f64cbf26591b817c6
//===--- Join.swift - Protocol and Algorithm for concatenation ------------===//\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 that presents the elements of a base sequence of sequences\n/// concatenated using a given separator.\n@frozen // lazy-performance\npublic struct JoinedSequence<Base: Sequence> where Base.Element: Sequence {\n\n public typealias Element = Base.Element.Element\n \n @usableFromInline // lazy-performance\n internal var _base: Base\n @usableFromInline // lazy-performance\n internal var _separator: ContiguousArray<Element>\n\n /// Creates an iterator that presents the elements of the sequences\n /// traversed by `base`, concatenated using `separator`.\n ///\n /// - Complexity: O(`separator.count`).\n @inlinable // lazy-performance\n public init<Separator: Sequence>(base: Base, separator: Separator)\n where Separator.Element == Element {\n self._base = base\n self._separator = ContiguousArray(separator)\n }\n}\n\nextension JoinedSequence: Sendable where Base: Sendable, Element: Sendable {}\n\nextension JoinedSequence {\n /// An iterator that presents the elements of the sequences traversed\n /// by a base iterator, concatenated using a given separator.\n @frozen // lazy-performance\n public struct Iterator {\n @frozen // lazy-performance\n @usableFromInline // lazy-performance\n internal enum _JoinIteratorState {\n case start\n case generatingElements\n case generatingSeparator\n case end\n }\n\n @usableFromInline // lazy-performance\n internal var _base: Base.Iterator\n @usableFromInline // lazy-performance\n internal var _inner: Base.Element.Iterator?\n @usableFromInline // lazy-performance\n internal var _separatorData: ContiguousArray<Element>\n @usableFromInline // lazy-performance\n internal var _separator: ContiguousArray<Element>.Iterator?\n @usableFromInline // lazy-performance\n internal var _state: _JoinIteratorState = .start\n\n /// Creates an iterator that presents the elements of `base` sequences\n /// concatenated using `separator`.\n ///\n /// - Complexity: O(`separator.count`).\n @inlinable // lazy-performance\n public init<Separator: Sequence>(base: Base.Iterator, separator: Separator)\n where Separator.Element == Element {\n self._base = base\n self._separatorData = ContiguousArray(separator)\n }\n }\n}\n\nextension JoinedSequence.Iterator: Sendable\n where Base.Iterator: Sendable,\n Base.Element.Iterator: Sendable,\n Element: Sendable {}\n\nextension JoinedSequence.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 @inlinable // lazy-performance\n public mutating func next() -> Element? {\n while true {\n switch _state {\n case .start:\n if let nextSubSequence = _base.next() {\n _inner = nextSubSequence.makeIterator()\n _state = .generatingElements\n } else {\n _state = .end\n return nil\n }\n\n case .generatingElements:\n let result = _inner!.next()\n if _fastPath(result != nil) {\n return result\n }\n _inner = _base.next()?.makeIterator()\n if _inner == nil {\n _state = .end\n return nil\n }\n if !_separatorData.isEmpty {\n _separator = _separatorData.makeIterator()\n _state = .generatingSeparator\n }\n\n case .generatingSeparator:\n let result = _separator!.next()\n if _fastPath(result != nil) {\n return result\n }\n _state = .generatingElements\n\n case .end:\n return nil\n }\n }\n fatalError()\n }\n}\n\nextension JoinedSequence: Sequence {\n /// Return 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(), separator: _separator)\n }\n\n @inlinable // lazy-performance\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n var result = ContiguousArray<Element>()\n let separatorSize = _separator.count\n\n if separatorSize == 0 {\n for x in _base {\n result.append(contentsOf: x)\n }\n return result\n }\n\n var iter = _base.makeIterator()\n if let first = iter.next() {\n result.append(contentsOf: first)\n while let next = iter.next() {\n result.append(contentsOf: _separator)\n result.append(contentsOf: next)\n }\n }\n\n return result\n }\n}\n \nextension Sequence where Element: Sequence {\n /// Returns the concatenated elements of this sequence of sequences,\n /// inserting the given separator between each element.\n ///\n /// This example shows how an array of `[Int]` instances can be joined, using\n /// another `[Int]` instance as the separator:\n ///\n /// let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n /// let joined = nestedNumbers.joined(separator: [-1, -2])\n /// print(Array(joined))\n /// // Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]"\n ///\n /// - Parameter separator: A sequence to insert between each of this\n /// sequence's elements.\n /// - Returns: The joined sequence of elements.\n @inlinable // lazy-performance\n public __consuming func joined<Separator: Sequence>(\n separator: Separator\n ) -> JoinedSequence<Self>\n where Separator.Element == Element.Element {\n return JoinedSequence(base: self, separator: separator)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Join.swift
cpp_apple_swift_stdlib_public_core_Join.swift
Swift
6,030
0.8
0.079787
0.261905
python-kit
161
2023-07-26T17:53:09.219372
MIT
false
5565e74637cfa091af1a38b85f8d208c
//===--- KeyValuePairs.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/// A lightweight collection of key-value pairs.\n///\n/// Use a `KeyValuePairs` instance when you need an ordered collection of\n/// key-value pairs and don't require the fast key lookup that the\n/// `Dictionary` type provides. Unlike key-value pairs in a true dictionary,\n/// neither the key nor the value of a `KeyValuePairs` instance must\n/// conform to the `Hashable` protocol.\n///\n/// You initialize a `KeyValuePairs` instance using a Swift dictionary\n/// literal. Besides maintaining the order of the original dictionary literal,\n/// `KeyValuePairs` also allows duplicates keys. For example:\n///\n/// let recordTimes: KeyValuePairs = ["Florence Griffith-Joyner": 10.49,\n/// "Evelyn Ashford": 10.76,\n/// "Evelyn Ashford": 10.79,\n/// "Marlies Gohr": 10.81]\n/// print(recordTimes.first!)\n/// // Prints "(key: "Florence Griffith-Joyner", value: 10.49)"\n///\n/// Some operations that are efficient on a dictionary are slower when using\n/// `KeyValuePairs`. In particular, to find the value matching a key, you\n/// must search through every element of the collection. The call to\n/// `firstIndex(where:)` in the following example must traverse the whole\n/// collection to find the element that matches the predicate:\n///\n/// let runner = "Marlies Gohr"\n/// if let index = recordTimes.firstIndex(where: { $0.0 == runner }) {\n/// let time = recordTimes[index].1\n/// print("\(runner) set a 100m record of \(time) seconds.")\n/// } else {\n/// print("\(runner) couldn't be found in the records.")\n/// }\n/// // Prints "Marlies Gohr set a 100m record of 10.81 seconds."\n///\n/// Key-Value Pairs as a Function Parameter\n/// ---------------------------------------\n///\n/// When calling a function with a `KeyValuePairs` parameter, you can pass\n/// a Swift dictionary literal without causing a `Dictionary` to be created.\n/// This capability can be especially important when the order of elements in\n/// the literal is significant.\n///\n/// For example, you could create an `IntPairs` structure that holds a list of\n/// two-integer tuples and use an initializer that accepts a\n/// `KeyValuePairs` instance.\n///\n/// struct IntPairs {\n/// var elements: [(Int, Int)]\n///\n/// init(_ elements: KeyValuePairs<Int, Int>) {\n/// self.elements = Array(elements)\n/// }\n/// }\n///\n/// When you're ready to create a new `IntPairs` instance, use a dictionary\n/// literal as the parameter to the `IntPairs` initializer. The\n/// `KeyValuePairs` instance preserves the order of the elements as\n/// passed.\n///\n/// let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1])\n/// print(pairs.elements)\n/// // Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]"\n@frozen // trivial-implementation\npublic struct KeyValuePairs<Key, Value>: ExpressibleByDictionaryLiteral {\n @usableFromInline // trivial-implementation\n internal let _elements: [(Key, Value)]\n\n /// Creates a new `KeyValuePairs` instance from the given dictionary\n /// literal.\n ///\n /// The order of the key-value pairs is kept intact in the resulting\n /// `KeyValuePairs` instance.\n @inlinable // trivial-implementation\n public init(dictionaryLiteral elements: (Key, Value)...) {\n self._elements = elements\n }\n}\n\n/// `Collection` conformance that allows `KeyValuePairs` to\n/// interoperate with the rest of the standard library.\nextension KeyValuePairs: RandomAccessCollection {\n /// The element type of a `KeyValuePairs`: a tuple containing an\n /// individual key-value pair.\n public typealias Element = (key: Key, value: Value)\n public typealias Index = Int\n public typealias Indices = Range<Int>\n public typealias SubSequence = Slice<KeyValuePairs>\n \n /// The position of the first element in a nonempty collection.\n ///\n /// If the `KeyValuePairs` instance is empty, `startIndex` is equal to\n /// `endIndex`.\n @inlinable // trivial-implementation\n public var startIndex: Index { return 0 }\n\n /// The collection's "past the end" position---that is, the position one\n /// greater than the last valid subscript argument.\n ///\n /// If the `KeyValuePairs` instance is empty, `endIndex` is equal to\n /// `startIndex`.\n @inlinable // trivial-implementation\n public var endIndex: Index { return _elements.endIndex }\n\n /// Accesses the element at the specified position.\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 /// - Returns: The key-value pair at position `position`.\n @inlinable // trivial-implementation\n public subscript(position: Index) -> Element {\n return _elements[position]\n }\n}\n\nextension KeyValuePairs {\n \n @available(SwiftStdlib 6.2, *)\n public var span: Span<Element> {\n @lifetime(borrow self)\n @_alwaysEmitIntoClient\n get {\n let rp = unsafe UnsafeRawPointer(_elements._buffer.firstElementAddress)\n let span = unsafe Span(\n _unsafeStart: unsafe rp.assumingMemoryBound(to: Element.self),\n count: _elements.count\n )\n return unsafe _overrideLifetime(span, borrowing: self)\n }\n }\n}\n\n@_unavailableInEmbedded\nextension KeyValuePairs: CustomStringConvertible {\n /// A string that represents the contents of the dictionary.\n public var description: String {\n return _makeKeyValuePairDescription()\n }\n}\n\n@_unavailableInEmbedded\nextension KeyValuePairs: CustomDebugStringConvertible {\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\nextension KeyValuePairs: Sendable\n where Key: Sendable, Value: Sendable { }\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_KeyValuePairs.swift
cpp_apple_swift_stdlib_public_core_KeyValuePairs.swift
Swift
6,349
0.95
0.030675
0.657895
react-lib
792
2024-02-21T15:25:31.556909
MIT
false
b9f49c2a984909a59887b5aeecf5d6aa
//===--- LazyCollection.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\npublic protocol LazyCollectionProtocol: Collection, LazySequenceProtocol\nwhere Elements: Collection {}\n\nextension LazyCollectionProtocol {\n // Lazy things are already lazy\n @inlinable // protocol-only\n public var lazy: LazyCollection<Elements> {\n return elements.lazy\n }\n }\n\n extension LazyCollectionProtocol where Elements: LazyCollectionProtocol {\n // Lazy things are already lazy\n @inlinable // protocol-only\n public var lazy: Elements {\n return elements\n }\n }\n\n/// A collection containing the same elements as a `Base` collection,\n/// but on which some operations such as `map` and `filter` are\n/// implemented lazily.\n///\n/// - See also: `LazySequenceProtocol`, `LazyCollection`\npublic typealias LazyCollection<T: Collection> = LazySequence<T>\n\nextension LazyCollection: Collection {\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 public typealias Indices = Base.Indices\n public typealias SubSequence = Slice<LazySequence>\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 { return _base.startIndex }\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 { return _base.endIndex }\n\n @inlinable\n public var indices: Indices { return _base.indices }\n\n // TODO: swift-3-indexing-model - add docs\n @inlinable\n public func index(after i: Index) -> Index {\n return _base.index(after: i)\n }\n\n /// Accesses the element at `position`.\n ///\n /// - Precondition: `position` is a valid position in `self` and\n /// `position != endIndex`.\n @inlinable\n public subscript(position: Index) -> Element {\n return _base[position]\n }\n\n /// A Boolean value indicating whether the collection is empty.\n @inlinable\n public var isEmpty: Bool {\n return _base.isEmpty\n }\n\n /// Returns the number of elements.\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 `Self` conforms to `RandomAccessCollection`;\n /// O(*n*) otherwise.\n @inlinable\n public var count: Int {\n return _base.count\n }\n\n // The following requirement enables 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 /// `Optional(nil)` if the element doesn't exist in the collection;\n /// `nil` if a search was not performed.\n ///\n /// - Complexity: Better than O(*n*)\n @inlinable\n public func _customIndexOfEquatableElement(\n _ element: Element\n ) -> Index?? {\n return _base._customIndexOfEquatableElement(element)\n }\n\n /// Returns `Optional(Optional(index))` if an element was found;\n /// `Optional(nil)` if the element doesn't exist in the collection;\n /// `nil` if a search was not performed.\n ///\n /// - Complexity: Better than O(*n*)\n @inlinable\n public func _customLastIndexOfEquatableElement(\n _ element: Element\n ) -> Index?? {\n return _base._customLastIndexOfEquatableElement(element)\n }\n\n // TODO: swift-3-indexing-model - add docs\n @inlinable\n public func index(_ i: Index, offsetBy n: Int) -> Index {\n return _base.index(i, offsetBy: n)\n }\n\n // TODO: swift-3-indexing-model - add docs\n @inlinable\n public func index(\n _ i: Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Index? {\n return _base.index(i, offsetBy: n, limitedBy: limit)\n }\n\n // TODO: swift-3-indexing-model - add docs\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n return _base.distance(from:start, to: end)\n }\n}\n\nextension LazyCollection: LazyCollectionProtocol { }\n\nextension LazyCollection: BidirectionalCollection\n where Base: BidirectionalCollection {\n @inlinable\n public func index(before i: Index) -> Index {\n return _base.index(before: i)\n }\n}\n\nextension LazyCollection: RandomAccessCollection\n where Base: RandomAccessCollection {}\n\nextension Slice: LazySequenceProtocol where Base: LazySequenceProtocol { }\nextension ReversedCollection: LazySequenceProtocol where Base: LazySequenceProtocol { }\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_LazyCollection.swift
cpp_apple_swift_stdlib_public_core_LazyCollection.swift
Swift
5,200
0.95
0.067901
0.428571
react-lib
803
2024-09-30T12:57:52.202260
MIT
false
d7faa794e6b13c3752537e08c9c780c1
//===--- LazySequence.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 on which normally-eager sequence operations are implemented\n/// lazily.\n///\n/// Lazy sequences can be used to avoid needless storage allocation\n/// and computation, because they use an underlying sequence for\n/// storage and compute their elements on demand. For example, `doubled` in\n/// this code sample is a sequence containing the values `2`, `4`, and `6`.\n///\n/// let doubled = [1, 2, 3].lazy.map { $0 * 2 }\n///\n/// Each time an element of the lazy sequence `doubled` is accessed, the \n/// closure accesses and transforms an element of the underlying array.\n///\n/// Sequence operations that take closure arguments, such as `map(_:)` and\n/// `filter(_:)`, are normally eager: They use the closure immediately and\n/// return a new array. When you use the `lazy` property, you give the standard\n/// library explicit permission to store the closure and the sequence\n/// in the result, and defer computation until it is needed.\n///\n/// ## Adding New Lazy Operations\n///\n/// To add a new lazy sequence operation, extend this protocol with\n/// a method that returns a lazy wrapper that itself conforms to\n/// `LazySequenceProtocol`. For example, an eager `scan(_:_:)`\n/// method is defined as follows:\n///\n/// extension Sequence {\n/// /// Returns an array containing the results of\n/// ///\n/// /// p.reduce(initial, nextPartialResult)\n/// ///\n/// /// for each prefix `p` of `self`, in order from shortest to\n/// /// longest. For example:\n/// ///\n/// /// (1..<6).scan(0, +) // [0, 1, 3, 6, 10, 15]\n/// ///\n/// /// - Complexity: O(n)\n/// func scan<Result>(\n/// _ initial: Result,\n/// _ nextPartialResult: (Result, Element) -> Result\n/// ) -> [Result] {\n/// var result = [initial]\n/// for x in self {\n/// result.append(nextPartialResult(result.last!, x))\n/// }\n/// return result\n/// }\n/// }\n///\n/// You can build a sequence type that lazily computes the elements in the\n/// result of a scan:\n///\n/// struct LazyScanSequence<Base: Sequence, Result>\n/// : LazySequenceProtocol\n/// {\n/// let initial: Result\n/// let base: Base\n/// let nextPartialResult:\n/// (Result, Base.Element) -> Result\n///\n/// struct Iterator: IteratorProtocol {\n/// var base: Base.Iterator\n/// var nextElement: Result?\n/// let nextPartialResult:\n/// (Result, Base.Element) -> Result\n/// \n/// mutating func next() -> Result? {\n/// return nextElement.map { result in\n/// nextElement = base.next().map {\n/// nextPartialResult(result, $0)\n/// }\n/// return result\n/// }\n/// }\n/// }\n/// \n/// func makeIterator() -> Iterator {\n/// return Iterator(\n/// base: base.makeIterator(),\n/// nextElement: initial as Result?,\n/// nextPartialResult: nextPartialResult)\n/// }\n/// }\n///\n/// Finally, you can give all lazy sequences a lazy `scan(_:_:)` method:\n/// \n/// extension LazySequenceProtocol {\n/// func scan<Result>(\n/// _ initial: Result,\n/// _ nextPartialResult: @escaping (Result, Element) -> Result\n/// ) -> LazyScanSequence<Self, Result> {\n/// return LazyScanSequence(\n/// initial: initial, base: self, nextPartialResult: nextPartialResult)\n/// }\n/// }\n///\n/// With this type and extension method, you can call `.lazy.scan(_:_:)` on any\n/// sequence to create a lazily computed scan. The resulting `LazyScanSequence`\n/// is itself lazy, too, so further sequence operations also defer computation.\n///\n/// The explicit permission to implement operations lazily applies \n/// only in contexts where the sequence is statically known to conform to\n/// `LazySequenceProtocol`. In the following example, because the extension \n/// applies only to `Sequence`, side-effects such as the accumulation of\n/// `result` are never unexpectedly dropped or deferred:\n///\n/// extension Sequence where Element == Int {\n/// func sum() -> Int {\n/// var result = 0\n/// _ = self.map { result += $0 }\n/// return result\n/// }\n/// }\n///\n/// Don't actually use `map` for this purpose, however, because it creates \n/// and discards the resulting array. Instead, use `reduce` for summing \n/// operations, or `forEach` or a `for`-`in` loop for operations with side \n/// effects.\npublic protocol LazySequenceProtocol: Sequence {\n /// A `Sequence` that can contain the same elements as this one,\n /// possibly with a simpler type.\n ///\n /// - See also: `elements`\n associatedtype Elements: Sequence = Self where Elements.Element == Element\n\n /// A sequence containing the same elements as this one, possibly with\n /// a simpler type.\n ///\n /// When implementing lazy operations, wrapping `elements` instead of `self`\n /// can prevent result types from growing an extra `LazySequence` layer.\n ///\n /// Note: this property need not be implemented by conforming types,\n /// it has a default implementation in a protocol extension that\n /// just returns `self`.\n var elements: Elements { get }\n}\n\n/// When there's no special associated `Elements` type, the `elements`\n/// property is provided.\nextension LazySequenceProtocol where Elements == Self {\n /// Identical to `self`.\n @inlinable // protocol-only\n public var elements: Self { return self }\n}\n\nextension LazySequenceProtocol {\n @inlinable // protocol-only\n public var lazy: LazySequence<Elements> {\n return elements.lazy\n }\n}\n\nextension LazySequenceProtocol where Elements: LazySequenceProtocol {\n @inlinable // protocol-only\n public var lazy: Elements {\n return elements\n }\n}\n\n/// A sequence containing the same elements as a `Base` sequence, but\n/// on which some operations such as `map` and `filter` are\n/// implemented lazily.\n///\n/// - See also: `LazySequenceProtocol`\n@frozen // lazy-performance\npublic struct LazySequence<Base: Sequence> {\n @usableFromInline\n internal var _base: Base\n\n /// Creates a sequence that has the same elements as `base`, but on\n /// which some operations such as `map` and `filter` are implemented\n /// lazily.\n @inlinable // lazy-performance\n internal init(_base: Base) {\n self._base = _base\n }\n}\n\nextension LazySequence: Sendable where Base: Sendable {}\n\nextension LazySequence: Sequence {\n public typealias Element = Base.Element\n public typealias Iterator = Base.Iterator\n\n @inlinable\n public __consuming func makeIterator() -> Iterator {\n return _base.makeIterator()\n }\n \n @inlinable // lazy-performance\n public var underestimatedCount: Int {\n return _base.underestimatedCount\n }\n\n @inlinable // lazy-performance\n @discardableResult\n public __consuming func _copyContents(\n initializing buf: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {\n return unsafe _base._copyContents(initializing: buf)\n }\n\n @inlinable // lazy-performance\n public func _customContainsEquatableElement(_ element: Element) -> Bool? { \n return _base._customContainsEquatableElement(element)\n }\n \n @inlinable // generic-performance\n public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n return _base._copyToContiguousArray()\n }\n}\n\nextension LazySequence: LazySequenceProtocol {\n public typealias Elements = Base\n\n /// The `Base` (presumably non-lazy) sequence from which `self` was created.\n @inlinable // lazy-performance\n public var elements: Elements { return _base }\n}\n\nextension Sequence {\n /// A sequence containing the same elements as this sequence,\n /// but on which some operations, such as `map` and `filter`, are\n /// implemented lazily.\n @inlinable // protocol-only\n public var lazy: LazySequence<Self> {\n return LazySequence(_base: self)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_LazySequence.swift
cpp_apple_swift_stdlib_public_core_LazySequence.swift
Swift
8,669
0.8
0.03719
0.697778
vue-tools
138
2025-02-27T17:58:36.963423
MIT
false
a043e5b3a3f949c37201cc7c50fefc29
//===----------------------------------------------------------------------===//\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// This file contains non-API (or underscored) declarations that are needed to\n// be kept around for ABI compatibility\n\nextension Unicode.UTF16 {\n @available(*, unavailable, renamed: "Unicode.UTF16.isASCII")\n @inlinable\n public static func _isASCII(_ x: CodeUnit) -> Bool {\n return Unicode.UTF16.isASCII(x)\n }\n}\n\n@available(*, unavailable, renamed: "Unicode.UTF8.isASCII")\n@inlinable\ninternal func _isASCII(_ x: UInt8) -> Bool {\n return Unicode.UTF8.isASCII(x)\n}\n\n@available(*, unavailable, renamed: "Unicode.UTF8.isContinuation")\n@inlinable\ninternal func _isContinuation(_ x: UInt8) -> Bool {\n return UTF8.isContinuation(x)\n}\n\nextension Substring {\n@available(*, unavailable, renamed: "Substring.base")\n @inlinable\n internal var _wholeString: String { return base }\n}\n\nextension String {\n @available(*, unavailable, renamed: "String.withUTF8")\n @inlinable\n internal func _withUTF8<R>(\n _ body: (UnsafeBufferPointer<UInt8>) throws -> R\n ) rethrows -> R {\n var copy = self\n return try copy.withUTF8(body)\n }\n}\n\nextension Substring {\n @available(*, unavailable, renamed: "Substring.withUTF8")\n @inlinable\n internal func _withUTF8<R>(\n _ body: (UnsafeBufferPointer<UInt8>) throws -> R\n ) rethrows -> R {\n var copy = self\n return try copy.withUTF8(body)\n }\n}\n\n// This function is no longer used but must be kept for ABI compatibility\n// because references to it may have been inlined.\n@usableFromInline\ninternal func _branchHint(_ actual: Bool, expected: Bool) -> Bool {\n // The LLVM intrinsic underlying int_expect_Int1 now requires an immediate\n // argument for the expected value so we cannot call it here. This should\n // never be called in cases where performance matters, so just return the\n // value without any branch hint.\n return actual\n}\n\nextension String {\n @usableFromInline // Never actually used in inlinable code...\n internal func _nativeCopyUTF16CodeUnits(\n into buffer: UnsafeMutableBufferPointer<UInt16>,\n range: Range<String.Index>\n ) { fatalError() }\n}\n\nextension String.UTF16View {\n // Swift 5.x: This was accidentally shipped as inlinable, but was never used\n // from an inlinable context. The definition is kept around for technical ABI\n // compatibility (even though it shouldn't matter), but is unused.\n @inlinable @inline(__always)\n internal var _shortHeuristic: Int { return 32 }\n}\n\n@usableFromInline\ninternal func unimplemented_utf8_32bit(\n _ message: String = "",\n file: StaticString = #file, line: UInt = #line\n) -> Never {\n fatalError("32-bit: Unimplemented for UTF-8 support", file: file, line: line)\n}\n\n@usableFromInline\ninternal func _unsafePlus(_ lhs: Int, _ rhs: Int) -> Int {\n#if INTERNAL_CHECKS_ENABLED\n return lhs + rhs\n#else\n return lhs &+ rhs\n#endif\n}\n\n@usableFromInline\ninternal func _unsafeMinus(_ lhs: Int, _ rhs: Int) -> Int {\n#if INTERNAL_CHECKS_ENABLED\n return lhs - rhs\n#else\n return lhs &- rhs\n#endif\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_LegacyABI.swift
cpp_apple_swift_stdlib_public_core_LegacyABI.swift
Swift
3,435
0.95
0.104348
0.27451
react-lib
828
2025-06-28T22:39:45.762345
MIT
false
d18cca6dd7c2d61884b33f65efe851e3
//===----------------------------------------------------------------------===//\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/// Extends the lifetime of the given instance.\n///\n/// - Parameters:\n/// - x: An instance to preserve until this function returns.\n@_alwaysEmitIntoClient\npublic func extendLifetime<T: ~Copyable & ~Escapable>(\n _ x: borrowing T\n) {\n Builtin.fixLifetime(x)\n}\n\n/// Evaluates a closure while ensuring that the given instance is not destroyed\n/// before the closure returns.\n///\n/// - Parameters:\n/// - x: An instance to preserve until the execution of `body` is completed.\n/// - body: A closure to execute that depends on the lifetime of `x` being\n/// extended. If `body` has a return value, that value is also used as the\n/// return value for the `withExtendedLifetime(_:_:)` method.\n/// - Returns: The return value, if any, of the `body` closure parameter.\n@_alwaysEmitIntoClient\npublic func withExtendedLifetime<\n T: ~Copyable & ~Escapable,\n E: Error,\n Result: ~Copyable\n>(\n _ x: borrowing T,\n _ body: () throws(E) -> Result\n) throws(E) -> Result {\n defer { _fixLifetime(x) }\n return try body()\n}\n\n@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n@_silgen_name("$ss20withExtendedLifetimeyq_x_q_yKXEtKr0_lF")\n@usableFromInline\ninternal func __abi_withExtendedLifetime<T, Result>(\n _ x: T,\n _ body: () throws -> Result\n) rethrows -> Result {\n defer { _fixLifetime(x) }\n return try body()\n}\n\n/// Evaluates a closure while ensuring that the given instance is not destroyed\n/// before the closure returns.\n///\n/// - Parameters:\n/// - x: An instance to preserve until the execution of `body` is completed.\n/// - body: A closure to execute that depends on the lifetime of `x` being\n/// extended. If `body` has a return value, that value is also used as the\n/// return value for the `withExtendedLifetime(_:_:)` method.\n/// - Returns: The return value, if any, of the `body` closure parameter.\n@_alwaysEmitIntoClient\npublic func withExtendedLifetime<\n T: ~Copyable & ~Escapable,\n E: Error,\n Result: ~Copyable\n>(\n _ x: borrowing T,\n _ body: (borrowing T) throws(E) -> Result\n) throws(E) -> Result {\n defer { _fixLifetime(x) }\n return try body(x)\n}\n\n@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n@_silgen_name("$ss20withExtendedLifetimeyq_x_q_xKXEtKr0_lF")\n@usableFromInline\ninternal func __abi_withExtendedLifetime<T, Result>(\n _ x: T, _ body: (T) throws -> Result\n) rethrows -> Result {\n defer { _fixLifetime(x) }\n return try body(x)\n}\n\n// Fix the lifetime of the given instruction so that the ARC optimizer does not\n// shorten the lifetime of x to be before this point.\n@_transparent\n@_preInverseGenerics\npublic func _fixLifetime<T: ~Copyable & ~Escapable>(_ x: borrowing T) {\n Builtin.fixLifetime(x)\n}\n\n/// Calls the given closure with a mutable pointer to the given argument.\n///\n/// The `withUnsafeMutablePointer(to:_:)` function is useful for calling\n/// Objective-C APIs that take in/out parameters (and default-constructible\n/// out parameters) by pointer.\n///\n/// The pointer argument to `body` is valid only during the execution of\n/// `withUnsafeMutablePointer(to:_:)`. Do not store or return the pointer for\n/// later use.\n///\n/// - Parameters:\n/// - value: An instance to temporarily use via pointer. Note that the `inout`\n/// exclusivity rules mean that, like any other `inout` argument, `value`\n/// cannot be directly accessed by other code for the duration of `body`.\n/// Access must only occur through the pointer argument to `body` until\n/// `body` returns.\n/// - body: A closure that takes a mutable pointer to `value` as its sole\n/// argument. If the closure has a return value, that value is also used\n/// as the return value of the `withUnsafeMutablePointer(to:_:)` function.\n/// The pointer argument is valid only for the duration of the function's\n/// execution.\n/// - Returns: The return value, if any, of the `body` closure.\n@_alwaysEmitIntoClient\npublic func withUnsafeMutablePointer<\n T: ~Copyable, E: Error, Result: ~Copyable\n>(\n to value: inout T,\n _ body: (UnsafeMutablePointer<T>) throws(E) -> Result\n) throws(E) -> Result {\n try unsafe body(UnsafeMutablePointer<T>(Builtin.addressof(&value)))\n}\n\n@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n@_silgen_name("$ss24withUnsafeMutablePointer2to_q_xz_q_SpyxGKXEtKr0_lF")\n@usableFromInline\ninternal func __abi_se0413_withUnsafeMutablePointer<T, Result>(\n to value: inout T,\n _ body: (UnsafeMutablePointer<T>) throws -> Result\n) throws -> Result {\n return try unsafe body(UnsafeMutablePointer<T>(Builtin.addressof(&value)))\n}\n\n/// Calls the given closure with a mutable pointer to the given argument.\n///\n/// This function is similar to `withUnsafeMutablePointer`, except that it\n/// doesn't trigger stack protection for the pointer.\n@_alwaysEmitIntoClient\npublic func _withUnprotectedUnsafeMutablePointer<\n T: ~Copyable, E: Error, Result: ~Copyable\n>(\n to value: inout T,\n _ body: (UnsafeMutablePointer<T>) throws(E) -> Result\n) throws(E) -> Result\n{\n#if $BuiltinUnprotectedAddressOf\n return try unsafe body(UnsafeMutablePointer<T>(Builtin.unprotectedAddressOf(&value)))\n#else\n return try body(UnsafeMutablePointer<T>(Builtin.addressof(&value)))\n#endif\n}\n\n/// Invokes the given closure with a pointer to the given argument.\n///\n/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C\n/// APIs that take in parameters by const pointer.\n///\n/// The pointer argument to `body` is valid only during the execution of\n/// `withUnsafePointer(to:_:)`. Do not store or return the pointer for later\n/// use.\n///\n/// - Parameters:\n/// - value: An instance to temporarily use via pointer.\n/// - body: A closure that takes a pointer to `value` as its sole argument. If\n/// the closure has a return value, that value is also used as the return\n/// value of the `withUnsafePointer(to:_:)` function. The pointer argument\n/// is valid only for the duration of the function's execution.\n/// It is undefined behavior to try to mutate through the pointer argument\n/// by converting it to `UnsafeMutablePointer` or any other mutable pointer\n/// type. If you need to mutate the argument through the pointer, use\n/// `withUnsafeMutablePointer(to:_:)` instead.\n/// - Returns: The return value, if any, of the `body` closure.\n@_alwaysEmitIntoClient\npublic func withUnsafePointer<T: ~Copyable, E: Error, Result: ~Copyable>(\n to value: borrowing T,\n _ body: (UnsafePointer<T>) throws(E) -> Result\n) throws(E) -> Result\n{\n return try unsafe body(UnsafePointer<T>(Builtin.addressOfBorrow(value)))\n}\n\n/// ABI: Historical withUnsafePointer(to:_:) rethrows, expressed as "throws",\n/// which is ABI-compatible with "rethrows".\n@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n@_silgen_name("$ss17withUnsafePointer2to_q_x_q_SPyxGKXEtKr0_lF")\n@usableFromInline\ninternal func __abi_withUnsafePointer<T, Result>(\n to value: T,\n _ body: (UnsafePointer<T>) throws -> Result\n) throws -> Result\n{\n return try unsafe body(UnsafePointer<T>(Builtin.addressOfBorrow(value)))\n}\n\n/// Invokes the given closure with a pointer to the given argument.\n///\n/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C\n/// APIs that take in parameters by const pointer.\n///\n/// The pointer argument to `body` is valid only during the execution of\n/// `withUnsafePointer(to:_:)`. Do not store or return the pointer for later\n/// use.\n///\n/// - Parameters:\n/// - value: An instance to temporarily use via pointer. Note that the `inout`\n/// exclusivity rules mean that, like any other `inout` argument, `value`\n/// cannot be directly accessed by other code for the duration of `body`.\n/// Access must only occur through the pointer argument to `body` until\n/// `body` returns.\n/// - body: A closure that takes a pointer to `value` as its sole argument. If\n/// the closure has a return value, that value is also used as the return\n/// value of the `withUnsafePointer(to:_:)` function. The pointer argument\n/// is valid only for the duration of the function's execution.\n/// It is undefined behavior to try to mutate through the pointer argument\n/// by converting it to `UnsafeMutablePointer` or any other mutable pointer\n/// type. If you need to mutate the argument through the pointer, use\n/// `withUnsafeMutablePointer(to:_:)` instead.\n/// - Returns: The return value, if any, of the `body` closure.\n@_alwaysEmitIntoClient\npublic func withUnsafePointer<T: ~Copyable, E: Error, Result: ~Copyable>(\n to value: inout T,\n _ body: (UnsafePointer<T>) throws(E) -> Result\n) throws(E) -> Result {\n try unsafe body(UnsafePointer<T>(Builtin.addressof(&value)))\n}\n\n/// ABI: Historical withUnsafePointer(to:_:) rethrows,\n/// expressed as "throws", which is ABI-compatible with "rethrows".\n@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n@_silgen_name("$ss17withUnsafePointer2to_q_xz_q_SPyxGKXEtKr0_lF")\n@usableFromInline\ninternal func __abi_se0413_withUnsafePointer<T, Result>(\n to value: inout T,\n _ body: (UnsafePointer<T>) throws -> Result\n) throws -> Result {\n return try unsafe body(UnsafePointer<T>(Builtin.addressof(&value)))\n}\n\n/// Invokes the given closure with a pointer to the given argument.\n///\n/// This function is similar to `withUnsafePointer`, except that it\n/// doesn't trigger stack protection for the pointer.\n@_alwaysEmitIntoClient\npublic func _withUnprotectedUnsafePointer<\n T: ~Copyable, E: Error, Result: ~Copyable\n>(\n to value: inout T,\n _ body: (UnsafePointer<T>) throws(E) -> Result\n) throws(E) -> Result {\n#if $BuiltinUnprotectedAddressOf\n return try unsafe body(UnsafePointer<T>(Builtin.unprotectedAddressOf(&value)))\n#else\n return try body(UnsafePointer<T>(Builtin.addressof(&value)))\n#endif\n}\n\n/// Invokes the given closure with a pointer to the given argument.\n///\n/// This function is similar to `withUnsafePointer`, except that it\n/// doesn't trigger stack protection for the pointer.\n@_alwaysEmitIntoClient\npublic func _withUnprotectedUnsafePointer<\n T: ~Copyable, E: Error, Result: ~Copyable\n>(\n to value: borrowing T,\n _ body: (UnsafePointer<T>) throws(E) -> Result\n) throws(E) -> Result {\n return try unsafe body(UnsafePointer<T>(Builtin.unprotectedAddressOfBorrow(value)))\n}\n\n@available(*, deprecated, message: "Use the copy operator")\n@_alwaysEmitIntoClient\n@inlinable\n@_transparent\n@_semantics("lifetimemanagement.copy")\npublic func _copy<T>(_ value: T) -> T {\n copy value\n}\n\n/// Unsafely discard any lifetime dependency on the `dependent` argument. Return\n/// a value identical to `dependent` with a lifetime dependency on the caller's\n/// borrow scope of the `source` argument.\n@unsafe\n@_unsafeNonescapableResult\n@_alwaysEmitIntoClient\n@_transparent\n@lifetime(borrow source)\ninternal func _overrideLifetime<\n T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable\n>(\n _ dependent: consuming T, borrowing source: borrowing U\n) -> T {\n // TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence\n // should be expressed by a builtin that is hidden within the function body.\n dependent\n}\n\n/// Unsafely discard any lifetime dependency on the `dependent` argument. Return\n/// a value identical to `dependent` that inherits all lifetime dependencies from\n/// the `source` argument.\n@unsafe\n@_unsafeNonescapableResult\n@_alwaysEmitIntoClient\n@_transparent\n@lifetime(copy source)\ninternal func _overrideLifetime<\n T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable\n>(\n _ dependent: consuming T, copying source: borrowing U\n) -> T {\n // TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence\n // should be expressed by a builtin that is hidden within the function body.\n dependent\n}\n\n/// Unsafely discard any lifetime dependency on the `dependent` argument.\n/// Return a value identical to `dependent` with a lifetime dependency\n/// on the caller's exclusive borrow scope of the `source` argument.\n@unsafe\n@_unsafeNonescapableResult\n@_alwaysEmitIntoClient\n@_transparent\n@lifetime(&source)\ninternal func _overrideLifetime<\n T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable\n>(\n _ dependent: consuming T,\n mutating source: inout U\n) -> T {\n // TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence\n // should be expressed by a builtin that is hidden within the function body.\n dependent\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_LifetimeManager.swift
cpp_apple_swift_stdlib_public_core_LifetimeManager.swift
Swift
12,810
0.95
0.177515
0.432602
vue-tools
541
2024-12-02T04:13:16.163979
GPL-3.0
false
93642defbc0b645ebfd7c762afb4087c
//===----------------------------------------------------------------------===//\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 $Macros && hasAttribute(attached)\n\n/// Specifies the module and type name for an externally-defined macro, which\n/// must conform to the appropriate set of `Macro` protocols.\n///\n/// This macro can only be used to define other macros. For example:\n///\n/// macro stringify<T>(_ value: T) -> (T, String) =\n/// #externalMacro(module: "ExampleMacros", type :"StringifyMacro")\n///\n/// Use of this macro in any other context is an error.\n@freestanding(expression)\npublic macro externalMacro<T>(module: String, type: String) -> T =\n Builtin.ExternalMacro\n\n// File and path-related information\n\n/// Produces a unique identifier for the given source file, comprised of\n/// the module and file name.\n@freestanding(expression)\npublic macro fileID<T: ExpressibleByStringLiteral>() -> T =\n Builtin.FileIDMacro\n\n/// Produces the complete path for the given source file.\n@freestanding(expression)\npublic macro filePath<T: ExpressibleByStringLiteral>() -> T =\n Builtin.FilePathMacro\n\n/// Produces either the result of `#filePath` or `#file`, depending\n/// on whether concise file paths (SE-0274) are enabled.\n@freestanding(expression)\npublic macro file<T: ExpressibleByStringLiteral>() -> T =\n Builtin.FileMacro\n\n/// Produces a string representation of the current function name.\n@freestanding(expression)\npublic macro function<T: ExpressibleByStringLiteral>() -> T =\n Builtin.FunctionMacro\n\n/// Produces the line number at which the macro is expanded.\n@freestanding(expression)\npublic macro line<T: ExpressibleByIntegerLiteral>() -> T =\n Builtin.LineMacro\n\n/// Produces the column number at which the macro is expanded.\n@freestanding(expression)\npublic macro column<T: ExpressibleByIntegerLiteral>() -> T =\n Builtin.ColumnMacro\n\n/// Produces the shared object handle for the macro expansion location.\n@freestanding(expression)\npublic macro dsohandle() -> UnsafeRawPointer = Builtin.DSOHandleMacro\n\n/// Produce the given warning message during compilation.\n@freestanding(declaration)\npublic macro warning(_ message: String) = Builtin.WarningMacro\n\n/// Produce the given error message during compilation.\n@freestanding(declaration)\npublic macro error(_ message: String) = Builtin.ErrorMacro\n\n#endif // $Macros && hasAttribute(attached)\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Macros.swift
cpp_apple_swift_stdlib_public_core_Macros.swift
Swift
2,760
0.95
0.121622
0.557377
awesome-app
311
2024-04-22T05:26:02.809152
GPL-3.0
false
7352db816069aa5cf856fb881b17dbf3
//===--- ManagedBuffer.swift - variable-sized buffer of aligned memory ----===//\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\nimport SwiftShims\n\n@usableFromInline\ninternal typealias _HeapObject = SwiftShims.HeapObject\n\n@usableFromInline\n@_silgen_name("swift_bufferAllocate")\ninternal func _swift_bufferAllocate(\n bufferType type: AnyClass,\n size: Int,\n alignmentMask: Int\n) -> AnyObject\n\n/// A class whose instances contain a property of type `Header` and raw\n/// storage for an array of `Element`, whose size is determined at\n/// instance creation.\n///\n/// Note that the `Element` array is suitably-aligned **raw memory**.\n/// You are expected to construct and---if necessary---destroy objects\n/// there yourself, using the APIs on `UnsafeMutablePointer<Element>`.\n/// Typical usage stores a count and capacity in `Header` and destroys\n/// any live elements in the `deinit` of a subclass.\n/// - Note: Subclasses must not have any stored properties; any storage\n/// needed should be included in `Header`.\n@_fixed_layout\nopen class ManagedBuffer<Header, Element: ~Copyable> {\n /// The stored `Header` instance.\n ///\n /// During instance creation, in particular during\n /// `ManagedBuffer.create`'s call to initialize, `ManagedBuffer`'s\n /// `header` property is as-yet uninitialized, and therefore\n /// reading the `header` property during `ManagedBuffer.create` is undefined.\n @_preInverseGenerics\n public final var header: Header\n\n #if $Embedded\n // In embedded mode this initializer has to be public, otherwise derived\n // classes cannot be specialized.\n @_preInverseGenerics\n public init(_doNotCallMe: ()) {\n _internalInvariantFailure("Only initialize these by calling create")\n }\n #else\n // This is really unfortunate. In Swift 5.0, the method descriptor for this\n // initializer was public and subclasses would "inherit" it, referencing its\n // method descriptor from their class override table.\n @_preInverseGenerics\n @usableFromInline\n internal init(_doNotCallMe: ()) {\n _internalInvariantFailure("Only initialize these by calling create")\n }\n #endif\n\n @_preInverseGenerics\n @inlinable\n deinit {}\n}\n\n@available(*, unavailable)\nextension ManagedBuffer: Sendable where Element: ~Copyable {}\n\nextension ManagedBuffer where Element: ~Copyable {\n /// Create a new instance of the most-derived class, calling\n /// `factory` on the partially-constructed object to generate\n /// an initial `Header`.\n @_preInverseGenerics\n @inlinable\n #if $Embedded\n // Transparent in Embedded Swift to avoid needing "self" as a metatype. By\n // inlining into the caller, we'll know the concrete type instead.\n @_transparent\n #endif\n public final class func create(\n minimumCapacity: Int,\n makingHeaderWith factory: (ManagedBuffer<Header, Element>) throws -> Header\n ) rethrows -> ManagedBuffer<Header, Element> {\n let p = Builtin.allocWithTailElems_1(\n self,\n minimumCapacity._builtinWordValue, Element.self)\n\n let initHeaderVal = try factory(p)\n unsafe p.headerAddress.initialize(to: initHeaderVal)\n // The _fixLifetime is not really needed, because p is used afterwards.\n // But let's be conservative and fix the lifetime after we use the\n // headerAddress.\n _fixLifetime(p)\n return p\n }\n\n /// The actual number of elements that can be stored in this object.\n ///\n /// This header may be nontrivial to compute; it is usually a good\n /// idea to store this information in the "header" area when\n /// an instance is created.\n @_preInverseGenerics\n @inlinable\n @available(OpenBSD, unavailable, message: "malloc_size is unavailable.")\n public final var capacity: Int {\n let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(self))\n let endAddr = unsafe storageAddr + _swift_stdlib_malloc_size(storageAddr)\n let realCapacity = unsafe endAddr.assumingMemoryBound(to: Element.self) -\n firstElementAddress\n return realCapacity\n }\n\n @_preInverseGenerics\n @inlinable\n internal final var firstElementAddress: UnsafeMutablePointer<Element> {\n return unsafe UnsafeMutablePointer(\n Builtin.projectTailElems(self, Element.self))\n }\n\n @_preInverseGenerics\n @inlinable\n internal final var headerAddress: UnsafeMutablePointer<Header> {\n return unsafe UnsafeMutablePointer<Header>(Builtin.addressof(&header))\n }\n}\n\nextension ManagedBuffer where Element: ~Copyable {\n /// Call `body` with an `UnsafeMutablePointer` to the stored\n /// `Header`.\n ///\n /// - Note: This pointer is valid only for the duration of the\n /// call to `body`.\n @_alwaysEmitIntoClient\n @inline(__always)\n public final func withUnsafeMutablePointerToHeader<E: Error, R: ~Copyable>(\n _ body: (UnsafeMutablePointer<Header>) throws(E) -> R\n ) throws(E) -> R {\n try unsafe withUnsafeMutablePointers { (v, _) throws(E) in try unsafe body(v) }\n }\n\n /// Call `body` with an `UnsafeMutablePointer` to the `Element`\n /// storage.\n ///\n /// - Note: This pointer is valid only for the duration of the\n /// call to `body`.\n @_alwaysEmitIntoClient\n @inline(__always)\n public final func withUnsafeMutablePointerToElements<E: Error, R: ~Copyable>(\n _ body: (UnsafeMutablePointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n try unsafe withUnsafeMutablePointers { (_, v) throws(E) in try unsafe body(v) }\n }\n\n /// Call `body` with `UnsafeMutablePointer`s to the stored `Header`\n /// and raw `Element` storage.\n ///\n /// - Note: These pointers are valid only for the duration of the\n /// call to `body`.\n @_alwaysEmitIntoClient\n @inline(__always)\n public final func withUnsafeMutablePointers<E: Error, R: ~Copyable>(\n _ body: (\n UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>\n ) throws(E) -> R\n ) throws(E) -> R {\n defer { _fixLifetime(self) }\n return try unsafe body(headerAddress, firstElementAddress)\n }\n}\n\nextension ManagedBuffer {\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @_silgen_name("$ss13ManagedBufferC32withUnsafeMutablePointerToHeaderyqd__qd__SpyxGKXEKlF")\n @usableFromInline\n internal final func __legacy_withUnsafeMutablePointerToHeader<R>(\n _ body: (UnsafeMutablePointer<Header>) throws -> R\n ) rethrows -> R {\n return try unsafe withUnsafeMutablePointers { (v, _) in return try unsafe body(v) }\n }\n\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @_silgen_name("$ss13ManagedBufferC34withUnsafeMutablePointerToElementsyqd__qd__Spyq_GKXEKlF")\n @usableFromInline\n internal final func __legacy_withUnsafeMutablePointerToElements<R>(\n _ body: (UnsafeMutablePointer<Element>) throws -> R\n ) rethrows -> R {\n return try unsafe withUnsafeMutablePointers { return try unsafe body($1) }\n }\n\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @_silgen_name("$ss13ManagedBufferC25withUnsafeMutablePointersyqd__qd__SpyxG_Spyq_GtKXEKlF")\n @usableFromInline\n internal final func __legacy_withUnsafeMutablePointers<R>(\n _ body: (\n UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>\n ) throws -> R\n ) rethrows -> R {\n defer { _fixLifetime(self) }\n return try unsafe body(headerAddress, firstElementAddress)\n }\n}\n\n/// Contains a buffer object, and provides access to an instance of\n/// `Header` and contiguous storage for an arbitrary number of\n/// `Element` instances stored in that buffer.\n///\n/// For most purposes, the `ManagedBuffer` class can be used on its own.\n/// However, in cases\n/// where objects of various different classes must serve as storage,\n/// you need to also use `ManagedBufferPointer`.\n///\n/// A valid buffer class is non-`@objc`, with no declared stored\n/// properties. Its `deinit` must destroy its\n/// stored `Header` and any constructed `Element`s.\n///\n/// Example Buffer Class\n/// --------------------\n///\n/// class MyBuffer<Element> { // non-@objc\n/// typealias Manager = ManagedBufferPointer<(Int, String), Element>\n/// deinit {\n/// Manager(unsafeBufferObject: self).withUnsafeMutablePointers {\n/// (pointerToHeader, pointerToElements) -> Void in\n/// pointerToElements.deinitialize(count: self.count)\n/// pointerToHeader.deinitialize(count: 1)\n/// }\n/// }\n///\n/// // All properties are *computed* based on members of the Header\n/// var count: Int {\n/// return Manager(unsafeBufferObject: self).header.0\n/// }\n/// var name: String {\n/// return Manager(unsafeBufferObject: self).header.1\n/// }\n/// }\n///\n@frozen\npublic struct ManagedBufferPointer<\n Header,\n Element: ~Copyable\n>: Copyable {\n\n @_preInverseGenerics\n @usableFromInline\n internal var _nativeBuffer: Builtin.NativeObject\n\n /// Create with new storage containing an initial `Header` and space\n /// for at least `minimumCapacity` `element`s.\n ///\n /// - parameter bufferClass: The class of the object used for storage.\n /// - parameter minimumCapacity: The minimum number of `Element`s that\n /// must be able to be stored in the new buffer.\n /// - parameter factory: A function that produces the initial\n /// `Header` instance stored in the buffer, given the `buffer`\n /// object and a function that can be called on it to get the actual\n /// number of allocated elements.\n ///\n /// - Precondition: `minimumCapacity >= 0`, and the type indicated by\n /// `bufferClass` is a non-`@objc` class with no declared stored\n /// properties. The `deinit` of `bufferClass` must destroy its\n /// stored `Header` and any constructed `Element`s.\n @_preInverseGenerics\n @inlinable\n @available(OpenBSD, unavailable, message: "malloc_size is unavailable.")\n public init(\n bufferClass: AnyClass,\n minimumCapacity: Int,\n makingHeaderWith factory:\n (_ buffer: AnyObject, _ capacity: (AnyObject) -> Int) throws -> Header\n ) rethrows {\n self = ManagedBufferPointer(\n bufferClass: bufferClass, minimumCapacity: minimumCapacity)\n\n // initialize the header field\n try unsafe withUnsafeMutablePointerToHeader {\n unsafe $0.initialize(to:\n try factory(\n self.buffer,\n {\n ManagedBufferPointer(unsafeBufferObject: $0).capacity\n }))\n }\n }\n\n /// Manage the given `buffer`.\n ///\n /// - Precondition: `buffer` is an instance of a non-`@objc` class whose\n /// `deinit` destroys its stored `Header` and any constructed `Element`s.\n @_preInverseGenerics\n @inlinable\n public init(unsafeBufferObject buffer: AnyObject) {\n #if !$Embedded\n ManagedBufferPointer._checkValidBufferClass(type(of: buffer))\n #endif\n\n self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)\n }\n\n //===--- internal/private API -------------------------------------------===//\n\n /// Internal version for use by _ContiguousArrayBuffer where we know that we\n /// have a valid buffer class.\n /// This version of the init function gets called from\n /// _ContiguousArrayBuffer's deinit function. Since 'deinit' does not get\n /// specialized with current versions of the compiler, we can't get rid of the\n /// _debugPreconditions in _checkValidBufferClass for any array. Since we know\n /// for the _ContiguousArrayBuffer that this check must always succeed we omit\n /// it in this specialized constructor.\n @_preInverseGenerics\n @inlinable\n internal init(_uncheckedUnsafeBufferObject buffer: AnyObject) {\n #if !$Embedded\n ManagedBufferPointer._internalInvariantValidBufferClass(type(of: buffer))\n #endif\n\n self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)\n }\n\n /// Create with new storage containing space for an initial `Header`\n /// and at least `minimumCapacity` `element`s.\n ///\n /// - parameter bufferClass: The class of the object used for storage.\n /// - parameter minimumCapacity: The minimum number of `Element`s that\n /// must be able to be stored in the new buffer.\n ///\n /// - Precondition: `minimumCapacity >= 0`, and the type indicated by\n /// `bufferClass` is a non-`@objc` class with no declared stored\n /// properties. The `deinit` of `bufferClass` must destroy its\n /// stored `Header` and any constructed `Element`s.\n @_preInverseGenerics\n @inlinable\n internal init(\n bufferClass: AnyClass,\n minimumCapacity: Int\n ) {\n ManagedBufferPointer._checkValidBufferClass(bufferClass, creating: true)\n _precondition(\n minimumCapacity >= 0,\n "ManagedBufferPointer must have non-negative capacity")\n\n self.init(\n _uncheckedBufferClass: bufferClass, minimumCapacity: minimumCapacity)\n }\n\n /// Internal version for use by _ContiguousArrayBuffer.init where we know that\n /// we have a valid buffer class and that the capacity is >= 0.\n @_preInverseGenerics\n @inlinable\n internal init(\n _uncheckedBufferClass: AnyClass,\n minimumCapacity: Int\n ) {\n ManagedBufferPointer._internalInvariantValidBufferClass(\n _uncheckedBufferClass, creating: true)\n _internalInvariant(\n minimumCapacity >= 0,\n "ManagedBufferPointer must have non-negative capacity")\n\n let totalSize = ManagedBufferPointer._elementOffset\n + minimumCapacity * MemoryLayout<Element>.stride\n\n let newBuffer: AnyObject = _swift_bufferAllocate(\n bufferType: _uncheckedBufferClass,\n size: totalSize,\n alignmentMask: ManagedBufferPointer._alignmentMask)\n\n self._nativeBuffer = Builtin.unsafeCastToNativeObject(newBuffer)\n }\n\n /// Manage the given `buffer`.\n ///\n /// - Note: It is an error to use the `header` property of the resulting\n /// instance unless it has been initialized.\n @_preInverseGenerics\n @inlinable\n internal init(_ buffer: ManagedBuffer<Header, Element>) {\n _nativeBuffer = Builtin.unsafeCastToNativeObject(buffer)\n }\n}\n\n@available(*, unavailable)\nextension ManagedBufferPointer: Sendable where Element: ~Copyable {}\n\nextension ManagedBufferPointer where Element: ~Copyable {\n /// The stored `Header` instance.\n @_preInverseGenerics\n @inlinable\n public var header: Header {\n _read {\n yield unsafe _headerPointer.pointee\n }\n _modify {\n yield unsafe &_headerPointer.pointee\n }\n }\n}\n\nextension ManagedBufferPointer where Element: ~Copyable {\n /// Returns the object instance being used for storage.\n @_preInverseGenerics\n @inlinable\n public var buffer: AnyObject {\n return Builtin.castFromNativeObject(_nativeBuffer)\n }\n\n /// The actual number of elements that can be stored in this object.\n ///\n /// This value may be nontrivial to compute; it is usually a good\n /// idea to store this information in the "header" area when\n /// an instance is created.\n @_preInverseGenerics\n @inlinable\n @available(OpenBSD, unavailable, message: "malloc_size is unavailable.")\n public var capacity: Int {\n return (\n _capacityInBytes &- ManagedBufferPointer._elementOffset\n ) / MemoryLayout<Element>.stride\n }\n\n /// Call `body` with an `UnsafeMutablePointer` to the stored\n /// `Header`.\n ///\n /// - Note: This pointer is valid only\n /// for the duration of the call to `body`.\n @_alwaysEmitIntoClient\n public func withUnsafeMutablePointerToHeader<E: Error, R: ~Copyable>(\n _ body: (UnsafeMutablePointer<Header>) throws(E) -> R\n ) throws(E) -> R {\n try unsafe withUnsafeMutablePointers { (v, _) throws(E) in try unsafe body(v) }\n }\n\n /// Call `body` with an `UnsafeMutablePointer` to the `Element`\n /// storage.\n ///\n /// - Note: This pointer is valid only for the duration of the\n /// call to `body`.\n @_alwaysEmitIntoClient\n public func withUnsafeMutablePointerToElements<E: Error, R: ~Copyable>(\n _ body: (UnsafeMutablePointer<Element>) throws(E) -> R\n ) throws(E) -> R {\n try unsafe withUnsafeMutablePointers { (_, v) throws(E) in try unsafe body(v) }\n }\n\n /// Call `body` with `UnsafeMutablePointer`s to the stored `Header`\n /// and raw `Element` storage.\n ///\n /// - Note: These pointers are valid only for the duration of the\n /// call to `body`.\n @_alwaysEmitIntoClient\n public func withUnsafeMutablePointers<E: Error, R: ~Copyable>(\n _ body: (\n UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>\n ) throws(E) -> R\n ) throws(E) -> R {\n defer { _fixLifetime(_nativeBuffer) }\n return try unsafe body(_headerPointer, _elementPointer)\n }\n\n /// Returns `true` if `self` holds the only strong reference to its\n /// buffer; otherwise, returns `false`.\n ///\n /// See `isKnownUniquelyReferenced` for details.\n @_preInverseGenerics\n @inlinable\n public mutating func isUniqueReference() -> Bool {\n return _isUnique(&_nativeBuffer)\n }\n}\n\nextension ManagedBufferPointer {\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @_silgen_name("$ss20ManagedBufferPointerV017withUnsafeMutableC8ToHeaderyqd__qd__SpyxGKXEKlF")\n @usableFromInline\n internal func withUnsafeMutablePointerToHeader<R>(\n _ body: (UnsafeMutablePointer<Header>) throws -> R\n ) rethrows -> R {\n try unsafe withUnsafeMutablePointers { (v, _) in try unsafe body(v) }\n }\n\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @_silgen_name("$ss20ManagedBufferPointerV017withUnsafeMutableC10ToElementsyqd__qd__Spyq_GKXEKlF")\n @usableFromInline\n internal func withUnsafeMutablePointerToElements<R>(\n _ body: (UnsafeMutablePointer<Element>) throws -> R\n ) rethrows -> R {\n try unsafe withUnsafeMutablePointers { (_, v) in try unsafe body(v) }\n }\n\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @_silgen_name("$ss20ManagedBufferPointerV25withUnsafeMutablePointersyqd__qd__SpyxG_Spyq_GtKXEKlF")\n @usableFromInline\n internal func withUnsafeMutablePointers<R>(\n _ body: (\n UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>\n ) throws -> R\n ) rethrows -> R {\n defer { _fixLifetime(_nativeBuffer) }\n return try unsafe body(_headerPointer, _elementPointer)\n }\n}\n\nextension ManagedBufferPointer where Element: ~Copyable {\n @_preInverseGenerics\n @inlinable\n internal static func _checkValidBufferClass(\n _ bufferClass: AnyClass, creating: Bool = false\n ) {\n unsafe _debugPrecondition(\n _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size\n || (\n (!creating || bufferClass is ManagedBuffer<Header, Element>.Type)\n && _class_getInstancePositiveExtentSize(bufferClass)\n == _headerOffset + MemoryLayout<Header>.size),\n "ManagedBufferPointer buffer class has illegal stored properties"\n )\n _debugPrecondition(\n _usesNativeSwiftReferenceCounting(bufferClass),\n "ManagedBufferPointer buffer class must be non-@objc"\n )\n }\n\n @_preInverseGenerics\n @inlinable\n internal static func _internalInvariantValidBufferClass(\n _ bufferClass: AnyClass, creating: Bool = false\n ) {\n unsafe _internalInvariant(\n _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size\n || (\n (!creating || bufferClass is ManagedBuffer<Header, Element>.Type)\n && _class_getInstancePositiveExtentSize(bufferClass)\n == _headerOffset + MemoryLayout<Header>.size),\n "ManagedBufferPointer buffer class has illegal stored properties"\n )\n _internalInvariant(\n _usesNativeSwiftReferenceCounting(bufferClass),\n "ManagedBufferPointer buffer class must be non-@objc"\n )\n }\n}\n\nextension ManagedBufferPointer where Element: ~Copyable {\n /// The required alignment for allocations of this type, minus 1\n @_preInverseGenerics\n @inlinable\n internal static var _alignmentMask: Int {\n return unsafe max(\n MemoryLayout<_HeapObject>.alignment,\n max(MemoryLayout<Header>.alignment, MemoryLayout<Element>.alignment)) &- 1\n }\n\n /// The actual number of bytes allocated for this object.\n @_preInverseGenerics\n @inlinable\n @available(OpenBSD, unavailable, message: "malloc_size is unavailable.")\n internal var _capacityInBytes: Int {\n return unsafe _swift_stdlib_malloc_size(_address)\n }\n\n /// The address of this instance in a convenient pointer-to-bytes form\n @_preInverseGenerics\n @inlinable\n internal var _address: UnsafeMutableRawPointer {\n return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_nativeBuffer))\n }\n\n /// Offset from the allocated storage for `self` to the stored `Header`\n @_preInverseGenerics\n @inlinable\n internal static var _headerOffset: Int {\n _onFastPath()\n return unsafe _roundUp(\n MemoryLayout<_HeapObject>.size,\n toAlignment: MemoryLayout<Header>.alignment)\n }\n\n /// An **unmanaged** pointer to the storage for the `Header`\n /// instance. Not safe to use without _fixLifetime calls to\n /// guarantee it doesn't dangle\n @_preInverseGenerics\n @inlinable\n internal var _headerPointer: UnsafeMutablePointer<Header> {\n _onFastPath()\n return unsafe (_address + ManagedBufferPointer._headerOffset).assumingMemoryBound(\n to: Header.self)\n }\n\n /// An **unmanaged** pointer to the storage for `Element`s. Not\n /// safe to use without _fixLifetime calls to guarantee it doesn't\n /// dangle.\n @_preInverseGenerics\n @inlinable\n internal var _elementPointer: UnsafeMutablePointer<Element> {\n _onFastPath()\n return unsafe (_address + ManagedBufferPointer._elementOffset).assumingMemoryBound(\n to: Element.self)\n }\n\n /// Offset from the allocated storage for `self` to the `Element` storage\n @_preInverseGenerics\n @inlinable\n internal static var _elementOffset: Int {\n _onFastPath()\n return _roundUp(\n _headerOffset + MemoryLayout<Header>.size,\n toAlignment: MemoryLayout<Element>.alignment)\n }\n}\n\n@_preInverseGenerics\nextension ManagedBufferPointer: Equatable where Element: ~Copyable {\n @_preInverseGenerics\n @inlinable\n public static func == (\n lhs: ManagedBufferPointer,\n rhs: ManagedBufferPointer\n ) -> Bool {\n return unsafe lhs._address == rhs._address\n }\n}\n\n// FIXME: when our calling convention changes to pass self at +0,\n// inout should be dropped from the arguments to these functions.\n// FIXME(docs): isKnownUniquelyReferenced should check weak/unowned counts too, \n// but currently does not. rdar://problem/29341361\n\n/// Returns a Boolean value indicating whether the given object is known to\n/// have a single strong reference.\n///\n/// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the\n/// copy-on-write optimization for the deep storage of value types:\n///\n/// mutating func update(withValue value: T) {\n/// if !isKnownUniquelyReferenced(&myStorage) {\n/// myStorage = self.copiedStorage()\n/// }\n/// myStorage.update(withValue: value)\n/// }\n///\n/// Use care when calling `isKnownUniquelyReferenced(_:)` from within a Boolean\n/// expression. In debug builds, an instance in the left-hand side of a `&&`\n/// or `||` expression may still be referenced when evaluating the right-hand\n/// side, inflating the instance's reference count. For example, this version\n/// of the `update(withValue)` method will re-copy `myStorage` on every call:\n///\n/// // Copies too frequently:\n/// mutating func badUpdate(withValue value: T) {\n/// if myStorage.shouldCopy || !isKnownUniquelyReferenced(&myStorage) {\n/// myStorage = self.copiedStorage()\n/// }\n/// myStorage.update(withValue: value)\n/// }\n///\n/// To avoid this behavior, swap the call `isKnownUniquelyReferenced(_:)` to\n/// the left-hand side or store the result of the first expression in a local\n/// constant:\n///\n/// mutating func goodUpdate(withValue value: T) {\n/// let shouldCopy = myStorage.shouldCopy\n/// if shouldCopy || !isKnownUniquelyReferenced(&myStorage) {\n/// myStorage = self.copiedStorage()\n/// }\n/// myStorage.update(withValue: value)\n/// }\n///\n/// `isKnownUniquelyReferenced(_:)` checks only for strong references to the\n/// given object---if `object` has additional weak or unowned references, the\n/// result may still be `true`. Because weak and unowned references cannot be\n/// the only reference to an object, passing a weak or unowned reference as\n/// `object` always results in `false`.\n///\n/// If the instance passed as `object` is being accessed by multiple threads\n/// simultaneously, this function may still return `true`. Therefore, you must\n/// only call this function from mutating methods with appropriate thread\n/// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)`\n/// only returns `true` when there is really one accessor, or when there is a\n/// race condition, which is already undefined behavior.\n///\n/// - Parameter object: An instance of a class. This function does *not* modify\n/// `object`; the use of `inout` is an implementation artifact.\n/// - Returns: `true` if `object` is known to have a single strong reference;\n/// otherwise, `false`.\n@inlinable\npublic func isKnownUniquelyReferenced<T: AnyObject>(_ object: inout T) -> Bool\n{\n return _isUnique(&object)\n}\n\n#if $Embedded\n@inlinable\npublic func isKnownUniquelyReferenced(_ object: inout Builtin.NativeObject) -> Bool\n{\n return _isUnique(&object)\n}\n#endif\n\n/// Returns a Boolean value indicating whether the given object is known to\n/// have a single strong reference.\n///\n/// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the\n/// copy-on-write optimization for the deep storage of value types:\n///\n/// mutating func update(withValue value: T) {\n/// if !isKnownUniquelyReferenced(&myStorage) {\n/// myStorage = self.copiedStorage()\n/// }\n/// myStorage.update(withValue: value)\n/// }\n///\n/// `isKnownUniquelyReferenced(_:)` checks only for strong references to the\n/// given object---if `object` has additional weak or unowned references, the\n/// result may still be `true`. Because weak and unowned references cannot be\n/// the only reference to an object, passing a weak or unowned reference as\n/// `object` always results in `false`.\n///\n/// If the instance passed as `object` is being accessed by multiple threads\n/// simultaneously, this function may still return `true`. Therefore, you must\n/// only call this function from mutating methods with appropriate thread\n/// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)`\n/// only returns `true` when there is really one accessor, or when there is a\n/// race condition, which is already undefined behavior.\n///\n/// - Parameter object: An instance of a class. This function does *not* modify\n/// `object`; the use of `inout` is an implementation artifact.\n/// - Returns: `true` if `object` is known to have a single strong reference;\n/// otherwise, `false`. If `object` is `nil`, the return value is `false`.\n@inlinable\npublic func isKnownUniquelyReferenced<T: AnyObject>(\n _ object: inout T?\n) -> Bool {\n return _isUnique(&object)\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ManagedBuffer.swift
cpp_apple_swift_stdlib_public_core_ManagedBuffer.swift
Swift
27,166
0.95
0.140921
0.412371
node-utils
876
2023-12-30T03:44:35.341900
GPL-3.0
false
efe174c198b5df37465a448f65723f40
//===--- Map.swift - Lazily map over a Sequence ---------------*- 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 those in a `Base`\n/// `Sequence` passed through a transform function returning `Element`.\n/// These elements are computed lazily, each time they're read, by\n/// calling the transform function on a base element.\n@frozen\npublic struct LazyMapSequence<Base: Sequence, Element> {\n\n public typealias Elements = LazyMapSequence\n\n @usableFromInline\n internal var _base: Base\n @usableFromInline\n internal let _transform: (Base.Element) -> Element\n\n /// Creates an instance with elements `transform(x)` for each element\n /// `x` of base.\n @inlinable\n internal init(_base: Base, transform: @escaping (Base.Element) -> Element) {\n self._base = _base\n self._transform = transform\n }\n}\n\n@available(*, unavailable)\nextension LazyMapSequence: Sendable {}\n\nextension LazyMapSequence {\n @frozen\n public struct Iterator {\n @usableFromInline\n internal var _base: Base.Iterator\n @usableFromInline\n internal let _transform: (Base.Element) -> Element\n\n @inlinable\n public var base: Base.Iterator { return _base }\n\n @inlinable\n internal init(\n _base: Base.Iterator, \n _transform: @escaping (Base.Element) -> Element\n ) {\n self._base = _base\n self._transform = _transform\n }\n }\n}\n\n@available(*, unavailable)\nextension LazyMapSequence.Iterator: Sendable {}\n\nextension LazyMapSequence.Iterator: IteratorProtocol, Sequence {\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\n public mutating func next() -> Element? {\n return _base.next().map(_transform)\n }\n}\n\nextension LazyMapSequence: LazySequenceProtocol {\n /// Returns an iterator over the elements of this sequence.\n ///\n /// - Complexity: O(1).\n @inlinable\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_base: _base.makeIterator(), _transform: _transform)\n }\n\n /// A value less than or equal to the number of elements in the sequence,\n /// calculated nondestructively.\n ///\n /// The default implementation returns 0. If you provide your own\n /// implementation, make sure to compute the value nondestructively.\n ///\n /// - Complexity: O(1), except if the sequence also conforms to `Collection`.\n /// In this case, see the documentation of `Collection.underestimatedCount`.\n @inlinable\n public var underestimatedCount: Int {\n return _base.underestimatedCount\n }\n}\n\n/// A `Collection` whose elements consist of those in a `Base`\n/// `Collection` passed through a transform function returning `Element`.\n/// These elements are computed lazily, each time they're read, by\n/// calling the transform function on a base element.\npublic typealias LazyMapCollection<T: Collection,U> = LazyMapSequence<T,U>\n\nextension LazyMapCollection: Collection {\n public typealias Index = Base.Index\n public typealias Indices = Base.Indices\n public typealias SubSequence = LazyMapCollection<Base.SubSequence, Element>\n\n @inlinable\n public var startIndex: Base.Index { return _base.startIndex }\n @inlinable\n public var endIndex: Base.Index { return _base.endIndex }\n\n @inlinable\n public func index(after i: Index) -> Index { return _base.index(after: i) }\n @inlinable\n public func formIndex(after i: inout Index) { _base.formIndex(after: &i) }\n\n /// Accesses the element at `position`.\n ///\n /// - Precondition: `position` is a valid position in `self` and\n /// `position != endIndex`.\n @inlinable\n public subscript(position: Base.Index) -> Element {\n return _transform(_base[position])\n }\n\n @inlinable\n public subscript(bounds: Range<Base.Index>) -> SubSequence {\n return SubSequence(_base: _base[bounds], transform: _transform)\n }\n\n @inlinable\n public var indices: Indices {\n return _base.indices\n }\n\n /// A Boolean value indicating whether the collection is empty.\n @inlinable\n public var isEmpty: Bool { return _base.isEmpty }\n\n /// The number of elements in the collection.\n ///\n /// To check whether the 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 `Index` conforms to `RandomAccessIndex`; O(*n*)\n /// otherwise.\n @inlinable\n public var count: Int {\n return _base.count\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy n: Int) -> Index {\n return _base.index(i, offsetBy: n)\n }\n\n @inlinable\n public func index(\n _ i: Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Index? {\n return _base.index(i, offsetBy: n, limitedBy: limit)\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n return _base.distance(from: start, to: end)\n }\n}\n\nextension LazyMapCollection: BidirectionalCollection\n where Base: BidirectionalCollection {\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 func index(before i: Index) -> Index { return _base.index(before: i) }\n\n @inlinable\n public func formIndex(before i: inout Index) {\n _base.formIndex(before: &i)\n }\n}\n\nextension LazyMapCollection: LazyCollectionProtocol { }\n\nextension LazyMapCollection: RandomAccessCollection\n where Base: RandomAccessCollection { }\n\n//===--- Support for s.lazy -----------------------------------------------===//\n\nextension LazySequenceProtocol {\n /// Returns a `LazyMapSequence` over this `Sequence`. The elements of\n /// the result are computed lazily, each time they are read, by\n /// calling `transform` function on a base element.\n @inlinable\n public func map<U>(\n _ transform: @escaping (Element) -> U\n ) -> LazyMapSequence<Elements, U> {\n return LazyMapSequence(_base: elements, transform: transform)\n }\n}\n\nextension LazyMapSequence {\n @inlinable\n @available(swift, introduced: 5)\n public func map<ElementOfResult>(\n _ transform: @escaping (Element) -> ElementOfResult\n ) -> LazyMapSequence<Base, ElementOfResult> {\n return LazyMapSequence<Base, ElementOfResult>(\n _base: _base,\n transform: { transform(self._transform($0)) })\n }\n}\n\nextension LazyMapCollection {\n @inlinable\n @available(swift, introduced: 5)\n public func map<ElementOfResult>(\n _ transform: @escaping (Element) -> ElementOfResult\n ) -> LazyMapCollection<Base, ElementOfResult> {\n return LazyMapCollection<Base, ElementOfResult>(\n _base: _base,\n transform: {transform(self._transform($0))})\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Map.swift
cpp_apple_swift_stdlib_public_core_Map.swift
Swift
7,363
0.95
0.055319
0.306931
react-lib
601
2024-09-20T23:35:27.176168
GPL-3.0
false
6db9caaeb572535245b56f3f9db52d99
//===----------------------------------------------------------------------===//\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/// The memory layout of a type, describing its size, stride, and alignment.\n///\n/// You can use `MemoryLayout` as a source of information about a type when\n/// allocating or binding memory using raw pointers. The following example\n/// declares a `Point` type with `x` and `y` coordinates and a Boolean\n/// `isFilled` property.\n///\n/// struct Point {\n/// let x: Double\n/// let y: Double\n/// let isFilled: Bool\n/// }\n///\n/// The size, stride, and alignment of the `Point` type are accessible as\n/// static properties of `MemoryLayout<Point>`.\n///\n/// // MemoryLayout<Point>.size == 17\n/// // MemoryLayout<Point>.stride == 24\n/// // MemoryLayout<Point>.alignment == 8\n///\n/// Always use a multiple of a type's `stride` instead of its `size` when\n/// allocating memory or accounting for the distance between instances in\n/// memory. This example allocates uninitialized raw memory with space\n/// for four instances of `Point`.\n///\n/// let count = 4\n/// let pointPointer = UnsafeMutableRawPointer.allocate(\n/// byteCount: count * MemoryLayout<Point>.stride,\n/// alignment: MemoryLayout<Point>.alignment)\n@frozen // namespace\npublic enum MemoryLayout<T: ~Copyable & ~Escapable>\n: ~BitwiseCopyable, Copyable, Escapable {}\n\nextension MemoryLayout where T: ~Copyable & ~Escapable {\n /// The contiguous memory footprint of `T`, in bytes.\n ///\n /// A type's size does not include any dynamically allocated or out of line\n /// storage. In particular, `MemoryLayout<T>.size`, when `T` is a class\n /// type, is the same regardless of how many stored properties `T` has.\n ///\n /// When allocating memory for multiple instances of `T` using an unsafe\n /// pointer, use a multiple of the type's stride instead of its size.\n @_transparent\n @_preInverseGenerics\n public static var size: Int {\n return Int(Builtin.sizeof(T.self))\n }\n\n /// The number of bytes from the start of one instance of `T` to the start of\n /// the next when stored in contiguous memory or in an `Array<T>`.\n ///\n /// This is the same as the number of bytes moved when an `UnsafePointer<T>`\n /// instance is incremented. `T` may have a lower minimal alignment that\n /// trades runtime performance for space efficiency. This value is always\n /// positive.\n @_transparent\n @_preInverseGenerics\n public static var stride: Int {\n return Int(Builtin.strideof(T.self))\n }\n\n /// The default memory alignment of `T`, in bytes.\n ///\n /// Use the `alignment` property for a type when allocating memory using an\n /// unsafe pointer. This value is always positive.\n @_transparent\n @_preInverseGenerics\n public static var alignment: Int {\n return Int(Builtin.alignof(T.self))\n }\n}\n\nextension MemoryLayout where T: ~Copyable & ~Escapable {\n /// Returns the contiguous memory footprint of the given instance.\n ///\n /// The result does not include any dynamically allocated or out of line\n /// storage. In particular, pointers and class instances all have the same\n /// contiguous memory footprint, regardless of the size of the referenced\n /// data.\n ///\n /// When you have a type instead of an instance, use the\n /// `MemoryLayout<T>.size` static property instead.\n ///\n /// let x: Int = 100\n ///\n /// // Finding the size of a value's type\n /// let s = MemoryLayout.size(ofValue: x)\n /// // s == 8\n ///\n /// // Finding the size of a type directly\n /// let t = MemoryLayout<Int>.size\n /// // t == 8\n ///\n /// - Parameter value: A value representative of the type to describe.\n /// - Returns: The size, in bytes, of the given value's type.\n @_transparent\n @_preInverseGenerics\n public static func size(ofValue value: borrowing T) -> Int {\n return MemoryLayout.size\n }\n\n /// Returns the number of bytes from the start of one instance of `T` to the\n /// start of the next when stored in contiguous memory or in an `Array<T>`.\n ///\n /// This is the same as the number of bytes moved when an `UnsafePointer<T>`\n /// instance is incremented. `T` may have a lower minimal alignment that\n /// trades runtime performance for space efficiency. The result is always\n /// positive.\n ///\n /// When you have a type instead of an instance, use the\n /// `MemoryLayout<T>.stride` static property instead.\n ///\n /// let x: Int = 100\n ///\n /// // Finding the stride of a value's type\n /// let s = MemoryLayout.stride(ofValue: x)\n /// // s == 8\n ///\n /// // Finding the stride of a type directly\n /// let t = MemoryLayout<Int>.stride\n /// // t == 8\n ///\n /// - Parameter value: A value representative of the type to describe.\n /// - Returns: The stride, in bytes, of the given value's type.\n @_transparent\n @_preInverseGenerics\n public static func stride(ofValue value: borrowing T) -> Int {\n return MemoryLayout.stride\n }\n\n /// Returns the default memory alignment of `T`.\n ///\n /// Use a type's alignment when allocating memory using an unsafe pointer.\n ///\n /// When you have a type instead of an instance, use the\n /// `MemoryLayout<T>.stride` static property instead.\n ///\n /// let x: Int = 100\n ///\n /// // Finding the alignment of a value's type\n /// let s = MemoryLayout.alignment(ofValue: x)\n /// // s == 8\n ///\n /// // Finding the alignment of a type directly\n /// let t = MemoryLayout<Int>.alignment\n /// // t == 8\n ///\n /// - Parameter value: A value representative of the type to describe.\n /// - Returns: The default memory alignment, in bytes, of the given value's\n /// type. This value is always positive.\n @_transparent\n @_preInverseGenerics\n public static func alignment(ofValue value: borrowing T) -> Int {\n return MemoryLayout.alignment\n }\n}\n\nextension MemoryLayout {\n /// Returns the offset of an inline stored property within a type's in-memory\n /// representation.\n ///\n /// You can use this method to find the distance in bytes that can be added\n /// to a pointer of type `T` to get a pointer to the property referenced by\n /// `key`. The offset is available only if the given key refers to inline,\n /// directly addressable storage within the in-memory representation of `T`.\n ///\n /// If the return value of this method is non-`nil`, then accessing the value\n /// by key path or by an offset pointer are equivalent. For example, for a\n /// variable `root` of type `T`, a key path `key` of type\n /// `WritableKeyPath<T, U>`, and a `value` of type `U`:\n ///\n /// // Mutation through the key path\n /// root[keyPath: key] = value\n ///\n /// // Mutation through the offset pointer\n /// withUnsafeMutableBytes(of: &root) { bytes in\n /// let offset = MemoryLayout<T>.offset(of: key)!\n /// let rawPointerToValue = bytes.baseAddress! + offset\n /// let pointerToValue = rawPointerToValue.assumingMemoryBound(to: U.self)\n /// pointerToValue.pointee = value\n /// }\n ///\n /// A property has inline, directly addressable storage when it is a stored\n /// property for which no additional work is required to extract or set the\n /// value. Properties are not directly accessible if they trigger any\n /// `didSet` or `willSet` accessors, perform any representation changes such\n /// as bridging or closure reabstraction, or mask the value out of\n /// overlapping storage as for packed bitfields. In addition, because class\n /// instance properties are always stored out-of-line, their positions are\n /// not accessible using `offset(of:)`.\n ///\n /// For example, in the `ProductCategory` type defined here, only\n /// `\.updateCounter`, `\.identifier`, and `\.identifier.name` refer to\n /// properties with inline, directly addressable storage:\n ///\n /// struct ProductCategory {\n /// struct Identifier {\n /// var name: String // addressable\n /// }\n ///\n /// var identifier: Identifier // addressable\n /// var updateCounter: Int // addressable\n /// var products: [Product] { // not addressable: didSet handler\n /// didSet { updateCounter += 1 }\n /// }\n /// var productCount: Int { // not addressable: computed property\n /// return products.count\n /// }\n /// }\n ///\n /// When using `offset(of:)` with a type imported from a library, don't\n /// assume that future versions of the library will have the same behavior.\n /// If a property is converted from a stored property to a computed\n /// property, the result of `offset(of:)` changes to `nil`. That kind of\n /// conversion is nonbreaking in other contexts, but would trigger a runtime\n /// error if the result of `offset(of:)` is force-unwrapped.\n ///\n /// - Parameter key: A key path referring to storage that can be accessed\n /// through a value of type `T`.\n /// - Returns: The offset in bytes from a pointer to a value of type `T` to a\n /// pointer to the storage referenced by `key`, or `nil` if no such offset\n /// is available for the storage referenced by `key`. If the value is\n /// `nil`, it can be because `key` is computed, has observers, requires\n /// reabstraction, or overlaps storage with other properties.\n @_transparent\n public static func offset(of key: PartialKeyPath<T>) -> Int? {\n return key._storedInlineOffset\n }\n}\n\n// Not-yet-public alignment conveniences\nextension MemoryLayout where T: ~Copyable {\n internal static var _alignmentMask: Int { return alignment - 1 }\n\n internal static func _roundingUpToAlignment(_ value: Int) -> Int {\n return (value + _alignmentMask) & ~_alignmentMask\n }\n internal static func _roundingDownToAlignment(_ value: Int) -> Int {\n return value & ~_alignmentMask\n }\n\n internal static func _roundingUpToAlignment(_ value: UInt) -> UInt {\n return (value + UInt(bitPattern: _alignmentMask)) & ~UInt(bitPattern: _alignmentMask)\n }\n internal static func _roundingDownToAlignment(_ value: UInt) -> UInt {\n return value & ~UInt(bitPattern: _alignmentMask)\n }\n\n internal static func _roundingUpToAlignment(_ value: UnsafeRawPointer) -> UnsafeRawPointer {\n return unsafe UnsafeRawPointer(bitPattern:\n _roundingUpToAlignment(UInt(bitPattern: value))).unsafelyUnwrapped\n }\n internal static func _roundingDownToAlignment(_ value: UnsafeRawPointer) -> UnsafeRawPointer {\n return unsafe UnsafeRawPointer(bitPattern:\n _roundingDownToAlignment(UInt(bitPattern: value))).unsafelyUnwrapped\n }\n\n internal static func _roundingUpToAlignment(_ value: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer {\n return unsafe UnsafeMutableRawPointer(bitPattern:\n _roundingUpToAlignment(UInt(bitPattern: value))).unsafelyUnwrapped\n }\n internal static func _roundingDownToAlignment(_ value: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer {\n return unsafe UnsafeMutableRawPointer(bitPattern:\n _roundingDownToAlignment(UInt(bitPattern: value))).unsafelyUnwrapped\n }\n\n internal static func _roundingUpBaseToAlignment(_ value: UnsafeRawBufferPointer) -> UnsafeRawBufferPointer {\n let baseAddressBits = Int(bitPattern: value.baseAddress)\n var misalignment = baseAddressBits & _alignmentMask\n if misalignment != 0 {\n misalignment = _alignmentMask & -misalignment\n return unsafe UnsafeRawBufferPointer(\n start: UnsafeRawPointer(bitPattern: baseAddressBits + misalignment),\n count: value.count - misalignment)\n }\n return unsafe value\n }\n\n internal static func _roundingUpBaseToAlignment(_ value: UnsafeMutableRawBufferPointer) -> UnsafeMutableRawBufferPointer {\n let baseAddressBits = Int(bitPattern: value.baseAddress)\n var misalignment = baseAddressBits & _alignmentMask\n if misalignment != 0 {\n misalignment = _alignmentMask & -misalignment\n return unsafe UnsafeMutableRawBufferPointer(\n start: UnsafeMutableRawPointer(bitPattern: baseAddressBits + misalignment),\n count: value.count - misalignment)\n }\n return unsafe value\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_MemoryLayout.swift
cpp_apple_swift_stdlib_public_core_MemoryLayout.swift
Swift
12,568
0.95
0.069536
0.665505
awesome-app
584
2024-08-11T01:39:25.399515
GPL-3.0
false
10eeb3e5d7d4a3804a7842fd14dd4ae8
//===----------------------------------------------------------------------===//\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 file contains only support for types deprecated from previous versions\n// of Swift\n\n#if !$Embedded\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "BidirectionalCollection")\npublic typealias BidirectionalIndexable = BidirectionalCollection\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "Collection")\npublic typealias IndexableBase = Collection\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "Collection")\npublic typealias Indexable = Collection\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "MutableCollection")\npublic typealias MutableIndexable = MutableCollection\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "RandomAccessCollection")\npublic typealias RandomAccessIndexable = RandomAccessCollection\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "RangeReplaceableIndexable")\npublic typealias RangeReplaceableIndexable = RangeReplaceableCollection\n@available(swift, deprecated: 4.2, renamed: "EnumeratedSequence.Iterator")\npublic typealias EnumeratedIterator<T: Sequence> = EnumeratedSequence<T>.Iterator\n@available(swift,deprecated: 4.2, obsoleted: 5.0, renamed: "CollectionOfOne.Iterator")\npublic typealias IteratorOverOne<T> = CollectionOfOne<T>.Iterator\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "EmptyCollection.Iterator")\npublic typealias EmptyIterator<T> = EmptyCollection<T>.Iterator\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyFilterSequence.Iterator")\npublic typealias LazyFilterIterator<T: Sequence> = LazyFilterSequence<T>.Iterator\n@available(swift, deprecated: 3.1, obsoleted: 5.0, message: "Use Base.Index")\npublic typealias LazyFilterIndex<Base: Collection> = Base.Index\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyDropWhileSequence.Iterator")\npublic typealias LazyDropWhileIterator<T> = LazyDropWhileSequence<T>.Iterator where T: Sequence\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyDropWhileCollection.Index")\npublic typealias LazyDropWhileIndex<T> = LazyDropWhileCollection<T>.Index where T: Collection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyDropWhileCollection")\npublic typealias LazyDropWhileBidirectionalCollection<T> = LazyDropWhileCollection<T> where T: BidirectionalCollection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyFilterCollection")\npublic typealias LazyFilterBidirectionalCollection<T> = LazyFilterCollection<T> where T: BidirectionalCollection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyMapSequence.Iterator")\npublic typealias LazyMapIterator<T, E> = LazyMapSequence<T, E>.Iterator where T: Sequence\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyMapCollection")\npublic typealias LazyMapBidirectionalCollection<T, E> = LazyMapCollection<T, E> where T: BidirectionalCollection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyMapCollection")\npublic typealias LazyMapRandomAccessCollection<T, E> = LazyMapCollection<T, E> where T: RandomAccessCollection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyCollection")\npublic typealias LazyBidirectionalCollection<T> = LazyCollection<T> where T: BidirectionalCollection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyCollection")\npublic typealias LazyRandomAccessCollection<T> = LazyCollection<T> where T: RandomAccessCollection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "FlattenCollection.Index")\npublic typealias FlattenCollectionIndex<T> = FlattenCollection<T>.Index where T: Collection, T.Element: Collection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "FlattenCollection.Index")\npublic typealias FlattenBidirectionalCollectionIndex<T> = FlattenCollection<T>.Index where T: BidirectionalCollection, T.Element: BidirectionalCollection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "FlattenCollection")\npublic typealias FlattenBidirectionalCollection<T> = FlattenCollection<T> where T: BidirectionalCollection, T.Element: BidirectionalCollection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "JoinedSequence.Iterator")\npublic typealias JoinedIterator<T: Sequence> = JoinedSequence<T>.Iterator where T.Element: Sequence\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "Zip2Sequence.Iterator")\npublic typealias Zip2Iterator<T, U> = Zip2Sequence<T, U>.Iterator where T: Sequence, U: Sequence\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyPrefixWhileSequence.Iterator")\npublic typealias LazyPrefixWhileIterator<T> = LazyPrefixWhileSequence<T>.Iterator where T: Sequence\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyPrefixWhileCollection.Index")\npublic typealias LazyPrefixWhileIndex<T> = LazyPrefixWhileCollection<T>.Index where T: Collection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "LazyPrefixWhileCollection")\npublic typealias LazyPrefixWhileBidirectionalCollection<T> = LazyPrefixWhileCollection<T> where T: BidirectionalCollection\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "ReversedCollection")\npublic typealias ReversedRandomAccessCollection<T: RandomAccessCollection> = ReversedCollection<T>\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "ReversedCollection.Index")\npublic typealias ReversedIndex<T: BidirectionalCollection> = ReversedCollection<T>.Index\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")\npublic typealias BidirectionalSlice<T> = Slice<T> where T: BidirectionalCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")\npublic typealias RandomAccessSlice<T> = Slice<T> where T: RandomAccessCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")\npublic typealias RangeReplaceableSlice<T> = Slice<T> where T: RangeReplaceableCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")\npublic typealias RangeReplaceableBidirectionalSlice<T> = Slice<T> where T: RangeReplaceableCollection & BidirectionalCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")\npublic typealias RangeReplaceableRandomAccessSlice<T> = Slice<T> where T: RangeReplaceableCollection & RandomAccessCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")\npublic typealias MutableSlice<T> = Slice<T> where T: MutableCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")\npublic typealias MutableBidirectionalSlice<T> = Slice<T> where T: MutableCollection & BidirectionalCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")\npublic typealias MutableRandomAccessSlice<T> = Slice<T> where T: MutableCollection & RandomAccessCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")\npublic typealias MutableRangeReplaceableSlice<T> = Slice<T> where T: MutableCollection & RangeReplaceableCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")\npublic typealias MutableRangeReplaceableBidirectionalSlice<T> = Slice<T> where T: MutableCollection & RangeReplaceableCollection & BidirectionalCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "Slice")\npublic typealias MutableRangeReplaceableRandomAccessSlice<T> = Slice<T> where T: MutableCollection & RangeReplaceableCollection & RandomAccessCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "DefaultIndices")\npublic typealias DefaultBidirectionalIndices<T> = DefaultIndices<T> where T: BidirectionalCollection\n@available(swift, deprecated: 4.0, obsoleted: 5.0, renamed: "DefaultIndices")\npublic typealias DefaultRandomAccessIndices<T> = DefaultIndices<T> where T: RandomAccessCollection\n\n// Deprecated by SE-0115.\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByNilLiteral")\npublic typealias NilLiteralConvertible = ExpressibleByNilLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinIntegerLiteral")\npublic typealias _BuiltinIntegerLiteralConvertible = _ExpressibleByBuiltinIntegerLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByIntegerLiteral")\npublic typealias IntegerLiteralConvertible = ExpressibleByIntegerLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinFloatLiteral")\npublic typealias _BuiltinFloatLiteralConvertible = _ExpressibleByBuiltinFloatLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByFloatLiteral")\npublic typealias FloatLiteralConvertible = ExpressibleByFloatLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinBooleanLiteral")\npublic typealias _BuiltinBooleanLiteralConvertible = _ExpressibleByBuiltinBooleanLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByBooleanLiteral")\npublic typealias BooleanLiteralConvertible = ExpressibleByBooleanLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinUnicodeScalarLiteral")\npublic typealias _BuiltinUnicodeScalarLiteralConvertible = _ExpressibleByBuiltinUnicodeScalarLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByUnicodeScalarLiteral")\npublic typealias UnicodeScalarLiteralConvertible = ExpressibleByUnicodeScalarLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinExtendedGraphemeClusterLiteral")\npublic typealias _BuiltinExtendedGraphemeClusterLiteralConvertible = _ExpressibleByBuiltinExtendedGraphemeClusterLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByExtendedGraphemeClusterLiteral")\npublic typealias ExtendedGraphemeClusterLiteralConvertible = ExpressibleByExtendedGraphemeClusterLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByBuiltinStringLiteral")\npublic typealias _BuiltinStringLiteralConvertible = _ExpressibleByBuiltinStringLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByStringLiteral")\npublic typealias StringLiteralConvertible = ExpressibleByStringLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByArrayLiteral")\npublic typealias ArrayLiteralConvertible = ExpressibleByArrayLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByDictionaryLiteral")\npublic typealias DictionaryLiteralConvertible = ExpressibleByDictionaryLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "ExpressibleByStringInterpolation")\npublic typealias StringInterpolationConvertible = ExpressibleByStringInterpolation\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByColorLiteral")\npublic typealias _ColorLiteralConvertible = _ExpressibleByColorLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByImageLiteral")\npublic typealias _ImageLiteralConvertible = _ExpressibleByImageLiteral\n@available(swift, deprecated: 3.0, obsoleted: 5.0, renamed: "_ExpressibleByFileReferenceLiteral")\npublic typealias _FileReferenceLiteralConvertible = _ExpressibleByFileReferenceLiteral\n\n@available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "ClosedRange.Index")\npublic typealias ClosedRangeIndex<T> = ClosedRange<T>.Index where T: Strideable, T.Stride: SignedInteger\n#endif\n\n/// An optional type that allows implicit member access.\n///\n/// The `ImplicitlyUnwrappedOptional` type is deprecated. To create an optional\n/// value that is implicitly unwrapped, place an exclamation mark (`!`) after\n/// the type that you want to denote as optional.\n///\n/// // An implicitly unwrapped optional integer\n/// let guaranteedNumber: Int! = 6\n///\n/// // An optional integer\n/// let possibleNumber: Int? = 5\n@available(*, unavailable, renamed: "Optional")\npublic typealias ImplicitlyUnwrappedOptional<Wrapped> = Optional<Wrapped>\n\nextension Range where Bound: Strideable, Bound.Stride: SignedInteger {\n /// Now that Range is conditionally a collection when Bound: Strideable,\n /// CountableRange is no longer needed. This is a deprecated initializer\n /// for any remaining uses of Range(countableRange).\n @available(swift, deprecated: 4.2, obsoleted: 5.0, message: "CountableRange is now a Range. No need to convert any more.")\n public init(_ other: Range<Bound>) {\n self = other\n } \n}\n\nextension ClosedRange where Bound: Strideable, Bound.Stride: SignedInteger {\n /// Now that Range is conditionally a collection when Bound: Strideable,\n /// CountableRange is no longer needed. This is a deprecated initializer\n /// for any remaining uses of Range(countableRange).\n @available(swift, deprecated: 4.2, obsoleted: 5.0, message: "CountableClosedRange is now a ClosedRange. No need to convert any more.")\n public init(_ other: ClosedRange<Bound>) {\n self = other\n } \n}\n\n#if !$Embedded\n@available(swift, deprecated: 5.0, renamed: "KeyValuePairs")\npublic typealias DictionaryLiteral<Key, Value> = KeyValuePairs<Key, Value>\n#endif\n\n#if !$Embedded\nextension LazySequenceProtocol {\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 @available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value")\n public func flatMap<ElementOfResult>(\n _ transform: @escaping (Elements.Element) -> ElementOfResult?\n ) -> LazyMapSequence<\n LazyFilterSequence<\n LazyMapSequence<Elements, ElementOfResult?>>,\n ElementOfResult\n > {\n return self.compactMap(transform)\n }\n}\n#endif\n\nextension String {\n /// A view of a string's contents as a collection of characters.\n ///\n /// Previous versions of Swift provided this view since String\n /// itself was not a collection. String is now a collection of\n /// characters, so this type is now just an alias for String.\n @available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please use String directly")\n public typealias CharacterView = String\n\n /// A view of the string's contents as a collection of characters.\n ///\n /// Previous versions of Swift provided this view since String\n /// itself was not a collection. String is now a collection of\n /// characters, so this type is now just an alias for String.\n @available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please use String directly")\n public var characters: String {\n get { return self }\n set { self = newValue }\n }\n\n /// Applies the given closure to a mutable view of the string's characters.\n ///\n /// Previous versions of Swift provided this view since String\n /// itself was not a collection. String is now a collection of\n /// characters, so this type is now just an alias for String.\n @available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please mutate the String directly")\n public mutating func withMutableCharacters<R>(\n _ body: (inout String) -> R\n ) -> R {\n return body(&self)\n }\n}\n\nextension String.UnicodeScalarView: _CustomPlaygroundQuickLookable {\n @available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UnicodeScalarView.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .text(description)\n }\n}\n\n//===--- Slicing Support --------------------------------------------------===//\n\n// @available(swift,deprecated: 5.0, renamed: "Unicode.UTF8")\npublic typealias UTF8 = Unicode.UTF8\n// @available(swift, deprecated: 5.0, renamed: "Unicode.UTF16")\npublic typealias UTF16 = Unicode.UTF16\n// @available(swift, deprecated: 5.0, renamed: "Unicode.UTF32")\npublic typealias UTF32 = Unicode.UTF32\n// @available(swift, deprecated: 5.0, renamed: "Unicode.Scalar")\npublic typealias UnicodeScalar = Unicode.Scalar\n\n\nextension String.UTF16View: _CustomPlaygroundQuickLookable {\n @available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UTF16View.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .text(description)\n }\n}\n\nextension String.UTF8View: _CustomPlaygroundQuickLookable {\n @available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UTF8View.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .text(description)\n }\n}\n\nextension Substring {\n /// A view of a string's contents as a collection of characters.\n ///\n /// Previous versions of Swift provided this view since String\n /// itself was not a collection. String is now a collection of\n /// characters, so this type is now just an alias for String.\n @available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please use Substring directly")\n public typealias CharacterView = Substring\n\n /// A view of the string's contents as a collection of characters.\n @available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please use Substring directly")\n public var characters: Substring {\n get {\n return self\n }\n set {\n self = newValue\n }\n }\n\n /// Applies the given closure to a mutable view of the string's characters.\n ///\n /// Previous versions of Swift provided this view since String\n /// itself was not a collection. String is now a collection of\n /// characters, so this type is now just an alias for String.\n @available(swift, deprecated: 3.2, obsoleted: 5.0, message: "Please mutate the Substring directly")\n public mutating func withMutableCharacters<R>(\n _ body: (inout Substring) -> R\n ) -> R {\n return body(&self)\n }\n\n private func _boundsCheck(_ range: Range<Index>) {\n _precondition(range.lowerBound >= startIndex,\n "String index range is out of bounds")\n _precondition(range.upperBound <= endIndex,\n "String index range is out of bounds")\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension Substring: _CustomPlaygroundQuickLookable {\n @available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "Substring.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return String(self).customPlaygroundQuickLook\n }\n}\n#endif\n\nextension Collection {\n @available(swift, deprecated: 4.0, obsoleted: 5.0, message: "all index distances are now of type Int")\n public func index<T: BinaryInteger>(_ i: Index, offsetBy n: T) -> Index {\n return index(i, offsetBy: Int(n))\n }\n @available(swift, deprecated: 4.0, obsoleted: 5.0, message: "all index distances are now of type Int")\n public func formIndex<T: BinaryInteger>(_ i: inout Index, offsetBy n: T) {\n return formIndex(&i, offsetBy: Int(n))\n }\n @available(swift, deprecated: 4.0, obsoleted: 5.0, message: "all index distances are now of type Int")\n public func index<T: BinaryInteger>(_ i: Index, offsetBy n: T, limitedBy limit: Index) -> Index? {\n return index(i, offsetBy: Int(n), limitedBy: limit)\n }\n @available(swift, deprecated: 4.0, obsoleted: 5.0, message: "all index distances are now of type Int")\n public func formIndex<T: BinaryInteger>(_ i: inout Index, offsetBy n: T, limitedBy limit: Index) -> Bool {\n return formIndex(&i, offsetBy: Int(n), limitedBy: limit)\n }\n @available(swift, deprecated: 4.0, obsoleted: 5.0, message: "all index distances are now of type Int")\n public func distance<T: BinaryInteger>(from start: Index, to end: Index) -> T {\n return numericCast(distance(from: start, to: end) as Int)\n }\n}\n\n\nextension UnsafeMutablePointer {\n @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "initialize(repeating:count:)")\n public func initialize(to newValue: Pointee, count: Int = 1) { \n unsafe initialize(repeating: newValue, count: count)\n }\n\n @available(swift, deprecated: 4.1, obsoleted: 5.0, message: "the default argument to deinitialize(count:) has been removed, please specify the count explicitly") \n @discardableResult\n public func deinitialize() -> UnsafeMutableRawPointer {\n return unsafe deinitialize(count: 1)\n }\n \n @available(swift, deprecated: 4.1, obsoleted: 5.0, message: "Swift currently only supports freeing entire heap blocks, use deallocate() instead")\n public func deallocate(capacity _: Int) { \n unsafe self.deallocate()\n }\n\n /// Initializes memory starting at this pointer's address with the elements\n /// of the given collection.\n ///\n /// The region of memory starting at this pointer and covering `source.count`\n /// instances of the pointer's `Pointee` type must be uninitialized or\n /// `Pointee` must be a trivial type. After calling `initialize(from:)`, the\n /// region is initialized.\n ///\n /// - Parameter source: A collection of elements of the pointer's `Pointee`\n /// type.\n // This is fundamentally unsafe since collections can underreport their count.\n @available(swift, deprecated: 4.2, obsoleted: 5.0, message: "it will be removed in Swift 5.0. Please use 'UnsafeMutableBufferPointer.initialize(from:)' instead")\n public func initialize<C: Collection>(from source: C)\n where C.Element == Pointee {\n let buf = unsafe UnsafeMutableBufferPointer(start: self, count: numericCast(source.count))\n var (remainders,writtenUpTo) = unsafe source._copyContents(initializing: buf)\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}\n\nextension UnsafeMutableRawPointer {\n @available(*, unavailable, renamed: "init(mutating:)")\n public init(@_nonEphemeral _ from: UnsafeRawPointer) { Builtin.unreachable() }\n\n @available(*, unavailable, renamed: "init(mutating:)")\n public init?(@_nonEphemeral _ from: UnsafeRawPointer?) { Builtin.unreachable() }\n\n @available(*, unavailable, renamed: "init(mutating:)")\n public init<T>(@_nonEphemeral _ from: UnsafePointer<T>) { Builtin.unreachable() }\n\n @available(*, unavailable, renamed: "init(mutating:)")\n public init?<T>(@_nonEphemeral _ from: UnsafePointer<T>?) { Builtin.unreachable() }\n}\n\nextension UnsafeRawPointer: @unsafe _CustomPlaygroundQuickLookable {\n internal var summary: String {\n let ptrValue = UInt64(\n bitPattern: Int64(Int(Builtin.ptrtoint_Word(_rawValue))))\n return ptrValue == 0\n ? "UnsafeRawPointer(nil)"\n : "UnsafeRawPointer(0x\(_uint64ToString(ptrValue, radix:16, uppercase:true)))"\n }\n\n @available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UnsafeRawPointer.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return unsafe .text(summary)\n }\n}\n\nextension UnsafeMutableRawPointer: @unsafe _CustomPlaygroundQuickLookable {\n private var summary: String {\n let ptrValue = UInt64(\n bitPattern: Int64(Int(Builtin.ptrtoint_Word(_rawValue))))\n return ptrValue == 0\n ? "UnsafeMutableRawPointer(nil)"\n : "UnsafeMutableRawPointer(0x\(_uint64ToString(ptrValue, radix:16, uppercase:true)))"\n }\n\n @available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UnsafeMutableRawPointer.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return unsafe .text(summary)\n }\n}\n\nextension UnsafePointer: @unsafe _CustomPlaygroundQuickLookable {\n private var summary: String {\n let ptrValue = UInt64(bitPattern: Int64(Int(Builtin.ptrtoint_Word(_rawValue))))\n return ptrValue == 0 \n ? "UnsafePointer(nil)" \n : "UnsafePointer(0x\(_uint64ToString(ptrValue, radix:16, uppercase:true)))"\n }\n\n @available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UnsafePointer.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: PlaygroundQuickLook {\n return unsafe .text(summary)\n }\n}\n\nextension UnsafeMutablePointer: @unsafe _CustomPlaygroundQuickLookable {\n private var summary: String {\n let ptrValue = UInt64(bitPattern: Int64(Int(Builtin.ptrtoint_Word(_rawValue))))\n return ptrValue == 0 \n ? "UnsafeMutablePointer(nil)" \n : "UnsafeMutablePointer(0x\(_uint64ToString(ptrValue, radix:16, uppercase:true)))"\n }\n\n @available(swift, deprecated: 4.2/*, obsoleted: 5.0*/, message: "UnsafeMutablePointer.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: PlaygroundQuickLook {\n return unsafe .text(summary)\n }\n}\n\n@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "UnsafeBufferPointer.Iterator")\npublic typealias UnsafeBufferPointerIterator<T> = UnsafeBufferPointer<T>.Iterator\n@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "UnsafeRawBufferPointer.Iterator")\npublic typealias UnsafeRawBufferPointerIterator<T> = UnsafeBufferPointer<T>.Iterator\n@available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "UnsafeRawBufferPointer.Iterator")\npublic typealias UnsafeMutableRawBufferPointerIterator<T> = UnsafeBufferPointer<T>.Iterator\n\nextension UnsafeMutableRawPointer {\n @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "allocate(byteCount:alignment:)")\n public static func allocate(\n bytes size: Int, alignedTo alignment: Int\n ) -> UnsafeMutableRawPointer {\n return UnsafeMutableRawPointer.allocate(byteCount: size, alignment: alignment)\n }\n \n @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "deallocate()", message: "Swift currently only supports freeing entire heap blocks, use deallocate() instead")\n public func deallocate(bytes _: Int, alignedTo _: Int) { \n unsafe self.deallocate()\n }\n\n @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "copyMemory(from:byteCount:)")\n public func copyBytes(from source: UnsafeRawPointer, count: Int) {\n unsafe copyMemory(from: source, byteCount: count)\n }\n\n @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "initializeMemory(as:repeating:count:)")\n @discardableResult\n public func initializeMemory<T>(\n as type: T.Type, at offset: Int = 0, count: Int = 1, to repeatedValue: T\n ) -> UnsafeMutablePointer<T> { \n return unsafe (self + offset * MemoryLayout<T>.stride).initializeMemory(\n as: type, repeating: repeatedValue, count: count)\n }\n\n @available(swift, deprecated: 4.1, obsoleted: 5.0, message: "it will be removed in Swift 5.0. Please use 'UnsafeMutableRawBufferPointer.initialize(from:)' instead")\n @discardableResult\n public func initializeMemory<C: Collection>(\n as type: C.Element.Type, from source: C\n ) -> UnsafeMutablePointer<C.Element> {\n // TODO: Optimize where `C` is a `ContiguousArrayBuffer`.\n // Initialize and bind each element of the container.\n var ptr = unsafe self\n for element in source {\n unsafe ptr.initializeMemory(as: C.Element.self, repeating: element, count: 1)\n unsafe ptr += MemoryLayout<C.Element>.stride\n }\n return unsafe UnsafeMutablePointer(_rawValue)\n }\n}\n\nextension UnsafeMutableRawBufferPointer {\n @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "allocate(byteCount:alignment:)")\n public static func allocate(count: Int) -> UnsafeMutableRawBufferPointer { \n return UnsafeMutableRawBufferPointer.allocate(\n byteCount: count, alignment: MemoryLayout<UInt>.alignment)\n }\n\n @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "copyMemory(from:)")\n public func copyBytes(from source: UnsafeRawBufferPointer) {\n unsafe copyMemory(from: source)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// The following overloads of flatMap are carefully crafted to allow the code\n// like the following:\n// ["hello"].flatMap { $0 }\n// return an array of strings without any type context in Swift 3 mode, at the\n// same time allowing the following code snippet to compile:\n// [0, 1].flatMap { x in\n// if String(x) == "foo" { return "bar" } else { return nil }\n// }\n// Note that the second overload is declared on a more specific protocol.\n// See: test/stdlib/StringFlatMap.swift for tests.\nextension Sequence {\n @available(swift, deprecated: 4.1/*, obsoleted: 5.1 */, renamed: "compactMap(_:)",\n message: "Please use compactMap(_:) for the case where closure returns an optional value")\n public func flatMap<ElementOfResult>(\n _ transform: (Element) throws -> ElementOfResult?\n ) rethrows -> [ElementOfResult] {\n return try _compactMap(transform)\n }\n}\n\nextension Collection {\n @available(swift, deprecated: 4.1, obsoleted: 5.0, renamed: "compactMap(_:)",\n message: "Please use compactMap(_:) for the case where closure returns an optional value")\n public func flatMap(\n _ transform: (Element) throws -> String?\n ) rethrows -> [String] {\n return try _compactMap(transform)\n }\n}\n\nextension Collection {\n /// Returns the first index in which an element of the collection satisfies\n /// the given predicate.\n @available(swift, deprecated: 5.0, renamed: "firstIndex(where:)")\n @inlinable\n public func index(\n where _predicate: (Element) throws -> Bool\n ) rethrows -> Index? {\n return try firstIndex(where: _predicate)\n }\n}\n\nextension Collection where Element: Equatable {\n /// Returns the first index where the specified value appears in the\n /// collection.\n @available(swift, deprecated: 5.0, renamed: "firstIndex(of:)")\n @inlinable\n public func index(of element: Element) -> Index? {\n return firstIndex(of: element)\n }\n}\n\nextension Zip2Sequence {\n @available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "Sequence1.Iterator")\n public typealias Stream1 = Sequence1.Iterator\n @available(swift, deprecated: 4.2, obsoleted: 5.0, renamed: "Sequence2.Iterator")\n public typealias Stream2 = Sequence2.Iterator\n}\n\n\n//===--- QuickLooks -------------------------------------------------------===//\n\n/// The sum of types that can be used as a Quick Look representation.\n///\n/// The `PlaygroundQuickLook` protocol is deprecated, and will be removed from\n/// the standard library in a future Swift release. To customize the logging of\n/// your type in a playground, conform to the\n/// `CustomPlaygroundDisplayConvertible` protocol, which does not use the\n/// `PlaygroundQuickLook` enum.\n///\n/// If you need to provide a customized playground representation in Swift 4.0\n/// or Swift 3.2 or earlier, use a conditional compilation block:\n///\n/// #if swift(>=4.1) || (swift(>=3.3) && !swift(>=4.0))\n/// // With Swift 4.1 and later (including Swift 3.3 and later), use\n/// // the CustomPlaygroundDisplayConvertible protocol.\n/// #else\n/// // With Swift 4.0 and Swift 3.2 and earlier, use PlaygroundQuickLook\n/// // and the CustomPlaygroundQuickLookable protocol.\n/// #endif\n@available(swift, deprecated: 4.2, message: "PlaygroundQuickLook will be removed in a future Swift version. For customizing how types are presented in playgrounds, use CustomPlaygroundDisplayConvertible instead.")\npublic typealias PlaygroundQuickLook = _PlaygroundQuickLook\n\n@frozen // rdar://problem/38719739 - needed by LLDB\npublic enum _PlaygroundQuickLook {\n case text(String)\n case int(Int64)\n case uInt(UInt64)\n case float(Float32)\n case double(Float64)\n case image(Any)\n case sound(Any)\n case color(Any)\n case bezierPath(Any)\n case attributedString(Any)\n case rectangle(Float64, Float64, Float64, Float64)\n case point(Float64, Float64)\n case size(Float64, Float64)\n case bool(Bool)\n case range(Int64, Int64)\n case view(Any)\n case sprite(Any)\n case url(String)\n case _raw([UInt8], String)\n}\n\n@available(*, unavailable)\nextension _PlaygroundQuickLook: Sendable {}\n\n#if SWIFT_ENABLE_REFLECTION\nextension _PlaygroundQuickLook {\n /// Creates a new Quick Look for the given instance.\n ///\n /// If the dynamic type of `subject` conforms to\n /// `CustomPlaygroundQuickLookable`, the result is found by calling its\n /// `customPlaygroundQuickLook` property. Otherwise, the result is\n /// synthesized by the language. In some cases, the synthesized result may\n /// be `.text(String(reflecting: subject))`.\n ///\n /// - Note: If the dynamic type of `subject` has value semantics, subsequent\n /// mutations of `subject` will not observable in the Quick Look. In\n /// general, though, the observability of such mutations is unspecified.\n ///\n /// - Parameter subject: The instance to represent with the resulting Quick\n /// Look.\n @available(swift, deprecated: 4.2, obsoleted: 5.0, message: "PlaygroundQuickLook will be removed in a future Swift version.")\n public init(reflecting subject: Any) {\n if let customized = subject as? _CustomPlaygroundQuickLookable {\n self = customized.customPlaygroundQuickLook\n }\n else if let customized = subject as? __DefaultCustomPlaygroundQuickLookable {\n self = customized._defaultCustomPlaygroundQuickLook\n }\n else {\n if let q = Mirror.quickLookObject(subject) {\n self = q\n }\n else {\n self = .text(String(reflecting: subject))\n }\n }\n }\n}\n#endif\n\n/// A type that explicitly supplies its own playground Quick Look.\n///\n/// The `CustomPlaygroundQuickLookable` protocol is deprecated, and will be\n/// removed from the standard library in a future Swift release. To customize\n/// the logging of your type in a playground, conform to the\n/// `CustomPlaygroundDisplayConvertible` protocol.\n///\n/// If you need to provide a customized playground representation in Swift 4.0\n/// or Swift 3.2 or earlier, use a conditional compilation block:\n///\n/// #if swift(>=4.1) || (swift(>=3.3) && !swift(>=4.0))\n/// // With Swift 4.1 and later (including Swift 3.3 and later),\n/// // conform to CustomPlaygroundDisplayConvertible.\n/// extension MyType: CustomPlaygroundDisplayConvertible { /*...*/ }\n/// #else\n/// // Otherwise, on Swift 4.0 and Swift 3.2 and earlier,\n/// // conform to CustomPlaygroundQuickLookable.\n/// extension MyType: CustomPlaygroundQuickLookable { /*...*/ }\n/// #endif\n@available(swift, deprecated: 4.2, obsoleted: 5.0, message: "CustomPlaygroundQuickLookable will be removed in a future Swift version. For customizing how types are presented in playgrounds, use CustomPlaygroundDisplayConvertible instead.")\npublic typealias CustomPlaygroundQuickLookable = _CustomPlaygroundQuickLookable\n\n//@available(swift, obsoleted: 5.0)\npublic protocol _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for this instance.\n ///\n /// If this type has value semantics, the `PlaygroundQuickLook` instance\n /// should be unaffected by subsequent mutations.\n var customPlaygroundQuickLook: _PlaygroundQuickLook { get }\n}\n\n// Double-underscored real version allows us to keep using this in AppKit while\n// warning for non-SDK use. This is probably overkill but it doesn't cost\n// anything.\n@available(swift, deprecated: 4.2, obsoleted: 5.0, message: "_DefaultCustomPlaygroundQuickLookable will be removed in a future Swift version. For customizing how types are presented in playgrounds, use CustomPlaygroundDisplayConvertible instead.")\npublic typealias _DefaultCustomPlaygroundQuickLookable = __DefaultCustomPlaygroundQuickLookable\n\n// @available(swift, obsoleted: 5.0)\npublic protocol __DefaultCustomPlaygroundQuickLookable {\n var _defaultCustomPlaygroundQuickLook: _PlaygroundQuickLook { get }\n}\n\nextension String {\n /// A type that represents the number of steps between two `String.Index`\n /// values, where one value is reachable from the other.\n ///\n /// In Swift, *reachability* refers to the ability to produce one value from\n /// the other through zero or more applications of `index(after:)`.\n @available(*, deprecated, message: "All index distances are now of type Int")\n public typealias IndexDistance = Int\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_MigrationSupport.swift
cpp_apple_swift_stdlib_public_core_MigrationSupport.swift
Swift
36,586
0.8
0.04577
0.269817
react-lib
679
2025-06-06T10:17:53.177624
Apache-2.0
false
d5a8c51fd0ec0c6ce75e6b1634cadd44
//===--- Mirror.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// FIXME: ExistentialCollection needs to be supported before this will work\n// without the ObjC Runtime.\n\n#if SWIFT_ENABLE_REFLECTION\n\n/// A representation of the substructure and display style of an instance of\n/// any type.\n///\n/// A mirror describes the parts that make up a particular instance, such as\n/// the instance's stored properties, collection or tuple elements, or its\n/// active enumeration case. Mirrors also provide a "display style" property\n/// that suggests how this mirror might be rendered.\n///\n/// Playgrounds and the debugger use the `Mirror` type to display\n/// representations of values of any type. For example, when you pass an\n/// instance to the `dump(_:_:_:_:)` function, a mirror is used to render that\n/// instance's runtime contents.\n///\n/// struct Point {\n/// let x: Int, y: Int\n/// }\n///\n/// let p = Point(x: 21, y: 30)\n/// print(String(reflecting: p))\n/// // Prints "▿ Point\n/// // - x: 21\n/// // - y: 30"\n///\n/// To customize the mirror representation of a custom type, add conformance to\n/// the `CustomReflectable` protocol.\npublic struct Mirror {\n /// The static type of the subject being reflected.\n ///\n /// This type may differ from the subject's dynamic type when this mirror\n /// is the `superclassMirror` of another mirror.\n public let subjectType: Any.Type\n\n /// A collection of `Child` elements describing the structure of the\n /// reflected subject.\n public let children: Children\n\n /// A suggested display style for the reflected subject.\n public let displayStyle: DisplayStyle?\n\n internal let _makeSuperclassMirror: () -> Mirror?\n internal let _defaultDescendantRepresentation: _DefaultDescendantRepresentation\n\n /// Creates a mirror that reflects on the given instance.\n ///\n /// If the dynamic type of `subject` conforms to `CustomReflectable`, the\n /// resulting mirror is determined by its `customMirror` property.\n /// Otherwise, the result is generated by the language.\n ///\n /// If the dynamic type of `subject` has value semantics, subsequent\n /// mutations of `subject` will not observable in `Mirror`. In general,\n /// though, the observability of mutations is unspecified.\n ///\n /// - Parameter subject: The instance for which to create a mirror.\n public init(reflecting subject: Any) {\n if case let customized as CustomReflectable = subject {\n self = customized.customMirror\n } else {\n self = Mirror(internalReflecting: subject)\n }\n }\n\n /// Creates a mirror representing the given subject with a specified\n /// structure.\n ///\n /// You use this initializer from within your type's `customMirror`\n /// implementation to create a customized mirror.\n ///\n /// If `subject` is a class instance, `ancestorRepresentation` determines\n /// whether ancestor classes will be represented and whether their\n /// `customMirror` implementations will be used. By default, the\n /// `customMirror` implementation of any ancestors is ignored. To prevent\n /// bypassing customized ancestors, pass\n /// `.customized({ super.customMirror })` as the `ancestorRepresentation`\n /// parameter when implementing your type's `customMirror` property.\n ///\n /// - Parameters:\n /// - subject: The instance to represent in the new mirror.\n /// - children: The structure to use for the mirror. The collection\n /// traversal modeled by `children` is captured so that the resulting\n /// mirror's children may be upgraded to a bidirectional or random\n /// access collection later. See the `children` property for details.\n /// - displayStyle: The preferred display style for the mirror when\n /// presented in the debugger or in a playground. The default is `nil`.\n /// - ancestorRepresentation: The means of generating the subject's\n /// ancestor representation. `ancestorRepresentation` is ignored if\n /// `subject` is not a class instance. The default is `.generated`.\n public init<Subject, C: Collection>(\n _ subject: Subject,\n children: C,\n displayStyle: DisplayStyle? = nil,\n ancestorRepresentation: AncestorRepresentation = .generated\n ) where C.Element == Child {\n\n self.subjectType = Subject.self\n self._makeSuperclassMirror = Mirror._superclassIterator(\n subject, ancestorRepresentation)\n\n self.children = Children(children)\n self.displayStyle = displayStyle\n self._defaultDescendantRepresentation\n = subject is CustomLeafReflectable ? .suppressed : .generated\n }\n\n /// Creates a mirror representing the given subject with unlabeled children.\n ///\n /// You use this initializer from within your type's `customMirror`\n /// implementation to create a customized mirror, particularly for custom\n /// types that are collections. The labels of the resulting mirror's\n /// `children` collection are all `nil`.\n ///\n /// If `subject` is a class instance, `ancestorRepresentation` determines\n /// whether ancestor classes will be represented and whether their\n /// `customMirror` implementations will be used. By default, the\n /// `customMirror` implementation of any ancestors is ignored. To prevent\n /// bypassing customized ancestors, pass\n /// `.customized({ super.customMirror })` as the `ancestorRepresentation`\n /// parameter when implementing your type's `customMirror` property.\n ///\n /// - Parameters:\n /// - subject: The instance to represent in the new mirror.\n /// - unlabeledChildren: The children to use for the mirror. The collection\n /// traversal modeled by `unlabeledChildren` is captured so that the\n /// resulting mirror's children may be upgraded to a bidirectional or\n /// random access collection later. See the `children` property for\n /// details.\n /// - displayStyle: The preferred display style for the mirror when\n /// presented in the debugger or in a playground. The default is `nil`.\n /// - ancestorRepresentation: The means of generating the subject's\n /// ancestor representation. `ancestorRepresentation` is ignored if\n /// `subject` is not a class instance. The default is `.generated`.\n public init<Subject, C: Collection>(\n _ subject: Subject,\n unlabeledChildren: C,\n displayStyle: DisplayStyle? = nil,\n ancestorRepresentation: AncestorRepresentation = .generated\n ) {\n self.subjectType = Subject.self\n self._makeSuperclassMirror = Mirror._superclassIterator(\n subject, ancestorRepresentation)\n\n let lazyChildren =\n unlabeledChildren.lazy.map { Child(label: nil, value: $0) }\n self.children = Children(lazyChildren)\n\n self.displayStyle = displayStyle\n self._defaultDescendantRepresentation\n = subject is CustomLeafReflectable ? .suppressed : .generated\n }\n\n /// Creates a mirror representing the given subject using a dictionary\n /// literal for the structure.\n ///\n /// You use this initializer from within your type's `customMirror`\n /// implementation to create a customized mirror. Pass a dictionary literal\n /// with string keys as `children`. Although an *actual* dictionary is\n /// arbitrarily-ordered, when you create a mirror with a dictionary literal,\n /// the ordering of the mirror's `children` will exactly match that of the\n /// literal you pass.\n ///\n /// If `subject` is a class instance, `ancestorRepresentation` determines\n /// whether ancestor classes will be represented and whether their\n /// `customMirror` implementations will be used. By default, the\n /// `customMirror` implementation of any ancestors is ignored. To prevent\n /// bypassing customized ancestors, pass\n /// `.customized({ super.customMirror })` as the `ancestorRepresentation`\n /// parameter when implementing your type's `customMirror` property.\n ///\n /// - Parameters:\n /// - subject: The instance to represent in the new mirror.\n /// - children: A dictionary literal to use as the structure for the\n /// mirror. The `children` collection of the resulting mirror may be\n /// upgraded to a random access collection later. See the `children`\n /// property for details.\n /// - displayStyle: The preferred display style for the mirror when\n /// presented in the debugger or in a playground. The default is `nil`.\n /// - ancestorRepresentation: The means of generating the subject's\n /// ancestor representation. `ancestorRepresentation` is ignored if\n /// `subject` is not a class instance. The default is `.generated`.\n public init<Subject>(\n _ subject: Subject,\n children: KeyValuePairs<String, Any>,\n displayStyle: DisplayStyle? = nil,\n ancestorRepresentation: AncestorRepresentation = .generated\n ) {\n self.subjectType = Subject.self\n self._makeSuperclassMirror = Mirror._superclassIterator(\n subject, ancestorRepresentation)\n\n let lazyChildren = children.lazy.map { Child(label: $0.0, value: $0.1) }\n self.children = Children(lazyChildren)\n\n self.displayStyle = displayStyle\n self._defaultDescendantRepresentation\n = subject is CustomLeafReflectable ? .suppressed : .generated\n }\n\n /// A mirror of the subject's superclass, if one exists.\n public var superclassMirror: Mirror? {\n return _makeSuperclassMirror()\n }\n}\n\n@available(*, unavailable)\nextension Mirror: Sendable {}\n\nextension Mirror {\n /// Representation of descendant classes that don't override\n /// `customMirror`.\n ///\n /// Note that the effect of this setting goes no deeper than the\n /// nearest descendant class that overrides `customMirror`, which\n /// in turn can determine representation of *its* descendants.\n internal enum _DefaultDescendantRepresentation {\n /// Generate a default mirror for descendant classes that don't\n /// override `customMirror`.\n ///\n /// This case is the default.\n case generated\n\n /// Suppress the representation of descendant classes that don't\n /// override `customMirror`.\n ///\n /// This option may be useful at the root of a class cluster, where\n /// implementation details of descendants should generally not be\n /// visible to clients.\n case suppressed\n }\n\n /// The representation to use for ancestor classes.\n ///\n /// A class that conforms to the `CustomReflectable` protocol can control how\n /// its mirror represents ancestor classes by initializing the mirror\n /// with an `AncestorRepresentation`. This setting has no effect on mirrors\n /// reflecting value type instances.\n public enum AncestorRepresentation {\n\n /// Generates a default mirror for all ancestor classes.\n ///\n /// This case is the default when initializing a `Mirror` instance.\n ///\n /// When you use this option, a subclass's mirror generates default mirrors\n /// even for ancestor classes that conform to the `CustomReflectable`\n /// protocol. To avoid dropping the customization provided by ancestor\n /// classes, an override of `customMirror` should pass\n /// `.customized({ super.customMirror })` as `ancestorRepresentation` when\n /// initializing its mirror.\n case generated\n\n /// Uses the nearest ancestor's implementation of `customMirror` to create\n /// a mirror for that ancestor.\n ///\n /// Other classes derived from such an ancestor are given a default mirror.\n /// The payload for this option should always be `{ super.customMirror }`:\n ///\n /// var customMirror: Mirror {\n /// return Mirror(\n /// self,\n /// children: ["someProperty": self.someProperty],\n /// ancestorRepresentation: .customized({ super.customMirror })) // <==\n /// }\n case customized(() -> Mirror)\n\n /// Suppresses the representation of all ancestor classes.\n ///\n /// In a mirror created with this ancestor representation, the\n /// `superclassMirror` property is `nil`.\n case suppressed\n }\n\n /// An element of the reflected instance's structure.\n ///\n /// When the `label` component in not `nil`, it may represent the name of a\n /// stored property or an active `enum` case. If you pass strings to the\n /// `descendant(_:_:)` method, labels are used for lookup.\n public typealias Child = (label: String?, value: Any)\n\n /// The type used to represent substructure.\n ///\n /// When working with a mirror that reflects a bidirectional or random access\n /// collection, you may find it useful to "upgrade" instances of this type\n /// to `AnyBidirectionalCollection` or `AnyRandomAccessCollection`. For\n /// example, to display the last twenty children of a mirror if they can be\n /// accessed efficiently, you write the following code:\n ///\n /// if let b = AnyBidirectionalCollection(someMirror.children) {\n /// for element in b.suffix(20) {\n /// print(element)\n /// }\n /// }\n public typealias Children = AnyCollection<Child>\n\n /// A suggestion of how a mirror's subject is to be interpreted.\n ///\n /// Playgrounds and the debugger will show a representation similar\n /// to the one used for instances of the kind indicated by the\n /// `DisplayStyle` case name when the mirror is used for display.\n public enum DisplayStyle: Sendable {\n case `struct`, `class`, `enum`, tuple, optional, collection\n case dictionary, `set`\n }\n\n internal static func _noSuperclassMirror() -> Mirror? { return nil }\n\n @_semantics("optimize.sil.specialize.generic.never")\n @inline(never)\n internal static func _superclassIterator<Subject>(\n _ subject: Subject, _ ancestorRepresentation: AncestorRepresentation\n ) -> () -> Mirror? {\n\n if let subjectClass = Subject.self as? AnyClass,\n let superclass = _getSuperclass(subjectClass) {\n\n switch ancestorRepresentation {\n case .generated:\n return {\n Mirror(internalReflecting: subject, subjectType: superclass)\n }\n case .customized(let makeAncestor):\n return {\n let ancestor = makeAncestor()\n if superclass == ancestor.subjectType\n || ancestor._defaultDescendantRepresentation == .suppressed {\n return ancestor\n } else {\n return Mirror(internalReflecting: subject,\n subjectType: superclass,\n customAncestor: ancestor)\n }\n }\n case .suppressed:\n break\n }\n }\n return Mirror._noSuperclassMirror\n }\n}\n\n@available(*, unavailable)\nextension Mirror.AncestorRepresentation: Sendable {}\n\n/// A type that explicitly supplies its own mirror.\n///\n/// You can create a mirror for any type using the `Mirror(reflecting:)`\n/// initializer, but if you are not satisfied with the mirror supplied for\n/// your type by default, you can make it conform to `CustomReflectable` and\n/// return a custom `Mirror` instance.\npublic protocol CustomReflectable {\n /// The custom mirror for this instance.\n ///\n /// If this type has value semantics, the mirror should be unaffected by\n /// subsequent mutations of the instance.\n var customMirror: Mirror { get }\n}\n\n/// A type that explicitly supplies its own mirror, but whose\n/// descendant classes are not represented in the mirror unless they\n/// also override `customMirror`.\npublic protocol CustomLeafReflectable: CustomReflectable {}\n\n//===--- Addressing -------------------------------------------------------===//\n\n/// A protocol for legitimate arguments to `Mirror`'s `descendant`\n/// method.\n///\n/// Do not declare new conformances to this protocol; they will not\n/// work as expected.\npublic protocol MirrorPath {\n // FIXME(ABI)#49 (Sealed Protocols): this protocol should be "non-open" and\n // you shouldn't be able to create conformances.\n}\nextension Int: MirrorPath {}\nextension String: MirrorPath {}\n\nextension Mirror {\n internal struct _Dummy: CustomReflectable {\n internal init(mirror: Mirror) {\n self.mirror = mirror\n }\n internal var mirror: Mirror\n internal var customMirror: Mirror { return mirror }\n }\n\n /// Returns a specific descendant of the reflected subject, or `nil` if no\n /// such descendant exists.\n ///\n /// Pass a variadic list of string and integer arguments. Each string\n /// argument selects the first child with a matching label. Each integer\n /// argument selects the child at that offset. For example, passing\n /// `1, "two", 3` as arguments to `myMirror.descendant(_:_:)` is equivalent\n /// to:\n ///\n /// var result: Any? = nil\n /// let children = myMirror.children\n /// if let i0 = children.index(\n /// children.startIndex, offsetBy: 1, limitedBy: children.endIndex),\n /// i0 != children.endIndex\n /// {\n /// let grandChildren = Mirror(reflecting: children[i0].value).children\n /// if let i1 = grandChildren.firstIndex(where: { $0.label == "two" }) {\n /// let greatGrandChildren =\n /// Mirror(reflecting: grandChildren[i1].value).children\n /// if let i2 = greatGrandChildren.index(\n /// greatGrandChildren.startIndex,\n /// offsetBy: 3,\n /// limitedBy: greatGrandChildren.endIndex),\n /// i2 != greatGrandChildren.endIndex\n /// {\n /// // Success!\n /// result = greatGrandChildren[i2].value\n /// }\n /// }\n /// }\n ///\n /// This function is suitable for exploring the structure of a mirror in a\n /// REPL or playground, but is not intended to be efficient. The efficiency\n /// of finding each element in the argument list depends on the argument\n /// type and the capabilities of the each level of the mirror's `children`\n /// collections. Each string argument requires a linear search, and unless\n /// the underlying collection supports random-access traversal, each integer\n /// argument also requires a linear operation.\n ///\n /// - Parameters:\n /// - first: The first mirror path component to access.\n /// - rest: Any remaining mirror path components.\n /// - Returns: The descendant of this mirror specified by the given mirror\n /// path components if such a descendant exists; otherwise, `nil`.\n public func descendant(\n _ first: MirrorPath, _ rest: MirrorPath...\n ) -> Any? {\n var result: Any = _Dummy(mirror: self)\n for e in [first] + rest {\n let children = Mirror(reflecting: result).children\n let position: Children.Index\n if case let label as String = e {\n position = children.firstIndex { $0.label == label } ?? children.endIndex\n }\n else if let offset = e as? Int {\n position = children.index(children.startIndex,\n offsetBy: offset,\n limitedBy: children.endIndex) ?? children.endIndex\n }\n else {\n _preconditionFailure(\n "Someone added a conformance to MirrorPath; that privilege is reserved to the standard library")\n }\n if position == children.endIndex { return nil }\n result = children[position].value\n }\n return result\n }\n}\n\n#else // SWIFT_ENABLE_REFLECTION\n\n@available(*, unavailable)\npublic struct Mirror {\n public enum AncestorRepresentation {\n case generated\n case customized(() -> Mirror)\n case suppressed\n }\n public init(reflecting subject: Any) { Builtin.unreachable() }\n public typealias Child = (label: String?, value: Any)\n public typealias Children = AnyCollection<Child>\n public enum DisplayStyle: Sendable {\n case `struct`, `class`, `enum`, tuple, optional, collection\n case dictionary, `set`\n }\n public init<Subject, C: Collection>(\n _ subject: Subject,\n children: C,\n displayStyle: DisplayStyle? = nil,\n ancestorRepresentation: AncestorRepresentation = .generated\n ) where C.Element == Child {\n Builtin.unreachable()\n }\n public init<Subject, C: Collection>(\n _ subject: Subject,\n unlabeledChildren: C,\n displayStyle: DisplayStyle? = nil,\n ancestorRepresentation: AncestorRepresentation = .generated\n ) {\n Builtin.unreachable()\n }\n public init<Subject>(\n _ subject: Subject,\n children: KeyValuePairs<String, Any>,\n displayStyle: DisplayStyle? = nil,\n ancestorRepresentation: AncestorRepresentation = .generated\n ) {\n Builtin.unreachable()\n }\n public let subjectType: Any.Type\n public let children: Children\n public let displayStyle: DisplayStyle?\n public var superclassMirror: Mirror? { Builtin.unreachable() }\n}\n\n@available(*, unavailable)\npublic protocol CustomReflectable {\n var customMirror: Mirror { get }\n}\n\n@available(*, unavailable)\npublic protocol CustomLeafReflectable: CustomReflectable {}\n\n@available(*, unavailable)\npublic protocol MirrorPath {}\n@available(*, unavailable)\nextension Int: MirrorPath {}\n@available(*, unavailable)\nextension String: MirrorPath {}\n\n@available(*, unavailable)\nextension Mirror {\n public func descendant(_ first: MirrorPath, _ rest: MirrorPath...) -> Any? {\n Builtin.unreachable()\n }\n}\n\n#endif // SWIFT_ENABLE_REFLECTION\n\n//===--- General Utilities ------------------------------------------------===//\n\n@_unavailableInEmbedded\nextension String {\n /// Creates a string representing the given value.\n ///\n /// Use this initializer to convert an instance of any type to its preferred\n /// representation as a `String` instance. The initializer creates the\n /// string representation of `instance` in one of the following ways,\n /// depending on its protocol conformance:\n ///\n /// - If `instance` conforms to the `TextOutputStreamable` protocol, the\n /// result is obtained by calling `instance.write(to: s)` on an empty\n /// string `s`.\n /// - If `instance` conforms to the `CustomStringConvertible` protocol, the\n /// result is `instance.description`.\n /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,\n /// the result is `instance.debugDescription`.\n /// - An unspecified result is supplied automatically by the Swift standard\n /// library.\n ///\n /// For example, this custom `Point` struct uses the default representation\n /// supplied by the standard library.\n ///\n /// struct Point {\n /// let x: Int, y: Int\n /// }\n ///\n /// let p = Point(x: 21, y: 30)\n /// print(String(describing: p))\n /// // Prints "Point(x: 21, y: 30)"\n ///\n /// After adding `CustomStringConvertible` conformance by implementing the\n /// `description` property, `Point` provides its own custom representation.\n ///\n /// extension Point: CustomStringConvertible {\n /// var description: String {\n /// return "(\(x), \(y))"\n /// }\n /// }\n ///\n /// print(String(describing: p))\n /// // Prints "(21, 30)"\n public init<Subject>(describing instance: Subject) {\n self.init()\n _print_unlocked(instance, &self)\n }\n\n // These overloads serve as fast paths for init(describing:), but they \n // also preserve source compatibility for clients which accidentally \n // used init(stringInterpolationSegment:) through constructs like \n // myArray.map(String.init).\n\n /// Creates a string representing the given value.\n ///\n /// Use this initializer to convert an instance of any type to its preferred\n /// representation as a `String` instance. The initializer creates the\n /// string representation of `instance` in one of the following ways,\n /// depending on its protocol conformance:\n ///\n /// - If `instance` conforms to the `TextOutputStreamable` protocol, the\n /// result is obtained by calling `instance.write(to: s)` on an empty\n /// string `s`.\n /// - If `instance` conforms to the `CustomStringConvertible` protocol, the\n /// result is `instance.description`.\n /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,\n /// the result is `instance.debugDescription`.\n /// - An unspecified result is supplied automatically by the Swift standard\n /// library.\n ///\n /// For example, this custom `Point` struct uses the default representation\n /// supplied by the standard library.\n ///\n /// struct Point {\n /// let x: Int, y: Int\n /// }\n ///\n /// let p = Point(x: 21, y: 30)\n /// print(String(describing: p))\n /// // Prints "Point(x: 21, y: 30)"\n ///\n /// After adding `CustomStringConvertible` conformance by implementing the\n /// `description` property, `Point` provides its own custom representation.\n ///\n /// extension Point: CustomStringConvertible {\n /// var description: String {\n /// return "(\(x), \(y))"\n /// }\n /// }\n ///\n /// print(String(describing: p))\n /// // Prints "(21, 30)"\n @inlinable\n public init<Subject: CustomStringConvertible>(describing instance: Subject) {\n self = instance.description\n }\n\n /// Creates a string representing the given value.\n ///\n /// Use this initializer to convert an instance of any type to its preferred\n /// representation as a `String` instance. The initializer creates the\n /// string representation of `instance` in one of the following ways,\n /// depending on its protocol conformance:\n ///\n /// - If `instance` conforms to the `TextOutputStreamable` protocol, the\n /// result is obtained by calling `instance.write(to: s)` on an empty\n /// string `s`.\n /// - If `instance` conforms to the `CustomStringConvertible` protocol, the\n /// result is `instance.description`.\n /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,\n /// the result is `instance.debugDescription`.\n /// - An unspecified result is supplied automatically by the Swift standard\n /// library.\n ///\n /// For example, this custom `Point` struct uses the default representation\n /// supplied by the standard library.\n ///\n /// struct Point {\n /// let x: Int, y: Int\n /// }\n ///\n /// let p = Point(x: 21, y: 30)\n /// print(String(describing: p))\n /// // Prints "Point(x: 21, y: 30)"\n ///\n /// After adding `CustomStringConvertible` conformance by implementing the\n /// `description` property, `Point` provides its own custom representation.\n ///\n /// extension Point: CustomStringConvertible {\n /// var description: String {\n /// return "(\(x), \(y))"\n /// }\n /// }\n ///\n /// print(String(describing: p))\n /// // Prints "(21, 30)"\n @inlinable\n public init<Subject: TextOutputStreamable>(describing instance: Subject) {\n self.init()\n instance.write(to: &self)\n }\n\n /// Creates a string representing the given value.\n ///\n /// Use this initializer to convert an instance of any type to its preferred\n /// representation as a `String` instance. The initializer creates the\n /// string representation of `instance` in one of the following ways,\n /// depending on its protocol conformance:\n ///\n /// - If `instance` conforms to the `TextOutputStreamable` protocol, the\n /// result is obtained by calling `instance.write(to: s)` on an empty\n /// string `s`.\n /// - If `instance` conforms to the `CustomStringConvertible` protocol, the\n /// result is `instance.description`.\n /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,\n /// the result is `instance.debugDescription`.\n /// - An unspecified result is supplied automatically by the Swift standard\n /// library.\n ///\n /// For example, this custom `Point` struct uses the default representation\n /// supplied by the standard library.\n ///\n /// struct Point {\n /// let x: Int, y: Int\n /// }\n ///\n /// let p = Point(x: 21, y: 30)\n /// print(String(describing: p))\n /// // Prints "Point(x: 21, y: 30)"\n ///\n /// After adding `CustomStringConvertible` conformance by implementing the\n /// `description` property, `Point` provides its own custom representation.\n ///\n /// extension Point: CustomStringConvertible {\n /// var description: String {\n /// return "(\(x), \(y))"\n /// }\n /// }\n ///\n /// print(String(describing: p))\n /// // Prints "(21, 30)"\n @inlinable\n public init<Subject>(describing instance: Subject)\n where Subject: CustomStringConvertible & TextOutputStreamable\n {\n self = instance.description\n }\n\n /// Creates a string with a detailed representation of the given value,\n /// suitable for debugging.\n ///\n /// Use this initializer to convert an instance of any type to its custom\n /// debugging representation. The initializer creates the string\n /// representation of `instance` in one of the following ways, depending on\n /// its protocol conformance:\n ///\n /// - If `subject` conforms to the `CustomDebugStringConvertible` protocol,\n /// the result is `subject.debugDescription`.\n /// - If `subject` conforms to the `CustomStringConvertible` protocol, the\n /// result is `subject.description`.\n /// - If `subject` conforms to the `TextOutputStreamable` protocol, the\n /// result is obtained by calling `subject.write(to: s)` on an empty\n /// string `s`.\n /// - An unspecified result is supplied automatically by the Swift standard\n /// library.\n ///\n /// For example, this custom `Point` struct uses the default representation\n /// supplied by the standard library.\n ///\n /// struct Point {\n /// let x: Int, y: Int\n /// }\n ///\n /// let p = Point(x: 21, y: 30)\n /// print(String(reflecting: p))\n /// // Prints "p: Point = {\n /// // x = 21\n /// // y = 30\n /// // }"\n ///\n /// After adding `CustomDebugStringConvertible` conformance by implementing\n /// the `debugDescription` property, `Point` provides its own custom\n /// debugging representation.\n ///\n /// extension Point: CustomDebugStringConvertible {\n /// var debugDescription: String {\n /// return "Point(x: \(x), y: \(y))"\n /// }\n /// }\n ///\n /// print(String(reflecting: p))\n /// // Prints "Point(x: 21, y: 30)"\n public init<Subject>(reflecting subject: Subject) {\n self.init()\n _debugPrint_unlocked(subject, &self)\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\n\n/// Reflection for `Mirror` itself.\nextension Mirror: CustomStringConvertible {\n public var description: String {\n return "Mirror for \(self.subjectType)"\n }\n}\n\nextension Mirror: CustomReflectable {\n public var customMirror: Mirror {\n return Mirror(self, children: [:])\n }\n}\n\n#endif // SWIFT_ENABLE_REFLECTION\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Mirror.swift
cpp_apple_swift_stdlib_public_core_Mirror.swift
Swift
30,844
0.95
0.088384
0.658073
python-kit
94
2024-12-16T07:51:35.483659
Apache-2.0
false
0dd9ecebf04aa48e3ed16523d3457e33
//===--- Mirrors.swift - Common _Mirror implementations -------------------===//\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#if SWIFT_ENABLE_REFLECTION\n\nextension Float: CustomReflectable {\n /// A mirror that reflects the `Float` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension Float: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `Float` instance.\n @available(*, deprecated, message: "Float.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .float(self)\n }\n}\n\nextension Double: CustomReflectable {\n /// A mirror that reflects the `Double` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension Double: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `Double` instance.\n @available(*, deprecated, message: "Double.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .double(self)\n }\n}\n\nextension Bool: CustomReflectable {\n /// A mirror that reflects the `Bool` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension Bool: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `Bool` instance.\n @available(*, deprecated, message: "Bool.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .bool(self)\n }\n}\n\nextension String: CustomReflectable {\n /// A mirror that reflects the `String` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension String: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `String` instance.\n @available(*, deprecated, message: "String.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .text(self)\n }\n}\n\nextension Character: CustomReflectable {\n /// A mirror that reflects the `Character` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension Character: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `Character` instance.\n @available(*, deprecated, message: "Character.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .text(String(self))\n }\n}\n\nextension Unicode.Scalar: CustomReflectable {\n /// A mirror that reflects the `Unicode.Scalar` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension Unicode.Scalar: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `Unicode.Scalar` instance.\n @available(*, deprecated, message: "Unicode.Scalar.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .uInt(UInt64(self))\n }\n}\n\nextension UInt8: CustomReflectable {\n /// A mirror that reflects the `UInt8` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension UInt8: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `UInt8` instance.\n @available(*, deprecated, message: "UInt8.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .uInt(UInt64(self))\n }\n}\n\nextension Int8: CustomReflectable {\n /// A mirror that reflects the `Int8` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension Int8: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `Int8` instance.\n @available(*, deprecated, message: "Int8.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .int(Int64(self))\n }\n}\n\nextension UInt16: CustomReflectable {\n /// A mirror that reflects the `UInt16` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension UInt16: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `UInt16` instance.\n @available(*, deprecated, message: "UInt16.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .uInt(UInt64(self))\n }\n}\n\nextension Int16: CustomReflectable {\n /// A mirror that reflects the `Int16` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension Int16: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `Int16` instance.\n @available(*, deprecated, message: "Int16.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .int(Int64(self))\n }\n}\n\nextension UInt32: CustomReflectable {\n /// A mirror that reflects the `UInt32` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension UInt32: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `UInt32` instance.\n @available(*, deprecated, message: "UInt32.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .uInt(UInt64(self))\n }\n}\n\nextension Int32: CustomReflectable {\n /// A mirror that reflects the `Int32` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension Int32: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `Int32` instance.\n @available(*, deprecated, message: "Int32.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .int(Int64(self))\n }\n}\n\nextension UInt64: CustomReflectable {\n /// A mirror that reflects the `UInt64` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension UInt64: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `UInt64` instance.\n @available(*, deprecated, message: "UInt64.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .uInt(UInt64(self))\n }\n}\n\nextension Int64: CustomReflectable {\n /// A mirror that reflects the `Int64` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension Int64: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `Int64` instance.\n @available(*, deprecated, message: "Int64.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .int(Int64(self))\n }\n}\n\nextension UInt: CustomReflectable {\n /// A mirror that reflects the `UInt` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension UInt: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `UInt` instance.\n @available(*, deprecated, message: "UInt.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .uInt(UInt64(self))\n }\n}\n\nextension Int: CustomReflectable {\n /// A mirror that reflects the `Int` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\nextension Int: _CustomPlaygroundQuickLookable {\n /// A custom playground Quick Look for the `Int` instance.\n @available(*, deprecated, message: "Int.customPlaygroundQuickLook will be removed in a future Swift version")\n public var customPlaygroundQuickLook: _PlaygroundQuickLook {\n return .int(Int64(self))\n }\n}\n\n#if !(os(Windows) || os(Android) || ($Embedded && !os(Linux) && !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS)))) && (arch(i386) || arch(x86_64))\nextension Float80: CustomReflectable {\n /// A mirror that reflects the Float80 instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n#endif\n\n@available(SwiftStdlib 6.0, *)\nextension UInt128: CustomReflectable {\n /// A mirror that reflects the `UInt128` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension Int128: CustomReflectable {\n /// A mirror that reflects the `Int128` instance.\n public var customMirror: Mirror {\n return Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Mirrors.swift
cpp_apple_swift_stdlib_public_core_Mirrors.swift
Swift
9,837
0.8
0.071429
0.205761
python-kit
843
2024-12-28T03:50:07.194009
GPL-3.0
false
d704da76c423d5a8ef57229be73adfea
//===----------------------------------------------------------------------===//\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// Extern C functions\n//===----------------------------------------------------------------------===//\n\n// FIXME: Once we have an FFI interface, make these have proper function bodies\n\n/// Returns if `x` is a power of 2.\n@_transparent\npublic // @testable\nfunc _isPowerOf2(_ x: UInt) -> Bool {\n if x == 0 {\n return false\n }\n // Note: use unchecked subtraction because we have checked that `x` is not\n // zero.\n return x & (x &- 1) == 0\n}\n\n/// Returns if `x` is a power of 2.\n@_transparent\npublic // @testable\nfunc _isPowerOf2(_ x: Int) -> Bool {\n if x <= 0 {\n return false\n }\n // Note: use unchecked subtraction because we have checked that `x` is not\n // `Int.min`.\n return x & (x &- 1) == 0\n}\n\n#if _runtime(_ObjC)\n@_transparent\npublic func _autorelease(_ x: AnyObject) {\n Builtin.retain(x)\n Builtin.autorelease(x)\n}\n#endif\n\n\n@available(SwiftStdlib 5.7, *)\n@_silgen_name("swift_getFunctionFullNameFromMangledName")\npublic // SPI (Distributed)\nfunc _getFunctionFullNameFromMangledNameImpl(\n _ mangledName: UnsafePointer<UInt8>, _ mangledNameLength: UInt\n) -> (UnsafePointer<UInt8>, UInt)\n\n/// Given a function's mangled name, return a human readable name.\n/// Used e.g. by Distributed.RemoteCallTarget to hide mangled names.\n@available(SwiftStdlib 5.7, *)\n@_unavailableInEmbedded\npublic // SPI (Distributed)\nfunc _getFunctionFullNameFromMangledName(mangledName: String) -> String? {\n let mangledNameUTF8 = Array(mangledName.utf8)\n let (stringPtr, count) =\n unsafe mangledNameUTF8.withUnsafeBufferPointer { (mangledNameUTF8) in\n return unsafe _getFunctionFullNameFromMangledNameImpl(\n mangledNameUTF8.baseAddress!,\n UInt(mangledNameUTF8.endIndex))\n }\n\n guard count > 0 else {\n return nil\n }\n\n return unsafe String._fromUTF8Repairing(\n UnsafeBufferPointer(start: stringPtr, count: Int(count))).0\n}\n\n// FIXME(ABI)#51 : this API should allow controlling different kinds of\n// qualification separately: qualification with module names and qualification\n// with type names that we are nested in.\n// But we can place it behind #if _runtime(_Native) and remove it from ABI on\n// Apple platforms, deferring discussions mentioned above.\n@_silgen_name("swift_getTypeName")\npublic func _getTypeName(_ type: Any.Type, qualified: Bool)\n -> (UnsafePointer<UInt8>, Int)\n\n/// Returns the demangled qualified name of a metatype.\n@_semantics("typeName")\n@_unavailableInEmbedded\npublic // @testable\nfunc _typeName(_ type: Any.Type, qualified: Bool = true) -> String {\n let (stringPtr, count) = unsafe _getTypeName(type, qualified: qualified)\n return unsafe String._fromUTF8Repairing(\n UnsafeBufferPointer(start: stringPtr, count: count)).0\n}\n\n@available(SwiftStdlib 5.3, *)\n@_silgen_name("swift_getMangledTypeName")\n@_preInverseGenerics\npublic func _getMangledTypeName(_ type: any (~Copyable & ~Escapable).Type)\n -> (UnsafePointer<UInt8>, Int)\n\n/// Returns the mangled name for a given type.\n@available(SwiftStdlib 5.3, *)\n@_unavailableInEmbedded\n@_preInverseGenerics\npublic // SPI\nfunc _mangledTypeName(_ type: any (~Copyable & ~Escapable).Type) -> String? {\n let (stringPtr, count) = unsafe _getMangledTypeName(type)\n guard count > 0 else {\n return nil\n }\n\n let (result, repairsMade) = unsafe String._fromUTF8Repairing(\n UnsafeBufferPointer(start: stringPtr, count: count))\n\n _precondition(!repairsMade, "repairs made to _mangledTypeName, this is not expected since names should be valid UTF-8")\n\n return result\n}\n\n/// Lookup a class given a name. Until the demangled encoding of type\n/// names is stabilized, this is limited to top-level class names (Foo.bar).\n@_unavailableInEmbedded\npublic // SPI(Foundation)\nfunc _typeByName(_ name: String) -> Any.Type? {\n let nameUTF8 = Array(name.utf8)\n return unsafe nameUTF8.withUnsafeBufferPointer { (nameUTF8) in\n return unsafe _getTypeByMangledNameUntrusted(nameUTF8.baseAddress!,\n UInt(nameUTF8.endIndex))\n }\n}\n\n@_silgen_name("swift_stdlib_getTypeByMangledNameUntrusted")\ninternal func _getTypeByMangledNameUntrusted(\n _ name: UnsafePointer<UInt8>,\n _ nameLength: UInt)\n -> Any.Type?\n\n@_silgen_name("swift_getTypeByMangledNameInEnvironment")\npublic func _getTypeByMangledNameInEnvironment(\n _ name: UnsafePointer<UInt8>,\n _ nameLength: UInt,\n genericEnvironment: UnsafeRawPointer?,\n genericArguments: UnsafeRawPointer?)\n -> Any.Type?\n\n@_silgen_name("swift_getTypeByMangledNameInContext")\npublic func _getTypeByMangledNameInContext(\n _ name: UnsafePointer<UInt8>,\n _ nameLength: UInt,\n genericContext: UnsafeRawPointer?,\n genericArguments: UnsafeRawPointer?)\n -> Any.Type?\n\n/// Prevents performance diagnostics in the passed closure.\n@_alwaysEmitIntoClient\n@_semantics("no_performance_analysis")\n@unsafe\npublic func _unsafePerformance<T>(_ c: () -> T) -> T {\n return c()\n}\n\n// Helper function that exploits a bug in rethrows checking to\n// allow us to call rethrows functions from generic typed-throws functions\n// and vice-versa.\n@usableFromInline\n@_alwaysEmitIntoClient\n@inline(__always)\nfunc _rethrowsViaClosure(_ fn: () throws -> ()) rethrows {\n try fn()\n}\n\n@available(SwiftStdlib 9999, *)\n@usableFromInline internal var swift_deletedCalleeAllocatedCoroutineMethodError: () {\n // TODO: CoroutineAccessors: Change to read from _read.\n @_silgen_name("swift_deletedCalleeAllocatedCoroutineMethodError")\n _read {\n fatalError("Fatal error: Call of deleted method")\n }\n}\n\n/// A type whose values can be implicitly or explicitly copied.\n///\n/// Conforming to this protocol indicates that a type's value can be copied;\n/// this protocol doesn’t have any required methods or properties.\n/// You don't generally need to write an explicit conformance to `Copyable`.\n/// The following places implicitly include `Copyable` conformance:\n///\n/// * Structure declarations,\n/// unless it has a noncopyable stored property\n/// * Enumeration declarations,\n/// unless it has a case whose associated value isn't copyable\n/// * Class declarations\n/// * Actor declarations\n/// * Protocol declarations\n/// * Associated type declarations\n/// * The `Self` type in a protocol extension\n/// * In an extension, the generic parameters of the type being extended\n///\n/// A class or actor can contain noncopyable stored properties,\n/// while still being copyable itself ---\n/// classes and actors are copied by retaining and releasing references.\n///\n/// In a declaration that includes generic type parameters,\n/// each generic type parameter implicitly includes `Copyable`\n/// in its list of requirements.\n/// Metatypes and tuples of copyable types are also implicitly copyable,\n/// as are boxed protocol types.\n/// For example,\n/// all of the following pairs of declarations are equivalent:\n///\n/// struct MyStructure { }\n/// struct MyStructure: Copyable { }\n///\n/// protocol MyProtocol { }\n/// protocol MyProtocol: Copyable { }\n///\n/// protocol AnotherProtocol {\n/// associatedtype MyType\n/// associatedtype MyType: Copyable\n/// }\n///\n/// func genericFunction<T>(t: T) { }\n/// func genericFunction<T>(t: T) where T: Copyable { }\n///\n/// let x: any MyProtocol\n/// let x: any MyProtocol & Copyable\n///\n/// To suppress an implicit conformance to `Copyable` you write `~Copyable`.\n/// For example,\n/// only copyable types can conform to `MyProtocol` in the example above,\n/// but both copyable and noncopyable types\n/// can conform `NoRequirements` in the example below:\n///\n/// protocol NoRequirements: ~Copyable { }\n///\n/// Extensions to the `Copyable` protocol are not allowed.\n@_marker public protocol Copyable/*: ~Escapable*/ {}\n\n@_documentation(visibility: internal)\n@_marker public protocol Escapable/*: ~Copyable*/ {}\n\n@_marker public protocol BitwiseCopyable: ~Escapable { }\n\n@available(*, deprecated, message: "Use BitwiseCopyable")\npublic typealias _BitwiseCopyable = BitwiseCopyable\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Misc.swift
cpp_apple_swift_stdlib_public_core_Misc.swift
Swift
8,407
0.95
0.068548
0.425339
node-utils
482
2024-01-24T20:48:04.359941
MIT
false
6e1ee4bdac2f4d69e873fa7b541db796
//===----------------------------------------------------------------------===//\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 collection that supports subscript assignment.\n///\n/// Collections that conform to `MutableCollection` gain the ability to\n/// change the value of their elements. This example shows how you can\n/// modify one of the names in an array of 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/// In addition to changing the value of an individual element, you can also\n/// change the values of a slice of elements in a mutable collection. For\n/// example, you can sort *part* of a mutable collection by calling the\n/// mutable `sort()` method on a subscripted subsequence. Here's an\n/// example that sorts the first half of an array of integers:\n///\n/// var numbers = [15, 40, 10, 30, 60, 25, 5, 100]\n/// numbers[0..<4].sort()\n/// print(numbers)\n/// // Prints "[10, 15, 30, 40, 60, 25, 5, 100]"\n///\n/// The `MutableCollection` protocol allows changing the values of a\n/// collection's elements but not the length of the collection itself. For\n/// operations that require adding or removing elements, see the\n/// `RangeReplaceableCollection` protocol instead.\n///\n/// Conforming to the MutableCollection Protocol\n/// ============================================\n///\n/// To add conformance to the `MutableCollection` protocol to your own\n/// custom collection, upgrade your type's subscript to support both read\n/// and write access.\n/// \n/// A value stored into a subscript of a `MutableCollection` instance must\n/// subsequently be accessible at that same position. That is, for a mutable\n/// collection instance `a`, index `i`, and value `x`, the two sets of\n/// assignments in the following code sample must be equivalent:\n///\n/// a[i] = x\n/// let y = a[i]\n/// \n/// // Must be equivalent to:\n/// a[i] = x\n/// let y = x\npublic protocol MutableCollection<Element>: Collection\nwhere SubSequence: MutableCollection\n{\n // FIXME: Associated type inference requires these.\n override associatedtype Element\n override associatedtype Index\n override associatedtype SubSequence\n\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 @_borrowed\n override subscript(position: Index) -> Element { get set }\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. 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 /// var 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 /// streets[index!] = "Eustace"\n /// print(streets[index!])\n /// // Prints "Eustace"\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 set }\n\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 mutating func partition(\n by belongsInSecondPartition: (Element) throws -> Bool\n ) rethrows -> Index\n\n /// Exchanges the values at the specified indices of the collection.\n ///\n /// Both parameters must be valid indices of the collection and not\n /// equal to `endIndex`. Passing the same index as both `i` and `j` has no\n /// effect.\n ///\n /// - Parameters:\n /// - i: The index of the first value to swap.\n /// - j: The index of the second value to swap.\n ///\n /// - Complexity: O(1)\n mutating func swapAt(_ i: Index, _ j: Index)\n\n /// Call `body(buffer)`, where `buffer` provides access to the contiguous\n /// mutable storage of the entire collection. If no such storage exists, it is\n /// first created. If the collection does not support an internal\n /// representation in the form of contiguous mutable storage, `body` is not\n /// called and `nil` is returned.\n ///\n /// The optimizer can often eliminate bounds- and uniqueness-checking\n /// within an algorithm. When that fails, however, invoking the same\n /// algorithm on `body`\ 's argument may let you trade safety for speed.\n ///\n /// A `Collection` that provides its own implementation of this method\n /// must provide contiguous storage to its elements in the same order\n /// as they appear in the collection. This guarantees that contiguous\n /// mutable storage to any of its subsequences can be generated by slicing\n /// `buffer` with a range formed from the distances to the subsequence's\n /// `startIndex` and `endIndex`, respectively.\n @available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable")\n mutating func _withUnsafeMutableBufferPointerIfSupported<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R?\n\n /// Executes a closure on the collection's contiguous storage.\n ///\n /// This method calls `body(buffer)`, where `buffer` provides access to the\n /// contiguous mutable storage of the entire collection. If the contiguous\n /// storage doesn't exist, the collection creates it. If the collection\n /// doesn't support an internal representation in the form of contiguous\n /// mutable storage, this method doesn't call `body` --- it immediately\n /// returns `nil`.\n ///\n /// The optimizer can often eliminate bounds- and uniqueness-checking\n /// within an algorithm. When that fails, however, invoking the same\n /// algorithm on the `buffer` argument may let you trade safety for speed.\n ///\n /// Always perform any necessary cleanup in the closure, because the\n /// method makes no guarantees about the state of the collection if the\n /// closure throws an error. Your changes to the collection may be absent\n /// from the collection after throwing the error, because the closure could\n /// receive a temporary copy rather than direct access to the collection's\n /// storage.\n ///\n /// - Warning: Your `body` closure must not replace `buffer`. This leads\n /// to a crash in all implementations of this method within the standard\n /// library.\n ///\n /// Successive calls to this method may provide a different pointer on each\n /// call. Don't store `buffer` outside of this method.\n ///\n /// A `Collection` that provides its own implementation of this method\n /// must provide contiguous storage to its elements in the same order\n /// as they appear in the collection. This guarantees that it's possible to\n /// generate contiguous mutable storage to any of its subsequences by slicing\n /// `buffer` with a range formed from the distances to the subsequence's\n /// `startIndex` and `endIndex`, respectively.\n ///\n /// - Parameters:\n /// - body: A closure that receives an in-out\n /// `UnsafeMutableBufferPointer` to the collection's contiguous storage.\n /// - Returns: The value returned from `body`, unless the collection doesn't\n /// support contiguous storage, in which case the method ignores `body` and\n /// returns `nil`.\n mutating func withContiguousMutableStorageIfAvailable<R>(\n _ body: (_ buffer: inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R?\n}\n\n// TODO: swift-3-indexing-model - review the following\nextension MutableCollection {\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 nil\n }\n\n @inlinable\n public mutating func withContiguousMutableStorageIfAvailable<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n return nil\n }\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. 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 /// var 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 /// streets[index!] = "Eustace"\n /// print(streets[index!])\n /// // Prints "Eustace"\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 @available(*, unavailable)\n @inlinable\n public subscript(bounds: Range<Index>) -> Slice<Self> {\n get {\n _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)\n return Slice(base: self, bounds: bounds)\n }\n set {\n _writeBackMutableSlice(&self, bounds: bounds, slice: newValue)\n }\n }\n\n // This unavailable default implementation of `subscript(bounds: Range<_>)`\n // prevents incomplete MutableCollection 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 due to the absence of a better option.\n @available(*, unavailable)\n @_alwaysEmitIntoClient\n public subscript(bounds: Range<Index>) -> SubSequence {\n get { fatalError() }\n set { fatalError() }\n }\n\n /// Exchanges the values at the specified indices of the collection.\n ///\n /// Both parameters must be valid indices of the collection that are not\n /// equal to `endIndex`. Calling `swapAt(_:_:)` with the same index as both\n /// `i` and `j` has no effect.\n ///\n /// - Parameters:\n /// - i: The index of the first value to swap.\n /// - j: The index of the second value to swap.\n ///\n /// - Complexity: O(1)\n @inlinable\n public mutating func swapAt(_ i: Index, _ j: Index) {\n guard i != j else { return }\n let tmp = self[i]\n self[i] = self[j]\n self[j] = tmp\n }\n}\n\nextension MutableCollection where SubSequence == Slice<Self> {\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. 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 /// var 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 /// streets[index!] = "Eustace"\n /// print(streets[index!])\n /// // Prints "Eustace"\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 @_alwaysEmitIntoClient\n public subscript(bounds: Range<Index>) -> Slice<Self> {\n get {\n _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)\n return Slice(base: self, bounds: bounds)\n }\n set {\n _writeBackMutableSlice(&self, bounds: bounds, slice: newValue)\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// moveSubranges(_:to:)\n//===----------------------------------------------------------------------===//\n\n#if !$Embedded\nextension MutableCollection {\n /// Moves the elements in the given subranges to just before the element at\n /// the specified index.\n ///\n /// This example finds all the uppercase letters in the array and then\n /// moves them to between `"i"` and `"j"`.\n ///\n /// var letters = Array("ABCdeFGhijkLMNOp")\n /// let uppercaseRanges = letters.indices(where: { $0.isUppercase })\n /// let rangeOfUppercase = letters.moveSubranges(uppercaseRanges, to: 10)\n /// // String(letters) == "dehiABCFGLMNOjkp"\n /// // rangeOfUppercase == 4..<13\n ///\n /// - Parameters:\n /// - subranges: The subranges of the elements to move.\n /// - insertionPoint: The index to use as the destination of the elements.\n /// - Returns: The new bounds of the moved elements.\n ///\n /// - Complexity: O(*n* log *n*) where *n* is the length of the collection.\n @available(SwiftStdlib 6.0, *)\n @discardableResult\n public mutating func moveSubranges(\n _ subranges: RangeSet<Index>, to insertionPoint: Index\n ) -> Range<Index> {\n let lowerCount = distance(from: startIndex, to: insertionPoint)\n let upperCount = distance(from: insertionPoint, to: endIndex)\n let start = _indexedStablePartition(\n count: lowerCount,\n range: startIndex..<insertionPoint,\n by: { subranges.contains($0) })\n let end = _indexedStablePartition(\n count: upperCount,\n range: insertionPoint..<endIndex,\n by: { !subranges.contains($0) })\n return start..<end\n }\n}\n#endif\n\n//===----------------------------------------------------------------------===//\n// _rotate(in:shiftingToStart:)\n//===----------------------------------------------------------------------===//\n\nextension MutableCollection {\n /// Rotates the elements of the collection so that the element at `middle`\n /// ends up first.\n ///\n /// - Returns: The new index of the element that was first pre-rotation.\n ///\n /// - Complexity: O(*n*)\n @discardableResult\n internal mutating func _rotate(\n in subrange: Range<Index>,\n shiftingToStart middle: Index\n ) -> Index {\n var m = middle, s = subrange.lowerBound\n let e = subrange.upperBound\n \n // Handle the trivial cases\n if s == m { return e }\n if m == e { return s }\n \n // We have two regions of possibly-unequal length that need to be\n // exchanged. The return value of this method is going to be the\n // position following that of the element that is currently last\n // (element j).\n //\n // [a b c d e f g|h i j] or [a b c|d e f g h i j]\n // ^ ^ ^ ^ ^ ^\n // s m e s m e\n //\n var ret = e // start with a known incorrect result.\n while true {\n // Exchange the leading elements of each region (up to the\n // length of the shorter region).\n //\n // [a b c d e f g|h i j] or [a b c|d e f g h i j]\n // ^^^^^ ^^^^^ ^^^^^ ^^^^^\n // [h i j d e f g|a b c] or [d e f|a b c g h i j]\n // ^ ^ ^ ^ ^ ^ ^ ^\n // s s1 m m1/e s s1/m m1 e\n //\n let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e)\n \n if m1 == e {\n // Left-hand case: we have moved element j into position. if\n // we haven't already, we can capture the return value which\n // is in s1.\n //\n // Note: the STL breaks the loop into two just to avoid this\n // comparison once the return value is known. I'm not sure\n // it's a worthwhile optimization, though.\n if ret == e { ret = s1 }\n \n // If both regions were the same size, we're done.\n if s1 == m { break }\n }\n \n // Now we have a smaller problem that is also a rotation, so we\n // can adjust our bounds and repeat.\n //\n // h i j[d e f g|a b c] or d e f[a b c|g h i j]\n // ^ ^ ^ ^ ^ ^\n // s m e s m e\n s = s1\n if s == m { m = m1 }\n }\n \n return ret\n }\n \n /// Swaps the elements of the two given subranges, up to the upper bound of\n /// the smaller subrange. The returned indices are the ends of the two\n /// ranges that were actually swapped.\n ///\n /// Input:\n /// [a b c d e f g h i j k l m n o p]\n /// ^^^^^^^ ^^^^^^^^^^^^^\n /// lhs rhs\n ///\n /// Output:\n /// [i j k l e f g h a b c d m n o p]\n /// ^ ^\n /// p q\n ///\n /// - Precondition: !lhs.isEmpty && !rhs.isEmpty\n /// - Postcondition: For returned indices `(p, q)`:\n ///\n /// - distance(from: lhs.lowerBound, to: p) == distance(from:\n /// rhs.lowerBound, to: q)\n /// - p == lhs.upperBound || q == rhs.upperBound\n internal mutating func _swapNonemptySubrangePrefixes(\n _ lhs: Range<Index>, _ rhs: Range<Index>\n ) -> (Index, Index) {\n _internalInvariant(!lhs.isEmpty)\n _internalInvariant(!rhs.isEmpty)\n \n var p = lhs.lowerBound\n var q = rhs.lowerBound\n repeat {\n swapAt(p, q)\n formIndex(after: &p)\n formIndex(after: &q)\n } while p != lhs.upperBound && q != rhs.upperBound\n return (p, q)\n }\n}\n\n/// Exchanges the values of the two arguments.\n///\n/// The two arguments must not alias each other. To swap two elements of a\n/// mutable collection, use the `swapAt(_:_:)` method of that collection\n/// instead of this function.\n///\n/// - Parameters:\n/// - a: The first value to swap.\n/// - b: The second value to swap.\n@inlinable\n@_preInverseGenerics\npublic func swap<T: ~Copyable>(_ a: inout T, _ b: inout T) {\n let temp = consume a\n a = consume b\n b = consume temp\n}\n\n/// Replaces the value of a mutable value with the supplied new value,\n/// returning the original.\n///\n/// - Parameters:\n/// - item: A mutable binding.\n/// - newValue: The new value of `item`.\n/// - Returns: The original value of `item`.\n@_alwaysEmitIntoClient\npublic func exchange<T: ~Copyable>(\n _ item: inout T,\n with newValue: consuming T\n) -> T {\n let oldValue = consume item\n item = consume newValue\n return oldValue\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_MutableCollection.swift
cpp_apple_swift_stdlib_public_core_MutableCollection.swift
Swift
21,848
0.95
0.038043
0.723282
python-kit
802
2025-06-16T19:22:10.644266
Apache-2.0
false
aca29ca084633cb2541daa2f612d2fc4
//===----------------------------------------------------------------------===//\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 wrapper around __RawDictionaryStorage that provides most of the\n/// implementation of Dictionary.\n@usableFromInline\n@frozen\n@safe\ninternal struct _NativeDictionary<Key: Hashable, Value> {\n @usableFromInline\n internal typealias Element = (key: Key, value: Value)\n\n /// See this comments on __RawDictionaryStorage and its subclasses to\n /// understand why we store an untyped storage here.\n @usableFromInline\n internal var _storage: __RawDictionaryStorage\n\n /// Constructs an instance from the empty singleton.\n @inlinable\n internal init() {\n unsafe self._storage = __RawDictionaryStorage.empty\n }\n\n /// Constructs a dictionary adopting the given storage.\n @inlinable\n internal init(_ storage: __owned __RawDictionaryStorage) {\n unsafe self._storage = storage\n }\n\n @inlinable\n internal init(capacity: Int) {\n if capacity == 0 {\n unsafe self._storage = __RawDictionaryStorage.empty\n } else {\n unsafe self._storage =\n _DictionaryStorage<Key, Value>.allocate(capacity: capacity)\n }\n }\n\n#if _runtime(_ObjC)\n @inlinable\n internal init(_ cocoa: __owned __CocoaDictionary) {\n self.init(cocoa, capacity: cocoa.count)\n }\n\n @inlinable\n internal init(_ cocoa: __owned __CocoaDictionary, capacity: Int) {\n if capacity == 0 {\n unsafe self._storage = __RawDictionaryStorage.empty\n } else {\n _internalInvariant(cocoa.count <= capacity)\n unsafe self._storage =\n _DictionaryStorage<Key, Value>.convert(cocoa, capacity: capacity)\n for (key, value) in cocoa {\n insertNew(\n key: _forceBridgeFromObjectiveC(key, Key.self),\n value: _forceBridgeFromObjectiveC(value, Value.self))\n }\n }\n }\n#endif\n}\n\n@available(*, unavailable)\nextension _NativeDictionary: Sendable {}\n\nextension _NativeDictionary { // Primitive fields\n @usableFromInline\n internal typealias Bucket = _HashTable.Bucket\n\n @inlinable\n internal var capacity: Int {\n @inline(__always)\n get {\n return unsafe _assumeNonNegative(_storage._capacity)\n }\n }\n\n @inlinable\n internal var hashTable: _HashTable {\n @inline(__always) get {\n return unsafe _storage._hashTable\n }\n }\n\n @inlinable\n internal var age: Int32 {\n @inline(__always) get {\n return unsafe _storage._age\n }\n }\n\n // This API is unsafe and needs a `_fixLifetime` in the caller.\n @inlinable\n internal var _keys: UnsafeMutablePointer<Key> {\n return unsafe _storage._rawKeys.assumingMemoryBound(to: Key.self)\n }\n\n @inlinable\n internal var _values: UnsafeMutablePointer<Value> {\n return unsafe _storage._rawValues.assumingMemoryBound(to: Value.self)\n }\n\n @inlinable\n @inline(__always)\n internal func invalidateIndices() {\n unsafe _storage._age &+= 1\n }\n}\n\nextension _NativeDictionary { // Low-level unchecked operations\n @inlinable\n @inline(__always)\n @unsafe\n internal func uncheckedKey(at bucket: Bucket) -> Key {\n defer { _fixLifetime(self) }\n unsafe _internalInvariant(hashTable.isOccupied(bucket))\n return unsafe _keys[bucket.offset]\n }\n\n @inlinable\n @inline(__always)\n @unsafe\n internal func uncheckedValue(at bucket: Bucket) -> Value {\n defer { _fixLifetime(self) }\n unsafe _internalInvariant(hashTable.isOccupied(bucket))\n return unsafe _values[bucket.offset]\n }\n\n @inlinable // FIXME(inline-always) was usableFromInline\n @inline(__always)\n @unsafe\n internal func uncheckedInitialize(\n at bucket: Bucket,\n toKey key: __owned Key,\n value: __owned Value) {\n defer { _fixLifetime(self) }\n unsafe _internalInvariant(hashTable.isValid(bucket))\n unsafe (_keys + bucket.offset).initialize(to: key)\n unsafe (_values + bucket.offset).initialize(to: value)\n }\n\n @inlinable // FIXME(inline-always) was usableFromInline\n @inline(__always)\n @unsafe\n internal func uncheckedDestroy(at bucket: Bucket) {\n defer { _fixLifetime(self) }\n unsafe _internalInvariant(hashTable.isValid(bucket))\n unsafe (_keys + bucket.offset).deinitialize(count: 1)\n unsafe (_values + bucket.offset).deinitialize(count: 1)\n }\n}\n\nextension _NativeDictionary { // Low-level lookup operations\n @inlinable\n @inline(__always)\n internal func hashValue(for key: Key) -> Int {\n return unsafe key._rawHashValue(seed: _storage._seed)\n }\n\n @safe\n @inlinable\n @inline(__always)\n internal func find(_ key: Key) -> (bucket: Bucket, found: Bool) {\n return unsafe _storage.find(key)\n }\n\n /// Search for a given element, assuming it has the specified hash value.\n ///\n /// If the element is not present in this set, return the position where it\n /// could be inserted.\n @inlinable\n @inline(__always)\n internal func find(\n _ key: Key,\n hashValue: Int\n ) -> (bucket: Bucket, found: Bool) {\n return unsafe _storage.find(key, hashValue: hashValue)\n }\n}\n\nextension _NativeDictionary { // ensureUnique\n @_alwaysEmitIntoClient\n @inline(never)\n internal mutating func _copyOrMoveAndResize(\n capacity: Int,\n moveElements: Bool\n ) {\n let capacity = Swift.max(capacity, self.capacity)\n let newStorage = unsafe _DictionaryStorage<Key, Value>.resize(\n original: _storage,\n capacity: capacity,\n move: moveElements)\n let result = unsafe _NativeDictionary(newStorage)\n if count > 0 {\n for unsafe bucket in unsafe hashTable {\n let key: Key\n let value: Value\n if moveElements {\n key = unsafe (_keys + bucket.offset).move()\n value = unsafe (_values + bucket.offset).move()\n } else {\n key = unsafe self.uncheckedKey(at: bucket)\n value = unsafe self.uncheckedValue(at: bucket)\n }\n result._unsafeInsertNew(key: key, value: value)\n }\n if moveElements {\n // Clear out old storage, ensuring that its deinit won't overrelease the\n // elements we've just moved out.\n unsafe _storage._hashTable.clear()\n unsafe _storage._count = 0\n }\n }\n unsafe _storage = result._storage\n }\n\n @inlinable\n internal mutating func resize(capacity: Int) {\n _copyOrMoveAndResize(capacity: capacity, moveElements: true)\n }\n\n @inlinable\n internal mutating func copyAndResize(capacity: Int) {\n _copyOrMoveAndResize(capacity: capacity, moveElements: false)\n }\n\n @inlinable\n @_semantics("optimize.sil.specialize.generic.size.never")\n internal mutating func copy() {\n let newStorage = unsafe _DictionaryStorage<Key, Value>.copy(original: _storage)\n unsafe _internalInvariant(newStorage._scale == _storage._scale)\n unsafe _internalInvariant(newStorage._age == _storage._age)\n unsafe _internalInvariant(newStorage._seed == _storage._seed)\n let result = unsafe _NativeDictionary(newStorage)\n if count > 0 {\n unsafe result.hashTable.copyContents(of: hashTable)\n unsafe result._storage._count = self.count\n for unsafe bucket in unsafe hashTable {\n let key = unsafe uncheckedKey(at: bucket)\n let value = unsafe uncheckedValue(at: bucket)\n unsafe result.uncheckedInitialize(at: bucket, toKey: key, value: value)\n }\n }\n unsafe _storage = result._storage\n }\n\n /// Ensure storage of self is uniquely held and can hold at least `capacity`\n /// elements.\n ///\n /// -Returns: `true` if contents were rehashed; otherwise, `false`.\n @inlinable\n @_semantics("optimize.sil.specialize.generic.size.never")\n internal mutating func ensureUnique(isUnique: Bool, capacity: Int) -> Bool {\n if _fastPath(capacity <= self.capacity && isUnique) {\n return false\n }\n if isUnique {\n resize(capacity: capacity)\n return true\n }\n if capacity <= self.capacity {\n copy()\n return false\n }\n copyAndResize(capacity: capacity)\n return true\n }\n\n internal mutating func reserveCapacity(_ capacity: Int, isUnique: Bool) {\n _ = ensureUnique(isUnique: isUnique, capacity: capacity)\n }\n}\n\nextension _NativeDictionary {\n @inlinable\n @inline(__always)\n func validatedBucket(for index: _HashTable.Index) -> Bucket {\n unsafe _precondition(hashTable.isOccupied(index.bucket) && index.age == age,\n "Attempting to access Dictionary elements using an invalid index")\n return unsafe index.bucket\n }\n\n @inlinable\n @inline(__always)\n func validatedBucket(for index: Dictionary<Key, Value>.Index) -> Bucket {\n#if _runtime(_ObjC)\n guard index._isNative else {\n index._cocoaPath()\n // Accept Cocoa indices as long as they contain a key that exists in this\n // dictionary, and the address of their Cocoa object generates the same\n // age.\n let cocoa = index._asCocoa\n if cocoa.age == self.age {\n let key = _forceBridgeFromObjectiveC(cocoa.key, Key.self)\n let (bucket, found) = find(key)\n if found {\n return bucket\n }\n }\n _preconditionFailure(\n "Attempting to access Dictionary elements using an invalid index")\n }\n#endif\n return unsafe validatedBucket(for: index._asNative)\n }\n}\n\nextension _NativeDictionary: _DictionaryBuffer {\n @usableFromInline\n internal typealias Index = Dictionary<Key, Value>.Index\n\n @inlinable\n internal var startIndex: Index {\n let bucket = unsafe hashTable.startBucket\n return unsafe Index(_native: _HashTable.Index(bucket: bucket, age: age))\n }\n\n @inlinable\n internal var endIndex: Index {\n let bucket = unsafe hashTable.endBucket\n return unsafe Index(_native: _HashTable.Index(bucket: bucket, age: age))\n }\n\n @inlinable\n internal func index(after index: Index) -> Index {\n#if _runtime(_ObjC)\n guard _fastPath(index._isNative) else {\n let _ = validatedBucket(for: index)\n let i = index._asCocoa\n return Index(_cocoa: i.dictionary.index(after: i))\n }\n#endif\n let bucket = unsafe validatedBucket(for: index._asNative)\n let next = unsafe hashTable.occupiedBucket(after: bucket)\n return unsafe Index(_native: _HashTable.Index(bucket: next, age: age))\n }\n\n @inlinable\n internal func index(forKey key: Key) -> Index? {\n if count == 0 {\n // Fast path that avoids computing the hash of the key.\n return nil\n }\n let (bucket, found) = find(key)\n guard found else { return nil }\n return unsafe Index(_native: _HashTable.Index(bucket: bucket, age: age))\n }\n\n @inlinable\n internal var count: Int {\n @inline(__always) get {\n return unsafe _assumeNonNegative(_storage._count)\n }\n }\n\n @inlinable\n @inline(__always)\n func contains(_ key: Key) -> Bool {\n if count == 0 {\n // Fast path that avoids computing the hash of the key.\n return false\n }\n return find(key).found\n }\n\n @inlinable\n @inline(__always)\n func lookup(_ key: Key) -> Value? {\n if count == 0 {\n // Fast path that avoids computing the hash of the key.\n return nil\n }\n let (bucket, found) = self.find(key)\n guard found else { return nil }\n return unsafe self.uncheckedValue(at: bucket)\n }\n\n @inlinable\n @inline(__always)\n func lookup(_ index: Index) -> (key: Key, value: Value) {\n let bucket = validatedBucket(for: index)\n let key = unsafe self.uncheckedKey(at: bucket)\n let value = unsafe self.uncheckedValue(at: bucket)\n return (key, value)\n }\n\n @inlinable\n @inline(__always)\n func key(at index: Index) -> Key {\n let bucket = validatedBucket(for: index)\n return unsafe self.uncheckedKey(at: bucket)\n }\n\n @inlinable\n @inline(__always)\n func value(at index: Index) -> Value {\n let bucket = validatedBucket(for: index)\n return unsafe self.uncheckedValue(at: bucket)\n }\n}\n\nextension _NativeDictionary {\n @inlinable\n subscript(key: Key, isUnique isUnique: Bool) -> Value? {\n @inline(__always)\n get {\n // Dummy definition; don't use.\n return lookup(key)\n }\n @inline(__always)\n _modify {\n let (bucket, found) = mutatingFind(key, isUnique: isUnique)\n // If found, move the old value out of storage, wrapping it into an\n // optional before yielding it.\n var value: Value? = unsafe (found ? (_values + bucket.offset).move() : nil)\n defer {\n // This is in a defer block because yield might throw, and we need to\n // preserve Dictionary invariants when that happens.\n if let value = value {\n if found {\n // **Mutation.** Initialize storage to new value.\n unsafe (_values + bucket.offset).initialize(to: value)\n } else {\n // **Insertion.** Insert the new entry at the correct place. Note\n // that `mutatingFind` already ensured that we have enough capacity.\n _insert(at: bucket, key: key, value: value)\n }\n } else {\n if found {\n // **Removal.** We've already deinitialized the value; deinitialize\n // the key too and register the removal.\n unsafe (_keys + bucket.offset).deinitialize(count: 1)\n _delete(at: bucket)\n } else {\n // Noop\n }\n }\n }\n yield &value\n }\n }\n}\n\n// This function has a highly visible name to make it stand out in stack traces.\n@usableFromInline\n@inline(never)\n@_unavailableInEmbedded\ninternal func KEY_TYPE_OF_DICTIONARY_VIOLATES_HASHABLE_REQUIREMENTS(\n _ keyType: Any.Type\n) -> Never {\n _assertionFailure(\n "Fatal error",\n """\n Duplicate keys of type '\(keyType)' were found in a Dictionary.\n This usually means either that the type violates Hashable's requirements, or\n that members of such a dictionary were mutated after insertion.\n """,\n flags: _fatalErrorFlags())\n}\n\nextension _NativeDictionary { // Insertions\n /// Insert a new element into uniquely held storage.\n /// Storage must be uniquely referenced with adequate capacity.\n /// The `key` must not be already present in the Dictionary.\n @inlinable\n internal func _unsafeInsertNew(key: __owned Key, value: __owned Value) {\n _internalInvariant(count + 1 <= capacity)\n let hashValue = self.hashValue(for: key)\n if _isDebugAssertConfiguration() {\n // In debug builds, perform a full lookup and trap if we detect duplicate\n // elements -- these imply that the Element type violates Hashable\n // requirements. This is generally more costly than a direct insertion,\n // because we'll need to compare elements in case of hash collisions.\n let (bucket, found) = find(key, hashValue: hashValue)\n guard !found else {\n #if !$Embedded\n KEY_TYPE_OF_DICTIONARY_VIOLATES_HASHABLE_REQUIREMENTS(Key.self)\n #else\n fatalError("duplicate keys in a Dictionary")\n #endif\n }\n unsafe hashTable.insert(bucket)\n unsafe uncheckedInitialize(at: bucket, toKey: key, value: value)\n } else {\n let bucket = unsafe hashTable.insertNew(hashValue: hashValue)\n unsafe uncheckedInitialize(at: bucket, toKey: key, value: value)\n }\n unsafe _storage._count &+= 1\n }\n\n /// Insert a new element into uniquely held storage, replacing an existing\n /// value (if any). Storage must be uniquely referenced with adequate\n /// capacity.\n @_alwaysEmitIntoClient @inlinable // Introduced in 5.1\n internal mutating func _unsafeUpdate(\n key: __owned Key,\n value: __owned Value\n ) {\n let (bucket, found) = find(key)\n if found {\n // Note that we also update the key here. This method is used to handle\n // collisions arising from equality transitions during bridging, and in\n // that case it is desirable to keep values paired with their original\n // keys. This is not how `updateValue(_:, forKey:)` works.\n unsafe (_keys + bucket.offset).pointee = key\n unsafe (_values + bucket.offset).pointee = value\n } else {\n _precondition(count < capacity)\n _insert(at: bucket, key: key, value: value)\n }\n }\n\n /// Insert a new entry into uniquely held storage.\n /// Storage must be uniquely referenced.\n /// The `key` must not be already present in the Dictionary.\n @inlinable\n internal mutating func insertNew(key: __owned Key, value: __owned Value) {\n _ = ensureUnique(isUnique: true, capacity: count + 1)\n _unsafeInsertNew(key: key, value: value)\n }\n\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 @safe\n @inlinable\n internal mutating func mutatingFind(\n _ key: Key,\n isUnique: Bool\n ) -> (bucket: Bucket, found: Bool) {\n let (bucket, found) = find(key)\n\n // Prepare storage.\n // If `key` isn't in the dictionary yet, assume that this access will end\n // up inserting it. (If we guess wrong, we might needlessly expand\n // storage; that's fine.) Otherwise this can only be a removal or an\n // in-place mutation.\n let rehashed = ensureUnique(\n isUnique: isUnique,\n capacity: count + (found ? 0 : 1))\n guard rehashed else { return (bucket, found) }\n let (b, f) = find(key)\n if f != found {\n #if !$Embedded\n KEY_TYPE_OF_DICTIONARY_VIOLATES_HASHABLE_REQUIREMENTS(Key.self)\n #else\n fatalError("duplicate keys in a Dictionary")\n #endif\n }\n return (b, found)\n }\n\n @inlinable\n internal func _insert(\n at bucket: Bucket,\n key: __owned Key,\n value: __owned Value) {\n _internalInvariant(count < capacity)\n unsafe hashTable.insert(bucket)\n unsafe uncheckedInitialize(at: bucket, toKey: key, value: value)\n unsafe _storage._count += 1\n }\n\n @inlinable\n internal mutating func updateValue(\n _ value: __owned Value,\n forKey key: Key,\n isUnique: Bool\n ) -> Value? {\n let (bucket, found) = mutatingFind(key, isUnique: isUnique)\n if found {\n let oldValue = unsafe (_values + bucket.offset).move()\n unsafe (_values + bucket.offset).initialize(to: value)\n return oldValue\n }\n _insert(at: bucket, key: key, value: value)\n return nil\n }\n\n @inlinable\n internal mutating func setValue(\n _ value: __owned Value,\n forKey key: Key,\n isUnique: Bool\n ) {\n let (bucket, found) = mutatingFind(key, isUnique: isUnique)\n if found {\n unsafe (_values + bucket.offset).pointee = value\n } else {\n _insert(at: bucket, key: key, value: value)\n }\n }\n}\n\nextension _NativeDictionary {\n @inlinable\n @inline(__always)\n internal mutating func swapValuesAt(\n _ a: Bucket,\n _ b: Bucket,\n isUnique: Bool\n ) {\n let rehashed = ensureUnique(isUnique: isUnique, capacity: capacity)\n _internalInvariant(!rehashed)\n unsafe _internalInvariant(hashTable.isOccupied(a) && hashTable.isOccupied(b))\n let value = unsafe (_values + a.offset).move()\n unsafe (_values + a.offset).moveInitialize(from: _values + b.offset, count: 1)\n unsafe (_values + b.offset).initialize(to: value)\n }\n \n @_alwaysEmitIntoClient\n internal func extractDictionary(\n using bitset: _UnsafeBitset, \n count: Int\n ) -> _NativeDictionary<Key, Value> {\n var count = count\n if count == 0 { return _NativeDictionary<Key, Value>() }\n if count == self.count { return self }\n let result = _NativeDictionary<Key, Value>(capacity: count)\n for unsafe offset in unsafe bitset {\n let key = unsafe self.uncheckedKey(at: Bucket(offset: offset))\n let value = unsafe self.uncheckedValue(at: Bucket(offset: offset))\n result._unsafeInsertNew(key: key, value: value)\n // The hash table can have set bits after the end of the bitmap.\n // Ignore them.\n count -= 1\n if count == 0 { break }\n }\n return result\n }\n}\n\nextension _NativeDictionary where Value: Equatable {\n @inlinable\n @inline(__always)\n func isEqual(to other: _NativeDictionary) -> Bool {\n if unsafe (self._storage === other._storage) { return true }\n if self.count != other.count { return false }\n\n for (key, value) in self {\n let (bucket, found) = other.find(key)\n guard found, unsafe other.uncheckedValue(at: bucket) == value else {\n return false\n }\n }\n return true\n }\n\n#if _runtime(_ObjC)\n @inlinable\n func isEqual(to other: __CocoaDictionary) -> Bool {\n if self.count != other.count { return false }\n\n defer { _fixLifetime(self) }\n for unsafe bucket in unsafe self.hashTable {\n let key = unsafe self.uncheckedKey(at: bucket)\n let value = unsafe self.uncheckedValue(at: bucket)\n guard\n let cocoaValue = other.lookup(_bridgeAnythingToObjectiveC(key)),\n value == _forceBridgeFromObjectiveC(cocoaValue, Value.self)\n else {\n return false\n }\n }\n return true\n }\n#endif\n}\n\nextension _NativeDictionary: _HashTableDelegate {\n @inlinable\n @inline(__always)\n internal func hashValue(at bucket: Bucket) -> Int {\n return unsafe hashValue(for: uncheckedKey(at: bucket))\n }\n\n @inlinable\n @inline(__always)\n internal func moveEntry(from source: Bucket, to target: Bucket) {\n unsafe _internalInvariant(hashTable.isValid(source))\n unsafe _internalInvariant(hashTable.isValid(target))\n unsafe (_keys + target.offset)\n .moveInitialize(from: _keys + source.offset, count: 1)\n unsafe (_values + target.offset)\n .moveInitialize(from: _values + source.offset, count: 1)\n }\n\n @inlinable\n @inline(__always)\n internal func swapEntry(_ left: Bucket, with right: Bucket) {\n unsafe _internalInvariant(hashTable.isValid(left))\n unsafe _internalInvariant(hashTable.isValid(right))\n unsafe swap(&_keys[left.offset], &_keys[right.offset])\n unsafe swap(&_values[left.offset], &_values[right.offset])\n }\n}\n\nextension _NativeDictionary { // Deletion\n @inlinable\n @_effects(releasenone)\n @_semantics("optimize.sil.specialize.generic.size.never")\n internal func _delete(at bucket: Bucket) {\n unsafe hashTable.delete(at: bucket, with: self)\n unsafe _storage._count -= 1\n unsafe _internalInvariant(_storage._count >= 0)\n invalidateIndices()\n }\n\n @inlinable\n @_semantics("optimize.sil.specialize.generic.size.never")\n @unsafe\n internal mutating func uncheckedRemove(\n at bucket: Bucket,\n isUnique: Bool\n ) -> Element {\n unsafe _internalInvariant(hashTable.isOccupied(bucket))\n let rehashed = ensureUnique(isUnique: isUnique, capacity: capacity)\n _internalInvariant(!rehashed)\n let oldKey = unsafe (_keys + bucket.offset).move()\n let oldValue = unsafe (_values + bucket.offset).move()\n _delete(at: bucket)\n return (oldKey, oldValue)\n }\n\n @usableFromInline\n internal mutating func removeAll(isUnique: Bool) {\n guard isUnique else {\n let scale = unsafe self._storage._scale\n unsafe _storage = _DictionaryStorage<Key, Value>.allocate(\n scale: scale,\n age: nil,\n seed: nil)\n return\n }\n for unsafe bucket in unsafe hashTable {\n unsafe (_keys + bucket.offset).deinitialize(count: 1)\n unsafe (_values + bucket.offset).deinitialize(count: 1)\n }\n unsafe hashTable.clear()\n unsafe _storage._count = 0\n invalidateIndices()\n }\n}\n\nextension _NativeDictionary { // High-level operations\n @inlinable\n internal func mapValues<T>(\n _ transform: (Value) throws -> T\n ) rethrows -> _NativeDictionary<Key, T> {\n let resultStorage = unsafe _DictionaryStorage<Key, T>.copy(original: _storage)\n unsafe _internalInvariant(resultStorage._seed == _storage._seed)\n let result = unsafe _NativeDictionary<Key, T>(resultStorage)\n // Because the current and new buffer have the same scale and seed, we can\n // initialize to the same locations in the new buffer, skipping hash value\n // recalculations.\n for unsafe bucket in unsafe hashTable {\n let key = unsafe self.uncheckedKey(at: bucket)\n let value = unsafe self.uncheckedValue(at: bucket)\n try result._insert(at: bucket, key: key, value: transform(value))\n }\n return result\n }\n\n @inlinable\n internal mutating func merge<S: Sequence>(\n _ keysAndValues: __owned S,\n isUnique: Bool,\n uniquingKeysWith combine: (Value, Value) throws -> Value\n ) rethrows where S.Element == (Key, Value) {\n var isUnique = isUnique\n for (key, value) in keysAndValues {\n let (bucket, found) = mutatingFind(key, isUnique: isUnique)\n isUnique = true\n if found {\n do {\n let newValue = try combine(unsafe uncheckedValue(at: bucket), value)\n unsafe _values[bucket.offset] = newValue\n } catch _MergeError.keyCollision {\n #if !$Embedded\n fatalError("Duplicate values for key: '\(key)'")\n #else\n fatalError("Duplicate values for a key in a Dictionary")\n #endif\n }\n } else {\n _insert(at: bucket, key: key, value: value)\n }\n }\n }\n\n #if $Embedded\n @inlinable\n internal mutating func merge<S: Sequence>(\n _ keysAndValues: __owned S,\n isUnique: Bool,\n uniquingKeysWith combine: (Value, Value) throws(_MergeError) -> Value\n ) where S.Element == (Key, Value) {\n var isUnique = isUnique\n for (key, value) in keysAndValues {\n let (bucket, found) = mutatingFind(key, isUnique: isUnique)\n isUnique = true\n if found {\n do throws(_MergeError) {\n let newValue = try combine(unsafe uncheckedValue(at: bucket), value)\n unsafe _values[bucket.offset] = newValue\n } catch {\n #if !$Embedded\n fatalError("Duplicate values for key: '\(key)'")\n #else\n fatalError("Duplicate values for a key in a Dictionary")\n #endif\n }\n } else {\n _insert(at: bucket, key: key, value: value)\n }\n }\n }\n #endif\n\n @inlinable\n @inline(__always)\n internal init<S: Sequence>(\n grouping values: __owned S,\n by keyForValue: (S.Element) throws -> Key\n ) rethrows where Value == [S.Element] {\n self.init()\n for value in values {\n let key = try keyForValue(value)\n let (bucket, found) = mutatingFind(key, isUnique: true)\n if found {\n unsafe _values[bucket.offset].append(value)\n } else {\n _insert(at: bucket, key: key, value: [value])\n }\n }\n }\n\n @_alwaysEmitIntoClient\n internal func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> _NativeDictionary<Key, Value> {\n try unsafe _UnsafeBitset.withTemporaryBitset(\n capacity: _storage._bucketCount\n ) { bitset in\n var count = 0\n for unsafe bucket in unsafe hashTable {\n if try unsafe isIncluded(\n (uncheckedKey(at: bucket), uncheckedValue(at: bucket))\n ) {\n unsafe bitset.uncheckedInsert(bucket.offset)\n count += 1\n }\n }\n return unsafe extractDictionary(using: bitset, count: count)\n }\n }\n}\n\nextension _NativeDictionary: Sequence {\n @usableFromInline\n @frozen\n @safe\n internal struct Iterator {\n // The iterator is iterating over a frozen view of the collection state, so\n // it keeps its own reference to the dictionary.\n @usableFromInline\n internal let base: _NativeDictionary\n @usableFromInline\n internal var iterator: _HashTable.Iterator\n\n @inlinable\n @inline(__always)\n init(_ base: __owned _NativeDictionary) {\n self.base = base\n unsafe self.iterator = base.hashTable.makeIterator()\n }\n }\n\n @inlinable\n internal __consuming func makeIterator() -> Iterator {\n return Iterator(self)\n }\n}\n\n@available(*, unavailable)\nextension _NativeDictionary.Iterator: Sendable {}\n\nextension _NativeDictionary.Iterator: IteratorProtocol {\n @usableFromInline\n internal typealias Element = (key: Key, value: Value)\n\n @inlinable\n @inline(__always)\n internal mutating func nextKey() -> Key? {\n guard let index = unsafe iterator.next() else { return nil }\n return unsafe base.uncheckedKey(at: index)\n }\n\n @inlinable\n @inline(__always)\n internal mutating func nextValue() -> Value? {\n guard let index = unsafe iterator.next() else { return nil }\n return unsafe base.uncheckedValue(at: index)\n }\n\n @inlinable\n @inline(__always)\n internal mutating func next() -> Element? {\n guard let index = unsafe iterator.next() else { return nil }\n let key = unsafe base.uncheckedKey(at: index)\n let value = unsafe base.uncheckedValue(at: index)\n return (key, value)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_NativeDictionary.swift
cpp_apple_swift_stdlib_public_core_NativeDictionary.swift
Swift
28,692
0.95
0.095032
0.12
react-lib
282
2024-04-24T01:12:19.757187
Apache-2.0
false
f36baf4a32966f2f71a3a2582c7efb07
//===----------------------------------------------------------------------===//\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 wrapper around __RawSetStorage that provides most of the\n/// implementation of Set.\n@usableFromInline\n@frozen\n@safe\ninternal struct _NativeSet<Element: Hashable> {\n /// See the comments on __RawSetStorage and its subclasses to understand why we\n /// store an untyped storage here.\n @usableFromInline\n internal var _storage: __RawSetStorage\n\n /// Constructs an instance from the empty singleton.\n @inlinable\n @inline(__always)\n internal init() {\n unsafe self._storage = __RawSetStorage.empty\n }\n\n /// Constructs a native set adopting the given storage.\n @inlinable\n @inline(__always)\n internal init(_ storage: __owned __RawSetStorage) {\n unsafe self._storage = storage\n }\n\n @inlinable\n internal init(capacity: Int) {\n if capacity == 0 {\n unsafe self._storage = __RawSetStorage.empty\n } else {\n unsafe self._storage = _SetStorage<Element>.allocate(capacity: capacity)\n }\n }\n\n#if _runtime(_ObjC)\n @inlinable\n internal init(_ cocoa: __owned __CocoaSet) {\n self.init(cocoa, capacity: cocoa.count)\n }\n\n @inlinable\n internal init(_ cocoa: __owned __CocoaSet, capacity: Int) {\n if capacity == 0 {\n unsafe self._storage = __RawSetStorage.empty\n } else {\n _internalInvariant(cocoa.count <= capacity)\n unsafe self._storage = _SetStorage<Element>.convert(cocoa, capacity: capacity)\n for element in cocoa {\n let nativeElement = _forceBridgeFromObjectiveC(element, Element.self)\n insertNew(nativeElement, isUnique: true)\n }\n }\n }\n#endif\n}\n\n@available(*, unavailable)\nextension _NativeSet: Sendable {}\n\nextension _NativeSet { // Primitive fields\n @usableFromInline\n internal typealias Bucket = _HashTable.Bucket\n\n @inlinable\n internal var capacity: Int {\n @inline(__always)\n get {\n return unsafe _assumeNonNegative(_storage._capacity)\n }\n }\n\n @_alwaysEmitIntoClient\n @inline(__always)\n internal var bucketCount: Int {\n unsafe _assumeNonNegative(_storage._bucketCount)\n }\n\n @inlinable\n internal var hashTable: _HashTable {\n @inline(__always) get {\n return unsafe _storage._hashTable\n }\n }\n\n @inlinable\n internal var age: Int32 {\n @inline(__always) get {\n return unsafe _storage._age\n }\n }\n\n // This API is unsafe and needs a `_fixLifetime` in the caller.\n @inlinable\n internal var _elements: UnsafeMutablePointer<Element> {\n return unsafe _storage._rawElements.assumingMemoryBound(to: Element.self)\n }\n\n @inlinable\n @inline(__always)\n internal func invalidateIndices() {\n unsafe _storage._age &+= 1\n }\n}\n\nextension _NativeSet { // Low-level unchecked operations\n @inlinable\n @inline(__always)\n @unsafe\n internal func uncheckedElement(at bucket: Bucket) -> Element {\n defer { _fixLifetime(self) }\n unsafe _internalInvariant(hashTable.isOccupied(bucket))\n return unsafe _elements[bucket.offset]\n }\n\n @inlinable\n @inline(__always)\n @unsafe\n internal func uncheckedInitialize(\n at bucket: Bucket,\n to element: __owned Element\n ) {\n unsafe _internalInvariant(hashTable.isValid(bucket))\n unsafe (_elements + bucket.offset).initialize(to: element)\n }\n\n @_alwaysEmitIntoClient @inlinable // Introduced in 5.1\n @inline(__always)\n @unsafe\n internal func uncheckedAssign(\n at bucket: Bucket,\n to element: __owned Element\n ) {\n unsafe _internalInvariant(hashTable.isOccupied(bucket))\n unsafe (_elements + bucket.offset).pointee = element\n }\n}\n\nextension _NativeSet { // Low-level lookup operations\n @inlinable\n @inline(__always)\n internal func hashValue(for element: Element) -> Int {\n return unsafe element._rawHashValue(seed: _storage._seed)\n }\n\n @safe\n @inlinable\n @inline(__always)\n internal func find(_ element: Element) -> (bucket: Bucket, found: Bool) {\n return find(element, hashValue: self.hashValue(for: element))\n }\n\n /// Search for a given element, assuming it has the specified hash value.\n ///\n /// If the element is not present in this set, return the position where it\n /// could be inserted.\n @inlinable\n @inline(__always)\n internal func find(\n _ element: Element,\n hashValue: Int\n ) -> (bucket: Bucket, found: Bool) {\n let hashTable = unsafe self.hashTable\n var bucket = unsafe hashTable.idealBucket(forHashValue: hashValue)\n while unsafe hashTable._isOccupied(bucket) {\n if unsafe uncheckedElement(at: bucket) == element {\n return (bucket, true)\n }\n unsafe bucket = unsafe hashTable.bucket(wrappedAfter: bucket)\n }\n return (bucket, false)\n }\n}\n\nextension _NativeSet { // ensureUnique\n @inlinable\n internal mutating func resize(capacity: Int) {\n let capacity = Swift.max(capacity, self.capacity)\n let result = unsafe _NativeSet(_SetStorage<Element>.resize(\n original: _storage,\n capacity: capacity,\n move: true))\n if count > 0 {\n for unsafe bucket in unsafe hashTable {\n let element = unsafe (self._elements + bucket.offset).move()\n unsafe result._unsafeInsertNew(element)\n }\n // Clear out old storage, ensuring that its deinit won't overrelease the\n // elements we've just moved out.\n unsafe _storage._hashTable.clear()\n unsafe _storage._count = 0\n }\n unsafe _storage = result._storage\n }\n\n @inlinable\n internal mutating func copyAndResize(capacity: Int) {\n let capacity = Swift.max(capacity, self.capacity)\n let result = unsafe _NativeSet(_SetStorage<Element>.resize(\n original: _storage,\n capacity: capacity,\n move: false))\n if count > 0 {\n for unsafe bucket in unsafe hashTable {\n unsafe result._unsafeInsertNew(self.uncheckedElement(at: bucket))\n }\n }\n unsafe _storage = result._storage\n }\n\n @inlinable\n internal mutating func copy() {\n let newStorage = unsafe _SetStorage<Element>.copy(original: _storage)\n unsafe _internalInvariant(newStorage._scale == _storage._scale)\n unsafe _internalInvariant(newStorage._age == _storage._age)\n unsafe _internalInvariant(newStorage._seed == _storage._seed)\n let result = unsafe _NativeSet(newStorage)\n if count > 0 {\n unsafe result.hashTable.copyContents(of: hashTable)\n unsafe result._storage._count = self.count\n for unsafe bucket in unsafe hashTable {\n let element = unsafe uncheckedElement(at: bucket)\n unsafe result.uncheckedInitialize(at: bucket, to: element)\n }\n }\n unsafe _storage = result._storage\n }\n\n /// Ensure storage of self is uniquely held and can hold at least `capacity`\n /// elements.\n ///\n /// -Returns: `true` if contents were rehashed; otherwise, `false`.\n @inlinable\n @inline(__always)\n internal mutating func ensureUnique(isUnique: Bool, capacity: Int) -> Bool {\n if _fastPath(capacity <= self.capacity && isUnique) {\n return false\n }\n if isUnique {\n resize(capacity: capacity)\n return true\n }\n if capacity <= self.capacity {\n copy()\n return false\n }\n copyAndResize(capacity: capacity)\n return true\n }\n\n internal mutating func reserveCapacity(_ capacity: Int, isUnique: Bool) {\n _ = ensureUnique(isUnique: isUnique, capacity: capacity)\n }\n}\n\nextension _NativeSet {\n @inlinable\n @inline(__always)\n func validatedBucket(for index: _HashTable.Index) -> Bucket {\n unsafe _precondition(hashTable.isOccupied(index.bucket) && index.age == age,\n "Attempting to access Set elements using an invalid index")\n return unsafe index.bucket\n }\n\n @inlinable\n @inline(__always)\n func validatedBucket(for index: Set<Element>.Index) -> Bucket {\n#if _runtime(_ObjC)\n guard index._isNative else {\n index._cocoaPath()\n let cocoa = index._asCocoa\n // Accept Cocoa indices as long as they contain an element that exists in\n // this set, and the address of their Cocoa object generates the same age.\n if cocoa.age == self.age {\n let element = _forceBridgeFromObjectiveC(cocoa.element, Element.self)\n let (bucket, found) = find(element)\n if found {\n return bucket\n }\n }\n _preconditionFailure(\n "Attempting to access Set elements using an invalid index")\n }\n#endif\n return unsafe validatedBucket(for: index._asNative)\n }\n}\n\nextension _NativeSet: _SetBuffer {\n @usableFromInline\n internal typealias Index = Set<Element>.Index\n\n @inlinable\n internal var startIndex: Index {\n let bucket = unsafe hashTable.startBucket\n return unsafe Index(_native: _HashTable.Index(bucket: bucket, age: age))\n }\n\n @inlinable\n internal var endIndex: Index {\n let bucket = unsafe hashTable.endBucket\n return unsafe Index(_native: _HashTable.Index(bucket: bucket, age: age))\n }\n\n @inlinable\n internal func index(after index: Index) -> Index {\n // Note that _asNative forces this not to work on Cocoa indices.\n let bucket = unsafe validatedBucket(for: index._asNative)\n let next = unsafe hashTable.occupiedBucket(after: bucket)\n return unsafe Index(_native: _HashTable.Index(bucket: next, age: age))\n }\n\n @inlinable\n @inline(__always)\n internal func index(for element: Element) -> Index? {\n if count == 0 {\n // Fast path that avoids computing the hash of the key.\n return nil\n }\n let (bucket, found) = find(element)\n guard found else { return nil }\n return unsafe Index(_native: _HashTable.Index(bucket: bucket, age: age))\n }\n\n @inlinable\n internal var count: Int {\n @inline(__always) get {\n return unsafe _assumeNonNegative(_storage._count)\n }\n }\n\n @inlinable\n @inline(__always)\n internal func contains(_ member: Element) -> Bool {\n // Fast path: Don't calculate the hash if the set has no elements.\n if count == 0 { return false }\n return find(member).found\n }\n\n @inlinable\n @inline(__always)\n internal func element(at index: Index) -> Element {\n let bucket = validatedBucket(for: index)\n return unsafe uncheckedElement(at: bucket)\n }\n}\n\n// This function has a highly visible name to make it stand out in stack traces.\n@usableFromInline\n@inline(never)\n@_unavailableInEmbedded\ninternal func ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(\n _ elementType: Any.Type\n) -> Never {\n _assertionFailure(\n "Fatal error",\n """\n Duplicate elements of type '\(elementType)' were found in a Set.\n This usually means either that the type violates Hashable's requirements, or\n that members of such a set were mutated after insertion.\n """,\n flags: _fatalErrorFlags())\n}\n\nextension _NativeSet { // Insertions\n /// Insert a new element into uniquely held storage.\n /// Storage must be uniquely referenced with adequate capacity.\n /// The `element` must not be already present in the Set.\n @inlinable\n @unsafe\n internal func _unsafeInsertNew(_ element: __owned Element) {\n _internalInvariant(count + 1 <= capacity)\n let hashValue = self.hashValue(for: element)\n if _isDebugAssertConfiguration() {\n // In debug builds, perform a full lookup and trap if we detect duplicate\n // elements -- these imply that the Element type violates Hashable\n // requirements. This is generally more costly than a direct insertion,\n // because we'll need to compare elements in case of hash collisions.\n let (bucket, found) = find(element, hashValue: hashValue)\n guard !found else {\n #if !$Embedded\n ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self)\n #else\n fatalError("duplicate elements in a Set")\n #endif\n }\n unsafe hashTable.insert(bucket)\n unsafe uncheckedInitialize(at: bucket, to: element)\n } else {\n let bucket = unsafe hashTable.insertNew(hashValue: hashValue)\n unsafe uncheckedInitialize(at: bucket, to: element)\n }\n unsafe _storage._count &+= 1\n }\n\n /// Insert a new element into uniquely held storage.\n /// Storage must be uniquely referenced.\n /// The `element` must not be already present in the Set.\n @inlinable\n internal mutating func insertNew(_ element: __owned Element, isUnique: Bool) {\n _ = ensureUnique(isUnique: isUnique, capacity: count + 1)\n unsafe _unsafeInsertNew(element)\n }\n\n @inlinable\n @unsafe\n internal func _unsafeInsertNew(_ element: __owned Element, at bucket: Bucket) {\n unsafe hashTable.insert(bucket)\n unsafe uncheckedInitialize(at: bucket, to: element)\n unsafe _storage._count += 1\n }\n\n @inlinable\n internal mutating func insertNew(\n _ element: __owned Element,\n at bucket: Bucket,\n isUnique: Bool\n ) {\n unsafe _internalInvariant(!hashTable.isOccupied(bucket))\n var bucket = bucket\n let rehashed = ensureUnique(isUnique: isUnique, capacity: count + 1)\n if rehashed {\n let (b, f) = find(element)\n if f {\n #if !$Embedded\n ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self)\n #else\n fatalError("duplicate elements in a Set")\n #endif\n }\n bucket = b\n }\n unsafe _unsafeInsertNew(element, at: bucket)\n }\n\n @inlinable\n internal mutating func update(\n with element: __owned Element,\n isUnique: Bool\n ) -> Element? {\n var (bucket, found) = find(element)\n let rehashed = ensureUnique(\n isUnique: isUnique,\n capacity: count + (found ? 0 : 1))\n if rehashed {\n let (b, f) = find(element)\n if f != found {\n #if !$Embedded\n ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self)\n #else\n fatalError("duplicate elements in a Set")\n #endif\n }\n bucket = b\n }\n if found {\n let old = unsafe (_elements + bucket.offset).move()\n unsafe uncheckedInitialize(at: bucket, to: element)\n return old\n }\n unsafe _unsafeInsertNew(element, at: bucket)\n return nil\n }\n\n /// Insert an element into uniquely held storage, replacing an existing value\n /// (if any). Storage must be uniquely referenced with adequate capacity.\n @_alwaysEmitIntoClient @inlinable // Introduced in 5.1\n internal mutating func _unsafeUpdate(\n with element: __owned Element\n ) {\n let (bucket, found) = find(element)\n if found {\n unsafe uncheckedAssign(at: bucket, to: element)\n } else {\n _precondition(count < capacity)\n unsafe _unsafeInsertNew(element, at: bucket)\n }\n }\n}\n\nextension _NativeSet {\n @inlinable\n @inline(__always)\n func isEqual(to other: _NativeSet) -> Bool {\n if unsafe (self._storage === other._storage) { return true }\n if self.count != other.count { return false }\n\n for member in self {\n guard other.find(member).found else { return false }\n }\n return true\n }\n\n#if _runtime(_ObjC)\n @inlinable\n func isEqual(to other: __CocoaSet) -> Bool {\n if self.count != other.count { return false }\n\n defer { _fixLifetime(self) }\n for unsafe bucket in unsafe self.hashTable {\n let key = unsafe self.uncheckedElement(at: bucket)\n let bridgedKey = _bridgeAnythingToObjectiveC(key)\n guard other.contains(bridgedKey) else { return false }\n }\n return true\n }\n#endif\n}\n\nextension _NativeSet: _HashTableDelegate {\n @inlinable\n @inline(__always)\n internal func hashValue(at bucket: Bucket) -> Int {\n return hashValue(for: unsafe uncheckedElement(at: bucket))\n }\n\n @inlinable\n @inline(__always)\n internal func moveEntry(from source: Bucket, to target: Bucket) {\n unsafe (_elements + target.offset)\n .moveInitialize(from: _elements + source.offset, count: 1)\n }\n}\n\nextension _NativeSet { // Deletion\n @inlinable\n @_effects(releasenone)\n internal mutating func _delete(at bucket: Bucket) {\n unsafe hashTable.delete(at: bucket, with: self)\n unsafe _storage._count -= 1\n unsafe _internalInvariant(_storage._count >= 0)\n invalidateIndices()\n }\n\n @inlinable\n @inline(__always)\n @unsafe\n internal mutating func uncheckedRemove(\n at bucket: Bucket,\n isUnique: Bool) -> Element {\n unsafe _internalInvariant(hashTable.isOccupied(bucket))\n let rehashed = ensureUnique(isUnique: isUnique, capacity: capacity)\n _internalInvariant(!rehashed)\n let old = unsafe (_elements + bucket.offset).move()\n _delete(at: bucket)\n return old\n }\n\n @usableFromInline\n internal mutating func removeAll(isUnique: Bool) {\n guard isUnique else {\n let scale = unsafe self._storage._scale\n unsafe _storage = _SetStorage<Element>.allocate(\n scale: scale,\n age: nil,\n seed: nil)\n return\n }\n for unsafe bucket in unsafe hashTable {\n unsafe (_elements + bucket.offset).deinitialize(count: 1)\n }\n unsafe hashTable.clear()\n unsafe _storage._count = 0\n invalidateIndices()\n }\n}\n\nextension _NativeSet: Sequence {\n @usableFromInline\n @frozen\n @safe\n internal struct Iterator {\n // The iterator is iterating over a frozen view of the collection state, so\n // it keeps its own reference to the set.\n @usableFromInline\n internal let base: _NativeSet\n @usableFromInline\n internal var iterator: _HashTable.Iterator\n\n @inlinable\n @inline(__always)\n init(_ base: __owned _NativeSet) {\n self.base = base\n unsafe self.iterator = base.hashTable.makeIterator()\n }\n }\n\n @inlinable\n @inline(__always)\n internal __consuming func makeIterator() -> Iterator {\n return Iterator(self)\n }\n}\n\n@available(*, unavailable)\nextension _NativeSet.Iterator: Sendable {}\n\nextension _NativeSet.Iterator: IteratorProtocol {\n @inlinable\n @inline(__always)\n internal mutating func next() -> Element? {\n guard let index = unsafe iterator.next() else { return nil }\n return unsafe base.uncheckedElement(at: index)\n }\n}\n\nextension _NativeSet {\n @_alwaysEmitIntoClient\n internal func isSubset<S: Sequence>(of possibleSuperset: S) -> Bool\n where S.Element == Element {\n unsafe _UnsafeBitset.withTemporaryBitset(capacity: self.bucketCount) { seen in\n // Mark elements in self that we've seen in `possibleSuperset`.\n var seenCount = 0\n for element in possibleSuperset {\n let (bucket, found) = find(element)\n guard found else { continue }\n let inserted = unsafe seen.uncheckedInsert(bucket.offset)\n if inserted {\n seenCount += 1\n if seenCount == self.count {\n return true\n }\n }\n }\n return false\n }\n }\n\n @_alwaysEmitIntoClient\n internal func isStrictSubset<S: Sequence>(of possibleSuperset: S) -> Bool\n where S.Element == Element {\n unsafe _UnsafeBitset.withTemporaryBitset(capacity: self.bucketCount) { seen in\n // Mark elements in self that we've seen in `possibleSuperset`.\n var seenCount = 0\n var isStrict = false\n for element in possibleSuperset {\n let (bucket, found) = find(element)\n guard found else {\n if !isStrict {\n isStrict = true\n if seenCount == self.count { return true }\n }\n continue\n }\n let inserted = unsafe seen.uncheckedInsert(bucket.offset)\n if inserted {\n seenCount += 1\n if seenCount == self.count, isStrict {\n return true\n }\n }\n }\n return false\n }\n }\n\n @_alwaysEmitIntoClient\n internal func isStrictSuperset<S: Sequence>(of possibleSubset: S) -> Bool\n where S.Element == Element {\n unsafe _UnsafeBitset.withTemporaryBitset(capacity: self.bucketCount) { seen in\n // Mark elements in self that we've seen in `possibleStrictSubset`.\n var seenCount = 0\n for element in possibleSubset {\n let (bucket, found) = find(element)\n guard found else { return false }\n let inserted = unsafe seen.uncheckedInsert(bucket.offset)\n if inserted {\n seenCount += 1\n if seenCount == self.count {\n return false\n }\n }\n }\n return true\n }\n }\n\n @_alwaysEmitIntoClient\n internal __consuming func extractSubset(\n using bitset: _UnsafeBitset,\n count: Int\n ) -> _NativeSet {\n var count = count\n if count == 0 { return _NativeSet() }\n if count == self.count { return self }\n let result = _NativeSet(capacity: count)\n for unsafe offset in unsafe bitset {\n unsafe result._unsafeInsertNew(self.uncheckedElement(at: Bucket(offset: offset)))\n // The hash table can have set bits after the end of the bitmap.\n // Ignore them.\n count -= 1\n if count == 0 { break }\n }\n return result\n }\n\n @_alwaysEmitIntoClient\n internal __consuming func subtracting<S: Sequence>(_ other: S) -> _NativeSet\n where S.Element == Element {\n guard count > 0 else { return _NativeSet() }\n\n // Find one item that we need to remove before creating a result set.\n var it = other.makeIterator()\n var bucket: Bucket? = nil\n while let next = it.next() {\n let (b, found) = find(next)\n if found {\n bucket = b\n break\n }\n }\n guard let bucket = bucket else { return self }\n\n // Rather than directly creating a new set, calculate the difference in a\n // bitset first. This ensures we hash each element (in both sets) only once,\n // and that we'll have an exact count for the result set, preventing\n // rehashings during insertions.\n return unsafe _UnsafeBitset.withTemporaryCopy(of: hashTable.bitset) { difference in\n var remainingCount = self.count\n\n let removed = unsafe difference.uncheckedRemove(bucket.offset)\n _internalInvariant(removed)\n remainingCount -= 1\n\n while let element = it.next() {\n let (bucket, found) = find(element)\n if found {\n if unsafe difference.uncheckedRemove(bucket.offset) {\n remainingCount -= 1\n if remainingCount == 0 { return _NativeSet() }\n }\n }\n }\n unsafe _internalInvariant(difference.count > 0)\n return unsafe extractSubset(using: difference, count: remainingCount)\n }\n }\n\n @_alwaysEmitIntoClient\n internal __consuming func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> _NativeSet<Element> {\n try unsafe _UnsafeBitset.withTemporaryBitset(capacity: bucketCount) { bitset in\n var count = 0\n for unsafe bucket in unsafe hashTable {\n if try isIncluded(unsafe uncheckedElement(at: bucket)) {\n unsafe bitset.uncheckedInsert(bucket.offset)\n count += 1\n }\n }\n return unsafe extractSubset(using: bitset, count: count)\n }\n }\n\n @_alwaysEmitIntoClient\n internal __consuming func intersection(\n _ other: _NativeSet<Element>\n ) -> _NativeSet<Element> {\n // Rather than directly creating a new set, mark common elements in a\n // bitset first. This minimizes hashing, and ensures that we'll have an\n // exact count for the result set, preventing rehashings during\n // insertions.\n unsafe _UnsafeBitset.withTemporaryBitset(capacity: bucketCount) { bitset in\n var count = 0\n // Prefer to iterate over the smaller set. However, we must be careful to\n // only include elements from `self`, not `other`.\n if self.count > other.count {\n for element in other {\n let (bucket, found) = find(element)\n if found {\n // `other` is a `Set`, so we can assume it doesn't have duplicates.\n unsafe bitset.uncheckedInsert(bucket.offset)\n count += 1\n }\n }\n } else {\n for unsafe bucket in unsafe hashTable {\n if other.find(unsafe uncheckedElement(at: bucket)).found {\n unsafe bitset.uncheckedInsert(bucket.offset)\n count += 1\n }\n }\n }\n return unsafe extractSubset(using: bitset, count: count)\n }\n }\n\n @_alwaysEmitIntoClient\n internal __consuming func genericIntersection<S: Sequence>(\n _ other: S\n ) -> _NativeSet<Element>\n where S.Element == Element {\n // Rather than directly creating a new set, mark common elements in a bitset\n // first. This minimizes hashing, and ensures that we'll have an exact count\n // for the result set, preventing rehashings during insertions.\n unsafe _UnsafeBitset.withTemporaryBitset(capacity: bucketCount) { bitset in\n var count = 0\n for element in other {\n let (bucket, found) = find(element)\n // Note: we need to be careful not to increment `count` here if the\n // element is a duplicate item.\n if found, unsafe bitset.uncheckedInsert(bucket.offset) {\n count += 1\n }\n }\n return unsafe extractSubset(using: bitset, count: count)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_NativeSet.swift
cpp_apple_swift_stdlib_public_core_NativeSet.swift
Swift
24,922
0.95
0.110976
0.113032
react-lib
188
2025-02-22T03:43:22.093968
BSD-3-Clause
false
564e8e46a4f4f583d0702c45fe678aba
//===----------------------------------------------------------------------===//\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/// An implementation detail used to implement support importing\n/// (Objective-)C entities marked with the swift_newtype Clang\n/// attribute.\npublic protocol _SwiftNewtypeWrapper\n: RawRepresentable, _HasCustomAnyHashableRepresentation { }\n\nextension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue: Hashable {\n /// The hash value.\n @inlinable\n public var hashValue: Int {\n return rawValue.hashValue\n }\n\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(rawValue)\n }\n\n @inlinable\n public func _rawHashValue(seed: Int) -> Int {\n return rawValue._rawHashValue(seed: seed)\n }\n}\n\nextension _SwiftNewtypeWrapper {\n public __consuming func _toCustomAnyHashable() -> AnyHashable? {\n return nil\n }\n}\n\nextension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue: Hashable {\n public __consuming func _toCustomAnyHashable() -> AnyHashable? {\n return AnyHashable(_box: _NewtypeWrapperAnyHashableBox(self))\n }\n}\n\ninternal struct _NewtypeWrapperAnyHashableBox<Base>: _AnyHashableBox\nwhere Base: _SwiftNewtypeWrapper & Hashable, Base.RawValue: Hashable {\n var _value: Base\n\n init(_ value: Base) {\n self._value = value\n }\n\n var _canonicalBox: _AnyHashableBox {\n return (_value.rawValue as AnyHashable)._box._canonicalBox\n }\n\n func _isEqual(to other: _AnyHashableBox) -> Bool? {\n _preconditionFailure("_isEqual called on non-canonical AnyHashable box")\n }\n\n var _hashValue: Int {\n _preconditionFailure("_hashValue called on non-canonical AnyHashable box")\n }\n\n func _hash(into hasher: inout Hasher) {\n _preconditionFailure("_hash(into:) called on non-canonical AnyHashable box")\n }\n\n func _rawHashValue(_seed: Int) -> Int {\n _preconditionFailure("_rawHashValue(_seed:) called on non-canonical AnyHashable box")\n }\n\n var _base: Any { return _value }\n\n func _unbox<T: Hashable>() -> T? {\n return _value as? T ?? _value.rawValue as? T\n }\n\n func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool {\n if let value = _value as? T {\n unsafe result.initialize(to: value)\n return true\n }\n if let value = _value.rawValue as? T {\n unsafe result.initialize(to: value)\n return true\n }\n return false\n }\n}\n\n#if _runtime(_ObjC)\nextension _SwiftNewtypeWrapper where Self.RawValue: _ObjectiveCBridgeable {\n // Note: This is the only default typealias for _ObjectiveCType, because\n // constrained extensions aren't allowed to define types in different ways.\n // Fortunately the others don't need it.\n public typealias _ObjectiveCType = Self.RawValue._ObjectiveCType\n\n @inlinable\n public func _bridgeToObjectiveC() -> Self.RawValue._ObjectiveCType {\n return rawValue._bridgeToObjectiveC()\n }\n @inlinable\n public static func _forceBridgeFromObjectiveC(\n _ source: Self.RawValue._ObjectiveCType,\n result: inout Self?\n ) {\n var innerResult: Self.RawValue?\n Self.RawValue._forceBridgeFromObjectiveC(source, result: &innerResult)\n result = innerResult.flatMap { Self(rawValue: $0) }\n }\n\n @inlinable\n public static func _conditionallyBridgeFromObjectiveC(\n _ source: Self.RawValue._ObjectiveCType,\n result: inout Self?\n ) -> Bool {\n var innerResult: Self.RawValue?\n let success = Self.RawValue._conditionallyBridgeFromObjectiveC(\n source,\n result: &innerResult)\n result = innerResult.flatMap { Self(rawValue: $0) }\n return success\n }\n\n @inlinable\n @_effects(readonly)\n public static func _unconditionallyBridgeFromObjectiveC(\n _ source: Self.RawValue._ObjectiveCType?\n ) -> Self {\n return Self(\n rawValue: Self.RawValue._unconditionallyBridgeFromObjectiveC(source))!\n }\n}\n\nextension _SwiftNewtypeWrapper where Self.RawValue: AnyObject {\n @inlinable\n public func _bridgeToObjectiveC() -> Self.RawValue {\n return rawValue\n }\n\n @inlinable\n public static func _forceBridgeFromObjectiveC(\n _ source: Self.RawValue,\n result: inout Self?\n ) {\n result = Self(rawValue: source)\n }\n\n @inlinable\n public static func _conditionallyBridgeFromObjectiveC(\n _ source: Self.RawValue,\n result: inout Self?\n ) -> Bool {\n result = Self(rawValue: source)\n return result != nil\n }\n\n @inlinable\n @_effects(readonly)\n public static func _unconditionallyBridgeFromObjectiveC(\n _ source: Self.RawValue?\n ) -> Self {\n return Self(rawValue: source!)!\n }\n}\n#endif\n\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_NewtypeWrapper.swift
cpp_apple_swift_stdlib_public_core_NewtypeWrapper.swift
Swift
5,102
0.95
0.033898
0.164474
react-lib
977
2025-06-06T23:35:24.083307
BSD-3-Clause
false
c4a7916be8d1a223ea39439dd21c48aa
//===----------------------------------------------------------------------===//\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 SwiftShims\n\nextension Sequence where Element == Unicode.Scalar {\n internal var _internalNFC: Unicode._InternalNFC<Self> {\n Unicode._InternalNFC(self)\n }\n}\n\nextension Unicode {\n\n /// The contents of the source sequence, in Normalization Form C.\n ///\n /// Normalization to NFC preserves canonical equivalence.\n ///\n internal struct _InternalNFC<Source> where Source: Sequence<Unicode.Scalar> {\n\n internal let source: Source\n\n internal init(_ source: Source) {\n self.source = source\n }\n }\n}\n\nextension Unicode._InternalNFC: Sequence {\n\n internal consuming func makeIterator() -> Iterator {\n Iterator(source: source.makeIterator())\n }\n\n internal struct Iterator: IteratorProtocol {\n\n internal var source: Source.Iterator\n internal var normalizer: Unicode._NFCNormalizer\n\n internal init(source: Source.Iterator) {\n self.source = source\n if let strIter = source as? String.UnicodeScalarView.Iterator {\n self.normalizer = Unicode._NFCNormalizer(sourceString: strIter._guts)\n } else if let substrIter = source as? Substring.UnicodeScalarView.Iterator {\n self.normalizer = Unicode._NFCNormalizer(sourceString: substrIter._elements._wholeGuts)\n } else {\n self.normalizer = Unicode._NFCNormalizer()\n }\n }\n\n internal mutating func next() -> Unicode.Scalar? {\n normalizer.resume { source.next() } ?? normalizer.flush()\n }\n }\n}\n\nextension Unicode._InternalNFC: Sendable where Source: Sendable {}\nextension Unicode._InternalNFC.Iterator: Sendable where Source.Iterator: Sendable {}\n\nextension Unicode {\n\n /// A stateful normalizer, producing a single logical stream\n /// of normalized text from chunked inputs.\n ///\n /// To use the normalizer, first create an instance.\n /// Next, feed it a chunk of a text stream using the `resume(consuming:)`\n /// function. The normalizer will consume from the stream and buffer\n /// it as needed, so continue feeding the same source until\n /// it returns `nil`, indicating that the source was exhausted.\n ///\n /// ```swift\n /// var normalizer = Unicode.NFCNormalizer()\n ///\n /// var input: some IteratorProtocol<Unicode.Scalar> = ...\n /// while let scalar = normalizer.resume(consuming: &input) {\n /// print(scalar)\n /// }\n ///\n /// // assert(input.next() == nil)\n /// ```\n ///\n /// You may continue consuming sources until you reach the end\n /// of the logical text stream. Once you reach the end,\n /// call `flush()` to drain any remaining content\n /// from the normalizer's buffers.\n ///\n /// ```swift\n /// while let scalar = normalizer.flush() {\n /// print(scalar)\n /// }\n /// ```\n ///\n /// The chunks of input text do not need to be aligned on any normalization\n /// boundary. The normalizer state has value semantics, so it is possible\n /// to copy and store and is inherently thread-safe.\n ///\n internal struct _NFCNormalizer: Sendable {\n\n internal enum State {\n case emittingSegment\n case consuming\n }\n\n internal var state = State.consuming\n internal var isTerminated = false\n internal var sourceIsAlreadyNFC = false\n\n internal var nfd = Unicode._NFDNormalizer()\n internal var buffer = Unicode._NormDataBuffer()\n // This is our starter that is currently being composed with other scalars\n // into new scalars. For example, "e\u{301}", here our first scalar is 'e',\n // which is a starter, thus we assign composee to this 'e' and move to the\n // next scalar. We attempt to compose our composee, 'e', with '\u{301}' and\n // find that there is a composition. Thus our new composee is now 'é' and\n // we continue to try and compose following scalars with this composee.\n internal var composee = Optional<Unicode.Scalar>.none\n\n internal init(sourceString: borrowing _StringGuts) {\n sourceIsAlreadyNFC = sourceString.isNFC\n }\n\n /// Creates a new normalizer.\n ///\n internal init() { }\n\n /// Resume normalizing the text stream.\n ///\n /// Each call to `resume` returns the next scalar in the normalized output,\n /// consuming elements from the given source as necessary.\n ///\n /// If the normalizer returns `nil`, the source was exhausted.\n /// One a source is exhausted, you may:\n ///\n /// - Call `resume` again some time later with a different source\n /// to continue processing the same logical text stream, or\n ///\n /// - Call `flush` in order to mark the end of the stream\n /// and consume data remaining in the normalizer's internal buffers.\n ///\n /// Typical usage looks like the following:\n ///\n /// ```swift\n /// var normalizer = Unicode.NFCNormalizer()\n ///\n /// var input: some IteratorProtocol<Unicode.Scalar> = ...\n /// while let scalar = normalizer.resume(consuming: &input) {\n /// print(scalar)\n /// }\n ///\n /// // We could resume again, consuming from another input here.\n /// // Finally, when we are done consuming inputs:\n ///\n /// while let scalar = normalizer.flush() {\n /// print(scalar)\n /// }\n /// ```\n ///\n /// The normalizer consumes data from the source as needed,\n /// meaning even if a call to `resume` returns a value,\n /// that value may have come from the normalizer's internal buffers\n /// without consuming the input source at all.\n ///\n /// Be careful to ensure each input source has been fully consumed\n /// before moving on to the next source (marked by `resume` returning `nil`).\n ///\n internal mutating func resume(\n consuming source: inout some IteratorProtocol<Unicode.Scalar>\n ) -> Unicode.Scalar? {\n resume(consuming: { source.next() })\n }\n\n // Intended ABI barrier for resume(consuming: inout some IteratorProtocol<Unicode.Scalar>).\n // when it becomes public.\n internal mutating func resume(\n consuming nextFromSource: () -> Unicode.Scalar?\n ) -> Unicode.Scalar? {\n\n guard !isTerminated else {\n return nil\n }\n guard !sourceIsAlreadyNFC else {\n return nextFromSource()\n }\n return _resume(consumingNFD: { $0.nfd._resume(consuming: nextFromSource) })\n }\n\n /// Marks the end of the text stream and\n /// returns the next scalar from the normalizer's internal buffer.\n ///\n /// Once you have finished feeding input data to the normalizer,\n /// call `flush` until it returns `nil`.\n ///\n /// ```swift\n /// while let scalar = normalizer.flush() {\n /// print(scalar)\n /// }\n /// ```\n ///\n /// After calling `flush`, all future calls to `resume`\n /// will immediately return `nil` without consuming from its source.\n /// This allows optional chaining to be used to\n /// fully normalize a stream:\n ///\n /// ```swift\n /// // Normalize the concatenation of inputA and inputB\n ///\n /// while let scalar =\n /// normalizer.resume(consuming: &inputA) ??\n /// normalizer.resume(consuming: &inputB) ??\n /// normalizer.flush()\n /// {\n /// print(scalar)\n /// }\n /// ```\n ///\n internal mutating func flush() -> Unicode.Scalar? {\n\n isTerminated = true\n\n guard !sourceIsAlreadyNFC else {\n return nil\n }\n\n // Process anything remaining from the NFD normalizer.\n if let next = _resume(consumingNFD: { $0.nfd._flush() }) {\n return next\n }\n\n // If we have a leftover composee, make sure to return it.\n // We may still have things in the buffer which are not complete segments.\n return composee.take() ?? buffer.next()?.scalar\n }\n }\n}\n\nextension Unicode._NFCNormalizer {\n\n @inline(never)\n internal mutating func _resume(\n consumingNFD nextNFD: (inout Self) -> ScalarAndNormData?\n ) -> Unicode.Scalar? {\n\n switch state {\n case .emittingSegment:\n\n if let buffered = buffer.next() {\n return buffered.scalar\n }\n state = .consuming\n fallthrough\n\n case .consuming:\n\n while let current = nextNFD(&self) {\n\n // The first starter in the sequence is our initial 'composee'.\n // Any scalars preceding the first starter have nothing to compose with\n // and are just emitted directly.\n\n guard let currentComposee = composee else {\n guard current.normData.canonicalCombiningClass == .notReordered else {\n return current.scalar\n }\n composee = current.scalar\n continue\n }\n\n guard let lastBufferedNormData = buffer.last?.normData else {\n\n // The buffer is empty so we have a simple Non-Blocked Pair,\n // <composee, current>. Look for an equivalent Primary Composite.\n // If 'current' is NFC_QC, we already know there won't be a composite.\n\n guard\n !current.normData.isNFCQC,\n let composed = compose(currentComposee, andNonNFCQC: current.scalar)\n else {\n\n // No Primary Composite found.\n // If 'current' is a starter, yield 'composee',\n // and begin a new segment with 'current' as the new 'composee'.\n // Otherwise, 'current' is a non-composing mark\n // that we need to buffer until we are finished composing.\n\n if current.normData.canonicalCombiningClass == .notReordered {\n composee = current.scalar\n return currentComposee\n }\n buffer.append(current)\n continue\n }\n\n // Primary Composite found. \n // It becomes our new 'composee' and 'current' is discarded.\n\n composee = composed\n continue\n }\n\n // We have the sequence <composee, [...buffer contents...], current>.\n // Check whether 'current' may compose with 'composee',\n // or whether it is blocked by the buffer contents.\n //\n // Blocking refers to the presence of a scalar X in the buffer\n // where CCC(X) == 0 or CCC(X) >= CCC(current).\n //\n // Example:\n //\n // - "a\u{0305}\u{0300}b" (a̅̀b) => NFC "a\u{0305}\u{0300}b" (a̅̀b)\n // - "a\u{0300}\u{0305}b" (à̅b) => NFC "\u{00E0}\u{0305}b" (à̅b)\n // ^^^ ^^^\n //\n // These strings contain two combining marks with the same combining\n // class: U+0305 COMBINING OVERLINE and U+0300 COMBINING GRAVE ACCENT.\n // Because these marks have the same class, they cannot be reordered\n // (their existing order is important). In one ordering, the accent\n // appears above the overline, and in the other the order is reversed.\n //\n // It turns out, there is no composite for <"a", overline>,\n // but there is one for <"a", grave accent>: the\n // U+00E0 LATIN SMALL LETTER A WITH GRAVE we see in the second example.\n //\n // Despite the overline not composing, it would be wrong\n // if the grave accent could squeeze ahead of it\n // via composition with the "a".\n // So the presence of the overline must block the composition.\n\n _internalInvariant(\n lastBufferedNormData.canonicalCombiningClass != .notReordered,\n "We never buffer starters"\n )\n\n // Since we consume an NFD stream\n // the buffer contents are already in canonical order,\n // and 'lastBufferedNormData' has the highest CCC in the buffer.\n\n _internalInvariant(\n lastBufferedNormData.canonicalCombiningClass <= current.normData.canonicalCombiningClass\n || current.normData.canonicalCombiningClass == .notReordered,\n "NFD stream not in canonical order"\n )\n\n guard lastBufferedNormData.canonicalCombiningClass < current.normData.canonicalCombiningClass else {\n\n // 'current' is blocked from composing with 'composee'.\n //\n // If 'current' is a starter, yield 'composee', \n // emit the segment that we have in the buffer,\n // and begin a new segment with 'current' as the new 'composee'.\n // Otherwise, 'current' is a non-composing mark\n // that we need to buffer until we are finished composing.\n\n if current.normData.canonicalCombiningClass == .notReordered {\n composee = current.scalar\n state = .emittingSegment\n return currentComposee\n }\n buffer.append(current)\n continue\n }\n\n _internalInvariant(current.normData.canonicalCombiningClass != .notReordered)\n\n // Look for a Primary Composite equivalent to <composee, current>.\n // If 'current' is NFC_QC, we already know there won't be any composite.\n\n guard\n !current.normData.isNFCQC,\n let composed = compose(currentComposee, andNonNFCQC: current.scalar)\n else {\n\n // No Primary Composite found.\n // We know 'current' is not a starter, so it is a non-composing mark\n // that we need to buffer until we are finished composing.\n buffer.append(current)\n continue\n }\n\n // Primary Composite found.\n // It becomes our new 'composee', and 'current' is discarded.\n\n composee = composed\n }\n\n // NFD source is exhausted.\n return nil\n }\n }\n\n private func compose(\n _ x: Unicode.Scalar,\n andNonNFCQC y: Unicode.Scalar\n ) -> Unicode.Scalar? {\n\n if let hangul = composeHangul(x, and: y) {\n return hangul\n }\n\n // Otherwise, lookup the composition.\n let composition = _swift_stdlib_getComposition(x.value, y.value)\n\n guard composition != .max else {\n return nil\n }\n\n return Unicode.Scalar(_value: composition)\n }\n\n @inline(never)\n private func composeHangul(\n _ x: Unicode.Scalar,\n and y: Unicode.Scalar\n ) -> Unicode.Scalar? {\n // L = Hangul leading consonants\n let L: (base: UInt32, count: UInt32) = (base: 0x1100, count: 19)\n // V = Hangul vowels\n let V: (base: UInt32, count: UInt32) = (base: 0x1161, count: 21)\n // T = Hangul tail consonants\n let T: (base: UInt32, count: UInt32) = (base: 0x11A7, count: 28)\n // N = Number of precomposed Hangul syllables that start with the same\n // leading consonant. (There is no base for N).\n let N: (base: UInt32, count: UInt32) = (base: 0x0, count: 588)\n // S = Hangul precomposed syllables\n let S: (base: UInt32, count: UInt32) = (base: 0xAC00, count: 11172)\n\n switch (x.value, y.value) {\n // Check for Hangul (L, V) -> LV compositions.\n case (L.base ..< L.base &+ L.count, V.base ..< V.base &+ V.count):\n let lIdx = x.value &- L.base\n let vIdx = y.value &- V.base\n let lvIdx = lIdx &* N.count &+ vIdx &* T.count\n let s = S.base &+ lvIdx\n return Unicode.Scalar(_value: s)\n\n // Check for Hangul (LV, T) -> LVT compositions.\n case (S.base ..< S.base &+ S.count, T.base &+ 1 ..< T.base &+ T.count):\n if (x.value &- S.base) % T.count == 0 {\n return Unicode.Scalar(_value: x.value &+ y.value &- T.base)\n } else {\n fallthrough\n }\n\n default:\n return nil\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_NFC.swift
cpp_apple_swift_stdlib_public_core_NFC.swift
Swift
15,551
0.95
0.072527
0.511568
python-kit
567
2024-04-16T03:35:14.642791
Apache-2.0
false
3c8da3e2fcf0297719ca32166ddaf50b
//===----------------------------------------------------------------------===//\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\nextension Sequence where Element == Unicode.Scalar {\n internal var _internalNFD: Unicode._InternalNFD<Self> {\n Unicode._InternalNFD(self)\n }\n}\n\nextension Unicode {\n\n /// The contents of the source sequence, in Normalization Form D.\n ///\n /// Normalization to NFD preserves canonical equivalence.\n ///\n internal struct _InternalNFD<Source> where Source: Sequence<Unicode.Scalar> {\n\n internal let source: Source\n\n internal init(_ source: Source) {\n self.source = source\n }\n }\n}\n\nextension Unicode._InternalNFD: Sequence {\n\n internal consuming func makeIterator() -> Iterator {\n Iterator(source: source.makeIterator())\n }\n\n internal struct Iterator: IteratorProtocol {\n\n internal var source: Source.Iterator\n internal var normalizer: Unicode._NFDNormalizer\n\n internal init(source: Source.Iterator) {\n self.source = source\n self.normalizer = Unicode._NFDNormalizer()\n }\n\n internal mutating func next() -> Unicode.Scalar? {\n normalizer.resume(consuming: &source) ?? normalizer.flush()\n }\n }\n}\n\nextension Unicode._InternalNFD: Sendable where Source: Sendable {}\nextension Unicode._InternalNFD.Iterator: Sendable where Source.Iterator: Sendable {}\n\nextension Unicode {\n\n /// A stateful normalizer, producing a single logical stream\n /// of normalized text from chunked inputs.\n ///\n /// To use the normalizer, first create an instance.\n /// Next, feed it a chunk of a text stream using the `resume(consuming:)`\n /// function. The normalizer will consume from the stream and buffer\n /// it as needed, so continue feeding the same source until\n /// it returns `nil`, indicating that the source was exhausted.\n ///\n /// ```swift\n /// var normalizer = Unicode.NFDNormalizer()\n ///\n /// var input: some IteratorProtocol<Unicode.Scalar> = ...\n /// while let scalar = normalizer.resume(consuming: &input) {\n /// print(scalar)\n /// }\n ///\n /// // assert(input.next() == nil)\n /// ```\n ///\n /// You may continue consuming sources until you reach the end\n /// of the logical text stream. Once you reach the end,\n /// call `flush()` to drain any remaining content\n /// from the normalizer's buffers.\n ///\n /// ```swift\n /// while let scalar = normalizer.flush() {\n /// print(scalar)\n /// }\n /// ```\n ///\n /// The chunks of input text do not need to be aligned on any normalization\n /// boundary. The normalizer state has value semantics, so it is possible\n /// to copy and store and is inherently thread-safe.\n ///\n internal struct _NFDNormalizer: Sendable {\n\n internal enum State {\n case emittingSegment\n case consuming\n case terminated\n }\n\n internal var state = State.consuming\n\n internal var buffer = Unicode._NormDataBuffer()\n internal var pendingStarter = Optional<ScalarAndNormData>.none\n internal var bufferIsSorted = false\n\n /// Creates a new normalizer.\n ///\n internal init() { }\n\n /// Resume normalizing the text stream.\n ///\n /// Each call to `resume` returns the next scalar in the normalized output,\n /// consuming elements from the given source as necessary.\n ///\n /// If the normalizer returns `nil`, the source was exhausted.\n /// One a source is exhausted, you may:\n ///\n /// - Call `resume` again some time later with a different source\n /// to continue processing the same logical text stream, or\n ///\n /// - Call `flush` in order to mark the end of the stream\n /// and consume data remaining in the normalizer's internal buffers.\n ///\n /// Typical usage looks like the following:\n ///\n /// ```swift\n /// var normalizer = Unicode.NFDNormalizer()\n ///\n /// var input: some IteratorProtocol<Unicode.Scalar> = ...\n /// while let scalar = normalizer.resume(consuming: &input) {\n /// print(scalar)\n /// }\n ///\n /// // We could resume again, consuming from another input here.\n /// // Finally, when we are done consuming inputs:\n ///\n /// while let scalar = normalizer.flush() {\n /// print(scalar)\n /// }\n /// ```\n ///\n /// The normalizer consumes data from the source as needed,\n /// meaning even if a call to `resume` returns a value,\n /// that value may have come from the normalizer's internal buffers\n /// without consuming the input source at all.\n ///\n /// Be careful to ensure each input source has been fully consumed\n /// before moving on to the next source (marked by `resume` returning `nil`).\n ///\n internal mutating func resume(\n consuming source: inout some IteratorProtocol<Unicode.Scalar>\n ) -> Unicode.Scalar? {\n resume(consuming: { source.next() })\n }\n\n // Intended ABI barrier for resume(consuming: inout some IteratorProtocol<Unicode.Scalar>).\n // when it becomes public.\n internal mutating func resume(\n consuming nextFromSource: () -> Unicode.Scalar?\n ) -> Unicode.Scalar? {\n _resume(consuming: nextFromSource)?.scalar\n }\n\n /// Marks the end of the text stream and\n /// returns the next scalar from the normalizer's internal buffer.\n ///\n /// Once you have finished feeding input data to the normalizer,\n /// call `flush` until it returns `nil`.\n ///\n /// ```swift\n /// while let scalar = normalizer.flush() {\n /// print(scalar)\n /// }\n /// ```\n ///\n /// After calling `flush`, all future calls to `resume`\n /// will immediately return `nil` without consuming from its source.\n /// This allows optional chaining to be used to\n /// fully normalize a stream:\n ///\n /// ```swift\n /// // Normalize the concatenation of inputA and inputB\n ///\n /// while let scalar =\n /// normalizer.resume(consuming: &inputA) ??\n /// normalizer.resume(consuming: &inputB) ??\n /// normalizer.flush()\n /// {\n /// print(scalar)\n /// }\n /// ```\n internal mutating func flush() -> Unicode.Scalar? {\n _flush()?.scalar\n }\n }\n}\n\nextension Unicode._NFDNormalizer {\n\n @inline(never)\n internal mutating func _resume(\n consuming nextFromSource: () -> Unicode.Scalar?\n ) -> ScalarAndNormData? {\n\n switch state {\n case .emittingSegment:\n _internalInvariant(\n pendingStarter != nil,\n "Must find next segment starter before emitting buffered segment"\n )\n _internalInvariant(\n bufferIsSorted,\n "Buffered segment must be sorted before being emitted"\n )\n\n if let buffered = buffer.next() {\n return buffered\n }\n bufferIsSorted = false\n state = .consuming\n fallthrough\n\n case .consuming:\n\n while let (scalar, normData) = takePendingOrConsume(nextFromSource) {\n\n // If this scalar is a starter, stash it and emit the decomposed segment\n // we have in the buffer. The buffer must be sorted first.\n\n if normData.canonicalCombiningClass == .notReordered, !buffer.isEmpty {\n pendingStarter = (scalar, normData)\n buffer.sort()\n bufferIsSorted = true\n state = .emittingSegment\n return buffer.next()\n }\n\n // If this scalar is NFD_QC, it does not need to be decomposed.\n\n if normData.isNFDQC {\n\n // If the scalar is a starter its CCC is 0,\n // so it does not need to be sorted and can be emitted directly.\n\n if normData.canonicalCombiningClass == .notReordered {\n return (scalar, normData)\n }\n buffer.append((scalar, normData))\n continue\n }\n\n // Otherwise, append the scalar's decomposition to the buffer.\n\n decomposeNonNFDQC((scalar, normData))\n }\n\n // Source is exhausted.\n return nil\n\n case .terminated:\n return nil\n }\n }\n\n internal mutating func _flush() -> ScalarAndNormData? {\n\n state = .terminated\n\n if !bufferIsSorted {\n buffer.sort()\n bufferIsSorted = true\n }\n\n // The buffer contains the decomposed segment *prior to*\n // any pending starter we might have.\n\n return buffer.next() ?? pendingStarter.take()\n }\n\n @inline(__always)\n private mutating func takePendingOrConsume(\n _ nextFromSource: () -> Unicode.Scalar?\n ) -> ScalarAndNormData? {\n\n if let pendingStarter = pendingStarter.take() {\n return pendingStarter\n } else if let nextScalar = nextFromSource() {\n return (nextScalar, Unicode._NormData(nextScalar))\n } else {\n return nil\n }\n }\n\n private mutating func decomposeNonNFDQC(\n _ scalarInfo: ScalarAndNormData\n ) {\n // Handle Hangul decomposition algorithmically.\n // S.base = 0xAC00\n // S.count = 11172\n // S.base + S.count - 1 = 0xD7A3\n if (0xAC00 ... 0xD7A3).contains(scalarInfo.scalar.value) {\n decomposeHangul(scalarInfo.scalar)\n return\n }\n\n // Otherwise, we need to lookup the decomposition (if there is one).\n decomposeSlow(scalarInfo)\n }\n\n @inline(never)\n private mutating func decomposeHangul(_ scalar: Unicode.Scalar) {\n // L = Hangul leading consonants\n let L: (base: UInt32, count: UInt32) = (base: 0x1100, count: 19)\n // V = Hangul vowels\n let V: (base: UInt32, count: UInt32) = (base: 0x1161, count: 21)\n // T = Hangul tail consonants\n let T: (base: UInt32, count: UInt32) = (base: 0x11A7, count: 28)\n // N = Number of precomposed Hangul syllables that start with the same\n // leading consonant. (There is no base for N).\n let N: (base: UInt32, count: UInt32) = (base: 0x0, count: 588)\n // S = Hangul precomposed syllables\n let S: (base: UInt32, count: UInt32) = (base: 0xAC00, count: 11172)\n\n let sIdx = scalar.value &- S.base\n\n let lIdx = sIdx / N.count\n let l = Unicode.Scalar(_value: L.base &+ lIdx)\n // Hangul leading consonants, L, always have normData of 0.\n // CCC = 0, NFC_QC = Yes, NFD_QC = Yes\n buffer.append((scalar: l, normData: .init(rawValue: 0)))\n\n let vIdx = (sIdx % N.count) / T.count\n let v = Unicode.Scalar(_value: V.base &+ vIdx)\n // Hangul vowels, V, always have normData of 4.\n // CCC = 0, NFC_QC = Maybe, NFD_QC = Yes\n buffer.append((scalar: v, normData: .init(rawValue: 4)))\n\n let tIdx = sIdx % T.count\n if tIdx != 0 {\n let t = Unicode.Scalar(_value: T.base &+ tIdx)\n // Hangul tail consonants, T, always have normData of 4.\n // CCC = 0, NFC_QC = Maybe, NFD_QC = Yes\n buffer.append((scalar: t, normData: .init(rawValue: 4)))\n }\n }\n\n @inline(never)\n private mutating func decomposeSlow(\n _ original: ScalarAndNormData\n ) {\n // Look into the decomposition perfect hash table.\n let decompEntry = Unicode._DecompositionEntry(original.scalar)\n\n // If this is not our original scalar, then we have no decomposition for this\n // scalar, so just emit itself. This is required because perfect hashing\n // does not know the original set of keys that it used to create itself, so\n // we store the original scalar in our decomposition entry to ensure that\n // scalars that hash to the same index don't succeed.\n guard original.scalar == decompEntry.hashedScalar else {\n buffer.append(original)\n return\n }\n\n var utf8 = unsafe decompEntry.utf8\n\n while utf8.count > 0 {\n let (scalar, len) = unsafe _decodeScalar(utf8, startingAt: 0)\n unsafe utf8 = unsafe UnsafeBufferPointer(rebasing: utf8[len...])\n\n // Fast path: Because this will be emitted into the completed NFD buffer,\n // we don't need to look at NFD_QC anymore which lets us do a larger\n // latiny check for NFC_QC and CCC (0xC0 vs. 0x300).\n let normData = Unicode._NormData(scalar, fastUpperbound: 0x300)\n\n buffer.append((scalar, normData))\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_NFD.swift
cpp_apple_swift_stdlib_public_core_NFD.swift
Swift
12,149
0.95
0.070496
0.481595
vue-tools
463
2025-03-07T19:33:52.561467
BSD-3-Clause
false
505f0a824052ef3ee8f327a31bf91b2c
//===----------------------------------------------------------------------===//\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 !$Embedded && hasFeature(Macros)\n@DebugDescription\nextension ObjectIdentifier {\n var lldbDescription: String {\n return "ObjectIdentifier(\(_value))"\n }\n}\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ObjectIdentifier+DebugDescription.swift
cpp_apple_swift_stdlib_public_core_ObjectIdentifier+DebugDescription.swift
Swift
690
0.8
0.15
0.684211
python-kit
755
2025-03-25T04:23:24.577977
BSD-3-Clause
false
4b7e3a37ecd6f3086e5b249940e93393
//===----------------------------------------------------------------------===//\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 !$Embedded\n\n/// A unique identifier for a class instance or metatype.\n///\n/// This unique identifier is only valid for comparisons during the lifetime\n/// of the instance.\n///\n/// In Swift, only class instances and metatypes have unique identities. There\n/// is no notion of identity for structs, enums, functions, or tuples.\n@frozen // trivial-implementation\npublic struct ObjectIdentifier: Sendable {\n @usableFromInline // trivial-implementation\n internal let _value: Builtin.RawPointer\n\n /// Creates an instance that uniquely identifies the given class instance.\n ///\n /// The following example creates an example class `IntegerRef` and compares\n /// instances of the class using their object identifiers and the identical-to\n /// operator (`===`):\n ///\n /// class IntegerRef {\n /// let value: Int\n /// init(_ value: Int) {\n /// self.value = value\n /// }\n /// }\n ///\n /// let x = IntegerRef(10)\n /// let y = x\n ///\n /// print(ObjectIdentifier(x) == ObjectIdentifier(y))\n /// // Prints "true"\n /// print(x === y)\n /// // Prints "true"\n ///\n /// let z = IntegerRef(10)\n /// print(ObjectIdentifier(x) == ObjectIdentifier(z))\n /// // Prints "false"\n /// print(x === z)\n /// // Prints "false"\n ///\n /// - Parameter x: An instance of a class.\n @inlinable // trivial-implementation\n public init(_ x: AnyObject) {\n self._value = Builtin.bridgeToRawPointer(x)\n }\n\n /// Creates an instance that uniquely identifies the given metatype.\n ///\n /// - Parameters:\n /// - x: A metatype.\n @_alwaysEmitIntoClient\n public init(_ x: any (~Copyable & ~Escapable).Type) {\n self._value = unsafe unsafeBitCast(x, to: Builtin.RawPointer.self)\n }\n\n @inlinable\n public init(_ x: Any.Type) {\n // FIXME: This ought to be obsoleted in favor of the generalized overload\n // above. Unfortunately, that one sometimes causes a runtime hang.\n self._value = unsafe unsafeBitCast(x, to: Builtin.RawPointer.self)\n }\n}\n\n#else\n\n@frozen // trivial-implementation\npublic struct ObjectIdentifier: Sendable {\n @usableFromInline // trivial-implementation\n internal let _value: Builtin.RawPointer\n\n @inlinable // trivial-implementation\n public init<Object: AnyObject>(_ x: Object) {\n self._value = Builtin.bridgeToRawPointer(x)\n }\n\n @inlinable // trivial-implementation\n public init<T: ~Copyable & ~Escapable>(_ x: T.Type) {\n self._value = unsafe unsafeBitCast(x, to: Builtin.RawPointer.self)\n }\n}\n\n#endif\n\n@_unavailableInEmbedded\nextension ObjectIdentifier: CustomDebugStringConvertible {\n /// A textual representation of the identifier, suitable for debugging.\n public var debugDescription: String {\n return "ObjectIdentifier(\(_rawPointerToString(_value)))"\n }\n}\n\nextension ObjectIdentifier: Equatable {\n @inlinable // trivial-implementation\n public static func == (x: ObjectIdentifier, y: ObjectIdentifier) -> Bool {\n return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value))\n }\n}\n\nextension ObjectIdentifier: Comparable {\n @inlinable // trivial-implementation\n public static func < (lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool {\n return UInt(bitPattern: lhs) < UInt(bitPattern: rhs)\n }\n}\n\nextension ObjectIdentifier: 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(Int(Builtin.ptrtoint_Word(_value)))\n }\n\n @_alwaysEmitIntoClient // For back deployment\n public func _rawHashValue(seed: Int) -> Int {\n Int(Builtin.ptrtoint_Word(_value))._rawHashValue(seed: seed)\n }\n}\n\nextension UInt {\n /// Creates an integer that captures the full value of the given object\n /// identifier.\n @inlinable // trivial-implementation\n public init(bitPattern objectID: ObjectIdentifier) {\n self.init(Builtin.ptrtoint_Word(objectID._value))\n }\n}\n\nextension Int {\n /// Creates an integer that captures the full value of the given object\n /// identifier.\n @inlinable // trivial-implementation\n public init(bitPattern objectID: ObjectIdentifier) {\n self.init(bitPattern: UInt(bitPattern: objectID))\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ObjectIdentifier.swift
cpp_apple_swift_stdlib_public_core_ObjectIdentifier.swift
Swift
4,823
0.95
0.092105
0.481481
vue-tools
216
2023-11-29T01:58:23.385580
BSD-3-Clause
false
6e971727e0269df5d6651c5670aaa428
//===----------------------------------------------------------------------===//\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 type that represents either a wrapped value or the absence of a value.\n///\n/// You use the `Optional` type whenever you use optional values, even if you\n/// never type the word `Optional`. Swift's type system usually shows the\n/// wrapped type's name with a trailing question mark (`?`) instead of showing\n/// the full type name. For example, if a variable has the type `Int?`, that's\n/// just another way of writing `Optional<Int>`. The shortened form is\n/// preferred for ease of reading and writing code.\n///\n/// The types of `shortForm` and `longForm` in the following code sample are\n/// the same:\n///\n/// let shortForm: Int? = Int("42")\n/// let longForm: Optional<Int> = Int("42")\n///\n/// The `Optional` type is an enumeration with two cases. `Optional.none` is\n/// equivalent to the `nil` literal. `Optional.some(Wrapped)` stores a wrapped\n/// value. For example:\n///\n/// let number: Int? = Optional.some(42)\n/// let noNumber: Int? = Optional.none\n/// print(noNumber == nil)\n/// // Prints "true"\n///\n/// You must unwrap the value of an `Optional` instance before you can use it\n/// in many contexts. Because Swift provides several ways to safely unwrap\n/// optional values, you can choose the one that helps you write clear,\n/// concise code.\n///\n/// The following examples use this dictionary of image names and file paths:\n///\n/// let imagePaths = ["star": "/glyphs/star.png",\n/// "portrait": "/images/content/portrait.jpg",\n/// "spacer": "/images/shared/spacer.gif"]\n///\n/// Getting a dictionary's value using a key returns an optional value, so\n/// `imagePaths["star"]` has type `Optional<String>` or, written in the\n/// preferred manner, `String?`.\n///\n/// Optional Binding\n/// ----------------\n///\n/// To conditionally bind the wrapped value of an `Optional` instance to a new\n/// variable, use one of the optional binding control structures, including\n/// `if let`, `guard let`, and `switch`.\n///\n/// if let starPath = imagePaths["star"] {\n/// print("The star image is at '\(starPath)'")\n/// } else {\n/// print("Couldn't find the star image")\n/// }\n/// // Prints "The star image is at '/glyphs/star.png'"\n///\n/// Optional Chaining\n/// -----------------\n///\n/// To safely access the properties and methods of a wrapped instance, use the\n/// postfix optional chaining operator (postfix `?`). The following example uses\n/// optional chaining to access the `hasSuffix(_:)` method on a `String?`\n/// instance.\n///\n/// if imagePaths["star"]?.hasSuffix(".png") == true {\n/// print("The star image is in PNG format")\n/// }\n/// // Prints "The star image is in PNG format"\n///\n/// Using the Nil-Coalescing Operator\n/// ---------------------------------\n///\n/// Use the nil-coalescing operator (`??`) to supply a default value in case\n/// the `Optional` instance is `nil`. Here a default path is supplied for an\n/// image that is missing from `imagePaths`.\n///\n/// let defaultImagePath = "/images/default.png"\n/// let heartPath = imagePaths["heart"] ?? defaultImagePath\n/// print(heartPath)\n/// // Prints "/images/default.png"\n///\n/// The `??` operator also works with another `Optional` instance on the\n/// right-hand side. As a result, you can chain multiple `??` operators\n/// together.\n///\n/// let shapePath = imagePaths["cir"] ?? imagePaths["squ"] ?? defaultImagePath\n/// print(shapePath)\n/// // Prints "/images/default.png"\n///\n/// Unconditional Unwrapping\n/// ------------------------\n///\n/// When you're certain that an instance of `Optional` contains a value, you\n/// can unconditionally unwrap the value by using the forced\n/// unwrap operator (postfix `!`). For example, the result of the failable `Int`\n/// initializer is unconditionally unwrapped in the example below.\n///\n/// let number = Int("42")!\n/// print(number)\n/// // Prints "42"\n///\n/// You can also perform unconditional optional chaining by using the postfix\n/// `!` operator.\n///\n/// let isPNG = imagePaths["star"]!.hasSuffix(".png")\n/// print(isPNG)\n/// // Prints "true"\n///\n/// Unconditionally unwrapping a `nil` instance with `!` triggers a runtime\n/// error.\n@frozen\npublic enum Optional<Wrapped: ~Copyable & ~Escapable>: ~Copyable, ~Escapable {\n // The compiler has special knowledge of Optional<Wrapped>, including the fact\n // that it is an `enum` with cases named `none` and `some`.\n\n /// The absence of a value.\n ///\n /// In code, the absence of a value is typically written using the `nil`\n /// literal rather than the explicit `.none` enumeration case.\n case none\n\n /// The presence of a value, stored as `Wrapped`.\n case some(Wrapped)\n}\n\nextension Optional: Copyable where Wrapped: Copyable & ~Escapable {}\n\nextension Optional: Escapable where Wrapped: Escapable & ~Copyable {}\n\nextension Optional: BitwiseCopyable\nwhere Wrapped: BitwiseCopyable & ~Escapable {}\n\nextension Optional: Sendable where Wrapped: ~Copyable & ~Escapable & Sendable {}\n\n\n@_preInverseGenerics\nextension Optional: ExpressibleByNilLiteral\nwhere Wrapped: ~Copyable & ~Escapable {\n /// Creates an instance initialized with `nil`.\n ///\n /// Do not call this initializer directly. It is used by the compiler when you\n /// initialize an `Optional` instance with a `nil` literal. For example:\n ///\n /// var i: Index? = nil\n ///\n /// In this example, the assignment to the `i` variable calls this\n /// initializer behind the scenes.\n @_transparent\n @_preInverseGenerics\n @lifetime(immortal)\n public init(nilLiteral: ()) {\n self = .none\n }\n}\n\nextension Optional where Wrapped: ~Copyable {\n /// Creates an instance that stores the given value.\n @_transparent\n @_preInverseGenerics\n public init(_ value: consuming Wrapped) {\n // FIXME: Merge this with the generalization below.\n // This is the original initializer, preserved to avoid breaking source\n // compatibility with clients that use the `Optional.init` syntax to create\n // a function reference. The ~Escapable generalization is currently breaking\n // that. (rdar://147533059)\n self = .some(value)\n }\n}\n\nextension Optional where Wrapped: ~Copyable & ~Escapable {\n /// Creates an instance that stores the given value.\n @_transparent\n @_alwaysEmitIntoClient\n @lifetime(copy value)\n public init(_ value: consuming Wrapped) {\n // FIXME: Merge this into the original entry above.\n self = .some(value)\n }\n}\n\nextension Optional {\n /// Evaluates the given closure when this `Optional` instance is not `nil`,\n /// passing the unwrapped value as a parameter.\n ///\n /// Use the `map` method with a closure that returns a non-optional value.\n /// This example performs an arithmetic operation on an\n /// optional integer.\n ///\n /// let possibleNumber: Int? = Int("42")\n /// let possibleSquare = possibleNumber.map { $0 * $0 }\n /// print(possibleSquare)\n /// // Prints "Optional(1764)"\n ///\n /// let noNumber: Int? = nil\n /// let noSquare = noNumber.map { $0 * $0 }\n /// print(noSquare)\n /// // Prints "nil"\n ///\n /// - Parameter transform: A closure that takes the unwrapped value\n /// of the instance.\n /// - Returns: The result of the given closure. If this instance is `nil`,\n /// returns `nil`.\n @_alwaysEmitIntoClient\n public func map<E: Error, U: ~Copyable>(\n _ transform: (Wrapped) throws(E) -> U\n ) throws(E) -> U? {\n switch self {\n case .some(let y):\n return .some(try transform(y))\n case .none:\n return .none\n }\n }\n\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @usableFromInline\n internal func map<U>(\n _ transform: (Wrapped) throws -> U\n ) rethrows -> U? {\n switch self {\n case .some(let y):\n return .some(try transform(y))\n case .none:\n return .none\n }\n }\n}\n\nextension Optional where Wrapped: ~Copyable {\n // FIXME(NCG): Make this public.\n @_alwaysEmitIntoClient\n public consuming func _consumingMap<U: ~Copyable, E: Error>(\n _ transform: (consuming Wrapped) throws(E) -> U\n ) throws(E) -> U? {\n switch consume self {\n case .some(let y):\n return .some(try transform(y))\n case .none:\n return .none\n }\n }\n\n // FIXME(NCG): Make this public.\n @_alwaysEmitIntoClient\n public borrowing func _borrowingMap<U: ~Copyable, E: Error>(\n _ transform: (borrowing Wrapped) throws(E) -> U\n ) throws(E) -> U? {\n switch self {\n case .some(let y):\n return .some(try transform(y))\n case .none:\n return .none\n }\n }\n}\n\nextension Optional {\n /// Evaluates the given closure when this `Optional` instance is not `nil`,\n /// passing the unwrapped value as a parameter.\n ///\n /// Use the `flatMap` method with a closure that returns an optional value.\n /// This example performs an arithmetic operation with an optional result on\n /// an optional integer.\n ///\n /// let possibleNumber: Int? = Int("42")\n /// let nonOverflowingSquare = possibleNumber.flatMap { x -> Int? in\n /// let (result, overflowed) = x.multipliedReportingOverflow(by: x)\n /// return overflowed ? nil : result\n /// }\n /// print(nonOverflowingSquare)\n /// // Prints "Optional(1764)"\n ///\n /// - Parameter transform: A closure that takes the unwrapped value\n /// of the instance.\n /// - Returns: The result of the given closure. If this instance is `nil`,\n /// returns `nil`.\n @_alwaysEmitIntoClient\n public func flatMap<E: Error, U: ~Copyable>(\n _ transform: (Wrapped) throws(E) -> U?\n ) throws(E) -> U? {\n switch self {\n case .some(let y):\n return try transform(y)\n case .none:\n return .none\n }\n }\n\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @usableFromInline\n internal func flatMap<U>(\n _ transform: (Wrapped) throws -> U?\n ) rethrows -> U? {\n switch self {\n case .some(let y):\n return try transform(y)\n case .none:\n return .none\n }\n }\n}\n\nextension Optional where Wrapped: ~Copyable {\n // FIXME(NCG): Make this public.\n @_alwaysEmitIntoClient\n public consuming func _consumingFlatMap<U: ~Copyable, E: Error>(\n _ transform: (consuming Wrapped) throws(E) -> U?\n ) throws(E) -> U? {\n switch consume self {\n case .some(let y):\n return try transform(consume y)\n case .none:\n return .none\n }\n }\n\n // FIXME(NCG): Make this public.\n @_alwaysEmitIntoClient\n public func _borrowingFlatMap<U: ~Copyable, E: Error>(\n _ transform: (borrowing Wrapped) throws(E) -> U?\n ) throws(E) -> U? {\n switch self {\n case .some(let y):\n return try transform(y)\n case .none:\n return .none\n }\n }\n}\n\nextension Optional where Wrapped: ~Escapable {\n /// The wrapped value of this instance, unwrapped without checking whether\n /// the instance is `nil`.\n ///\n /// The `unsafelyUnwrapped` property provides the same value as the forced\n /// unwrap operator (postfix `!`). However, in optimized builds (`-O`), no\n /// check is performed to ensure that the current instance actually has a\n /// value. Accessing this property in the case of a `nil` value is a serious\n /// programming error and could lead to undefined behavior or a runtime\n /// error.\n ///\n /// In debug builds (`-Onone`), the `unsafelyUnwrapped` property has the same\n /// behavior as using the postfix `!` operator and triggers a runtime error\n /// if the instance is `nil`.\n ///\n /// The `unsafelyUnwrapped` property is recommended over calling the\n /// `unsafeBitCast(_:)` function because the property is more restrictive\n /// and because accessing the property still performs checking in debug\n /// builds.\n ///\n /// - Warning: This property trades safety for performance. Use\n /// `unsafelyUnwrapped` only when you are confident that this instance\n /// will never be equal to `nil` and only after you've tried using the\n /// postfix `!` operator.\n @inlinable\n @_preInverseGenerics\n @unsafe\n public var unsafelyUnwrapped: Wrapped {\n // FIXME: Generalize this for ~Copyable wrapped types. Note that the current\n // implementation is copying the value, so that generalization will need to\n // be emitted into clients -- `@_preInverseGenerics` will not cut it.\n @inline(__always)\n @lifetime(copy self)\n get {\n if let x = self {\n return x\n }\n _debugPreconditionFailure("unsafelyUnwrapped of nil optional")\n }\n }\n}\n\nextension Optional where Wrapped: ~Copyable & ~Escapable {\n // FIXME(NCG): Do we want this? It seems like we do. Make this public.\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public consuming func _consumingUnsafelyUnwrap() -> Wrapped {\n switch consume self {\n case .some(let x):\n return x\n case .none:\n _debugPreconditionFailure("consumingUsafelyUnwrap of nil optional")\n }\n }\n}\n\nextension Optional where Wrapped: ~Escapable {\n /// - Returns: `unsafelyUnwrapped`.\n ///\n /// This version is for internal stdlib use; it avoids any checking\n /// overhead for users, even in Debug builds.\n @inlinable\n @_preInverseGenerics\n internal var _unsafelyUnwrappedUnchecked: Wrapped {\n @inline(__always)\n @lifetime(copy self)\n get {\n if let x = self {\n return x\n }\n _internalInvariantFailure("_unsafelyUnwrappedUnchecked of nil optional")\n }\n }\n}\n\nextension Optional where Wrapped: ~Copyable & ~Escapable {\n /// - Returns: `unsafelyUnwrapped`.\n ///\n /// This version is for internal stdlib use; it avoids any checking\n /// overhead for users, even in Debug builds.\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n internal consuming func _consumingUncheckedUnwrapped() -> Wrapped {\n if let x = self {\n return x\n }\n _internalInvariantFailure("_uncheckedUnwrapped of nil optional")\n }\n}\n\nextension Optional where Wrapped: ~Copyable & ~Escapable {\n /// Takes the wrapped value being stored in this instance and returns it while\n /// also setting the instance to `nil`. If there is no value being stored in\n /// this instance, this returns `nil` instead.\n ///\n /// var numberOfShoes: Int? = 34\n ///\n /// if let numberOfShoes = numberOfShoes.take() {\n /// print(numberOfShoes)\n /// // Prints "34"\n /// }\n ///\n /// print(numberOfShoes)\n /// // Prints "nil"\n ///\n /// - Returns: The wrapped value being stored in this instance. If this\n /// instance is `nil`, returns `nil`.\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public mutating func take() -> Self {\n let result = consume self\n self = nil\n return result\n }\n}\n\n@_unavailableInEmbedded\nextension Optional: CustomDebugStringConvertible {\n /// A textual representation of this instance, suitable for debugging.\n public var debugDescription: String {\n switch self {\n case .some(let value):\n#if !SWIFT_STDLIB_STATIC_PRINT\n var result = "Optional("\n #if !$Embedded\n debugPrint(value, terminator: "", to: &result)\n #else\n _ = value\n "(cannot print value in embedded Swift)".write(to: &result)\n #endif\n result += ")"\n return result\n#else\n return "(optional printing not available)"\n#endif\n case .none:\n return "nil"\n }\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension Optional: CustomReflectable {\n public var customMirror: Mirror {\n switch self {\n case .some(let value):\n return Mirror(\n self,\n children: [ "some": value ],\n displayStyle: .optional)\n case .none:\n return Mirror(self, children: [:], displayStyle: .optional)\n }\n }\n}\n#endif\n\n@_transparent\npublic // COMPILER_INTRINSIC\nfunc _diagnoseUnexpectedNilOptional(\n _filenameStart: Builtin.RawPointer,\n _filenameLength: Builtin.Word,\n _filenameIsASCII: Builtin.Int1,\n _line: Builtin.Word,\n _isImplicitUnwrap: Builtin.Int1\n) {\n // Cannot use _preconditionFailure as the file and line info would not be\n // printed.\n if Bool(_isImplicitUnwrap) {\n _preconditionFailure(\n "Unexpectedly found nil while implicitly unwrapping an Optional value",\n file: StaticString(_start: _filenameStart,\n utf8CodeUnitCount: _filenameLength,\n isASCII: _filenameIsASCII),\n line: UInt(_line))\n } else {\n _preconditionFailure(\n "Unexpectedly found nil while unwrapping an Optional value",\n file: StaticString(_start: _filenameStart,\n utf8CodeUnitCount: _filenameLength,\n isASCII: _filenameIsASCII),\n line: UInt(_line))\n }\n}\n\nextension Optional: Equatable where Wrapped: Equatable {\n /// Returns a Boolean value indicating whether two optional instances are\n /// equal.\n ///\n /// Use this equal-to operator (`==`) to compare any two optional instances of\n /// a type that conforms to the `Equatable` protocol. The comparison returns\n /// `true` if both arguments are `nil` or if the two arguments wrap values\n /// that are equal. Conversely, the comparison returns `false` if only one of\n /// the arguments is `nil` or if the two arguments wrap values that are not\n /// equal.\n ///\n /// let group1 = [1, 2, 3, 4, 5]\n /// let group2 = [1, 3, 5, 7, 9]\n /// if group1.first == group2.first {\n /// print("The two groups start the same.")\n /// }\n /// // Prints "The two groups start the same."\n ///\n /// You can also use this operator to compare a non-optional value to an\n /// optional that wraps the same type. The non-optional value is wrapped as an\n /// optional before the comparison is made. In the following example, the\n /// `numberToMatch` constant is wrapped as an optional before comparing to the\n /// optional `numberFromString`:\n ///\n /// let numberToMatch: Int = 23\n /// let numberFromString: Int? = Int("23") // Optional(23)\n /// if numberToMatch == numberFromString {\n /// print("It's a match!")\n /// }\n /// // Prints "It's a match!"\n ///\n /// An instance that is expressed as a literal can also be used with this\n /// operator. In the next example, an integer literal is compared with the\n /// optional integer `numberFromString`. The literal `23` is inferred as an\n /// `Int` instance and then wrapped as an optional before the comparison is\n /// performed.\n ///\n /// if 23 == numberFromString {\n /// print("It's a match!")\n /// }\n /// // Prints "It's a match!"\n ///\n /// - Parameters:\n /// - lhs: An optional value to compare.\n /// - rhs: Another optional value to compare.\n @_transparent\n public static func ==(lhs: Wrapped?, rhs: Wrapped?) -> Bool {\n switch (lhs, rhs) {\n case let (l?, r?):\n return l == r\n case (nil, nil):\n return true\n default:\n return false\n }\n }\n}\n\nextension Optional: Hashable where Wrapped: 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 .none:\n hasher.combine(0 as UInt8)\n case .some(let wrapped):\n hasher.combine(1 as UInt8)\n hasher.combine(wrapped)\n }\n }\n}\n\n// Enable pattern matching against the nil literal, even if the element type\n// isn't equatable.\n@frozen\npublic struct _OptionalNilComparisonType: ExpressibleByNilLiteral {\n /// Create an instance initialized with `nil`.\n @_transparent\n public init(nilLiteral: ()) {\n }\n}\n\nextension Optional where Wrapped: ~Copyable & ~Escapable {\n /// Returns a Boolean value indicating whether an argument matches `nil`.\n ///\n /// You can use the pattern-matching operator (`~=`) to test whether an\n /// optional instance is `nil` even when the wrapped value's type does not\n /// conform to the `Equatable` protocol. The pattern-matching operator is used\n /// internally in `case` statements for pattern matching.\n ///\n /// The following example declares the `stream` variable as an optional\n /// instance of a hypothetical `DataStream` type, and then uses a `switch`\n /// statement to determine whether the stream is `nil` or has a configured\n /// value. When evaluating the `nil` case of the `switch` statement, this\n /// operator is called behind the scenes.\n ///\n /// var stream: DataStream? = nil\n /// switch stream {\n /// case nil:\n /// print("No data stream is configured.")\n /// case let x?:\n /// print("The data stream has \(x.availableBytes) bytes available.")\n /// }\n /// // Prints "No data stream is configured."\n ///\n /// - Note: To test whether an instance is `nil` in an `if` statement, use the\n /// equal-to operator (`==`) instead of the pattern-matching operator. The\n /// pattern-matching operator is primarily intended to enable `case`\n /// statement pattern matching.\n ///\n /// - Parameters:\n /// - lhs: A `nil` literal.\n /// - rhs: A value to match against `nil`.\n @_transparent\n @_preInverseGenerics\n public static func ~=(\n lhs: _OptionalNilComparisonType,\n rhs: borrowing Wrapped?\n ) -> Bool {\n switch rhs {\n case .some:\n return false\n case .none:\n return true\n }\n }\n\n // Enable equality comparisons against the nil literal, even if the\n // element type isn't equatable\n\n /// Returns a Boolean value indicating whether the left-hand-side argument is\n /// `nil`.\n ///\n /// You can use this equal-to operator (`==`) to test whether an optional\n /// instance is `nil` even when the wrapped value's type does not conform to\n /// the `Equatable` protocol.\n ///\n /// The following example declares the `stream` variable as an optional\n /// instance of a hypothetical `DataStream` type. Although `DataStream` is not\n /// an `Equatable` type, this operator allows checking whether `stream` is\n /// `nil`.\n ///\n /// var stream: DataStream? = nil\n /// if stream == nil {\n /// print("No data stream is configured.")\n /// }\n /// // Prints "No data stream is configured."\n ///\n /// - Parameters:\n /// - lhs: A value to compare to `nil`.\n /// - rhs: A `nil` literal.\n @_transparent\n @_preInverseGenerics\n public static func ==(\n lhs: borrowing Wrapped?,\n rhs: _OptionalNilComparisonType\n ) -> Bool {\n switch lhs {\n case .some:\n return false\n case .none:\n return true\n }\n }\n\n /// Returns a Boolean value indicating whether the left-hand-side argument is\n /// not `nil`.\n ///\n /// You can use this not-equal-to operator (`!=`) to test whether an optional\n /// instance is not `nil` even when the wrapped value's type does not conform\n /// to the `Equatable` protocol.\n ///\n /// The following example declares the `stream` variable as an optional\n /// instance of a hypothetical `DataStream` type. Although `DataStream` is not\n /// an `Equatable` type, this operator allows checking whether `stream` wraps\n /// a value and is therefore not `nil`.\n ///\n /// var stream: DataStream? = fetchDataStream()\n /// if stream != nil {\n /// print("The data stream has been configured.")\n /// }\n /// // Prints "The data stream has been configured."\n ///\n /// - Parameters:\n /// - lhs: A value to compare to `nil`.\n /// - rhs: A `nil` literal.\n @_transparent\n @_preInverseGenerics\n public static func !=(\n lhs: borrowing Wrapped?,\n rhs: _OptionalNilComparisonType\n ) -> Bool {\n switch lhs {\n case .some:\n return true\n case .none:\n return false\n }\n }\n\n /// Returns a Boolean value indicating whether the right-hand-side argument is\n /// `nil`.\n ///\n /// You can use this equal-to operator (`==`) to test whether an optional\n /// instance is `nil` even when the wrapped value's type does not conform to\n /// the `Equatable` protocol.\n ///\n /// The following example declares the `stream` variable as an optional\n /// instance of a hypothetical `DataStream` type. Although `DataStream` is not\n /// an `Equatable` type, this operator allows checking whether `stream` is\n /// `nil`.\n ///\n /// var stream: DataStream? = nil\n /// if nil == stream {\n /// print("No data stream is configured.")\n /// }\n /// // Prints "No data stream is configured."\n ///\n /// - Parameters:\n /// - lhs: A `nil` literal.\n /// - rhs: A value to compare to `nil`.\n @_transparent\n @_preInverseGenerics\n public static func ==(\n lhs: _OptionalNilComparisonType,\n rhs: borrowing Wrapped?\n ) -> Bool {\n switch rhs {\n case .some:\n return false\n case .none:\n return true\n }\n }\n\n /// Returns a Boolean value indicating whether the right-hand-side argument is\n /// not `nil`.\n ///\n /// You can use this not-equal-to operator (`!=`) to test whether an optional\n /// instance is not `nil` even when the wrapped value's type does not conform\n /// to the `Equatable` protocol.\n ///\n /// The following example declares the `stream` variable as an optional\n /// instance of a hypothetical `DataStream` type. Although `DataStream` is not\n /// an `Equatable` type, this operator allows checking whether `stream` wraps\n /// a value and is therefore not `nil`.\n ///\n /// var stream: DataStream? = fetchDataStream()\n /// if nil != stream {\n /// print("The data stream has been configured.")\n /// }\n /// // Prints "The data stream has been configured."\n ///\n /// - Parameters:\n /// - lhs: A `nil` literal.\n /// - rhs: A value to compare to `nil`.\n @_transparent\n @_preInverseGenerics\n public static func !=(\n lhs: _OptionalNilComparisonType,\n rhs: borrowing Wrapped?\n ) -> Bool {\n switch rhs {\n case .some:\n return true\n case .none:\n return false\n }\n }\n}\n\n/// Performs a nil-coalescing operation, returning the wrapped value of an\n/// `Optional` instance or a default value.\n///\n/// A nil-coalescing operation unwraps the left-hand side if it has a value, or\n/// it returns the right-hand side as a default. The result of this operation\n/// will have the non-optional type of the left-hand side's `Wrapped` type.\n///\n/// This operator uses short-circuit evaluation: `optional` is checked first,\n/// and `defaultValue` is evaluated only if `optional` is `nil`. For example:\n///\n/// func getDefault() -> Int {\n/// print("Calculating default...")\n/// return 42\n/// }\n///\n/// let goodNumber = Int("100") ?? getDefault()\n/// // goodNumber == 100\n///\n/// let notSoGoodNumber = Int("invalid-input") ?? getDefault()\n/// // Prints "Calculating default..."\n/// // notSoGoodNumber == 42\n///\n/// In this example, `goodNumber` is assigned a value of `100` because\n/// `Int("100")` succeeded in returning a non-`nil` result. When\n/// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns\n/// `nil`, and so the `getDefault()` method is called to supply a default\n/// value.\n///\n/// - Parameters:\n/// - optional: An optional value.\n/// - defaultValue: A value to use as a default. `defaultValue` is the same\n/// type as the `Wrapped` type of `optional`.\n@_transparent\n@_alwaysEmitIntoClient\npublic func ?? <T: ~Copyable>(\n optional: consuming T?,\n defaultValue: @autoclosure () throws -> T // FIXME: typed throws\n) rethrows -> T {\n // FIXME: We want this to support nonescapable `T` types.\n // To implement that, we need to be able to express that the result's lifetime\n // is limited to the intersection of `optional` and the result of\n // `defaultValue`:\n // @lifetime(optional, defaultValue.result)\n switch consume optional {\n case .some(let value):\n return value\n case .none:\n return try defaultValue()\n }\n}\n\n@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n@_silgen_name("$ss2qqoiyxxSg_xyKXKtKlF")\n@usableFromInline\ninternal func _legacy_abi_optionalNilCoalescingOperator <T>(\n optional: T?,\n defaultValue: @autoclosure () throws -> T\n) rethrows -> T {\n switch optional {\n case .some(let value):\n return value\n case .none:\n return try defaultValue()\n }\n}\n\n/// Performs a nil-coalescing operation, returning the wrapped value of an\n/// `Optional` instance or a default `Optional` value.\n///\n/// A nil-coalescing operation unwraps the left-hand side if it has a value, or\n/// returns the right-hand side as a default. The result of this operation\n/// will be the same type as its arguments.\n///\n/// This operator uses short-circuit evaluation: `optional` is checked first,\n/// and `defaultValue` is evaluated only if `optional` is `nil`. For example:\n///\n/// let goodNumber = Int("100") ?? Int("42")\n/// print(goodNumber)\n/// // Prints "Optional(100)"\n///\n/// let notSoGoodNumber = Int("invalid-input") ?? Int("42")\n/// print(notSoGoodNumber)\n/// // Prints "Optional(42)"\n///\n/// In this example, `goodNumber` is assigned a value of `100` because\n/// `Int("100")` succeeds in returning a non-`nil` result. When\n/// `notSoGoodNumber` is initialized, `Int("invalid-input")` fails and returns\n/// `nil`, and so `Int("42")` is called to supply a default value.\n///\n/// Because the result of this nil-coalescing operation is itself an optional\n/// value, you can chain default values by using `??` multiple times. The\n/// first optional value that isn't `nil` stops the chain and becomes the\n/// result of the whole expression. The next example tries to find the correct\n/// text for a greeting in two separate dictionaries before falling back to a\n/// static default.\n///\n/// let greeting = userPrefs[greetingKey] ??\n/// defaults[greetingKey] ?? "Greetings!"\n///\n/// If `userPrefs[greetingKey]` has a value, that value is assigned to\n/// `greeting`. If not, any value in `defaults[greetingKey]` will succeed, and\n/// if not that, `greeting` will be set to the non-optional default value,\n/// `"Greetings!"`.\n///\n/// - Parameters:\n/// - optional: An optional value.\n/// - defaultValue: A value to use as a default. `defaultValue` and\n/// `optional` have the same type.\n@_transparent\n@_alwaysEmitIntoClient\npublic func ?? <T: ~Copyable>(\n optional: consuming T?,\n defaultValue: @autoclosure () throws -> T? // FIXME: typed throws\n) rethrows -> T? {\n // FIXME: We want this to support nonescapable `T` types.\n // To implement that, we need to be able to express that the result's lifetime\n // is limited to the intersection of `optional` and the result of\n // `defaultValue`:\n // @lifetime(optional, defaultValue.result)\n switch consume optional {\n case .some(let value):\n return value\n case .none:\n return try defaultValue()\n }\n}\n\n@_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n@usableFromInline\ninternal func ?? <T>(\n optional: T?,\n defaultValue: @autoclosure () throws -> T?\n) rethrows -> T? {\n switch optional {\n case .some(let value):\n return value\n case .none:\n return try defaultValue()\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Bridging\n//===----------------------------------------------------------------------===//\n\n#if _runtime(_ObjC)\nextension Optional: _ObjectiveCBridgeable {\n // The object that represents `none` for an Optional of this type.\n internal static var _nilSentinel: AnyObject {\n @_silgen_name("_swift_Foundation_getOptionalNilSentinelObject")\n get\n }\n\n public func _bridgeToObjectiveC() -> AnyObject {\n // Bridge a wrapped value by unwrapping.\n if let value = self {\n return _bridgeAnythingToObjectiveC(value)\n }\n // Bridge nil using a sentinel.\n return type(of: self)._nilSentinel\n }\n\n public static func _forceBridgeFromObjectiveC(\n _ source: AnyObject,\n result: inout Optional<Wrapped>?\n ) {\n // Map the nil sentinel back to .none.\n // NB that the signature of _forceBridgeFromObjectiveC adds another level\n // of optionality, so we need to wrap the immediate result of the conversion\n // in `.some`.\n if source === _nilSentinel {\n result = .some(.none)\n return\n }\n // Otherwise, force-bridge the underlying value.\n let unwrappedResult = source as! Wrapped\n result = .some(.some(unwrappedResult))\n }\n\n public static func _conditionallyBridgeFromObjectiveC(\n _ source: AnyObject,\n result: inout Optional<Wrapped>?\n ) -> Bool {\n // Map the nil sentinel back to .none.\n // NB that the signature of _forceBridgeFromObjectiveC adds another level\n // of optionality, so we need to wrap the immediate result of the conversion\n // in `.some` to indicate success of the bridging operation, with a nil\n // result.\n if source === _nilSentinel {\n result = .some(.none)\n return true\n }\n // Otherwise, try to bridge the underlying value.\n if let unwrappedResult = source as? Wrapped {\n result = .some(.some(unwrappedResult))\n return true\n } else {\n result = .none\n return false\n }\n }\n\n @_effects(readonly)\n public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)\n -> Optional<Wrapped> {\n if let nonnullSource = source {\n // Map the nil sentinel back to none.\n if nonnullSource === _nilSentinel {\n return .none\n } else {\n return .some(nonnullSource as! Wrapped)\n }\n } else {\n // If we unexpectedly got nil, just map it to `none` too.\n return .none\n }\n }\n}\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Optional.swift
cpp_apple_swift_stdlib_public_core_Optional.swift
Swift
33,867
0.95
0.096267
0.536008
node-utils
753
2024-09-22T07:32:10.694744
BSD-3-Clause
false
4de3923b6193538bda3b7dba5f42e425
//===--- OptionSet.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 type that presents a mathematical set interface to a bit set.\n///\n/// You use the `OptionSet` protocol to represent bitset types, where\n/// individual bits represent members of a set. Adopting this protocol in\n/// your custom types lets you perform set-related operations such as\n/// membership tests, unions, and intersections on those types. What's more,\n/// when implemented using specific criteria, adoption of this protocol\n/// requires no extra work on your part.\n///\n/// When creating an option set, include a `rawValue` property in your type\n/// declaration. For your type to automatically receive default implementations\n/// for set-related operations, the `rawValue` property must be of a type that\n/// conforms to the `FixedWidthInteger` protocol, such as `Int` or `UInt8`.\n/// Next, create unique options as static properties of your custom type using\n/// unique powers of two (1, 2, 4, 8, 16, and so forth) for each individual\n/// property's raw value so that each property can be represented by a single\n/// bit of the type's raw value.\n///\n/// For example, consider a custom type called `ShippingOptions` that is an\n/// option set of the possible ways to ship a customer's purchase.\n/// `ShippingOptions` includes a `rawValue` property of type `Int` that stores\n/// the bit mask of available shipping options. The static members `nextDay`,\n/// `secondDay`, `priority`, and `standard` are unique, individual options.\n///\n/// struct ShippingOptions: OptionSet {\n/// let rawValue: Int\n///\n/// static let nextDay = ShippingOptions(rawValue: 1 << 0)\n/// static let secondDay = ShippingOptions(rawValue: 1 << 1)\n/// static let priority = ShippingOptions(rawValue: 1 << 2)\n/// static let standard = ShippingOptions(rawValue: 1 << 3)\n///\n/// static let express: ShippingOptions = [.nextDay, .secondDay]\n/// static let all: ShippingOptions = [.express, .priority, .standard]\n/// }\n///\n/// Declare additional preconfigured option set values as static properties\n/// initialized with an array literal containing other option values. In the\n/// example, because the `express` static property is assigned an array\n/// literal with the `nextDay` and `secondDay` options, it will contain those\n/// two elements.\n///\n/// Using an Option Set Type\n/// ========================\n///\n/// When you need to create an instance of an option set, assign one of the\n/// type's static members to your variable or constant. Alternatively, to\n/// create an option set instance with multiple members, assign an array\n/// literal with multiple static members of the option set. To create an empty\n/// instance, assign an empty array literal to your variable.\n///\n/// let singleOption: ShippingOptions = .priority\n/// let multipleOptions: ShippingOptions = [.nextDay, .secondDay, .priority]\n/// let noOptions: ShippingOptions = []\n///\n/// Use set-related operations to check for membership and to add or remove\n/// members from an instance of your custom option set type. The following\n/// example shows how you can determine free shipping options based on a\n/// customer's purchase price:\n///\n/// let purchasePrice = 87.55\n///\n/// var freeOptions: ShippingOptions = []\n/// if purchasePrice > 50 {\n/// freeOptions.insert(.priority)\n/// }\n///\n/// if freeOptions.contains(.priority) {\n/// print("You've earned free priority shipping!")\n/// } else {\n/// print("Add more to your cart for free priority shipping!")\n/// }\n/// // Prints "You've earned free priority shipping!"\npublic protocol OptionSet: SetAlgebra, RawRepresentable {\n // We can't constrain the associated Element type to be the same as\n // Self, but we can do almost as well with a default and a\n // constrained extension\n \n /// The element type of the option set.\n ///\n /// To inherit all the default implementations from the `OptionSet` protocol,\n /// the `Element` type must be `Self`, the default.\n associatedtype Element = Self\n\n // FIXME: This initializer should just be the failable init from\n // RawRepresentable. Unfortunately, current language limitations\n // that prevent non-failable initializers from forwarding to\n // failable ones would prevent us from generating the non-failing\n // default (zero-argument) initializer. Since OptionSet's main\n // purpose is to create convenient conformances to SetAlgebra,\n // we opt for a non-failable initializer.\n \n /// Creates a new option set from the given raw value.\n ///\n /// This initializer always succeeds, even if the value passed as `rawValue`\n /// exceeds the static properties declared as part of the option set. This\n /// example creates an instance of `ShippingOptions` with a raw value beyond\n /// the highest element, with a bit mask that effectively contains all the\n /// declared static members.\n ///\n /// let extraOptions = ShippingOptions(rawValue: 255)\n /// print(extraOptions.isStrictSuperset(of: .all))\n /// // Prints "true"\n ///\n /// - Parameter rawValue: The raw value of the option set to create. Each bit\n /// of `rawValue` potentially represents an element of the option set,\n /// though raw values may include bits that are not defined as distinct\n /// values of the `OptionSet` type.\n init(rawValue: RawValue)\n}\n\n/// `OptionSet` requirements for which default implementations\n/// are supplied.\n///\n/// - Note: A type conforming to `OptionSet` can implement any of\n/// these initializers or methods, and those implementations will be\n/// used in lieu of these defaults.\nextension OptionSet {\n /// Returns a new option set of the elements contained in this set, in the\n /// given set, or in both.\n ///\n /// This example uses the `union(_:)` method to add two more shipping options\n /// to the default set.\n ///\n /// let defaultShipping = ShippingOptions.standard\n /// let memberShipping = defaultShipping.union([.secondDay, .priority])\n /// print(memberShipping.contains(.priority))\n /// // Prints "true"\n ///\n /// - Parameter other: An option set.\n /// - Returns: A new option set made up of the elements contained in this\n /// set, in `other`, or in both.\n @inlinable // generic-performance\n public func union(_ other: Self) -> Self {\n var r: Self = Self(rawValue: self.rawValue)\n r.formUnion(other)\n return r\n }\n \n /// Returns a new option set with only the elements contained in both this\n /// set and the given set.\n ///\n /// This example uses the `intersection(_:)` method to limit the available\n /// shipping options to what can be used with a PO Box destination.\n ///\n /// // Can only ship standard or priority to PO Boxes\n /// let poboxShipping: ShippingOptions = [.standard, .priority]\n /// let memberShipping: ShippingOptions =\n /// [.standard, .priority, .secondDay]\n ///\n /// let availableOptions = memberShipping.intersection(poboxShipping)\n /// print(availableOptions.contains(.priority))\n /// // Prints "true"\n /// print(availableOptions.contains(.secondDay))\n /// // Prints "false"\n ///\n /// - Parameter other: An option set.\n /// - Returns: A new option set with only the elements contained in both this\n /// set and `other`.\n @inlinable // generic-performance\n public func intersection(_ other: Self) -> Self {\n var r = Self(rawValue: self.rawValue)\n r.formIntersection(other)\n return r\n }\n \n /// Returns a new option set with the elements contained in this set or in\n /// the given set, but not in both.\n ///\n /// - Parameter other: An option set.\n /// - Returns: A new option set with only the elements contained in either\n /// this set or `other`, but not in both.\n @inlinable // generic-performance\n public func symmetricDifference(_ other: Self) -> Self {\n var r = Self(rawValue: self.rawValue)\n r.formSymmetricDifference(other)\n return r\n }\n}\n\n/// `OptionSet` requirements for which default implementations are\n/// supplied when `Element == Self`, which is the default.\n///\n/// - Note: A type conforming to `OptionSet` can implement any of\n/// these initializers or methods, and those implementations will be\n/// used in lieu of these defaults.\nextension OptionSet where Element == Self {\n /// Returns a Boolean value that indicates whether a given element is a\n /// member of the option set.\n ///\n /// This example uses the `contains(_:)` method to check whether next-day\n /// shipping is in the `availableOptions` instance.\n ///\n /// let availableOptions = ShippingOptions.express\n /// if availableOptions.contains(.nextDay) {\n /// print("Next day shipping available")\n /// }\n /// // Prints "Next day shipping available"\n ///\n /// - Parameter member: The element to look for in the option set.\n /// - Returns: `true` if the option set contains `member`; otherwise,\n /// `false`.\n @inlinable // generic-performance\n public func contains(_ member: Self) -> Bool {\n return self.isSuperset(of: member)\n }\n \n /// Adds the given element to the option set if it is not already a member.\n ///\n /// In the following example, the `.secondDay` shipping option is added to\n /// the `freeOptions` option set if `purchasePrice` is greater than 50.0. For\n /// the `ShippingOptions` declaration, see the `OptionSet` protocol\n /// discussion.\n ///\n /// let purchasePrice = 87.55\n ///\n /// var freeOptions: ShippingOptions = [.standard, .priority]\n /// if purchasePrice > 50 {\n /// freeOptions.insert(.secondDay)\n /// }\n /// print(freeOptions.contains(.secondDay))\n /// // Prints "true"\n ///\n /// - Parameter newMember: The element to insert.\n /// - Returns: `(true, newMember)` if `newMember` was not contained in\n /// `self`. Otherwise, returns `(false, oldMember)`, where `oldMember` is\n /// the member of the set equal to `newMember`.\n @inlinable // generic-performance\n @discardableResult\n public mutating func insert(\n _ newMember: Element\n ) -> (inserted: Bool, memberAfterInsert: Element) {\n let oldMember = self.intersection(newMember)\n let shouldInsert = oldMember != newMember\n let result = (\n inserted: shouldInsert,\n memberAfterInsert: shouldInsert ? newMember : oldMember)\n if shouldInsert {\n self.formUnion(newMember)\n }\n return result\n }\n \n /// Removes the given element and all elements subsumed by it.\n ///\n /// In the following example, the `.priority` shipping option is removed from\n /// the `options` option set. Attempting to remove the same shipping option\n /// a second time results in `nil`, because `options` no longer contains\n /// `.priority` as a member.\n ///\n /// var options: ShippingOptions = [.secondDay, .priority]\n /// let priorityOption = options.remove(.priority)\n /// print(priorityOption == .priority)\n /// // Prints "true"\n ///\n /// print(options.remove(.priority))\n /// // Prints "nil"\n ///\n /// In the next example, the `.express` element is passed to `remove(_:)`.\n /// Although `.express` is not a member of `options`, `.express` subsumes\n /// the remaining `.secondDay` element of the option set. Therefore,\n /// `options` is emptied and the intersection between `.express` and\n /// `options` is returned.\n ///\n /// let expressOption = options.remove(.express)\n /// print(expressOption == .express)\n /// // Prints "false"\n /// print(expressOption == .secondDay)\n /// // Prints "true"\n ///\n /// - Parameter member: The element of the set to remove.\n /// - Returns: The intersection of `[member]` and the set, if the\n /// intersection was nonempty; otherwise, `nil`.\n @inlinable // generic-performance\n @discardableResult\n public mutating func remove(_ member: Element) -> Element? {\n let intersectionElements = intersection(member)\n guard !intersectionElements.isEmpty else {\n return nil\n }\n \n self.subtract(member)\n return intersectionElements\n }\n\n /// Inserts the given element into the set.\n ///\n /// If `newMember` is not contained in the set but subsumes current members\n /// of the set, the subsumed members are returned.\n ///\n /// var options: ShippingOptions = [.secondDay, .priority]\n /// let replaced = options.update(with: .express)\n /// print(replaced == .secondDay)\n /// // Prints "true"\n ///\n /// - Returns: The intersection of `[newMember]` and the set if the\n /// intersection was nonempty; otherwise, `nil`.\n @inlinable // generic-performance\n @discardableResult\n public mutating func update(with newMember: Element) -> Element? {\n let r = self.intersection(newMember)\n self.formUnion(newMember)\n return r.isEmpty ? nil : r\n }\n}\n\n/// `OptionSet` requirements for which default implementations are\n/// supplied when `RawValue` conforms to `FixedWidthInteger`,\n/// which is the usual case. Each distinct bit of an option set's\n/// `.rawValue` corresponds to a disjoint value of the `OptionSet`.\n///\n/// - `union` is implemented as a bitwise "or" (`|`) of `rawValue`s\n/// - `intersection` is implemented as a bitwise "and" (`&`) of\n/// `rawValue`s\n/// - `symmetricDifference` is implemented as a bitwise "exclusive or"\n/// (`^`) of `rawValue`s\n///\n/// - Note: A type conforming to `OptionSet` can implement any of\n/// these initializers or methods, and those implementations will be\n/// used in lieu of these defaults.\nextension OptionSet where RawValue: FixedWidthInteger {\n /// Creates an empty option set.\n ///\n /// This initializer creates an option set with a raw value of zero.\n @inlinable // generic-performance\n public init() {\n self.init(rawValue: 0)\n }\n\n /// Inserts the elements of another set into this option set.\n ///\n /// This method is implemented as a `|` (bitwise OR) operation on the\n /// two sets' raw values.\n ///\n /// - Parameter other: An option set.\n @inlinable // generic-performance\n public mutating func formUnion(_ other: Self) {\n self = Self(rawValue: self.rawValue | other.rawValue)\n }\n \n /// Removes all elements of this option set that are not \n /// also present in the given set.\n ///\n /// This method is implemented as a `&` (bitwise AND) operation on the\n /// two sets' raw values.\n ///\n /// - Parameter other: An option set.\n @inlinable // generic-performance\n public mutating func formIntersection(_ other: Self) {\n self = Self(rawValue: self.rawValue & other.rawValue)\n }\n \n /// Replaces this set with a new set containing all elements \n /// contained in either this set or the given set, but not in both.\n ///\n /// This method is implemented as a `^` (bitwise XOR) operation on the two\n /// sets' raw values.\n ///\n /// - Parameter other: An option set.\n @inlinable // generic-performance\n public mutating func formSymmetricDifference(_ other: Self) {\n self = Self(rawValue: self.rawValue ^ other.rawValue)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_OptionSet.swift
cpp_apple_swift_stdlib_public_core_OptionSet.swift
Swift
15,462
0.95
0.06117
0.777778
node-utils
236
2024-06-06T02:14:06.177384
BSD-3-Clause
false
791872e21316857b09efe2478f715915
//===----------------------------------------------------------------------===//\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//===----------------------------------------------------------------------===//\n// Input/Output interfaces\n//===----------------------------------------------------------------------===//\n\n/// A type that can be the target of text-streaming operations.\n///\n/// You can send the output of the standard library's `print(_:to:)` and\n/// `dump(_:to:)` functions to an instance of a type that conforms to the\n/// `TextOutputStream` protocol instead of to standard output. Swift's\n/// `String` type conforms to `TextOutputStream` already, so you can capture\n/// the output from `print(_:to:)` and `dump(_:to:)` in a string instead of\n/// logging it to standard output.\n///\n/// var s = ""\n/// for n in 1...5 {\n/// print(n, terminator: "", to: &s)\n/// }\n/// // s == "12345"\n///\n/// Conforming to the TextOutputStream Protocol\n/// ===========================================\n///\n/// To make your custom type conform to the `TextOutputStream` protocol,\n/// implement the required `write(_:)` method. Functions that use a\n/// `TextOutputStream` target may call `write(_:)` multiple times per writing\n/// operation.\n///\n/// As an example, here's an implementation of an output stream that converts\n/// any input to its plain ASCII representation before sending it to standard\n/// output.\n///\n/// struct ASCIILogger: TextOutputStream {\n/// mutating func write(_ string: String) {\n/// let ascii = string.unicodeScalars.lazy.map { scalar in\n/// scalar == "\n"\n/// ? "\n"\n/// : scalar.escaped(asASCII: true)\n/// }\n/// print(ascii.joined(separator: ""), terminator: "")\n/// }\n/// }\n///\n/// The `ASCIILogger` type's `write(_:)` method processes its string input by\n/// escaping each Unicode scalar, with the exception of `"\n"` line returns.\n/// By sending the output of the `print(_:to:)` function to an instance of\n/// `ASCIILogger`, you invoke its `write(_:)` method.\n///\n/// let s = "Hearts ♡ and Diamonds ♢"\n/// print(s)\n/// // Prints "Hearts ♡ and Diamonds ♢"\n///\n/// var asciiLogger = ASCIILogger()\n/// print(s, to: &asciiLogger)\n/// // Prints "Hearts \u{2661} and Diamonds \u{2662}"\npublic protocol TextOutputStream {\n mutating func _lock()\n mutating func _unlock()\n\n /// Appends the given string to the stream.\n mutating func write(_ string: String)\n\n mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>)\n}\n\nextension TextOutputStream {\n public mutating func _lock() {}\n public mutating func _unlock() {}\n\n public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) {\n unsafe write(String._fromASCII(buffer))\n }\n}\n\n/// A source of text-streaming operations.\n///\n/// Instances of types that conform to the `TextOutputStreamable` protocol can\n/// write their value to instances of any type that conforms to the\n/// `TextOutputStream` protocol. The Swift standard library's text-related\n/// types, `String`, `Character`, and `Unicode.Scalar`, all conform to\n/// `TextOutputStreamable`.\n///\n/// Conforming to the TextOutputStreamable Protocol\n/// =====================================\n///\n/// To add `TextOutputStreamable` conformance to a custom type, implement the\n/// required `write(to:)` method. Call the given output stream's `write(_:)`\n/// method in your implementation.\npublic protocol TextOutputStreamable {\n /// Writes a textual representation of this instance into the given output\n /// stream.\n func write<Target: TextOutputStream>(to target: inout Target)\n}\n\n/// A type with a customized textual representation.\n///\n/// Types that conform to the `CustomStringConvertible` protocol can provide\n/// their own representation to be used when converting an instance to a\n/// string. The `String(describing:)` initializer is the preferred way to\n/// convert an instance of *any* type to a string. If the passed instance\n/// conforms to `CustomStringConvertible`, the `String(describing:)`\n/// initializer and the `print(_:)` function use the instance's custom\n/// `description` property.\n///\n/// Accessing a type's `description` property directly or using\n/// `CustomStringConvertible` as a generic constraint is discouraged.\n///\n/// Conforming to the CustomStringConvertible Protocol\n/// ==================================================\n///\n/// Add `CustomStringConvertible` conformance to your custom types by defining\n/// a `description` property.\n///\n/// For example, this custom `Point` struct uses the default representation\n/// supplied by the standard library:\n///\n/// struct Point {\n/// let x: Int, y: Int\n/// }\n///\n/// let p = Point(x: 21, y: 30)\n/// print(p)\n/// // Prints "Point(x: 21, y: 30)"\n///\n/// After implementing the `description` property and declaring\n/// `CustomStringConvertible` conformance, the `Point` type provides its own\n/// custom representation.\n///\n/// extension Point: CustomStringConvertible {\n/// var description: String {\n/// return "(\(x), \(y))"\n/// }\n/// }\n///\n/// print(p)\n/// // Prints "(21, 30)"\npublic protocol CustomStringConvertible {\n /// A textual representation of this instance.\n ///\n /// Calling this property directly is discouraged. Instead, convert an\n /// instance of any type to a string by using the `String(describing:)`\n /// initializer. This initializer works with any type, and uses the custom\n /// `description` property for types that conform to\n /// `CustomStringConvertible`:\n ///\n /// struct Point: CustomStringConvertible {\n /// let x: Int, y: Int\n ///\n /// var description: String {\n /// return "(\(x), \(y))"\n /// }\n /// }\n ///\n /// let p = Point(x: 21, y: 30)\n /// let s = String(describing: p)\n /// print(s)\n /// // Prints "(21, 30)"\n ///\n /// The conversion of `p` to a string in the assignment to `s` uses the\n /// `Point` type's `description` property.\n var description: String { get }\n}\n\n/// A type that can be represented as a string in a lossless, unambiguous way.\n///\n/// For example, the integer value 1050 can be represented in its entirety as\n/// the string "1050".\n///\n/// The description property of a conforming type must be a value-preserving\n/// representation of the original value. As such, it should be possible to\n/// re-create an instance from its string representation.\npublic protocol LosslessStringConvertible: CustomStringConvertible {\n /// Instantiates an instance of the conforming type from a string\n /// representation.\n init?(_ description: String)\n}\n\n/// A type with a customized textual representation suitable for debugging\n/// purposes.\n///\n/// Swift provides a default debugging textual representation for any type.\n/// That default representation is used by the `String(reflecting:)`\n/// initializer and the `debugPrint(_:)` function for types that don't provide\n/// their own. To customize that representation, make your type conform to the\n/// `CustomDebugStringConvertible` protocol.\n///\n/// Because the `String(reflecting:)` initializer works for instances of *any*\n/// type, returning an instance's `debugDescription` if the value passed\n/// conforms to `CustomDebugStringConvertible`, accessing a type's\n/// `debugDescription` property directly or using\n/// `CustomDebugStringConvertible` as a generic constraint is discouraged.\n///\n/// - Note: Calling the `dump(_:_:_:_:)` function and printing in the debugger\n/// uses both `String(reflecting:)` and `Mirror(reflecting:)` to collect\n/// information about an instance. If you implement\n/// `CustomDebugStringConvertible` conformance for your custom type, you may\n/// want to consider providing a custom mirror by implementing\n/// `CustomReflectable` conformance, as well.\n///\n/// Conforming to the CustomDebugStringConvertible Protocol\n/// =======================================================\n///\n/// Add `CustomDebugStringConvertible` conformance to your custom types by\n/// defining a `debugDescription` property.\n///\n/// For example, this custom `Point` struct uses the default representation\n/// supplied by the standard library:\n///\n/// struct Point {\n/// let x: Int, y: Int\n/// }\n///\n/// let p = Point(x: 21, y: 30)\n/// print(String(reflecting: p))\n/// // Prints "Point(x: 21, y: 30)"\n///\n/// After adding `CustomDebugStringConvertible` conformance by implementing the\n/// `debugDescription` property, `Point` provides its own custom debugging\n/// representation.\n///\n/// extension Point: CustomDebugStringConvertible {\n/// var debugDescription: String {\n/// return "(\(x), \(y))"\n/// }\n/// }\n///\n/// print(String(reflecting: p))\n/// // Prints "(21, 30)"\npublic protocol CustomDebugStringConvertible {\n /// A textual representation of this instance, suitable for debugging.\n ///\n /// Calling this property directly is discouraged. Instead, convert an\n /// instance of any type to a string by using the `String(reflecting:)`\n /// initializer. This initializer works with any type, and uses the custom\n /// `debugDescription` property for types that conform to\n /// `CustomDebugStringConvertible`:\n ///\n /// struct Point: CustomDebugStringConvertible {\n /// let x: Int, y: Int\n ///\n /// var debugDescription: String {\n /// return "(\(x), \(y))"\n /// }\n /// }\n ///\n /// let p = Point(x: 21, y: 30)\n /// let s = String(reflecting: p)\n /// print(s)\n /// // Prints "(21, 30)"\n ///\n /// The conversion of `p` to a string in the assignment to `s` uses the\n /// `Point` type's `debugDescription` property.\n var debugDescription: String { get }\n}\n\n//===----------------------------------------------------------------------===//\n// Default (ad-hoc) printing\n//===----------------------------------------------------------------------===//\n\n@_silgen_name("swift_EnumCaseName")\ninternal func _getEnumCaseName<T>(_ value: T) -> UnsafePointer<CChar>?\n\n@_silgen_name("swift_OpaqueSummary")\ninternal func _opaqueSummary(_ metadata: Any.Type) -> UnsafePointer<CChar>?\n\n/// Obtain a fallback raw value for an enum type without metadata; this\n/// should be OK for enums from C/C++ until they have metadata (see\n/// <rdar://22036374>). Note that if this turns out to be a Swift Enum\n/// with missing metadata, the raw value may be misleading.\n@_semantics("optimize.sil.specialize.generic.never")\ninternal func _fallbackEnumRawValue<T>(_ value: T) -> Int64? {\n switch MemoryLayout.size(ofValue: value) {\n case 8:\n return unsafe unsafeBitCast(value, to:Int64.self)\n case 4:\n return unsafe Int64(unsafeBitCast(value, to:Int32.self))\n case 2:\n return unsafe Int64(unsafeBitCast(value, to:Int16.self))\n case 1:\n return unsafe Int64(unsafeBitCast(value, to:Int8.self))\n default:\n return nil\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\n/// Do our best to print a value that cannot be printed directly.\n@_semantics("optimize.sil.specialize.generic.never")\ninternal func _adHocPrint_unlocked<T, TargetStream: TextOutputStream>(\n _ value: T, _ mirror: Mirror, _ target: inout TargetStream,\n isDebugPrint: Bool\n) {\n func printTypeName(_ type: Any.Type) {\n // Print type names without qualification, unless we're debugPrint'ing.\n target.write(_typeName(type, qualified: isDebugPrint))\n }\n\n if let displayStyle = mirror.displayStyle {\n switch displayStyle {\n case .optional:\n if let child = mirror.children.first {\n _debugPrint_unlocked(child.1, &target)\n } else {\n _debugPrint_unlocked("nil", &target)\n }\n case .tuple:\n target.write("(")\n var first = true\n for (label, value) in mirror.children {\n if first {\n first = false\n } else {\n target.write(", ")\n }\n\n if let label = label {\n if !label.isEmpty && label[label.startIndex] != "." {\n target.write(label)\n target.write(": ")\n }\n }\n\n _debugPrint_unlocked(value, &target)\n }\n target.write(")")\n case .struct:\n printTypeName(mirror.subjectType)\n target.write("(")\n var first = true\n for (label, value) in mirror.children {\n if let label = label {\n if first {\n first = false\n } else {\n target.write(", ")\n }\n target.write(label)\n target.write(": ")\n _debugPrint_unlocked(value, &target)\n }\n }\n target.write(")")\n case .enum:\n if let cString = unsafe _getEnumCaseName(value),\n let caseName = unsafe String(validatingCString: cString) {\n // Write the qualified type name in debugPrint.\n if isDebugPrint {\n printTypeName(mirror.subjectType)\n target.write(".")\n }\n target.write(caseName)\n } else {\n printTypeName(mirror.subjectType)\n // The case name is garbage; this might be a C/C++ enum without\n // metadata, so see if we can get a raw value\n if let rawValue = _fallbackEnumRawValue(value) {\n target.write("(rawValue: ")\n _debugPrint_unlocked(rawValue, &target);\n target.write(")")\n }\n }\n if let (_, value) = mirror.children.first {\n if Mirror(reflecting: value).displayStyle == .tuple {\n _debugPrint_unlocked(value, &target)\n } else {\n target.write("(")\n _debugPrint_unlocked(value, &target)\n target.write(")")\n }\n }\n default:\n target.write(_typeName(mirror.subjectType))\n }\n } else if let metatypeValue = value as? Any.Type {\n // Metatype\n printTypeName(metatypeValue)\n } else {\n // Fall back to the type or an opaque summary of the kind\n if let cString = unsafe _opaqueSummary(mirror.subjectType),\n let opaqueSummary = unsafe String(validatingCString: cString) {\n target.write(opaqueSummary)\n } else {\n target.write(_typeName(mirror.subjectType, qualified: true))\n }\n }\n}\n#endif\n\n@usableFromInline\n@_semantics("optimize.sil.specialize.generic.never")\n@_unavailableInEmbedded\ninternal func _print_unlocked<T, TargetStream: TextOutputStream>(\n _ value: T, _ target: inout TargetStream\n) {\n // Optional has no representation suitable for display; therefore,\n // values of optional type should be printed as a debug\n // string. Check for Optional first, before checking protocol\n // conformance below, because an Optional value is convertible to a\n // protocol if its wrapped type conforms to that protocol.\n // Note: _isOptional doesn't work here when T == Any, hence we\n // use a more elaborate formulation:\n if _openExistential(type(of: value as Any), do: _isOptional) {\n let debugPrintable = value as! CustomDebugStringConvertible\n debugPrintable.debugDescription.write(to: &target)\n return\n }\n\n if let string = value as? String {\n target.write(string)\n return\n }\n\n if case let streamableObject as TextOutputStreamable = value {\n streamableObject.write(to: &target)\n return\n }\n\n if case let printableObject as CustomStringConvertible = value {\n printableObject.description.write(to: &target)\n return\n }\n\n if case let debugPrintableObject as CustomDebugStringConvertible = value {\n debugPrintableObject.debugDescription.write(to: &target)\n return\n }\n\n#if SWIFT_ENABLE_REFLECTION\n let mirror = Mirror(reflecting: value)\n _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: false)\n#else\n target.write("(value cannot be printed without reflection)")\n#endif\n}\n\n//===----------------------------------------------------------------------===//\n// `debugPrint`\n//===----------------------------------------------------------------------===//\n\n@_semantics("optimize.sil.specialize.generic.never")\n@inline(never)\n@_unavailableInEmbedded\npublic func _debugPrint_unlocked<T, TargetStream: TextOutputStream>(\n _ value: T, _ target: inout TargetStream\n) {\n if let debugPrintableObject = value as? CustomDebugStringConvertible {\n debugPrintableObject.debugDescription.write(to: &target)\n return\n }\n\n if let printableObject = value as? CustomStringConvertible {\n printableObject.description.write(to: &target)\n return\n }\n\n if let streamableObject = value as? TextOutputStreamable {\n streamableObject.write(to: &target)\n return\n }\n\n#if SWIFT_ENABLE_REFLECTION\n let mirror = Mirror(reflecting: value)\n _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true)\n#else\n target.write("(value cannot be printed without reflection)")\n#endif\n}\n\n#if SWIFT_ENABLE_REFLECTION\n@_semantics("optimize.sil.specialize.generic.never")\ninternal func _dumpPrint_unlocked<T, TargetStream: TextOutputStream>(\n _ value: T, _ mirror: Mirror, _ target: inout TargetStream\n) {\n if let displayStyle = mirror.displayStyle {\n // Containers and tuples are always displayed in terms of their element\n // count\n switch displayStyle {\n case .tuple:\n let count = mirror.children.count\n target.write(count == 1 ? "(1 element)" : "(\(count) elements)")\n return\n case .collection:\n let count = mirror.children.count\n target.write(count == 1 ? "1 element" : "\(count) elements")\n return\n case .dictionary:\n let count = mirror.children.count\n target.write(count == 1 ? "1 key/value pair" : "\(count) key/value pairs")\n return\n case .`set`:\n let count = mirror.children.count\n target.write(count == 1 ? "1 member" : "\(count) members")\n return\n default:\n break\n }\n }\n\n if let debugPrintableObject = value as? CustomDebugStringConvertible {\n debugPrintableObject.debugDescription.write(to: &target)\n return\n }\n\n if let printableObject = value as? CustomStringConvertible {\n printableObject.description.write(to: &target)\n return\n }\n\n if let streamableObject = value as? TextOutputStreamable {\n streamableObject.write(to: &target)\n return\n }\n\n if let displayStyle = mirror.displayStyle {\n switch displayStyle {\n case .`class`, .`struct`:\n // Classes and structs without custom representations are displayed as\n // their fully qualified type name\n target.write(_typeName(mirror.subjectType, qualified: true))\n return\n case .`enum`:\n target.write(_typeName(mirror.subjectType, qualified: true))\n if let cString = unsafe _getEnumCaseName(value),\n let caseName = unsafe String(validatingCString: cString) {\n target.write(".")\n target.write(caseName)\n }\n return\n default:\n break\n }\n }\n\n _adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true)\n}\n#endif\n\n//===----------------------------------------------------------------------===//\n// OutputStreams\n//===----------------------------------------------------------------------===//\n\ninternal struct _Stdout: TextOutputStream {\n internal init() {}\n\n internal mutating func _lock() {\n _swift_stdlib_flockfile_stdout()\n }\n\n internal mutating func _unlock() {\n _swift_stdlib_funlockfile_stdout()\n }\n\n internal mutating func write(_ string: String) {\n if string.isEmpty { return }\n\n var string = string\n _ = string.withUTF8 { utf8 in\n unsafe _swift_stdlib_fwrite_stdout(utf8.baseAddress!, 1, utf8.count)\n }\n }\n}\n\nextension String: TextOutputStream {\n /// Appends the given string to this string.\n ///\n /// - Parameter other: A string to append.\n public mutating func write(_ other: String) {\n self += other\n }\n\n public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) {\n unsafe self._guts.append(_StringGuts(buffer, isASCII: true))\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Streamables\n//===----------------------------------------------------------------------===//\n\nextension String: TextOutputStreamable {\n /// Writes the string into the given output stream.\n ///\n /// - Parameter target: An output stream.\n @inlinable\n public func write<Target: TextOutputStream>(to target: inout Target) {\n target.write(self)\n }\n}\n\nextension Character: TextOutputStreamable {\n /// Writes the character into the given output stream.\n ///\n /// - Parameter target: An output stream.\n public func write<Target: TextOutputStream>(to target: inout Target) {\n target.write(String(self))\n }\n}\n\nextension Unicode.Scalar: TextOutputStreamable {\n /// Writes the textual representation of the Unicode scalar into the given\n /// output stream.\n ///\n /// - Parameter target: An output stream.\n public func write<Target: TextOutputStream>(to target: inout Target) {\n target.write(String(Character(self)))\n }\n}\n\n/// A hook for playgrounds to print through.\npublic var _playgroundPrintHook: ((String) -> Void)? = nil\n\ninternal struct _TeeStream<L: TextOutputStream, R: TextOutputStream>\n : TextOutputStream\n{\n internal var left: L\n internal var right: R\n\n internal init(left: L, right: R) {\n self.left = left\n self.right = right\n }\n /// Append the given `string` to this stream.\n internal mutating func write(_ string: String) {\n left.write(string); right.write(string)\n }\n\n internal mutating func _lock() { left._lock(); right._lock() }\n internal mutating func _unlock() { right._unlock(); left._unlock() }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_OutputStream.swift
cpp_apple_swift_stdlib_public_core_OutputStream.swift
Swift
21,994
0.95
0.099688
0.489831
node-utils
809
2025-03-14T16:07:56.096022
Apache-2.0
false
ec34ceb43646b710e94778bf93bb2e3f
//===--- PlaygroundDisplay.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 type that supplies a custom description for playground logging.\n///\n/// Playground logging can generate, at a minimum, a structured description\n/// of any type. If you want to provide a custom description of your type to be\n/// logged in place of the default description, conform to the\n/// `CustomPlaygroundDisplayConvertible` protocol.\n///\n/// Playground logging generates a richer, more specialized description of core\n/// types. For example, the contents of a `String` are logged, as are the\n/// components of an `NSColor` or `UIColor`. The current playground logging\n/// implementation logs specialized descriptions of at least the following\n/// types:\n///\n/// - `String` and `NSString`\n/// - `Int`, `UInt`, and the other standard library integer types\n/// - `Float` and `Double`\n/// - `Bool`\n/// - `Date` and `NSDate`\n/// - `NSAttributedString`\n/// - `NSNumber`\n/// - `NSRange`\n/// - `URL` and `NSURL`\n/// - `CGPoint`, `CGSize`, and `CGRect`\n/// - `NSColor`, `UIColor`, `CGColor`, and `CIColor`\n/// - `NSImage`, `UIImage`, `CGImage`, and `CIImage`\n/// - `NSBezierPath` and `UIBezierPath`\n/// - `NSView` and `UIView`\n///\n/// Playground logging may also be able to support specialized descriptions\n/// of other types.\n///\n/// Conforming to the CustomPlaygroundDisplayConvertible Protocol\n/// -------------------------------------------------------------\n///\n/// To add `CustomPlaygroundDisplayConvertible` conformance to your custom type,\n/// implement the `playgroundDescription` property. If your implementation\n/// returns an instance of one of the types above, that type's specialized\n/// description is used. If you return any other type, a structured description\n/// is generated.\n///\n/// If your type has value semantics, the `playgroundDescription` should be\n/// unaffected by subsequent mutations, if possible.\n///\n/// If your type's `playgroundDescription` returns an instance which itself\n/// conforms to `CustomPlaygroundDisplayConvertible`, then that type's\n/// `playgroundDescription` will be used, and so on. To prevent infinite loops,\n/// playground logging implementations can place a reasonable limit on this\n/// kind of chaining.\npublic protocol CustomPlaygroundDisplayConvertible {\n /// A custom playground description for this instance.\n var playgroundDescription: Any { get }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_PlaygroundDisplay.swift
cpp_apple_swift_stdlib_public_core_PlaygroundDisplay.swift
Swift
2,832
0.8
0.078125
0.952381
vue-tools
591
2023-12-10T08:22:42.763399
BSD-3-Clause
false
83811a3caf808e2e229ef65d16425858
//===----------------------------------------------------------------------===//\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#if SWIFT_ENABLE_REFLECTION\npublic typealias _CustomReflectableOrNone = CustomReflectable\n#else\npublic typealias _CustomReflectableOrNone = Any\n#endif\n\n#if !$Embedded\npublic typealias _CustomDebugStringConvertibleOrNone = CustomDebugStringConvertible\n#else\npublic typealias _CustomDebugStringConvertibleOrNone = Any\n#endif\n\n/// A stdlib-internal protocol modeled by the intrinsic pointer types,\n/// UnsafeMutablePointer, UnsafePointer, UnsafeRawPointer,\n/// UnsafeMutableRawPointer, and AutoreleasingUnsafeMutablePointer.\npublic protocol _Pointer:\n Hashable,\n Strideable,\n _CustomDebugStringConvertibleOrNone,\n _CustomReflectableOrNone,\n BitwiseCopyable\n{\n /// A type that represents the distance between two pointers.\n typealias Distance = Int\n\n associatedtype Pointee: ~Copyable\n\n /// The underlying raw pointer value.\n var _rawValue: Builtin.RawPointer { get }\n\n /// Creates a pointer from a raw value.\n init(_ _rawValue: Builtin.RawPointer)\n}\n\nextension _Pointer {\n /// Creates a new typed pointer from the given opaque pointer.\n ///\n /// - Parameter from: The opaque pointer to convert to a typed pointer.\n @_transparent\n public init(_ from: OpaquePointer) {\n unsafe self.init(from._rawValue)\n }\n\n /// Creates a new typed pointer from the given opaque pointer.\n ///\n /// - Parameter from: The opaque pointer to convert to a typed pointer. If\n /// `from` is `nil`, the result of this initializer is `nil`.\n @_transparent\n public init?(_ from: OpaquePointer?) {\n guard let unwrapped = unsafe from else { return nil }\n unsafe self.init(unwrapped)\n }\n\n /// Creates a new pointer from the given address, specified as a bit\n /// pattern.\n ///\n /// The address passed as `bitPattern` must have the correct alignment for\n /// the pointer's `Pointee` type. That is,\n /// `bitPattern % MemoryLayout<Pointee>.alignment` must be `0`.\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 self.init(Builtin.inttoptr_Word(bitPattern._builtinWordValue))\n }\n\n /// Creates a new pointer from the given address, specified as a bit\n /// pattern.\n ///\n /// The address passed as `bitPattern` must have the correct alignment for\n /// the pointer's `Pointee` type. That is,\n /// `bitPattern % MemoryLayout<Pointee>.alignment` must be `0`.\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 self.init(Builtin.inttoptr_Word(bitPattern._builtinWordValue))\n }\n\n /// Creates a new pointer from the given pointer.\n ///\n /// - Parameter other: The typed pointer to convert.\n @_transparent\n public init(@_nonEphemeral _ other: Self) {\n self.init(other._rawValue)\n }\n\n /// Creates a new pointer from the given pointer.\n ///\n /// - Parameter other: The typed pointer to convert. If `other` is `nil`, the\n /// result is `nil`.\n @_transparent\n public init?(@_nonEphemeral _ other: Self?) {\n guard let unwrapped = other else { return nil }\n self.init(unwrapped._rawValue)\n }\n}\n\n// well, this is pretty annoying\nextension _Pointer /*: Equatable */ {\n // - Note: This may be more efficient than Strideable's implementation\n // calling self.distance().\n /// Returns a Boolean value indicating whether two pointers are equal.\n ///\n /// - Parameters:\n /// - lhs: A pointer.\n /// - rhs: Another pointer.\n /// - Returns: `true` if `lhs` and `rhs` reference the same memory address;\n /// otherwise, `false`.\n @_transparent\n public static func == (lhs: Self, rhs: Self) -> Bool {\n return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))\n }\n\n /// Returns a Boolean value indicating whether two pointers represent\n /// the same memory address.\n ///\n /// - Parameters:\n /// - lhs: A pointer.\n /// - rhs: Another pointer.\n /// - Returns: `true` if `lhs` and `rhs` reference the same memory address;\n /// otherwise, `false`.\n @inlinable\n @_alwaysEmitIntoClient\n public static func == <Other: _Pointer>(lhs: Self, rhs: Other) -> Bool {\n return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))\n }\n\n /// Returns a Boolean value indicating whether two pointers represent\n /// different memory addresses.\n ///\n /// - Parameters:\n /// - lhs: A pointer.\n /// - rhs: Another pointer.\n /// - Returns: `true` if `lhs` and `rhs` reference different memory addresses;\n /// otherwise, `false`.\n @inlinable\n @_alwaysEmitIntoClient\n public static func != <Other: _Pointer>(lhs: Self, rhs: Other) -> Bool {\n return Bool(Builtin.cmp_ne_RawPointer(lhs._rawValue, rhs._rawValue))\n }\n}\n\nextension _Pointer /*: Comparable */ {\n // - Note: This is an unsigned comparison unlike Strideable's\n // implementation.\n /// Returns a Boolean value indicating whether the first pointer references\n /// a memory location earlier than the second pointer references.\n ///\n /// - Parameters:\n /// - lhs: A pointer.\n /// - rhs: Another pointer.\n /// - Returns: `true` if `lhs` references a memory address earlier than\n /// `rhs`; otherwise, `false`.\n @_transparent\n public static func < (lhs: Self, rhs: Self) -> Bool {\n return Bool(Builtin.cmp_ult_RawPointer(lhs._rawValue, rhs._rawValue))\n }\n\n /// Returns a Boolean value indicating whether the first pointer references\n /// a memory location earlier than the second pointer references.\n ///\n /// - Parameters:\n /// - lhs: A pointer.\n /// - rhs: Another pointer.\n /// - Returns: `true` if `lhs` references a memory address\n /// earlier than `rhs`; otherwise, `false`.\n @inlinable\n @_alwaysEmitIntoClient\n public static func < <Other: _Pointer>(lhs: Self, rhs: Other) -> Bool {\n return Bool(Builtin.cmp_ult_RawPointer(lhs._rawValue, rhs._rawValue))\n }\n\n /// Returns a Boolean value indicating whether the first pointer references\n /// a memory location earlier than or same as the second pointer references.\n ///\n /// - Parameters:\n /// - lhs: A pointer.\n /// - rhs: Another pointer.\n /// - Returns: `true` if `lhs` references a memory address\n /// earlier than or the same as `rhs`; otherwise, `false`.\n @inlinable\n @_alwaysEmitIntoClient\n public static func <= <Other: _Pointer>(lhs: Self, rhs: Other) -> Bool {\n return Bool(Builtin.cmp_ule_RawPointer(lhs._rawValue, rhs._rawValue))\n }\n\n /// Returns a Boolean value indicating whether the first pointer references\n /// a memory location later than the second pointer references.\n ///\n /// - Parameters:\n /// - lhs: A pointer.\n /// - rhs: Another pointer.\n /// - Returns: `true` if `lhs` references a memory address\n /// later than `rhs`; otherwise, `false`.\n @inlinable\n @_alwaysEmitIntoClient\n public static func > <Other: _Pointer>(lhs: Self, rhs: Other) -> Bool {\n return Bool(Builtin.cmp_ugt_RawPointer(lhs._rawValue, rhs._rawValue))\n }\n\n /// Returns a Boolean value indicating whether the first pointer references\n /// a memory location later than or same as the second pointer references.\n ///\n /// - Parameters:\n /// - lhs: A pointer.\n /// - rhs: Another pointer.\n /// - Returns: `true` if `lhs` references a memory address\n /// later than or the same as `rhs`; otherwise, `false`.\n @inlinable\n @_alwaysEmitIntoClient\n public static func >= <Other: _Pointer>(lhs: Self, rhs: Other) -> Bool {\n return Bool(Builtin.cmp_uge_RawPointer(lhs._rawValue, rhs._rawValue))\n }\n}\n\nextension _Pointer /*: Strideable*/ {\n /// Returns a pointer to the next consecutive instance.\n ///\n /// The resulting pointer must be within the bounds of the same allocation as\n /// this pointer.\n ///\n /// - Returns: A pointer advanced from this pointer by\n /// `MemoryLayout<Pointee>.stride` bytes.\n @_transparent\n public func successor() -> Self {\n return advanced(by: 1)\n }\n\n /// Returns a pointer to the previous consecutive instance.\n ///\n /// The resulting pointer must be within the bounds of the same allocation as\n /// this pointer.\n ///\n /// - Returns: A pointer shifted backward from this pointer by\n /// `MemoryLayout<Pointee>.stride` bytes.\n @_transparent\n public func predecessor() -> Self {\n return advanced(by: -1)\n }\n\n /// Returns the distance from this pointer to the given pointer, counted as\n /// instances of the pointer's `Pointee` type.\n ///\n /// With pointers `p` and `q`, the result of `p.distance(to: q)` is\n /// equivalent to `q - p`.\n ///\n /// Typed pointers are required to be properly aligned for their `Pointee`\n /// type. Proper alignment ensures that the result of `distance(to:)`\n /// accurately measures the distance between the two pointers, counted in\n /// strides of `Pointee`. To find the distance in bytes between two\n /// pointers, convert them to `UnsafeRawPointer` instances before calling\n /// `distance(to:)`.\n ///\n /// - Parameter end: The pointer to calculate the distance to.\n /// - Returns: The distance from this pointer to `end`, in strides of the\n /// pointer's `Pointee` type. To access the stride, use\n /// `MemoryLayout<Pointee>.stride`.\n @_transparent\n public func distance(to end: Self) -> Int {\n return\n Int(Builtin.sub_Word(Builtin.ptrtoint_Word(end._rawValue),\n Builtin.ptrtoint_Word(_rawValue)))\n / MemoryLayout<Pointee>.stride\n }\n\n /// Returns a pointer offset from this pointer by the specified number of\n /// instances.\n ///\n /// With pointer `p` and distance `n`, the result of `p.advanced(by: n)` is\n /// equivalent to `p + n`.\n ///\n /// The resulting pointer must be within the bounds of the same allocation as\n /// this pointer.\n ///\n /// - Parameter n: The number of strides of the pointer's `Pointee` type to\n /// offset this pointer. To access the stride, use\n /// `MemoryLayout<Pointee>.stride`. `n` may be positive, negative, or\n /// zero.\n /// - Returns: A pointer offset from this pointer by `n` instances of the\n /// `Pointee` type.\n @_transparent\n public func advanced(by n: Int) -> Self {\n return Self(Builtin.gep_Word(\n self._rawValue, n._builtinWordValue, Pointee.self))\n }\n}\n\nextension _Pointer /*: Hashable */ {\n @inlinable\n @safe public func hash(into hasher: inout Hasher) {\n hasher.combine(UInt(bitPattern: self))\n }\n\n @inlinable\n @safe public func _rawHashValue(seed: Int) -> Int {\n return Hasher._hash(seed: seed, UInt(bitPattern: self))\n }\n}\n\n@_unavailableInEmbedded\nextension _Pointer /*: CustomDebugStringConvertible */ {\n /// A textual representation of the pointer, suitable for debugging.\n @safe public var debugDescription: String {\n return _rawPointerToString(_rawValue)\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension _Pointer /*: CustomReflectable */ {\n @safe public var customMirror: Mirror {\n let ptrValue = UInt64(\n bitPattern: Int64(Int(Builtin.ptrtoint_Word(_rawValue))))\n return Mirror(self, children: ["pointerValue": ptrValue])\n }\n}\n#endif\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 @safe\n @_transparent\n public init<P: _Pointer>(bitPattern pointer: P?) {\n if let pointer = pointer {\n self = Int(Builtin.ptrtoint_Word(pointer._rawValue))\n } else {\n self = 0\n }\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 @safe\n @_transparent\n public init<P: _Pointer>(bitPattern pointer: P?) {\n if let pointer = pointer {\n self = UInt(Builtin.ptrtoint_Word(pointer._rawValue))\n } else {\n self = 0\n }\n }\n}\n\n// Pointer arithmetic operators (formerly via Strideable)\nextension Strideable where Self: _Pointer {\n @_transparent\n public static func + (@_nonEphemeral lhs: Self, rhs: Self.Stride) -> Self {\n return lhs.advanced(by: rhs)\n }\n\n @_transparent\n public static func + (lhs: Self.Stride, @_nonEphemeral rhs: Self) -> Self {\n return rhs.advanced(by: lhs)\n }\n\n @_transparent\n public static func - (@_nonEphemeral lhs: Self, rhs: Self.Stride) -> Self {\n return lhs.advanced(by: -rhs)\n }\n\n @_transparent\n public static func - (lhs: Self, rhs: Self) -> Self.Stride {\n return rhs.distance(to: lhs)\n }\n\n @_transparent\n public static func += (lhs: inout Self, rhs: Self.Stride) {\n lhs = lhs.advanced(by: rhs)\n }\n\n @_transparent\n public static func -= (lhs: inout Self, rhs: Self.Stride) {\n lhs = lhs.advanced(by: -rhs)\n }\n}\n\n/// Derive a pointer argument from a convertible pointer type.\n@_transparent\npublic // COMPILER_INTRINSIC\nfunc _convertPointerToPointerArgument<\n FromPointer: _Pointer,\n ToPointer: _Pointer\n>(_ from: FromPointer) -> ToPointer {\n return ToPointer(from._rawValue)\n}\n\n/// Derive a pointer argument from the address of an inout parameter.\n@_transparent\npublic // COMPILER_INTRINSIC\nfunc _convertInOutToPointerArgument<\n ToPointer: _Pointer\n>(_ from: Builtin.RawPointer) -> ToPointer {\n return ToPointer(from)\n}\n\n\n/// Derive a pointer argument from a value array parameter.\n///\n/// This always produces a non-null pointer, even if the array doesn't have any\n/// storage.\n#if !$Embedded\n@_transparent\npublic // COMPILER_INTRINSIC\nfunc _convertConstArrayToPointerArgument<\n FromElement,\n ToPointer: _Pointer\n>(_ arr: [FromElement]) -> (AnyObject?, ToPointer) {\n let (owner, opaquePointer) = unsafe arr._cPointerArgs()\n\n let validPointer: ToPointer\n if let addr = unsafe opaquePointer {\n validPointer = ToPointer(addr._rawValue)\n } else {\n let lastAlignedValue = ~(MemoryLayout<FromElement>.alignment - 1)\n let lastAlignedPointer = unsafe UnsafeRawPointer(bitPattern: lastAlignedValue)!\n validPointer = ToPointer(lastAlignedPointer._rawValue)\n }\n return (owner, validPointer)\n}\n#else\n@_transparent\npublic // COMPILER_INTRINSIC\nfunc _convertConstArrayToPointerArgument<\n FromElement,\n ToPointer: _Pointer\n>(_ arr: [FromElement]) -> (Builtin.NativeObject?, ToPointer) {\n let (owner, opaquePointer) = unsafe arr._cPointerArgs()\n\n let validPointer: ToPointer\n if let addr = unsafe opaquePointer {\n validPointer = ToPointer(addr._rawValue)\n } else {\n let lastAlignedValue = ~(MemoryLayout<FromElement>.alignment - 1)\n let lastAlignedPointer = unsafe UnsafeRawPointer(bitPattern: lastAlignedValue)!\n validPointer = ToPointer(lastAlignedPointer._rawValue)\n }\n return (owner, validPointer)\n}\n#endif\n\n/// Derive a pointer argument from an inout array parameter.\n///\n/// This always produces a non-null pointer, even if the array's length is 0.\n#if !$Embedded\n@_transparent\npublic // COMPILER_INTRINSIC\nfunc _convertMutableArrayToPointerArgument<\n FromElement,\n ToPointer: _Pointer\n>(_ a: inout [FromElement]) -> (AnyObject?, ToPointer) {\n // TODO: Putting a canary at the end of the array in checked builds might\n // be a good idea\n\n // Call reserve to force contiguous storage.\n a.reserveCapacity(0)\n unsafe _debugPrecondition(a._baseAddressIfContiguous != nil || a.isEmpty)\n\n return _convertConstArrayToPointerArgument(a)\n}\n#else\n@_transparent\npublic // COMPILER_INTRINSIC\nfunc _convertMutableArrayToPointerArgument<\n FromElement,\n ToPointer: _Pointer\n>(_ a: inout [FromElement]) -> (Builtin.NativeObject?, ToPointer) {\n // TODO: Putting a canary at the end of the array in checked builds might\n // be a good idea\n\n // Call reserve to force contiguous storage.\n a.reserveCapacity(0)\n _debugPrecondition(unsafe a._baseAddressIfContiguous != nil || a.isEmpty)\n\n return _convertConstArrayToPointerArgument(a)\n}\n#endif\n\n/// Derive a UTF-8 pointer argument from a value string parameter.\n#if !$Embedded\n@_transparent\npublic // COMPILER_INTRINSIC\nfunc _convertConstStringToUTF8PointerArgument<\n ToPointer: _Pointer\n>(_ str: String) -> (AnyObject?, ToPointer) {\n let utf8 = Array(str.utf8CString)\n return _convertConstArrayToPointerArgument(utf8)\n}\n#else\n@_transparent\npublic // COMPILER_INTRINSIC\nfunc _convertConstStringToUTF8PointerArgument<\n ToPointer: _Pointer\n>(_ str: String) -> (Builtin.NativeObject?, ToPointer) {\n let utf8 = Array(str.utf8CString)\n return _convertConstArrayToPointerArgument(utf8)\n}\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Pointer.swift
cpp_apple_swift_stdlib_public_core_Pointer.swift
Swift
17,277
0.95
0.060837
0.443515
python-kit
97
2023-10-26T06:39:10.519286
GPL-3.0
false
5e8c0530739dced6a7a9d1e2d1300954
//===----------------------------------------------------------------------===//\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// Swift Standard Prolog Library.\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n// Standardized uninhabited type\n//===----------------------------------------------------------------------===//\n/// A type that has no values and can't be constructed.\n///\n/// Use `Never` as the return type of a function\n/// that doesn't return normally --- for example,\n/// because it runs forever or terminates the program.\n///\n/// // An infinite loop never returns.\n/// func forever() -> Never {\n/// while true {\n/// print("I will print forever.")\n/// }\n/// }\n///\n/// // Calling fatalError(_:file:line:) unconditionally stops the program.\n/// func crashAndBurn() -> Never {\n/// fatalError("Something very, very bad happened")\n/// }\n///\n/// A function that returns `Never` is called a _nonreturning_ function.\n/// Closures, methods, computed properties, and subscripts\n/// can also be nonreturning.\n///\n/// There's no way to create an instance of `Never`;\n/// this characteristic makes it an _uninhabited_ type.\n/// You can use an uninhabited type like `Never`\n/// to represent states in your program\n/// that are impossible to reach during execution.\n/// Swift's type system uses this information ---\n/// for example, to reason about control statements\n/// in cases that are known to be unreachable.\n///\n/// let favoriteNumber: Result<Int, Never> = .success(42)\n/// switch favoriteNumber {\n/// case .success(let value):\n/// print("My favorite number is", value)\n/// }\n///\n/// In the code above,\n/// `favoriteNumber` has a failure type of `Never`,\n/// indicating that it always succeeds.\n/// The switch statement is therefore exhaustive,\n/// even though it doesn't contain a `.failure` case,\n/// because that case could never be reached.\n@frozen\npublic enum Never {}\n\nextension Never: BitwiseCopyable {}\n\nextension Never: Sendable {}\n\nextension Never: Error {}\n\nextension Never: Equatable, Comparable, Hashable {}\n\n@available(SwiftStdlib 5.5, *)\n@_unavailableInEmbedded\nextension Never: Identifiable {\n @available(SwiftStdlib 5.5, *)\n public var id: Never {\n switch self {}\n }\n}\n\n@available(SwiftStdlib 5.9, *)\n@_unavailableInEmbedded\nextension Never: Encodable {\n @available(SwiftStdlib 5.9, *)\n public func encode(to encoder: any Encoder) throws {}\n}\n\n@available(SwiftStdlib 5.9, *)\n@_unavailableInEmbedded\nextension Never: Decodable {\n @available(SwiftStdlib 5.9, *)\n public init(from decoder: any Decoder) throws {\n let context = DecodingError.Context(\n codingPath: decoder.codingPath,\n debugDescription: "Unable to decode an instance of Never.")\n throw DecodingError.typeMismatch(Never.self, context)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Standardized aliases\n//===----------------------------------------------------------------------===//\n/// The return type of functions that don't explicitly specify a return type,\n/// that is, an empty tuple `()`.\n///\n/// When declaring a function or method, you don't need to specify a return\n/// type if no value will be returned. However, the type of a function,\n/// method, or closure always includes a return type, which is `Void` if\n/// otherwise unspecified.\n///\n/// Use `Void` or an empty tuple as the return type when declaring a closure,\n/// function, or method that doesn't return a value.\n///\n/// // No return type declared:\n/// func logMessage(_ s: String) {\n/// print("Message: \(s)")\n/// }\n///\n/// let logger: (String) -> Void = logMessage\n/// logger("This is a void function")\n/// // Prints "Message: This is a void function"\npublic typealias Void = ()\n\n//===----------------------------------------------------------------------===//\n// Aliases for floating point types\n//===----------------------------------------------------------------------===//\n// FIXME: it should be the other way round, Float = Float32, Double = Float64,\n// but the type checker loses sugar currently, and ends up displaying 'FloatXX'\n// in diagnostics.\n/// A 32-bit floating point type.\npublic typealias Float32 = Float\n/// A 64-bit floating point type.\npublic typealias Float64 = Double\n\n//===----------------------------------------------------------------------===//\n// Default types for unconstrained literals\n//===----------------------------------------------------------------------===//\n/// The default type for an otherwise-unconstrained integer literal.\npublic typealias IntegerLiteralType = Int\n/// The default type for an otherwise-unconstrained floating-point literal.\npublic typealias FloatLiteralType = Double\n\n/// The default type for an otherwise-unconstrained Boolean literal.\n///\n/// When you create a constant or variable using one of the Boolean literals\n/// `true` or `false`, the resulting type is determined by the\n/// `BooleanLiteralType` alias. For example:\n///\n/// let isBool = true\n/// print("isBool is a '\(type(of: isBool))'")\n/// // Prints "isBool is a 'Bool'"\n///\n/// The type aliased by `BooleanLiteralType` must conform to the\n/// `ExpressibleByBooleanLiteral` protocol.\npublic typealias BooleanLiteralType = Bool\n\n/// The default type for an otherwise-unconstrained unicode scalar literal.\n@_unavailableInEmbedded\npublic typealias UnicodeScalarType = String\n/// The default type for an otherwise-unconstrained Unicode extended\n/// grapheme cluster literal.\n@_unavailableInEmbedded\npublic typealias ExtendedGraphemeClusterType = String\n/// The default type for an otherwise-unconstrained string literal.\n@_unavailableInEmbedded\npublic typealias StringLiteralType = String\n\n//===----------------------------------------------------------------------===//\n// Default types for unconstrained number literals\n//===----------------------------------------------------------------------===//\n#if !(os(Windows) || os(Android) || ($Embedded && !os(Linux) && !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS)))) && (arch(i386) || arch(x86_64))\npublic typealias _MaxBuiltinFloatType = Builtin.FPIEEE80\n#else\npublic typealias _MaxBuiltinFloatType = Builtin.FPIEEE64\n#endif\n\n//===----------------------------------------------------------------------===//\n// Standard protocols\n//===----------------------------------------------------------------------===//\n\n#if _runtime(_ObjC)\n/// The protocol to which all classes implicitly conform.\n///\n/// You use `AnyObject` when you need the flexibility of an untyped object or\n/// when you use bridged Objective-C methods and properties that return an\n/// untyped result. `AnyObject` can be used as the concrete type for an\n/// instance of any class, class type, or class-only protocol. For example:\n///\n/// class FloatRef {\n/// let value: Float\n/// init(_ value: Float) {\n/// self.value = value\n/// }\n/// }\n///\n/// let x = FloatRef(2.3)\n/// let y: AnyObject = x\n/// let z: AnyObject = FloatRef.self\n///\n/// `AnyObject` can also be used as the concrete type for an instance of a type\n/// that bridges to an Objective-C class. Many value types in Swift bridge to\n/// Objective-C counterparts, like `String` and `Int`.\n///\n/// let s: AnyObject = "This is a bridged string." as NSString\n/// print(s is NSString)\n/// // Prints "true"\n///\n/// let v: AnyObject = 100 as NSNumber\n/// print(type(of: v))\n/// // Prints "__NSCFNumber"\n///\n/// The flexible behavior of the `AnyObject` protocol is similar to\n/// Objective-C's `id` type. For this reason, imported Objective-C types\n/// frequently use `AnyObject` as the type for properties, method parameters,\n/// and return values.\n///\n/// Casting AnyObject Instances to a Known Type\n/// ===========================================\n///\n/// Objects with a concrete type of `AnyObject` maintain a specific dynamic\n/// type and can be cast to that type using one of the type-cast operators\n/// (`as`, `as?`, or `as!`).\n///\n/// This example uses the conditional downcast operator (`as?`) to\n/// conditionally cast the `s` constant declared above to an instance of\n/// Swift's `String` type.\n///\n/// if let message = s as? String {\n/// print("Successful cast to String: \(message)")\n/// }\n/// // Prints "Successful cast to String: This is a bridged string."\n///\n/// If you have prior knowledge that an `AnyObject` instance has a particular\n/// type, you can use the unconditional downcast operator (`as!`). Performing\n/// an invalid cast triggers a runtime error.\n///\n/// let message = s as! String\n/// print("Successful cast to String: \(message)")\n/// // Prints "Successful cast to String: This is a bridged string."\n///\n/// let badCase = v as! String\n/// // Runtime error\n///\n/// Casting is always safe in the context of a `switch` statement.\n///\n/// let mixedArray: [AnyObject] = [s, v]\n/// for object in mixedArray {\n/// switch object {\n/// case let x as String:\n/// print("'\(x)' is a String")\n/// default:\n/// print("'\(object)' is not a String")\n/// }\n/// }\n/// // Prints "'This is a bridged string.' is a String"\n/// // Prints "'100' is not a String"\n///\n/// Accessing Objective-C Methods and Properties\n/// ============================================\n///\n/// When you use `AnyObject` as a concrete type, you have at your disposal\n/// every `@objc` method and property---that is, methods and properties\n/// imported from Objective-C or marked with the `@objc` attribute. Because\n/// Swift can't guarantee at compile time that these methods and properties\n/// are actually available on an `AnyObject` instance's underlying type, these\n/// `@objc` symbols are available as implicitly unwrapped optional methods and\n/// properties, respectively.\n///\n/// This example defines an `IntegerRef` type with an `@objc` method named\n/// `getIntegerValue()`.\n///\n/// class IntegerRef {\n/// let value: Int\n/// init(_ value: Int) {\n/// self.value = value\n/// }\n///\n/// @objc func getIntegerValue() -> Int {\n/// return value\n/// }\n/// }\n///\n/// func getObject() -> AnyObject {\n/// return IntegerRef(100)\n/// }\n///\n/// let obj: AnyObject = getObject()\n///\n/// In the example, `obj` has a static type of `AnyObject` and a dynamic type\n/// of `IntegerRef`. You can use optional chaining to call the `@objc` method\n/// `getIntegerValue()` on `obj` safely. If you're sure of the dynamic type of\n/// `obj`, you can call `getIntegerValue()` directly.\n///\n/// let possibleValue = obj.getIntegerValue?()\n/// print(possibleValue)\n/// // Prints "Optional(100)"\n///\n/// let certainValue = obj.getIntegerValue()\n/// print(certainValue)\n/// // Prints "100"\n///\n/// If the dynamic type of `obj` doesn't implement a `getIntegerValue()`\n/// method, the system returns a runtime error when you initialize\n/// `certainValue`.\n///\n/// Alternatively, if you need to test whether `obj.getIntegerValue()` exists,\n/// use optional binding before calling the method.\n///\n/// if let f = obj.getIntegerValue {\n/// print("The value of 'obj' is \(f())")\n/// } else {\n/// print("'obj' does not have a 'getIntegerValue()' method")\n/// }\n/// // Prints "The value of 'obj' is 100"\npublic typealias AnyObject = Builtin.AnyObject\n#else\n/// The protocol to which all classes implicitly conform.\npublic typealias AnyObject = Builtin.AnyObject\n#endif\n\n/// The protocol to which all class types implicitly conform.\n///\n/// You can use the `AnyClass` protocol as the concrete type for an instance of\n/// any class. When you do, all known `@objc` class methods and properties are\n/// available as implicitly unwrapped optional methods and properties,\n/// respectively. For example:\n///\n/// class IntegerRef {\n/// @objc class func getDefaultValue() -> Int {\n/// return 42\n/// }\n/// }\n///\n/// func getDefaultValue(_ c: AnyClass) -> Int? {\n/// return c.getDefaultValue?()\n/// }\n///\n/// The `getDefaultValue(_:)` function uses optional chaining to safely call\n/// the implicitly unwrapped class method on `c`. Calling the function with\n/// different class types shows how the `getDefaultValue()` class method is\n/// only conditionally available.\n///\n/// print(getDefaultValue(IntegerRef.self))\n/// // Prints "Optional(42)"\n///\n/// print(getDefaultValue(NSString.self))\n/// // Prints "nil"\npublic typealias AnyClass = AnyObject.Type\n\n//===----------------------------------------------------------------------===//\n// Standard pattern matching forms\n//===----------------------------------------------------------------------===//\n\n/// Returns a Boolean value indicating whether two arguments match by value\n/// equality.\n///\n/// The pattern-matching operator (`~=`) is used internally in `case`\n/// statements for pattern matching. When you match against an `Equatable`\n/// value in a `case` statement, this operator is called behind the scenes.\n///\n/// let weekday = 3\n/// let lunch: String\n/// switch weekday {\n/// case 3:\n/// lunch = "Taco Tuesday!"\n/// default:\n/// lunch = "Pizza again."\n/// }\n/// // lunch == "Taco Tuesday!"\n///\n/// In this example, the `case 3` expression uses this pattern-matching\n/// operator to test whether `weekday` is equal to the value `3`.\n///\n/// - Note: In most cases, you should use the equal-to operator (`==`) to test\n/// whether two instances are equal. The pattern-matching operator is\n/// primarily intended to enable `case` statement pattern matching.\n///\n/// - Parameters:\n/// - lhs: A value to compare.\n/// - rhs: Another value to compare.\n@_transparent\npublic func ~= <T: Equatable>(a: T, b: T) -> Bool {\n return a == b\n}\n\n//===----------------------------------------------------------------------===//\n// Standard precedence groups\n//===----------------------------------------------------------------------===//\n\nprecedencegroup AssignmentPrecedence {\n assignment: true\n associativity: right\n}\nprecedencegroup FunctionArrowPrecedence {\n associativity: right\n higherThan: AssignmentPrecedence\n}\nprecedencegroup TernaryPrecedence {\n associativity: right\n higherThan: FunctionArrowPrecedence\n}\nprecedencegroup DefaultPrecedence {\n higherThan: TernaryPrecedence\n}\nprecedencegroup LogicalDisjunctionPrecedence {\n associativity: left\n higherThan: TernaryPrecedence\n}\nprecedencegroup LogicalConjunctionPrecedence {\n associativity: left\n higherThan: LogicalDisjunctionPrecedence\n}\nprecedencegroup ComparisonPrecedence {\n higherThan: LogicalConjunctionPrecedence\n}\nprecedencegroup NilCoalescingPrecedence {\n associativity: right\n higherThan: ComparisonPrecedence\n}\nprecedencegroup CastingPrecedence {\n higherThan: NilCoalescingPrecedence\n}\nprecedencegroup RangeFormationPrecedence {\n higherThan: CastingPrecedence\n}\nprecedencegroup AdditionPrecedence {\n associativity: left\n higherThan: RangeFormationPrecedence\n}\nprecedencegroup MultiplicationPrecedence {\n associativity: left\n higherThan: AdditionPrecedence\n}\nprecedencegroup BitwiseShiftPrecedence {\n higherThan: MultiplicationPrecedence\n}\n\n\n//===----------------------------------------------------------------------===//\n// Standard operators\n//===----------------------------------------------------------------------===//\n\n// Standard postfix operators.\npostfix operator ++\npostfix operator --\npostfix operator ...\n\n// Optional<T> unwrapping operator is built into the compiler as a part of\n// postfix expression grammar.\n//\n// postfix operator !\n\n// Standard prefix operators.\nprefix operator ++\nprefix operator --\nprefix operator !\nprefix operator ~\nprefix operator +\nprefix operator -\nprefix operator ...\nprefix operator ..<\n\n// Standard infix operators.\n\n// "Exponentiative"\n\ninfix operator <<: BitwiseShiftPrecedence\ninfix operator &<<: BitwiseShiftPrecedence\ninfix operator >>: BitwiseShiftPrecedence\ninfix operator &>>: BitwiseShiftPrecedence\n\n// "Multiplicative"\n\ninfix operator *: MultiplicationPrecedence\ninfix operator &*: MultiplicationPrecedence\ninfix operator /: MultiplicationPrecedence\ninfix operator %: MultiplicationPrecedence\ninfix operator &: MultiplicationPrecedence\n\n// "Additive"\n\ninfix operator +: AdditionPrecedence\ninfix operator &+: AdditionPrecedence\ninfix operator -: AdditionPrecedence\ninfix operator &-: AdditionPrecedence\ninfix operator |: AdditionPrecedence\ninfix operator ^: AdditionPrecedence\n\n// FIXME: is this the right precedence level for "..." ?\ninfix operator ...: RangeFormationPrecedence\ninfix operator ..<: RangeFormationPrecedence\n\n// The cast operators 'as' and 'is' are hardcoded as if they had the\n// following attributes:\n// infix operator as: CastingPrecedence\n\n// "Coalescing"\n\ninfix operator ??: NilCoalescingPrecedence\n\n// "Comparative"\n\ninfix operator <: ComparisonPrecedence\ninfix operator <=: ComparisonPrecedence\ninfix operator >: ComparisonPrecedence\ninfix operator >=: ComparisonPrecedence\ninfix operator ==: ComparisonPrecedence\ninfix operator !=: ComparisonPrecedence\ninfix operator ===: ComparisonPrecedence\ninfix operator !==: ComparisonPrecedence\n// FIXME: ~= will be built into the compiler.\ninfix operator ~=: ComparisonPrecedence\n\n// "Conjunctive"\n\ninfix operator &&: LogicalConjunctionPrecedence\n\n// "Disjunctive"\n\ninfix operator ||: LogicalDisjunctionPrecedence\n\n// User-defined ternary operators are not supported. The ? : operator is\n// hardcoded as if it had the following attributes:\n// operator ternary ? : : TernaryPrecedence\n\n// User-defined assignment operators are not supported. The = operator is\n// hardcoded as if it had the following attributes:\n// infix operator =: AssignmentPrecedence\n\n// Compound\n\ninfix operator *=: AssignmentPrecedence\ninfix operator &*=: AssignmentPrecedence\ninfix operator /=: AssignmentPrecedence\ninfix operator %=: AssignmentPrecedence\ninfix operator +=: AssignmentPrecedence\ninfix operator &+=: AssignmentPrecedence\ninfix operator -=: AssignmentPrecedence\ninfix operator &-=: AssignmentPrecedence\ninfix operator <<=: AssignmentPrecedence\ninfix operator &<<=: AssignmentPrecedence\ninfix operator >>=: AssignmentPrecedence\ninfix operator &>>=: AssignmentPrecedence\ninfix operator &=: AssignmentPrecedence\ninfix operator ^=: AssignmentPrecedence\ninfix operator |=: AssignmentPrecedence\n\n// Workaround for <rdar://problem/14011860> SubTLF: Default\n// implementations in protocols. Library authors should ensure\n// that this operator never needs to be seen by end-users. See\n// test/Prototypes/GenericDispatch.swift for a fully documented\n// example of how this operator is used, and how its use can be hidden\n// from users.\ninfix operator ~>\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Policy.swift
cpp_apple_swift_stdlib_public_core_Policy.swift
Swift
19,396
0.95
0.113718
0.693676
vue-tools
475
2024-03-14T13:05:52.382078
GPL-3.0
false
b5ed412f876a2ef8b47a2ff458778645
//===-- PrefixWhile.swift - Lazy views for prefix(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\n/// A sequence whose elements consist of the initial consecutive elements of\n/// some base sequence that satisfy a given predicate.\n///\n/// - Note: When `LazyPrefixWhileSequence` wraps a collection type, the \n/// performance of accessing `endIndex` depends on how many \n/// elements satisfy the predicate at the start of the collection, and might \n/// not offer the usual performance given by the `Collection` protocol.\n/// Accessing `endIndex`, the `last` property, or calling methods that\n/// depend on moving indices might not have the documented complexity.\n@frozen // lazy-performance\npublic struct LazyPrefixWhileSequence<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 @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 LazyPrefixWhileSequence: Sendable {}\n\nextension LazyPrefixWhileSequence {\n /// An iterator over the initial elements traversed by a base iterator that\n /// satisfy a given predicate.\n ///\n /// This is the associated iterator for the `LazyPrefixWhileSequence`,\n /// `LazyPrefixWhileCollection`, and `LazyPrefixWhileBidirectionalCollection`\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 LazyPrefixWhileSequence.Iterator: Sendable {}\n\nextension LazyPrefixWhileSequence.Iterator: IteratorProtocol, Sequence {\n @inlinable // lazy-performance\n public mutating func next() -> Element? {\n // Return elements from the base iterator until one fails the predicate.\n if !_predicateHasFailed, let nextElement = _base.next() {\n if _predicate(nextElement) {\n return nextElement\n } else {\n _predicateHasFailed = true\n }\n }\n return nil\n }\n}\n\nextension LazyPrefixWhileSequence: Sequence {\n @inlinable // lazy-performance\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_base: _base.makeIterator(), predicate: _predicate)\n }\n}\n\nextension LazyPrefixWhileSequence: LazySequenceProtocol {\n public typealias Elements = LazyPrefixWhileSequence\n}\n\nextension LazySequenceProtocol {\n /// Returns a lazy sequence of the initial consecutive 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 included or\n /// `false` otherwise. Once `predicate` returns `false` it will not be\n /// called again.\n @inlinable // lazy-performance\n public __consuming func prefix(\n while predicate: @escaping (Elements.Element) -> Bool\n ) -> LazyPrefixWhileSequence<Self.Elements> {\n return LazyPrefixWhileSequence(_base: self.elements, predicate: predicate)\n }\n}\n\n/// A lazy collection wrapper that includes the initial consecutive\n/// elements of an underlying collection that satisfy a predicate.\n///\n/// - Note: The performance of accessing `endIndex` depends on how many \n/// elements satisfy the predicate at the start of the collection, and might \n/// not offer the usual performance given by the `Collection` protocol.\n/// Accessing `endIndex`, the `last` property, or calling methods that\n/// depend on moving indices might not have the documented complexity.\npublic typealias LazyPrefixWhileCollection<T: Collection> = LazyPrefixWhileSequence<T>\n\nextension LazyPrefixWhileCollection {\n /// A position in the base collection of a `LazyPrefixWhileCollection` or the\n /// end of that collection.\n @frozen // lazy-performance\n @usableFromInline\n internal enum _IndexRepresentation {\n case index(Base.Index)\n case pastEnd\n }\n \n /// A position in a `LazyPrefixWhileCollection` or\n /// `LazyPrefixWhileBidirectionalCollection` instance.\n @frozen // lazy-performance\n public struct Index {\n /// The position corresponding to `self` in the underlying collection.\n @usableFromInline // lazy-performance\n internal let _value: _IndexRepresentation\n\n /// Creates a new index wrapper for `i`.\n @inlinable // lazy-performance\n internal init(_ i: Base.Index) {\n self._value = .index(i)\n }\n\n /// Creates a new index that can represent the `endIndex` of a\n /// `LazyPrefixWhileCollection<Base>`. This is not the same as a wrapper\n /// around `Base.endIndex`.\n @inlinable // lazy-performance\n internal init(endOf: Base) {\n self._value = .pastEnd\n }\n }\n}\n\nextension LazyPrefixWhileSequence._IndexRepresentation: Sendable\n where Base.Index: Sendable {}\n\nextension LazyPrefixWhileSequence.Index: Sendable\n where Base.Index: Sendable {}\n\n// FIXME: should work on the typealias\nextension LazyPrefixWhileSequence.Index: Comparable where Base: Collection {\n @inlinable // lazy-performance\n public static func == (\n lhs: LazyPrefixWhileCollection<Base>.Index, \n rhs: LazyPrefixWhileCollection<Base>.Index\n ) -> Bool {\n switch (lhs._value, rhs._value) {\n case let (.index(l), .index(r)):\n return l == r\n case (.pastEnd, .pastEnd):\n return true\n case (.pastEnd, .index), (.index, .pastEnd):\n return false\n }\n }\n\n @inlinable // lazy-performance\n public static func < (\n lhs: LazyPrefixWhileCollection<Base>.Index, \n rhs: LazyPrefixWhileCollection<Base>.Index\n ) -> Bool {\n switch (lhs._value, rhs._value) {\n case let (.index(l), .index(r)):\n return l < r\n case (.index, .pastEnd):\n return true\n case (.pastEnd, _):\n return false\n }\n }\n}\n\n// FIXME: should work on the typealias\nextension LazyPrefixWhileSequence.Index: Hashable where Base.Index: Hashable, Base: Collection {\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 _value {\n case .index(let value):\n hasher.combine(value)\n case .pastEnd:\n hasher.combine(Int.max)\n }\n }\n}\n\nextension LazyPrefixWhileCollection: Collection {\n public typealias SubSequence = Slice<LazyPrefixWhileCollection<Base>>\n\n @inlinable // lazy-performance\n public var startIndex: Index {\n return Index(_base.startIndex)\n }\n\n @inlinable // lazy-performance\n public var endIndex: Index {\n // If the first element of `_base` satisfies the predicate, there is at\n // least one element in the lazy collection: Use the explicit `.pastEnd` index.\n if let first = _base.first, _predicate(first) {\n return Index(endOf: _base)\n }\n\n // `_base` is either empty or `_predicate(_base.first!) == false`. In either\n // case, the lazy collection is empty, so `endIndex == startIndex`.\n return startIndex\n }\n\n @inlinable // lazy-performance\n public func index(after i: Index) -> Index {\n _precondition(i != endIndex, "Can't advance past endIndex")\n guard case .index(let i) = i._value else {\n _preconditionFailure("Invalid index passed to index(after:)")\n }\n let nextIndex = _base.index(after: i)\n guard nextIndex != _base.endIndex && _predicate(_base[nextIndex]) else {\n return Index(endOf: _base)\n }\n return Index(nextIndex)\n }\n\n @inlinable // lazy-performance\n public subscript(position: Index) -> Element {\n switch position._value {\n case .index(let i):\n return _base[i]\n case .pastEnd:\n _preconditionFailure("Index out of range")\n }\n }\n}\n\nextension LazyPrefixWhileCollection: LazyCollectionProtocol { }\n\nextension LazyPrefixWhileCollection: BidirectionalCollection\nwhere Base: BidirectionalCollection {\n @inlinable // lazy-performance\n public func index(before i: Index) -> Index {\n switch i._value {\n case .index(let i):\n _precondition(i != _base.startIndex, "Can't move before startIndex")\n return Index(_base.index(before: i))\n case .pastEnd:\n // Look for the position of the last element in a non-empty\n // prefix(while:) collection by searching forward for a predicate\n // failure.\n\n // Safe to assume that `_base.startIndex != _base.endIndex`; if they\n // were equal, `_base.startIndex` would be used as the `endIndex` of\n // this collection.\n _internalInvariant(!_base.isEmpty)\n var result = _base.startIndex\n while true {\n let next = _base.index(after: result)\n if next == _base.endIndex || !_predicate(_base[next]) {\n break\n }\n result = next\n }\n return Index(result)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_PrefixWhile.swift
cpp_apple_swift_stdlib_public_core_PrefixWhile.swift
Swift
9,709
0.8
0.076125
0.264591
python-kit
860
2024-12-10T04:42:19.673381
GPL-3.0
false
557b79e934fd4454eb82c6c7d4cfcf8f
@inline(never)\nprivate func consume<T>(_ t: T) {\n withExtendedLifetime(t) { t in }\n}\n@usableFromInline\ninternal func _prespecialize() {\n consume(Array<()>.self)\n consume(Array<(Optional<String>, Any)>.self)\n consume(Array<Any>.self)\n consume(Array<AnyHashable>.self)\n consume(Array<Dictionary<String, Any>>.self)\n consume(Array<Dictionary<String, AnyObject>>.self)\n consume(Array<Int64>.self)\n consume(Array<Int>.self)\n consume(Array<Optional<Any>>.self)\n consume(Array<Optional<String>>.self)\n#if _runtime(_ObjC)\n consume(_ArrayBuffer<()>.self)\n consume(_ArrayBuffer<(Optional<String>, Any)>.self)\n consume(_ArrayBuffer<Any>.self)\n consume(_ArrayBuffer<AnyHashable>.self)\n consume(_ArrayBuffer<Dictionary<String, Any>>.self)\n consume(_ArrayBuffer<Dictionary<String, AnyObject>>.self)\n consume(_ArrayBuffer<Int64>.self)\n consume(_ArrayBuffer<Int>.self)\n consume(_ArrayBuffer<Optional<Any>>.self)\n consume(_ArrayBuffer<Optional<String>>.self)\n#endif\n consume(ClosedRange<Int>.self)\n consume(ContiguousArray<(AnyHashable, Any)>.self)\n consume(ContiguousArray<(Optional<String>, Any)>.self)\n consume(ContiguousArray<Any>.self)\n consume(ContiguousArray<AnyHashable>.self)\n consume(ContiguousArray<Dictionary<String, AnyObject>>.self)\n consume(ContiguousArray<Int64>.self)\n consume(ContiguousArray<String>.self)\n consume(_ContiguousArrayStorage<(AnyHashable, Any)>.self)\n consume(_ContiguousArrayStorage<(Optional<String>, Any)>.self)\n consume(_ContiguousArrayStorage<Any>.self)\n consume(_ContiguousArrayStorage<AnyHashable>.self)\n consume(_ContiguousArrayStorage<Dictionary<String, AnyObject>>.self)\n consume(_ContiguousArrayStorage<Int64>.self)\n consume(_ContiguousArrayStorage<String>.self)\n consume(Dictionary<String, String>.Index.self)\n consume(Dictionary<String, String>.Iterator.self)\n consume(Dictionary<AnyHashable, Any>.self)\n consume(Dictionary<AnyHashable, Any>.Iterator.self)\n consume(Dictionary<AnyHashable, AnyHashable>.self)\n consume(Dictionary<AnyHashable, AnyHashable>.Iterator.self)\n consume(Dictionary<AnyHashable, AnyObject>.self)\n consume(Dictionary<String, Any>.self)\n consume(Dictionary<String, Any>.Iterator.self)\n consume(Dictionary<String, AnyHashable>.self)\n consume(Dictionary<String, AnyObject>.self)\n consume(Dictionary<String, Array<String>>.self)\n consume(Dictionary<String, Dictionary<String, Any>>.self)\n consume(Dictionary<String, String>.self)\n consume(Dictionary<String, UInt8>.self)\n consume(IndexingIterator<Array<Dictionary<String, AnyObject>>>.self)\n consume(IndexingIterator<Array<Int>>.self)\n consume(IndexingIterator<Array<String>>.self)\n consume(IndexingIterator<ClosedRange<Int>>.self)\n consume(IndexingIterator<Range<Int>>.self)\n consume(IndexingIterator<String.UTF8View>.self)\n consume(Optional<()>.self)\n consume(Optional<(Any, Any)>.self)\n consume(Optional<(AnyHashable, Any)>.self)\n consume(Optional<(AnyHashable, AnyHashable)>.self)\n consume(Optional<(CodingUserInfoKey, Any)>.self)\n consume(Optional<(Int64, Bool)>.self)\n consume(Optional<(Optional<String>, Any)>.self)\n consume(Optional<(String, Any)>.self)\n consume(Optional<(String, AnyObject)>.self)\n consume(Optional<(String, Array<String>)>.self)\n consume(Optional<(String, Int64)>.self)\n consume(Optional<(String, String)>.self)\n consume(Optional<(String, UInt8)>.self)\n consume(Optional<Any>.self)\n consume(Optional<AnyObject>.self)\n consume(Optional<Array<Int64>>.self)\n consume(Optional<Array<String>>.self)\n consume(Optional<Bool>.self)\n consume(Optional<CodingKey>.self)\n consume(Optional<CodingUserInfoKey>.self)\n consume(Optional<CustomDebugStringConvertible>.self)\n#if SWIFT_ENABLE_REFLECTION\n consume(Optional<CustomReflectable>.self)\n#endif\n consume(Optional<CustomStringConvertible>.self)\n consume(Optional<Dictionary<AnyHashable, Any>>.self)\n consume(Optional<Dictionary<String, Any>>.self)\n consume(Optional<Dictionary<String, AnyObject>>.self)\n consume(Optional<Dictionary<String, Array<String>>>.self)\n consume(Optional<Dictionary<String, String>>.self)\n consume(Optional<Double>.self)\n consume(Optional<Int64>.self)\n consume(Optional<Int8>.self)\n#if SWIFT_ENABLE_REFLECTION\n consume(Optional<Mirror.DisplayStyle>.self)\n#endif\n consume(Optional<Optional<Int64>>.self)\n consume(Optional<Optional<String>>.self)\n consume(Optional<Set<String>>.self)\n consume(Optional<TextOutputStreamable>.self)\n consume(Optional<UInt8>.self)\n unsafe consume(Optional<UnsafeBufferPointer<AnyObject>>.self)\n consume(PartialRangeFrom<Int>.self)\n consume(Range<String.Index>.self)\n consume(ReversedCollection<Range<Int>>.self)\n consume(ReversedCollection<Range<Int>>.Iterator.self)\n consume(Set<Int>.self)\n consume(Set<String>.self)\n consume(Set<String>.Iterator.self)\n consume(Set<String>.self)\n unsafe consume(Unmanaged<AnyObject>.self)\n unsafe consume(UnsafeBufferPointer<AnyObject>.self)\n unsafe consume(UnsafeBufferPointer<Int8>.self)\n unsafe consume(UnsafePointer<Int8>.self)\n}\n\n@_specializeExtension\nextension Array {\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _endMutation(),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n mutating func __specialize_class__endMutation(){ Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _createNewBuffer(bufferIsUnique:minimumCapacity:growForAppend:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n mutating func __specialize_class__createNewBuffer(bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool) { Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _makeUniqueAndReserveCapacityIfNotUnique(),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n mutating func __specialize_class__makeUniqueAndReserveCapacityIfNotUnique() { Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _appendElementAssumeUniqueAndCapacity(_:newElement:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n mutating func __specialize_class__appendElementAssumeUniqueAndCapacity(_: Int, newElement: __owned Element) { Builtin.unreachable() }\n}\n\n#if _runtime(_ObjC)\n@_specializeExtension\nextension _ArrayBuffer {\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _consumeAndCreateNew(bufferIsUnique:minimumCapacity:growForAppend:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n func __specialize_class__consumeAndCreateNew(bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool) -> _ArrayBuffer<Element> { Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _copyContents(initializing:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n __consuming func __specialize_class__copyContents(\n initializing buffer: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) { Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _copyContents(subRange:initializing:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n __consuming func __specialize_class__copyContents(subRange: Range<Int>, initializing: Swift.UnsafeMutablePointer<Element>) -> Swift.UnsafeMutablePointer<Element> { Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _getElementSlowPath(_:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n func __specialize_class__getElementSlowPath(_ i: Int) -> AnyObject { Builtin.unreachable() }\n}\n#endif\n\n@_specializeExtension\nextension ContiguousArray {\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _endMutation(),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n mutating func __specialize_class__endMutation(){ Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _createNewBuffer(bufferIsUnique:minimumCapacity:growForAppend:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n mutating func __specialize_class__createNewBuffer(bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool) { Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _makeUniqueAndReserveCapacityIfNotUnique(),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n mutating func __specialize_class__makeUniqueAndReserveCapacityIfNotUnique() { Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _appendElementAssumeUniqueAndCapacity(_:newElement:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n mutating func __specialize_class__appendElementAssumeUniqueAndCapacity(_: Int, newElement: __owned Element) { Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _reserveCapacityImpl(minimumCapacity:growForAppend:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n mutating func __specialize_class__reserveCapacityImpl(minimumCapacity: Int, growForAppend: Bool) { Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _reserveCapacityAssumingUniqueBuffer(oldCount:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n mutating func __specialize_class__reserveCapacityAssumingUniqueBuffer(oldCount: Int) { Builtin.unreachable() }\n\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: reserveCapacity(_:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n mutating func __specialize_class__reserveCapacity(_ minimumCapacity: Int) { Builtin.unreachable() }\n}\n\n@_specializeExtension\nextension _ContiguousArrayBuffer {\n @_specialize(exported: true,\n availability: SwiftStdlib 5.9, *;\n target: _consumeAndCreateNew(bufferIsUnique:minimumCapacity:growForAppend:),\n where @_noMetadata Element : _Class)\n @available(SwiftStdlib 5.9, *)\n @usableFromInline\n func __specialize_class__consumeAndCreateNew(bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool) -> _ContiguousArrayBuffer<Element> { Builtin.unreachable() }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Prespecialize.swift
cpp_apple_swift_stdlib_public_core_Prespecialize.swift
Swift
11,333
0.8
0.015209
0.03252
python-kit
157
2025-03-10T16:22:04.562299
Apache-2.0
false
8c6184a17a9b170e6fc09bf7800620d3
//===--- Print.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#if !SWIFT_STDLIB_STATIC_PRINT\n\n/// Writes the textual representations of the given items into the standard\n/// output.\n///\n/// You can pass zero or more items to the `print(_:separator:terminator:)`\n/// function. The textual representation for each item is the same as that\n/// obtained by calling `String(describing: item)`. The following example\n/// prints a string, a closed range of integers, and a group of floating-point\n/// values to standard output:\n///\n/// print("One two three four five")\n/// // Prints "One two three four five"\n///\n/// print(1...5)\n/// // Prints "1...5"\n///\n/// print(1.0, 2.0, 3.0, 4.0, 5.0)\n/// // Prints "1.0 2.0 3.0 4.0 5.0"\n///\n/// To print the items separated by something other than a space, pass a string\n/// as `separator`.\n///\n/// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ")\n/// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0"\n///\n/// The output from each call to `print(_:separator:terminator:)` includes a\n/// newline by default. To print the items without a trailing newline, pass an\n/// empty string as `terminator`.\n///\n/// for n in 1...5 {\n/// print(n, terminator: "")\n/// }\n/// // Prints "12345"\n///\n/// - Parameters:\n/// - items: Zero or more items to print.\n/// - separator: A string to print between each item. The default is a single\n/// space (`" "`).\n/// - terminator: The string to print after all items have been printed. The\n/// default is a newline (`"\n"`).\npublic func print(\n _ items: Any...,\n separator: String = " ",\n terminator: String = "\n"\n) {\n if let hook = _playgroundPrintHook {\n var output = _TeeStream(left: "", right: _Stdout())\n _print(items, separator: separator, terminator: terminator, to: &output)\n hook(output.left)\n }\n else {\n var output = _Stdout()\n _print(items, separator: separator, terminator: terminator, to: &output)\n }\n}\n\n/// Writes the textual representations of the given items most suitable for\n/// debugging into the standard output.\n///\n/// You can pass zero or more items to the\n/// `debugPrint(_:separator:terminator:)` function. The textual representation\n/// for each item is the same as that obtained by calling\n/// `String(reflecting: item)`. The following example prints the debugging\n/// representation of a string, a closed range of integers, and a group of\n/// floating-point values to standard output:\n///\n/// debugPrint("One two three four five")\n/// // Prints "One two three four five"\n///\n/// debugPrint(1...5)\n/// // Prints "ClosedRange(1...5)"\n///\n/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0)\n/// // Prints "1.0 2.0 3.0 4.0 5.0"\n///\n/// To print the items separated by something other than a space, pass a string\n/// as `separator`.\n///\n/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ")\n/// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0"\n///\n/// The output from each call to `debugPrint(_:separator:terminator:)` includes\n/// a newline by default. To print the items without a trailing newline, pass\n/// an empty string as `terminator`.\n///\n/// for n in 1...5 {\n/// debugPrint(n, terminator: "")\n/// }\n/// // Prints "12345"\n///\n/// - Parameters:\n/// - items: Zero or more items to print.\n/// - separator: A string to print between each item. The default is a single\n/// space (`" "`).\n/// - terminator: The string to print after all items have been printed. The\n/// default is a newline (`"\n"`).\npublic func debugPrint(\n _ items: Any...,\n separator: String = " ",\n terminator: String = "\n"\n) {\n if let hook = _playgroundPrintHook {\n var output = _TeeStream(left: "", right: _Stdout())\n _debugPrint(items, separator: separator, terminator: terminator, to: &output)\n hook(output.left)\n }\n else {\n var output = _Stdout()\n _debugPrint(items, separator: separator, terminator: terminator, to: &output)\n }\n}\n\n/// Writes the textual representations of the given items into the given output\n/// stream.\n///\n/// You can pass zero or more items to the `print(_:separator:terminator:to:)`\n/// function. The textual representation for each item is the same as that\n/// obtained by calling `String(describing: item)`. The following example\n/// prints a closed range of integers to a string:\n///\n/// var range = "My range: "\n/// print(1...5, to: &range)\n/// // range == "My range: 1...5\n"\n///\n/// To print the items separated by something other than a space, pass a string\n/// as `separator`.\n///\n/// var separated = ""\n/// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated)\n/// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n"\n///\n/// The output from each call to `print(_:separator:terminator:to:)` includes a\n/// newline by default. To print the items without a trailing newline, pass an\n/// empty string as `terminator`.\n///\n/// var numbers = ""\n/// for n in 1...5 {\n/// print(n, terminator: "", to: &numbers)\n/// }\n/// // numbers == "12345"\n///\n/// - Parameters:\n/// - items: Zero or more items to print.\n/// - separator: A string to print between each item. The default is a single\n/// space (`" "`).\n/// - terminator: The string to print after all items have been printed. The\n/// default is a newline (`"\n"`).\n/// - output: An output stream to receive the text representation of each\n/// item.\npublic func print<Target: TextOutputStream>(\n _ items: Any...,\n separator: String = " ",\n terminator: String = "\n",\n to output: inout Target\n) {\n _print(items, separator: separator, terminator: terminator, to: &output)\n}\n\n/// Writes the textual representations of the given items most suitable for\n/// debugging into the given output stream.\n///\n/// You can pass zero or more items to the\n/// `debugPrint(_:separator:terminator:to:)` function. The textual\n/// representation for each item is the same as that obtained by calling\n/// `String(reflecting: item)`. The following example prints a closed range of\n/// integers to a string:\n///\n/// var range = "My range: "\n/// debugPrint(1...5, to: &range)\n/// // range == "My range: ClosedRange(1...5)\n"\n///\n/// To print the items separated by something other than a space, pass a string\n/// as `separator`.\n///\n/// var separated = ""\n/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated)\n/// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n"\n///\n/// The output from each call to `debugPrint(_:separator:terminator:to:)`\n/// includes a newline by default. To print the items without a trailing\n/// newline, pass an empty string as `terminator`.\n///\n/// var numbers = ""\n/// for n in 1...5 {\n/// debugPrint(n, terminator: "", to: &numbers)\n/// }\n/// // numbers == "12345"\n///\n/// - Parameters:\n/// - items: Zero or more items to print.\n/// - separator: A string to print between each item. The default is a single\n/// space (`" "`).\n/// - terminator: The string to print after all items have been printed. The\n/// default is a newline (`"\n"`).\n/// - output: An output stream to receive the text representation of each\n/// item.\npublic func debugPrint<Target: TextOutputStream>(\n _ items: Any...,\n separator: String = " ",\n terminator: String = "\n",\n to output: inout Target\n) {\n _debugPrint(items, separator: separator, terminator: terminator, to: &output)\n}\n\ninternal func _print<Target: TextOutputStream>(\n _ items: [Any],\n separator: String = " ",\n terminator: String = "\n",\n to output: inout Target\n) {\n var prefix = ""\n output._lock()\n defer { output._unlock() }\n for item in items {\n output.write(prefix)\n _print_unlocked(item, &output)\n prefix = separator\n }\n output.write(terminator)\n}\n\ninternal func _debugPrint<Target: TextOutputStream>(\n _ items: [Any],\n separator: String = " ",\n terminator: String = "\n",\n to output: inout Target\n) {\n var prefix = ""\n output._lock()\n defer { output._unlock() }\n for item in items {\n output.write(prefix)\n _debugPrint_unlocked(item, &output)\n prefix = separator\n }\n output.write(terminator)\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Print.swift
cpp_apple_swift_stdlib_public_core_Print.swift
Swift
8,640
0.95
0.083004
0.681633
python-kit
898
2025-06-25T08:17:55.110582
MIT
false
e16ddde83d9ade18d72f2af88a6133a1
//===----------------------------------------------------------------------===//\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/// Pseudo-namespace for pointer authentication primitives.\ninternal enum _PtrAuth {\n internal struct Key {\n var _value: Int32\n\n @_transparent\n init(_value: Int32) {\n self._value = _value\n }\n\n#if _ptrauth(_arm64e)\n @_transparent\n static var ASIA: Key { return Key(_value: 0) }\n @_transparent\n static var ASIB: Key { return Key(_value: 1) }\n @_transparent\n static var ASDA: Key { return Key(_value: 2) }\n @_transparent\n static var ASDB: Key { return Key(_value: 3) }\n\n /// A process-independent key which can be used to sign code pointers.\n /// Signing and authenticating with this key is a no-op in processes\n /// which disable ABI pointer authentication.\n @_transparent\n static var processIndependentCode: Key { return .ASIA }\n\n /// A process-specific key which can be used to sign code pointers.\n /// Signing and authenticating with this key is enforced even in processes\n /// which disable ABI pointer authentication.\n @_transparent\n static var processDependentCode: Key { return .ASIB }\n\n /// A process-independent key which can be used to sign data pointers.\n /// Signing and authenticating with this key is a no-op in processes\n /// which disable ABI pointer authentication.\n @_transparent\n static var processIndependentData: Key { return .ASDA }\n\n /// A process-specific key which can be used to sign data pointers.\n /// Signing and authenticating with this key is a no-op in processes\n /// which disable ABI pointer authentication.\n @_transparent\n static var processDependentData: Key { return .ASDB }\n#elseif _ptrauth(_none)\n /// A process-independent key which can be used to sign code pointers.\n /// Signing and authenticating with this key is a no-op in processes\n /// which disable ABI pointer authentication.\n @_transparent\n static var processIndependentCode: Key { return Key(_value: 0) }\n\n /// A process-specific key which can be used to sign code pointers.\n /// Signing and authenticating with this key is enforced even in processes\n /// which disable ABI pointer authentication.\n @_transparent\n static var processDependentCode: Key { return Key(_value: 0) }\n\n /// A process-independent key which can be used to sign data pointers.\n /// Signing and authenticating with this key is a no-op in processes\n /// which disable ABI pointer authentication.\n @_transparent\n static var processIndependentData: Key { return Key(_value: 0) }\n\n /// A process-specific key which can be used to sign data pointers.\n /// Signing and authenticating with this key is a no-op in processes\n /// which disable ABI pointer authentication.\n @_transparent\n static var processDependentData: Key { return Key(_value: 0) }\n#else\n #error("unsupported ptrauth scheme")\n#endif\n }\n\n#if _ptrauth(_arm64e)\n /// Blend a pointer and a small integer to form a new extra-data\n /// discriminator. Not all bits of the inputs are guaranteed to\n /// contribute to the result.\n @_transparent\n static func blend(pointer: UnsafeRawPointer,\n discriminator: UInt64) -> UInt64 {\n return UInt64(Builtin.int_ptrauth_blend(\n UInt64(UInt(bitPattern: pointer))._value,\n discriminator._value))\n }\n\n /// Sign an unauthenticated pointer.\n @_semantics("no.preserve.debugger") // Relies on inlining this function.\n @_transparent\n static func sign(pointer: UnsafeRawPointer,\n key: Key,\n discriminator: UInt64) -> UnsafeRawPointer {\n let bitPattern = UInt64(Builtin.int_ptrauth_sign(\n UInt64(UInt(bitPattern: pointer))._value,\n key._value._value,\n discriminator._value))\n\n return unsafe UnsafeRawPointer(bitPattern:\n UInt(truncatingIfNeeded: bitPattern)).unsafelyUnwrapped\n }\n\n /// Authenticate a pointer using one scheme and resign it using another.\n @_transparent\n @_semantics("no.preserve.debugger") // Relies on inlining this function.\n static func authenticateAndResign(pointer: UnsafeRawPointer,\n oldKey: Key,\n oldDiscriminator: UInt64,\n newKey: Key,\n newDiscriminator: UInt64) -> UnsafeRawPointer {\n let bitPattern = UInt64(Builtin.int_ptrauth_resign(\n UInt64(UInt(bitPattern: pointer))._value,\n oldKey._value._value,\n oldDiscriminator._value,\n newKey._value._value,\n newDiscriminator._value))\n\n return unsafe UnsafeRawPointer(bitPattern:\n UInt(truncatingIfNeeded: bitPattern)).unsafelyUnwrapped\n }\n\n /// Get the type-specific discriminator for a function type.\n @_semantics("no.preserve.debugger") // Don't keep the generic version alive\n @_transparent\n static func discriminator<T>(for type: T.Type) -> UInt64 {\n return UInt64(Builtin.typePtrAuthDiscriminator(type))\n }\n\n#elseif _ptrauth(_none)\n /// Blend a pointer and a small integer to form a new extra-data\n /// discriminator. Not all bits of the inputs are guaranteed to\n /// contribute to the result.\n @_transparent\n static func blend(pointer _: UnsafeRawPointer,\n discriminator _: UInt64) -> UInt64{\n return 0\n }\n\n /// Sign an unauthenticated pointer.\n @_transparent\n static func sign(pointer: UnsafeRawPointer,\n key: Key,\n discriminator: UInt64) -> UnsafeRawPointer {\n return unsafe pointer\n }\n\n /// Authenticate a pointer using one scheme and resign it using another.\n @_transparent\n static func authenticateAndResign(pointer: UnsafeRawPointer,\n oldKey: Key,\n oldDiscriminator: UInt64,\n newKey: Key,\n newDiscriminator: UInt64) -> UnsafeRawPointer {\n return unsafe pointer\n }\n\n /// Get the type-specific discriminator for a function type.\n @_transparent\n static func discriminator<T>(for type: T.Type) -> UInt64 {\n return 0\n }\n#else\n #error("Unsupported ptrauth scheme")\n#endif\n}\n\n// Helpers for working with authenticated function pointers.\n\nextension UnsafeRawPointer {\n /// Load a function pointer from memory that has been authenticated\n /// specifically for its given address.\n @_semantics("no.preserve.debugger") // Don't keep the generic version alive\n @_transparent\n internal func _loadAddressDiscriminatedFunctionPointer<T>(\n fromByteOffset offset: Int = 0,\n as type: T.Type,\n discriminator: UInt64\n ) -> T {\n let src = unsafe self + offset\n\n let srcDiscriminator = unsafe _PtrAuth.blend(pointer: src,\n discriminator: discriminator)\n let ptr = unsafe src.load(as: UnsafeRawPointer.self)\n let resigned = unsafe _PtrAuth.authenticateAndResign(\n pointer: ptr,\n oldKey: .processIndependentCode,\n oldDiscriminator: srcDiscriminator,\n newKey: .processIndependentCode,\n newDiscriminator: _PtrAuth.discriminator(for: type))\n\n return unsafe unsafeBitCast(resigned, to: type)\n }\n\n @_semantics("no.preserve.debugger") // Don't keep the generic version alive\n @_transparent\n internal func _loadAddressDiscriminatedFunctionPointer<T>(\n fromByteOffset offset: Int = 0,\n as type: Optional<T>.Type,\n discriminator: UInt64\n ) -> Optional<T> {\n let src = unsafe self + offset\n\n let srcDiscriminator = unsafe _PtrAuth.blend(pointer: src,\n discriminator: discriminator)\n guard let ptr = unsafe src.load(as: Optional<UnsafeRawPointer>.self) else {\n return nil\n }\n let resigned = unsafe _PtrAuth.authenticateAndResign(\n pointer: ptr,\n oldKey: .processIndependentCode,\n oldDiscriminator: srcDiscriminator,\n newKey: .processIndependentCode,\n newDiscriminator: _PtrAuth.discriminator(for: T.self))\n\n return unsafe .some(unsafeBitCast(resigned, to: T.self))\n }\n\n}\n\nextension UnsafeMutableRawPointer {\n /// Copy a function pointer from memory that has been authenticated\n /// specifically for its given address.\n internal func _copyAddressDiscriminatedFunctionPointer(\n from src: UnsafeRawPointer,\n discriminator: UInt64\n ) {\n if unsafe src == UnsafeRawPointer(self) { return }\n\n let srcDiscriminator = unsafe _PtrAuth.blend(pointer: src,\n discriminator: discriminator)\n let destDiscriminator = unsafe _PtrAuth.blend(pointer: self,\n discriminator: discriminator)\n\n let ptr = unsafe src.load(as: UnsafeRawPointer.self)\n let resigned = unsafe _PtrAuth.authenticateAndResign(\n pointer: ptr,\n oldKey: .processIndependentCode,\n oldDiscriminator: srcDiscriminator,\n newKey: .processIndependentCode,\n newDiscriminator: destDiscriminator)\n\n unsafe storeBytes(of: resigned, as: UnsafeRawPointer.self)\n }\n\n @_transparent\n internal func _storeFunctionPointerWithAddressDiscrimination(\n _ unsignedPointer: UnsafeRawPointer,\n discriminator: UInt64\n ) {\n let destDiscriminator = unsafe _PtrAuth.blend(pointer: self,\n discriminator: discriminator)\n let signed = unsafe _PtrAuth.sign(pointer: unsignedPointer,\n key: .processIndependentCode,\n discriminator: destDiscriminator)\n unsafe storeBytes(of: signed, as: UnsafeRawPointer.self)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_PtrAuth.swift
cpp_apple_swift_stdlib_public_core_PtrAuth.swift
Swift
9,990
0.95
0.082707
0.270386
awesome-app
220
2024-05-29T13:16:35.748420
GPL-3.0
false
4dd08cc61a7ff2e1ac0b126f2e5ddeeb
//===--- Random.swift -----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 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/// A type that provides uniformly distributed random data.\n///\n/// When you call methods that use random data, such as creating new random\n/// values or shuffling a collection, you can pass a `RandomNumberGenerator`\n/// type to be used as the source for randomness. When you don't pass a\n/// generator, the default `SystemRandomNumberGenerator` type is used.\n///\n/// When providing new APIs that use randomness, provide a version that accepts\n/// a generator conforming to the `RandomNumberGenerator` protocol as well as a\n/// version that uses the default system generator. For example, this `Weekday`\n/// enumeration provides static methods that return a random day of the week:\n///\n/// enum Weekday: CaseIterable {\n/// case sunday, monday, tuesday, wednesday, thursday, friday, saturday\n///\n/// static func random<G: RandomNumberGenerator>(using generator: inout G) -> Weekday {\n/// return Weekday.allCases.randomElement(using: &generator)!\n/// }\n///\n/// static func random() -> Weekday {\n/// var g = SystemRandomNumberGenerator()\n/// return Weekday.random(using: &g)\n/// }\n/// }\n///\n/// Conforming to the RandomNumberGenerator Protocol\n/// ================================================\n///\n/// A custom `RandomNumberGenerator` type can have different characteristics\n/// than the default `SystemRandomNumberGenerator` type. For example, a\n/// seedable generator can be used to generate a repeatable sequence of random\n/// values for testing purposes.\n///\n/// To make a custom type conform to the `RandomNumberGenerator` protocol,\n/// implement the required `next()` method. Each call to `next()` must produce\n/// a uniform and independent random value.\n///\n/// Types that conform to `RandomNumberGenerator` should specifically document\n/// the thread safety and quality of the generator.\npublic protocol RandomNumberGenerator {\n /// Returns a value from a uniform, independent distribution of binary data.\n ///\n /// Use this method when you need random binary data to generate another\n /// value. If you need an integer value within a specific range, use the\n /// static `random(in:using:)` method on that integer type instead of this\n /// method.\n ///\n /// - Returns: An unsigned 64-bit random value.\n mutating func next() -> UInt64\n}\n\nextension RandomNumberGenerator {\n \n // An unavailable default implementation of next() prevents types that do\n // not implement the RandomNumberGenerator interface from conforming to the\n // protocol; without this, the default next() method returning a generic\n // unsigned integer will be used, recursing infinitely and probably blowing\n // the stack.\n @available(*, unavailable)\n @_alwaysEmitIntoClient\n public mutating func next() -> UInt64 { fatalError() }\n \n /// Returns a value from a uniform, independent distribution of binary data.\n ///\n /// Use this method when you need random binary data to generate another\n /// value. If you need an integer value within a specific range, use the\n /// static `random(in:using:)` method on that integer type instead of this\n /// method.\n ///\n /// - Returns: A random value of `T`. Bits are randomly distributed so that\n /// every value of `T` is equally likely to be returned.\n @inlinable\n public mutating func next<T: FixedWidthInteger & UnsignedInteger>() -> T {\n return T._random(using: &self)\n }\n\n /// Returns a random value that is less than the given upper bound.\n ///\n /// Use this method when you need random binary data to generate another\n /// value. If you need an integer value within a specific range, use the\n /// static `random(in:using:)` method on that integer type instead of this\n /// method.\n ///\n /// - Parameter upperBound: The upper bound for the randomly generated value.\n /// Must be non-zero.\n /// - Returns: A random value of `T` in the range `0..<upperBound`. Every\n /// value in the range `0..<upperBound` is equally likely to be returned.\n @inlinable\n public mutating func next<T: FixedWidthInteger & UnsignedInteger>(\n upperBound: T\n ) -> T {\n _precondition(upperBound != 0, "upperBound cannot be zero.")\n // We use Lemire's "nearly divisionless" method for generating random\n // integers in an interval. For a detailed explanation, see:\n // https://arxiv.org/abs/1805.10941\n var random: T = next()\n var m = random.multipliedFullWidth(by: upperBound)\n if m.low < upperBound {\n let t = (0 &- upperBound) % upperBound\n while m.low < t {\n random = next()\n m = random.multipliedFullWidth(by: upperBound)\n }\n }\n return m.high\n }\n}\n\n/// The system's default source of random data.\n///\n/// When you generate random values, shuffle a collection, or perform another\n/// operation that depends on random data, this type is the generator used by\n/// default. For example, the two method calls in this example are equivalent:\n///\n/// let x = Int.random(in: 1...100)\n/// var g = SystemRandomNumberGenerator()\n/// let y = Int.random(in: 1...100, using: &g)\n///\n/// `SystemRandomNumberGenerator` is automatically seeded, is safe to use in\n/// multiple threads, and uses a cryptographically secure algorithm whenever\n/// possible.\n///\n/// Platform Implementation of `SystemRandomNumberGenerator`\n/// ========================================================\n///\n/// While the system generator is automatically seeded and thread-safe on every\n/// platform, the cryptographic quality of the stream of random data produced by\n/// the generator may vary. For more detail, see the documentation for the APIs\n/// used by each platform.\n///\n/// - Apple platforms use `arc4random_buf(3)`.\n/// - Linux platforms use `getrandom(2)` when available; otherwise, they read\n/// from `/dev/urandom`.\n/// - Windows uses `BCryptGenRandom`.\n@frozen\npublic struct SystemRandomNumberGenerator: RandomNumberGenerator, Sendable {\n /// Creates a new instance of the system's default random number generator.\n @inlinable\n public init() { }\n\n /// Returns a value from a uniform, independent distribution of binary data.\n ///\n /// - Returns: An unsigned 64-bit random value.\n @inlinable\n public mutating func next() -> UInt64 {\n var random: UInt64 = 0\n unsafe _withUnprotectedUnsafeMutablePointer(to: &random) {\n unsafe swift_stdlib_random($0, MemoryLayout<UInt64>.size)\n }\n return random\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Random.swift
cpp_apple_swift_stdlib_public_core_Random.swift
Swift
6,943
0.95
0.054217
0.734177
vue-tools
36
2024-05-26T12:33:04.196725
GPL-3.0
false
5cb97400955e2e3b38f7c57cc8453b97
//===----------------------------------------------------------------------===//\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 efficient random-access index traversal.\n///\n/// Random-access collections can move indices any distance and \n/// measure the distance between indices in O(1) time. Therefore, the\n/// fundamental difference between random-access and bidirectional collections\n/// is that operations that depend on index movement or distance measurement\n/// offer significantly improved efficiency. For example, a random-access\n/// collection's `count` property is calculated in O(1) instead of requiring\n/// iteration of an entire collection.\n///\n/// Conforming to the RandomAccessCollection Protocol\n/// =================================================\n///\n/// The `RandomAccessCollection` protocol adds further constraints on the\n/// associated `Indices` and `SubSequence` types, but otherwise imposes no\n/// additional requirements over the `BidirectionalCollection` protocol.\n/// However, in order to meet the complexity guarantees of a random-access\n/// collection, either the index for your custom type must conform to the\n/// `Strideable` protocol or you must implement the `index(_:offsetBy:)` and\n/// `distance(from:to:)` methods with O(1) efficiency.\npublic protocol RandomAccessCollection<Element>: BidirectionalCollection\nwhere SubSequence: RandomAccessCollection, Indices: RandomAccessCollection\n{\n // FIXME: Associated type inference requires these.\n override associatedtype Element\n override associatedtype Index\n override associatedtype SubSequence\n override associatedtype 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 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: Associated type inference requires these.\n @_borrowed\n override subscript(position: Index) -> Element { get }\n override var startIndex: Index { get }\n override var endIndex: Index { get }\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 override 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 override 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)\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)\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)\n @_nonoverride func distance(from start: Index, to end: Index) -> Int\n}\n\n// TODO: swift-3-indexing-model - (By creating an ambiguity?), try to\n// make sure RandomAccessCollection models implement\n// index(_:offsetBy:) and distance(from:to:), or they will get the\n// wrong complexity.\n\n/// Default implementation for random access collections.\nextension RandomAccessCollection {\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 /// let i = numbers.index(numbers.startIndex, offsetBy: 4)\n /// print(numbers[i])\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` should be greater than `i` to have any\n /// effect. Likewise, if `distance < 0`, `limit` should be less than `i`\n /// to have any 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)\n @inlinable\n public func index(\n _ i: Index, offsetBy distance: Int, limitedBy limit: Index\n ) -> Index? {\n // FIXME: swift-3-indexing-model: tests.\n let l = self.distance(from: i, to: limit)\n if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l {\n return nil\n }\n return index(i, offsetBy: distance)\n }\n}\n\n// Provides an alternative default associated type witness for Indices\n// for random access collections with strideable indices.\nextension RandomAccessCollection where Index: Strideable, Index.Stride == Int {\n @_implements(Collection, Indices)\n public typealias _Default_Indices = Range<Index>\n}\n\nextension RandomAccessCollection\nwhere Index: Strideable,\n Index.Stride == Int,\n Indices == Range<Index> {\n\n /// The indices that are valid for subscripting the collection, in ascending\n /// order.\n @inlinable\n public var indices: Range<Index> {\n return startIndex..<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 value immediately after `i`.\n @inlinable\n public func index(after i: Index) -> Index {\n // FIXME: swift-3-indexing-model: tests for the trap.\n unsafe _failEarlyRangeCheck(\n i, bounds: Range(uncheckedBounds: (startIndex, endIndex)))\n return i.advanced(by: 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 greater than\n /// `startIndex`.\n /// - Returns: The index value immediately before `i`.\n @inlinable // protocol-only\n public func index(before i: Index) -> Index {\n let result = i.advanced(by: -1)\n // FIXME: swift-3-indexing-model: tests for the trap.\n unsafe _failEarlyRangeCheck(\n result, bounds: Range(uncheckedBounds: (startIndex, endIndex)))\n return result\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 collection.\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 ///\n /// - Complexity: O(1)\n @inlinable\n public func index(_ i: Index, offsetBy distance: Index.Stride) -> Index {\n let result = i.advanced(by: distance)\n // This range check is not precise, tighter bounds exist based on `n`.\n // Unfortunately, we would need to perform index manipulation to\n // compute those bounds, which is probably too slow in the general\n // case.\n // FIXME: swift-3-indexing-model: tests for the trap.\n unsafe _failEarlyRangeCheck(\n result, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex)))\n return result\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 ///\n /// - Complexity: O(1)\n @inlinable\n public func distance(from start: Index, to end: Index) -> Index.Stride {\n // FIXME: swift-3-indexing-model: tests for traps.\n unsafe _failEarlyRangeCheck(\n start, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex)))\n unsafe _failEarlyRangeCheck(\n end, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex)))\n return start.distance(to: end)\n }\n}\n\n\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_RandomAccessCollection.swift
cpp_apple_swift_stdlib_public_core_RandomAccessCollection.swift
Swift
15,211
0.95
0.056604
0.782235
awesome-app
802
2025-05-05T04:56:03.948669
BSD-3-Clause
false
71c2fc2e53f821f884b41687a5d6fb14
//===--- Range.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 type that can be used to slice a collection.\n///\n/// A type that conforms to `RangeExpression` can convert itself to a\n/// `Range<Bound>` of indices within a given collection.\npublic protocol RangeExpression<Bound> {\n /// The type for which the expression describes a range.\n associatedtype Bound: Comparable\n\n /// Returns the range of indices described by this range expression within\n /// the given collection.\n ///\n /// You can use the `relative(to:)` method to convert a range expression,\n /// which could be missing one or both of its endpoints, into a concrete\n /// range that is bounded on both sides. The following example uses this\n /// method to convert a partial range up to `4` into a half-open range,\n /// using an array instance to add the range's lower bound.\n ///\n /// let numbers = [10, 20, 30, 40, 50, 60, 70]\n /// let upToFour = ..<4\n ///\n /// let r1 = upToFour.relative(to: numbers)\n /// // r1 == 0..<4\n ///\n /// The `r1` range is bounded on the lower end by `0` because that is the\n /// starting index of the `numbers` array. When the collection passed to\n /// `relative(to:)` starts with a different index, that index is used as the\n /// lower bound instead. The next example creates a slice of `numbers`\n /// starting at index `2`, and then uses the slice with `relative(to:)` to\n /// convert `upToFour` to a concrete range.\n ///\n /// let numbersSuffix = numbers[2...]\n /// // numbersSuffix == [30, 40, 50, 60, 70]\n ///\n /// let r2 = upToFour.relative(to: numbersSuffix)\n /// // r2 == 2..<4\n ///\n /// Use this method only if you need the concrete range it produces. To\n /// access a slice of a collection using a range expression, use the\n /// collection's generic subscript that uses a range expression as its\n /// parameter.\n ///\n /// let numbersPrefix = numbers[upToFour]\n /// // numbersPrefix == [10, 20, 30, 40]\n ///\n /// - Parameter collection: The collection to evaluate this range expression\n /// in relation to.\n /// - Returns: A range suitable for slicing `collection`. The returned range\n /// is *not* guaranteed to be inside the bounds of `collection`. Callers\n /// should apply the same preconditions to the return value as they would\n /// to a range provided directly by the user.\n func relative<C: Collection>(\n to collection: C\n ) -> Range<Bound> where C.Index == Bound\n \n /// Returns a Boolean value indicating whether the given element is contained\n /// within the range expression.\n ///\n /// - Parameter element: The element to check for containment.\n /// - Returns: `true` if `element` is contained in the range expression;\n /// otherwise, `false`.\n func contains(_ element: Bound) -> Bool\n}\n\nextension RangeExpression {\n\n /// Returns a Boolean value indicating whether a value is included in a\n /// range.\n ///\n /// You can use the pattern-matching operator (`~=`) to test whether a value\n /// is included in a range. The pattern-matching operator is used\n /// internally in `case` statements for pattern matching. The following\n /// example uses the `~=` operator to test whether an integer is included in\n /// a range of single-digit numbers:\n ///\n /// let chosenNumber = 3\n /// if 0..<10 ~= chosenNumber {\n /// print("\(chosenNumber) is a single digit.")\n /// }\n /// // Prints "3 is a single digit."\n ///\n /// - Parameters:\n /// - pattern: A range.\n /// - bound: A value to match against `pattern`.\n @inlinable\n public static func ~= (pattern: Self, value: Bound) -> Bool {\n return pattern.contains(value)\n } \n}\n\n/// A half-open interval from a lower bound up to, but not including, an upper\n/// bound.\n///\n/// You create a `Range` instance by using the half-open range operator\n/// (`..<`).\n///\n/// let underFive = 0.0..<5.0\n///\n/// You can use a `Range` instance to quickly check if a value is contained in\n/// a particular range of values. For example:\n///\n/// underFive.contains(3.14)\n/// // true\n/// underFive.contains(6.28)\n/// // false\n/// underFive.contains(5.0)\n/// // false\n///\n/// `Range` instances can represent an empty interval, unlike `ClosedRange`.\n///\n/// let empty = 0.0..<0.0\n/// empty.contains(0.0)\n/// // false\n/// empty.isEmpty\n/// // true\n///\n/// Using a Range as a Collection of Consecutive Values\n/// ----------------------------------------------------\n///\n/// When a range uses integers as its lower and upper bounds, or any other type\n/// that conforms to the `Strideable` protocol with an integer stride, you can\n/// use that range in a `for`-`in` loop or with any sequence or collection\n/// method. The elements of the range are the consecutive values from its\n/// lower bound up to, but not including, its upper bound.\n///\n/// for n in 3..<5 {\n/// print(n)\n/// }\n/// // Prints "3"\n/// // Prints "4"\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:to:by:)` function.\n@frozen\npublic struct Range<Bound: Comparable> {\n /// The range's lower bound.\n ///\n /// In an empty range, `lowerBound` is equal to `upperBound`.\n public let lowerBound: Bound\n\n /// The range's upper bound.\n ///\n /// In an empty range, `upperBound` is equal to `lowerBound`. A `Range`\n /// instance does not contain its 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 half-open range operator\n /// (`..<`) to form `Range` 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 "Range requires lowerBound <= upperBound")\n unsafe self.init(\n _uncheckedBounds: (lower: bounds.lower, upper: bounds.upper)\n )\n }\n\n /// Returns a Boolean value indicating whether the given element is contained\n /// within the range.\n ///\n /// Because `Range` represents a half-open range, a `Range` instance does not\n /// contain its upper bound. `element` is contained in the range if it is\n /// greater than or equal to the lower bound and less than the upper 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 lowerBound <= element && element < upperBound\n }\n\n /// A Boolean value indicating whether the range contains no elements.\n ///\n /// An empty `Range` instance has equal lower and upper bounds.\n ///\n /// let empty: Range = 10..<10\n /// print(empty.isEmpty)\n /// // Prints "true"\n @inlinable\n public var isEmpty: Bool {\n return lowerBound == upperBound\n }\n}\n\nextension Range: Sequence\nwhere Bound: Strideable, Bound.Stride: SignedInteger {\n public typealias Element = Bound\n public typealias Iterator = IndexingIterator<Range<Bound>>\n}\n\nextension Range: Collection, BidirectionalCollection, RandomAccessCollection\nwhere Bound: Strideable, Bound.Stride: SignedInteger\n{\n /// A type that represents a position in the range.\n public typealias Index = Bound\n public typealias Indices = Range<Bound>\n public typealias SubSequence = Range<Bound>\n\n @inlinable\n public var startIndex: Index { return lowerBound }\n\n @inlinable\n public var endIndex: Index { return upperBound }\n\n @inlinable\n @inline(__always)\n public func index(after i: Index) -> Index {\n _failEarlyRangeCheck(i, bounds: startIndex..<endIndex)\n\n return i.advanced(by: 1)\n }\n\n @inlinable\n public func index(before i: Index) -> Index {\n _precondition(i > lowerBound)\n _precondition(i <= upperBound)\n\n return i.advanced(by: -1)\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy n: Int) -> Index {\n let r = i.advanced(by: numericCast(n))\n _precondition(r >= lowerBound)\n _precondition(r <= upperBound)\n return r\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n return numericCast(start.distance(to: end))\n }\n\n /// Accesses the subsequence bounded by the given range.\n ///\n /// - Parameter bounds: A range of the range's indices. The upper and lower\n /// bounds of the `bounds` range must be valid indices of the collection.\n @inlinable\n public subscript(bounds: Range<Index>) -> Range<Bound> {\n return bounds\n }\n\n /// The indices that are valid for subscripting the range, in ascending\n /// order.\n @inlinable\n public var indices: Indices {\n return self\n }\n\n @inlinable\n public func _customContainsEquatableElement(_ element: Element) -> Bool? {\n return lowerBound <= element && element < upperBound\n }\n\n @inlinable\n public func _customIndexOfEquatableElement(_ element: Bound) -> Index?? {\n return lowerBound <= element && element < upperBound ? 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 /// 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) -> Element {\n // FIXME: swift-3-indexing-model: tests for the range check.\n _debugPrecondition(self.contains(position), "Index out of range")\n return position\n }\n}\n\nextension Range where Bound: Strideable, Bound.Stride: SignedInteger {\n /// Creates an instance equivalent to the given `ClosedRange`.\n ///\n /// - Parameter other: A closed range to convert to a `Range` instance.\n ///\n /// An equivalent range must be representable as an instance of Range<Bound>.\n /// For example, passing a closed range with an upper bound of `Int.max`\n /// triggers a runtime error, because the resulting half-open range would\n /// require an upper bound of `Int.max + 1`, which is not representable as\n /// an `Int`.\n @inlinable // trivial-implementation\n public init(_ other: ClosedRange<Bound>) {\n let upperBound = other.upperBound.advanced(by: 1)\n unsafe self.init(\n _uncheckedBounds: (lower: other.lowerBound, upper: upperBound)\n )\n }\n}\n\nextension Range: RangeExpression {\n /// Returns the range of indices described by this range expression within\n /// the given collection.\n ///\n /// - Parameter collection: The collection to evaluate this range expression\n /// in relation to.\n /// - Returns: A range suitable for slicing `collection`. The returned range\n /// is *not* guaranteed to be inside the bounds of `collection`. Callers\n /// should apply the same preconditions to the return value as they would\n /// to a range provided directly by the user.\n @inlinable // trivial-implementation\n public func relative<C: Collection>(to collection: C) -> Range<Bound>\n where C.Index == Bound {\n self\n }\n}\n\nextension Range {\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: Range = 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 an empty range within the\n /// bounds of `limits`.\n ///\n /// let y: Range = 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: Range) -> Range {\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 Range(_uncheckedBounds: (lower: lower, upper: upper))\n }\n}\n\n@_unavailableInEmbedded\nextension Range: 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 Range: CustomDebugStringConvertible {\n /// A textual representation of the range, suitable for debugging.\n public var debugDescription: String {\n return "Range(\(String(reflecting: lowerBound))"\n + "..<\(String(reflecting: upperBound)))"\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension Range: CustomReflectable {\n public var customMirror: Mirror {\n return Mirror(\n self, children: ["lowerBound": lowerBound, "upperBound": upperBound])\n }\n}\n#endif\n\nextension Range: 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 /// That requirement holds even for empty ranges.\n ///\n /// let x = 5..<15\n /// print(x == 5..<15)\n /// // Prints "true"\n ///\n /// let y = 5..<5\n /// print(y == 15..<15)\n /// // Prints "false"\n ///\n /// - Parameters:\n /// - lhs: A range to compare.\n /// - rhs: Another range to compare.\n @inlinable\n public static func == (lhs: Range<Bound>, rhs: Range<Bound>) -> Bool {\n return\n lhs.lowerBound == rhs.lowerBound &&\n lhs.upperBound == rhs.upperBound\n }\n}\n\nextension Range: Hashable where 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 hasher.combine(lowerBound)\n hasher.combine(upperBound)\n }\n}\n\n@_unavailableInEmbedded\nextension Range: 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 \(Range.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 Range: 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\n/// A partial half-open interval up to, but not including, an upper bound.\n///\n/// You create `PartialRangeUpTo` instances by using the prefix half-open range\n/// operator (prefix `..<`).\n///\n/// let upToFive = ..<5.0\n///\n/// You can use a `PartialRangeUpTo` instance to quickly check if a value is\n/// contained in a particular range of values. For example:\n///\n/// upToFive.contains(3.14) // true\n/// upToFive.contains(6.28) // false\n/// upToFive.contains(5.0) // false\n///\n/// You can use a `PartialRangeUpTo` instance of a collection's indices to\n/// represent the range from the start of the collection up to, but not\n/// including, the partial range's upper bound.\n///\n/// let numbers = [10, 20, 30, 40, 50, 60, 70]\n/// print(numbers[..<3])\n/// // Prints "[10, 20, 30]"\n@frozen\npublic struct PartialRangeUpTo<Bound: Comparable> {\n public let upperBound: Bound\n \n @inlinable // trivial-implementation\n public init(_ upperBound: Bound) { self.upperBound = upperBound }\n}\n\nextension PartialRangeUpTo: RangeExpression {\n @_transparent\n public func relative<C: Collection>(to collection: C) -> Range<Bound>\n where C.Index == Bound {\n return collection.startIndex..<self.upperBound\n }\n \n @_transparent\n public func contains(_ element: Bound) -> Bool {\n return element < upperBound\n }\n}\n\n@_unavailableInEmbedded\nextension PartialRangeUpTo: Decodable where Bound: Decodable {\n public init(from decoder: Decoder) throws {\n var container = try decoder.unkeyedContainer()\n try self.init(container.decode(Bound.self))\n }\n}\n\n@_unavailableInEmbedded\nextension PartialRangeUpTo: Encodable where Bound: Encodable {\n public func encode(to encoder: Encoder) throws {\n var container = encoder.unkeyedContainer()\n try container.encode(self.upperBound)\n }\n}\n\n/// A partial interval up to, and including, an upper bound.\n///\n/// You create `PartialRangeThrough` instances by using the prefix closed range\n/// operator (prefix `...`).\n///\n/// let throughFive = ...5.0\n///\n/// You can use a `PartialRangeThrough` instance to quickly check if a value is\n/// contained in a particular range of values. For example:\n///\n/// throughFive.contains(4.0) // true\n/// throughFive.contains(5.0) // true\n/// throughFive.contains(6.0) // false\n///\n/// You can use a `PartialRangeThrough` instance of a collection's indices to\n/// represent the range from the start of the collection up to, and including,\n/// the partial range's upper bound.\n///\n/// let numbers = [10, 20, 30, 40, 50, 60, 70]\n/// print(numbers[...3])\n/// // Prints "[10, 20, 30, 40]"\n@frozen\npublic struct PartialRangeThrough<Bound: Comparable> { \n public let upperBound: Bound\n \n @inlinable // trivial-implementation\n public init(_ upperBound: Bound) { self.upperBound = upperBound }\n}\n\nextension PartialRangeThrough: RangeExpression {\n @_transparent\n public func relative<C: Collection>(to collection: C) -> Range<Bound>\n where C.Index == Bound {\n return collection.startIndex..<collection.index(after: self.upperBound)\n }\n @_transparent\n public func contains(_ element: Bound) -> Bool {\n return element <= upperBound\n }\n}\n\n@_unavailableInEmbedded\nextension PartialRangeThrough: Decodable where Bound: Decodable {\n public init(from decoder: Decoder) throws {\n var container = try decoder.unkeyedContainer()\n try self.init(container.decode(Bound.self))\n }\n}\n\n@_unavailableInEmbedded\nextension PartialRangeThrough: Encodable where Bound: Encodable {\n public func encode(to encoder: Encoder) throws {\n var container = encoder.unkeyedContainer()\n try container.encode(self.upperBound)\n }\n}\n\n/// A partial interval extending upward from a lower bound.\n///\n/// You create `PartialRangeFrom` instances by using the postfix range operator\n/// (postfix `...`).\n///\n/// let atLeastFive = 5...\n///\n/// You can use a partial range to quickly check if a value is contained in a\n/// particular range of values. For example:\n///\n/// atLeastFive.contains(4)\n/// // false\n/// atLeastFive.contains(5)\n/// // true\n/// atLeastFive.contains(6)\n/// // true\n///\n/// You can use a partial range of a collection's indices to represent the\n/// range from the partial range's lower bound up to the end of the\n/// collection.\n///\n/// let numbers = [10, 20, 30, 40, 50, 60, 70]\n/// print(numbers[3...])\n/// // Prints "[40, 50, 60, 70]"\n///\n/// Using a Partial Range as a Sequence\n/// -----------------------------------\n///\n/// When a partial 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\n/// method that doesn't require that the sequence is finite. The elements of\n/// a partial range are the consecutive values from its lower bound continuing\n/// upward indefinitely.\n///\n/// func isTheMagicNumber(_ x: Int) -> Bool {\n/// return x == 3\n/// }\n///\n/// for x in 1... {\n/// if isTheMagicNumber(x) {\n/// print("\(x) is the magic number!")\n/// break\n/// } else {\n/// print("\(x) wasn't it...")\n/// }\n/// }\n/// // "1 wasn't it..."\n/// // "2 wasn't it..."\n/// // "3 is the magic number!"\n///\n/// Because a `PartialRangeFrom` sequence counts upward indefinitely, do not\n/// use one with methods that read the entire sequence before returning, such\n/// as `map(_:)`, `filter(_:)`, or `suffix(_:)`. It is safe to use operations\n/// that put an upper limit on the number of elements they access, such as\n/// `prefix(_:)` or `dropFirst(_:)`, and operations that you can guarantee\n/// will terminate, such as passing a closure you know will eventually return\n/// `true` to `first(where:)`.\n///\n/// In the following example, the `asciiTable` sequence is made by zipping\n/// together the characters in the `alphabet` string with a partial range\n/// starting at 65, the ASCII value of the capital letter A. Iterating over\n/// two zipped sequences continues only as long as the shorter of the two\n/// sequences, so the iteration stops at the end of `alphabet`.\n///\n/// let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\n/// let asciiTable = zip(65..., alphabet)\n/// for (code, letter) in asciiTable {\n/// print(code, letter)\n/// }\n/// // "65 A"\n/// // "66 B"\n/// // "67 C"\n/// // ...\n/// // "89 Y"\n/// // "90 Z"\n///\n/// The behavior of incrementing indefinitely is determined by the type of\n/// `Bound`. For example, iterating over an instance of\n/// `PartialRangeFrom<Int>` traps when the sequence's next value would be\n/// above `Int.max`.\n@frozen\npublic struct PartialRangeFrom<Bound: Comparable> {\n public let lowerBound: Bound\n\n @inlinable // trivial-implementation\n public init(_ lowerBound: Bound) { self.lowerBound = lowerBound }\n}\n\nextension PartialRangeFrom: RangeExpression {\n @_transparent\n public func relative<C: Collection>(\n to collection: C\n ) -> Range<Bound> where C.Index == Bound {\n return self.lowerBound..<collection.endIndex\n }\n @inlinable // trivial-implementation\n public func contains(_ element: Bound) -> Bool {\n return lowerBound <= element\n }\n}\n\nextension PartialRangeFrom: Sequence\n where Bound: Strideable, Bound.Stride: SignedInteger\n{\n public typealias Element = Bound\n\n /// The iterator for a `PartialRangeFrom` instance.\n @frozen\n public struct Iterator: IteratorProtocol {\n @usableFromInline\n internal var _current: Bound\n @inlinable\n public init(_current: Bound) { self._current = _current }\n\n /// Advances to the next element and returns it, or `nil` if no next\n /// element 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\n /// element exists; otherwise, `nil`.\n @inlinable\n public mutating func next() -> Bound? {\n defer { _current = _current.advanced(by: 1) }\n return _current\n }\n }\n\n /// Returns an iterator for this sequence.\n @inlinable\n public __consuming func makeIterator() -> Iterator { \n return Iterator(_current: lowerBound) \n }\n}\n\n@_unavailableInEmbedded\nextension PartialRangeFrom: Decodable where Bound: Decodable {\n public init(from decoder: Decoder) throws {\n var container = try decoder.unkeyedContainer()\n try self.init(container.decode(Bound.self))\n }\n}\n\n@_unavailableInEmbedded\nextension PartialRangeFrom: Encodable where Bound: Encodable {\n public func encode(to encoder: Encoder) throws {\n var container = encoder.unkeyedContainer()\n try container.encode(self.lowerBound)\n }\n}\n\nextension Comparable {\n /// Returns a half-open range that contains its lower bound but not its upper\n /// bound.\n ///\n /// Use the half-open range operator (`..<`) to create a range of any type\n /// that conforms to the `Comparable` protocol. This example creates a\n /// `Range<Double>` from zero up to, but not including, 5.0.\n ///\n /// let lessThanFive = 0.0..<5.0\n /// print(lessThanFive.contains(3.14)) // Prints "true"\n /// print(lessThanFive.contains(5.0)) // Prints "false"\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) -> Range<Self> {\n _precondition(minimum <= maximum,\n "Range requires lowerBound <= upperBound")\n return unsafe Range(_uncheckedBounds: (lower: minimum, upper: maximum))\n }\n\n /// Returns a partial range up to, but not including, its upper bound.\n ///\n /// Use the prefix half-open range operator (prefix `..<`) to create a\n /// partial range of any type that conforms to the `Comparable` protocol.\n /// This example creates a `PartialRangeUpTo<Double>` instance that includes\n /// any value less than `5.0`.\n ///\n /// let upToFive = ..<5.0\n ///\n /// upToFive.contains(3.14) // true\n /// upToFive.contains(6.28) // false\n /// upToFive.contains(5.0) // false\n ///\n /// You can use this type of partial range of a collection's indices to\n /// represent the range from the start of the collection up to, but not\n /// including, the partial range's upper bound.\n ///\n /// let numbers = [10, 20, 30, 40, 50, 60, 70]\n /// print(numbers[..<3])\n /// // Prints "[10, 20, 30]"\n ///\n /// - Parameter maximum: The upper bound for the range.\n ///\n /// - Precondition: `maximum` must compare equal to itself (i.e. cannot be NaN).\n @_transparent\n public static prefix func ..< (maximum: Self) -> PartialRangeUpTo<Self> {\n _precondition(maximum == maximum,\n "Range cannot have an unordered upper bound.")\n return PartialRangeUpTo(maximum)\n }\n\n /// Returns a partial range up to, and including, its upper bound.\n ///\n /// Use the prefix closed range operator (prefix `...`) to create a partial\n /// range of any type that conforms to the `Comparable` protocol. This\n /// example creates a `PartialRangeThrough<Double>` instance that includes\n /// any value less than or equal to `5.0`.\n ///\n /// let throughFive = ...5.0\n ///\n /// throughFive.contains(4.0) // true\n /// throughFive.contains(5.0) // true\n /// throughFive.contains(6.0) // false\n ///\n /// You can use this type of partial range of a collection's indices to\n /// represent the range from the start of the collection up to, and\n /// including, the partial range's upper bound.\n ///\n /// let numbers = [10, 20, 30, 40, 50, 60, 70]\n /// print(numbers[...3])\n /// // Prints "[10, 20, 30, 40]"\n ///\n /// - Parameter maximum: The upper bound for the range.\n ///\n /// - Precondition: `maximum` must compare equal to itself (i.e. cannot be NaN).\n @_transparent\n public static prefix func ... (maximum: Self) -> PartialRangeThrough<Self> {\n _precondition(maximum == maximum,\n "Range cannot have an unordered upper bound.")\n return PartialRangeThrough(maximum)\n }\n\n /// Returns a partial range extending upward from a lower bound.\n ///\n /// Use the postfix range operator (postfix `...`) to create a partial range\n /// of any type that conforms to the `Comparable` protocol. This example\n /// creates a `PartialRangeFrom<Double>` instance that includes any value\n /// greater than or equal to `5.0`.\n ///\n /// let atLeastFive = 5.0...\n ///\n /// atLeastFive.contains(4.0) // false\n /// atLeastFive.contains(5.0) // true\n /// atLeastFive.contains(6.0) // true\n ///\n /// You can use this type of partial range of a collection's indices to\n /// represent the range from the partial range's lower bound up to the end\n /// of the collection.\n ///\n /// let numbers = [10, 20, 30, 40, 50, 60, 70]\n /// print(numbers[3...])\n /// // Prints "[40, 50, 60, 70]"\n ///\n /// - Parameter minimum: The lower bound for the range.\n ///\n /// - Precondition: `minimum` must compare equal to itself (i.e. cannot be NaN).\n @_transparent\n public static postfix func ... (minimum: Self) -> PartialRangeFrom<Self> {\n _precondition(minimum == minimum,\n "Range cannot have an unordered lower bound.")\n return PartialRangeFrom(minimum)\n }\n}\n\n/// A range expression that represents the entire range of a collection.\n///\n/// You can use the unbounded range operator (`...`) to create a slice of a\n/// collection that contains all of the collection's elements. Slicing with an\n/// unbounded range is essentially a conversion of a collection instance into\n/// its slice type.\n///\n/// For example, the following code declares `countLetterChanges(_:_:)`, a\n/// function that finds the number of changes required to change one\n/// word or phrase into another. The function uses a recursive approach to\n/// perform the same comparisons on smaller and smaller pieces of the original\n/// strings. In order to use recursion without making copies of the strings at\n/// each step, `countLetterChanges(_:_:)` uses `Substring`, a string's slice\n/// type, for its parameters.\n///\n/// func countLetterChanges(_ s1: Substring, _ s2: Substring) -> Int {\n/// if s1.isEmpty { return s2.count }\n/// if s2.isEmpty { return s1.count }\n///\n/// let cost = s1.first == s2.first ? 0 : 1\n///\n/// return min(\n/// countLetterChanges(s1.dropFirst(), s2) + 1,\n/// countLetterChanges(s1, s2.dropFirst()) + 1,\n/// countLetterChanges(s1.dropFirst(), s2.dropFirst()) + cost)\n/// }\n///\n/// To call `countLetterChanges(_:_:)` with two strings, use an unbounded\n/// range in each string's subscript.\n///\n/// let word1 = "grizzly"\n/// let word2 = "grisly"\n/// let changes = countLetterChanges(word1[...], word2[...])\n/// // changes == 2\n@frozen // namespace\npublic enum UnboundedRange_ {\n // FIXME: replace this with a computed var named `...` when the language makes\n // that possible.\n\n /// Creates an unbounded range expression.\n ///\n /// The unbounded range operator (`...`) is valid only within a collection's\n /// subscript.\n public static postfix func ... (_: UnboundedRange_) -> () {\n // This function is uncallable\n }\n}\n\n/// The type of an unbounded range operator.\npublic typealias UnboundedRange = (UnboundedRange_)->()\n\nextension Collection {\n /// Accesses the contiguous subrange of the collection's elements specified\n /// by a range expression.\n ///\n /// The range expression is converted to a concrete subrange relative to this\n /// collection. For example, using a `PartialRangeFrom` range expression\n /// with an array accesses the subrange from the start of the range\n /// expression until the end of the array.\n ///\n /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]\n /// let streetsSlice = streets[2...]\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 uses. This example searches `streetsSlice` for one\n /// of the strings in the slice, and then uses that index in the original\n /// 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's indices may result in a\n /// runtime 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 @inlinable\n public subscript<R: RangeExpression>(r: R)\n -> SubSequence where R.Bound == Index {\n return self[r.relative(to: self)]\n }\n \n @inlinable\n public subscript(x: UnboundedRange) -> SubSequence {\n return self[startIndex...]\n }\n}\n\nextension MutableCollection {\n @inlinable\n public subscript<R: RangeExpression>(r: R) -> SubSequence\n where R.Bound == Index {\n get {\n return self[r.relative(to: self)]\n }\n set {\n self[r.relative(to: self)] = newValue\n }\n }\n\n @inlinable\n public subscript(x: UnboundedRange) -> SubSequence {\n get {\n return self[startIndex...]\n }\n set {\n self[startIndex...] = newValue\n }\n }\n}\n\n// TODO: enhance RangeExpression to make this generic and available on\n// any expression.\nextension Range {\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 half-open range does not include its upper bound, the ranges\n /// in the following example do not overlap:\n ///\n /// let y = 20..<30\n /// print(x.overlaps(y))\n /// // Prints "false"\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 // Disjoint iff the other range is completely before or after our range.\n // Additionally either `Range` (unlike a `ClosedRange`) could be empty, in\n // which case it is disjoint with everything as overlap is defined as having\n // an element in common.\n let isDisjoint = other.upperBound <= self.lowerBound\n || self.upperBound <= other.lowerBound\n || self.isEmpty || other.isEmpty\n return !isDisjoint\n }\n\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 /// Because a half-open range does not include its upper bound, the ranges\n /// in the following example do not overlap:\n ///\n /// let y = 20...30\n /// print(x.overlaps(y))\n /// // Prints "false"\n ///\n /// - Parameter other: A closed 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 // Additionally the `Range` (unlike the `ClosedRange`) could be empty, in\n // which case it is disjoint with everything as overlap is defined as having\n // an element in common.\n let isDisjoint = other.upperBound < self.lowerBound\n || self.upperBound <= other.lowerBound\n || self.isEmpty\n return !isDisjoint\n }\n}\n\nextension Range {\n /// Returns a Boolean value indicating whether the given range is contained\n /// within this range.\n ///\n /// The given range is contained within this range if its bounds are equal to\n /// or within the bounds of this 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 /// 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 /// range.\n ///\n /// let emptyRange = 3..<3\n /// emptyRange.contains(3..<3) // true\n /// emptyRange.contains(5..<5) // true\n ///\n /// - Parameter other: A range to check for containment within this range.\n /// - Returns: `true` if `other` is empty or wholly contained within this\n /// range; otherwise, `false`.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public func contains(_ other: Range<Bound>) -> Bool {\n other.isEmpty ||\n (lowerBound <= other.lowerBound && upperBound >= other.upperBound)\n }\n \n /// Returns a Boolean value indicating whether the given closed range is\n /// contained within this range.\n ///\n /// The given closed range is contained within this range if its bounds are\n /// contained within this range. If this range is empty, it cannot contain a\n /// closed range, since closed ranges by definition contain their boundaries.\n ///\n /// let range = 0..<10\n /// range.contains(2...5) // true\n /// range.contains(2...10) // false\n /// range.contains(2...12) // false\n ///\n /// let emptyRange = 3..<3\n /// emptyRange.contains(3...3) // false\n ///\n /// - Parameter other: A closed range to check for containment within this\n /// range.\n /// - Returns: `true` if `other` is wholly contained within this 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\n// Note: this is not for compatibility only, it is considered a useful\n// shorthand. TODO: Add documentation\npublic typealias CountableRange<Bound: Strideable> = Range<Bound>\n where Bound.Stride: SignedInteger\n\n// Note: this is not for compatibility only, it is considered a useful\n// shorthand. TODO: Add documentation\npublic typealias CountablePartialRangeFrom<Bound: Strideable> = PartialRangeFrom<Bound>\n where Bound.Stride: SignedInteger\n\nextension Range: Sendable where Bound: Sendable { }\nextension PartialRangeUpTo: Sendable where Bound: Sendable { }\nextension PartialRangeThrough: Sendable where Bound: Sendable { }\nextension PartialRangeFrom: Sendable where Bound: Sendable { }\nextension PartialRangeFrom.Iterator: Sendable where Bound: Sendable { }\n\nextension Range where Bound == String.Index {\n @_alwaysEmitIntoClient // Swift 5.7\n internal var _encodedOffsetRange: Range<Int> {\n _internalInvariant(\n (lowerBound._canBeUTF8 && upperBound._canBeUTF8)\n || (lowerBound._canBeUTF16 && upperBound._canBeUTF16))\n return unsafe Range<Int>(\n _uncheckedBounds: (lowerBound._encodedOffset, upperBound._encodedOffset))\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Range.swift
cpp_apple_swift_stdlib_public_core_Range.swift
Swift
40,096
0.95
0.066138
0.60397
python-kit
914
2025-06-10T05:04:33.255438
MIT
false
f9322de634241bddae1e5fc32d75a4b5
//===--- RangeReplaceableCollection.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// A Collection protocol with replaceSubrange.\n//\n//===----------------------------------------------------------------------===//\n\n/// A collection that supports replacement of an arbitrary subrange of elements\n/// with the elements of another collection.\n///\n/// Range-replaceable collections provide operations that insert and remove\n/// elements. For example, you can add elements to an array of strings by\n/// calling any of the inserting or appending operations that the\n/// `RangeReplaceableCollection` protocol defines.\n///\n/// var bugs = ["Aphid", "Damselfly"]\n/// bugs.append("Earwig")\n/// bugs.insert(contentsOf: ["Bumblebee", "Cicada"], at: 1)\n/// print(bugs)\n/// // Prints "["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]"\n///\n/// Likewise, `RangeReplaceableCollection` types can remove one or more\n/// elements using a single operation.\n///\n/// bugs.removeLast()\n/// bugs.removeSubrange(1...2)\n/// print(bugs)\n/// // Prints "["Aphid", "Damselfly"]"\n///\n/// bugs.removeAll()\n/// print(bugs)\n/// // Prints "[]"\n///\n/// Lastly, use the eponymous `replaceSubrange(_:with:)` method to replace\n/// a subrange of elements with the contents of another collection. Here,\n/// three elements in the middle of an array of integers are replaced by the\n/// 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/// Conforming to the RangeReplaceableCollection Protocol\n/// =====================================================\n///\n/// To add `RangeReplaceableCollection` conformance to your custom collection,\n/// add an empty initializer and the `replaceSubrange(_:with:)` method to your\n/// custom type. `RangeReplaceableCollection` provides default implementations\n/// of all its other methods using this initializer and method. For example,\n/// the `removeSubrange(_:)` method is implemented by calling\n/// `replaceSubrange(_:with:)` with an empty collection for the `newElements`\n/// parameter. You can override any of the protocol's required methods to\n/// provide your own custom implementation.\npublic protocol RangeReplaceableCollection<Element>: Collection\nwhere SubSequence: RangeReplaceableCollection {\n // FIXME: Associated type inference requires this.\n override associatedtype SubSequence\n\n //===--- Fundamental Requirements ---------------------------------------===//\n\n /// Creates a new, empty collection.\n init()\n\n /// Replaces the specified subrange of elements with the given collection.\n ///\n /// This method has the effect of removing the specified range of elements\n /// from the collection and inserting the new elements at the same location.\n /// The 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 /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameters:\n /// - subrange: The subrange of the collection to replace. The bounds of\n /// the range must be valid indices of the collection.\n /// - newElements: The new elements to add to the collection.\n ///\n /// - Complexity: O(*n* + *m*), where *n* is length of this collection and\n /// *m* is the length of `newElements`. If the call to this method simply\n /// appends the contents of `newElements` to the collection, this method is\n /// equivalent to `append(contentsOf:)`.\n mutating func replaceSubrange<C>(\n _ subrange: Range<Index>,\n with newElements: __owned C\n ) where C: Collection, C.Element == Element\n\n /// Prepares the collection to store the specified number of elements, when\n /// doing so is appropriate for the underlying type.\n ///\n /// If you are adding a known number of elements to a collection, use this\n /// method to avoid multiple reallocations. A type that conforms to\n /// `RangeReplaceableCollection` can choose how to respond when this method\n /// is called. Depending on the type, it may make sense to allocate more or\n /// less storage than requested, or to take no action at all.\n ///\n /// - Parameter n: The requested number of elements to store.\n mutating func reserveCapacity(_ n: Int)\n\n //===--- Derivable Requirements -----------------------------------------===//\n\n /// Creates a new collection containing the specified number of a single,\n /// repeated value.\n ///\n /// The following example creates 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 init(repeating repeatedValue: Element, count: Int)\n\n /// Creates a new instance of a collection containing the elements of a\n /// sequence.\n ///\n /// - Parameter elements: The sequence of elements for the new collection.\n /// `elements` must be finite.\n init<S: Sequence>(_ elements: S)\n where S.Element == Element\n\n /// Adds an element to the end of the collection.\n ///\n /// If the collection does not have sufficient capacity for another element,\n /// additional storage is allocated before appending `newElement`. The\n /// following example adds a new number to an array of integers:\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.append(100)\n ///\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 100]"\n ///\n /// - Parameter newElement: The element to append to the collection.\n ///\n /// - Complexity: O(1) on average, over many calls to `append(_:)` on the\n /// same collection.\n mutating func append(_ newElement: __owned Element)\n\n /// Adds the elements of a sequence or collection to the end of this\n /// collection.\n ///\n /// The collection being appended to allocates any additional necessary\n /// storage to hold the new elements.\n ///\n /// The following example appends the elements of a `Range<Int>` instance to\n /// 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 collection.\n ///\n /// - Complexity: O(*m*), where *m* is the length of `newElements`.\n mutating func append<S: Sequence>(contentsOf newElements: __owned S)\n where S.Element == Element\n // FIXME(ABI)#166 (Evolution): Consider replacing .append(contentsOf) with +=\n // suggestion in SE-91\n\n /// Inserts a new element into the collection at the specified position.\n ///\n /// The new element is inserted before the element currently at the\n /// specified index. If you pass the collection's `endIndex` property as\n /// the `index` parameter, the new element is appended to the\n /// collection.\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 /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter newElement: The new element to insert into the collection.\n /// - Parameter i: The position at which to insert the new element.\n /// `index` must be a valid index into the collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection. If\n /// `i == endIndex`, this method is equivalent to `append(_:)`.\n mutating func insert(_ newElement: __owned Element, at i: Index)\n\n /// Inserts the elements of a sequence into the collection at the specified\n /// position.\n ///\n /// The new elements are inserted before the element currently at the\n /// specified index. If you pass the collection's `endIndex` property as the\n /// `index` parameter, the new elements are appended to the collection.\n ///\n /// Here's an example of inserting a range of integers into an array of the\n /// same type:\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.insert(contentsOf: 100...103, at: 3)\n /// print(numbers)\n /// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]"\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter newElements: The new elements to insert into the collection.\n /// - Parameter i: The position at which to insert the new elements. `index`\n /// must be a valid index of the collection.\n ///\n /// - Complexity: O(*n* + *m*), where *n* is length of this collection and\n /// *m* is the length of `newElements`. If `i == endIndex`, this method\n /// is equivalent to `append(contentsOf:)`.\n mutating func insert<S: Collection>(contentsOf newElements: __owned S, at i: Index)\n where S.Element == Element\n\n /// Removes and returns the element at the specified position.\n ///\n /// All the elements following the specified position are moved to close the\n /// gap. This example removes the middle element from an array of\n /// measurements.\n ///\n /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6]\n /// let removed = measurements.remove(at: 2)\n /// print(measurements)\n /// // Prints "[1.2, 1.5, 1.2, 1.6]"\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter i: The position of the element to remove. `index` must be\n /// a valid index of the collection that is not equal to the collection's\n /// end index.\n /// - Returns: The removed element.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @discardableResult\n mutating func remove(at i: Index) -> Element\n\n /// Removes the specified subrange of elements from the collection.\n ///\n /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]\n /// bugs.removeSubrange(1...3)\n /// print(bugs)\n /// // Prints "["Aphid", "Earwig"]"\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter bounds: The subrange of the collection to remove. The bounds\n /// of the range must be valid indices of the collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n mutating func removeSubrange(_ bounds: Range<Index>)\n\n /// Customization point for `removeLast()`. Implement this function if you\n /// want to replace the default implementation.\n ///\n /// The collection must not be empty.\n ///\n /// - Returns: A non-nil value if the operation was performed.\n mutating func _customRemoveLast() -> Element?\n\n /// Customization point for `removeLast(_:)`. Implement this function if you\n /// want to replace the default implementation.\n ///\n /// - Parameter n: The number of elements to remove from the collection.\n /// `n` must be greater than or equal to zero and must not exceed the\n /// number of elements in the collection.\n /// - Returns: `true` if the operation was performed.\n mutating func _customRemoveLast(_ n: Int) -> Bool\n\n /// Removes and returns the first element of the collection.\n ///\n /// The collection must not be empty.\n ///\n /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]\n /// bugs.removeFirst()\n /// print(bugs)\n /// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]"\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Returns: The removed element.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @discardableResult\n mutating func removeFirst() -> Element\n\n /// Removes the specified number of elements from the beginning of the\n /// collection.\n ///\n /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]\n /// bugs.removeFirst(3)\n /// print(bugs)\n /// // Prints "["Damselfly", "Earwig"]"\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter k: The number of elements to remove from the collection.\n /// `k` must be greater than or equal to zero and must not exceed the\n /// number of elements in the collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n mutating func removeFirst(_ k: Int)\n\n /// Removes all elements from the collection.\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter keepCapacity: Pass `true` to request that the collection\n /// avoid releasing its storage. Retaining the collection's storage can\n /// be a useful optimization when you're planning to grow the collection\n /// again. The default value is `false`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n mutating func removeAll(keepingCapacity keepCapacity: Bool /*= false*/)\n\n /// Removes all the elements that satisfy the given predicate.\n ///\n /// Use this method to remove every element in a collection that meets\n /// particular criteria. The order of the remaining elements is preserved.\n /// This example removes all the odd values from an\n /// array of numbers:\n ///\n /// var numbers = [5, 6, 7, 8, 9, 10, 11]\n /// numbers.removeAll(where: { $0 % 2 != 0 })\n /// // numbers == [6, 8, 10]\n ///\n /// - Parameter shouldBeRemoved: A closure that takes an element of the\n /// sequence as its argument and returns a Boolean value indicating\n /// whether the element should be removed from the collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n mutating func removeAll(\n where shouldBeRemoved: (Element) throws -> Bool) rethrows\n\n // FIXME: Associated type inference requires these.\n @_borrowed\n override subscript(position: Index) -> Element { get }\n override subscript(bounds: Range<Index>) -> SubSequence { get }\n}\n\n//===----------------------------------------------------------------------===//\n// Default implementations for RangeReplaceableCollection\n//===----------------------------------------------------------------------===//\n\nextension RangeReplaceableCollection {\n /// Creates a new collection containing the specified number of a single,\n /// repeated 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 public init(repeating repeatedValue: Element, count: Int) {\n self.init()\n if count != 0 {\n let elements = Repeated(_repeating: repeatedValue, count: count)\n append(contentsOf: elements)\n }\n }\n\n /// Creates a new instance of a collection containing the elements of a\n /// sequence.\n ///\n /// - Parameter elements: The sequence of elements for the new collection.\n @inlinable\n public init<S: Sequence>(_ elements: S)\n where S.Element == Element {\n self.init()\n append(contentsOf: elements)\n }\n\n /// Adds an element to the end of the collection.\n ///\n /// If the collection does not have sufficient capacity for another element,\n /// additional storage is allocated before appending `newElement`. The\n /// following example adds a new number to an array of integers:\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.append(100)\n ///\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 100]"\n ///\n /// - Parameter newElement: The element to append to the collection.\n ///\n /// - Complexity: O(1) on average, over many calls to `append(_:)` on the\n /// same collection.\n @inlinable\n public mutating func append(_ newElement: __owned Element) {\n insert(newElement, at: endIndex)\n }\n\n /// Adds the elements of a sequence or collection to the end of this\n /// collection.\n ///\n /// The collection being appended to allocates any additional necessary\n /// storage to hold the new elements.\n ///\n /// The following example appends the elements of a `Range<Int>` instance to\n /// 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 collection.\n ///\n /// - Complexity: O(*m*), where *m* is the length of `newElements`.\n @inlinable\n public mutating func append<S: Sequence>(contentsOf newElements: __owned S)\n where S.Element == Element {\n for element in newElements {\n append(element)\n }\n }\n\n /// Inserts a new element into the collection at the specified position.\n ///\n /// The new element is inserted before the element currently at the\n /// specified index. If you pass the collection's `endIndex` property as\n /// the `index` parameter, the new element is appended to the\n /// collection.\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 /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter newElement: The new element to insert into the collection.\n /// - Parameter i: The position at which to insert the new element.\n /// `index` must be a valid index into the collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection. If\n /// `i == endIndex`, this method is equivalent to `append(_:)`.\n @inlinable\n public mutating func insert(\n _ newElement: __owned Element, at i: Index\n ) {\n replaceSubrange(i..<i, with: CollectionOfOne(newElement))\n }\n\n /// Inserts the elements of a sequence into the collection at the specified\n /// position.\n ///\n /// The new elements are inserted before the element currently at the\n /// specified index. If you pass the collection's `endIndex` property as the\n /// `index` parameter, the new elements are appended to the collection.\n ///\n /// Here's an example of inserting a range of integers into an array of the\n /// same type:\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers.insert(contentsOf: 100...103, at: 3)\n /// print(numbers)\n /// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]"\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter newElements: The new elements to insert into the collection.\n /// - Parameter i: The position at which to insert the new elements. `index`\n /// must be a valid index of the collection.\n ///\n /// - Complexity: O(*n* + *m*), where *n* is length of this collection and\n /// *m* is the length of `newElements`. If `i == endIndex`, this method\n /// is equivalent to `append(contentsOf:)`.\n @inlinable\n public mutating func insert<C: Collection>(\n contentsOf newElements: __owned C, at i: Index\n ) where C.Element == Element {\n replaceSubrange(i..<i, with: newElements)\n }\n\n /// Removes and returns the element at the specified position.\n ///\n /// All the elements following the specified position are moved to close the\n /// gap. This example removes the middle element from an array of\n /// measurements.\n ///\n /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6]\n /// let removed = measurements.remove(at: 2)\n /// print(measurements)\n /// // Prints "[1.2, 1.5, 1.2, 1.6]"\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter position: The position of the element to remove. `position`\n /// must be a valid index of the collection that is not equal to the\n /// collection's end index.\n /// - Returns: The removed element.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n @discardableResult\n public mutating func remove(at position: Index) -> Element {\n _precondition(!isEmpty, "Can't remove from an empty collection")\n let result: Element = self[position]\n replaceSubrange(position..<index(after: position), with: EmptyCollection())\n return result\n }\n\n /// Removes the elements in the specified subrange from the collection.\n ///\n /// All the elements following the specified position are moved to close the\n /// gap. This example removes three elements from the middle of an array of\n /// measurements.\n ///\n /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5]\n /// measurements.removeSubrange(1..<4)\n /// print(measurements)\n /// // Prints "[1.2, 1.5]"\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter bounds: The range of the collection to be removed. The\n /// bounds of the range must be valid indices of the collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public mutating func removeSubrange(_ bounds: Range<Index>) {\n replaceSubrange(bounds, with: EmptyCollection())\n }\n\n /// Removes the specified number of elements from the beginning of the\n /// collection.\n ///\n /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]\n /// bugs.removeFirst(3)\n /// print(bugs)\n /// // Prints "["Damselfly", "Earwig"]"\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter k: The number of elements to remove from the collection.\n /// `k` must be greater than or equal to zero and must not exceed the\n /// number of elements in the collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\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 end = index(startIndex, offsetBy: k, limitedBy: endIndex) else {\n _preconditionFailure(\n "Can't remove more items from a collection than it has")\n }\n removeSubrange(startIndex..<end)\n }\n\n /// Removes and returns the first element of the collection.\n ///\n /// The collection must not be empty.\n ///\n /// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]\n /// bugs.removeFirst()\n /// print(bugs)\n /// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]"\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Returns: The removed element.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n @discardableResult\n public mutating func removeFirst() -> Element {\n _precondition(!isEmpty,\n "Can't remove first element from an empty collection")\n let firstElement = first!\n removeFirst(1)\n return firstElement\n }\n\n /// Removes all elements from the collection.\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter keepCapacity: Pass `true` to request that the collection\n /// avoid releasing its storage. Retaining the collection's storage can\n /// be a useful optimization when you're planning to grow the collection\n /// again. The default value is `false`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {\n if !keepCapacity {\n self = Self()\n }\n else {\n replaceSubrange(startIndex..<endIndex, with: EmptyCollection())\n }\n }\n\n /// Prepares the collection to store the specified number of elements, when\n /// doing so is appropriate for the underlying type.\n ///\n /// If you will be adding a known number of elements to a collection, use\n /// this method to avoid multiple reallocations. A type that conforms to\n /// `RangeReplaceableCollection` can choose how to respond when this method\n /// is called. Depending on the type, it may make sense to allocate more or\n /// less storage than requested or to take no action at all.\n ///\n /// - Parameter n: The requested number of elements to store.\n @inlinable\n public mutating func reserveCapacity(_ n: Int) {}\n}\n\nextension RangeReplaceableCollection where SubSequence == Self {\n /// Removes and returns the first element of the collection.\n ///\n /// The collection must not be empty.\n ///\n /// Calling this method may invalidate all saved indices of this\n /// collection. Do not rely on a previously stored index value after\n /// altering a collection with any operation that can change its length.\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 _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 /// Attempting to remove more elements than exist in the collection\n /// triggers a runtime error.\n ///\n /// Calling this method may invalidate all saved indices of this\n /// collection. Do not rely on a previously stored index value after\n /// altering a collection with any operation that can change its length.\n ///\n /// - Parameter k: The number of elements to remove from the collection.\n /// `k` must be greater than or equal to zero and must not exceed the\n /// number of 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\nextension RangeReplaceableCollection {\n /// Replaces the specified subrange of elements with the given collection.\n ///\n /// This method has the effect of removing the specified range of elements\n /// from the collection and inserting the new elements at the same location.\n /// The 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 /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameters:\n /// - subrange: The subrange of the collection to replace. The bounds of\n /// the range must be valid indices of the collection.\n /// - newElements: The new elements to add to the collection.\n ///\n /// - Complexity: O(*n* + *m*), where *n* is length of this collection and\n /// *m* is the length of `newElements`. If the call to this method simply\n /// appends the contents of `newElements` to the collection, the complexity\n /// is O(*m*).\n @inlinable\n public mutating func replaceSubrange<C: Collection, R: RangeExpression>(\n _ subrange: R,\n with newElements: __owned C\n ) where C.Element == Element, R.Bound == Index {\n self.replaceSubrange(subrange.relative(to: self), with: newElements)\n }\n\n // This unavailable default implementation of\n // `replaceSubrange<C: Collection>(_: Range<Index>, with: C)` prevents\n // incomplete RangeReplaceableCollection implementations from satisfying\n // the protocol through the use of the generic convenience implementation\n // `replaceSubrange<C: Collection, R: RangeExpression>(_: R, with: C)`,\n // If that were the case, at runtime the implementation generic over\n // `RangeExpression` would call itself in an infinite recursion\n // due to the absence of a better option.\n @available(*, unavailable)\n @_alwaysEmitIntoClient\n public mutating func replaceSubrange<C>(\n _ subrange: Range<Index>,\n with newElements: C\n ) where C: Collection, C.Element == Element {\n fatalError()\n }\n\n /// Removes the elements in the specified subrange from the collection.\n ///\n /// All the elements following the specified position are moved to close the\n /// gap. This example removes three elements from the middle of an array of\n /// measurements.\n ///\n /// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5]\n /// measurements.removeSubrange(1..<4)\n /// print(measurements)\n /// // Prints "[1.2, 1.5]"\n ///\n /// Calling this method may invalidate any existing indices for use with this\n /// collection.\n ///\n /// - Parameter bounds: The range of the collection to be removed. The\n /// bounds of the range must be valid indices of the collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public mutating func removeSubrange<R: RangeExpression>(\n _ bounds: R\n ) where R.Bound == Index {\n removeSubrange(bounds.relative(to: self))\n }\n}\n\nextension RangeReplaceableCollection {\n @inlinable\n public mutating func _customRemoveLast() -> Element? {\n return nil\n }\n\n @inlinable\n public mutating func _customRemoveLast(_ n: Int) -> Bool {\n return false\n }\n}\n\nextension RangeReplaceableCollection\n where Self: BidirectionalCollection, SubSequence == Self {\n\n @inlinable\n public mutating func _customRemoveLast() -> Element? {\n let element = last!\n self = self[startIndex..<index(before: endIndex)]\n return element\n }\n\n @inlinable\n public mutating func _customRemoveLast(_ n: Int) -> Bool {\n guard let end = index(endIndex, offsetBy: -n, 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 return true\n }\n}\n\nextension RangeReplaceableCollection where Self: BidirectionalCollection {\n /// Removes and returns the last element of the collection.\n ///\n /// Calling this method may invalidate all saved indices of this\n /// collection. Do not rely on a previously stored index value after\n /// altering a collection with any operation that can change its length.\n ///\n /// - Returns: The last element of the collection if the collection is not\n /// empty; otherwise, `nil`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public mutating func popLast() -> Element? {\n if isEmpty { return nil }\n // duplicate of removeLast logic below, to avoid redundant precondition\n if let result = _customRemoveLast() { return result }\n return remove(at: index(before: endIndex))\n }\n\n /// Removes and returns the last element of the collection.\n ///\n /// The collection must not be empty.\n ///\n /// Calling this method may invalidate all saved indices of this\n /// collection. Do not rely on a previously stored index value after\n /// altering a collection with any operation that can change its length.\n ///\n /// - Returns: The last element of the collection.\n ///\n /// - Complexity: O(1)\n @inlinable\n @discardableResult\n public mutating func removeLast() -> Element {\n _precondition(!isEmpty, "Can't remove last element from an empty collection")\n // NOTE if you change this implementation, change popLast above as well\n // AND change the tie-breaker implementations in the next extension\n if let result = _customRemoveLast() { return result }\n return remove(at: index(before: endIndex))\n }\n\n /// Removes the specified number of elements from the end of the\n /// collection.\n ///\n /// Attempting to remove more elements than exist in the collection\n /// triggers a runtime error.\n ///\n /// Calling this method may invalidate all saved indices of this\n /// collection. Do not rely on a previously stored index value after\n /// altering a collection with any operation that can change its length.\n ///\n /// - Parameter k: The number of elements to remove from the collection.\n /// `k` must be greater than or equal to zero and must not exceed the\n /// number of elements in the collection.\n ///\n /// - Complexity: O(*k*), where *k* is the specified number of elements.\n @inlinable\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 if _customRemoveLast(k) {\n return\n }\n let end = endIndex\n guard let start = index(end, offsetBy: -k, limitedBy: startIndex)\n else {\n _preconditionFailure(\n "Can't remove more items from a collection than it contains")\n }\n\n removeSubrange(start..<end)\n }\n}\n\n/// Ambiguity breakers.\nextension RangeReplaceableCollection\nwhere Self: BidirectionalCollection, SubSequence == Self {\n /// Removes and returns the last element of the collection.\n ///\n /// Calling this method may invalidate all saved indices of this\n /// collection. Do not rely on a previously stored index value after\n /// altering a collection with any operation that can change its length.\n ///\n /// - Returns: The last element of the collection if the collection is not\n /// empty; otherwise, `nil`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public mutating func popLast() -> Element? {\n if isEmpty { return nil }\n // duplicate of removeLast logic below, to avoid redundant precondition\n if let result = _customRemoveLast() { return result }\n return remove(at: index(before: endIndex))\n }\n\n /// Removes and returns the last element of the collection.\n ///\n /// The collection must not be empty.\n ///\n /// Calling this method may invalidate all saved indices of this\n /// collection. Do not rely on a previously stored index value after\n /// altering a collection with any operation that can change its length.\n ///\n /// - Returns: The last element of the collection.\n ///\n /// - Complexity: O(1)\n @inlinable\n @discardableResult\n public mutating func removeLast() -> Element {\n _precondition(!isEmpty, "Can't remove last element from an empty collection")\n // NOTE if you change this implementation, change popLast above as well\n if let result = _customRemoveLast() { return result }\n return remove(at: index(before: endIndex))\n }\n\n /// Removes the specified number of elements from the end of the\n /// collection.\n ///\n /// Attempting to remove more elements than exist in the collection\n /// triggers a runtime error.\n ///\n /// Calling this method may invalidate all saved indices of this\n /// collection. Do not rely on a previously stored index value after\n /// altering a collection with any operation that can change its length.\n ///\n /// - Parameter k: The number of elements to remove from the collection.\n /// `k` must be greater than or equal to zero and must not exceed the\n /// number of elements in the collection.\n ///\n /// - Complexity: O(*k*), where *k* is the specified number of elements.\n @inlinable\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 if _customRemoveLast(k) {\n return\n }\n let end = endIndex\n guard let start = index(end, offsetBy: -k, limitedBy: startIndex)\n else {\n _preconditionFailure(\n "Can't remove more items from a collection than it contains")\n }\n removeSubrange(start..<end)\n }\n}\n\nextension RangeReplaceableCollection {\n /// Creates a new collection by concatenating the elements of a collection and\n /// a sequence.\n ///\n /// The two arguments must have the same `Element` type. For example, you can\n /// concatenate the elements of an integer array and a `Range<Int>` instance.\n ///\n /// let numbers = [1, 2, 3, 4]\n /// let moreNumbers = numbers + (5...10)\n /// print(moreNumbers)\n /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"\n ///\n /// The resulting collection has the type of the argument on the left-hand\n /// side. In the example above, `moreNumbers` has the same type as `numbers`,\n /// which is `[Int]`.\n ///\n /// - Parameters:\n /// - lhs: A range-replaceable collection.\n /// - rhs: A collection or finite sequence.\n @inlinable\n public static func + <\n Other: Sequence\n >(lhs: Self, rhs: Other) -> Self\n where Element == Other.Element {\n var lhs = lhs\n // FIXME: what if lhs is a reference type? This will mutate it.\n lhs.append(contentsOf: rhs)\n return lhs\n }\n\n /// Creates a new collection by concatenating the elements of a sequence and a\n /// collection.\n ///\n /// The two arguments must have the same `Element` type. For example, you can\n /// concatenate the elements of a `Range<Int>` instance and an integer array.\n ///\n /// let numbers = [7, 8, 9, 10]\n /// let moreNumbers = (1...6) + numbers\n /// print(moreNumbers)\n /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"\n ///\n /// The resulting collection has the type of argument on the right-hand side.\n /// In the example above, `moreNumbers` has the same type as `numbers`, which\n /// is `[Int]`.\n ///\n /// - Parameters:\n /// - lhs: A collection or finite sequence.\n /// - rhs: A range-replaceable collection.\n @inlinable\n public static func + <\n Other: Sequence\n >(lhs: Other, rhs: Self) -> Self\n where Element == Other.Element {\n var result = Self()\n result.reserveCapacity(rhs.count + lhs.underestimatedCount)\n result.append(contentsOf: lhs)\n result.append(contentsOf: rhs)\n return result\n }\n\n /// Appends the elements of a sequence to a range-replaceable collection.\n ///\n /// Use this operator to append the elements of a sequence to the end of\n /// range-replaceable collection with same `Element` type. This example\n /// appends the elements of a `Range<Int>` instance to an array of integers.\n ///\n /// var numbers = [1, 2, 3, 4, 5]\n /// numbers += 10...15\n /// print(numbers)\n /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"\n ///\n /// - Parameters:\n /// - lhs: The array to append to.\n /// - rhs: A collection or finite sequence.\n ///\n /// - Complexity: O(*m*), where *m* is the length of the right-hand-side\n /// argument.\n @inlinable\n public static func += <\n Other: Sequence\n >(lhs: inout Self, rhs: Other)\n where Element == Other.Element {\n lhs.append(contentsOf: rhs)\n }\n\n /// Creates a new collection by concatenating the elements of two collections.\n ///\n /// The two arguments must have the same `Element` type. For example, you can\n /// concatenate the elements of two integer arrays.\n ///\n /// let lowerNumbers = [1, 2, 3, 4]\n /// let higherNumbers: ContiguousArray = [5, 6, 7, 8, 9, 10]\n /// let allNumbers = lowerNumbers + higherNumbers\n /// print(allNumbers)\n /// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"\n ///\n /// The resulting collection has the type of the argument on the left-hand\n /// side. In the example above, `moreNumbers` has the same type as `numbers`,\n /// which is `[Int]`.\n ///\n /// - Parameters:\n /// - lhs: A range-replaceable collection.\n /// - rhs: Another range-replaceable collection.\n @inlinable\n public static func + <\n Other: RangeReplaceableCollection\n >(lhs: Self, rhs: Other) -> Self\n where Element == Other.Element {\n var lhs = lhs\n // FIXME: what if lhs is a reference type? This will mutate it.\n lhs.append(contentsOf: rhs)\n return lhs\n }\n}\n\n\nextension RangeReplaceableCollection {\n /// Returns a new collection of the same type containing, in order, the\n /// elements of the original collection that satisfy the given predicate.\n ///\n /// In this example, `filter(_:)` is used to include only names shorter than\n /// five characters.\n ///\n /// let cast = ["Vivien", "Marlon", "Kim", "Karl"]\n /// let shortNames = cast.filter { $0.count < 5 }\n /// print(shortNames)\n /// // Prints "["Kim", "Karl"]"\n ///\n /// - Parameter isIncluded: A closure that takes an element of the\n /// sequence as its argument and returns a Boolean value indicating\n /// whether the element should be included in the returned collection.\n /// - Returns: A collection of the elements that `isIncluded` allowed.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n @available(swift, introduced: 4.0)\n public __consuming func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> Self {\n var result = Self()\n for element in self where try isIncluded(element) {\n result.append(element)\n }\n return result\n }\n}\n\nextension RangeReplaceableCollection where Self: MutableCollection {\n /// Removes all the elements that satisfy the given predicate.\n ///\n /// Use this method to remove every element in a collection that meets\n /// particular criteria. The order of the remaining elements is preserved.\n /// This example removes all the odd values from an\n /// array of numbers:\n ///\n /// var numbers = [5, 6, 7, 8, 9, 10, 11]\n /// numbers.removeAll(where: { $0 % 2 != 0 })\n /// // numbers == [6, 8, 10]\n ///\n /// - Parameter shouldBeRemoved: A closure that takes an element of the\n /// sequence as its argument and returns a Boolean value indicating\n /// whether the element should be removed from the collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public mutating func removeAll(\n where shouldBeRemoved: (Element) throws -> Bool\n ) rethrows {\n let suffixStart = try _halfStablePartition(isSuffixElement: shouldBeRemoved)\n removeSubrange(suffixStart...)\n }\n}\n\nextension RangeReplaceableCollection {\n /// Removes all the elements that satisfy the given predicate.\n ///\n /// Use this method to remove every element in a collection that meets\n /// particular criteria. The order of the remaining elements is preserved.\n /// This example removes all the vowels from a string:\n ///\n /// var phrase = "The rain in Spain stays mainly in the plain."\n ///\n /// let vowels: Set<Character> = ["a", "e", "i", "o", "u"]\n /// phrase.removeAll(where: { vowels.contains($0) })\n /// // phrase == "Th rn n Spn stys mnly n th pln."\n ///\n /// - Parameter shouldBeRemoved: A closure that takes an element of the\n /// sequence as its argument and returns a Boolean value indicating\n /// whether the element should be removed from the collection.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @inlinable\n public mutating func removeAll(\n where shouldBeRemoved: (Element) throws -> Bool\n ) rethrows {\n self = try filter { try !shouldBeRemoved($0) }\n }\n}\n\n#if !$Embedded\nextension RangeReplaceableCollection {\n /// Removes the elements at the given indices.\n ///\n /// For example, this code sample finds the indices of all the vowel\n /// characters in the string, and then removes those characters.\n ///\n /// var 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 /// str.removeSubranges(vowelIndices)\n /// // str == "Th rn n Spn stys mnly n th pln."\n ///\n /// - Parameter subranges: The indices of the elements to remove.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @available(SwiftStdlib 6.0, *)\n @inlinable\n public mutating func removeSubranges(_ subranges: RangeSet<Index>) {\n guard !subranges.isEmpty else {\n return\n }\n \n let inversion = subranges._inverted(within: self)\n var result = Self()\n for range in inversion.ranges {\n result.append(contentsOf: self[range])\n }\n self = result\n }\n}\n\nextension MutableCollection where Self: RangeReplaceableCollection {\n /// Removes the elements at the given indices.\n ///\n /// For example, this code sample finds the indices of all the negative\n /// numbers in the array, and then removes those values.\n ///\n /// var numbers = [5, 7, -3, -8, 11, 2, -1, 6]\n /// let negativeIndices = numbers.indices(where: { $0 < 0 })\n ///\n /// numbers.removeSubranges(negativeIndices)\n /// // numbers == [5, 7, 11, 2, 6]\n ///\n /// - Parameter subranges: The indices of the elements to remove.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the collection.\n @available(SwiftStdlib 6.0, *)\n @inlinable\n public mutating func removeSubranges(_ subranges: RangeSet<Index>) {\n guard let firstRange = subranges.ranges.first else {\n return\n }\n \n var endOfElementsToKeep = firstRange.lowerBound\n var firstUnprocessed = firstRange.upperBound\n \n // This performs a half-stable partition based on the ranges in\n // `indices`. At all times, the collection is divided into three\n // regions:\n //\n // - `self[..<endOfElementsToKeep]` contains only elements that will\n // remain in the collection after this method call.\n // - `self[endOfElementsToKeep..<firstUnprocessed]` contains only\n // elements that will be removed.\n // - `self[firstUnprocessed...]` contains a mix of elements to remain\n // and elements to be removed.\n //\n // Each iteration of this loop moves the elements that are _between_\n // two ranges to remove from the third region to the first region.\n for range in subranges.ranges.dropFirst() {\n let nextLow = range.lowerBound\n while firstUnprocessed != nextLow {\n swapAt(endOfElementsToKeep, firstUnprocessed)\n formIndex(after: &endOfElementsToKeep)\n formIndex(after: &firstUnprocessed)\n }\n \n firstUnprocessed = range.upperBound\n }\n \n // After dealing with all the ranges in `subranges`, move the elements\n // that are still in the third region down to the first.\n while firstUnprocessed != endIndex {\n swapAt(endOfElementsToKeep, firstUnprocessed)\n formIndex(after: &endOfElementsToKeep)\n formIndex(after: &firstUnprocessed)\n }\n \n removeSubrange(endOfElementsToKeep..<endIndex)\n }\n}\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_RangeReplaceableCollection.swift
cpp_apple_swift_stdlib_public_core_RangeReplaceableCollection.swift
Swift
48,898
0.95
0.054245
0.704564
python-kit
91
2023-10-07T00:22:03.567508
BSD-3-Clause
false
c866080e36d9d27aee97a72e2422c4dd
//===--- RangeSet.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 set of values of any comparable type, represented by ranges.\n///\n/// You can use a range set to efficiently represent a set of `Comparable`\n/// values that spans any number of discontiguous ranges. Range sets are\n/// commonly used to represent multiple subranges of a collection, by storing\n/// ranges of a collection's index type.\n///\n/// In this example, `negativeSubranges` is a range set representing the\n/// locations of all the negative values in `numbers`:\n///\n/// var numbers = [10, 12, -5, 14, -3, -9, 15]\n/// let negativeSubranges = numbers.indices(where: { $0 < 0 })\n/// // numbers[negativeSubranges].count == 3\n///\n/// numbers.moveSubranges(negativeSubranges, to: 0)\n/// // numbers == [-5, -3, -9, 10, 12, 14, 15]\n@available(SwiftStdlib 6.0, *)\npublic struct RangeSet<Bound: Comparable> {\n @usableFromInline\n internal var _ranges: Ranges\n\n /// A collection of the ranges that make up the range set.\n ///\n /// The ranges that you access by using `ranges` never overlap, are never\n /// empty, and are always in increasing order.\n public var ranges: Ranges {\n return _ranges\n }\n\n /// Creates an empty range set.\n public init() {\n _ranges = Ranges()\n }\n \n /// Creates a range set containing the given range.\n ///\n /// - Parameter range: The range to use for the new range set.\n public init(_ range: Range<Bound>) {\n if !range.isEmpty {\n self._ranges = Ranges(_range: range)\n } else {\n self._ranges = Ranges()\n }\n }\n \n /// Creates a range set containing the values in the given ranges.\n ///\n /// Any empty ranges in `ranges` are ignored, and non-empty ranges are merged\n /// to eliminate any overlaps. As such, the `ranges` collection in the\n /// resulting range set may not be equivalent to the sequence of ranges\n /// passed to this initializer.\n ///\n /// - Parameter ranges: The ranges to use for the new range set.\n public init(_ ranges: some Sequence<Range<Bound>>) {\n if let ranges = _specialize(ranges, for: Ranges.self) {\n self.init(_ranges: ranges)\n return\n }\n self.init(_ranges: Ranges(_unorderedRanges: Array(ranges)))\n }\n\n @usableFromInline\n internal init(_ranges: Ranges) {\n self._ranges = _ranges\n }\n \n /// Checks the invariants of `_ranges`.\n ///\n /// The ranges stored by a range set are never empty, never overlap,\n /// and are always stored in ascending order when comparing their lower\n /// or upper bounds. In addition to not overlapping, no two consecutive\n /// ranges share an upper and lower bound — `[0..<5, 5..<10]` is ill-formed,\n /// and would instead be represented as `[0..<10]`.\n @usableFromInline\n internal func _checkInvariants() {\n#if INTERNAL_CHECKS_ENABLED\n for (a, b) in zip(_ranges, _ranges.dropFirst()) {\n _precondition(!a.isEmpty && !b.isEmpty, "Empty range in range set")\n _precondition(\n a.upperBound < b.lowerBound,\n "Out of order/overlapping ranges in range set")\n }\n#endif\n }\n \n /// Creates a new range set from `ranges`, which satisfies the range set\n /// invariants.\n @usableFromInline\n internal init(_orderedRanges ranges: [Range<Bound>]) {\n switch ranges.count {\n case 0: self._ranges = Ranges()\n case 1: self._ranges = Ranges(_range: ranges[0])\n default: self._ranges = Ranges(_ranges: ranges)\n }\n _checkInvariants()\n }\n \n /// A Boolean value indicating whether the range set is empty.\n public var isEmpty: Bool {\n _ranges.isEmpty\n }\n \n /// Returns a Boolean value indicating whether the given value is\n /// contained by the ranges in the range set.\n ///\n /// - Parameter value: The value to look for in the range set.\n /// - Returns: `true` if `value` is contained by a range in the range set;\n /// otherwise, `false`.\n ///\n /// - Complexity: O(log *n*), where *n* is the number of ranges in the\n /// range set.\n public func contains(_ value: Bound) -> Bool {\n _ranges._contains(value)\n }\n \n /// Inserts the given range into the range set.\n ///\n /// - Parameter range: The range to insert into the set.\n ///\n /// - Complexity: O(*n*), where *n* is the number of ranges in the range\n /// set.\n @inlinable\n public mutating func insert(contentsOf range: Range<Bound>) {\n if range.isEmpty { return }\n _ranges._insert(contentsOf: range)\n }\n \n /// Removes the given range from the range set.\n ///\n /// - Parameter range: The range to remove from the set.\n ///\n /// - Complexity: O(*n*), where *n* is the number of ranges in the range\n /// set.\n public mutating func remove(contentsOf range: Range<Bound>) {\n if range.isEmpty { return }\n _ranges._remove(contentsOf: range)\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension RangeSet: Equatable {\n public static func == (left: Self, right: Self) -> Bool {\n left._ranges == right._ranges\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension RangeSet: Hashable where Bound: Hashable {\n public func hash(into hasher: inout Hasher) {\n hasher.combine(self._ranges)\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension RangeSet: Sendable where Bound: Sendable {}\n\n// MARK: - Collection APIs\n\n@available(SwiftStdlib 6.0, *)\nextension RangeSet {\n /// Creates a new range set containing ranges that contain only the\n /// specified indices in the given collection.\n ///\n /// - Parameters:\n /// - index: The index to include in the range set. `index` must be a\n /// valid index of `collection` that isn't the collection's `endIndex`.\n /// - collection: The collection that contains `index`.\n @inlinable\n public init<S: Sequence, C: Collection>(\n _ indices: S, within collection: C\n ) where S.Element == C.Index, C.Index == Bound {\n self.init()\n for i in indices {\n self.insert(i, within: collection)\n }\n }\n\n /// Inserts a range that contains only the specified index into the range\n /// set.\n ///\n /// - Parameters:\n /// - index: The index to insert into the range set. `index` must be a\n /// valid index of `collection` that isn't the collection's `endIndex`.\n /// - collection: The collection that contains `index`.\n ///\n /// - Returns: `true` if the range set was modified, or `false` if\n /// the given `index` was already in the range set.\n ///\n /// - Complexity: O(*n*), where *n* is the number of ranges in the range\n /// set.\n @discardableResult\n public mutating func insert<C: Collection>(\n _ index: Bound, within collection: C\n ) -> Bool where C.Index == Bound {\n _ranges._insert(contentsOf: index ..< collection.index(after: index))\n }\n \n /// Removes the range that contains only the specified index from the range\n /// set.\n ///\n /// - Parameters:\n /// - index: The index to remove from the range set. `index` must be a\n /// valid index of `collection` that isn't the collection's `endIndex`.\n /// - collection: The collection that contains `index`.\n ///\n /// - Complexity: O(*n*), where *n* is the number of ranges in the range\n /// set.\n public mutating func remove<C: Collection>(\n _ index: Bound, within collection: C\n ) where C.Index == Bound {\n remove(contentsOf: index ..< collection.index(after: index))\n }\n\n /// Returns a range set that represents all the elements in the given\n /// collection that aren't represented by this range set.\n ///\n /// - Parameter collection: The collection that the range set is relative\n /// to.\n /// - Returns: A new range set that represents the elements in `collection`\n /// that aren't represented by this range set.\n ///\n /// - Complexity: O(*n*), where *n* is the number of ranges in the range\n /// set.\n @usableFromInline\n internal func _inverted<C: Collection>(\n within collection: C\n ) -> RangeSet where C: Collection, C.Index == Bound {\n return RangeSet(_ranges: _ranges._gaps(\n boundedBy: collection.startIndex ..< collection.endIndex))\n }\n}\n\n// MARK: - SetAlgebra\n\n// These methods only depend on the ranges that comprise the range set, so\n// we can provide them even when we can't provide `SetAlgebra` conformance.\n@available(SwiftStdlib 6.0, *)\nextension RangeSet {\n /// Adds the contents of the given range set to this range set.\n ///\n /// - Parameter other: A range set to merge with this one.\n ///\n /// - Complexity: O(*m* + *n*), where *m* and *n* are the number of ranges in\n /// this and the other range set.\n public mutating func formUnion(_ other: __owned RangeSet<Bound>) {\n self = self.union(other)\n }\n \n /// Removes the contents of this range set that aren't also in the given\n /// range set.\n ///\n /// - Parameter other: A range set to intersect with.\n public mutating func formIntersection(_ other: RangeSet<Bound>) {\n self = self.intersection(other)\n }\n \n /// Removes the contents of this range set that are also in the given set\n /// and adds the contents of the given set that are not already in this\n /// range set.\n ///\n /// - Parameter other: A range set to perform a symmetric difference against.\n public mutating func formSymmetricDifference(\n _ other: __owned RangeSet<Bound>\n ) {\n self = self.symmetricDifference(other)\n }\n \n /// Removes the contents of the given range set from this range set.\n ///\n /// - Parameter other: A range set to subtract from this one.\n public mutating func subtract(_ other: RangeSet<Bound>) {\n for range in other._ranges {\n remove(contentsOf: range)\n }\n }\n \n /// Returns a new range set containing the contents of both this set and the\n /// given set.\n ///\n /// - Parameter other: The range set to merge with this one.\n /// - Returns: A new range set.\n public __consuming func union(\n _ other: __owned RangeSet<Bound>\n ) -> RangeSet<Bound> {\n return RangeSet(_ranges: _ranges._union(other._ranges))\n }\n \n /// Returns a new range set containing the contents of both this set and the\n /// given set.\n ///\n /// - Parameter other: The range set to merge with this one.\n /// - Returns: A new range set.\n public __consuming func intersection(\n _ other: RangeSet<Bound>\n ) -> RangeSet<Bound> {\n return RangeSet(_ranges: _ranges._intersection(other._ranges))\n }\n \n /// Returns a new range set representing the values in this range set or the\n /// given range set, but not both.\n ///\n /// - Parameter other: The range set to find a symmetric difference with.\n /// - Returns: A new range set.\n public __consuming func symmetricDifference(\n _ other: __owned RangeSet<Bound>\n ) -> RangeSet<Bound> {\n return union(other).subtracting(intersection(other))\n }\n \n /// Returns a new set containing the contents of this range set that are not\n /// also in the given range set.\n ///\n /// - Parameter other: The range set to subtract.\n /// - Returns: A new range set.\n public __consuming func subtracting(\n _ other: RangeSet<Bound>\n ) -> RangeSet<Bound> {\n var result = self\n result.subtract(other)\n return result\n }\n \n /// Returns a Boolean value that indicates whether this range set is a\n /// subset of the given set.\n ///\n /// - Parameter other: A range set to compare against.\n /// - Returns: `true` if this range set is a subset of `other`;\n /// otherwise, `false`.\n public func isSubset(of other: RangeSet<Bound>) -> Bool {\n var remaining = other.ranges[...]\n for range in ranges {\n guard let containingIdx = remaining.firstIndex(where: {\n $0.contains(range.lowerBound)\n }) else {\n return false\n }\n\n if remaining[containingIdx].upperBound < range.upperBound {\n return false\n }\n\n remaining = other.ranges[containingIdx...]\n }\n return true\n }\n \n /// Returns a Boolean value that indicates whether this range set is a\n /// superset of the given set.\n ///\n /// - Parameter other: A range set to compare against.\n /// - Returns: `true` if this range set is a superset of `other`;\n /// otherwise, `false`.\n public func isSuperset(of other: RangeSet<Bound>) -> Bool {\n other.isSubset(of: self)\n }\n \n /// Returns a Boolean value that indicates whether this range set is a\n /// strict subset of the given set.\n ///\n /// - Parameter other: A range set to compare against.\n /// - Returns: `true` if this range set is a strict subset of `other`;\n /// otherwise, `false`.\n public func isStrictSubset(of other: RangeSet<Bound>) -> Bool {\n self != other && isSubset(of: other)\n }\n \n /// Returns a Boolean value that indicates whether this range set is a\n /// strict superset of the given set.\n ///\n /// - Parameter other: A range set to compare against.\n /// - Returns: `true` if this range set is a strict superset of `other`;\n /// otherwise, `false`.\n public func isStrictSuperset(of other: RangeSet<Bound>) -> Bool {\n other.isStrictSubset(of: self)\n }\n\n /// Returns a Boolean value that indicates whether this range set set has\n /// no members in common with the given set.\n ///\n /// - Parameter other: A range set to compare against.\n /// - Returns: `true` if this range set has no elements in common with\n /// `other`; otherwise, `false`.\n public func isDisjoint(_ other: RangeSet<Bound>) -> Bool {\n self.intersection(other).isEmpty\n }\n}\n\n@available(SwiftStdlib 6.0, *)\n@_unavailableInEmbedded\nextension RangeSet: CustomStringConvertible {\n public var description: String {\n return _ranges.description\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_RangeSet.swift
cpp_apple_swift_stdlib_public_core_RangeSet.swift
Swift
13,820
0.8
0.061576
0.509485
vue-tools
789
2024-08-25T23:04:45.425079
BSD-3-Clause
false
97b4ec8b88fc98347600ca8122cc4be5
//===--- RangeSetRanges.swift ---------------------------------*- swift -*-===//\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\n@available(SwiftStdlib 6.0, *)\nextension RangeSet {\n /// A collection of the ranges that make up a range set.\n public struct Ranges {\n internal var _storage: ContiguousArray<Range<Bound>>\n\n @usableFromInline\n internal init() {\n _storage = []\n }\n \n @usableFromInline\n internal init(_range: Range<Bound>) {\n _storage = [_range]\n }\n \n @usableFromInline\n internal init(_ranges: [Range<Bound>]) {\n _storage = ContiguousArray(_ranges)\n }\n\n @usableFromInline\n internal init(_unorderedRanges: [Range<Bound>]) {\n _storage = ContiguousArray(_unorderedRanges)\n _storage.sort {\n $0.lowerBound < $1.lowerBound\n }\n \n // Find the index of the first non-empty range. If all ranges are empty,\n // the result is empty.\n guard let firstNonEmpty = _storage.firstIndex(where: { $0.isEmpty == false }) else {\n _storage = []\n return\n }\n \n // Swap that non-empty range to be first. (This and the swap in the loop\n // might be no-ops, if no empty or overlapping ranges have been found.)\n _storage.swapAt(0, firstNonEmpty)\n \n // That single range is now a valid range set, so we set up three sections \n // of the storage array:\n //\n // 1: a processed, valid range set (0...lastValid)\n // 2: ranges to discard (lastValid + 1 ..< current)\n // 3: unprocessed ranges (current ..< _storage.count)\n //\n // Section 2 is made up of ranges that are either empty or that overlap\n // with the ranges in section 1. By waiting to remove these ranges until\n // we've processed the entire array, we avoid needing to constantly\n // reshuffle the elements during processing.\n var lastValid = 0\n var current = firstNonEmpty + 1\n \n while current < _storage.count {\n defer { current += 1 }\n \n // Skip over empty ranges.\n if _storage[current].isEmpty { continue }\n \n // If the last valid range overlaps with the current range, extend the\n // last valid range to cover the current.\n if _storage[lastValid].upperBound >= _storage[current].lowerBound {\n let newUpper = Swift.max(\n _storage[lastValid].upperBound,\n _storage[current].upperBound)\n _storage[lastValid] = unsafe Range(\n uncheckedBounds: (_storage[lastValid].lowerBound, newUpper))\n } else {\n // Otherwise, this is a valid new range to add to the range set: \n // swap it into place at the end of the valid section.\n lastValid += 1\n _storage.swapAt(current, lastValid)\n }\n }\n \n // Now that we've processed the whole array, remove anything left after\n // the valid section.\n _storage.removeSubrange((lastValid + 1) ..< _storage.count)\n }\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension RangeSet.Ranges {\n @usableFromInline\n internal func _contains(_ bound: Bound) -> Bool {\n let i = _storage._partitioningIndex { $0.upperBound > bound }\n return i == _storage.endIndex ? false : _storage[i].lowerBound <= bound\n }\n\n /// Returns a range indicating the existing ranges that `range` overlaps\n /// with.\n ///\n /// For example, if `self` is `[0..<5, 10..<15, 20..<25, 30..<35]`, then:\n ///\n /// - `_indicesOfRange(12..<14) == 1..<2`\n /// - `_indicesOfRange(12..<19) == 1..<2`\n /// - `_indicesOfRange(17..<19) == 2..<2`\n /// - `_indicesOfRange(12..<22) == 1..<3`\n @usableFromInline\n internal func _indicesOfRange(\n _ range: Range<Bound>,\n in subranges: ContiguousArray<Range<Bound>>,\n includeAdjacent: Bool = true\n ) -> Range<Int> {\n guard subranges.count > 1 else {\n if subranges.isEmpty {\n return 0 ..< 0\n } else {\n let subrange = subranges[0]\n if range.upperBound < subrange.lowerBound {\n return 0 ..< 0\n } else if range.lowerBound > subrange.upperBound {\n return 1 ..< 1\n } else {\n return 0 ..< 1\n }\n }\n }\n\n // The beginning index for the position of `range` is the first range\n // with an upper bound larger than `range`'s lower bound. The range\n // at this position may or may not overlap `range`.\n let beginningIndex = subranges._partitioningIndex {\n if includeAdjacent {\n $0.upperBound >= range.lowerBound\n } else {\n $0.upperBound > range.lowerBound\n }\n }\n \n // The ending index for `range` is the first range with a lower bound\n // greater than `range`'s upper bound. If this is the same as\n // `beginningIndex`, than `range` doesn't overlap any of the existing\n // ranges. If this is `ranges.endIndex`, then `range` overlaps the\n // rest of the ranges. Otherwise, `range` overlaps one or\n // more ranges in the set.\n let endingIndex = subranges[beginningIndex...]._partitioningIndex {\n if includeAdjacent {\n $0.lowerBound > range.upperBound\n } else {\n $0.lowerBound >= range.upperBound\n }\n }\n \n return beginningIndex ..< endingIndex\n }\n\n // Insert a non-empty range into the storage\n @usableFromInline\n @discardableResult\n internal mutating func _insert(contentsOf range: Range<Bound>) -> Bool {\n let indices = _indicesOfRange(range, in: _storage)\n if indices.isEmpty {\n _storage.insert(range, at: indices.lowerBound)\n return true\n } else {\n let lower = Swift.min(\n _storage[indices.lowerBound].lowerBound, range.lowerBound)\n let upper = Swift.max(\n _storage[indices.upperBound - 1].upperBound, range.upperBound)\n let newRange = lower ..< upper\n if indices.count == 1 && newRange == _storage[indices.lowerBound] {\n return false\n }\n _storage.replaceSubrange(indices, with: CollectionOfOne(newRange))\n return true\n }\n }\n\n // Remove a non-empty range from the storage\n @usableFromInline\n internal mutating func _remove(contentsOf range: Range<Bound>) {\n let indices = _indicesOfRange(range, in: _storage, includeAdjacent: false)\n guard !indices.isEmpty else {\n return\n }\n \n let overlapsLowerBound =\n range.lowerBound > _storage[indices.lowerBound].lowerBound\n let overlapsUpperBound =\n range.upperBound < _storage[indices.upperBound - 1].upperBound\n\n switch (overlapsLowerBound, overlapsUpperBound) {\n case (false, false):\n _storage.removeSubrange(indices)\n case (false, true):\n let newRange =\n range.upperBound..<_storage[indices.upperBound - 1].upperBound\n _storage.replaceSubrange(indices, with: CollectionOfOne(newRange))\n case (true, false):\n let newRange =\n _storage[indices.lowerBound].lowerBound ..< range.lowerBound\n _storage.replaceSubrange(indices, with: CollectionOfOne(newRange))\n case (true, true):\n _storage.replaceSubrange(indices, with: _Pair(\n _storage[indices.lowerBound].lowerBound..<range.lowerBound,\n range.upperBound..<_storage[indices.upperBound - 1].upperBound\n ))\n }\n }\n\n /// Returns a that represents the ranges of values within the\n /// given bounds that aren't represented by this range set.\n @usableFromInline\n internal func _gaps(boundedBy bounds: Range<Bound>) -> Self {\n let indices = _indicesOfRange(bounds, in: _storage)\n guard !indices.isEmpty else {\n return Self(_range: bounds)\n }\n \n var result: [Range<Bound>] = []\n var low = bounds.lowerBound\n for range in _storage[indices] {\n let gapRange = low ..< range.lowerBound\n if !gapRange.isEmpty {\n result.append(gapRange)\n }\n low = range.upperBound\n }\n let finalRange = low ..< bounds.upperBound\n if !finalRange.isEmpty {\n result.append(finalRange)\n }\n let resultVal = Self(_ranges: result)\n return resultVal\n }\n\n @usableFromInline\n internal func _intersection(_ other: Self) -> Self {\n let left = self._storage\n let right = other._storage\n var otherRangeIndex = 0\n var result: [Range<Bound>] = []\n \n // Considering these two range sets:\n //\n // self = [0..<5, 9..<14]\n // other = [1..<3, 4..<6, 8..<12]\n //\n // `self.intersection(other)` looks like this, where x's cover the\n // ranges in `self`, y's cover the ranges in `other`, and z's cover the\n // resulting ranges:\n //\n // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n // xxxxxxxxxxxxxxxxxxx__ xxxxxxxxxxxxxxxxxxx__\n // yyyyyyy__ yyyyyyy__ yyyyyyyyyyyyyyy__\n // zzzzzzz__ zzz__ zzzzzzzzzzz__\n //\n // The same, but for `other.intersection(self)`:\n //\n // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n // xxxxxxx__ xxxxxxx__ xxxxxxxxxxxxxxx__\n // yyyyyyyyyyyyyyyyyyy__ yyyyyyyyyyyyyyyyyyy__\n // zzzzzzz__ zzz__ zzzzzzzzzzz__\n \n for currentRange in left {\n // Search forward in `right` until finding either an overlapping\n // range or one that is strictly higher than this range.\n while otherRangeIndex < right.endIndex &&\n right[otherRangeIndex].upperBound <= currentRange.lowerBound\n {\n otherRangeIndex += 1\n }\n \n // For each range in `right` that overlaps with the current range\n // in `left`, append the intersection to the result.\n while otherRangeIndex < right.endIndex &&\n right[otherRangeIndex].lowerBound < currentRange.upperBound\n {\n let overlap = right[otherRangeIndex].clamped(to: currentRange)\n result.append(overlap)\n \n // If the range in `right` continues past the current range in\n // `self`, it could overlap the next range in `self`, so break\n // out of examining the current range.\n guard\n currentRange.upperBound > right[otherRangeIndex].upperBound\n else {\n break\n }\n otherRangeIndex += 1\n }\n }\n \n return Self(_ranges: result)\n }\n \n @usableFromInline\n internal func _union(_ other: Self) -> Self {\n // Empty cases\n if other.isEmpty {\n return self\n } else if self.isEmpty {\n return other\n }\n \n // Instead of naively inserting the ranges of `other` into `self`,\n // which can cause reshuffling with every insertion, this approach\n // uses the guarantees that each array of ranges is non-overlapping and in\n // increasing order to directly derive the union.\n //\n // Each range in the resulting range set is found by:\n //\n // 1. Finding the current lowest bound of the two range sets.\n // 2. Searching for the first upper bound that is outside the merged\n // boundaries of the two range sets.\n \n // Use temporaries so that we can swap a/b, to simplify the logic below\n var a = self._storage\n var b = other._storage\n var aIndex = a.startIndex\n var bIndex = b.startIndex\n \n var result: [Range<Bound>] = []\n while aIndex < a.endIndex, bIndex < b.endIndex {\n // Make sure that `a` is the source of the lower bound and `b` is the\n // potential source for the upper bound.\n if b[bIndex].lowerBound < a[aIndex].lowerBound {\n swap(&a, &b)\n swap(&aIndex, &bIndex)\n }\n \n var candidateRange = a[aIndex]\n aIndex += 1\n \n // Look for the correct upper bound, which is the first upper bound that\n // isn't contained in the next range of the "other" ranges array.\n while bIndex < b.endIndex, candidateRange.upperBound >= b[bIndex].lowerBound {\n if candidateRange.upperBound >= b[bIndex].upperBound {\n // The range `b[bIndex]` is entirely contained by `candidateRange`,\n // so we need to advance and look at the next range in `b`.\n bIndex += 1\n } else {\n // The range `b[bIndex]` extends past `candidateRange`, so:\n //\n // 1. We grow `candidateRange` to the upper bound of `b[bIndex]`\n // 2. We swap the two range arrays, so that we're looking for the\n // new upper bound in the other array.\n candidateRange = candidateRange.lowerBound ..< b[bIndex].upperBound\n bIndex += 1\n swap(&a, &b)\n swap(&aIndex, &bIndex)\n }\n }\n \n result.append(candidateRange)\n }\n \n // Collect any remaining ranges without needing to merge.\n if aIndex < a.endIndex {\n result.append(contentsOf: a[aIndex...])\n } else if bIndex < b.endIndex {\n result.append(contentsOf: b[bIndex...])\n }\n\n return Self(_ranges: result)\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension RangeSet.Ranges: Sequence {\n public typealias Element = Range<Bound>\n public typealias Iterator = IndexingIterator<Self>\n}\n\n@available(SwiftStdlib 6.0, *)\nextension RangeSet.Ranges: Collection {\n public typealias Index = Int\n public typealias Indices = Range<Index>\n public typealias SubSequence = Slice<Self>\n \n public var startIndex: Index {\n 0\n }\n \n public var endIndex: Index {\n _storage.count\n }\n \n public var count: Int {\n self.endIndex\n }\n\n public subscript(i: Index) -> Element {\n _storage[i]\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension RangeSet.Ranges: RandomAccessCollection {}\n\n@available(SwiftStdlib 6.0, *)\nextension RangeSet.Ranges: Equatable {\n public static func == (left: Self, right: Self) -> Bool {\n left._storage == right._storage\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension RangeSet.Ranges: Hashable where Bound: Hashable {\n public func hash(into hasher: inout Hasher) {\n hasher.combine(_storage)\n }\n}\n\n@available(SwiftStdlib 6.0, *)\nextension RangeSet.Ranges: Sendable where Bound: Sendable {}\n\n@available(SwiftStdlib 6.0, *)\n@_unavailableInEmbedded\nextension RangeSet.Ranges: CustomStringConvertible {\n public var description: String {\n _makeCollectionDescription()\n }\n}\n\n/// A collection of two elements, to avoid heap allocation when calling\n/// `replaceSubrange` with just two elements.\ninternal struct _Pair<Element>: RandomAccessCollection {\n internal var pair: (first: Element, second: Element)\n \n internal init(_ first: Element, _ second: Element) {\n self.pair = (first, second)\n }\n \n internal var startIndex: Int { 0 }\n internal var endIndex: Int { 2 }\n \n internal subscript(position: Int) -> Element {\n get {\n switch position {\n case 0: return pair.first\n case 1: return pair.second\n default: _preconditionFailure("Index is out of range")\n }\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_RangeSetRanges.swift
cpp_apple_swift_stdlib_public_core_RangeSetRanges.swift
Swift
15,021
0.8
0.08204
0.273869
vue-tools
797
2023-09-03T21:03:28.526367
GPL-3.0
false
971fa72dce6be11531f80ff60e468b8f
//===----------------------------------------------------------------------===//\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#if SWIFT_ENABLE_REFLECTION\n\nimport SwiftShims\n\ninternal func _isClassType(_ type: Any.Type) -> Bool {\n // a thick metatype is represented with a pointer metadata structure,\n // so this unsafeBitCast is a safe operation here.\n return unsafe swift_isClassType(unsafeBitCast(type, to: UnsafeRawPointer.self))\n}\n\n@_silgen_name("swift_getMetadataKind")\ninternal func _metadataKind(_: Any.Type) -> UInt\n\n@_silgen_name("swift_reflectionMirror_normalizedType")\ninternal func _getNormalizedType<T>(_: T, type: Any.Type) -> Any.Type\n\n@_silgen_name("swift_reflectionMirror_count")\ninternal func _getChildCount<T>(_: T, type: Any.Type) -> Int\n\n@_silgen_name("swift_reflectionMirror_recursiveCount")\ninternal func _getRecursiveChildCount(_: Any.Type) -> Int\n\n@_silgen_name("swift_reflectionMirror_recursiveChildMetadata")\ninternal func _getChildMetadata(\n _: Any.Type,\n index: Int,\n fieldMetadata: UnsafeMutablePointer<_FieldReflectionMetadata>\n) -> Any.Type\n\n@_silgen_name("swift_reflectionMirror_recursiveChildOffset")\ninternal func _getChildOffset(\n _: Any.Type,\n index: Int\n) -> Int\n\ninternal typealias NameFreeFunc = @convention(c) (UnsafePointer<CChar>?) -> Void\n\n@_silgen_name("swift_reflectionMirror_subscript")\ninternal func _getChild<T>(\n of: T,\n type: Any.Type,\n index: Int,\n outName: UnsafeMutablePointer<UnsafePointer<CChar>?>,\n outFreeFunc: UnsafeMutablePointer<NameFreeFunc?>\n) -> Any\n\n// Returns 'c' (class), 'e' (enum), 's' (struct), 't' (tuple), or '\0' (none)\n@_silgen_name("swift_reflectionMirror_displayStyle")\ninternal func _getDisplayStyle<T>(_: T) -> CChar\n\ninternal func getChild<T>(of value: T, type: Any.Type, index: Int) -> (label: String?, value: Any) {\n var nameC: UnsafePointer<CChar>? = nil\n var freeFunc: NameFreeFunc? = nil\n \n let value = unsafe _getChild(of: value, type: type, index: index, outName: &nameC, outFreeFunc: &freeFunc)\n \n let name = unsafe nameC.flatMap({ unsafe String(validatingCString: $0) })\n unsafe freeFunc?(nameC)\n return (name, value)\n}\n\n#if _runtime(_ObjC)\n@_silgen_name("swift_reflectionMirror_quickLookObject")\ninternal func _getQuickLookObject<T>(_: T) -> AnyObject?\n\n@_silgen_name("_swift_stdlib_NSObject_isKindOfClass")\ninternal func _isImpl(_ object: AnyObject, kindOf: UnsafePointer<CChar>) -> Bool\n\ninternal func _is(_ object: AnyObject, kindOf `class`: String) -> Bool {\n return unsafe `class`.withCString {\n return unsafe _isImpl(object, kindOf: $0)\n }\n}\n\ninternal func _getClassPlaygroundQuickLook(\n _ object: AnyObject\n) -> _PlaygroundQuickLook? {\n if _is(object, kindOf: "NSNumber") {\n let number: _NSNumber = unsafe unsafeBitCast(object, to: _NSNumber.self)\n switch unsafe UInt8(number.objCType[0]) {\n case UInt8(ascii: "d"):\n return .double(number.doubleValue)\n case UInt8(ascii: "f"):\n return .float(number.floatValue)\n case UInt8(ascii: "Q"):\n return .uInt(number.unsignedLongLongValue)\n default:\n return .int(number.longLongValue)\n }\n }\n \n if _is(object, kindOf: "NSAttributedString") {\n return .attributedString(object)\n }\n \n if _is(object, kindOf: "NSImage") ||\n _is(object, kindOf: "UIImage") ||\n _is(object, kindOf: "NSImageView") ||\n _is(object, kindOf: "UIImageView") ||\n _is(object, kindOf: "CIImage") ||\n _is(object, kindOf: "NSBitmapImageRep") {\n return .image(object)\n }\n \n if _is(object, kindOf: "NSColor") ||\n _is(object, kindOf: "UIColor") {\n return .color(object)\n }\n \n if _is(object, kindOf: "NSBezierPath") ||\n _is(object, kindOf: "UIBezierPath") {\n return .bezierPath(object)\n }\n \n if _is(object, kindOf: "NSString") {\n return .text(_forceBridgeFromObjectiveC(object, String.self))\n }\n\n return .none\n}\n#endif\n\nextension Mirror {\n internal init(internalReflecting subject: Any,\n subjectType: Any.Type? = nil,\n customAncestor: Mirror? = nil)\n {\n let subjectType = subjectType ?? _getNormalizedType(subject, type: type(of: subject))\n \n let childCount = _getChildCount(subject, type: subjectType)\n let children = (0 ..< childCount).lazy.map({\n getChild(of: subject, type: subjectType, index: $0)\n })\n self.children = Children(children)\n \n self._makeSuperclassMirror = {\n guard let subjectClass = subjectType as? AnyClass,\n let superclass = _getSuperclass(subjectClass) else {\n return nil\n }\n \n // Handle custom ancestors. If we've hit the custom ancestor's subject type,\n // or descendants are suppressed, return it. Otherwise continue reflecting.\n if let customAncestor = customAncestor {\n if superclass == customAncestor.subjectType {\n return customAncestor\n }\n if customAncestor._defaultDescendantRepresentation == .suppressed {\n return customAncestor\n }\n }\n return Mirror(internalReflecting: subject,\n subjectType: superclass,\n customAncestor: customAncestor)\n }\n \n let rawDisplayStyle = _getDisplayStyle(subject)\n switch UnicodeScalar(Int(rawDisplayStyle)) {\n case "c": self.displayStyle = .class\n case "e": self.displayStyle = .enum\n case "s": self.displayStyle = .struct\n case "t": self.displayStyle = .tuple\n case "\0": self.displayStyle = nil\n default: preconditionFailure("Unknown raw display style '\(rawDisplayStyle)'")\n }\n \n self.subjectType = subjectType\n self._defaultDescendantRepresentation = .generated\n }\n \n internal static func quickLookObject(_ subject: Any) -> _PlaygroundQuickLook? {\n#if _runtime(_ObjC)\n let object = _getQuickLookObject(subject)\n return object.flatMap(_getClassPlaygroundQuickLook)\n#else\n return nil\n#endif\n }\n}\n\n/// Options for calling `_forEachField(of:options:body:)`.\n@available(SwiftStdlib 5.2, *)\n@_spi(Reflection)\npublic struct _EachFieldOptions: OptionSet {\n public var rawValue: UInt32\n\n public init(rawValue: UInt32) {\n self.rawValue = rawValue\n }\n\n /// Require the top-level type to be a class.\n ///\n /// If this is not set, the top-level type is required to be a struct or\n /// tuple.\n public static var classType = _EachFieldOptions(rawValue: 1 << 0)\n\n /// Ignore fields that can't be introspected.\n ///\n /// If not set, the presence of things that can't be introspected causes\n /// the function to immediately return `false`.\n public static var ignoreUnknown = _EachFieldOptions(rawValue: 1 << 1)\n}\n\n@available(SwiftStdlib 5.2, *)\nextension _EachFieldOptions: Sendable {}\n\n/// The metadata "kind" for a type.\n@available(SwiftStdlib 5.2, *)\n@_spi(Reflection)\npublic enum _MetadataKind: UInt {\n // With "flags":\n // runtimePrivate = 0x100\n // nonHeap = 0x200\n // nonType = 0x400\n \n case `class` = 0\n case `struct` = 0x200 // 0 | nonHeap\n case `enum` = 0x201 // 1 | nonHeap\n case optional = 0x202 // 2 | nonHeap\n case foreignClass = 0x203 // 3 | nonHeap\n case opaque = 0x300 // 0 | runtimePrivate | nonHeap\n case tuple = 0x301 // 1 | runtimePrivate | nonHeap\n case function = 0x302 // 2 | runtimePrivate | nonHeap\n case existential = 0x303 // 3 | runtimePrivate | nonHeap\n case metatype = 0x304 // 4 | runtimePrivate | nonHeap\n case objcClassWrapper = 0x305 // 5 | runtimePrivate | nonHeap\n case existentialMetatype = 0x306 // 6 | runtimePrivate | nonHeap\n case heapLocalVariable = 0x400 // 0 | nonType\n case heapGenericLocalVariable = 0x500 // 0 | nonType | runtimePrivate\n case errorObject = 0x501 // 1 | nonType | runtimePrivate\n case unknown = 0xffff\n \n init(_ type: Any.Type) {\n let v = _metadataKind(type)\n if let result = _MetadataKind(rawValue: v) {\n self = result\n } else {\n self = .unknown\n }\n }\n}\n\n@available(SwiftStdlib 5.2, *)\nextension _MetadataKind: Sendable {}\n\n/// Calls the given closure on every field of the specified type.\n///\n/// If `body` returns `false` for any field, no additional fields are visited.\n///\n/// - Parameters:\n/// - type: The type to inspect.\n/// - options: Options to use when reflecting over `type`.\n/// - body: A closure to call with information about each field in `type`.\n/// The parameters to `body` are a pointer to a C string holding the name\n/// of the field, the offset of the field in bytes, the type of the field,\n/// and the `_MetadataKind` of the field's type.\n/// - Returns: `true` if every invocation of `body` returns `true`; otherwise,\n/// `false`.\n@available(SwiftStdlib 5.2, *)\n@discardableResult\n@_spi(Reflection)\npublic func _forEachField(\n of type: Any.Type,\n options: _EachFieldOptions = [],\n body: (UnsafePointer<CChar>, Int, Any.Type, _MetadataKind) -> Bool\n) -> Bool {\n // Require class type iff `.classType` is included as an option\n if _isClassType(type) != options.contains(.classType) {\n return false\n }\n\n let childCount = _getRecursiveChildCount(type)\n for i in 0..<childCount {\n let offset = _getChildOffset(type, index: i)\n\n var field = unsafe _FieldReflectionMetadata()\n let childType = unsafe _getChildMetadata(type, index: i, fieldMetadata: &field)\n defer { unsafe field.freeFunc?(field.name) }\n let kind = _MetadataKind(childType)\n\n if let name = unsafe field.name {\n if unsafe !body(name, offset, childType, kind) {\n return false\n }\n } else {\n if unsafe !body("", offset, childType, kind) {\n return false\n }\n }\n }\n\n return true\n}\n\n/// Calls the given closure on every field of the specified type.\n///\n/// If `body` returns `false` for any field, no additional fields are visited.\n///\n/// - Parameters:\n/// - type: The type to inspect.\n/// - options: Options to use when reflecting over `type`.\n/// - body: A closure to call with information about each field in `type`.\n/// The parameters to `body` are a pointer to a C string holding the name\n/// of the field and an erased keypath for it.\n/// - Returns: `true` if every invocation of `body` returns `true`; otherwise,\n/// `false`.\n@available(SwiftStdlib 5.4, *)\n@discardableResult\n@_spi(Reflection)\npublic func _forEachFieldWithKeyPath<Root>(\n of type: Root.Type,\n options: _EachFieldOptions = [],\n body: (UnsafePointer<CChar>, PartialKeyPath<Root>) -> Bool\n) -> Bool {\n // Class types not supported because the metadata does not have\n // enough information to construct computed properties.\n if _isClassType(type) || options.contains(.classType) {\n return false\n }\n let ignoreUnknown = options.contains(.ignoreUnknown)\n\n let childCount = _getRecursiveChildCount(type)\n for i in 0..<childCount {\n let offset = _getChildOffset(type, index: i)\n\n var field = unsafe _FieldReflectionMetadata()\n let childType = unsafe _getChildMetadata(type, index: i, fieldMetadata: &field)\n defer { unsafe field.freeFunc?(field.name) }\n let kind = _MetadataKind(childType)\n let supportedType: Bool\n switch kind {\n case .struct, .class, .optional, .existential,\n .existentialMetatype, .tuple, .enum:\n supportedType = true\n default:\n supportedType = false\n }\n if unsafe !supportedType || !field.isStrong {\n if !ignoreUnknown { return false }\n continue;\n }\n func keyPathType<Leaf>(for: Leaf.Type) -> PartialKeyPath<Root>.Type {\n if unsafe field.isVar { return WritableKeyPath<Root, Leaf>.self }\n return KeyPath<Root, Leaf>.self\n }\n let resultSize = MemoryLayout<Int32>.size + MemoryLayout<Int>.size\n let partialKeyPath = unsafe _openExistential(childType, do: keyPathType)\n ._create(capacityInBytes: resultSize) {\n var destBuilder = unsafe KeyPathBuffer.Builder($0)\n unsafe destBuilder.pushHeader(KeyPathBuffer.Header(\n size: resultSize - MemoryLayout<Int>.size,\n trivial: true,\n hasReferencePrefix: false,\n isSingleComponent: true\n ))\n let component = unsafe RawKeyPathComponent(\n header: RawKeyPathComponent.Header(stored: .struct,\n mutable: field.isVar,\n inlineOffset: UInt32(offset)),\n body: UnsafeRawBufferPointer(start: nil, count: 0))\n unsafe component.clone(\n into: &destBuilder.buffer,\n endOfReferencePrefix: false)\n }\n\n if let name = unsafe field.name {\n if unsafe !body(name, partialKeyPath) {\n return false\n }\n } else {\n if unsafe !body("", partialKeyPath) {\n return false\n }\n }\n }\n\n return true\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ReflectionMirror.swift
cpp_apple_swift_stdlib_public_core_ReflectionMirror.swift
Swift
13,010
0.95
0.125
0.191176
react-lib
778
2024-10-16T00:05:32.728272
MIT
false
ff0c33f879422b40b7c29dd5a4bd5191
//===--- Repeat.swift - A Collection that repeats a value N times ---------===//\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 whose elements are all identical.\n///\n/// You create an instance of the `Repeated` collection by calling the\n/// `repeatElement(_:count:)` function. The following example creates a\n/// collection containing the name "Humperdinck" repeated five times:\n///\n/// let repeatedName = repeatElement("Humperdinck", count: 5)\n/// for name in repeatedName {\n/// print(name)\n/// }\n/// // "Humperdinck"\n/// // "Humperdinck"\n/// // "Humperdinck"\n/// // "Humperdinck"\n/// // "Humperdinck"\n@frozen\npublic struct Repeated<Element> {\n /// The number of elements in this collection.\n public let count: Int\n\n /// The value of every element in this collection.\n public let repeatedValue: Element\n\n /// Creates an instance that contains `count` elements having the\n /// value `repeatedValue`.\n @inlinable // trivial-implementation\n internal init(_repeating repeatedValue: Element, count: Int) {\n _precondition(count >= 0, "Repetition count should be non-negative")\n self.count = count\n self.repeatedValue = repeatedValue\n }\n}\n\nextension Repeated: RandomAccessCollection {\n public typealias Indices = Range<Int>\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 "past the\n /// end" position that's not valid for use as a subscript.\n public typealias Index = Int\n\n /// The position of the first element in a nonempty collection.\n ///\n /// In a `Repeated` collection, `startIndex` is always equal to zero. If the\n /// collection is empty, `startIndex` is equal to `endIndex`.\n @inlinable // trivial-implementation\n public var startIndex: Index {\n return 0\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 /// In a `Repeated` collection, `endIndex` is always equal to `count`. If the\n /// collection is empty, `endIndex` is equal to `startIndex`.\n @inlinable // trivial-implementation\n public var endIndex: Index {\n return count\n }\n\n /// Accesses the element at the specified position.\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 @inlinable // trivial-implementation\n public subscript(position: Int) -> Element {\n _precondition(position >= 0 && position < count, "Index out of range")\n return repeatedValue\n }\n}\n\n/// Creates a collection containing the specified number of the given element.\n///\n/// The following example creates a `Repeated<Int>` collection containing five\n/// zeroes:\n///\n/// let zeroes = repeatElement(0, count: 5)\n/// for x in zeroes {\n/// print(x)\n/// }\n/// // 0\n/// // 0\n/// // 0\n/// // 0\n/// // 0\n///\n/// - Parameters:\n/// - element: The element to repeat.\n/// - count: The number of times to repeat `element`.\n/// - Returns: A collection that contains `count` elements that are all\n/// `element`.\n@inlinable // trivial-implementation\npublic func repeatElement<T>(_ element: T, count n: Int) -> Repeated<T> {\n return Repeated(_repeating: element, count: n)\n}\n\nextension Repeated: Sendable where Element: Sendable { }\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Repeat.swift
cpp_apple_swift_stdlib_public_core_Repeat.swift
Swift
3,812
0.95
0.054054
0.673267
node-utils
65
2023-09-01T00:14:57.762484
MIT
false
c02c09c773747a7e416269e4aa0ffdb3
//===----------------------------------------------------------------------===//\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_STDLIB_STATIC_PRINT\n\n/// Print a string as is to stdout.\npublic // COMPILER_INTRINSIC\nfunc _replPrintLiteralString(_ text: String) {\n print(text, terminator: "")\n}\n\n/// Print the debug representation of `value`, followed by a newline.\n@inline(never)\npublic // COMPILER_INTRINSIC\nfunc _replDebugPrintln<T>(_ value: T) {\n debugPrint(value)\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_REPL.swift
cpp_apple_swift_stdlib_public_core_REPL.swift
Swift
881
0.8
0.107143
0.625
vue-tools
88
2024-06-28T00:50:13.868885
MIT
false
de1dd60d6de85cc54ff660e3ac6df836
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2018 - 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 value that represents either a success or a failure, including an\n/// associated value in each case.\n@frozen\npublic enum Result<Success: ~Copyable & ~Escapable, Failure: Error> {\n /// A success, storing a `Success` value.\n case success(Success)\n\n /// A failure, storing a `Failure` value.\n case failure(Failure)\n}\n\nextension Result: Copyable where Success: Copyable & ~Escapable {}\n\nextension Result: Escapable where Success: Escapable & ~Copyable {}\n\nextension Result: Sendable where Success: Sendable & ~Copyable & ~Escapable {}\n\nextension Result: Equatable where Success: Equatable, Failure: Equatable {}\n\nextension Result: Hashable where Success: Hashable, Failure: Hashable {}\n\nextension Result {\n /// Returns a new result, mapping any success value using the given\n /// transformation.\n ///\n /// Use this method when you need to transform the value of a `Result`\n /// instance when it represents a success. The following example transforms\n /// the integer success value of a result into a string:\n ///\n /// func getNextInteger() -> Result<Int, Error> { /* ... */ }\n ///\n /// let integerResult = getNextInteger()\n /// // integerResult == .success(5)\n /// let stringResult = integerResult.map { String($0) }\n /// // stringResult == .success("5")\n ///\n /// - Parameter transform: A closure that takes the success value of this\n /// instance.\n /// - Returns: A `Result` instance with the result of evaluating `transform`\n /// as the new success value if this instance represents a success.\n @_alwaysEmitIntoClient\n @_disfavoredOverload // FIXME: Workaround for source compat issue with\n // functions that used to shadow the original map\n // (rdar://125016028)\n public func map<NewSuccess: ~Copyable>(\n _ transform: (Success) -> NewSuccess\n ) -> Result<NewSuccess, Failure> {\n switch self {\n case let .success(success):\n return .success(transform(success))\n case let .failure(failure):\n return .failure(failure)\n }\n }\n}\n\nextension Result {\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @_silgen_name("$ss6ResultO3mapyAByqd__q_Gqd__xXElF")\n @usableFromInline\n internal func __abi_map<NewSuccess>(\n _ transform: (Success) -> NewSuccess\n ) -> Result<NewSuccess, Failure> {\n switch self {\n case let .success(success):\n return .success(transform(success))\n case let .failure(failure):\n return .failure(failure)\n }\n }\n}\n\nextension Result where Success: ~Copyable {\n // FIXME(NCG): Make this public.\n @_alwaysEmitIntoClient\n public consuming func _consumingMap<NewSuccess: ~Copyable>(\n _ transform: (consuming Success) -> NewSuccess\n ) -> Result<NewSuccess, Failure> {\n switch consume self {\n case let .success(success):\n return .success(transform(consume success))\n case let .failure(failure):\n return .failure(consume failure)\n }\n }\n\n // FIXME(NCG): Make this public.\n @_alwaysEmitIntoClient\n public borrowing func _borrowingMap<NewSuccess: ~Copyable>(\n _ transform: (borrowing Success) -> NewSuccess\n ) -> Result<NewSuccess, Failure> {\n switch self {\n case .success(let success):\n return .success(transform(success))\n case let .failure(failure):\n return .failure(failure)\n }\n }\n}\n\nextension Result where Success: ~Copyable & ~Escapable {\n /// Returns a new result, mapping any failure value using the given\n /// transformation.\n ///\n /// Use this method when you need to transform the value of a `Result`\n /// instance when it represents a failure. The following example transforms\n /// the error value of a result by wrapping it in a custom `Error` type:\n ///\n /// struct DatedError: Error {\n /// var error: Error\n /// var date: Date\n ///\n /// init(_ error: Error) {\n /// self.error = error\n /// self.date = Date()\n /// }\n /// }\n ///\n /// let result: Result<Int, Error> = // ...\n /// // result == .failure(<error value>)\n /// let resultWithDatedError = result.mapError { DatedError($0) }\n /// // result == .failure(DatedError(error: <error value>, date: <date>))\n ///\n /// - Parameter transform: A closure that takes the failure value of the\n /// instance.\n /// - Returns: A `Result` instance with the result of evaluating `transform`\n /// as the new failure value if this instance represents a failure.\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public consuming func mapError<NewFailure>(\n _ transform: (Failure) -> NewFailure\n ) -> Result<Success, NewFailure> {\n switch consume self {\n case let .success(success):\n return .success(consume success)\n case let .failure(failure):\n return .failure(transform(failure))\n }\n }\n}\n\nextension Result {\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @usableFromInline\n internal func mapError<NewFailure>(\n _ transform: (Failure) -> NewFailure\n ) -> Result<Success, NewFailure> {\n switch self {\n case let .success(success):\n return .success(success)\n case let .failure(failure):\n return .failure(transform(failure))\n }\n }\n}\n\nextension Result {\n /// Returns a new result, mapping any success value using the given\n /// transformation and unwrapping the produced result.\n ///\n /// Use this method to avoid a nested result when your transformation\n /// produces another `Result` type.\n ///\n /// In this example, note the difference in the result of using `map` and\n /// `flatMap` with a transformation that returns a result type.\n ///\n /// func getNextInteger() -> Result<Int, Error> {\n /// .success(4)\n /// }\n /// func getNextAfterInteger(_ n: Int) -> Result<Int, Error> {\n /// .success(n + 1)\n /// }\n ///\n /// let result = getNextInteger().map { getNextAfterInteger($0) }\n /// // result == .success(.success(5))\n ///\n /// let result = getNextInteger().flatMap { getNextAfterInteger($0) }\n /// // result == .success(5)\n ///\n /// - Parameter transform: A closure that takes the success value of the\n /// instance.\n /// - Returns: A `Result` instance, either from the closure or the previous\n /// `.failure`.\n @_alwaysEmitIntoClient\n @_disfavoredOverload // FIXME: Workaround for source compat issue with\n // functions that used to shadow the original flatMap\n // (rdar://125016028)\n public func flatMap<NewSuccess: ~Copyable>(\n _ transform: (Success) -> Result<NewSuccess, Failure>\n ) -> Result<NewSuccess, Failure> {\n switch self {\n case let .success(success):\n return transform(success)\n case let .failure(failure):\n return .failure(failure)\n }\n }\n}\n\nextension Result {\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @_silgen_name("$ss6ResultO7flatMapyAByqd__q_GADxXElF")\n @usableFromInline\n internal func __abi_flatMap<NewSuccess>(\n _ transform: (Success) -> Result<NewSuccess, Failure>\n ) -> Result<NewSuccess, Failure> {\n switch self {\n case let .success(success):\n return transform(success)\n case let .failure(failure):\n return .failure(failure)\n }\n }\n}\n\nextension Result where Success: ~Copyable {\n // FIXME(NCG): Make this public.\n @_alwaysEmitIntoClient\n public consuming func _consumingFlatMap<NewSuccess: ~Copyable>(\n _ transform: (consuming Success) -> Result<NewSuccess, Failure>\n ) -> Result<NewSuccess, Failure> {\n switch consume self {\n case let .success(success):\n return transform(consume success)\n case let .failure(failure):\n return .failure(failure)\n }\n }\n\n // FIXME(NCG): Make this public.\n @_alwaysEmitIntoClient\n public borrowing func _borrowingFlatMap<NewSuccess: ~Copyable>(\n _ transform: (borrowing Success) -> Result<NewSuccess, Failure>\n ) -> Result<NewSuccess, Failure> {\n switch self {\n case .success(let success):\n return transform(success)\n case let .failure(failure):\n return .failure(failure)\n }\n }\n}\n\nextension Result where Success: ~Copyable {\n // FIXME: This should allow ~Escapable Success types\n // (https://forums.swift.org/t/se-0465-standard-library-primitives-for-nonescapable-types/78310/5)\n\n /// Returns a new result, mapping any failure value using the given\n /// transformation and unwrapping the produced result.\n ///\n /// - Parameter transform: A closure that takes the failure value of the\n /// instance.\n /// - Returns: A `Result` instance, either from the closure or the previous\n /// `.success`.\n @_alwaysEmitIntoClient\n public consuming func flatMapError<NewFailure>(\n _ transform: (Failure) -> Result<Success, NewFailure>\n ) -> Result<Success, NewFailure> {\n switch consume self {\n case let .success(success):\n return .success(success)\n case let .failure(failure):\n return transform(failure)\n }\n }\n}\n\nextension Result {\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @_silgen_name("$ss6ResultO12flatMapErroryAByxqd__GADq_XEs0D0Rd__lF")\n @usableFromInline\n internal func __abi_flatMapError<NewFailure>(\n _ transform: (Failure) -> Result<Success, NewFailure>\n ) -> Result<Success, NewFailure> {\n switch self {\n case let .success(success):\n return .success(success)\n case let .failure(failure):\n return transform(failure)\n }\n }\n}\n\nextension Result where Success: ~Copyable & ~Escapable {\n /// Returns the success value as a throwing expression.\n ///\n /// Use this method to retrieve the value of this result if it represents a\n /// success, or to catch the value if it represents a failure.\n ///\n /// let integerResult: Result<Int, Error> = .success(5)\n /// do {\n /// let value = try integerResult.get()\n /// print("The value is \(value).")\n /// } catch {\n /// print("Error retrieving the value: \(error)")\n /// }\n /// // Prints "The value is 5."\n ///\n /// - Returns: The success value, if the instance represents a success.\n /// - Throws: The failure value, if the instance represents a failure.\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public consuming func get() throws(Failure) -> Success {\n switch consume self {\n case let .success(success):\n return success\n case let .failure(failure):\n throw failure\n }\n }\n}\n\nextension Result {\n /// ABI: Historical get() throws\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @_silgen_name("$ss6ResultO3getxyKF")\n @usableFromInline\n func __abi_get() throws -> Success {\n switch self {\n case let .success(success):\n return success\n case let .failure(failure):\n throw failure\n }\n }\n\n}\n\nextension Result where Success: ~Copyable {\n /// Creates a new result by evaluating a throwing closure, capturing the\n /// returned value as a success, or any thrown error as a failure.\n ///\n /// - Parameter body: A potentially throwing closure to evaluate.\n @_alwaysEmitIntoClient\n public init(catching body: () throws(Failure) -> Success) {\n // FIXME: This should allow a non-escapable `Success` -- but what's `self`'s lifetime dependence in that case?\n do {\n self = .success(try body())\n } catch {\n self = .failure(error)\n }\n }\n}\n\nextension Result where Failure == Swift.Error {\n /// ABI: Historical init(catching:)\n @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)\n @_silgen_name("$ss6ResultOss5Error_pRs_rlE8catchingAByxsAC_pGxyKXE_tcfC")\n @usableFromInline\n init(__abi_catching body: () throws(Failure) -> Success) {\n do {\n self = .success(try body())\n } catch {\n self = .failure(error)\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Result.swift
cpp_apple_swift_stdlib_public_core_Result.swift
Swift
12,202
0.95
0.086721
0.363372
python-kit
513
2024-04-16T21:48:56.080095
Apache-2.0
false
19a8ce1b05b8b2018213fbfeb7b54292
//===--- Reverse.swift - Sequence and collection reversal -----------------===//\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 MutableCollection where Self: BidirectionalCollection {\n /// Reverses the elements of the collection in place.\n ///\n /// The following example reverses the elements of an array of characters:\n ///\n /// var characters: [Character] = ["C", "a", "f", "é"]\n /// characters.reverse()\n /// print(characters)\n /// // Prints "["é", "f", "a", "C"]"\n ///\n /// - Complexity: O(*n*), where *n* is the number of elements in the\n /// collection.\n @inlinable // protocol-only\n public mutating func reverse() {\n if isEmpty { return }\n var f = startIndex\n var l = index(before: endIndex)\n while f < l {\n swapAt(f, l)\n formIndex(after: &f)\n formIndex(before: &l)\n }\n }\n}\n\n/// A collection that presents the elements of its base collection\n/// in reverse order.\n///\n/// - Note: This type is the result of `x.reversed()` where `x` is a\n/// collection having bidirectional indices.\n///\n/// The `reversed()` method is always lazy when applied to a collection\n/// with bidirectional indices, but does not implicitly confer\n/// laziness on algorithms applied to its result. In other words, for\n/// ordinary collections `c` having bidirectional indices:\n///\n/// * `c.reversed()` does not create new storage\n/// * `c.reversed().map(f)` maps eagerly and returns a new array\n/// * `c.lazy.reversed().map(f)` maps lazily and returns a `LazyMapCollection`\n@frozen\npublic struct ReversedCollection<Base: BidirectionalCollection> {\n public let _base: Base\n\n /// Creates an instance that presents the elements of `base` in\n /// reverse order.\n ///\n /// - Complexity: O(1)\n @inlinable\n internal init(_base: Base) {\n self._base = _base\n }\n}\n\nextension ReversedCollection: Sendable where Base: Sendable {}\n\nextension ReversedCollection {\n // An iterator that can be much faster than the iterator of a reversed slice.\n @frozen\n public struct Iterator {\n @usableFromInline\n internal let _base: Base\n @usableFromInline\n internal var _position: Base.Index\n\n @inlinable\n @inline(__always)\n /// Creates an iterator over the given collection.\n public /// @testable\n init(_base: Base) {\n self._base = _base\n self._position = _base.endIndex\n }\n }\n}\n\nextension ReversedCollection.Iterator: Sendable\n where Base: Sendable, Base.Index: Sendable {}\n\nextension ReversedCollection.Iterator: IteratorProtocol, Sequence {\n public typealias Element = Base.Element\n \n @inlinable\n @inline(__always)\n public mutating func next() -> Element? {\n guard _fastPath(_position != _base.startIndex) else { return nil }\n _base.formIndex(before: &_position)\n return _base[_position]\n }\n}\n\nextension ReversedCollection: Sequence {\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 Element = Base.Element\n\n @inlinable\n @inline(__always)\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_base: _base)\n }\n}\n\nextension ReversedCollection {\n /// An index that traverses the same positions as an underlying index,\n /// with inverted traversal direction.\n @frozen\n public struct Index {\n /// The position after this position in the underlying collection.\n ///\n /// To find the position that corresponds with this index in the original,\n /// underlying collection, use that collection's `index(before:)` method\n /// with the `base` property.\n ///\n /// The following example declares a function that returns the index of the\n /// last even number in the passed array, if one is found. First, the\n /// function finds the position of the last even number as a `ReversedIndex`\n /// in a reversed view of the array of numbers. Next, the function calls the\n /// array's `index(before:)` method to return the correct position in the\n /// passed array.\n ///\n /// func indexOfLastEven(_ numbers: [Int]) -> Int? {\n /// let reversedNumbers = numbers.reversed()\n /// guard let i = reversedNumbers.firstIndex(where: { $0 % 2 == 0 })\n /// else { return nil }\n ///\n /// return numbers.index(before: i.base)\n /// }\n ///\n /// let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]\n /// if let lastEven = indexOfLastEven(numbers) {\n /// print("Last even number: \(numbers[lastEven])")\n /// }\n /// // Prints "Last even number: 40"\n public let base: Base.Index\n\n /// Creates a new index into a reversed collection for the position before\n /// the specified index.\n ///\n /// When you create an index into a reversed collection using `base`, an\n /// index from the underlying collection, the resulting index is the\n /// position of the element *before* the element referenced by `base`. The\n /// following example creates a new `ReversedIndex` from the index of the\n /// `"a"` character in a string's character view.\n ///\n /// let name = "Horatio"\n /// let aIndex = name.firstIndex(of: "a")!\n /// // name[aIndex] == "a"\n ///\n /// let reversedName = name.reversed()\n /// let i = ReversedCollection<String>.Index(aIndex)\n /// // reversedName[i] == "r"\n ///\n /// The element at the position created using `ReversedIndex<...>(aIndex)` is\n /// `"r"`, the character before `"a"` in the `name` string.\n ///\n /// - Parameter base: The position after the element to create an index for.\n @inlinable\n public init(_ base: Base.Index) {\n self.base = base\n }\n }\n}\n\nextension ReversedCollection.Index: Sendable where Base.Index: Sendable {}\n\nextension ReversedCollection.Index: Comparable {\n @inlinable\n public static func == (\n lhs: ReversedCollection<Base>.Index,\n rhs: ReversedCollection<Base>.Index\n ) -> Bool {\n // Note ReversedIndex has inverted logic compared to base Base.Index\n return lhs.base == rhs.base\n }\n\n @inlinable\n public static func < (\n lhs: ReversedCollection<Base>.Index,\n rhs: ReversedCollection<Base>.Index\n ) -> Bool {\n // Note ReversedIndex has inverted logic compared to base Base.Index\n return lhs.base > rhs.base\n }\n}\n\nextension ReversedCollection.Index: Hashable where Base.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(base)\n }\n}\n\nextension ReversedCollection: BidirectionalCollection { \n @inlinable\n public var startIndex: Index {\n return Index(_base.endIndex)\n }\n\n @inlinable\n public var endIndex: Index {\n return Index(_base.startIndex)\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n return Index(_base.index(before: i.base))\n }\n\n @inlinable\n public func index(before i: Index) -> Index {\n return Index(_base.index(after: i.base))\n }\n\n @inlinable\n public func index(_ i: Index, offsetBy n: Int) -> Index {\n // FIXME: swift-3-indexing-model: `-n` can trap on Int.min.\n return Index(_base.index(i.base, offsetBy: -n))\n }\n\n @inlinable\n public func index(\n _ i: Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Index? {\n // FIXME: swift-3-indexing-model: `-n` can trap on Int.min.\n return _base.index(i.base, offsetBy: -n, limitedBy: limit.base)\n .map(Index.init)\n }\n\n @inlinable\n public func distance(from start: Index, to end: Index) -> Int {\n return _base.distance(from: end.base, to: start.base)\n }\n\n @inlinable\n public subscript(position: Index) -> Element {\n return _base[_base.index(before: position.base)]\n }\n}\n\nextension ReversedCollection: RandomAccessCollection where Base: RandomAccessCollection { }\n\nextension ReversedCollection {\n /// Reversing a reversed collection returns the original collection.\n ///\n /// - Complexity: O(1)\n @inlinable\n @available(swift, introduced: 4.2)\n public __consuming func reversed() -> Base {\n return _base\n }\n}\n\nextension BidirectionalCollection {\n /// Returns a view presenting the elements of the collection in reverse\n /// order.\n ///\n /// You can reverse a collection without allocating new space for its\n /// elements by calling this `reversed()` method. A `ReversedCollection`\n /// instance wraps an underlying collection and provides access to its\n /// elements in reverse order. This example prints the characters of a\n /// string in reverse order:\n ///\n /// let word = "Backwards"\n /// for char in word.reversed() {\n /// print(char, terminator: "")\n /// }\n /// // Prints "sdrawkcaB"\n ///\n /// If you need a reversed collection of the same type, you may be able to\n /// use the collection's sequence-based or collection-based initializer. For\n /// example, to get the reversed version of a string, reverse its\n /// characters and initialize a new `String` instance from the result.\n ///\n /// let reversedWord = String(word.reversed())\n /// print(reversedWord)\n /// // Prints "sdrawkcaB"\n ///\n /// - Complexity: O(1)\n @inlinable\n public __consuming func reversed() -> ReversedCollection<Self> {\n return ReversedCollection(_base: self)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Reverse.swift
cpp_apple_swift_stdlib_public_core_Reverse.swift
Swift
9,894
0.95
0.049669
0.481752
python-kit
544
2024-09-11T23:04:19.378866
GPL-3.0
false
a6c5413152c39acab613ce09d011b1bb
//===----------------------------------------------------------*- 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/// This file contains Swift wrappers for functions defined in the C++ runtime.\n///\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n//===----------------------------------------------------------------------===//\n// Atomics\n//===----------------------------------------------------------------------===//\n\n@_transparent\npublic // @testable\nfunc _stdlib_atomicCompareExchangeStrongPtr(\n object target: UnsafeMutablePointer<UnsafeRawPointer?>,\n expected: UnsafeMutablePointer<UnsafeRawPointer?>,\n desired: UnsafeRawPointer?\n) -> Bool {\n // We use Builtin.Word here because Builtin.RawPointer can't be nil.\n let (oldValue, won) = unsafe Builtin.cmpxchg_seqcst_seqcst_Word(\n target._rawValue,\n UInt(bitPattern: expected.pointee)._builtinWordValue,\n UInt(bitPattern: desired)._builtinWordValue)\n unsafe expected.pointee = UnsafeRawPointer(bitPattern: Int(oldValue))\n return Bool(won)\n}\n\n/// Atomic compare and exchange of `UnsafeMutablePointer<T>` with sequentially\n/// consistent memory ordering. Precise semantics are defined in C++11 or C11.\n///\n/// - Warning: This operation is extremely tricky to use correctly because of\n/// writeback semantics.\n///\n/// It is best to use it directly on an\n/// `UnsafeMutablePointer<UnsafeMutablePointer<T>>` that is known to point\n/// directly to the memory where the value is stored.\n///\n/// In a call like this:\n///\n/// _stdlib_atomicCompareExchangeStrongPtr(&foo.property1.property2, ...)\n///\n/// you need to manually make sure that:\n///\n/// - all properties in the chain are physical (to make sure that no writeback\n/// happens; the compare-and-exchange instruction should operate on the\n/// shared memory); and\n///\n/// - the shared memory that you are accessing is located inside a heap\n/// allocation (a class instance property, a `_BridgingBuffer`, a pointer to\n/// an `Array` element etc.)\n///\n/// If the conditions above are not met, the code will still compile, but the\n/// compare-and-exchange instruction will operate on the writeback buffer, and\n/// you will get a *race* while doing writeback into shared memory.\n@_transparent\npublic // @testable\nfunc _stdlib_atomicCompareExchangeStrongPtr<T>(\n object target: UnsafeMutablePointer<UnsafeMutablePointer<T>>,\n expected: UnsafeMutablePointer<UnsafeMutablePointer<T>>,\n desired: UnsafeMutablePointer<T>\n) -> Bool {\n let rawTarget = unsafe UnsafeMutableRawPointer(target).assumingMemoryBound(\n to: Optional<UnsafeRawPointer>.self)\n let rawExpected = unsafe UnsafeMutableRawPointer(expected).assumingMemoryBound(\n to: Optional<UnsafeRawPointer>.self)\n return unsafe _stdlib_atomicCompareExchangeStrongPtr(\n object: rawTarget,\n expected: rawExpected,\n desired: UnsafeRawPointer(desired))\n}\n\n/// Atomic compare and exchange of `UnsafeMutablePointer<T>` with sequentially\n/// consistent memory ordering. Precise semantics are defined in C++11 or C11.\n///\n/// - Warning: This operation is extremely tricky to use correctly because of\n/// writeback semantics.\n///\n/// It is best to use it directly on an\n/// `UnsafeMutablePointer<UnsafeMutablePointer<T>>` that is known to point\n/// directly to the memory where the value is stored.\n///\n/// In a call like this:\n///\n/// _stdlib_atomicCompareExchangeStrongPtr(&foo.property1.property2, ...)\n///\n/// you need to manually make sure that:\n///\n/// - all properties in the chain are physical (to make sure that no writeback\n/// happens; the compare-and-exchange instruction should operate on the\n/// shared memory); and\n///\n/// - the shared memory that you are accessing is located inside a heap\n/// allocation (a class instance property, a `_BridgingBuffer`, a pointer to\n/// an `Array` element etc.)\n///\n/// If the conditions above are not met, the code will still compile, but the\n/// compare-and-exchange instruction will operate on the writeback buffer, and\n/// you will get a *race* while doing writeback into shared memory.\n@_transparent\npublic // @testable\nfunc _stdlib_atomicCompareExchangeStrongPtr<T>(\n object target: UnsafeMutablePointer<UnsafeMutablePointer<T>?>,\n expected: UnsafeMutablePointer<UnsafeMutablePointer<T>?>,\n desired: UnsafeMutablePointer<T>?\n) -> Bool {\n let rawTarget = unsafe UnsafeMutableRawPointer(target).assumingMemoryBound(\n to: Optional<UnsafeRawPointer>.self)\n let rawExpected = unsafe UnsafeMutableRawPointer(expected).assumingMemoryBound(\n to: Optional<UnsafeRawPointer>.self)\n return unsafe _stdlib_atomicCompareExchangeStrongPtr(\n object: rawTarget,\n expected: rawExpected,\n desired: UnsafeRawPointer(desired))\n}\n\n@_transparent\n@discardableResult\n@_unavailableInEmbedded\npublic // @testable\nfunc _stdlib_atomicInitializeARCRef(\n object target: UnsafeMutablePointer<AnyObject?>,\n desired: AnyObject\n) -> Bool {\n // Note: this assumes that AnyObject? is layout-compatible with a RawPointer\n // that simply points to the same memory.\n var expected: UnsafeRawPointer? = nil\n let unmanaged = unsafe Unmanaged.passRetained(desired)\n let desiredPtr = unsafe unmanaged.toOpaque()\n let rawTarget = unsafe UnsafeMutableRawPointer(target).assumingMemoryBound(\n to: Optional<UnsafeRawPointer>.self)\n let wonRace = unsafe withUnsafeMutablePointer(to: &expected) {\n unsafe _stdlib_atomicCompareExchangeStrongPtr(\n object: rawTarget, expected: $0, desired: desiredPtr\n )\n }\n if !wonRace {\n // Some other thread initialized the value. Balance the retain that we\n // performed on 'desired'.\n unsafe unmanaged.release()\n }\n return wonRace\n}\n\n@_transparent\n@_unavailableInEmbedded\npublic // @testable\nfunc _stdlib_atomicLoadARCRef(\n object target: UnsafeMutablePointer<AnyObject?>\n) -> AnyObject? {\n let value = Builtin.atomicload_seqcst_Word(target._rawValue)\n if let unwrapped = unsafe UnsafeRawPointer(bitPattern: Int(value)) {\n return unsafe Unmanaged<AnyObject>.fromOpaque(unwrapped).takeUnretainedValue()\n }\n return nil\n}\n\n@_transparent\n@_alwaysEmitIntoClient\n@discardableResult\npublic func _stdlib_atomicAcquiringInitializeARCRef<T: AnyObject>(\n object target: UnsafeMutablePointer<T?>,\n desired: __owned T\n) -> Unmanaged<T> {\n // Note: this assumes that AnyObject? is layout-compatible with a RawPointer\n // that simply points to the same memory, and that `nil` is represented by an\n // all-zero bit pattern.\n let unmanaged = unsafe Unmanaged.passRetained(desired)\n let desiredPtr = unsafe unmanaged.toOpaque()\n\n let (value, won) = Builtin.cmpxchg_acqrel_acquire_Word(\n target._rawValue,\n 0._builtinWordValue,\n Builtin.ptrtoint_Word(desiredPtr._rawValue))\n\n if Bool(won) { return unsafe unmanaged }\n\n // Some other thread initialized the value before us. Balance the retain that\n // we performed on 'desired', and return what we loaded.\n unsafe unmanaged.release()\n let ptr = UnsafeRawPointer(Builtin.inttoptr_Word(value))\n return unsafe Unmanaged<T>.fromOpaque(ptr)\n}\n\n@_alwaysEmitIntoClient\n@_transparent\npublic func _stdlib_atomicAcquiringLoadARCRef<T: AnyObject>(\n object target: UnsafeMutablePointer<T?>\n) -> Unmanaged<T>? {\n let value = Builtin.atomicload_acquire_Word(target._rawValue)\n if Int(value) == 0 { return nil }\n let opaque = UnsafeRawPointer(Builtin.inttoptr_Word(value))\n return unsafe Unmanaged<T>.fromOpaque(opaque)\n}\n\n//===----------------------------------------------------------------------===//\n// Conversion of primitive types to `String`\n//===----------------------------------------------------------------------===//\n\n/// A 32 byte buffer.\ninternal struct _Buffer32 {\n internal var _x0: UInt8 = 0\n internal var _x1: UInt8 = 0\n internal var _x2: UInt8 = 0\n internal var _x3: UInt8 = 0\n internal var _x4: UInt8 = 0\n internal var _x5: UInt8 = 0\n internal var _x6: UInt8 = 0\n internal var _x7: UInt8 = 0\n internal var _x8: UInt8 = 0\n internal var _x9: UInt8 = 0\n internal var _x10: UInt8 = 0\n internal var _x11: UInt8 = 0\n internal var _x12: UInt8 = 0\n internal var _x13: UInt8 = 0\n internal var _x14: UInt8 = 0\n internal var _x15: UInt8 = 0\n internal var _x16: UInt8 = 0\n internal var _x17: UInt8 = 0\n internal var _x18: UInt8 = 0\n internal var _x19: UInt8 = 0\n internal var _x20: UInt8 = 0\n internal var _x21: UInt8 = 0\n internal var _x22: UInt8 = 0\n internal var _x23: UInt8 = 0\n internal var _x24: UInt8 = 0\n internal var _x25: UInt8 = 0\n internal var _x26: UInt8 = 0\n internal var _x27: UInt8 = 0\n internal var _x28: UInt8 = 0\n internal var _x29: UInt8 = 0\n internal var _x30: UInt8 = 0\n internal var _x31: UInt8 = 0\n\n internal init() {}\n\n internal mutating func withBytes<Result>(\n _ body: (UnsafeMutablePointer<UInt8>) throws -> Result\n ) rethrows -> Result {\n return try unsafe withUnsafeMutablePointer(to: &self) {\n try unsafe body(UnsafeMutableRawPointer($0).assumingMemoryBound(to: UInt8.self))\n }\n }\n}\n\n/// A 72 byte buffer.\ninternal struct _Buffer72 {\n internal var _x0: UInt8 = 0\n internal var _x1: UInt8 = 0\n internal var _x2: UInt8 = 0\n internal var _x3: UInt8 = 0\n internal var _x4: UInt8 = 0\n internal var _x5: UInt8 = 0\n internal var _x6: UInt8 = 0\n internal var _x7: UInt8 = 0\n internal var _x8: UInt8 = 0\n internal var _x9: UInt8 = 0\n internal var _x10: UInt8 = 0\n internal var _x11: UInt8 = 0\n internal var _x12: UInt8 = 0\n internal var _x13: UInt8 = 0\n internal var _x14: UInt8 = 0\n internal var _x15: UInt8 = 0\n internal var _x16: UInt8 = 0\n internal var _x17: UInt8 = 0\n internal var _x18: UInt8 = 0\n internal var _x19: UInt8 = 0\n internal var _x20: UInt8 = 0\n internal var _x21: UInt8 = 0\n internal var _x22: UInt8 = 0\n internal var _x23: UInt8 = 0\n internal var _x24: UInt8 = 0\n internal var _x25: UInt8 = 0\n internal var _x26: UInt8 = 0\n internal var _x27: UInt8 = 0\n internal var _x28: UInt8 = 0\n internal var _x29: UInt8 = 0\n internal var _x30: UInt8 = 0\n internal var _x31: UInt8 = 0\n internal var _x32: UInt8 = 0\n internal var _x33: UInt8 = 0\n internal var _x34: UInt8 = 0\n internal var _x35: UInt8 = 0\n internal var _x36: UInt8 = 0\n internal var _x37: UInt8 = 0\n internal var _x38: UInt8 = 0\n internal var _x39: UInt8 = 0\n internal var _x40: UInt8 = 0\n internal var _x41: UInt8 = 0\n internal var _x42: UInt8 = 0\n internal var _x43: UInt8 = 0\n internal var _x44: UInt8 = 0\n internal var _x45: UInt8 = 0\n internal var _x46: UInt8 = 0\n internal var _x47: UInt8 = 0\n internal var _x48: UInt8 = 0\n internal var _x49: UInt8 = 0\n internal var _x50: UInt8 = 0\n internal var _x51: UInt8 = 0\n internal var _x52: UInt8 = 0\n internal var _x53: UInt8 = 0\n internal var _x54: UInt8 = 0\n internal var _x55: UInt8 = 0\n internal var _x56: UInt8 = 0\n internal var _x57: UInt8 = 0\n internal var _x58: UInt8 = 0\n internal var _x59: UInt8 = 0\n internal var _x60: UInt8 = 0\n internal var _x61: UInt8 = 0\n internal var _x62: UInt8 = 0\n internal var _x63: UInt8 = 0\n internal var _x64: UInt8 = 0\n internal var _x65: UInt8 = 0\n internal var _x66: UInt8 = 0\n internal var _x67: UInt8 = 0\n internal var _x68: UInt8 = 0\n internal var _x69: UInt8 = 0\n internal var _x70: UInt8 = 0\n internal var _x71: UInt8 = 0\n\n internal init() {}\n\n internal mutating func withBytes<Result>(\n _ body: (UnsafeMutablePointer<UInt8>) throws -> Result\n ) rethrows -> Result {\n return try unsafe withUnsafeMutablePointer(to: &self) {\n try unsafe body(UnsafeMutableRawPointer($0).assumingMemoryBound(to: UInt8.self))\n }\n }\n}\n\n#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))\n#if arch(wasm32)\n// Note that this takes a Float32 argument instead of Float16, because clang\n// doesn't have _Float16 on all platforms yet.\n@available(SwiftStdlib 5.3, *)\ntypealias _CFloat16Argument = Float32\n#else\n@available(SwiftStdlib 5.3, *)\ntypealias _CFloat16Argument = Float16\n#endif\n\n@available(SwiftStdlib 5.3, *)\n@_silgen_name("swift_float16ToString")\ninternal func _float16ToStringImpl(\n _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,\n _ bufferLength: UInt,\n _ value: _CFloat16Argument,\n _ debug: Bool\n) -> Int\n\n@available(SwiftStdlib 5.3, *)\ninternal func _float16ToString(\n _ value: Float16,\n debug: Bool\n) -> (buffer: _Buffer32, length: Int) {\n _internalInvariant(MemoryLayout<_Buffer32>.size == 32)\n var buffer = _Buffer32()\n let length = unsafe buffer.withBytes { (bufferPtr) in\n unsafe _float16ToStringImpl(bufferPtr, 32, _CFloat16Argument(value), debug)\n }\n return (buffer, length)\n}\n#endif\n\n// Returns a UInt64, but that value is the length of the string, so it's\n// guaranteed to fit into an Int. This is part of the ABI, so we can't\n// trivially change it to Int. Callers can safely convert the result\n// to any integer type without checks, however.\n@_silgen_name("swift_float32ToString")\ninternal func _float32ToStringImpl(\n _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,\n _ bufferLength: UInt,\n _ value: Float32,\n _ debug: Bool\n) -> UInt64\n\ninternal func _float32ToString(\n _ value: Float32,\n debug: Bool\n) -> (buffer: _Buffer32, length: Int) {\n _internalInvariant(MemoryLayout<_Buffer32>.size == 32)\n var buffer = _Buffer32()\n let length = unsafe buffer.withBytes { (bufferPtr) in unsafe Int(\n truncatingIfNeeded: _float32ToStringImpl(bufferPtr, 32, value, debug)\n )}\n return (buffer, length)\n}\n\n// Returns a UInt64, but that value is the length of the string, so it's\n// guaranteed to fit into an Int. This is part of the ABI, so we can't\n// trivially change it to Int. Callers can safely convert the result\n// to any integer type without checks, however.\n@_silgen_name("swift_float64ToString")\ninternal func _float64ToStringImpl(\n _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,\n _ bufferLength: UInt,\n _ value: Float64,\n _ debug: Bool\n) -> UInt64\n\ninternal func _float64ToString(\n _ value: Float64,\n debug: Bool\n) -> (buffer: _Buffer32, length: Int) {\n _internalInvariant(MemoryLayout<_Buffer32>.size == 32)\n var buffer = _Buffer32()\n let length = unsafe buffer.withBytes { (bufferPtr) in unsafe Int(\n truncatingIfNeeded: _float64ToStringImpl(bufferPtr, 32, value, debug)\n )}\n return (buffer, length)\n}\n\n\n#if !(os(Windows) || os(Android) || ($Embedded && !os(Linux) && !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS)))) && (arch(i386) || arch(x86_64))\n\n// Returns a UInt64, but that value is the length of the string, so it's\n// guaranteed to fit into an Int. This is part of the ABI, so we can't\n// trivially change it to Int. Callers can safely convert the result\n// to any integer type without checks, however.\n@_silgen_name("swift_float80ToString")\ninternal func _float80ToStringImpl(\n _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,\n _ bufferLength: UInt,\n _ value: Float80,\n _ debug: Bool\n) -> UInt64\n\ninternal func _float80ToString(\n _ value: Float80,\n debug: Bool\n) -> (buffer: _Buffer32, length: Int) {\n _internalInvariant(MemoryLayout<_Buffer32>.size == 32)\n var buffer = _Buffer32()\n let length = unsafe buffer.withBytes { (bufferPtr) in Int(\n truncatingIfNeeded: unsafe _float80ToStringImpl(bufferPtr, 32, value, debug)\n )}\n return (buffer, length)\n}\n#endif\n\n#if !$Embedded\n// Returns a UInt64, but that value is the length of the string, so it's\n// guaranteed to fit into an Int. This is part of the ABI, so we can't\n// trivially change it to Int. Callers can safely convert the result\n// to any integer type without checks, however.\n@_silgen_name("swift_int64ToString")\ninternal func _int64ToStringImpl(\n _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,\n _ bufferLength: UInt,\n _ value: Int64,\n _ radix: Int64,\n _ uppercase: Bool\n) -> UInt64\n#else\ninternal func _int64ToStringImpl(\n _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,\n _ bufferLength: UInt,\n _ value: Int64,\n _ radix: Int64,\n _ uppercase: Bool\n) -> UInt64 {\n return UInt64(unsafe value._toStringImpl(buffer, bufferLength, Int(radix), uppercase))\n}\n#endif\n\ninternal func _int64ToString(\n _ value: Int64,\n radix: Int64 = 10,\n uppercase: Bool = false\n) -> String {\n if radix >= 10 {\n var buffer = _Buffer32()\n return unsafe buffer.withBytes { (bufferPtr) in\n let actualLength = unsafe _int64ToStringImpl(bufferPtr, 32, value, radix, uppercase)\n return unsafe String._fromASCII(UnsafeBufferPointer(\n start: bufferPtr, count: Int(truncatingIfNeeded: actualLength)\n ))\n }\n } else {\n var buffer = _Buffer72()\n return unsafe buffer.withBytes { (bufferPtr) in\n let actualLength = unsafe _int64ToStringImpl(bufferPtr, 72, value, radix, uppercase)\n return unsafe String._fromASCII(UnsafeBufferPointer(\n start: bufferPtr, count: Int(truncatingIfNeeded: actualLength)\n ))\n }\n }\n}\n\n#if !$Embedded\n// Returns a UInt64, but that value is the length of the string, so it's\n// guaranteed to fit into an Int. This is part of the ABI, so we can't\n// trivially change it to Int. Callers can safely convert the result\n// to any integer type without checks, however.\n@_silgen_name("swift_uint64ToString")\ninternal func _uint64ToStringImpl(\n _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,\n _ bufferLength: UInt,\n _ value: UInt64,\n _ radix: Int64,\n _ uppercase: Bool\n) -> UInt64\n#else\ninternal func _uint64ToStringImpl(\n _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>,\n _ bufferLength: UInt,\n _ value: UInt64,\n _ radix: Int64,\n _ uppercase: Bool\n) -> UInt64 {\n return unsafe UInt64(value._toStringImpl(buffer, bufferLength, Int(radix), uppercase))\n}\n#endif\n\npublic // @testable\nfunc _uint64ToString(\n _ value: UInt64,\n radix: Int64 = 10,\n uppercase: Bool = false\n) -> String {\n if radix >= 10 {\n var buffer = _Buffer32()\n return unsafe buffer.withBytes { (bufferPtr) in\n let actualLength = unsafe _uint64ToStringImpl(bufferPtr, 32, value, radix, uppercase)\n return unsafe String._fromASCII(UnsafeBufferPointer(\n start: bufferPtr, count: Int(truncatingIfNeeded: actualLength)\n ))\n }\n } else {\n var buffer = _Buffer72()\n return unsafe buffer.withBytes { (bufferPtr) in\n let actualLength = unsafe _uint64ToStringImpl(bufferPtr, 72, value, radix, uppercase)\n return unsafe String._fromASCII(UnsafeBufferPointer(\n start: bufferPtr, count: Int(truncatingIfNeeded: actualLength)\n ))\n }\n }\n}\n\n@inlinable\ninternal func _rawPointerToString(_ value: Builtin.RawPointer) -> String {\n var result = _uint64ToString(\n UInt64(UInt(bitPattern: UnsafeRawPointer(value))),\n radix: 16,\n uppercase: false\n )\n for _ in unsafe 0..<(2 * MemoryLayout<UnsafeRawPointer>.size - result.utf16.count) {\n result = "0" + result\n }\n return "0x" + result\n}\n\n#if _runtime(_ObjC)\n// At runtime, these classes are derived from `__SwiftNativeNSXXXBase`,\n// which are derived from `NSXXX`.\n//\n// The @swift_native_objc_runtime_base attribute\n// allows us to subclass an Objective-C class and still use the fast Swift\n// memory allocator.\n//\n// NOTE: older runtimes called these _SwiftNativeNSXXX. The two must\n// coexist, so they were renamed. The old names must not be used in the\n// new runtime.\n\n@_fixed_layout\n@usableFromInline\n@objc @_swift_native_objc_runtime_base(__SwiftNativeNSArrayBase)\ninternal class __SwiftNativeNSArray {\n @inlinable\n @nonobjc\n internal init() {}\n// @objc public init(coder: AnyObject) {}\n @inlinable\n deinit {}\n}\n\n@available(*, unavailable)\nextension __SwiftNativeNSArray: Sendable {}\n\n@_fixed_layout\n@usableFromInline\n@objc @_swift_native_objc_runtime_base(__SwiftNativeNSMutableArrayBase)\ninternal class _SwiftNativeNSMutableArray {\n @inlinable\n @nonobjc\n internal init() {}\n// @objc public init(coder: AnyObject) {}\n @inlinable\n deinit {}\n}\n\n@available(*, unavailable)\nextension _SwiftNativeNSMutableArray: Sendable {}\n\n@_fixed_layout\n@usableFromInline\n@objc @_swift_native_objc_runtime_base(__SwiftNativeNSDictionaryBase)\ninternal class __SwiftNativeNSDictionary {\n @nonobjc\n internal init() {}\n @objc public init(coder: AnyObject) {}\n deinit {}\n}\n\n@available(*, unavailable)\nextension __SwiftNativeNSDictionary: Sendable {}\n\n@_fixed_layout\n@usableFromInline\n@objc @_swift_native_objc_runtime_base(__SwiftNativeNSSetBase)\ninternal class __SwiftNativeNSSet {\n @nonobjc\n internal init() {}\n @objc public init(coder: AnyObject) {}\n deinit {}\n}\n\n@available(*, unavailable)\nextension __SwiftNativeNSSet: Sendable {}\n\n@objc\n@_swift_native_objc_runtime_base(__SwiftNativeNSEnumeratorBase)\ninternal class __SwiftNativeNSEnumerator {\n @nonobjc\n internal init() {}\n @objc public init(coder: AnyObject) {}\n deinit {}\n}\n\n//===----------------------------------------------------------------------===//\n// Support for reliable testing of the return-autoreleased optimization\n//===----------------------------------------------------------------------===//\n\n@objc\ninternal class __stdlib_ReturnAutoreleasedDummy {\n @objc\n internal init() {}\n\n // Use 'dynamic' to force Objective-C dispatch, which uses the\n // return-autoreleased call sequence.\n @objc\n internal dynamic func returnsAutoreleased(_ x: AnyObject) -> AnyObject {\n return x\n }\n}\n\n/// This function ensures that the return-autoreleased optimization works.\n///\n/// On some platforms (for example, x86_64), the first call to\n/// `objc_autoreleaseReturnValue` will always autorelease because it would fail\n/// to verify the instruction sequence in the caller. On x86_64 certain PLT\n/// entries would be still pointing to the resolver function, and sniffing\n/// the call sequence would fail.\n///\n/// This code should live in the core stdlib dylib because PLT tables are\n/// separate for each dylib.\n///\n/// Call this function in a fresh autorelease pool.\npublic func _stdlib_initializeReturnAutoreleased() {\n#if arch(x86_64)\n // On x86_64 it is sufficient to perform one cycle of return-autoreleased\n // call sequence in order to initialize all required PLT entries.\n let dummy = __stdlib_ReturnAutoreleasedDummy()\n _ = dummy.returnsAutoreleased(dummy)\n#endif\n}\n#else\n\n@_fixed_layout\n@usableFromInline\ninternal class __SwiftNativeNSArray {\n @inlinable\n internal init() {}\n @inlinable\n deinit {}\n}\n@_fixed_layout\n@usableFromInline\ninternal class __SwiftNativeNSDictionary {\n @inlinable\n internal init() {}\n @inlinable\n deinit {}\n}\n@_fixed_layout\n@usableFromInline\ninternal class __SwiftNativeNSSet {\n @inlinable\n internal init() {}\n @inlinable\n deinit {}\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Runtime.swift
cpp_apple_swift_stdlib_public_core_Runtime.swift
Swift
22,810
0.95
0.058156
0.24159
react-lib
291
2024-01-16T23:31:33.309459
GPL-3.0
false
2c75a1dedb49a561909ecd7d99206264
//===--- RuntimeFunctionCounters.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// This file implements the experimental support for collecting the state of\n// runtime function counters, which are used to determine how many times\n// a given runtime function was called.\n//\n// It is possible to get the global counters, which represent the total\n// number of invocations, or per-object counters, which represent the\n// number of runtime functions calls for a specific object.\n\n// By default, this feature is enabled only when assertions are enabled. To control it\n// separately, set the SWIFT_ENABLE_RUNTIME_FUNCTION_COUNTERS environment variable when\n// invoking build-script:\n// SWIFT_ENABLE_RUNTIME_FUNCTION_COUNTERS=TRUE ./utils/build-script ...\n#if SWIFT_ENABLE_RUNTIME_FUNCTION_COUNTERS\n\n/// Collect all references inside the object using Mirrors.\n/// - Parameter value: the value to be inspected\n/// - Parameter references: the array which should contain the collected\n/// references\n/// - Parameter visitedItems: the dictionary for keeping track of visited\n/// objects\ninternal func _collectAllReferencesInsideObjectImpl(\n _ value: Any,\n references: inout [UnsafeRawPointer],\n visitedItems: inout [ObjectIdentifier: Int]\n) {\n // Use the structural reflection and ignore any\n // custom reflectable overrides.\n let mirror = Mirror(internalReflecting: value)\n\n let id: ObjectIdentifier?\n let ref: UnsafeRawPointer?\n if type(of: value) is AnyObject.Type {\n // Object is a class (but not an ObjC-bridged struct)\n let toAnyObject = _unsafeDowncastToAnyObject(fromAny: value)\n unsafe ref = unsafe UnsafeRawPointer(Unmanaged.passUnretained(toAnyObject).toOpaque())\n id = ObjectIdentifier(toAnyObject)\n } else if type(of: value) is Builtin.BridgeObject.Type {\n unsafe ref = UnsafeRawPointer(\n Builtin.bridgeToRawPointer(value as! Builtin.BridgeObject))\n id = nil\n } else if type(of: value) is Builtin.NativeObject.Type {\n unsafe ref = UnsafeRawPointer(\n Builtin.bridgeToRawPointer(value as! Builtin.NativeObject))\n id = nil\n } else if let metatypeInstance = value as? Any.Type {\n // Object is a metatype\n id = ObjectIdentifier(metatypeInstance)\n unsafe ref = nil\n } else {\n id = nil\n unsafe ref = nil\n }\n\n if let theId = id {\n // Bail if this object was seen already.\n if visitedItems[theId] != nil {\n return\n }\n // Remember that this object was seen already.\n let identifier = visitedItems.count\n visitedItems[theId] = identifier\n }\n\n // If it is a reference, add it to the result.\n if let ref = unsafe ref {\n unsafe references.append(ref)\n }\n\n // Recursively visit the children of the current value.\n let count = mirror.children.count\n var currentIndex = mirror.children.startIndex\n for _ in 0..<count {\n let (_, child) = mirror.children[currentIndex]\n mirror.children.formIndex(after: &currentIndex)\n unsafe _collectAllReferencesInsideObjectImpl(\n child,\n references: &references,\n visitedItems: &visitedItems)\n }\n}\n\n// This is a namespace for runtime functions related to management\n// of runtime function counters.\npublic // @testable\nstruct _RuntimeFunctionCounters {\n#if os(Windows) && arch(x86_64)\n public typealias RuntimeFunctionCountersUpdateHandler =\n @convention(c) (_ object: UnsafeRawPointer, _ functionId: Int) -> Void\n#else\n public typealias RuntimeFunctionCountersUpdateHandler =\n @convention(c) (_ object: UnsafeRawPointer, _ functionId: Int64) -> Void\n#endif\n\n public static let runtimeFunctionNames =\n getRuntimeFunctionNames()\n public static let runtimeFunctionCountersOffsets =\n unsafe _RuntimeFunctionCounters.getRuntimeFunctionCountersOffsets()\n public static let numRuntimeFunctionCounters =\n Int(_RuntimeFunctionCounters.getNumRuntimeFunctionCounters())\n public static let runtimeFunctionNameToIndex: [String: Int] =\n getRuntimeFunctionNameToIndex()\n\n /// Get the names of all runtime functions whose calls are being\n /// tracked.\n @_silgen_name("_swift_getRuntimeFunctionNames")\n public static func _getRuntimeFunctionNames() ->\n UnsafePointer<UnsafePointer<CChar>>\n\n public static func getRuntimeFunctionNames() -> [String] {\n let names = unsafe _RuntimeFunctionCounters._getRuntimeFunctionNames()\n let numRuntimeFunctionCounters =\n Int(_RuntimeFunctionCounters.getNumRuntimeFunctionCounters())\n var functionNames: [String] = []\n functionNames.reserveCapacity(numRuntimeFunctionCounters)\n for index in 0..<numRuntimeFunctionCounters {\n let name = unsafe String(cString: names[index])\n functionNames.append(name)\n }\n return functionNames\n }\n\n /// Get the offsets of the collected runtime function counters inside\n /// the state.\n @_silgen_name("_swift_getRuntimeFunctionCountersOffsets")\n public static func getRuntimeFunctionCountersOffsets() ->\n UnsafePointer<UInt16>\n\n /// Get the number of different runtime functions whose calls are being\n /// tracked.\n @_silgen_name("_swift_getNumRuntimeFunctionCounters")\n public static func getNumRuntimeFunctionCounters() -> UInt64\n\n /// Dump all per-object runtime function counters.\n @_silgen_name("_swift_dumpObjectsRuntimeFunctionPointers")\n public static func dumpObjectsRuntimeFunctionPointers()\n\n @discardableResult\n @_silgen_name("_swift_setGlobalRuntimeFunctionCountersUpdateHandler")\n public static func setGlobalRuntimeFunctionCountersUpdateHandler(\n handler: RuntimeFunctionCountersUpdateHandler?\n ) -> RuntimeFunctionCountersUpdateHandler?\n\n /// Collect all references inside the object using Mirrors.\n public static func collectAllReferencesInsideObject(_ value: Any) ->\n [UnsafeRawPointer] {\n var visited: [ObjectIdentifier: Int] = [:]\n var references: [UnsafeRawPointer] = unsafe []\n unsafe _collectAllReferencesInsideObjectImpl(\n value, references: &references, visitedItems: &visited)\n return unsafe references\n }\n\n /// Build a map from counter name to counter index inside the state struct.\n internal static func getRuntimeFunctionNameToIndex() -> [String: Int] {\n let runtimeFunctionNames = _RuntimeFunctionCounters.getRuntimeFunctionNames()\n let numRuntimeFunctionCounters =\n Int(_RuntimeFunctionCounters.getNumRuntimeFunctionCounters())\n var runtimeFunctionNameToIndex: [String: Int] = [:]\n runtimeFunctionNameToIndex.reserveCapacity(numRuntimeFunctionCounters)\n\n for index in 0..<numRuntimeFunctionCounters {\n let name = runtimeFunctionNames[index]\n runtimeFunctionNameToIndex[name] = index\n }\n return runtimeFunctionNameToIndex\n }\n}\n\n/// This protocol defines a set of operations for accessing runtime function\n/// counters statistics.\npublic // @testable\nprotocol _RuntimeFunctionCountersStats: CustomDebugStringConvertible {\n init()\n\n /// Dump the current state of all counters.\n func dump<T: TextOutputStream>(skipUnchanged: Bool, to: inout T)\n\n /// Dump the diff between the current state and a different state of all\n /// counters.\n func dumpDiff<T: TextOutputStream>(\n _ after: Self, skipUnchanged: Bool, to: inout T\n )\n\n /// Compute a diff between two states of runtime function counters.\n /// Return a new state representing the diff.\n func diff(_ other: Self) -> Self\n\n /// Access counters by name.\n subscript(_ counterName: String) -> UInt32 { get set }\n\n /// Access counters by index.\n subscript(_ index: Int) -> UInt32 { get set }\n}\n\nextension _RuntimeFunctionCountersStats {\n /// Dump the current state of all counters.\n public func dump(skipUnchanged: Bool) {\n var output = _Stdout()\n dump(skipUnchanged: skipUnchanged, to: &output)\n }\n\n /// Dump the diff between the current state and a different state of all\n /// counters.\n public func dumpDiff(_ after: Self, skipUnchanged: Bool) {\n var output = _Stdout()\n dumpDiff(after, skipUnchanged: skipUnchanged, to: &output)\n }\n}\n\nextension _RuntimeFunctionCountersStats {\n public var debugDescription: String {\n var result = ""\n dump(skipUnchanged: true, to: &result)\n return result\n }\n}\n\n// A helper type that encapsulates the logic for collecting runtime function\n// counters. This type should not be used directly. You should use its\n// wrappers GlobalRuntimeFunctionCountersState and\n// ObjectRuntimeFunctionCountersState instead.\ninternal struct _RuntimeFunctionCountersState: _RuntimeFunctionCountersStats {\n /// Reserve enough space for 64 elements.\n typealias Counters =\n (\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32, UInt32,\n UInt32, UInt32, UInt32, UInt32\n )\n\n private var counters: Counters = (\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0), UInt32(0),\n UInt32(0), UInt32(0), UInt32(0), UInt32(0)\n )\n\n // Use counter name as index.\n subscript(_ counterName: String) -> UInt32 {\n get {\n if let index = _RuntimeFunctionCounters.runtimeFunctionNameToIndex[counterName] {\n return self[index]\n }\n fatalError("Unknown counter name: \(counterName)")\n }\n\n set {\n if let index = _RuntimeFunctionCounters.runtimeFunctionNameToIndex[counterName] {\n self[index] = newValue\n return\n }\n fatalError("Unknown counter name: \(counterName)")\n }\n }\n\n subscript(_ index: Int) -> UInt32 {\n @inline(never)\n get {\n if (index >= _RuntimeFunctionCounters.numRuntimeFunctionCounters) {\n fatalError("Counter index should be in the range " +\n "0..<\(_RuntimeFunctionCounters.numRuntimeFunctionCounters)")\n }\n var tmpCounters = counters\n let counter: UInt32 = unsafe withUnsafePointer(to: &tmpCounters) { ptr in\n return unsafe ptr.withMemoryRebound(to: UInt32.self, capacity: 64) { buf in\n return unsafe buf[index]\n }\n }\n return counter\n }\n\n @inline(never)\n set {\n if (index >= _RuntimeFunctionCounters.numRuntimeFunctionCounters) {\n fatalError("Counter index should be in the range " +\n "0..<\(_RuntimeFunctionCounters.numRuntimeFunctionCounters)")\n }\n unsafe withUnsafeMutablePointer(to: &counters) {\n unsafe $0.withMemoryRebound(to: UInt32.self, capacity: 64) {\n unsafe $0[index] = newValue\n }\n }\n }\n }\n}\n\nextension _RuntimeFunctionCounters {\n @_silgen_name("_swift_getObjectRuntimeFunctionCounters")\n internal static func getObjectRuntimeFunctionCounters(\n _ object: UnsafeRawPointer, _ result: inout _RuntimeFunctionCountersState)\n\n @_silgen_name("_swift_getGlobalRuntimeFunctionCounters")\n internal static func getGlobalRuntimeFunctionCounters(\n _ result: inout _RuntimeFunctionCountersState)\n\n @_silgen_name("_swift_setGlobalRuntimeFunctionCounters")\n internal static func setGlobalRuntimeFunctionCounters(\n _ state: inout _RuntimeFunctionCountersState)\n\n @_silgen_name("_swift_setObjectRuntimeFunctionCounters")\n internal static func setObjectRuntimeFunctionCounters(\n _ object: UnsafeRawPointer,\n _ state: inout _RuntimeFunctionCountersState)\n\n @discardableResult\n @_silgen_name("_swift_setGlobalRuntimeFunctionCountersMode")\n static\n public // @testable\n func setGlobalRuntimeFunctionCountersMode(enable: Bool) -> Bool\n\n @discardableResult\n @_silgen_name("_swift_setPerObjectRuntimeFunctionCountersMode")\n static\n public // @testable\n func setPerObjectRuntimeFunctionCountersMode(enable: Bool) -> Bool\n\n /// Enable runtime function counters updates by the runtime.\n static\n public // @testable\n func enableRuntimeFunctionCountersUpdates(\n mode: (globalMode: Bool, perObjectMode: Bool) = (true, true)) {\n _RuntimeFunctionCounters.setGlobalRuntimeFunctionCountersMode(\n enable: mode.globalMode)\n _RuntimeFunctionCounters.setPerObjectRuntimeFunctionCountersMode(\n enable: mode.perObjectMode)\n }\n\n /// Disable runtime function counters updates by the runtime.\n static\n public // @testable\n func disableRuntimeFunctionCountersUpdates() ->\n (globalMode: Bool, perObjectMode: Bool) {\n let oldGlobalMode =\n _RuntimeFunctionCounters.setGlobalRuntimeFunctionCountersMode(\n enable: false)\n let oldPerObjectMode =\n _RuntimeFunctionCounters.setPerObjectRuntimeFunctionCountersMode(\n enable: false)\n return (oldGlobalMode, oldPerObjectMode)\n }\n}\n\nextension _RuntimeFunctionCountersStats {\n typealias Counters = _RuntimeFunctionCounters\n @inline(never)\n public // @testable\n func dump<T: TextOutputStream>(skipUnchanged: Bool, to: inout T) {\n for i in 0..<Counters.numRuntimeFunctionCounters {\n if skipUnchanged && self[i] == 0 {\n continue\n }\n print("counter \(i) : " +\n "\(Counters.runtimeFunctionNames[i])" +\n " at offset: " +\n "\(unsafe Counters.runtimeFunctionCountersOffsets[i]):" +\n " \(self[i])", to: &to)\n }\n }\n\n @inline(never)\n public // @testable\n func dumpDiff<T: TextOutputStream>(\n _ after: Self, skipUnchanged: Bool, to: inout T\n ) {\n for i in 0..<Counters.numRuntimeFunctionCounters {\n if self[i] == 0 && after[i] == 0 {\n continue\n }\n if skipUnchanged && self[i] == after[i] {\n continue\n }\n print("counter \(i) : " +\n "\(Counters.runtimeFunctionNames[i])" +\n " at offset: " +\n "\(unsafe Counters.runtimeFunctionCountersOffsets[i]): " +\n "before \(self[i]) " +\n "after \(after[i])" + " diff=\(after[i]-self[i])", to: &to)\n }\n }\n\n public // @testable\n func diff(_ other: Self) -> Self {\n var result = Self()\n for i in 0..<Counters.numRuntimeFunctionCounters {\n result[i] = other[i] - self[i]\n }\n return result\n }\n}\n\n/// This type should be used to collect statistics about the global runtime\n/// function pointers.\npublic // @testable\nstruct _GlobalRuntimeFunctionCountersState: _RuntimeFunctionCountersStats {\n var state = _RuntimeFunctionCountersState()\n\n public init() {\n getGlobalRuntimeFunctionCounters()\n }\n\n mutating public func getGlobalRuntimeFunctionCounters() {\n _RuntimeFunctionCounters.getGlobalRuntimeFunctionCounters(&state)\n }\n\n mutating public func setGlobalRuntimeFunctionCounters() {\n _RuntimeFunctionCounters.setGlobalRuntimeFunctionCounters(&state)\n }\n\n public subscript(_ index: String) -> UInt32 {\n get {\n return state[index]\n }\n set {\n state[index] = newValue\n }\n }\n\n public subscript(_ index: Int) -> UInt32 {\n get {\n return state[index]\n }\n set {\n state[index] = newValue\n }\n }\n}\n\n/// This type should be used to collect statistics about object runtime\n/// function pointers.\npublic // @testable\nstruct _ObjectRuntimeFunctionCountersState: _RuntimeFunctionCountersStats {\n var state = _RuntimeFunctionCountersState()\n\n // Initialize with the counters for a given object.\n public init(_ p: UnsafeRawPointer) {\n unsafe getObjectRuntimeFunctionCounters(p)\n }\n\n public init() {\n }\n\n mutating public func getObjectRuntimeFunctionCounters(_ o: UnsafeRawPointer) {\n unsafe _RuntimeFunctionCounters.getObjectRuntimeFunctionCounters(o, &state)\n }\n\n mutating public func setObjectRuntimeFunctionCounters(_ o: UnsafeRawPointer) {\n unsafe _RuntimeFunctionCounters.setObjectRuntimeFunctionCounters(o, &state)\n }\n\n public subscript(_ index: String) -> UInt32 {\n get {\n return state[index]\n }\n set {\n state[index] = newValue\n }\n }\n\n public subscript(_ index: Int) -> UInt32 {\n get {\n return state[index]\n }\n set {\n state[index] = newValue\n }\n }\n}\n\n/// Collects all references inside an object.\n/// Runtime counters tracking is disabled for the duration of this operation\n/// so that it does not affect those counters.\npublic // @testable\nfunc _collectReferencesInsideObject(_ value: Any) -> [UnsafeRawPointer] {\n let savedMode = _RuntimeFunctionCounters.disableRuntimeFunctionCountersUpdates()\n // Collect all references inside the object\n let refs = unsafe _RuntimeFunctionCounters.collectAllReferencesInsideObject(value)\n _RuntimeFunctionCounters.enableRuntimeFunctionCountersUpdates(mode: savedMode)\n return unsafe refs\n}\n\n/// A helper method to measure how global and per-object function counters\n/// were changed during execution of a closure provided as a parameter.\n/// Returns counter diffs for global counters and for the object-specific\n/// counters related to a given object.\npublic // @testable\nfunc _measureRuntimeFunctionCountersDiffs(\n objects: [UnsafeRawPointer], _ body: () -> Void) ->\n (_GlobalRuntimeFunctionCountersState, [_ObjectRuntimeFunctionCountersState]) {\n let savedMode =\n _RuntimeFunctionCounters.disableRuntimeFunctionCountersUpdates()\n let globalCountersBefore = _GlobalRuntimeFunctionCountersState()\n var objectsCountersBefore: [_ObjectRuntimeFunctionCountersState] = []\n for unsafe object in unsafe objects {\n unsafe objectsCountersBefore.append(_ObjectRuntimeFunctionCountersState(object))\n }\n // Enable counters updates.\n _RuntimeFunctionCounters.enableRuntimeFunctionCountersUpdates(\n mode: (globalMode: true, perObjectMode: true))\n // Execute the provided user's code.\n body()\n // Disable counters updates.\n _RuntimeFunctionCounters.enableRuntimeFunctionCountersUpdates(\n mode: (globalMode: false, perObjectMode: false))\n\n let globalCountersAfter = _GlobalRuntimeFunctionCountersState()\n var objectsCountersDiff: [_ObjectRuntimeFunctionCountersState] = []\n for unsafe (idx, object) in unsafe objects.enumerated() {\n let objectCountersAfter = unsafe _ObjectRuntimeFunctionCountersState(object)\n objectsCountersDiff.append(\n objectsCountersBefore[idx].diff(objectCountersAfter))\n }\n\n _RuntimeFunctionCounters.enableRuntimeFunctionCountersUpdates(\n mode: savedMode)\n return (globalCountersBefore.diff(globalCountersAfter), objectsCountersDiff)\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_RuntimeFunctionCounters.swift
cpp_apple_swift_stdlib_public_core_RuntimeFunctionCounters.swift
Swift
19,434
0.95
0.094718
0.182377
awesome-app
941
2024-12-18T12:44:14.030967
Apache-2.0
false
97d51700b988123e9fafd7bde80507fa
//===----------------------------------------------------------------------===//\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\n/// A type `T` whose metatype `T.Type` is `Sendable`.\n@_marker public protocol SendableMetatype: ~Copyable, ~Escapable { }\n\n/// A thread-safe type whose values can be shared across arbitrary concurrent\n/// contexts without introducing a risk of data races. Values of the type may\n/// have no shared mutable state, or they may protect that state with a lock or\n/// by forcing it to only be accessed from a specific actor.\n///\n/// You can safely pass values of a sendable type\n/// from one concurrency domain to another ---\n/// for example, you can pass a sendable value as the argument\n/// when calling an actor's methods.\n/// All of the following can be marked as sendable:\n///\n/// - Value types\n///\n/// - Reference types with no mutable storage\n///\n/// - Reference types that internally manage access to their state\n///\n/// - Functions and closures (by marking them with `@Sendable`)\n///\n/// Although this protocol doesn't have any required methods or properties,\n/// it does have semantic requirements that are enforced at compile time.\n/// These requirements are listed in the sections below.\n/// Conformance to `Sendable` must be declared\n/// in the same file as the type's declaration.\n///\n/// To declare conformance to `Sendable` without any compiler enforcement,\n/// write `@unchecked Sendable`.\n/// You are responsible for the correctness of unchecked sendable types,\n/// for example, by protecting all access to its state with a lock or a queue.\n/// Unchecked conformance to `Sendable` also disables enforcement\n/// of the rule that conformance must be in the same file.\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/// ### Sendable Structures and Enumerations\n///\n/// To satisfy the requirements of the `Sendable` protocol,\n/// an enumeration or structure must have only sendable\n/// members and associated values.\n/// In some cases, structures and enumerations\n/// that satisfy the requirements implicitly conform to `Sendable`:\n///\n/// - Frozen structures and enumerations\n///\n/// - Structures and enumerations\n/// that aren't public and aren't marked `@usableFromInline`.\n///\n/// Otherwise, you need to declare conformance to `Sendable` explicitly.\n///\n/// Structures that have nonsendable stored properties\n/// and enumerations that have nonsendable associated values\n/// can be marked as `@unchecked Sendable`,\n/// disabling compile-time correctness checks,\n/// after you manually verify that\n/// they satisfy the `Sendable` protocol's semantic requirements.\n///\n/// ### Sendable Actors\n///\n/// All actor types implicitly conform to `Sendable`\n/// because actors ensure that all access to their mutable state\n/// is performed sequentially.\n///\n/// ### Sendable Classes\n///\n/// To satisfy the requirements of the `Sendable` protocol,\n/// a class must:\n///\n/// - Be marked `final`\n///\n/// - Contain only stored properties that are immutable and sendable\n///\n/// - Have no superclass or have `NSObject` as the superclass\n///\n/// Classes marked with `@MainActor` are implicitly sendable,\n/// because the main actor coordinates all access to its state.\n/// These classes can have stored properties that are mutable and nonsendable.\n///\n/// Classes that don't meet the requirements above\n/// can be marked as `@unchecked Sendable`,\n/// disabling compile-time correctness checks,\n/// after you manually verify that\n/// they satisfy the `Sendable` protocol's semantic requirements.\n///\n/// ### Sendable Functions and Closures\n///\n/// Instead of conforming to the `Sendable` protocol,\n/// you mark sendable functions and closures with the `@Sendable` attribute.\n/// Any values that the function or closure captures must be sendable.\n/// In addition, sendable closures must use only by-value captures,\n/// and the captured values must be of a sendable type.\n///\n/// In a context that expects a sendable closure,\n/// a closure that satisfies the requirements\n/// implicitly conforms to `Sendable` ---\n/// for example, in a call to `Task.detached(priority:operation:)`.\n///\n/// You can explicitly mark a closure as sendable\n/// by writing `@Sendable` as part of a type annotation,\n/// or by writing `@Sendable` before the closure's parameters ---\n/// for example:\n///\n/// let sendableClosure = { @Sendable (number: Int) -> String in\n/// if number > 12 {\n/// return "More than a dozen."\n/// } else {\n/// return "Less than a dozen"\n/// }\n/// }\n///\n/// ### Sendable Tuples\n///\n/// To satisfy the requirements of the `Sendable` protocol,\n/// all of the elements of the tuple must be sendable.\n/// Tuples that satisfy the requirements implicitly conform to `Sendable`.\n///\n/// ### Sendable Metatypes\n///\n/// Metatypes such as `Int.Type` implicitly conform to the `Sendable` protocol.\n@_marker public protocol Sendable: SendableMetatype, ~Copyable, ~Escapable { }\n\n///\n/// A type whose values can safely be passed across concurrency domains by copying,\n/// but which disables some safety checking at the conformance site.\n///\n/// Use an unchecked conformance to `Sendable` instead --- for example:\n///\n/// struct MyStructure: @unchecked Sendable { ... }\n@available(*, deprecated, message: "Use @unchecked Sendable instead")\n@available(swift, obsoleted: 6.0, message: "Use @unchecked Sendable instead")\n@_marker public protocol UnsafeSendable: Sendable { }\n\n// Historical names\n@available(*, deprecated, renamed: "Sendable")\n@available(swift, obsoleted: 6.0, renamed: "Sendable")\npublic typealias ConcurrentValue = Sendable\n\n@available(*, deprecated, renamed: "Sendable")\n@available(swift, obsoleted: 6.0, renamed: "Sendable")\npublic typealias UnsafeConcurrentValue = UnsafeSendable\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Sendable.swift
cpp_apple_swift_stdlib_public_core_Sendable.swift
Swift
6,417
0.95
0.06962
0.928105
python-kit
639
2024-10-13T18:06:07.097308
Apache-2.0
false
e196e5c64032cc810e469abff06350ed
//===----------------------------------------------------------------------===//\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 supplies the values of a sequence one at a time.\n///\n/// The `IteratorProtocol` protocol is tightly linked with the `Sequence`\n/// protocol. Sequences provide access to their elements by creating an\n/// iterator, which keeps track of its iteration process and returns one\n/// element at a time as it advances through the sequence.\n///\n/// Whenever you use a `for`-`in` loop with an array, set, or any other\n/// collection or sequence, you're using that type's iterator. Swift uses a\n/// sequence's or collection's iterator internally to enable the `for`-`in`\n/// loop language construct.\n///\n/// Using a sequence's iterator directly gives you access to the same elements\n/// in the same order as iterating over that sequence using a `for`-`in` loop.\n/// For example, you might typically use a `for`-`in` loop to print each of\n/// the elements in an array.\n///\n/// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"]\n/// for animal in animals {\n/// print(animal)\n/// }\n/// // Prints "Antelope"\n/// // Prints "Butterfly"\n/// // Prints "Camel"\n/// // Prints "Dolphin"\n///\n/// Behind the scenes, Swift uses the `animals` array's iterator to loop over\n/// the contents of the array.\n///\n/// var animalIterator = animals.makeIterator()\n/// while let animal = animalIterator.next() {\n/// print(animal)\n/// }\n/// // Prints "Antelope"\n/// // Prints "Butterfly"\n/// // Prints "Camel"\n/// // Prints "Dolphin"\n///\n/// The call to `animals.makeIterator()` returns an instance of the array's\n/// iterator. Next, the `while` loop calls the iterator's `next()` method\n/// repeatedly, binding each element that is returned to `animal` and exiting\n/// when the `next()` method returns `nil`.\n///\n/// Using Iterators Directly\n/// ========================\n///\n/// You rarely need to use iterators directly, because a `for`-`in` loop is the\n/// more idiomatic approach to traversing a sequence in Swift. Some\n/// algorithms, however, may call for direct iterator use.\n///\n/// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)`\n/// method defined in the standard library, which takes an initial value and a\n/// combining closure, `reduce1(_:)` uses the first element of the sequence as\n/// the initial value.\n///\n/// Here's an implementation of the `reduce1(_:)` method. The sequence's\n/// iterator is used directly to retrieve the initial value before looping\n/// over the rest of the sequence.\n///\n/// extension Sequence {\n/// func reduce1(\n/// _ nextPartialResult: (Element, Element) -> Element\n/// ) -> Element?\n/// {\n/// var i = makeIterator()\n/// guard var accumulated = i.next() else {\n/// return nil\n/// }\n///\n/// while let element = i.next() {\n/// accumulated = nextPartialResult(accumulated, element)\n/// }\n/// return accumulated\n/// }\n/// }\n///\n/// The `reduce1(_:)` method makes certain kinds of sequence operations\n/// simpler. Here's how to find the longest string in a sequence, using the\n/// `animals` array introduced earlier as an example:\n///\n/// let longestAnimal = animals.reduce1 { current, element in\n/// if current.count > element.count {\n/// return current\n/// } else {\n/// return element\n/// }\n/// }\n/// print(longestAnimal)\n/// // Prints Optional("Butterfly")\n///\n/// Using Multiple Iterators\n/// ========================\n///\n/// Whenever you use multiple iterators (or `for`-`in` loops) over a single\n/// sequence, be sure you know that the specific sequence supports repeated\n/// iteration, either because you know its concrete type or because the\n/// sequence is also constrained to the `Collection` protocol.\n///\n/// Obtain each separate iterator from separate calls to the sequence's\n/// `makeIterator()` method rather than by copying. Copying an iterator is\n/// safe, but advancing one copy of an iterator by calling its `next()` method\n/// may invalidate other copies of that iterator. `for`-`in` loops are safe in\n/// this regard.\n///\n/// Adding IteratorProtocol Conformance to Your Type\n/// ================================================\n///\n/// Implementing an iterator that conforms to `IteratorProtocol` is simple.\n/// Declare a `next()` method that advances one step in the related sequence\n/// and returns the current element. When the sequence has been exhausted, the\n/// `next()` method returns `nil`.\n///\n/// For example, consider a custom `Countdown` sequence. You can initialize the\n/// `Countdown` sequence with a starting integer and then iterate over the\n/// count down to zero. The `Countdown` structure's definition is short: It\n/// contains only the starting count and the `makeIterator()` method required\n/// by the `Sequence` protocol.\n///\n/// struct Countdown: Sequence {\n/// let start: Int\n///\n/// func makeIterator() -> CountdownIterator {\n/// return CountdownIterator(self)\n/// }\n/// }\n///\n/// The `makeIterator()` method returns another custom type, an iterator named\n/// `CountdownIterator`. The `CountdownIterator` type keeps track of both the\n/// `Countdown` sequence that it's iterating and the number of times it has\n/// returned a value.\n///\n/// struct CountdownIterator: IteratorProtocol {\n/// let countdown: Countdown\n/// var times = 0\n///\n/// init(_ countdown: Countdown) {\n/// self.countdown = countdown\n/// }\n///\n/// mutating func next() -> Int? {\n/// let nextNumber = countdown.start - times\n/// guard nextNumber > 0\n/// else { return nil }\n///\n/// times += 1\n/// return nextNumber\n/// }\n/// }\n///\n/// Each time the `next()` method is called on a `CountdownIterator` instance,\n/// it calculates the new next value, checks to see whether it has reached\n/// zero, and then returns either the number, or `nil` if the iterator is\n/// finished returning elements of the sequence.\n///\n/// Creating and iterating over a `Countdown` sequence uses a\n/// `CountdownIterator` to handle the iteration.\n///\n/// let threeTwoOne = Countdown(start: 3)\n/// for count in threeTwoOne {\n/// print("\(count)...")\n/// }\n/// // Prints "3..."\n/// // Prints "2..."\n/// // Prints "1..."\npublic protocol IteratorProtocol<Element> {\n /// The type of element traversed by the iterator.\n associatedtype 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, in order, all the elements of the\n /// underlying sequence. As soon as the sequence has run out of elements, all\n /// subsequent calls return `nil`.\n ///\n /// You must not call this method if any other copy of this iterator has been\n /// advanced with a call to its `next()` method.\n ///\n /// The following example shows how an iterator can be used explicitly to\n /// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and\n /// then call 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 mutating func next() -> Element?\n}\n\n/// A type that provides sequential, iterated access to its elements.\n///\n/// A sequence is a list of values that you can step through one at a time. The\n/// most common way to iterate over the elements of a sequence is to use a\n/// `for`-`in` loop:\n///\n/// let oneTwoThree = 1...3\n/// for number in oneTwoThree {\n/// print(number)\n/// }\n/// // Prints "1"\n/// // Prints "2"\n/// // Prints "3"\n///\n/// While seemingly simple, this capability gives you access to a large number\n/// of operations that you can perform on any sequence. As an example, to\n/// check whether a sequence includes a particular value, you can test each\n/// value sequentially until you've found a match or reached the end of the\n/// sequence. This example checks to see whether a particular insect is in an\n/// array.\n///\n/// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]\n/// var hasMosquito = false\n/// for bug in bugs {\n/// if bug == "Mosquito" {\n/// hasMosquito = true\n/// break\n/// }\n/// }\n/// print("'bugs' has a mosquito: \(hasMosquito)")\n/// // Prints "'bugs' has a mosquito: false"\n///\n/// The `Sequence` protocol provides default implementations for many common\n/// operations that depend on sequential access to a sequence's values. For\n/// clearer, more concise code, the example above could use the array's\n/// `contains(_:)` method, which every sequence inherits from `Sequence`,\n/// instead of iterating manually:\n///\n/// if bugs.contains("Mosquito") {\n/// print("Break out the bug spray.")\n/// } else {\n/// print("Whew, no mosquitos!")\n/// }\n/// // Prints "Whew, no mosquitos!"\n///\n/// Repeated Access\n/// ===============\n///\n/// The `Sequence` protocol makes no requirement on conforming types regarding\n/// whether they will be destructively consumed by iteration. As a\n/// consequence, don't assume that multiple `for`-`in` loops on a sequence\n/// will either resume iteration or restart from the beginning:\n///\n/// for element in sequence {\n/// if ... some condition { break }\n/// }\n///\n/// for element in sequence {\n/// // No defined behavior\n/// }\n///\n/// In this case, you cannot assume either that a sequence will be consumable\n/// and will resume iteration, or that a sequence is a collection and will\n/// restart iteration from the first element. A conforming sequence that is\n/// not a collection is allowed to produce an arbitrary sequence of elements\n/// in the second `for`-`in` loop.\n///\n/// To establish that a type you've created supports nondestructive iteration,\n/// add conformance to the `Collection` protocol.\n///\n/// Conforming to the Sequence Protocol\n/// ===================================\n///\n/// Making your own custom types conform to `Sequence` enables many useful\n/// operations, like `for`-`in` looping and the `contains` method, without\n/// much effort. To add `Sequence` conformance to your own custom type, add a\n/// `makeIterator()` method that returns an iterator.\n///\n/// Alternatively, if your type can act as its own iterator, implementing the\n/// requirements of the `IteratorProtocol` protocol and declaring conformance\n/// to both `Sequence` and `IteratorProtocol` are sufficient.\n///\n/// Here's a definition of a `Countdown` sequence that serves as its own\n/// iterator. The `makeIterator()` method is provided as a default\n/// implementation.\n///\n/// struct Countdown: Sequence, IteratorProtocol {\n/// var count: Int\n///\n/// mutating func next() -> Int? {\n/// if count == 0 {\n/// return nil\n/// } else {\n/// defer { count -= 1 }\n/// return count\n/// }\n/// }\n/// }\n///\n/// let threeToGo = Countdown(count: 3)\n/// for i in threeToGo {\n/// print(i)\n/// }\n/// // Prints "3"\n/// // Prints "2"\n/// // Prints "1"\n///\n/// Expected Performance\n/// ====================\n///\n/// A sequence should provide its iterator in O(1). The `Sequence` protocol\n/// makes no other requirements about element access, so routines that\n/// traverse a sequence should be considered O(*n*) unless documented\n/// otherwise.\npublic protocol Sequence<Element> {\n /// A type representing the sequence's elements.\n associatedtype Element\n\n /// A type that provides the sequence's iteration interface and\n /// encapsulates its iteration state.\n associatedtype Iterator: IteratorProtocol where Iterator.Element == 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(*, unavailable, renamed: "Iterator")\n typealias Generator = Iterator\n\n /// A type that represents a subsequence of some of the sequence's elements.\n // associatedtype SubSequence: Sequence = AnySequence<Element>\n // where Element == SubSequence.Element,\n // SubSequence.SubSequence == SubSequence\n // typealias SubSequence = AnySequence<Element>\n\n /// Returns an iterator over the elements of this sequence.\n __consuming func makeIterator() -> Iterator\n\n /// A value less than or equal to the number of elements in the sequence,\n /// calculated nondestructively.\n ///\n /// The default implementation returns 0. If you provide your own\n /// implementation, make sure to compute the value nondestructively.\n ///\n /// - Complexity: O(1), except if the sequence also conforms to `Collection`.\n /// In this case, see the documentation of `Collection.underestimatedCount`.\n var underestimatedCount: Int { get }\n\n /// Sequences whose `Element` is `Equatable` and that are able to quickly\n /// check if they contain a particular value can implement this requirement\n /// to speed up the standard `contains` method.\n ///\n /// The default implementation returns nil, indicating that `contains` should\n /// fall back to the standard linear search algorithm.\n ///\n /// `Sequence` and `Collection` algorithms other than `contains` itself may\n /// adapt their behavior based on whether or not this function returns nil.\n /// For example, a generic algorithm that needs to do containment checks for\n /// many different values may decide not to copy items into a temporary `Set`\n /// if it sees that the sequence implements this method. Therefore, sequences\n /// should only implement this method if they can do it in better than linear\n /// time.\n ///\n /// For sequences that are destructively consumed by iteration, calling this\n /// method must not consume any elements. (Such sequences usually leave this\n /// method with its default, `nil`-returning implementation, which trivially\n /// satisfies this requirement.)\n ///\n /// - Returns: `nil` if containment cannot be verified in better than linear\n /// time; otherwise, the method returns a boolean value indicating whether\n /// or not the item is an element of this sequence.\n ///\n /// - Complexity: If this function returns `nil`, it must do so in constant\n /// (O(1)) time. If this returns non-`nil`, then it must have better than linear\n /// (O(*n*)) complexity.\n func _customContainsEquatableElement(\n _ element: Element\n ) -> Bool?\n\n /// Create a native array buffer containing the elements of `self`,\n /// in the same order.\n __consuming func _copyToContiguousArray() -> ContiguousArray<Element>\n\n /// Copy `self` into an unsafe buffer, initializing its memory.\n ///\n /// The default implementation simply iterates over the elements of the\n /// sequence, initializing the buffer one item at a time.\n ///\n /// For sequences whose elements are stored in contiguous chunks of memory,\n /// it may be more efficient to copy them in bulk, using the\n /// `UnsafeMutablePointer.initialize(from:count:)` method.\n ///\n /// - Parameter ptr: An unsafe buffer addressing uninitialized memory. The\n /// buffer must be of sufficient size to accommodate\n /// `source.underestimatedCount` elements. (Some implementations trap\n /// if given a buffer that's smaller than this.)\n ///\n /// - Returns: `(it, c)`, where `c` is the number of elements copied into the\n /// buffer, and `it` is a partially consumed iterator that can be used to\n /// retrieve elements that did not fit into the buffer (if any). (This can\n /// only happen if `underestimatedCount` turned out to be an actual\n /// underestimate, and the buffer did not contain enough space to hold the\n /// entire sequence.)\n ///\n /// On return, the memory region in `buffer[0 ..< c]` is initialized to\n /// the first `c` elements in the sequence.\n __consuming func _copyContents(\n initializing ptr: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index)\n\n /// Executes a closure on the sequence’s contiguous storage.\n ///\n /// This method calls `body(buffer)`, where `buffer` is a pointer to the\n /// collection’s contiguous storage. If the contiguous storage doesn't exist,\n /// the collection creates it. If the collection doesn’t support an internal\n /// representation in a form of contiguous storage, the method doesn’t call\n /// `body` --- it immediately returns `nil`.\n ///\n /// The optimizer can often eliminate bounds- and uniqueness-checking\n /// within an algorithm. When that fails, however, invoking the same\n /// algorithm on the `buffer` argument may let you trade safety for speed.\n ///\n /// Successive calls to this method may provide a different pointer on each\n /// call. Don't store `buffer` outside of this method.\n ///\n /// A `Collection` that provides its own implementation of this method\n /// must provide contiguous storage to its elements in the same order\n /// as they appear in the collection. This guarantees that it's possible to\n /// generate contiguous mutable storage to any of its subsequences by slicing\n /// `buffer` with a range formed from the distances to the subsequence's\n /// `startIndex` and `endIndex`, respectively.\n ///\n /// - Parameters:\n /// - body: A closure that receives an `UnsafeBufferPointer` to the\n /// sequence's contiguous storage.\n /// - Returns: The value returned from `body`, unless the sequence doesn't\n /// support contiguous storage, in which case the method ignores `body` and\n /// returns `nil`.\n @safe\n func withContiguousStorageIfAvailable<R>(\n _ body: (_ buffer: UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R?\n}\n\n// Provides a default associated type witness for Iterator when the\n// Self type is both a Sequence and an Iterator.\nextension Sequence where Self: IteratorProtocol {\n @_implements(Sequence, Iterator)\n public typealias _Default_Iterator = Self\n}\n\n/// A default makeIterator() function for `IteratorProtocol` instances that\n/// are declared to conform to `Sequence`\nextension Sequence where Self.Iterator == Self {\n /// Returns an iterator over the elements of this sequence.\n @inlinable\n public __consuming func makeIterator() -> Self {\n return self\n }\n}\n\n/// A sequence that lazily consumes and drops `n` elements from an underlying\n/// `Base` iterator before possibly returning the first available element.\n///\n/// The underlying iterator's sequence may be infinite.\n@frozen\npublic struct DropFirstSequence<Base: Sequence> {\n @usableFromInline\n internal let _base: Base\n @usableFromInline\n internal let _limit: Int\n \n @inlinable \n public init(_ base: Base, dropping limit: Int) {\n _precondition(limit >= 0, \n "Can't drop a negative number of elements from a sequence")\n _base = base\n _limit = limit\n }\n}\n\nextension DropFirstSequence: Sendable where Base: Sendable {}\n\nextension DropFirstSequence: Sequence {\n public typealias Element = Base.Element\n public typealias Iterator = Base.Iterator\n public typealias SubSequence = AnySequence<Element>\n \n @inlinable\n @inline(__always)\n public __consuming func makeIterator() -> Iterator {\n var it = _base.makeIterator()\n var dropped = 0\n while dropped < _limit, it.next() != nil { dropped &+= 1 }\n return it\n }\n\n @inlinable\n public __consuming func dropFirst(_ k: Int) -> DropFirstSequence<Base> {\n // If this is already a _DropFirstSequence, we need to fold in\n // the current drop count and drop limit so no data is lost.\n //\n // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to\n // [1,2,3,4].dropFirst(2).\n return DropFirstSequence(_base, dropping: _limit + k)\n }\n}\n\n/// A sequence that only consumes up to `n` elements from an underlying\n/// `Base` iterator.\n///\n/// The underlying iterator's sequence may be infinite.\n@frozen\npublic struct PrefixSequence<Base: Sequence> {\n @usableFromInline\n internal var _base: Base\n @usableFromInline\n internal let _maxLength: Int\n\n @inlinable\n public init(_ base: Base, maxLength: Int) {\n _precondition(maxLength >= 0, "Can't take a prefix of negative length")\n _base = base\n _maxLength = maxLength\n }\n}\n\nextension PrefixSequence: Sendable where Base: Sendable {}\n\nextension PrefixSequence {\n @frozen\n public struct Iterator {\n @usableFromInline\n internal var _base: Base.Iterator\n @usableFromInline\n internal var _remaining: Int\n \n @inlinable\n internal init(_ base: Base.Iterator, maxLength: Int) {\n _base = base\n _remaining = maxLength\n }\n } \n}\n\nextension PrefixSequence.Iterator: Sendable where Base.Iterator: Sendable {}\n\nextension PrefixSequence.Iterator: IteratorProtocol {\n public typealias Element = Base.Element\n \n @inlinable\n public mutating func next() -> Element? {\n if _remaining != 0 {\n _remaining &-= 1\n return _base.next()\n } else {\n return nil\n }\n } \n}\n\nextension PrefixSequence: Sequence {\n @inlinable\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_base.makeIterator(), maxLength: _maxLength)\n }\n\n @inlinable\n public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Base> {\n let length = Swift.min(maxLength, self._maxLength)\n return PrefixSequence(_base, maxLength: length)\n }\n}\n\n\n/// A sequence that lazily consumes and drops `n` elements from an underlying\n/// `Base` iterator before possibly returning the first available element.\n///\n/// The underlying iterator's sequence may be infinite.\n@frozen\npublic struct DropWhileSequence<Base: Sequence> {\n public typealias Element = Base.Element\n \n @usableFromInline\n internal var _iterator: Base.Iterator\n @usableFromInline\n internal var _nextElement: Element?\n \n @inlinable\n internal init(iterator: Base.Iterator, predicate: (Element) throws -> Bool) rethrows {\n _iterator = iterator\n _nextElement = _iterator.next()\n \n while let x = _nextElement, try predicate(x) {\n _nextElement = _iterator.next()\n }\n }\n \n @inlinable\n internal init(_ base: Base, predicate: (Element) throws -> Bool) rethrows {\n self = try DropWhileSequence(iterator: base.makeIterator(), predicate: predicate)\n }\n}\n\nextension DropWhileSequence: Sendable\n where Base.Iterator: Sendable, Element: Sendable {}\n\nextension DropWhileSequence {\n @frozen\n public struct Iterator {\n @usableFromInline\n internal var _iterator: Base.Iterator\n @usableFromInline\n internal var _nextElement: Element?\n \n @inlinable\n internal init(_ iterator: Base.Iterator, nextElement: Element?) {\n _iterator = iterator\n _nextElement = nextElement\n }\n }\n}\n\nextension DropWhileSequence.Iterator: Sendable\n where Base.Iterator: Sendable, Element: Sendable {}\n\nextension DropWhileSequence.Iterator: IteratorProtocol {\n public typealias Element = Base.Element\n \n @inlinable\n public mutating func next() -> Element? {\n guard let next = _nextElement else { return nil }\n _nextElement = _iterator.next()\n return next\n }\n}\n\nextension DropWhileSequence: Sequence {\n @inlinable\n public func makeIterator() -> Iterator {\n return Iterator(_iterator, nextElement: _nextElement)\n }\n \n @inlinable\n public __consuming func drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> DropWhileSequence<Base> {\n guard let x = _nextElement, try predicate(x) else { return self }\n return try DropWhileSequence(iterator: _iterator, predicate: predicate)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Default implementations for Sequence\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\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 ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n @_alwaysEmitIntoClient\n public func map<T, E>(\n _ transform: (Element) throws(E) -> T\n ) throws(E) -> [T] {\n let initialCapacity = underestimatedCount\n var result = ContiguousArray<T>()\n result.reserveCapacity(initialCapacity)\n\n var iterator = self.makeIterator()\n\n // Add elements up to the initial capacity without checking for regrowth.\n for _ in 0..<initialCapacity {\n result.append(try transform(iterator.next()!))\n }\n // Add remaining elements, if any.\n while let element = iterator.next() {\n result.append(try transform(element))\n }\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("$sSTsE3mapySayqd__Gqd__7ElementQzKXEKlF")\n func __rethrows_map<T>(\n _ transform: (Element) throws -> T\n ) throws -> [T] {\n try map(transform)\n }\n\n /// Returns an array containing, in order, the elements of the sequence\n /// that satisfy the given predicate.\n ///\n /// In this example, `filter(_:)` is used to include only names shorter than\n /// five characters.\n ///\n /// let cast = ["Vivien", "Marlon", "Kim", "Karl"]\n /// let shortNames = cast.filter { $0.count < 5 }\n /// print(shortNames)\n /// // Prints "["Kim", "Karl"]"\n ///\n /// - Parameter isIncluded: A closure that takes an element of the\n /// sequence as its argument and returns a Boolean value indicating\n /// whether the element should be included in the returned array.\n /// - Returns: An array of the elements that `isIncluded` allowed.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public __consuming func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n return try _filter(isIncluded)\n }\n\n @_transparent\n public func _filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> [Element] {\n\n var result = ContiguousArray<Element>()\n\n var iterator = self.makeIterator()\n\n while let element = iterator.next() {\n if try isIncluded(element) {\n result.append(element)\n }\n }\n\n return Array(result)\n }\n\n /// A value less than or equal to the number of elements in the sequence,\n /// calculated nondestructively.\n ///\n /// The default implementation returns 0. If you provide your own\n /// implementation, make sure to compute the value nondestructively.\n ///\n /// - Complexity: O(1), except if the sequence also conforms to `Collection`.\n /// In this case, see the documentation of `Collection.underestimatedCount`.\n @inlinable\n public var underestimatedCount: Int {\n return 0\n }\n\n @inlinable\n @inline(__always)\n public func _customContainsEquatableElement(\n _ element: Iterator.Element\n ) -> Bool? {\n return nil\n }\n\n /// Calls the given closure on each element in the sequence in the same order\n /// as a `for`-`in` loop.\n ///\n /// The two loops in the following example produce the same output:\n ///\n /// let numberWords = ["one", "two", "three"]\n /// for word in numberWords {\n /// print(word)\n /// }\n /// // Prints "one"\n /// // Prints "two"\n /// // Prints "three"\n ///\n /// numberWords.forEach { word in\n /// print(word)\n /// }\n /// // Same as above\n ///\n /// Using the `forEach` method is distinct from a `for`-`in` loop in two\n /// important ways:\n ///\n /// 1. You cannot use a `break` or `continue` statement to exit the current\n /// call of the `body` closure or skip subsequent calls.\n /// 2. Using the `return` statement in the `body` closure will exit only from\n /// the current call to `body`, not from any outer scope, and won't skip\n /// subsequent calls.\n ///\n /// - Parameter body: A closure that takes an element of the sequence as a\n /// parameter.\n @_semantics("sequence.forEach")\n @inlinable\n public func forEach(\n _ body: (Element) throws -> Void\n ) rethrows {\n for element in self {\n try body(element)\n }\n }\n}\n\nextension Sequence {\n /// Returns the first element of the sequence that satisfies the given\n /// predicate.\n ///\n /// The following example uses the `first(where:)` method to find the first\n /// negative number in an array of integers:\n ///\n /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]\n /// if let firstNegative = numbers.first(where: { $0 < 0 }) {\n /// print("The first negative number is \(firstNegative).")\n /// }\n /// // Prints "The first negative number is -2."\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 first 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 sequence.\n @inlinable\n public func first(\n where predicate: (Element) throws -> Bool\n ) rethrows -> Element? {\n for element in self {\n if try predicate(element) {\n return element\n }\n }\n return nil\n }\n}\n\nextension Sequence where Element: Equatable {\n /// Returns the longest possible subsequences of the sequence, 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 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 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 /// .map(String.init))\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 /// .map(String.init))\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 /// .map(String.init))\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 sequence, or one\n /// less than the number of subsequences to return. If `maxSplits + 1`\n /// subsequences are returned, the last one is a suffix of the original\n /// sequence containing the remaining elements. `maxSplits` must be\n /// greater than or equal to zero. The default value 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 sequence and for each instance of `separator` at the\n /// start or end of the sequence. If `true`, only nonempty subsequences\n /// are returned. The default value is `true`.\n /// - Returns: An array of subsequences, split from this sequence's elements.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public __consuming func split(\n separator: Element,\n maxSplits: Int = Int.max,\n omittingEmptySubsequences: Bool = true\n ) -> [ArraySlice<Element>] {\n return split(\n maxSplits: maxSplits,\n omittingEmptySubsequences: omittingEmptySubsequences,\n whereSeparator: { $0 == separator })\n }\n}\n\nextension Sequence {\n\n /// Returns the longest possible subsequences of the sequence, in order, that\n /// don't contain elements satisfying the given predicate. Elements that are\n /// used to split the sequence are not returned as part of 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 /// .map(String.init))\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(\n /// line.split(maxSplits: 1, whereSeparator: { $0 == " " })\n /// .map(String.init))\n /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"\n ///\n /// The final example passes `true` for the `allowEmptySlices` parameter, so\n /// the returned array contains empty strings where spaces were repeated.\n ///\n /// print(\n /// line.split(\n /// omittingEmptySubsequences: false,\n /// whereSeparator: { $0 == " " }\n /// ).map(String.init))\n /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"\n ///\n /// - Parameters:\n /// - maxSplits: The maximum number of times to split the sequence, or one\n /// less than the number of subsequences to return. If `maxSplits + 1`\n /// subsequences are returned, the last one is a suffix of the original\n /// sequence containing the remaining elements. `maxSplits` must be\n /// greater than or equal to zero. The default value 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 sequence satisfying the `isSeparator` predicate.\n /// If `true`, only nonempty subsequences are returned. The default\n /// value is `true`.\n /// - isSeparator: A closure that returns `true` if its argument should be\n /// used to split the sequence; otherwise, `false`.\n /// - Returns: An array of subsequences, split from this sequence's elements.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public __consuming func split(\n maxSplits: Int = Int.max,\n omittingEmptySubsequences: Bool = true,\n whereSeparator isSeparator: (Element) throws -> Bool\n ) rethrows -> [ArraySlice<Element>] {\n _precondition(maxSplits >= 0, "Must take zero or more splits")\n let whole = Array(self)\n return try whole.split(\n maxSplits: maxSplits, \n omittingEmptySubsequences: omittingEmptySubsequences, \n whereSeparator: isSeparator)\n }\n\n /// Returns a subsequence, up to the given maximum length, containing the\n /// final elements of the sequence.\n ///\n /// The sequence must be finite. If the maximum length exceeds the number of\n /// elements in the sequence, the result contains all the elements in the\n /// sequence.\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 ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public __consuming func suffix(_ maxLength: Int) -> [Element] {\n _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence")\n guard maxLength != 0 else { return [] }\n\n // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>\n // Put incoming elements into a ring buffer to save space. Once all\n // elements are consumed, reorder the ring buffer into a copy and return it.\n // This saves memory for sequences particularly longer than `maxLength`.\n var ringBuffer = ContiguousArray<Element>()\n ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount))\n\n var i = 0\n\n for element in self {\n if ringBuffer.count < maxLength {\n ringBuffer.append(element)\n } else {\n ringBuffer[i] = element\n i += 1\n if i >= maxLength {\n i = 0\n }\n }\n }\n\n if i != ringBuffer.startIndex {\n var rotated = ContiguousArray<Element>()\n rotated.reserveCapacity(ringBuffer.count)\n rotated += ringBuffer[i..<ringBuffer.endIndex]\n rotated += ringBuffer[0..<i]\n return Array(rotated)\n } else {\n return Array(ringBuffer)\n }\n }\n\n /// Returns a sequence 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 sequence, the result is an empty sequence.\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 sequence. `k` must be greater than or equal to zero.\n /// - Returns: A sequence starting after the specified number of\n /// elements.\n ///\n /// - Complexity: O(1), with O(*k*) deferred to each iteration of the result,\n /// where *k* is the number of elements to drop from the beginning of\n /// the sequence.\n @inlinable\n public __consuming func dropFirst(_ k: Int = 1) -> DropFirstSequence<Self> {\n return DropFirstSequence(self, dropping: k)\n }\n\n /// Returns a sequence containing all but the given number of final\n /// elements.\n ///\n /// The sequence must be finite. If the number of elements to drop exceeds\n /// the number of elements in the sequence, the result is an empty\n /// sequence.\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 n: The number of elements to drop off the end of the\n /// sequence. `n` must be greater than or equal to zero.\n /// - Returns: A sequence leaving off the specified number of elements.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public __consuming func dropLast(_ k: Int = 1) -> [Element] {\n _precondition(k >= 0, "Can't drop a negative number of elements from a sequence")\n guard k != 0 else { return Array(self) }\n\n // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>\n // Put incoming elements from this sequence in a holding tank, a ring buffer\n // of size <= k. If more elements keep coming in, pull them out of the\n // holding tank into the result, an `Array`. This saves\n // `k` * sizeof(Element) of memory, because slices keep the entire\n // memory of an `Array` alive.\n var result = ContiguousArray<Element>()\n var ringBuffer = ContiguousArray<Element>()\n var i = ringBuffer.startIndex\n\n for element in self {\n if ringBuffer.count < k {\n ringBuffer.append(element)\n } else {\n result.append(ringBuffer[i])\n ringBuffer[i] = element\n i += 1\n if i >= k {\n i = 0\n }\n }\n }\n return Array(result)\n }\n\n /// Returns a sequence by skipping the initial, consecutive elements that\n /// satisfy the given predicate.\n ///\n /// The following example uses the `drop(while:)` method to skip over the\n /// positive numbers at the beginning of the `numbers` array. The result\n /// begins with the first element of `numbers` that does not satisfy\n /// `predicate`.\n ///\n /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]\n /// let startingWithNegative = numbers.drop(while: { $0 > 0 })\n /// // startingWithNegative == [-2, 9, -6, 10, 1]\n ///\n /// If `predicate` matches every element in the sequence, the result is an\n /// empty sequence.\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 should be included in the result.\n /// - Returns: A sequence starting after the initial, consecutive elements\n /// that satisfy `predicate`.\n ///\n /// - Complexity: O(*k*), where *k* is the number of elements to drop from\n /// the beginning of the sequence.\n @inlinable\n public __consuming func drop(\n while predicate: (Element) throws -> Bool\n ) rethrows -> DropWhileSequence<Self> {\n return try DropWhileSequence(self, predicate: predicate)\n }\n\n /// Returns a sequence, up to the specified maximum length, containing the\n /// initial elements of the sequence.\n ///\n /// If the maximum length exceeds the number of elements in the sequence,\n /// the result contains all the elements in the sequence.\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. The\n /// value of `maxLength` must be greater than or equal to zero.\n /// - Returns: A sequence starting at the beginning of this sequence\n /// with at most `maxLength` elements.\n ///\n /// - Complexity: O(1)\n @inlinable\n public __consuming func prefix(_ maxLength: Int) -> PrefixSequence<Self> {\n return PrefixSequence(self, maxLength: maxLength)\n }\n\n /// Returns a sequence containing the initial, consecutive elements that\n /// satisfy the given predicate.\n ///\n /// The following example uses the `prefix(while:)` method to find the\n /// positive numbers at the beginning of the `numbers` array. Every element\n /// of `numbers` up to, but not including, the first negative value is\n /// included in the result.\n ///\n /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1]\n /// let positivePrefix = numbers.prefix(while: { $0 > 0 })\n /// // positivePrefix == [3, 7, 4]\n ///\n /// If `predicate` matches every element in the sequence, the resulting\n /// sequence contains every element of the sequence.\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 should be included in the result.\n /// - Returns: A sequence of the initial, consecutive elements that\n /// satisfy `predicate`.\n ///\n /// - Complexity: O(*k*), where *k* is the length of the result.\n @inlinable\n public __consuming func prefix(\n while predicate: (Element) throws -> Bool\n ) rethrows -> [Element] {\n var result = ContiguousArray<Element>()\n\n for element in self {\n guard try predicate(element) else {\n break\n }\n result.append(element)\n }\n return Array(result)\n }\n}\n\nextension Sequence {\n /// Copy `self` into an unsafe buffer, initializing its memory.\n ///\n /// The default implementation simply iterates over the elements of the\n /// sequence, initializing the buffer one item at a time.\n ///\n /// For sequences whose elements are stored in contiguous chunks of memory,\n /// it may be more efficient to copy them in bulk, using the\n /// `UnsafeMutablePointer.initialize(from:count:)` method.\n ///\n /// - Parameter ptr: An unsafe buffer addressing uninitialized memory. The\n /// buffer must be of sufficient size to accommodate\n /// `source.underestimatedCount` elements. (Some implementations trap\n /// if given a buffer that's smaller than this.)\n ///\n /// - Returns: `(it, c)`, where `c` is the number of elements copied into the\n /// buffer, and `it` is a partially consumed iterator that can be used to\n /// retrieve elements that did not fit into the buffer (if any). (This can\n /// only happen if `underestimatedCount` turned out to be an actual\n /// underestimate, and the buffer did not contain enough space to hold the\n /// entire sequence.)\n ///\n /// On return, the memory region in `buffer[0 ..< c]` is initialized to\n /// the first `c` elements in the sequence.\n @inlinable\n public __consuming func _copyContents(\n initializing buffer: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {\n return unsafe _copySequenceContents(initializing: buffer)\n }\n\n @_alwaysEmitIntoClient\n internal __consuming func _copySequenceContents(\n initializing buffer: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {\n var it = self.makeIterator()\n guard var ptr = buffer.baseAddress else { return (it, buffer.startIndex) }\n for idx in buffer.indices {\n guard let x = it.next() else {\n return (it, idx)\n }\n unsafe ptr.initialize(to: x)\n unsafe ptr += 1\n }\n return (it, buffer.endIndex)\n }\n \n @inlinable\n @safe\n public func withContiguousStorageIfAvailable<R>(\n _ body: (UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n return nil\n } \n}\n\n// FIXME(ABI)#182\n// Pending <rdar://problem/14011860> and <rdar://problem/14396120>,\n// pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness"\n/// A sequence built around an iterator of type `Base`.\n///\n/// Useful mostly to recover the ability to use `for`...`in`,\n/// given just an iterator `i`:\n///\n/// for x in IteratorSequence(i) { ... }\n@frozen\npublic struct IteratorSequence<Base: IteratorProtocol> {\n @usableFromInline\n internal var _base: Base\n\n /// Creates an instance whose iterator is a copy of `base`.\n @inlinable\n public init(_ base: Base) {\n _base = base\n }\n}\n\nextension IteratorSequence: IteratorProtocol, Sequence {\n\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\n public mutating func next() -> Base.Element? {\n return _base.next()\n }\n}\n\nextension IteratorSequence: Sendable where Base: Sendable { }\n\n/* FIXME: ideally for compatibility we would declare\nextension Sequence {\n @available(swift, deprecated: 5, message: "")\n public typealias SubSequence = AnySequence<Element>\n}\n*/\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Sequence.swift
cpp_apple_swift_stdlib_public_core_Sequence.swift
Swift
48,806
0.95
0.091468
0.662007
react-lib
634
2025-04-19T05:46:16.935092
GPL-3.0
false
7f99403e7bf8f0e8ba128937a82ca639
//===--- SequenceAlgorithms.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//===----------------------------------------------------------------------===//\n// enumerated()\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns a sequence of pairs (*n*, *x*), where *n* represents a\n /// consecutive integer starting at zero and *x* represents an element of\n /// the sequence.\n ///\n /// This example enumerates the characters of the string "Swift" and prints\n /// each character along with its place in the string.\n ///\n /// for (n, c) in "Swift".enumerated() {\n /// print("\(n): '\(c)'")\n /// }\n /// // Prints "0: 'S'"\n /// // Prints "1: 'w'"\n /// // Prints "2: 'i'"\n /// // Prints "3: 'f'"\n /// // Prints "4: 't'"\n ///\n /// When you enumerate a collection, the integer part of each pair is a counter\n /// for the enumeration, but is not necessarily the index of the paired value.\n /// These counters can be used as indices only in instances of zero-based,\n /// integer-indexed collections, such as `Array` and `ContiguousArray`. For\n /// other collections the counters may be out of range or of the wrong type\n /// to use as an index. To iterate over the elements of a collection with its\n /// indices, use the `zip(_:_:)` function.\n ///\n /// This example iterates over the indices and elements of a set, building a\n /// list consisting of indices of names with five or fewer letters.\n ///\n /// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]\n /// var shorterIndices: [Set<String>.Index] = []\n /// for (i, name) in zip(names.indices, names) {\n /// if name.count <= 5 {\n /// shorterIndices.append(i)\n /// }\n /// }\n ///\n /// Now that the `shorterIndices` array holds the indices of the shorter\n /// names in the `names` set, you can use those indices to access elements in\n /// the set.\n ///\n /// for i in shorterIndices {\n /// print(names[i])\n /// }\n /// // Prints "Sofia"\n /// // Prints "Mateo"\n ///\n /// - Returns: A sequence of pairs enumerating the sequence.\n ///\n /// - Complexity: O(1)\n @inlinable // protocol-only\n public func enumerated() -> EnumeratedSequence<Self> {\n return EnumeratedSequence(_base: self)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// min(), max()\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns the minimum element in the sequence, using the given predicate as\n /// the comparison between elements.\n ///\n /// The predicate must be a *strict weak ordering* over the elements. That\n /// is, for any elements `a`, `b`, and `c`, the following conditions must\n /// hold:\n ///\n /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)\n /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are\n /// both `true`, then `areInIncreasingOrder(a, c)` is also\n /// `true`. (Transitive comparability)\n /// - Two elements are *incomparable* if neither is ordered before the other\n /// according to the predicate. If `a` and `b` are incomparable, and `b`\n /// and `c` are incomparable, then `a` and `c` are also incomparable.\n /// (Transitive incomparability)\n ///\n /// This example shows how to use the `min(by:)` method on a\n /// dictionary to find the key-value pair with the lowest value.\n ///\n /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]\n /// let leastHue = hues.min { a, b in a.value < b.value }\n /// print(leastHue)\n /// // Prints "Optional((key: "Coral", value: 16))"\n ///\n /// - Parameter areInIncreasingOrder: A predicate that returns `true`\n /// if its first argument should be ordered before its second\n /// argument; otherwise, `false`.\n /// - Returns: The sequence's minimum element, according to\n /// `areInIncreasingOrder`. If the sequence has no elements, returns\n /// `nil`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable // protocol-only\n @warn_unqualified_access\n public func min(\n by areInIncreasingOrder: (Element, Element) throws -> Bool\n ) rethrows -> Element? {\n var it = makeIterator()\n guard var result = it.next() else { return nil }\n while let e = it.next() {\n if try areInIncreasingOrder(e, result) { result = e }\n }\n return result\n }\n\n /// Returns the maximum element in the sequence, using the given predicate\n /// as the comparison between elements.\n ///\n /// The predicate must be a *strict weak ordering* over the elements. That\n /// is, for any elements `a`, `b`, and `c`, the following conditions must\n /// hold:\n ///\n /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)\n /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are\n /// both `true`, then `areInIncreasingOrder(a, c)` is also\n /// `true`. (Transitive comparability)\n /// - Two elements are *incomparable* if neither is ordered before the other\n /// according to the predicate. If `a` and `b` are incomparable, and `b`\n /// and `c` are incomparable, then `a` and `c` are also incomparable.\n /// (Transitive incomparability)\n ///\n /// This example shows how to use the `max(by:)` method on a\n /// dictionary to find the key-value pair with the highest value.\n ///\n /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]\n /// let greatestHue = hues.max { a, b in a.value < b.value }\n /// print(greatestHue)\n /// // Prints "Optional((key: "Heliotrope", value: 296))"\n ///\n /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its\n /// first argument should be ordered before its second argument;\n /// otherwise, `false`.\n /// - Returns: The sequence's maximum element if the sequence is not empty;\n /// otherwise, `nil`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable // protocol-only\n @warn_unqualified_access\n public func max(\n by areInIncreasingOrder: (Element, Element) throws -> Bool\n ) rethrows -> Element? {\n var it = makeIterator()\n guard var result = it.next() else { return nil }\n while let e = it.next() {\n if try areInIncreasingOrder(result, e) { result = e }\n }\n return result\n }\n}\n\nextension Sequence where Element: Comparable {\n /// Returns the minimum element in the sequence.\n ///\n /// This example finds the smallest value in an array of height measurements.\n ///\n /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]\n /// let lowestHeight = heights.min()\n /// print(lowestHeight)\n /// // Prints "Optional(58.5)"\n ///\n /// - Returns: The sequence's minimum element. If the sequence has no\n /// elements, returns `nil`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n @warn_unqualified_access\n public func min() -> Element? {\n return self.min(by: <)\n }\n\n /// Returns the maximum element in the sequence.\n ///\n /// This example finds the largest value in an array of height measurements.\n ///\n /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]\n /// let greatestHeight = heights.max()\n /// print(greatestHeight)\n /// // Prints "Optional(67.5)"\n ///\n /// - Returns: The sequence's maximum element. If the sequence has no\n /// elements, returns `nil`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n @warn_unqualified_access\n public func max() -> Element? {\n return self.max(by: <)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// starts(with:)\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns a Boolean value indicating whether the initial elements of the\n /// sequence are equivalent to the elements in another sequence, using\n /// the given predicate as the equivalence test.\n ///\n /// The predicate must be an *equivalence relation* over the elements. That\n /// is, for any elements `a`, `b`, and `c`, the following conditions must\n /// hold:\n ///\n /// - `areEquivalent(a, a)` is always `true`. (Reflexivity)\n /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)\n /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then\n /// `areEquivalent(a, c)` is also `true`. (Transitivity)\n ///\n /// - Parameters:\n /// - possiblePrefix: A sequence to compare to this sequence.\n /// - areEquivalent: A predicate that returns `true` if its two arguments\n /// are equivalent; otherwise, `false`.\n /// - Returns: `true` if the initial elements of the sequence are equivalent\n /// to the elements of `possiblePrefix`; otherwise, `false`. If\n /// `possiblePrefix` has no elements, the return value is `true`.\n ///\n /// - Complexity: O(*m*), where *m* is the lesser of the length of the\n /// sequence and the length of `possiblePrefix`.\n @inlinable\n public func starts<PossiblePrefix: Sequence>(\n with possiblePrefix: PossiblePrefix,\n by areEquivalent: (Element, PossiblePrefix.Element) throws -> Bool\n ) rethrows -> Bool {\n var possiblePrefixIterator = possiblePrefix.makeIterator()\n for e0 in self {\n if let e1 = possiblePrefixIterator.next() {\n if try !areEquivalent(e0, e1) {\n return false\n }\n }\n else {\n return true\n }\n }\n return possiblePrefixIterator.next() == nil\n }\n}\n\nextension Sequence where Element: Equatable {\n /// Returns a Boolean value indicating whether the initial elements of the\n /// sequence are the same as the elements in another sequence.\n ///\n /// This example tests whether one countable range begins with the elements\n /// of another countable range.\n ///\n /// let a = 1...3\n /// let b = 1...10\n ///\n /// print(b.starts(with: a))\n /// // Prints "true"\n ///\n /// Passing a sequence with no elements or an empty collection as\n /// `possiblePrefix` always results in `true`.\n ///\n /// print(b.starts(with: []))\n /// // Prints "true"\n ///\n /// - Parameter possiblePrefix: A sequence to compare to this sequence.\n /// - Returns: `true` if the initial elements of the sequence are the same as\n /// the elements of `possiblePrefix`; otherwise, `false`. If\n /// `possiblePrefix` has no elements, the return value is `true`.\n ///\n /// - Complexity: O(*m*), where *m* is the lesser of the length of the\n /// sequence and the length of `possiblePrefix`.\n @inlinable\n public func starts<PossiblePrefix: Sequence>(\n with possiblePrefix: PossiblePrefix\n ) -> Bool where PossiblePrefix.Element == Element {\n return self.starts(with: possiblePrefix, by: ==)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// elementsEqual()\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns a Boolean value indicating whether this sequence and another\n /// sequence contain equivalent elements in the same order, using the given\n /// predicate as the equivalence test.\n ///\n /// At least one of the sequences must be finite.\n ///\n /// The predicate must be an *equivalence relation* over the elements. That\n /// is, for any elements `a`, `b`, and `c`, the following conditions must\n /// hold:\n ///\n /// - `areEquivalent(a, a)` is always `true`. (Reflexivity)\n /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)\n /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then\n /// `areEquivalent(a, c)` is also `true`. (Transitivity)\n ///\n /// - Parameters:\n /// - other: A sequence to compare to this sequence.\n /// - areEquivalent: A predicate that returns `true` if its two arguments\n /// are equivalent; otherwise, `false`.\n /// - Returns: `true` if this sequence and `other` contain equivalent items,\n /// using `areEquivalent` as the equivalence test; otherwise, `false.`\n ///\n /// - Complexity: O(*m*), where *m* is the lesser of the length of the\n /// sequence and the length of `other`.\n @inlinable\n public func elementsEqual<OtherSequence: Sequence>(\n _ other: OtherSequence,\n by areEquivalent: (Element, OtherSequence.Element) throws -> Bool\n ) rethrows -> Bool {\n var iter1 = self.makeIterator()\n var iter2 = other.makeIterator()\n while true {\n switch (iter1.next(), iter2.next()) {\n case let (e1?, e2?):\n if try !areEquivalent(e1, e2) {\n return false\n }\n case (_?, nil), (nil, _?): return false\n case (nil, nil): return true\n }\n }\n fatalError()\n }\n}\n\nextension Sequence where Element: Equatable {\n /// Returns a Boolean value indicating whether this sequence and another\n /// sequence contain the same elements in the same order.\n ///\n /// At least one of the sequences must be finite.\n ///\n /// This example tests whether one countable range shares the same elements\n /// as another countable range and an array.\n ///\n /// let a = 1...3\n /// let b = 1...10\n ///\n /// print(a.elementsEqual(b))\n /// // Prints "false"\n /// print(a.elementsEqual([1, 2, 3]))\n /// // Prints "true"\n ///\n /// - Parameter other: A sequence to compare to this sequence.\n /// - Returns: `true` if this sequence and `other` contain the same elements\n /// in the same order.\n ///\n /// - Complexity: O(*m*), where *m* is the lesser of the length of the\n /// sequence and the length of `other`.\n @inlinable\n public func elementsEqual<OtherSequence: Sequence>(\n _ other: OtherSequence\n ) -> Bool where OtherSequence.Element == Element {\n return self.elementsEqual(other, by: ==)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// lexicographicallyPrecedes()\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns a Boolean value indicating whether the sequence precedes another\n /// sequence in a lexicographical (dictionary) ordering, using the given\n /// predicate to compare elements.\n ///\n /// The predicate must be a *strict weak ordering* over the elements. That\n /// is, for any elements `a`, `b`, and `c`, the following conditions must\n /// hold:\n ///\n /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)\n /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are\n /// both `true`, then `areInIncreasingOrder(a, c)` is also\n /// `true`. (Transitive comparability)\n /// - Two elements are *incomparable* if neither is ordered before the other\n /// according to the predicate. If `a` and `b` are incomparable, and `b`\n /// and `c` are incomparable, then `a` and `c` are also incomparable.\n /// (Transitive incomparability)\n ///\n /// - Parameters:\n /// - other: A sequence to compare to this sequence.\n /// - areInIncreasingOrder: A predicate that returns `true` if its first\n /// argument should be ordered before its second argument; otherwise,\n /// `false`.\n /// - Returns: `true` if this sequence precedes `other` in a dictionary\n /// ordering as ordered by `areInIncreasingOrder`; otherwise, `false`.\n ///\n /// - Note: This method implements the mathematical notion of lexicographical\n /// ordering, which has no connection to Unicode. If you are sorting\n /// strings to present to the end user, use `String` APIs that perform\n /// localized comparison instead.\n ///\n /// - Complexity: O(*m*), where *m* is the lesser of the length of the\n /// sequence and the length of `other`.\n @inlinable\n public func lexicographicallyPrecedes<OtherSequence: Sequence>(\n _ other: OtherSequence,\n by areInIncreasingOrder: (Element, Element) throws -> Bool\n ) rethrows -> Bool\n where OtherSequence.Element == Element {\n var iter1 = self.makeIterator()\n var iter2 = other.makeIterator()\n while true {\n guard let e1 = iter1.next() else {\n return iter2.next() != nil\n }\n guard let e2 = iter2.next() else {\n return false\n }\n if try areInIncreasingOrder(e1, e2) {\n return true\n }\n if try areInIncreasingOrder(e2, e1) {\n return false\n }\n }\n fatalError()\n }\n}\n\nextension Sequence where Element: Comparable {\n /// Returns a Boolean value indicating whether the sequence precedes another\n /// sequence in a lexicographical (dictionary) ordering, using the\n /// less-than operator (`<`) to compare elements.\n ///\n /// This example uses the `lexicographicallyPrecedes` method to test which\n /// array of integers comes first in a lexicographical ordering.\n ///\n /// let a = [1, 2, 2, 2]\n /// let b = [1, 2, 3, 4]\n ///\n /// print(a.lexicographicallyPrecedes(b))\n /// // Prints "true"\n /// print(b.lexicographicallyPrecedes(b))\n /// // Prints "false"\n ///\n /// - Parameter other: A sequence to compare to this sequence.\n /// - Returns: `true` if this sequence precedes `other` in a dictionary\n /// ordering; otherwise, `false`.\n ///\n /// - Note: This method implements the mathematical notion of lexicographical\n /// ordering, which has no connection to Unicode. If you are sorting\n /// strings to present to the end user, use `String` APIs that\n /// perform localized comparison.\n ///\n /// - Complexity: O(*m*), where *m* is the lesser of the length of the\n /// sequence and the length of `other`.\n @inlinable\n public func lexicographicallyPrecedes<OtherSequence: Sequence>(\n _ other: OtherSequence\n ) -> Bool where OtherSequence.Element == Element {\n return self.lexicographicallyPrecedes(other, by: <)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// contains()\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns a Boolean value indicating whether the sequence contains an\n /// element that satisfies the given predicate.\n ///\n /// You can use the predicate to check for an element of a type that\n /// doesn't conform to the `Equatable` protocol, such as the\n /// `HTTPResponse` enumeration in this example.\n ///\n /// enum HTTPResponse {\n /// case ok\n /// case error(Int)\n /// }\n ///\n /// let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]\n /// let hadError = lastThreeResponses.contains { element in\n /// if case .error = element {\n /// return true\n /// } else {\n /// return false\n /// }\n /// }\n /// // 'hadError' == true\n ///\n /// Alternatively, a predicate can be satisfied by a range of `Equatable`\n /// elements or a general condition. This example shows how you can check an\n /// array for an expense greater than $100.\n ///\n /// let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]\n /// let hasBigPurchase = expenses.contains { $0 > 100 }\n /// // 'hasBigPurchase' == true\n ///\n /// - Parameter predicate: A closure that takes an element of the sequence\n /// as its argument and returns a Boolean value that indicates whether\n /// the passed element represents a match.\n /// - Returns: `true` if the sequence contains an element that satisfies\n /// `predicate`; otherwise, `false`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func contains(\n where predicate: (Element) throws -> Bool\n ) rethrows -> Bool {\n for e in self {\n if try predicate(e) {\n return true\n }\n }\n return false\n }\n\n /// Returns a Boolean value indicating whether every element of a sequence\n /// satisfies a given predicate.\n ///\n /// The following code uses this method to test whether all the names in an\n /// array have at least five characters:\n ///\n /// let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]\n /// let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 })\n /// // allHaveAtLeastFive == true\n ///\n /// If the sequence is empty, this method returns `true`.\n ///\n /// - Parameter predicate: A closure that takes an element of the sequence\n /// as its argument and returns a Boolean value that indicates whether\n /// the passed element satisfies a condition.\n /// - Returns: `true` if the sequence contains only elements that satisfy\n /// `predicate`; otherwise, `false`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func allSatisfy(\n _ predicate: (Element) throws -> Bool\n ) rethrows -> Bool {\n return try !contains { try !predicate($0) }\n }\n}\n\nextension Sequence where Element: Equatable {\n /// Returns a Boolean value indicating whether the sequence contains the\n /// given element.\n ///\n /// This example checks to see whether a favorite actor is in an array\n /// storing a movie's cast.\n ///\n /// let cast = ["Vivien", "Marlon", "Kim", "Karl"]\n /// print(cast.contains("Marlon"))\n /// // Prints "true"\n /// print(cast.contains("James"))\n /// // Prints "false"\n ///\n /// - Parameter element: The element to find in the sequence.\n /// - Returns: `true` if the element was found in the sequence; otherwise,\n /// `false`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func contains(_ element: Element) -> Bool {\n if let result = _customContainsEquatableElement(element) {\n return result\n } else {\n return self.contains { $0 == element }\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// count(where:)\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns the number of elements in the sequence that satisfy the given\n /// predicate.\n ///\n /// You can use this method to count the number of elements that pass a test.\n /// The following example finds the number of names that are fewer than\n /// five characters long:\n ///\n /// let names = ["Jacqueline", "Ian", "Amy", "Juan", "Soroush", "Tiffany"]\n /// let shortNameCount = names.count(where: { $0.count < 5 })\n /// // shortNameCount == 3\n ///\n /// To find the number of times a specific element appears in the sequence,\n /// use the equal to operator (`==`) in the closure to test for a match.\n ///\n /// let birds = ["duck", "duck", "duck", "duck", "goose"]\n /// let duckCount = birds.count(where: { $0 == "duck" })\n /// // duckCount == 4\n ///\n /// The sequence must be finite.\n ///\n /// - Parameter predicate: A closure that takes each element of the sequence\n /// as its argument and returns a Boolean value indicating whether\n /// the element should be included in the count.\n /// - Returns: The number of elements in the sequence that satisfy the given\n /// predicate.\n @_alwaysEmitIntoClient\n public func count<E>(\n where predicate: (Element) throws(E) -> Bool\n ) throws(E) -> Int {\n var count = 0\n for e in self {\n count += try predicate(e) ? 1 : 0\n }\n return count\n }\n}\n\n//===----------------------------------------------------------------------===//\n// reduce()\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns the result of combining the elements of the sequence using the\n /// given closure.\n ///\n /// Use the `reduce(_:_:)` method to produce a single value from the elements\n /// of an entire sequence. For example, you can use this method on an array\n /// of numbers to find their sum or product.\n ///\n /// The `nextPartialResult` closure is called sequentially with an\n /// accumulating value initialized to `initialResult` and each element of\n /// the sequence. This example shows how to find the sum of an array of\n /// numbers.\n ///\n /// let numbers = [1, 2, 3, 4]\n /// let numberSum = numbers.reduce(0, { x, y in\n /// x + y\n /// })\n /// // numberSum == 10\n ///\n /// When `numbers.reduce(_:_:)` is called, the following steps occur:\n ///\n /// 1. The `nextPartialResult` closure is called with `initialResult`---`0`\n /// in this case---and the first element of `numbers`, returning the sum:\n /// `1`.\n /// 2. The closure is called again repeatedly with the previous call's return\n /// value and each element of the sequence.\n /// 3. When the sequence is exhausted, the last value returned from the\n /// closure is returned to the caller.\n ///\n /// If the sequence has no elements, `nextPartialResult` is never executed\n /// and `initialResult` is the result of the call to `reduce(_:_:)`.\n ///\n /// - Parameters:\n /// - initialResult: The value to use as the initial accumulating value.\n /// `initialResult` is passed to `nextPartialResult` the first time the\n /// closure is executed.\n /// - nextPartialResult: A closure that combines an accumulating value and\n /// an element of the sequence into a new accumulating value, to be used\n /// in the next call of the `nextPartialResult` closure or returned to\n /// the caller.\n /// - Returns: The final accumulated value. If the sequence has no elements,\n /// the result is `initialResult`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func reduce<Result>(\n _ initialResult: Result,\n _ nextPartialResult:\n (_ partialResult: Result, Element) throws -> Result\n ) rethrows -> Result {\n var accumulator = initialResult\n for element in self {\n accumulator = try nextPartialResult(accumulator, element)\n }\n return accumulator\n }\n\n /// Returns the result of combining the elements of the sequence using the\n /// given closure.\n ///\n /// Use the `reduce(into:_:)` method to produce a single value from the\n /// elements of an entire sequence. For example, you can use this method on an\n /// array of integers to filter adjacent equal entries or count frequencies.\n ///\n /// This method is preferred over `reduce(_:_:)` for efficiency when the\n /// result is a copy-on-write type, for example an Array or a Dictionary.\n ///\n /// The `updateAccumulatingResult` closure is called sequentially with a\n /// mutable accumulating value initialized to `initialResult` and each element\n /// of the sequence. This example shows how to build a dictionary of letter\n /// frequencies of a string.\n ///\n /// let letters = "abracadabra"\n /// let letterCount = letters.reduce(into: [:]) { counts, letter in\n /// counts[letter, default: 0] += 1\n /// }\n /// // letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]\n ///\n /// When `letters.reduce(into:_:)` is called, the following steps occur:\n ///\n /// 1. The `updateAccumulatingResult` closure is called with the initial\n /// accumulating value---`[:]` in this case---and the first character of\n /// `letters`, modifying the accumulating value by setting `1` for the key\n /// `"a"`.\n /// 2. The closure is called again repeatedly with the updated accumulating\n /// value and each element of the sequence.\n /// 3. When the sequence is exhausted, the accumulating value is returned to\n /// the caller.\n ///\n /// If the sequence has no elements, `updateAccumulatingResult` is never\n /// executed and `initialResult` is the result of the call to\n /// `reduce(into:_:)`.\n ///\n /// - Parameters:\n /// - initialResult: The value to use as the initial accumulating value.\n /// - updateAccumulatingResult: A closure that updates the accumulating\n /// value with an element of the sequence.\n /// - Returns: The final accumulated value. If the sequence has no elements,\n /// the result is `initialResult`.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public func reduce<Result>(\n into initialResult: __owned Result,\n _ updateAccumulatingResult:\n (_ partialResult: inout Result, Element) throws -> ()\n ) rethrows -> Result {\n var accumulator = initialResult\n for element in self {\n try updateAccumulatingResult(&accumulator, element)\n }\n return accumulator\n }\n}\n\n//===----------------------------------------------------------------------===//\n// reversed()\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns an array containing the elements of this sequence in reverse\n /// order.\n ///\n /// The sequence must be finite.\n ///\n /// - Returns: An array containing the elements of this sequence in\n /// reverse order.\n ///\n /// - Complexity: O(*n*), where *n* is the length of the sequence.\n @inlinable\n public __consuming func reversed() -> [Element] {\n // FIXME(performance): optimize to 1 pass? But Array(self) can be\n // optimized to a memcpy() sometimes. Those cases are usually collections,\n // though.\n var result = Array(self)\n let count = result.count\n for i in 0..<count/2 {\n result.swapAt(i, count - ((i + 1) as Int))\n }\n return result\n }\n}\n\n//===----------------------------------------------------------------------===//\n// flatMap()\n//===----------------------------------------------------------------------===//\n\nextension Sequence {\n /// Returns an array containing the concatenated results of calling the\n /// given transformation with each element of this sequence.\n ///\n /// Use this method to receive a single-level collection when your\n /// transformation produces a sequence or collection for each element.\n ///\n /// In this example, note the difference in the result of using `map` and\n /// `flatMap` with a transformation that returns an array.\n ///\n /// let numbers = [1, 2, 3, 4]\n ///\n /// let mapped = numbers.map { Array(repeating: $0, count: $0) }\n /// // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]\n ///\n /// let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }\n /// // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]\n ///\n /// In fact, `s.flatMap(transform)` is equivalent to\n /// `Array(s.map(transform).joined())`.\n ///\n /// - Parameter transform: A closure that accepts an element of this\n /// sequence as its argument and returns a sequence or collection.\n /// - Returns: The resulting flattened array.\n ///\n /// - Complexity: O(*m* + *n*), where *n* is the length of this sequence\n /// and *m* is the length of the result.\n @inlinable\n public func flatMap<SegmentOfResult: Sequence>(\n _ transform: (Element) throws -> SegmentOfResult\n ) rethrows -> [SegmentOfResult.Element] {\n var result: [SegmentOfResult.Element] = []\n for element in self {\n result.append(contentsOf: try transform(element))\n }\n return result\n }\n}\n\nextension Sequence {\n /// Returns an array containing the non-`nil` results of calling the given\n /// transformation with each element of this sequence.\n ///\n /// Use this method to receive an array of non-optional values when your\n /// transformation produces an optional value.\n ///\n /// In this example, note the difference in the result of using `map` and\n /// `compactMap` with a transformation that returns an optional `Int` value.\n ///\n /// let possibleNumbers = ["1", "2", "three", "///4///", "5"]\n ///\n /// let mapped: [Int?] = possibleNumbers.map { str in Int(str) }\n /// // [1, 2, nil, nil, 5]\n ///\n /// let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }\n /// // [1, 2, 5]\n ///\n /// - Parameter transform: A closure that accepts an element of this\n /// sequence as its argument and returns an optional value.\n /// - Returns: An array of the non-`nil` results of calling `transform`\n /// with each element of the sequence.\n ///\n /// - Complexity: O(*n*), where *n* is the length of this sequence.\n @inlinable // protocol-only\n public func compactMap<ElementOfResult>(\n _ transform: (Element) throws -> ElementOfResult?\n ) rethrows -> [ElementOfResult] {\n return try _compactMap(transform)\n }\n\n // The implementation of compactMap accepting a closure with an optional result.\n // Factored out into a separate function in order to be used in multiple\n // overloads.\n @inlinable // protocol-only\n @inline(__always)\n public func _compactMap<ElementOfResult>(\n _ transform: (Element) throws -> ElementOfResult?\n ) rethrows -> [ElementOfResult] {\n var result: [ElementOfResult] = []\n for element in self {\n if let newElement = try transform(element) {\n result.append(newElement)\n }\n }\n return result\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_SequenceAlgorithms.swift
cpp_apple_swift_stdlib_public_core_SequenceAlgorithms.swift
Swift
33,288
0.95
0.091121
0.701818
node-utils
698
2025-06-07T17:40:32.640764
GPL-3.0
false
d84ffb78e2fa042fa9eb4eedd2b9cd52
//===----------------------------------------------------------------------===//\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/// An unordered collection of unique elements.\n///\n/// You use a set instead of an array when you need to test efficiently for\n/// membership and you aren't concerned with the order of the elements in the\n/// collection, or when you need to ensure that each element appears only once\n/// in a collection.\n///\n/// You can create a set with any element type that conforms to the `Hashable`\n/// protocol. By default, most types in the standard library are hashable,\n/// including strings, numeric and Boolean types, enumeration cases without\n/// associated values, and even sets themselves.\n///\n/// Swift makes it as easy to create a new set as to create a new array. Simply\n/// assign an array literal to a variable or constant with the `Set` type\n/// specified.\n///\n/// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]\n/// if ingredients.contains("sugar") {\n/// print("No thanks, too sweet.")\n/// }\n/// // Prints "No thanks, too sweet."\n///\n/// Set Operations\n/// ==============\n///\n/// Sets provide a suite of mathematical set operations. For example, you can\n/// efficiently test a set for membership of an element or check its\n/// intersection with another set:\n///\n/// - Use the `contains(_:)` method to test whether a set contains a specific\n/// element.\n/// - Use the "equal to" operator (`==`) to test whether two sets contain the\n/// same elements.\n/// - Use the `isSubset(of:)` method to test whether a set contains all the\n/// elements of another set or sequence.\n/// - Use the `isSuperset(of:)` method to test whether all elements of a set\n/// are contained in another set or sequence.\n/// - Use the `isStrictSubset(of:)` and `isStrictSuperset(of:)` methods to test\n/// whether a set is a subset or superset of, but not equal to, another set.\n/// - Use the `isDisjoint(with:)` method to test whether a set has any elements\n/// in common with another set.\n///\n/// You can also combine, exclude, or subtract the elements of two sets:\n///\n/// - Use the `union(_:)` method to create a new set with the elements of a set\n/// and another set or sequence.\n/// - Use the `intersection(_:)` method to create a new set with only the\n/// elements common to a set and another set or sequence.\n/// - Use the `symmetricDifference(_:)` method to create a new set with the\n/// elements that are in either a set or another set or sequence, but not in\n/// both.\n/// - Use the `subtracting(_:)` method to create a new set with the elements of\n/// a set that are not also in another set or sequence.\n///\n/// You can modify a set in place by using these methods' mutating\n/// counterparts: `formUnion(_:)`, `formIntersection(_:)`,\n/// `formSymmetricDifference(_:)`, and `subtract(_:)`.\n///\n/// Set operations are not limited to use with other sets. Instead, you can\n/// perform set operations with another set, an array, or any other sequence\n/// type.\n///\n/// var primes: Set = [2, 3, 5, 7]\n///\n/// // Tests whether primes is a subset of a Range<Int>\n/// print(primes.isSubset(of: 0..<10))\n/// // Prints "true"\n///\n/// // Performs an intersection with an Array<Int>\n/// let favoriteNumbers = [5, 7, 15, 21]\n/// print(primes.intersection(favoriteNumbers))\n/// // Prints "[5, 7]"\n///\n/// Sequence and Collection Operations\n/// ==================================\n///\n/// In addition to the `Set` type's set operations, you can use any nonmutating\n/// sequence or collection methods with a set.\n///\n/// if primes.isEmpty {\n/// print("No primes!")\n/// } else {\n/// print("We have \(primes.count) primes.")\n/// }\n/// // Prints "We have 4 primes."\n///\n/// let primesSum = primes.reduce(0, +)\n/// // 'primesSum' == 17\n///\n/// let primeStrings = primes.sorted().map(String.init)\n/// // 'primeStrings' == ["2", "3", "5", "7"]\n///\n/// You can iterate through a set's unordered elements with a `for`-`in` loop.\n///\n/// for number in primes {\n/// print(number)\n/// }\n/// // Prints "5"\n/// // Prints "7"\n/// // Prints "2"\n/// // Prints "3"\n///\n/// Many sequence and collection operations return an array or a type-erasing\n/// collection wrapper instead of a set. To restore efficient set operations,\n/// create a new set from the result.\n///\n/// let primesStrings = primes.map(String.init)\n/// // 'primesStrings' is of type Array<String>\n/// let primesStringsSet = Set(primes.map(String.init))\n/// // 'primesStringsSet' is of type Set<String>\n///\n/// Bridging Between Set and NSSet\n/// ==============================\n///\n/// You can bridge between `Set` and `NSSet` using the `as` operator. For\n/// bridging to be possible, the `Element` type of a set must be a class, an\n/// `@objc` protocol (a protocol imported from Objective-C or marked with the\n/// `@objc` attribute), or a type that bridges to a Foundation type.\n///\n/// Bridging from `Set` to `NSSet` always takes O(1) time and space. When the\n/// set's `Element` type is neither a class nor an `@objc` protocol, any\n/// required bridging of elements occurs at the first access of each element,\n/// so the first operation that uses the contents of the set (for example, a\n/// membership test) can take O(*n*).\n///\n/// Bridging from `NSSet` to `Set` first calls the `copy(with:)` method\n/// (`- copyWithZone:` in Objective-C) on the set to get an immutable copy and\n/// then performs additional Swift bookkeeping work that takes O(1) time. For\n/// instances of `NSSet` that are already immutable, `copy(with:)` returns the\n/// same set in constant time; otherwise, the copying performance is\n/// unspecified. The instances of `NSSet` and `Set` share buffer using the\n/// same copy-on-write optimization that is used when two instances of `Set`\n/// share buffer.\n@frozen\n@_eagerMove\npublic struct Set<Element: Hashable> {\n @usableFromInline\n internal var _variant: _Variant\n\n /// Creates an empty set with preallocated space for at least the specified\n /// number of elements.\n ///\n /// Use this initializer to avoid intermediate reallocations of a set's\n /// storage buffer when you know how many elements you'll insert into the set\n /// after creation.\n ///\n /// - Parameter minimumCapacity: The minimum number of elements that the\n /// newly created set should be able to store without reallocating its\n /// storage buffer.\n public // FIXME(reserveCapacity): Should be inlinable\n init(minimumCapacity: Int) {\n _variant = _Variant(native: _NativeSet(capacity: minimumCapacity))\n }\n\n /// Private initializer.\n @inlinable\n internal init(_native: __owned _NativeSet<Element>) {\n _variant = _Variant(native: _native)\n }\n\n#if _runtime(_ObjC)\n @inlinable\n internal init(_cocoa: __owned __CocoaSet) {\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 `NSSet` is immutable;\n /// * `Element` is bridged verbatim to Objective-C (i.e.,\n /// is a reference type).\n @inlinable\n public // SPI(Foundation)\n init(_immutableCocoaSet: __owned AnyObject) {\n _internalInvariant(_isBridgedVerbatimToObjectiveC(Element.self),\n "Set can be backed by NSSet _variant only when the member type can be bridged verbatim to Objective-C")\n self.init(_cocoa: __CocoaSet(_immutableCocoaSet))\n }\n#endif\n}\n\nextension Set: ExpressibleByArrayLiteral {\n /// Creates a set containing the elements of 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 set using an array\n /// literal as its value by enclosing a comma-separated list of values in\n /// square brackets. You can use an array literal anywhere a set is expected\n /// by the type context.\n ///\n /// Here, a set of strings is created from an array literal holding only\n /// strings.\n ///\n /// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]\n /// if ingredients.isSuperset(of: ["sugar", "salt"]) {\n /// print("Whatever it is, it's bound to be delicious!")\n /// }\n /// // Prints "Whatever it is, it's bound to be delicious!"\n ///\n /// - Parameter elements: A variadic list of elements of the new set.\n @inlinable\n @inline(__always)\n public init(arrayLiteral elements: Element...) {\n if elements.isEmpty {\n self.init()\n return\n }\n self.init(_nonEmptyArrayLiteral: elements)\n }\n\n @_alwaysEmitIntoClient\n internal init(_nonEmptyArrayLiteral elements: [Element]) {\n let native = _NativeSet<Element>(capacity: elements.count)\n for element in elements {\n let (bucket, found) = native.find(element)\n if found {\n // FIXME: Shouldn't this trap?\n continue\n }\n unsafe native._unsafeInsertNew(element, at: bucket)\n }\n self.init(_native: native)\n }\n}\n\nextension Set: Sequence {\n /// Returns an iterator over the members of the set.\n @inlinable\n @inline(__always)\n public __consuming func makeIterator() -> Iterator {\n return _variant.makeIterator()\n }\n\n /// Returns a Boolean value that indicates whether the given element exists\n /// in the set.\n ///\n /// This example uses the `contains(_:)` method to test whether an integer is\n /// a member of a set of prime numbers.\n ///\n /// let primes: Set = [2, 3, 5, 7]\n /// let x = 5\n /// if primes.contains(x) {\n /// print("\(x) is prime!")\n /// } else {\n /// print("\(x). Not prime.")\n /// }\n /// // Prints "5 is prime!"\n ///\n /// - Parameter member: An element to look for in the set.\n /// - Returns: `true` if `member` exists in the set; otherwise, `false`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func contains(_ member: Element) -> Bool {\n return _variant.contains(member)\n }\n\n @inlinable\n @inline(__always)\n public func _customContainsEquatableElement(_ member: Element) -> Bool? {\n return contains(member)\n }\n}\n\n// This is not quite Sequence.filter, because that returns [Element], not Self\n// (RangeReplaceableCollection.filter returns Self, but Set isn't an RRC)\nextension Set {\n /// Returns a new set containing the elements of the set that satisfy the\n /// given predicate.\n ///\n /// In this example, `filter(_:)` is used to include only names shorter than\n /// five characters.\n ///\n /// let cast: Set = ["Vivien", "Marlon", "Kim", "Karl"]\n /// let shortNames = cast.filter { $0.count < 5 }\n ///\n /// shortNames.isSubset(of: cast)\n /// // true\n /// shortNames.contains("Vivien")\n /// // false\n ///\n /// - Parameter isIncluded: A closure that takes an element as its argument\n /// and returns a Boolean value indicating whether the element should be\n /// included in the returned set.\n /// - Returns: A set of the elements that `isIncluded` allows.\n @inlinable\n @available(swift, introduced: 4.0)\n public __consuming func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> Set {\n return try Set(_native: _variant.filter(isIncluded))\n }\n}\n\nextension Set: Collection {\n /// The starting position for iterating members of the set.\n ///\n /// If the set is empty, `startIndex` is equal to `endIndex`.\n @inlinable\n public var startIndex: Index {\n return _variant.startIndex\n }\n\n /// The "past the end" position for the set---that is, the position one\n /// greater than the last valid subscript argument.\n ///\n /// If the set is empty, `endIndex` is equal to `startIndex`.\n @inlinable\n public var endIndex: Index {\n return _variant.endIndex\n }\n\n /// Accesses the member at the given position.\n @inlinable\n public subscript(position: Index) -> Element {\n // FIXME(accessors): Provide a _read\n get {\n return _variant.element(at: position)\n }\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 // APINAMING: complexity docs are broadly missing in this file.\n\n /// Returns the index of the given element in the set, or `nil` if the\n /// element is not a member of the set.\n ///\n /// - Parameter member: An element to search for in the set.\n /// - Returns: The index of `member` if it exists in the set; otherwise,\n /// `nil`.\n ///\n /// - Complexity: O(1)\n @inlinable\n public func firstIndex(of member: Element) -> Index? {\n return _variant.index(for: member)\n }\n\n @inlinable\n @inline(__always)\n public func _customIndexOfEquatableElement(\n _ member: Element\n ) -> Index?? {\n return Optional(firstIndex(of: member))\n }\n\n @inlinable\n @inline(__always)\n public func _customLastIndexOfEquatableElement(\n _ member: Element\n ) -> Index?? {\n // The first and last elements are the same because each element is unique.\n return _customIndexOfEquatableElement(member)\n }\n\n /// The number of elements in the set.\n ///\n /// - Complexity: O(1).\n @inlinable\n public var count: Int {\n return _variant.count\n }\n\n /// A Boolean value that indicates whether the set is empty.\n @inlinable\n public var isEmpty: Bool {\n return count == 0\n }\n}\n\n// FIXME: rdar://problem/23549059 (Optimize == for Set)\n// Look into initially trying to compare the two sets by directly comparing the\n// contents of both buffers in order. If they happen to have the exact same\n// ordering we can get the `true` response without ever hashing. If the two\n// buffers' contents differ at all then we have to fall back to hashing the\n// rest of the elements (but we don't need to hash any prefix that did match).\nextension Set: Equatable {\n /// Returns a Boolean value indicating whether two sets have equal elements.\n ///\n /// - Parameters:\n /// - lhs: A set.\n /// - rhs: Another set.\n /// - Returns: `true` if the `lhs` and `rhs` have the same elements; otherwise,\n /// `false`.\n @inlinable\n public static func == (lhs: Set<Element>, rhs: Set<Element>) -> 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 Set: 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 // FIXME(ABI)#177: <rdar://problem/18915294> Cache Set<T> hashValue\n\n // Generate a seed from a snapshot of the hasher. This makes members' hash\n // values depend on the state of the hasher, which improves hashing\n // quality. (E.g., it makes it possible to resolve collisions by passing in\n // a different hasher.)\n var copy = hasher\n let seed = copy._finalize()\n\n var hash = 0\n for member in self {\n hash ^= member._rawHashValue(seed: seed)\n }\n hasher.combine(hash)\n }\n}\n\n@_unavailableInEmbedded\nextension Set: _HasCustomAnyHashableRepresentation {\n public __consuming func _toCustomAnyHashable() -> AnyHashable? {\n return AnyHashable(_box: _SetAnyHashableBox(self))\n }\n}\n\n@_unavailableInEmbedded\ninternal struct _SetAnyHashableBox<Element: Hashable>: _AnyHashableBox {\n internal let _value: Set<Element>\n internal let _canonical: Set<AnyHashable>\n\n internal init(_ value: __owned Set<Element>) {\n self._value = value\n self._canonical = value as Set<AnyHashable>\n }\n\n internal var _base: Any {\n return _value\n }\n\n internal var _canonicalBox: _AnyHashableBox {\n return _SetAnyHashableBox<AnyHashable>(_canonical)\n }\n\n internal func _isEqual(to other: _AnyHashableBox) -> Bool? {\n guard let other = other as? _SetAnyHashableBox<AnyHashable> 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\nextension Set: SetAlgebra {\n\n /// Inserts the given element in the set if it is not already present.\n ///\n /// If an element equal to `newMember` is already contained in the set, this\n /// method has no effect. In the following example, a new element is\n /// inserted into `classDays`, a set of days of the week. When an existing\n /// element is inserted, the `classDays` set does not change.\n ///\n /// enum DayOfTheWeek: Int {\n /// case sunday, monday, tuesday, wednesday, thursday,\n /// friday, saturday\n /// }\n ///\n /// var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]\n /// print(classDays.insert(.monday))\n /// // Prints "(inserted: true, memberAfterInsert: DayOfTheWeek.monday)"\n /// print(classDays)\n /// // Prints "[DayOfTheWeek.friday, DayOfTheWeek.wednesday, DayOfTheWeek.monday]"\n ///\n /// print(classDays.insert(.friday))\n /// // Prints "(inserted: false, memberAfterInsert: DayOfTheWeek.friday)"\n /// print(classDays)\n /// // Prints "[DayOfTheWeek.friday, DayOfTheWeek.wednesday, DayOfTheWeek.monday]"\n ///\n /// - Parameter newMember: An element to insert into the set.\n /// - Returns: `(true, newMember)` if `newMember` was not contained in the\n /// set. If an element equal to `newMember` was already contained in the\n /// set, the method returns `(false, oldMember)`, where `oldMember` is the\n /// element that was equal to `newMember`. In some cases, `oldMember` may\n /// be distinguishable from `newMember` by identity comparison or some\n /// other means.\n @inlinable\n @discardableResult\n public mutating func insert(\n _ newMember: __owned Element\n ) -> (inserted: Bool, memberAfterInsert: Element) {\n return _variant.insert(newMember)\n }\n\n /// Inserts the given element into the set unconditionally.\n ///\n /// If an element equal to `newMember` is already contained in the set,\n /// `newMember` replaces the existing element. In this example, an existing\n /// element is inserted into `classDays`, a set of days of the week.\n ///\n /// enum DayOfTheWeek: Int {\n /// case sunday, monday, tuesday, wednesday, thursday,\n /// friday, saturday\n /// }\n ///\n /// var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday]\n /// print(classDays.update(with: .monday))\n /// // Prints "Optional(DayOfTheWeek.monday)"\n ///\n /// - Parameter newMember: An element to insert into the set.\n /// - Returns: An element equal to `newMember` if the set already contained\n /// such a member; otherwise, `nil`. In some cases, the returned element\n /// may be distinguishable from `newMember` by identity comparison or some\n /// other means.\n @inlinable\n @discardableResult\n public mutating func update(with newMember: __owned Element) -> Element? {\n return _variant.update(with: newMember)\n }\n\n /// Removes the specified element from the set.\n ///\n /// This example removes the element `"sugar"` from a set of ingredients.\n ///\n /// var ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]\n /// let toRemove = "sugar"\n /// if let removed = ingredients.remove(toRemove) {\n /// print("The recipe is now \(removed)-free.")\n /// }\n /// // Prints "The recipe is now sugar-free."\n ///\n /// - Parameter member: The element to remove from the set.\n /// - Returns: The value of the `member` parameter if it was a member of the\n /// set; otherwise, `nil`.\n @inlinable\n @discardableResult\n public mutating func remove(_ member: Element) -> Element? {\n return _variant.remove(member)\n }\n\n /// Removes the element at the given index of the set.\n ///\n /// - Parameter position: The index of the member to remove. `position` must\n /// be a valid index of the set, and must not be equal to the set's end\n /// index.\n /// - Returns: The element that was removed from the set.\n @inlinable\n @discardableResult\n public mutating func remove(at position: Index) -> Element {\n return _variant.remove(at: position)\n }\n\n /// Removes all members from the set.\n ///\n /// - Parameter keepingCapacity: If `true`, the set's buffer capacity is\n /// preserved; if `false`, the underlying buffer is released. The\n /// default is `false`.\n @inlinable\n public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {\n _variant.removeAll(keepingCapacity: keepCapacity)\n }\n\n /// Removes the first element of the set.\n ///\n /// Because a set is not an ordered collection, the "first" element may not\n /// be the first element that was added to the set. The set must not be\n /// empty.\n ///\n /// - Complexity: Amortized O(1) if the set does not wrap a bridged `NSSet`.\n /// If the set wraps a bridged `NSSet`, the performance is unspecified.\n ///\n /// - Returns: A member of the set.\n @inlinable\n @discardableResult\n public mutating func removeFirst() -> Element {\n _precondition(!isEmpty, "Can't removeFirst from an empty Set")\n return remove(at: startIndex)\n }\n\n //\n // APIs below this comment should be implemented strictly in terms of\n // *public* APIs above. `_variant` should not be accessed directly.\n //\n // This separates concerns for testing. Tests for the following APIs need\n // not to concern themselves with testing correctness of behavior of\n // underlying buffer (and different variants of it), only correctness of the\n // API itself.\n //\n\n /// Creates an empty set.\n ///\n /// This is equivalent to initializing with an empty array literal. For\n /// example:\n ///\n /// var emptySet = Set<Int>()\n /// print(emptySet.isEmpty)\n /// // Prints "true"\n ///\n /// emptySet = []\n /// print(emptySet.isEmpty)\n /// // Prints "true"\n @inlinable\n public init() {\n self = Set<Element>(_native: _NativeSet())\n }\n\n /// Creates a new set from a finite sequence of items.\n ///\n /// Use this initializer to create a new set from an existing sequence, for\n /// example, an array or a range.\n ///\n /// let validIndices = Set(0..<7).subtracting([2, 4, 5])\n /// print(validIndices)\n /// // Prints "[6, 0, 1, 3]"\n ///\n /// This initializer can also be used to restore set methods after performing\n /// sequence operations such as `filter(_:)` or `map(_:)` on a set. For\n /// example, after filtering a set of prime numbers to remove any below 10,\n /// you can create a new set by using this initializer.\n ///\n /// let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23]\n /// let laterPrimes = Set(primes.lazy.filter { $0 > 10 })\n /// print(laterPrimes)\n /// // Prints "[17, 19, 23, 11, 13]"\n ///\n /// - Parameter sequence: The elements to use as members of the new set.\n @inlinable\n public init<Source: Sequence>(_ sequence: __owned Source)\n where Source.Element == Element {\n if let s = sequence as? Set<Element> {\n // If this sequence is actually a `Set`, then we can quickly\n // adopt its storage and let COW handle uniquing only if necessary.\n self = s\n } else {\n self.init(minimumCapacity: sequence.underestimatedCount)\n for item in sequence {\n insert(item)\n }\n }\n }\n\n /// Returns a Boolean value that indicates whether the set is a subset of the\n /// given sequence.\n ///\n /// Set *A* is a subset of another set *B* if every member of *A* is also a\n /// member of *B*.\n ///\n /// let employees = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(attendees.isSubset(of: employees))\n /// // Prints "true"\n ///\n /// - Parameter possibleSuperset: A sequence of elements. `possibleSuperset`\n /// must be finite.\n /// - Returns: `true` if the set is a subset of `possibleSuperset`;\n /// otherwise, `false`.\n @inlinable\n public func isSubset<S: Sequence>(of possibleSuperset: S) -> Bool\n where S.Element == Element {\n guard !isEmpty else { return true }\n if self.count == 1 { return possibleSuperset.contains(self.first!) }\n if let s = possibleSuperset as? Set<Element> {\n return isSubset(of: s)\n }\n return _variant.convertedToNative.isSubset(of: possibleSuperset)\n }\n\n /// Returns a Boolean value that indicates whether the set is a strict subset\n /// of the given sequence.\n ///\n /// Set *A* is a strict subset of another set *B* if every member of *A* is\n /// also a member of *B* and *B* contains at least one element that is not a\n /// member of *A*.\n ///\n /// let employees = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(attendees.isStrictSubset(of: employees))\n /// // Prints "true"\n ///\n /// // A set is never a strict subset of itself:\n /// print(attendees.isStrictSubset(of: attendees))\n /// // Prints "false"\n ///\n /// - Parameter possibleStrictSuperset: A sequence of elements.\n /// `possibleStrictSuperset` must be finite.\n /// - Returns: `true` is the set is strict subset of\n /// `possibleStrictSuperset`; otherwise, `false`.\n @inlinable\n public func isStrictSubset<S: Sequence>(of possibleStrictSuperset: S) -> Bool\n where S.Element == Element {\n if let s = possibleStrictSuperset as? Set<Element> {\n return isStrictSubset(of: s)\n }\n return _variant.convertedToNative.isStrictSubset(of: possibleStrictSuperset)\n }\n\n /// Returns a Boolean value that indicates whether the set is a superset of\n /// the given sequence.\n ///\n /// Set *A* is a superset of another set *B* if every member of *B* is also a\n /// member of *A*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees = ["Alicia", "Bethany", "Diana"]\n /// print(employees.isSuperset(of: attendees))\n /// // Prints "true"\n ///\n /// - Parameter possibleSubset: A sequence of elements. `possibleSubset` must\n /// be finite.\n /// - Returns: `true` if the set is a superset of `possibleSubset`;\n /// otherwise, `false`.\n @inlinable\n public func isSuperset<S: Sequence>(of possibleSubset: __owned S) -> Bool\n where S.Element == Element {\n if let s = possibleSubset as? Set<Element> {\n return isSuperset(of: s)\n }\n for member in possibleSubset {\n if !contains(member) {\n return false\n }\n }\n return true\n }\n\n /// Returns a Boolean value that indicates whether the set is a strict\n /// superset of the given sequence.\n ///\n /// Set *A* is a strict superset of another set *B* if every member of *B* is\n /// also a member of *A* and *A* contains at least one element that is *not*\n /// a member of *B*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees = ["Alicia", "Bethany", "Diana"]\n /// print(employees.isStrictSuperset(of: attendees))\n /// // Prints "true"\n /// print(employees.isStrictSuperset(of: employees))\n /// // Prints "false"\n ///\n /// - Parameter possibleStrictSubset: A sequence of elements.\n /// `possibleStrictSubset` must be finite.\n /// - Returns: `true` if the set is a strict superset of\n /// `possibleStrictSubset`; otherwise, `false`.\n @inlinable\n public func isStrictSuperset<S: Sequence>(of possibleStrictSubset: S) -> Bool\n where S.Element == Element {\n if isEmpty { return false }\n if let s = possibleStrictSubset as? Set<Element> {\n return isStrictSuperset(of: s)\n }\n return _variant.convertedToNative.isStrictSuperset(of: possibleStrictSubset)\n }\n\n /// Returns a Boolean value that indicates whether the set has no members in\n /// common with the given sequence.\n ///\n /// In the following example, the `employees` set is disjoint with the\n /// elements of the `visitors` array because no name appears in both.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let visitors = ["Marcia", "Nathaniel", "Olivia"]\n /// print(employees.isDisjoint(with: visitors))\n /// // Prints "true"\n ///\n /// - Parameter other: A sequence of elements. `other` must be finite.\n /// - Returns: `true` if the set has no elements in common with `other`;\n /// otherwise, `false`.\n @inlinable\n public func isDisjoint<S: Sequence>(with other: S) -> Bool\n where S.Element == Element {\n if let s = other as? Set<Element> {\n return isDisjoint(with: s)\n }\n return _isDisjoint(with: other)\n }\n\n /// Returns a new set with the elements of both this set and the given\n /// sequence.\n ///\n /// In the following example, the `attendeesAndVisitors` set is made up\n /// of the elements of the `attendees` set and the `visitors` array:\n ///\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// let visitors = ["Marcia", "Nathaniel"]\n /// let attendeesAndVisitors = attendees.union(visitors)\n /// print(attendeesAndVisitors)\n /// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"\n ///\n /// If the set already contains one or more elements that are also in\n /// `other`, the existing members are kept. If `other` contains multiple\n /// instances of equivalent elements, only the first instance is kept.\n ///\n /// let initialIndices = Set(0..<5)\n /// let expandedIndices = initialIndices.union([2, 3, 6, 6, 7, 7])\n /// print(expandedIndices)\n /// // Prints "[2, 4, 6, 7, 0, 1, 3]"\n ///\n /// - Parameter other: A sequence of elements. `other` must be finite.\n /// - Returns: A new set with the unique elements of this set and `other`.\n @inlinable\n public __consuming func union<S: Sequence>(_ other: __owned S) -> Set<Element>\n where S.Element == Element {\n var newSet = self\n newSet.formUnion(other)\n return newSet\n }\n\n /// Inserts the elements of the given sequence into the set.\n ///\n /// If the set already contains one or more elements that are also in\n /// `other`, the existing members are kept. If `other` contains multiple\n /// instances of equivalent elements, only the first instance is kept.\n ///\n /// var attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// let visitors = ["Diana", "Marcia", "Nathaniel"]\n /// attendees.formUnion(visitors)\n /// print(attendees)\n /// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"\n ///\n /// - Parameter other: A sequence of elements. `other` must be finite.\n @inlinable\n public mutating func formUnion<S: Sequence>(_ other: __owned S)\n where S.Element == Element {\n for item in other {\n insert(item)\n }\n }\n\n /// Returns a new set containing the elements of this set that do not occur\n /// in the given sequence.\n ///\n /// In the following example, the `nonNeighbors` set is made up of the\n /// elements of the `employees` set that are not elements of `neighbors`:\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]\n /// let nonNeighbors = employees.subtracting(neighbors)\n /// print(nonNeighbors)\n /// // Prints "["Chris", "Diana", "Alicia"]"\n ///\n /// - Parameter other: A sequence of elements. `other` must be finite.\n /// - Returns: A new set.\n @inlinable\n public __consuming func subtracting<S: Sequence>(_ other: S) -> Set<Element>\n where S.Element == Element {\n return self._subtracting(other)\n }\n\n @inlinable\n internal __consuming func _subtracting<S: Sequence>(\n _ other: S\n ) -> Set<Element>\n where S.Element == Element {\n return Set(_native: _variant.convertedToNative.subtracting(other))\n }\n\n /// Removes the elements of the given sequence from the set.\n ///\n /// In the following example, the elements of the `employees` set that are\n /// also elements of the `neighbors` array are removed. In particular, the\n /// names `"Bethany"` and `"Eric"` are removed from `employees`.\n ///\n /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]\n /// employees.subtract(neighbors)\n /// print(employees)\n /// // Prints "["Chris", "Diana", "Alicia"]"\n ///\n /// - Parameter other: A sequence of elements. `other` must be finite.\n @inlinable\n public mutating func subtract<S: Sequence>(_ other: S)\n where S.Element == Element {\n _subtract(other)\n }\n\n @inlinable\n internal mutating func _subtract<S: Sequence>(_ other: S)\n where S.Element == Element {\n // If self is empty we don't need to iterate over `other` because there's\n // nothing to remove on self.\n guard !isEmpty else { return }\n\n for item in other {\n remove(item)\n }\n }\n\n /// Returns a new set with the elements that are common to both this set and\n /// the given sequence.\n ///\n /// In the following example, the `bothNeighborsAndEmployees` set is made up\n /// of the elements that are in *both* the `employees` and `neighbors` sets.\n /// Elements that are in only one or the other are left out of the result of\n /// the intersection.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]\n /// let bothNeighborsAndEmployees = employees.intersection(neighbors)\n /// print(bothNeighborsAndEmployees)\n /// // Prints "["Bethany", "Eric"]"\n ///\n /// - Parameter other: A sequence of elements. `other` must be finite.\n /// - Returns: A new set.\n @inlinable\n public __consuming func intersection<S: Sequence>(_ other: S) -> Set<Element>\n where S.Element == Element {\n if let other = other as? Set<Element> {\n return self.intersection(other)\n }\n return Set(_native: _variant.convertedToNative.genericIntersection(other))\n }\n\n /// Removes the elements of the set that aren't also in the given sequence.\n ///\n /// In the following example, the elements of the `employees` set that are\n /// not also members of the `neighbors` set are removed. In particular, the\n /// names `"Alicia"`, `"Chris"`, and `"Diana"` are removed.\n ///\n /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]\n /// employees.formIntersection(neighbors)\n /// print(employees)\n /// // Prints "["Bethany", "Eric"]"\n ///\n /// - Parameter other: A sequence of elements. `other` must be finite.\n @inlinable\n public mutating func formIntersection<S: Sequence>(_ other: S)\n where S.Element == Element {\n // FIXME: This discards storage reserved with reserveCapacity.\n // FIXME: Depending on the ratio of elements kept in the result, it may be\n // faster to do the removals in place, in bulk.\n self = self.intersection(other)\n }\n\n /// Returns a new set with the elements that are either in this set or in the\n /// given sequence, but not in both.\n ///\n /// In the following example, the `eitherNeighborsOrEmployees` set is made up\n /// of the elements of the `employees` and `neighbors` sets that are not in\n /// both `employees` *and* `neighbors`. In particular, the names `"Bethany"`\n /// and `"Eric"` do not appear in `eitherNeighborsOrEmployees`.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]\n /// let neighbors = ["Bethany", "Eric", "Forlani"]\n /// let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors)\n /// print(eitherNeighborsOrEmployees)\n /// // Prints "["Diana", "Forlani", "Alicia"]"\n ///\n /// - Parameter other: A sequence of elements. `other` must be finite.\n /// - Returns: A new set.\n @inlinable\n public __consuming func symmetricDifference<S: Sequence>(\n _ other: __owned S\n ) -> Set<Element>\n where S.Element == Element {\n var newSet = self\n newSet.formSymmetricDifference(other)\n return newSet\n }\n\n /// Replace this set with the elements contained in this set or the given\n /// set, but not both.\n ///\n /// In the following example, the elements of the `employees` set that are\n /// also members of `neighbors` are removed from `employees`, while the\n /// elements of `neighbors` that are not members of `employees` are added to\n /// `employees`. In particular, the names `"Bethany"` and `"Eric"` are\n /// removed from `employees` while the name `"Forlani"` is added.\n ///\n /// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]\n /// let neighbors = ["Bethany", "Eric", "Forlani"]\n /// employees.formSymmetricDifference(neighbors)\n /// print(employees)\n /// // Prints "["Diana", "Forlani", "Alicia"]"\n ///\n /// - Parameter other: A sequence of elements. `other` must be finite.\n @inlinable\n public mutating func formSymmetricDifference<S: Sequence>(\n _ other: __owned S)\n where S.Element == Element {\n let otherSet = Set(other)\n formSymmetricDifference(otherSet)\n }\n}\n\n@_unavailableInEmbedded\nextension Set: CustomStringConvertible, CustomDebugStringConvertible {\n /// A string that represents the contents of the set.\n public var description: String {\n return _makeCollectionDescription()\n }\n\n /// A string that represents the contents of the set, suitable for debugging.\n public var debugDescription: String {\n return _makeCollectionDescription(withTypeName: "Set")\n }\n}\n\nextension Set {\n /// Removes the elements of the given set from this set.\n ///\n /// In the following example, the elements of the `employees` set that are\n /// also members of the `neighbors` set are removed. In particular, the\n /// names `"Bethany"` and `"Eric"` are removed from `employees`.\n ///\n /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]\n /// employees.subtract(neighbors)\n /// print(employees)\n /// // Prints "["Diana", "Chris", "Alicia"]"\n ///\n /// - Parameter other: Another set.\n @inlinable\n public mutating func subtract(_ other: Set<Element>) {\n _subtract(other)\n }\n\n /// Returns a Boolean value that indicates whether this set is a subset of\n /// the given set.\n ///\n /// Set *A* is a subset of another set *B* if every member of *A* is also a\n /// member of *B*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(attendees.isSubset(of: employees))\n /// // Prints "true"\n ///\n /// - Parameter other: Another set.\n /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.\n @inlinable\n public func isSubset(of other: Set<Element>) -> Bool {\n guard self.count <= other.count else { return false }\n for member in self {\n guard other.contains(member) else {\n return false\n }\n }\n return true\n }\n\n /// Returns a Boolean value that indicates whether this set is a superset of\n /// the given set.\n ///\n /// Set *A* is a superset of another set *B* if every member of *B* is also a\n /// member of *A*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(employees.isSuperset(of: attendees))\n /// // Prints "true"\n ///\n /// - Parameter other: Another set.\n /// - Returns: `true` if the set is a superset of `other`; otherwise,\n /// `false`.\n @inlinable\n public func isSuperset(of other: Set<Element>) -> Bool {\n return other.isSubset(of: self)\n }\n\n /// Returns a Boolean value that indicates whether this set has no members in\n /// common with the given set.\n ///\n /// In the following example, the `employees` set is disjoint with the\n /// `visitors` set because no name appears in both sets.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]\n /// print(employees.isDisjoint(with: visitors))\n /// // Prints "true"\n ///\n /// - Parameter other: Another set.\n /// - Returns: `true` if the set has no elements in common with `other`;\n /// otherwise, `false`.\n @inlinable\n public func isDisjoint(with other: Set<Element>) -> Bool {\n guard !isEmpty && !other.isEmpty else { return true }\n let (smaller, larger) =\n count < other.count ? (self, other) : (other, self)\n for member in smaller {\n if larger.contains(member) {\n return false\n }\n }\n return true\n }\n\n @inlinable\n internal func _isDisjoint<S: Sequence>(with other: S) -> Bool\n where S.Element == Element {\n guard !isEmpty else { return true }\n\n for member in other {\n if contains(member) {\n return false\n }\n }\n return true\n }\n\n /// Returns a new set containing the elements of this set that do not occur\n /// in the given set.\n ///\n /// In the following example, the `nonNeighbors` set is made up of the\n /// elements of the `employees` set that are not elements of `neighbors`:\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]\n /// let nonNeighbors = employees.subtracting(neighbors)\n /// print(nonNeighbors)\n /// // Prints "["Diana", "Chris", "Alicia"]"\n ///\n /// - Parameter other: Another set.\n /// - Returns: A new set.\n @inlinable\n public __consuming func subtracting(_ other: Set<Element>) -> Set<Element> {\n // Heuristic: if `other` is small enough, it's better to make a copy of the\n // set and remove each item one by one. (The best cutoff point depends on\n // the `Element` type; the one below is an educated guess.) FIXME: Derive a\n // better cutoff by benchmarking.\n if other.count <= self.count / 8 {\n var copy = self\n copy._subtract(other)\n return copy\n }\n // Otherwise do a regular subtraction using a temporary bitmap.\n return self._subtracting(other)\n }\n\n /// Returns a Boolean value that indicates whether the set is a strict\n /// superset of the given sequence.\n ///\n /// Set *A* is a strict superset of another set *B* if every member of *B* is\n /// also a member of *A* and *A* contains at least one element that is *not*\n /// a member of *B*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(employees.isStrictSuperset(of: attendees))\n /// // Prints "true"\n /// print(employees.isStrictSuperset(of: employees))\n /// // Prints "false"\n ///\n /// - Parameter other: Another set.\n /// - Returns: `true` if the set is a strict superset of\n /// `other`; otherwise, `false`.\n @inlinable\n public func isStrictSuperset(of other: Set<Element>) -> Bool {\n return self.count > other.count && other.isSubset(of: self)\n }\n\n /// Returns a Boolean value that indicates whether the set is a strict subset\n /// of the given sequence.\n ///\n /// Set *A* is a strict subset of another set *B* if every member of *A* is\n /// also a member of *B* and *B* contains at least one element that is not a\n /// member of *A*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(attendees.isStrictSubset(of: employees))\n /// // Prints "true"\n ///\n /// // A set is never a strict subset of itself:\n /// print(attendees.isStrictSubset(of: attendees))\n /// // Prints "false"\n ///\n /// - Parameter other: Another set.\n /// - Returns: `true` if the set is a strict subset of\n /// `other`; otherwise, `false`.\n @inlinable\n public func isStrictSubset(of other: Set<Element>) -> Bool {\n return self.count < other.count && self.isSubset(of: other)\n }\n\n /// Returns a new set with the elements that are common to both this set and\n /// the given sequence.\n ///\n /// In the following example, the `bothNeighborsAndEmployees` set is made up\n /// of the elements that are in *both* the `employees` and `neighbors` sets.\n /// Elements that are in only one or the other are left out of the result of\n /// the intersection.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]\n /// let bothNeighborsAndEmployees = employees.intersection(neighbors)\n /// print(bothNeighborsAndEmployees)\n /// // Prints "["Bethany", "Eric"]"\n ///\n /// - Parameter other: Another set.\n /// - Returns: A new set.\n @inlinable\n public __consuming func intersection(_ other: Set<Element>) -> Set<Element> {\n Set(_native: _variant.intersection(other))\n }\n\n /// Removes the elements of the set that are also in the given sequence and\n /// adds the members of the sequence that are not already in the set.\n ///\n /// In the following example, the elements of the `employees` set that are\n /// also members of `neighbors` are removed from `employees`, while the\n /// elements of `neighbors` that are not members of `employees` are added to\n /// `employees`. In particular, the names `"Alicia"`, `"Chris"`, and\n /// `"Diana"` are removed from `employees` while the names `"Forlani"` and\n /// `"Greta"` are added.\n ///\n /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]\n /// employees.formSymmetricDifference(neighbors)\n /// print(employees)\n /// // Prints "["Diana", "Chris", "Forlani", "Alicia", "Greta"]"\n ///\n /// - Parameter other: Another set.\n @inlinable\n public mutating func formSymmetricDifference(_ other: __owned Set<Element>) {\n for member in other {\n if contains(member) {\n remove(member)\n } else {\n insert(member)\n }\n }\n }\n}\n\nextension Set {\n /// The position of an element in a set.\n @frozen\n public struct Index {\n // Index for native buffer is efficient. Index for bridged NSSet is\n // 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 NSSet 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(__CocoaSet.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 self.init(_variant: unsafe .native(index))\n }\n\n#if _runtime(_ObjC)\n @inlinable\n @inline(__always)\n internal init(_cocoa index: __owned __CocoaSet.Index) {\n self.init(_variant: .cocoa(index))\n }\n#endif\n }\n}\n\nextension Set.Index {\n#if _runtime(_ObjC)\n @usableFromInline @_transparent\n internal var _guaranteedNative: Bool {\n return _canBeClass(Element.self) == 0\n }\n\n /// Allow the optimizer to consider the surrounding code unreachable if\n /// Set<Element> is guaranteed to be native.\n @usableFromInline\n @_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#endif\n\n#if _runtime(_ObjC)\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 Set elements using an invalid index")\n#endif\n }\n }\n\n#if _runtime(_ObjC)\n @usableFromInline\n internal var _asCocoa: __CocoaSet.Index {\n @_transparent\n get {\n switch _variant {\n case .native:\n _preconditionFailure(\n "Attempting to access Set 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 Set 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 Set.Index: Equatable {\n @inlinable\n public static func == (\n lhs: Set<Element>.Index,\n rhs: Set<Element>.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 sets")\n #endif\n }\n }\n}\n\nextension Set.Index: Comparable {\n @inlinable\n public static func < (\n lhs: Set<Element>.Index,\n rhs: Set<Element>.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 sets")\n #endif\n }\n }\n}\n\nextension Set.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 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 Set {\n /// An iterator over the members of a `Set<Element>`.\n @frozen\n public struct Iterator {\n // Set has a separate IteratorProtocol and Index because of efficiency\n // and implementability reasons.\n //\n // Native sets have efficient indices. Bridged NSSet 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(_NativeSet<Element>.Iterator)\n#if _runtime(_ObjC)\n case cocoa(__CocoaSet.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 _NativeSet<Element>.Iterator) {\n self.init(_variant: .native(_native))\n }\n\n#if _runtime(_ObjC)\n @usableFromInline\n internal init(_cocoa: __owned __CocoaSet.Iterator) {\n self.init(_variant: .cocoa(_cocoa))\n }\n#endif\n }\n}\n\n@available(*, unavailable)\nextension Set.Iterator._Variant: Sendable {}\n\nextension Set.Iterator {\n#if _runtime(_ObjC)\n @usableFromInline @_transparent\n internal var _guaranteedNative: Bool {\n return _canBeClass(Element.self) == 0\n }\n\n /// Allow the optimizer to consider the surrounding code unreachable if\n /// Set<Element> is guaranteed to be native.\n @usableFromInline @_transparent\n internal func _cocoaPath() {\n if _guaranteedNative {\n _conditionallyUnreachable()\n }\n }\n#endif\n\n#if _runtime(_ObjC)\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: _NativeSet<Element>.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: __CocoaSet.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\nextension Set.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() -> Element? {\n#if _runtime(_ObjC)\n guard _isNative else {\n guard let cocoaElement = _asCocoa.next() else { return nil }\n return _forceBridgeFromObjectiveC(cocoaElement, Element.self)\n }\n#endif\n return _asNative.next()\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension Set.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 Set: CustomReflectable {\n /// A mirror that reflects the set.\n public var customMirror: Mirror {\n let style = Mirror.DisplayStyle.`set`\n return Mirror(self, unlabeledChildren: self, displayStyle: style)\n }\n}\n#endif\n\nextension Set {\n /// Removes and returns the first element of the set.\n ///\n /// Because a set is not an ordered collection, the "first" element may not\n /// be the first element that was added to the set.\n ///\n /// - Returns: A member of the set. If the set is empty, returns `nil`.\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 elements that the set 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 elements.\n ///\n /// If you are adding a known number of elements to a set, use this\n /// method to avoid multiple reallocations. This method ensures that the\n /// set has unique, mutable, contiguous storage, with space allocated\n /// for at least the requested number of elements.\n ///\n /// Calling the `reserveCapacity(_:)` method on a set with bridged\n /// storage triggers a copy to contiguous storage even if the existing\n /// storage has room to store `minimumCapacity` elements.\n ///\n /// - Parameter minimumCapacity: The requested number of elements 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 SetIndex<Element: Hashable> = Set<Element>.Index\npublic typealias SetIterator<Element: Hashable> = Set<Element>.Iterator\n\nextension Set: @unchecked Sendable\n where Element: Sendable { }\nextension Set.Index: @unchecked Sendable\n where Element: Sendable { }\nextension Set.Iterator: @unchecked Sendable\n where Element: Sendable { }\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Set.swift
cpp_apple_swift_stdlib_public_core_Set.swift
Swift
57,464
0.75
0.076506
0.543577
python-kit
695
2023-08-17T13:18:28.164576
GPL-3.0
false
03ef5d8c1ed096c701e97483a398ff45
//===--- SetAlgebra.swift - Protocols for set operations ------------------===//\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//\n//===----------------------------------------------------------------------===//\n\n/// A type that provides mathematical set operations.\n///\n/// You use types that conform to the `SetAlgebra` protocol when you need\n/// efficient membership tests or mathematical set operations such as\n/// intersection, union, and subtraction. In the standard library, you can\n/// use the `Set` type with elements of any hashable type, or you can easily\n/// create bit masks with `SetAlgebra` conformance using the `OptionSet`\n/// protocol. See those types for more information.\n///\n/// - Note: Unlike ordinary set types, the `Element` type of an `OptionSet` is\n/// identical to the `OptionSet` type itself. The `SetAlgebra` protocol is\n/// specifically designed to accommodate both kinds of set.\n///\n/// Conforming to the SetAlgebra Protocol\n/// =====================================\n///\n/// When implementing a custom type that conforms to the `SetAlgebra` protocol,\n/// you must implement the required initializers and methods. For the\n/// inherited methods to work properly, conforming types must meet the\n/// following axioms. Assume that `S` is a custom type that conforms to the\n/// `SetAlgebra` protocol, `x` and `y` are instances of `S`, and `e` is of\n/// type `S.Element`---the type that the set holds.\n///\n/// - `S() == []`\n/// - `x.intersection(x) == x`\n/// - `x.intersection([]) == []`\n/// - `x.union(x) == x`\n/// - `x.union([]) == x`\n/// - `x.contains(e)` implies `x.union(y).contains(e)`\n/// - `x.union(y).contains(e)` implies `x.contains(e) || y.contains(e)`\n/// - `x.contains(e) && y.contains(e)` if and only if\n/// `x.intersection(y).contains(e)`\n/// - `x.isSubset(of: y)` implies `x.union(y) == y`\n/// - `x.isSuperset(of: y)` implies `x.union(y) == x`\n/// - `x.isSubset(of: y)` if and only if `y.isSuperset(of: x)`\n/// - `x.isStrictSuperset(of: y)` if and only if\n/// `x.isSuperset(of: y) && x != y`\n/// - `x.isStrictSubset(of: y)` if and only if `x.isSubset(of: y) && x != y`\npublic protocol SetAlgebra<Element>: Equatable, ExpressibleByArrayLiteral {\n /// A type for which the conforming type provides a containment test.\n associatedtype Element\n \n /// Creates an empty set.\n ///\n /// This initializer is equivalent to initializing with an empty array\n /// literal. For example, you create an empty `Set` instance with either\n /// this initializer or with an empty array literal.\n ///\n /// var emptySet = Set<Int>()\n /// print(emptySet.isEmpty)\n /// // Prints "true"\n ///\n /// emptySet = []\n /// print(emptySet.isEmpty)\n /// // Prints "true"\n init()\n \n /// Returns a Boolean value that indicates whether the given element exists\n /// in the set.\n ///\n /// This example uses the `contains(_:)` method to test whether an integer is\n /// a member of a set of prime numbers.\n ///\n /// let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]\n /// let x = 5\n /// if primes.contains(x) {\n /// print("\(x) is prime!")\n /// } else {\n /// print("\(x). Not prime.")\n /// }\n /// // Prints "5 is prime!"\n ///\n /// - Parameter member: An element to look for in the set.\n /// - Returns: `true` if `member` exists in the set; otherwise, `false`.\n func contains(_ member: Element) -> Bool\n\n /// Returns a new set with the elements of both this and the given set.\n ///\n /// In the following example, the `attendeesAndVisitors` set is made up\n /// of the elements of the `attendees` and `visitors` sets:\n ///\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// let visitors = ["Marcia", "Nathaniel"]\n /// let attendeesAndVisitors = attendees.union(visitors)\n /// print(attendeesAndVisitors)\n /// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"\n ///\n /// If the set already contains one or more elements that are also in\n /// `other`, the existing members are kept.\n ///\n /// let initialIndices = Set(0..<5)\n /// let expandedIndices = initialIndices.union([2, 3, 6, 7])\n /// print(expandedIndices)\n /// // Prints "[2, 4, 6, 7, 0, 1, 3]"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: A new set with the unique elements of this set and `other`.\n ///\n /// - Note: if this set and `other` contain elements that are equal but\n /// distinguishable (e.g. via `===`), which of these elements is present\n /// in the result is unspecified.\n __consuming func union(_ other: __owned Self) -> Self\n \n /// Returns a new set with the elements that are common to both this set and\n /// the given set.\n ///\n /// In the following example, the `bothNeighborsAndEmployees` set is made up\n /// of the elements that are in *both* the `employees` and `neighbors` sets.\n /// Elements that are in only one or the other are left out of the result of\n /// the intersection.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]\n /// let bothNeighborsAndEmployees = employees.intersection(neighbors)\n /// print(bothNeighborsAndEmployees)\n /// // Prints "["Bethany", "Eric"]"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: A new set.\n ///\n /// - Note: if this set and `other` contain elements that are equal but\n /// distinguishable (e.g. via `===`), which of these elements is present\n /// in the result is unspecified.\n __consuming func intersection(_ other: Self) -> Self\n\n /// Returns a new set with the elements that are either in this set or in the\n /// given set, but not in both.\n ///\n /// In the following example, the `eitherNeighborsOrEmployees` set is made up\n /// of the elements of the `employees` and `neighbors` sets that are not in\n /// both `employees` *and* `neighbors`. In particular, the names `"Bethany"`\n /// and `"Eric"` do not appear in `eitherNeighborsOrEmployees`.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani"]\n /// let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors)\n /// print(eitherNeighborsOrEmployees)\n /// // Prints "["Diana", "Forlani", "Alicia"]"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: A new set.\n __consuming func symmetricDifference(_ other: __owned Self) -> Self\n\n // FIXME(move-only types): SetAlgebra.insert is not implementable by a\n // set with move-only Element type, since it would be necessary to copy\n // the argument in order to both store it inside the set and return it as\n // the `memberAfterInsert`.\n\n /// Inserts the given element in the set if it is not already present.\n ///\n /// If an element equal to `newMember` is already contained in the set, this\n /// method has no effect. In this example, a new element is inserted into\n /// `classDays`, a set of days of the week. When an existing element is\n /// inserted, the `classDays` set does not change.\n ///\n /// enum DayOfTheWeek: Int {\n /// case sunday, monday, tuesday, wednesday, thursday,\n /// friday, saturday\n /// }\n ///\n /// var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]\n /// print(classDays.insert(.monday))\n /// // Prints "(true, .monday)"\n /// print(classDays)\n /// // Prints "[.friday, .wednesday, .monday]"\n ///\n /// print(classDays.insert(.friday))\n /// // Prints "(false, .friday)"\n /// print(classDays)\n /// // Prints "[.friday, .wednesday, .monday]"\n ///\n /// - Parameter newMember: An element to insert into the set.\n /// - Returns: `(true, newMember)` if `newMember` was not contained in the\n /// set. If an element equal to `newMember` was already contained in the\n /// set, the method returns `(false, oldMember)`, where `oldMember` is the\n /// element that was equal to `newMember`. In some cases, `oldMember` may\n /// be distinguishable from `newMember` by identity comparison or some\n /// other means.\n @discardableResult\n mutating func insert(\n _ newMember: __owned Element\n ) -> (inserted: Bool, memberAfterInsert: Element)\n \n /// Removes the given element and any elements subsumed by the given element.\n ///\n /// - Parameter member: The element of the set to remove.\n /// - Returns: For ordinary sets, an element equal to `member` if `member` is\n /// contained in the set; otherwise, `nil`. In some cases, a returned\n /// element may be distinguishable from `member` by identity comparison\n /// or some other means.\n ///\n /// For sets where the set type and element type are the same, like\n /// `OptionSet` types, this method returns any intersection between the set\n /// and `[member]`, or `nil` if the intersection is empty.\n @discardableResult\n mutating func remove(_ member: Element) -> Element?\n\n /// Inserts the given element into the set unconditionally.\n ///\n /// If an element equal to `newMember` is already contained in the set,\n /// `newMember` replaces the existing element. In this example, an existing\n /// element is inserted into `classDays`, a set of days of the week.\n ///\n /// enum DayOfTheWeek: Int {\n /// case sunday, monday, tuesday, wednesday, thursday,\n /// friday, saturday\n /// }\n ///\n /// var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday]\n /// print(classDays.update(with: .monday))\n /// // Prints "Optional(.monday)"\n ///\n /// - Parameter newMember: An element to insert into the set.\n /// - Returns: For ordinary sets, an element equal to `newMember` if the set\n /// already contained such a member; otherwise, `nil`. In some cases, the\n /// returned element may be distinguishable from `newMember` by identity\n /// comparison or some other means.\n ///\n /// For sets where the set type and element type are the same, like\n /// `OptionSet` types, this method returns any intersection between the \n /// set and `[newMember]`, or `nil` if the intersection is empty.\n @discardableResult\n mutating func update(with newMember: __owned Element) -> Element?\n \n /// Adds the elements of the given set to the set.\n ///\n /// In the following example, the elements of the `visitors` set are added to\n /// the `attendees` set:\n ///\n /// var attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// let visitors: Set = ["Diana", "Marcia", "Nathaniel"]\n /// attendees.formUnion(visitors)\n /// print(attendees)\n /// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"\n ///\n /// If the set already contains one or more elements that are also in\n /// `other`, the existing members are kept.\n ///\n /// var initialIndices = Set(0..<5)\n /// initialIndices.formUnion([2, 3, 6, 7])\n /// print(initialIndices)\n /// // Prints "[2, 4, 6, 7, 0, 1, 3]"\n ///\n /// - Parameter other: A set of the same type as the current set.\n mutating func formUnion(_ other: __owned Self)\n\n /// Removes the elements of this set that aren't also in the given set.\n ///\n /// In the following example, the elements of the `employees` set that are\n /// not also members of the `neighbors` set are removed. In particular, the\n /// names `"Alicia"`, `"Chris"`, and `"Diana"` are removed.\n ///\n /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]\n /// employees.formIntersection(neighbors)\n /// print(employees)\n /// // Prints "["Bethany", "Eric"]"\n ///\n /// - Parameter other: A set of the same type as the current set.\n mutating func formIntersection(_ other: Self)\n\n /// Removes the elements of the set that are also in the given set and adds\n /// the members of the given set that are not already in the set.\n ///\n /// In the following example, the elements of the `employees` set that are\n /// also members of `neighbors` are removed from `employees`, while the\n /// elements of `neighbors` that are not members of `employees` are added to\n /// `employees`. In particular, the names `"Bethany"` and `"Eric"` are\n /// removed from `employees` while the name `"Forlani"` is added.\n ///\n /// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani"]\n /// employees.formSymmetricDifference(neighbors)\n /// print(employees)\n /// // Prints "["Diana", "Forlani", "Alicia"]"\n ///\n /// - Parameter other: A set of the same type.\n mutating func formSymmetricDifference(_ other: __owned Self)\n\n //===--- Requirements with default implementations ----------------------===//\n /// Returns a new set containing the elements of this set that do not occur\n /// in the given set.\n ///\n /// In the following example, the `nonNeighbors` set is made up of the\n /// elements of the `employees` set that are not elements of `neighbors`:\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]\n /// let nonNeighbors = employees.subtracting(neighbors)\n /// print(nonNeighbors)\n /// // Prints "["Diana", "Chris", "Alicia"]"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: A new set.\n __consuming func subtracting(_ other: Self) -> Self\n\n /// Returns a Boolean value that indicates whether the set is a subset of\n /// another set.\n ///\n /// Set *A* is a subset of another set *B* if every member of *A* is also a\n /// member of *B*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(attendees.isSubset(of: employees))\n /// // Prints "true"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.\n func isSubset(of other: Self) -> Bool\n\n /// Returns a Boolean value that indicates whether the set has no members in\n /// common with the given set.\n ///\n /// In the following example, the `employees` set is disjoint with the\n /// `visitors` set because no name appears in both sets.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]\n /// print(employees.isDisjoint(with: visitors))\n /// // Prints "true"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: `true` if the set has no elements in common with `other`;\n /// otherwise, `false`.\n func isDisjoint(with other: Self) -> Bool\n\n /// Returns a Boolean value that indicates whether the set is a superset of\n /// the given set.\n ///\n /// Set *A* is a superset of another set *B* if every member of *B* is also a\n /// member of *A*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(employees.isSuperset(of: attendees))\n /// // Prints "true"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: `true` if the set is a superset of `possibleSubset`;\n /// otherwise, `false`.\n func isSuperset(of other: Self) -> Bool\n\n /// A Boolean value that indicates whether the set has no elements.\n var isEmpty: Bool { get }\n \n /// Creates a new set from a finite sequence of items.\n ///\n /// Use this initializer to create a new set from an existing sequence, like\n /// an array or a range:\n ///\n /// let validIndices = Set(0..<7).subtracting([2, 4, 5])\n /// print(validIndices)\n /// // Prints "[6, 0, 1, 3]"\n ///\n /// - Parameter sequence: The elements to use as members of the new set.\n init<S: Sequence>(_ sequence: __owned S) where S.Element == Element\n\n /// Removes the elements of the given set from this set.\n ///\n /// In the following example, the elements of the `employees` set that are\n /// also members of the `neighbors` set are removed. In particular, the\n /// names `"Bethany"` and `"Eric"` are removed from `employees`.\n ///\n /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]\n /// employees.subtract(neighbors)\n /// print(employees)\n /// // Prints "["Diana", "Chris", "Alicia"]"\n ///\n /// - Parameter other: A set of the same type as the current set.\n mutating func subtract(_ other: Self)\n}\n\n/// `SetAlgebra` requirements for which default implementations\n/// are supplied.\n///\n/// - Note: A type conforming to `SetAlgebra` can implement any of\n/// these initializers or methods, and those implementations will be\n/// used in lieu of these defaults.\nextension SetAlgebra {\n /// Creates a new set from a finite sequence of items.\n ///\n /// Use this initializer to create a new set from an existing sequence, like\n /// an array or a range:\n ///\n /// let validIndices = Set(0..<7).subtracting([2, 4, 5])\n /// print(validIndices)\n /// // Prints "[6, 0, 1, 3]"\n ///\n /// - Parameter sequence: The elements to use as members of the new set.\n @inlinable // protocol-only\n public init<S: Sequence>(_ sequence: __owned S)\n where S.Element == Element {\n self.init()\n // Needed to fully optimize OptionSet literals.\n _onFastPath()\n for e in sequence { insert(e) }\n }\n\n /// Removes the elements of the given set from this set.\n ///\n /// In the following example, the elements of the `employees` set that are\n /// also members of the `neighbors` set are removed. In particular, the\n /// names `"Bethany"` and `"Eric"` are removed from `employees`.\n ///\n /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]\n /// employees.subtract(neighbors)\n /// print(employees)\n /// // Prints "["Diana", "Chris", "Alicia"]"\n ///\n /// - Parameter other: A set of the same type as the current set.\n @inlinable // protocol-only\n public mutating func subtract(_ other: Self) {\n self.formIntersection(self.symmetricDifference(other))\n }\n\n /// Returns a Boolean value that indicates whether the set is a subset of\n /// another set.\n ///\n /// Set *A* is a subset of another set *B* if every member of *A* is also a\n /// member of *B*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(attendees.isSubset(of: employees))\n /// // Prints "true"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.\n @inlinable // protocol-only\n public func isSubset(of other: Self) -> Bool {\n return self.intersection(other) == self\n }\n\n /// Returns a Boolean value that indicates whether the set is a superset of\n /// the given set.\n ///\n /// Set *A* is a superset of another set *B* if every member of *B* is also a\n /// member of *A*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(employees.isSuperset(of: attendees))\n /// // Prints "true"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: `true` if the set is a superset of `other`; otherwise,\n /// `false`.\n @inlinable // protocol-only\n public func isSuperset(of other: Self) -> Bool {\n return other.isSubset(of: self)\n }\n\n /// Returns a Boolean value that indicates whether the set has no members in\n /// common with the given set.\n ///\n /// In the following example, the `employees` set is disjoint with the\n /// `visitors` set because no name appears in both sets.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]\n /// print(employees.isDisjoint(with: visitors))\n /// // Prints "true"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: `true` if the set has no elements in common with `other`;\n /// otherwise, `false`.\n @inlinable // protocol-only\n public func isDisjoint(with other: Self) -> Bool {\n return self.intersection(other).isEmpty\n }\n\n /// Returns a new set containing the elements of this set that do not occur\n /// in the given set.\n ///\n /// In the following example, the `nonNeighbors` set is made up of the\n /// elements of the `employees` set that are not elements of `neighbors`:\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]\n /// let nonNeighbors = employees.subtracting(neighbors)\n /// print(nonNeighbors)\n /// // Prints "["Diana", "Chris", "Alicia"]"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: A new set.\n @inlinable // protocol-only\n public func subtracting(_ other: Self) -> Self {\n return self.intersection(self.symmetricDifference(other))\n }\n\n /// A Boolean value that indicates whether the set has no elements.\n @inlinable // protocol-only\n public var isEmpty: Bool {\n return self == Self()\n }\n\n /// Returns a Boolean value that indicates whether this set is a strict\n /// superset of the given set.\n ///\n /// Set *A* is a strict superset of another set *B* if every member of *B* is\n /// also a member of *A* and *A* contains at least one element that is *not*\n /// a member of *B*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(employees.isStrictSuperset(of: attendees))\n /// // Prints "true"\n ///\n /// // A set is never a strict superset of itself:\n /// print(employees.isStrictSuperset(of: employees))\n /// // Prints "false"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: `true` if the set is a strict superset of `other`; otherwise,\n /// `false`.\n @inlinable // protocol-only\n public func isStrictSuperset(of other: Self) -> Bool {\n return self.isSuperset(of: other) && self != other\n }\n\n /// Returns a Boolean value that indicates whether this set is a strict\n /// subset of the given set.\n ///\n /// Set *A* is a strict subset of another set *B* if every member of *A* is\n /// also a member of *B* and *B* contains at least one element that is not a\n /// member of *A*.\n ///\n /// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]\n /// let attendees: Set = ["Alicia", "Bethany", "Diana"]\n /// print(attendees.isStrictSubset(of: employees))\n /// // Prints "true"\n ///\n /// // A set is never a strict subset of itself:\n /// print(attendees.isStrictSubset(of: attendees))\n /// // Prints "false"\n ///\n /// - Parameter other: A set of the same type as the current set.\n /// - Returns: `true` if the set is a strict subset of `other`; otherwise,\n /// `false`.\n @inlinable // protocol-only\n public func isStrictSubset(of other: Self) -> Bool {\n return other.isStrictSuperset(of: self)\n }\n}\n\nextension SetAlgebra where Element == ArrayLiteralElement {\n /// Creates a set containing the elements of 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 set using an array\n /// literal as its value by enclosing a comma-separated list of values in\n /// square brackets. You can use an array literal anywhere a set is expected\n /// by the type context.\n ///\n /// Here, a set of strings is created from an array literal holding only\n /// strings:\n ///\n /// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]\n /// if ingredients.isSuperset(of: ["sugar", "salt"]) {\n /// print("Whatever it is, it's bound to be delicious!")\n /// }\n /// // Prints "Whatever it is, it's bound to be delicious!"\n ///\n /// - Parameter arrayLiteral: A list of elements of the new set.\n @inlinable // protocol-only\n public init(arrayLiteral: Element...) {\n self.init(arrayLiteral)\n } \n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_SetAlgebra.swift
cpp_apple_swift_stdlib_public_core_SetAlgebra.swift
Swift
25,092
0.95
0.073129
0.869176
vue-tools
967
2024-08-09T22:05:08.376997
MIT
false
16501b175a0029f986b43710458302de
//===----------------------------------------------------------------------===//\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// Convenience APIs for Set<AnyHashable>\n//===----------------------------------------------------------------------===//\n\nextension Set where Element == AnyHashable {\n @inlinable\n @discardableResult\n public mutating func insert<ConcreteElement: Hashable>(\n _ newMember: __owned ConcreteElement\n ) -> (inserted: Bool, memberAfterInsert: ConcreteElement) {\n let (inserted, memberAfterInsert) =\n insert(AnyHashable(newMember))\n return (\n inserted: inserted,\n memberAfterInsert: memberAfterInsert.base as! ConcreteElement)\n }\n\n @inlinable\n @discardableResult\n public mutating func update<ConcreteElement: Hashable>(\n with newMember: __owned ConcreteElement\n ) -> ConcreteElement? {\n return update(with: AnyHashable(newMember))\n .map { $0.base as! ConcreteElement }\n }\n\n @inlinable\n @discardableResult\n public mutating func remove<ConcreteElement: Hashable>(\n _ member: ConcreteElement\n ) -> ConcreteElement? {\n return remove(AnyHashable(member))\n .map { $0.base as! ConcreteElement }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_SetAnyHashableExtensions.swift
cpp_apple_swift_stdlib_public_core_SetAnyHashableExtensions.swift
Swift
1,648
0.8
0.06383
0.325581
vue-tools
977
2024-09-23T07:24:38.049544
MIT
false
62caa12a9a93015ac5419ef41951c117
//===----------------------------------------------------------------------===//\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 `NSSet.allObjects`, but does not leave objects on the\n/// autorelease pool.\ninternal func _stdlib_NSSet_allObjects(_ object: AnyObject) -> _BridgingBuffer {\n let nss = unsafe unsafeBitCast(object, to: _NSSet.self)\n let count = nss.count\n let storage = _BridgingBuffer(count)\n unsafe nss.getObjects(storage.baseAddress)\n return storage\n}\n\nextension _NativeSet { // Bridging\n @usableFromInline\n internal __consuming func bridged() -> AnyObject {\n _connectOrphanedFoundationSubclassesIfNeeded()\n \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 nsSet: _NSSetCore\n\n if unsafe _storage === __RawSetStorage.empty || count == 0 {\n unsafe nsSet = __RawSetStorage.empty\n } else if _isBridgedVerbatimToObjectiveC(Element.self) {\n unsafe nsSet = unsafeDowncast(_storage, to: _SetStorage<Element>.self)\n } else {\n nsSet = _SwiftDeferredNSSet(self)\n }\n\n // Cast from "minimal NSSet" to "NSSet"\n // Note that if you actually ask Swift for this cast, it will fail.\n // Never trust a shadow protocol!\n return nsSet\n }\n}\n\n/// An NSEnumerator that works with any _NativeSet of verbatim bridgeable\n/// elements. Used by the various NSSet impls.\n@safe\nfinal internal class _SwiftSetNSEnumerator<Element: Hashable>\n : __SwiftNativeNSEnumerator, _NSEnumerator {\n\n @nonobjc internal var base: _NativeSet<Element>\n @nonobjc internal var bridgedElements: __BridgingHashBuffer?\n @nonobjc internal var nextBucket: _NativeSet<Element>.Bucket\n @nonobjc internal var endBucket: _NativeSet<Element>.Bucket\n\n @objc\n internal override required init() {\n _internalInvariantFailure("don't call this designated initializer")\n }\n\n internal init(_ base: __owned _NativeSet<Element>) {\n _internalInvariant(_isBridgedVerbatimToObjectiveC(Element.self))\n _internalInvariant(_orphanedFoundationSubclassesReparented)\n self.base = base\n unsafe self.bridgedElements = 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 _SwiftDeferredNSSet<Element>) {\n _internalInvariant(!_isBridgedVerbatimToObjectiveC(Element.self))\n _internalInvariant(_orphanedFoundationSubclassesReparented)\n self.base = deferred.native\n unsafe self.bridgedElements = deferred.bridgeElements()\n unsafe self.nextBucket = base.hashTable.startBucket\n unsafe self.endBucket = base.hashTable.endBucket\n super.init()\n }\n\n private func bridgedElement(at bucket: _HashTable.Bucket) -> AnyObject {\n unsafe _internalInvariant(base.hashTable.isOccupied(bucket))\n if let bridgedElements = unsafe self.bridgedElements {\n return unsafe bridgedElements[bucket]\n }\n return unsafe _bridgeAnythingToObjectiveC(base.uncheckedElement(at: bucket))\n }\n\n //\n // NSEnumerator implementation.\n //\n // Do not call any of these methods from the standard library!\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.bridgedElement(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.bridgedElement(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/// _NativeSet, and can be upcast to NSSelf when bridging is necessary. This is\n/// the fallback implementation for situations where toll-free bridging isn't\n/// possible. On first access, a _NativeSet of AnyObject will be constructed\n/// containing all the bridged elements.\nfinal internal class _SwiftDeferredNSSet<Element: Hashable>\n : __SwiftNativeNSSet, _NSSetCore {\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 _bridgedElements_DoNotUse: AnyObject?\n\n /// The unbridged elements.\n internal var native: _NativeSet<Element>\n\n internal init(_ native: __owned _NativeSet<Element>) {\n _internalInvariant(native.count > 0)\n _internalInvariant(!_isBridgedVerbatimToObjectiveC(Element.self))\n self.native = native\n super.init()\n }\n\n /// Returns the pointer to the stored property, which contains bridged\n /// Set elements.\n @nonobjc\n private var _bridgedElementsPtr: UnsafeMutablePointer<AnyObject?> {\n return unsafe _getUnsafePointerToStoredProperties(self)\n .assumingMemoryBound(to: Optional<AnyObject>.self)\n }\n\n /// The buffer for bridged Set elements, if present.\n @nonobjc\n private var _bridgedElements: __BridgingHashBuffer? {\n guard let ref = unsafe _stdlib_atomicLoadARCRef(object: _bridgedElementsPtr) else {\n return nil\n }\n return unsafe unsafeDowncast(ref, to: __BridgingHashBuffer.self)\n }\n\n /// Attach a buffer for bridged Set elements.\n @nonobjc\n private func _initializeBridgedElements(_ storage: __BridgingHashBuffer) {\n unsafe _stdlib_atomicInitializeARCRef(\n object: _bridgedElementsPtr,\n desired: storage)\n }\n\n @nonobjc\n internal func bridgeElements() -> __BridgingHashBuffer {\n if let bridgedElements = unsafe _bridgedElements { return unsafe bridgedElements }\n\n // Allocate and initialize heap storage for bridged objects.\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.uncheckedElement(at: bucket))\n unsafe bridged.initialize(at: bucket, to: object)\n }\n\n // Atomically put the bridged elements in place.\n unsafe _initializeBridgedElements(bridged)\n return unsafe _bridgedElements!\n }\n\n @objc\n internal required init(objects: UnsafePointer<AnyObject?>, count: Int) {\n _internalInvariantFailure("don't call this designated initializer")\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 `NSSet` type, which is immutable.\n return self\n }\n\n @objc(member:)\n internal func member(_ object: AnyObject) -> AnyObject? {\n guard let element = _conditionallyBridgeFromObjectiveC(object, Element.self)\n else { return nil }\n\n let (bucket, found) = native.find(element)\n guard found else { return nil }\n let bridged = unsafe bridgeElements()\n return unsafe bridged[bucket]\n }\n\n @objc\n internal func objectEnumerator() -> _NSEnumerator {\n return _SwiftSetNSEnumerator<Element>(self)\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\n // Only need to bridge once, so we can hoist it out of the loop.\n let bridgedElements = unsafe bridgeElements()\n\n var stored = 0\n for i in 0..<count {\n if bucket == endBucket { break }\n unsafe unmanagedObjects[i] = unsafe bridgedElements[bucket]\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 overlays called this struct _CocoaSet. 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 __CocoaSet {\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 __CocoaSet: Sendable {}\n\nextension __CocoaSet {\n @usableFromInline\n @_effects(releasenone)\n internal func member(for index: Index) -> AnyObject {\n return index.element\n }\n\n @usableFromInline\n internal func member(for element: AnyObject) -> AnyObject? {\n let nss = unsafe unsafeBitCast(object, to: _NSSet.self)\n return nss.member(element)\n }\n}\n\nextension __CocoaSet {\n @usableFromInline\n internal func isEqual(to other: __CocoaSet) -> Bool {\n return _stdlib_NSObject_isEqual(self.object, other.object)\n }\n}\n\nextension __CocoaSet: _SetBuffer {\n @usableFromInline\n internal typealias Element = AnyObject\n\n @usableFromInline // FIXME(cocoa-index): Should be inlinable\n internal var startIndex: Index {\n @_effects(releasenone)\n get {\n let allKeys = _stdlib_NSSet_allObjects(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_NSSet_allObjects(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,\n "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(for element: AnyObject) -> 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 !contains(element) {\n return nil\n }\n\n let allKeys = _stdlib_NSSet_allObjects(object)\n for i in 0..<allKeys.count {\n if _stdlib_NSObject_isEqual(element, allKeys[i]) {\n return Index(Index.Storage(self, allKeys), offset: i)\n }\n }\n _internalInvariantFailure(\n "An NSSet member wasn't listed amongst its enumerated contents")\n }\n\n @usableFromInline\n internal var count: Int {\n let nss = unsafe unsafeBitCast(object, to: _NSSet.self)\n return nss.count\n }\n\n @usableFromInline\n internal func contains(_ element: AnyObject) -> Bool {\n let nss = unsafe unsafeBitCast(object, to: _NSSet.self)\n return nss.member(element) != nil\n }\n\n @usableFromInline // FIXME(cocoa-index): Make inlinable\n @_effects(releasenone)\n internal func element(at i: Index) -> AnyObject {\n let element: AnyObject? = i.element\n _internalInvariant(element != nil, "Item not found in underlying NSSet")\n return element!\n }\n}\n\nextension __CocoaSet {\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: __owned Storage, offset: Int) {\n self._storage = _bridgeObject(fromNative: storage)\n self._offset = offset\n }\n }\n}\n\nextension __CocoaSet.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 NSSet, which owns members in `allObjects`,\n /// or `allKeys`, for NSSet and NSDictionary respectively.\n internal let base: __CocoaSet\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 __CocoaSet,\n _ allKeys: __owned _BridgingBuffer\n ) {\n self.base = base\n self.allKeys = allKeys\n }\n }\n}\n\nextension __CocoaSet.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\nextension __CocoaSet.Index {\n @usableFromInline // FIXME(cocoa-index): Make inlinable\n @nonobjc\n internal var element: AnyObject {\n @_effects(readonly)\n get {\n _precondition(_offset < storage.allKeys.count,\n "Attempting to access Set 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(releasenone)\n get {\n return unsafe _HashTable.age(for: storage.base.object)\n }\n }\n}\n\nextension __CocoaSet.Index: Equatable {\n @usableFromInline // FIXME(cocoa-index): Make inlinable\n @_effects(readonly)\n internal static func == (lhs: __CocoaSet.Index, rhs: __CocoaSet.Index) -> Bool {\n _precondition(lhs.storage.base.object === rhs.storage.base.object,\n "Comparing indexes from different sets")\n return lhs._offset == rhs._offset\n }\n}\n\nextension __CocoaSet.Index: Comparable {\n @usableFromInline // FIXME(cocoa-index): Make inlinable\n @_effects(readonly)\n internal static func < (lhs: __CocoaSet.Index, rhs: __CocoaSet.Index) -> Bool {\n _precondition(lhs.storage.base.object === rhs.storage.base.object,\n "Comparing indexes from different sets")\n return lhs._offset < rhs._offset\n }\n}\n\nextension __CocoaSet: Sequence {\n @safe\n @usableFromInline\n final internal class Iterator {\n // Cocoa Set 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: __CocoaSet\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 __CocoaSet) {\n self.base = base\n }\n }\n\n @usableFromInline\n internal __consuming func makeIterator() -> Iterator {\n return Iterator(self)\n }\n}\n\n@available(*, unavailable)\nextension __CocoaSet.Iterator: Sendable {}\n\nextension __CocoaSet.Iterator: IteratorProtocol {\n @usableFromInline\n internal typealias Element = AnyObject\n\n @usableFromInline\n internal func next() -> Element? {\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\n//===--- Bridging ---------------------------------------------------------===//\n\nextension Set {\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 ) -> Set<Element>? {\n\n // Try all three NSSet impls that we currently provide.\n\n if let deferred = s as? _SwiftDeferredNSSet<Element> {\n return Set(_native: deferred.native)\n }\n\n if let nativeStorage = unsafe s as? _SetStorage<Element> {\n return unsafe Set(_native: _NativeSet(nativeStorage))\n }\n\n if unsafe s === __RawSetStorage.empty {\n return Set()\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_SetBridging.swift
cpp_apple_swift_stdlib_public_core_SetBridging.swift
Swift
20,667
0.95
0.083981
0.164855
python-kit
53
2025-01-08T10:32:24.195776
BSD-3-Clause
false
a1e6422894a0b92c7d70b15e318f5ed3
//===----------------------------------------------------------------------===//\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 `Set` from unique members.\n///\n/// Using a builder can be faster than inserting members into an empty\n/// `Set`.\n@frozen\npublic // SPI(Foundation)\nstruct _SetBuilder<Element: Hashable> {\n @usableFromInline\n internal var _target: _NativeSet<Element>\n @usableFromInline\n internal let _requestedCount: Int\n\n @inlinable\n public init(count: Int) {\n _target = _NativeSet(capacity: count)\n _requestedCount = count\n }\n\n @inlinable\n @inline(__always)\n public mutating func add(member: Element) {\n _precondition(_target.count < _requestedCount,\n "Can't add more members than promised")\n unsafe _target._unsafeInsertNew(member)\n }\n\n @inlinable\n public __consuming func take() -> Set<Element> {\n _precondition(_target.count == _requestedCount,\n "The number of members added does not match the promised count")\n return Set(_native: _target)\n }\n}\n\n@available(*, unavailable)\nextension _SetBuilder: Sendable {}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_SetBuilder.swift
cpp_apple_swift_stdlib_public_core_SetBuilder.swift
Swift
1,476
0.8
0.041667
0.348837
awesome-app
660
2023-08-19T17:55:51.282788
Apache-2.0
false
df1c35b39cf2ca8f1a2faa4d186c1e34
//===----------------------------------------------------------------------===//\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 Set<Element> --------===//\n\nextension Set {\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) -> Element?\n ) {\n var target = _NativeSet<Element>(capacity: source.count)\n if allowingDuplicates {\n for m in source {\n guard let member = transform(m) else { return nil }\n target._unsafeUpdate(with: member)\n }\n } else {\n for m in source {\n guard let member = transform(m) else { return nil }\n unsafe target._unsafeInsertNew(member)\n }\n }\n self.init(_native: target)\n }\n}\n\n/// Perform a non-bridged upcast that always succeeds.\n///\n/// - Precondition: `BaseValue` is a base class or base `@objc`\n/// protocol (such as `AnyObject`) of `DerivedValue`.\n@inlinable\n@_unavailableInEmbedded\npublic func _setUpCast<DerivedValue, BaseValue>(\n _ source: Set<DerivedValue>\n) -> Set<BaseValue> {\n return Set(\n _mapping: source,\n // String and NSString have different concepts of equality, so Set<NSString>\n // may generate key collisions when "upcasted" to Set<String>.\n // See rdar://problem/35995647\n allowingDuplicates: (BaseValue.self == String.self)\n ) { member in\n (member as! BaseValue)\n }!\n}\n\n/// Called by the casting machinery.\n@_silgen_name("_swift_setDownCastIndirect")\n@_unavailableInEmbedded\ninternal func _setDownCastIndirect<SourceValue, TargetValue>(\n _ source: UnsafePointer<Set<SourceValue>>,\n _ target: UnsafeMutablePointer<Set<TargetValue>>) {\n unsafe target.initialize(to: _setDownCast(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: `DerivedValue` is a subtype of `BaseValue` and both\n/// are reference types.\n@inlinable\n@_unavailableInEmbedded\npublic func _setDownCast<BaseValue, DerivedValue>(_ source: Set<BaseValue>)\n -> Set<DerivedValue> {\n\n#if _runtime(_ObjC)\n if _isClassOrObjCExistential(BaseValue.self)\n && _isClassOrObjCExistential(DerivedValue.self) {\n guard source._variant.isNative else {\n return Set(_immutableCocoaSet: source._variant.asCocoa.object)\n }\n return Set(_immutableCocoaSet: source._variant.asNative.bridged())\n }\n#endif\n // We can't just delegate to _setDownCastConditional here because we rely on\n // `as!` to generate nice runtime errors when the downcast fails.\n\n return Set(\n _mapping: source,\n // String and NSString have different concepts of equality, so\n // NSString-keyed Sets may generate key collisions when downcasted\n // to String. See rdar://problem/35995647\n allowingDuplicates: (DerivedValue.self == String.self)\n ) { member in\n (member as! DerivedValue)\n }!\n}\n\n/// Called by the casting machinery.\n@_silgen_name("_swift_setDownCastConditionalIndirect")\n@_unavailableInEmbedded\ninternal func _setDownCastConditionalIndirect<SourceValue, TargetValue>(\n _ source: UnsafePointer<Set<SourceValue>>,\n _ target: UnsafeMutablePointer<Set<TargetValue>>\n) -> Bool {\n if let result: Set<TargetValue> = unsafe _setDownCastConditional(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: `DerivedValue` is a subtype of `BaseValue` and both\n/// are reference types.\n@inlinable\n@_unavailableInEmbedded\npublic func _setDownCastConditional<BaseValue, DerivedValue>(\n _ source: Set<BaseValue>\n) -> Set<DerivedValue>? {\n return Set(\n _mapping: source,\n // String and NSString have different concepts of equality, so\n // NSString-keyed Sets may generate key collisions when downcasted\n // to String. See rdar://problem/35995647\n allowingDuplicates: (DerivedValue.self == String.self)\n ) { member in\n member as? DerivedValue\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_SetCasting.swift
cpp_apple_swift_stdlib_public_core_SetCasting.swift
Swift
4,616
0.95
0.086957
0.348837
python-kit
370
2025-05-20T06:00:35.689918
MIT
false
379a342614fb2d77c5e40fd28b3038f2
//===----------------------------------------------------------------------===//\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 `Set` 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 _RawSetStorage. 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 __RawSetStorage: __SwiftNativeNSSet {\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 set.\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 set. 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 set instance.\n @usableFromInline\n internal final var _seed: Int\n\n /// A raw pointer to the start of the tail-allocated hash buffer holding set\n /// members.\n @usableFromInline\n @nonobjc\n internal final var _rawElements: 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 _EmptySetSingleton. The two\n// must coexist without conflicting ObjC class names, so it was renamed.\n// The old names must not be used in the new runtime.\n@unsafe @_fixed_layout\n@usableFromInline\n@_objc_non_lazy_realization\ninternal class __EmptySetSingleton: __RawSetStorage {\n @nonobjc\n override internal init(_doNotCallMe: ()) {\n _internalInvariantFailure("This class cannot be directly initialized")\n }\n\n#if _runtime(_ObjC)\n @objc\n internal required init(objects: UnsafePointer<AnyObject?>, count: Int) {\n _internalInvariantFailure("This class cannot be directly initialized")\n }\n#endif\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 _swiftEmptySetSingleton: (Int, Int, Int, Int, UInt8, UInt8, UInt16, UInt32, 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 /*rawElements*/1, \n /*metadata*/~1\n )\n#endif\n\nextension __RawSetStorage {\n /// The empty singleton that is used for every single Set that is created\n /// without any elements. The contents of the storage must never be mutated.\n @inlinable\n @nonobjc\n internal static var empty: __EmptySetSingleton {\n return unsafe Builtin.bridgeFromRawPointer(\n Builtin.addressof(&_swiftEmptySetSingleton))\n }\n}\n\nextension __EmptySetSingleton: @unsafe _NSSetCore {\n#if _runtime(_ObjC)\n //\n // NSSet implementation, assuming Self is the empty singleton\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 0\n }\n\n @objc(member:)\n internal func member(_ object: AnyObject) -> AnyObject? {\n return nil\n }\n\n @objc\n internal func objectEnumerator() -> _NSEnumerator {\n return __SwiftEmptyNSEnumerator()\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 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 return 0\n }\n#endif\n}\n\n@unsafe @usableFromInline\nfinal internal class _SetStorage<Element: Hashable>\n : __RawSetStorage, @unsafe _NSSetCore {\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(Element.self) {\n let elements = unsafe _elements\n for unsafe bucket in unsafe _hashTable {\n unsafe (elements + bucket.offset).deinitialize(count: 1)\n }\n }\n unsafe _fixLifetime(self)\n }\n\n @inlinable\n final internal var _elements: UnsafeMutablePointer<Element> {\n @inline(__always)\n get {\n return unsafe self._rawElements.assumingMemoryBound(to: Element.self)\n }\n }\n\n internal var asNative: _NativeSet<Element> {\n return unsafe _NativeSet(self)\n }\n\n#if _runtime(_ObjC)\n @objc\n internal required init(objects: UnsafePointer<AnyObject?>, count: Int) {\n _internalInvariantFailure("don't call this designated initializer")\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\n internal func objectEnumerator() -> _NSEnumerator {\n return unsafe _SwiftSetNSEnumerator<Element>(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 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 let element = unsafe _elements[bucket.offset]\n unsafe unmanagedObjects[i] = _bridgeAnythingToObjectiveC(element)\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(member:)\n internal func member(_ object: AnyObject) -> AnyObject? {\n guard let native = _conditionallyBridgeFromObjectiveC(object, Element.self)\n else { return nil }\n\n let (bucket, found) = unsafe asNative.find(native)\n guard found else { return nil }\n return unsafe _bridgeAnythingToObjectiveC(_elements[bucket.offset])\n }\n#endif\n}\n\nextension _SetStorage {\n @usableFromInline\n @_effects(releasenone)\n internal static func copy(original: __RawSetStorage) -> _SetStorage {\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: __RawSetStorage,\n capacity: Int,\n move: Bool\n ) -> _SetStorage {\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) -> _SetStorage {\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: __CocoaSet,\n capacity: Int\n ) -> _SetStorage {\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 ) -> _SetStorage {\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_2(\n _SetStorage<Element>.self,\n wordCount._builtinWordValue, _HashTable.Word.self,\n bucketCount._builtinWordValue, Element.self)\n\n let metadataAddr = unsafe Builtin.projectTailElems(storage, _HashTable.Word.self)\n let elementsAddr = Builtin.getTailAddr_Word(\n metadataAddr, wordCount._builtinWordValue, _HashTable.Word.self,\n Element.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._rawElements = UnsafeMutableRawPointer(elementsAddr)\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_SetStorage.swift
cpp_apple_swift_stdlib_public_core_SetStorage.swift
Swift
12,934
0.95
0.090452
0.25
vue-tools
628
2023-11-08T16:34:34.129398
MIT
false
3ec6cdf01068d38a6a5275f419533441
//===----------------------------------------------------------------------===//\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 _SetBuffer {\n associatedtype Element\n associatedtype Index\n\n var startIndex: Index { get }\n var endIndex: Index { get }\n func index(after i: Index) -> Index\n func index(for element: Element) -> Index?\n var count: Int { get }\n\n func contains(_ member: Element) -> Bool\n func element(at i: Index) -> Element\n}\n\nextension Set {\n @usableFromInline\n @frozen\n @safe\n internal struct _Variant {\n @usableFromInline\n internal var object: _BridgeStorage<__RawSetStorage>\n\n @inlinable\n @inline(__always)\n init(dummy: ()) {\n#if _pointerBitWidth(_64) && !$Embedded\n unsafe self.object = _BridgeStorage(taggedPayload: 0)\n#elseif _pointerBitWidth(_32) || $Embedded\n self.init(native: _NativeSet())\n#else\n#error("Unknown platform")\n#endif\n }\n\n @inlinable\n @inline(__always)\n init(native: __owned _NativeSet<Element>) {\n unsafe self.object = _BridgeStorage(native: native._storage)\n }\n\n#if _runtime(_ObjC)\n @inlinable\n @inline(__always)\n init(cocoa: __owned __CocoaSet) {\n unsafe self.object = _BridgeStorage(objC: cocoa.object)\n }\n#endif\n }\n}\n\nextension Set._Variant {\n#if _runtime(_ObjC)\n @usableFromInline\n @_transparent\n internal var guaranteedNative: Bool {\n return _canBeClass(Element.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: _NativeSet<Element> {\n get {\n return unsafe _NativeSet(object.unflaggedNativeInstance)\n }\n set {\n self = .init(native: newValue)\n }\n _modify {\n var native = unsafe _NativeSet<Element>(object.unflaggedNativeInstance)\n self = .init(dummy: ())\n defer {\n // This is in a defer block because yield might throw, and we need to\n // preserve Set's storage invariants when that happens.\n unsafe object = .init(native: native._storage)\n }\n yield &native\n }\n }\n\n#if _runtime(_ObjC)\n @inlinable\n internal var asCocoa: __CocoaSet {\n return unsafe __CocoaSet(object.objCInstance)\n }\n#endif\n\n @_alwaysEmitIntoClient\n internal var convertedToNative: _NativeSet<Element> {\n#if _runtime(_ObjC)\n guard isNative else { return _NativeSet<Element>(asCocoa) }\n#endif\n return asNative\n }\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: _NativeSet(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 Set._Variant: _SetBuffer {\n @usableFromInline\n internal typealias Index = Set<Element>.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(for element: Element) -> Index? {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoaElement = _bridgeAnythingToObjectiveC(element)\n guard let index = asCocoa.index(for: cocoaElement) else { return nil }\n return Index(_cocoa: index)\n }\n#endif\n return asNative.index(for: element)\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 internal func contains(_ member: Element) -> Bool {\n#if _runtime(_ObjC)\n guard isNative else {\n return asCocoa.contains(_bridgeAnythingToObjectiveC(member))\n }\n#endif\n return asNative.contains(member)\n }\n\n @inlinable\n @inline(__always)\n internal func element(at index: Index) -> Element {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoaMember = asCocoa.element(at: index._asCocoa)\n return _forceBridgeFromObjectiveC(cocoaMember, Element.self)\n }\n#endif\n return asNative.element(at: index)\n }\n}\n\nextension Set._Variant {\n @inlinable\n internal mutating func update(with value: __owned Element) -> Element? {\n#if _runtime(_ObjC)\n guard isNative else {\n // Make sure we have space for an extra element.\n var native = _NativeSet<Element>(asCocoa, capacity: asCocoa.count + 1)\n let old = native.update(with: value, isUnique: true)\n self = .init(native: native)\n return old\n }\n#endif\n let isUnique = self.isUniquelyReferenced()\n return asNative.update(with: value, isUnique: isUnique)\n }\n\n @inlinable\n internal mutating func insert(\n _ element: __owned Element\n ) -> (inserted: Bool, memberAfterInsert: Element) {\n#if _runtime(_ObjC)\n guard isNative else {\n // Make sure we have space for an extra element.\n let cocoaMember = _bridgeAnythingToObjectiveC(element)\n let cocoa = asCocoa\n if let m = cocoa.member(for: cocoaMember) {\n return (false, _forceBridgeFromObjectiveC(m, Element.self))\n }\n var native = _NativeSet<Element>(cocoa, capacity: cocoa.count + 1)\n native.insertNew(element, isUnique: true)\n self = .init(native: native)\n return (true, element)\n }\n#endif\n let (bucket, found) = asNative.find(element)\n if found {\n return (false, unsafe asNative.uncheckedElement(at: bucket))\n }\n let isUnique = self.isUniquelyReferenced()\n asNative.insertNew(element, at: bucket, isUnique: isUnique)\n return (true, element)\n }\n\n @inlinable\n @discardableResult\n internal mutating func remove(at index: Index) -> Element {\n#if _runtime(_ObjC)\n guard isNative else {\n // We have to migrate the data first. But after we do so, the Cocoa\n // index becomes useless, so get the element first.\n let cocoa = asCocoa\n let cocoaMember = cocoa.member(for: index._asCocoa)\n let nativeMember = _forceBridgeFromObjectiveC(cocoaMember, Element.self)\n return _migrateToNative(cocoa, removing: nativeMember)\n }\n#endif\n let isUnique = isUniquelyReferenced()\n let bucket = asNative.validatedBucket(for: index)\n return unsafe asNative.uncheckedRemove(at: bucket, isUnique: isUnique)\n }\n\n @inlinable\n @discardableResult\n internal mutating func remove(_ member: Element) -> Element? {\n#if _runtime(_ObjC)\n guard isNative else {\n let cocoa = asCocoa\n let cocoaMember = _bridgeAnythingToObjectiveC(member)\n guard cocoa.contains(cocoaMember) else { return nil }\n return _migrateToNative(cocoa, removing: member)\n }\n#endif\n let (bucket, found) = asNative.find(member)\n guard found else { return nil }\n let isUnique = isUniquelyReferenced()\n return unsafe asNative.uncheckedRemove(at: bucket, isUnique: isUnique)\n }\n\n#if _runtime(_ObjC)\n @inlinable\n internal mutating func _migrateToNative(\n _ cocoa: __CocoaSet,\n removing member: Element\n ) -> Element {\n // FIXME(performance): fuse data migration and element deletion into one\n // operation.\n var native = _NativeSet<Element>(cocoa)\n let (bucket, found) = native.find(member)\n _precondition(found, "Bridging did not preserve equality")\n let old = unsafe native.uncheckedRemove(at: bucket, isUnique: true)\n _precondition(member == old, "Bridging did not preserve equality")\n self = .init(native: native)\n return old\n }\n#endif\n\n @inlinable\n internal mutating func removeAll(keepingCapacity keepCapacity: Bool) {\n if !keepCapacity {\n self = .init(native: _NativeSet<Element>())\n return\n }\n guard count > 0 else { return }\n\n#if _runtime(_ObjC)\n guard isNative else {\n self = .init(native: _NativeSet(capacity: asCocoa.count))\n return\n }\n#endif\n let isUnique = isUniquelyReferenced()\n asNative.removeAll(isUnique: isUnique)\n }\n}\n\nextension Set._Variant {\n /// Returns an iterator over the elements.\n ///\n /// - Complexity: O(1).\n @inlinable\n @inline(__always)\n internal __consuming func makeIterator() -> Set<Element>.Iterator {\n#if _runtime(_ObjC)\n guard isNative else {\n return Set.Iterator(_cocoa: asCocoa.makeIterator())\n }\n#endif\n return Set.Iterator(_native: asNative.makeIterator())\n }\n}\n\nextension Set._Variant {\n @_alwaysEmitIntoClient\n internal __consuming func filter(\n _ isIncluded: (Element) throws -> Bool\n ) rethrows -> _NativeSet<Element> {\n#if _runtime(_ObjC)\n guard isNative else {\n var result = _NativeSet<Element>()\n for cocoaElement in asCocoa {\n let nativeElement = _forceBridgeFromObjectiveC(\n cocoaElement, Element.self)\n if try isIncluded(nativeElement) {\n result.insertNew(nativeElement, isUnique: true)\n }\n }\n return result\n }\n#endif\n return try asNative.filter(isIncluded)\n }\n\n @_alwaysEmitIntoClient\n internal __consuming func intersection(\n _ other: Set<Element>\n ) -> _NativeSet<Element> {\n#if _runtime(_ObjC)\n switch (self.isNative, other._variant.isNative) {\n case (true, true):\n return asNative.intersection(other._variant.asNative)\n case (true, false):\n return asNative.genericIntersection(other)\n case (false, false):\n return _NativeSet(asCocoa).genericIntersection(other)\n case (false, true):\n // Note: It is tempting to implement this as `that.intersection(this)`,\n // but intersection isn't symmetric -- the result should only contain\n // elements from `self`.\n let that = other._variant.asNative\n var result = _NativeSet<Element>()\n for cocoaElement in asCocoa {\n let nativeElement = _forceBridgeFromObjectiveC(\n cocoaElement, Element.self)\n if that.contains(nativeElement) {\n result.insertNew(nativeElement, isUnique: true)\n }\n }\n return result\n }\n#else\n return asNative.intersection(other._variant.asNative)\n#endif\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_SetVariant.swift
cpp_apple_swift_stdlib_public_core_SetVariant.swift
Swift
12,194
0.95
0.112903
0.225
react-lib
49
2024-10-08T14:56:56.484739
GPL-3.0
false
daf4cbfc22254a5a38865f93314ef694
//===--- ShadowProtocols.swift - Protocols for decoupled ObjC bridging ----===//\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 foundation\n// classes such as NSArray directly. We _can_, however, use an @objc\n// protocols whose API is "layout-compatible" with that of NSArray,\n// and use unsafe casts to treat NSArray instances as instances of\n// that protocol.\n//\n//===----------------------------------------------------------------------===//\n\n#if _runtime(_ObjC)\nimport SwiftShims\n\n@objc\ninternal protocol _ShadowProtocol {}\n\n/// A shadow for the `NSFastEnumeration` protocol.\n@objc\ninternal protocol _NSFastEnumeration: _ShadowProtocol {\n @objc(countByEnumeratingWithState:objects:count:)\n func countByEnumerating(\n with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,\n objects: UnsafeMutablePointer<AnyObject>?, count: Int\n ) -> Int\n}\n\n/// A shadow for the `NSEnumerator` class.\n@objc\ninternal protocol _NSEnumerator: _ShadowProtocol {\n init()\n func nextObject() -> AnyObject?\n}\n\n/// A token that can be used for `NSZone*`.\ninternal typealias _SwiftNSZone = OpaquePointer\n\n/// A shadow for the `NSCopying` protocol.\n@objc\ninternal protocol _NSCopying: _ShadowProtocol {\n @objc(copyWithZone:)\n func copy(with zone: _SwiftNSZone?) -> AnyObject\n}\n\n/// A shadow for the "core operations" of NSArray.\n///\n/// Covers a set of operations everyone needs to implement in order to\n/// be a useful `NSArray` subclass.\n@unsafe_no_objc_tagged_pointer @objc\ninternal protocol _NSArrayCore: _NSCopying, _NSFastEnumeration {\n\n @objc(objectAtIndex:)\n func objectAt(_ index: Int) -> AnyObject\n\n func getObjects(_: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange)\n\n @objc(countByEnumeratingWithState:objects:count:)\n override func countByEnumerating(\n with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,\n objects: UnsafeMutablePointer<AnyObject>?, count: Int\n ) -> Int\n\n var count: Int { get }\n}\n\n/// A shadow for the "core operations" of NSDictionary.\n///\n/// Covers a set of operations everyone needs to implement in order to\n/// be a useful `NSDictionary` subclass.\n@objc\ninternal protocol _NSDictionaryCore: _NSCopying, _NSFastEnumeration {\n // The following methods should be overridden when implementing an\n // NSDictionary subclass.\n\n // The designated initializer of `NSDictionary`.\n init(\n objects: UnsafePointer<AnyObject?>,\n forKeys: UnsafeRawPointer, count: Int)\n\n var count: Int { get }\n\n @objc(objectForKey:)\n func object(forKey aKey: AnyObject) -> AnyObject?\n\n func keyEnumerator() -> _NSEnumerator\n\n // We also override the following methods for efficiency.\n\n @objc(copyWithZone:)\n override func copy(with zone: _SwiftNSZone?) -> AnyObject\n\n @objc(getObjects:andKeys:count:)\n func getObjects(\n _ objects: UnsafeMutablePointer<AnyObject>?,\n andKeys keys: UnsafeMutablePointer<AnyObject>?,\n count: Int\n )\n\n @objc(countByEnumeratingWithState:objects:count:)\n override func countByEnumerating(\n with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,\n objects: UnsafeMutablePointer<AnyObject>?, count: Int\n ) -> Int\n}\n\n/// A shadow for the API of `NSDictionary` we will use in the core\n/// stdlib.\n///\n/// `NSDictionary` operations, in addition to those on\n/// `_NSDictionaryCore`, that we need to use from the core stdlib.\n/// Distinct from `_NSDictionaryCore` because we don't want to be\n/// forced to implement operations that `NSDictionary` already\n/// supplies.\n@unsafe_no_objc_tagged_pointer @objc\ninternal protocol _NSDictionary: _NSDictionaryCore {\n // Note! This API's type is different from what is imported by the clang\n // importer.\n override func getObjects(\n _ objects: UnsafeMutablePointer<AnyObject>?,\n andKeys keys: UnsafeMutablePointer<AnyObject>?,\n count: Int)\n}\n\n/// A shadow for the "core operations" of NSSet.\n///\n/// Covers a set of operations everyone needs to implement in order to\n/// be a useful `NSSet` subclass.\n@objc\ninternal protocol _NSSetCore: _NSCopying, _NSFastEnumeration {\n\n // The following methods should be overridden when implementing an\n // NSSet subclass.\n\n // The designated initializer of `NSSet`.\n init(objects: UnsafePointer<AnyObject?>, count: Int)\n\n var count: Int { get }\n func member(_ object: AnyObject) -> AnyObject?\n func objectEnumerator() -> _NSEnumerator\n\n // We also override the following methods for efficiency.\n\n @objc(copyWithZone:)\n override func copy(with zone: _SwiftNSZone?) -> AnyObject\n\n @objc(countByEnumeratingWithState:objects:count:)\n override func countByEnumerating(\n with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,\n objects: UnsafeMutablePointer<AnyObject>?, count: Int\n ) -> Int\n}\n\n/// A shadow for the API of NSSet we will use in the core\n/// stdlib.\n///\n/// `NSSet` operations, in addition to those on\n/// `_NSSetCore`, that we need to use from the core stdlib.\n/// Distinct from `_NSSetCore` because we don't want to be\n/// forced to implement operations that `NSSet` already\n/// supplies.\n@unsafe_no_objc_tagged_pointer @objc\ninternal protocol _NSSet: _NSSetCore {\n @objc(getObjects:count:) func getObjects(\n _ buffer: UnsafeMutablePointer<AnyObject>,\n count: Int\n )\n\n @objc(getObjects:) func getObjects(\n _ buffer: UnsafeMutablePointer<AnyObject>\n )\n}\n\n/// A shadow for the API of NSNumber we will use in the core\n/// stdlib.\n@objc\ninternal protocol _NSNumber {\n var doubleValue: Double { get }\n var floatValue: Float { get }\n var unsignedLongLongValue: UInt64 { get }\n var longLongValue: Int64 { get }\n var objCType: UnsafePointer<Int8> { get }\n}\n\n#else\n\ninternal protocol _NSSetCore {}\ninternal protocol _NSDictionaryCore {}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_ShadowProtocols.swift
cpp_apple_swift_stdlib_public_core_ShadowProtocols.swift
Swift
6,268
0.95
0.085
0.409639
vue-tools
624
2024-02-29T05:14:15.538861
MIT
false
82d986f20646c62802bc2f18df5bc081
//===----------------------------------------------------------------------===//\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/// Additions to 'SwiftShims' that can be written in Swift.\n///\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\n#if _runtime(_ObjC)\n@inlinable\ninternal func _makeSwiftNSFastEnumerationState()\n -> _SwiftNSFastEnumerationState {\n return unsafe _SwiftNSFastEnumerationState(\n state: 0, itemsPtr: nil, mutationsPtr: nil,\n extra: (0, 0, 0, 0, 0))\n}\n\n/// A dummy value to be used as the target for `mutationsPtr` in fast\n/// enumeration implementations.\n@usableFromInline\ninternal var _fastEnumerationStorageMutationsTarget: CUnsignedLong = 0\n\n/// A dummy pointer to be used as `mutationsPtr` in fast enumeration\n/// implementations.\n@usableFromInline\ninternal let _fastEnumerationStorageMutationsPtr =\n unsafe UnsafeMutablePointer<CUnsignedLong>(Builtin.addressof(&_fastEnumerationStorageMutationsTarget))\n#endif\n\n@usableFromInline @_alwaysEmitIntoClient\ninternal func _mallocSize(ofAllocation ptr: UnsafeRawPointer) -> Int? {\n return unsafe _swift_stdlib_has_malloc_size() ? _swift_stdlib_malloc_size(ptr) : nil\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Shims.swift
cpp_apple_swift_stdlib_public_core_Shims.swift
Swift
1,597
0.95
0.093023
0.552632
awesome-app
44
2025-04-23T07:42:33.051069
MIT
false
54aed811a702ba9bab33631446a5f6f4
//===--- SIMDVector.swift -------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2018 - 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\ninfix operator .==: ComparisonPrecedence\ninfix operator .!=: ComparisonPrecedence\ninfix operator .<: ComparisonPrecedence\ninfix operator .<=: ComparisonPrecedence\ninfix operator .>: ComparisonPrecedence\ninfix operator .>=: ComparisonPrecedence\n\ninfix operator .&: LogicalConjunctionPrecedence\ninfix operator .^: LogicalDisjunctionPrecedence\ninfix operator .|: LogicalDisjunctionPrecedence\ninfix operator .&=: AssignmentPrecedence\ninfix operator .^=: AssignmentPrecedence\ninfix operator .|=: AssignmentPrecedence\nprefix operator .!\n\n/// A type that can function as storage for a SIMD vector type.\n///\n/// The `SIMDStorage` protocol defines a storage layout and provides\n/// elementwise accesses. Computational operations are defined on the `SIMD`\n/// protocol, which refines this protocol, and on the concrete types that\n/// conform to `SIMD`.\npublic protocol SIMDStorage {\n /// The type of scalars in the vector space.\n #if $Embedded\n associatedtype Scalar: Hashable\n #else\n associatedtype Scalar: Codable, Hashable\n #endif\n\n /// The number of scalars, or elements, in the vector.\n var scalarCount: Int { get }\n \n /// Creates a vector with zero in all lanes.\n init()\n \n /// Accesses the element at the specified index.\n ///\n /// - Parameter index: The index of the element to access. `index` must be in\n /// the range `0..<scalarCount`.\n subscript(index: Int) -> Scalar { get set }\n}\n\nextension SIMDStorage {\n /// The number of scalars, or elements, in a vector of this type.\n @_alwaysEmitIntoClient\n public static var scalarCount: Int {\n // Wouldn't it make more sense to define the instance var in terms of the\n // static var? Yes, probably, but by doing it this way we make the static\n // var backdeployable.\n return Self().scalarCount\n }\n}\n\n/// A type that can be used as an element in a SIMD vector.\npublic protocol SIMDScalar : BitwiseCopyable {\n associatedtype SIMDMaskScalar: SIMDScalar & FixedWidthInteger & SignedInteger\n where SIMDMaskScalar.SIMDMaskScalar == SIMDMaskScalar\n associatedtype SIMD2Storage: SIMDStorage where SIMD2Storage.Scalar == Self\n associatedtype SIMD4Storage: SIMDStorage where SIMD4Storage.Scalar == Self\n associatedtype SIMD8Storage: SIMDStorage where SIMD8Storage.Scalar == Self\n associatedtype SIMD16Storage: SIMDStorage where SIMD16Storage.Scalar == Self\n associatedtype SIMD32Storage: SIMDStorage where SIMD32Storage.Scalar == Self\n associatedtype SIMD64Storage: SIMDStorage where SIMD64Storage.Scalar == Self\n}\n\n#if $Embedded\n/// A SIMD vector of a fixed number of elements.\npublic protocol SIMD<Scalar>:\n SIMDStorage,\n Hashable,\n ExpressibleByArrayLiteral\n{\n /// The mask type resulting from pointwise comparisons of this vector type.\n associatedtype MaskStorage: SIMD\n where MaskStorage.Scalar: FixedWidthInteger & SignedInteger\n}\n\n#else\n\n/// A SIMD vector of a fixed number of elements.\npublic protocol SIMD<Scalar>:\n SIMDStorage,\n Codable,\n Hashable,\n CustomStringConvertible,\n ExpressibleByArrayLiteral\n{\n /// The mask type resulting from pointwise comparisons of this vector type.\n associatedtype MaskStorage: SIMD\n where MaskStorage.Scalar: FixedWidthInteger & SignedInteger\n}\n\n#endif\n\nextension SIMD {\n /// The valid indices for subscripting the vector.\n @_transparent\n public var indices: Range<Int> {\n return 0 ..< scalarCount\n }\n \n /// A vector with the specified value in all lanes.\n @_transparent\n public init(repeating value: Scalar) {\n self.init()\n for i in indices { self[i] = value }\n }\n \n /// Returns a Boolean value indicating whether two vectors are equal.\n @_transparent\n public static func ==(a: Self, b: Self) -> Bool {\n var result = true\n for i in a.indices { result = result && a[i] == b[i] }\n return result\n }\n \n /// Hashes the elements of the vector using the given hasher.\n @inlinable\n public func hash(into hasher: inout Hasher) {\n for i in indices { hasher.combine(self[i]) }\n }\n\n#if !$Embedded\n\n /// Encodes the scalars of this vector into the given encoder in an unkeyed\n /// container.\n ///\n /// This function throws an error if any values are invalid for the given\n /// encoder's format.\n ///\n /// - Parameter encoder: The encoder to write data to.\n public func encode(to encoder: Encoder) throws {\n var container = encoder.unkeyedContainer()\n for i in indices {\n try container.encode(self[i])\n }\n }\n\n /// Creates a new vector by decoding scalars from the given decoder.\n ///\n /// This initializer throws an error if reading from the decoder fails, or\n /// if the data read is corrupted or otherwise invalid.\n ///\n /// - Parameter decoder: The decoder to read data from.\n public init(from decoder: Decoder) throws {\n self.init()\n var container = try decoder.unkeyedContainer()\n guard container.count == scalarCount else {\n throw DecodingError.dataCorrupted(\n DecodingError.Context(\n codingPath: decoder.codingPath,\n debugDescription: "Expected vector with exactly \(scalarCount) elements."\n )\n )\n }\n for i in indices {\n self[i] = try container.decode(Scalar.self)\n }\n }\n\n /// A textual description of the vector.\n public var description: String {\n get {\n return "\(Self.self)(" + indices.map({"\(self[$0])"}).joined(separator: ", ") + ")"\n }\n }\n\n#endif\n\n /// A vector mask with the result of a pointwise equality comparison.\n ///\n /// Equivalent to:\n /// ```\n /// var result = SIMDMask<MaskStorage>()\n /// for i in result.indices {\n /// result[i] = a[i] == b[i]\n /// }\n /// ```\n @_transparent\n public static func .==(a: Self, b: Self) -> SIMDMask<MaskStorage> {\n var result = SIMDMask<MaskStorage>()\n for i in result.indices { result[i] = a[i] == b[i] }\n return result\n }\n \n /// A vector mask with the result of a pointwise inequality comparison.\n ///\n /// Equivalent to:\n /// ```\n /// var result = SIMDMask<MaskStorage>()\n /// for i in result.indices {\n /// result[i] = a[i] != b[i]\n /// }\n /// ```\n @_transparent\n public static func .!=(a: Self, b: Self) -> SIMDMask<MaskStorage> {\n var result = SIMDMask<MaskStorage>()\n for i in result.indices { result[i] = a[i] != b[i] }\n return result\n }\n \n /// Replaces elements of this vector with elements of `other` in the lanes\n /// where `mask` is `true`.\n ///\n /// Equivalent to:\n /// ```\n /// for i in indices {\n /// if mask[i] { self[i] = other[i] }\n /// }\n /// ```\n @_transparent\n public mutating func replace(with other: Self, where mask: SIMDMask<MaskStorage>) {\n for i in indices { self[i] = mask[i] ? other[i] : self[i] }\n }\n \n /// Creates a vector from the specified elements.\n ///\n /// - Parameter scalars: The elements to use in the vector. `scalars` must\n /// have the same number of elements as the vector type.\n @inlinable\n public init(arrayLiteral scalars: Scalar...) {\n self.init(scalars)\n }\n \n /// Creates a vector from the given sequence.\n ///\n /// - Precondition: `scalars` must have the same number of elements as the\n /// vector type.\n ///\n /// - Parameter scalars: The elements to use in the vector.\n @inlinable\n public init<S: Sequence>(_ scalars: S) where S.Element == Scalar {\n self.init()\n var index = 0\n for scalar in scalars {\n if index == scalarCount {\n _preconditionFailure("Too many elements in sequence.")\n }\n self[index] = scalar\n index += 1\n }\n if index < scalarCount {\n _preconditionFailure("Not enough elements in sequence.")\n }\n }\n \n /// Extracts the scalars at specified indices to form a SIMD2.\n ///\n /// The elements of the index vector are wrapped modulo the count of elements\n /// in this vector. Because of this, the index is always in-range and no trap\n /// can occur.\n @_alwaysEmitIntoClient\n public subscript<Index>(index: SIMD2<Index>) -> SIMD2<Scalar>\n where Index: FixedWidthInteger {\n var result = SIMD2<Scalar>()\n for i in result.indices {\n result[i] = self[Int(index[i]) % scalarCount]\n }\n return result\n }\n \n /// Extracts the scalars at specified indices to form a SIMD3.\n ///\n /// The elements of the index vector are wrapped modulo the count of elements\n /// in this vector. Because of this, the index is always in-range and no trap\n /// can occur.\n @_alwaysEmitIntoClient\n public subscript<Index>(index: SIMD3<Index>) -> SIMD3<Scalar>\n where Index: FixedWidthInteger {\n var result = SIMD3<Scalar>()\n for i in result.indices {\n result[i] = self[Int(index[i]) % scalarCount]\n }\n return result\n }\n \n /// Extracts the scalars at specified indices to form a SIMD4.\n ///\n /// The elements of the index vector are wrapped modulo the count of elements\n /// in this vector. Because of this, the index is always in-range and no trap\n /// can occur.\n @_alwaysEmitIntoClient\n public subscript<Index>(index: SIMD4<Index>) -> SIMD4<Scalar>\n where Index: FixedWidthInteger {\n var result = SIMD4<Scalar>()\n for i in result.indices {\n result[i] = self[Int(index[i]) % scalarCount]\n }\n return result\n }\n \n /// Extracts the scalars at specified indices to form a SIMD8.\n ///\n /// The elements of the index vector are wrapped modulo the count of elements\n /// in this vector. Because of this, the index is always in-range and no trap\n /// can occur.\n @_alwaysEmitIntoClient\n public subscript<Index>(index: SIMD8<Index>) -> SIMD8<Scalar>\n where Index: FixedWidthInteger {\n var result = SIMD8<Scalar>()\n for i in result.indices {\n result[i] = self[Int(index[i]) % scalarCount]\n }\n return result\n }\n \n /// Extracts the scalars at specified indices to form a SIMD16.\n ///\n /// The elements of the index vector are wrapped modulo the count of elements\n /// in this vector. Because of this, the index is always in-range and no trap\n /// can occur.\n @_alwaysEmitIntoClient\n public subscript<Index>(index: SIMD16<Index>) -> SIMD16<Scalar>\n where Index: FixedWidthInteger {\n var result = SIMD16<Scalar>()\n for i in result.indices {\n result[i] = self[Int(index[i]) % scalarCount]\n }\n return result\n }\n \n /// Extracts the scalars at specified indices to form a SIMD32.\n ///\n /// The elements of the index vector are wrapped modulo the count of elements\n /// in this vector. Because of this, the index is always in-range and no trap\n /// can occur.\n @_alwaysEmitIntoClient\n public subscript<Index>(index: SIMD32<Index>) -> SIMD32<Scalar>\n where Index: FixedWidthInteger {\n var result = SIMD32<Scalar>()\n for i in result.indices {\n result[i] = self[Int(index[i]) % scalarCount]\n }\n return result\n }\n \n /// Extracts the scalars at specified indices to form a SIMD64.\n ///\n /// The elements of the index vector are wrapped modulo the count of elements\n /// in this vector. Because of this, the index is always in-range and no trap\n /// can occur.\n @_alwaysEmitIntoClient\n public subscript<Index>(index: SIMD64<Index>) -> SIMD64<Scalar>\n where Index: FixedWidthInteger {\n var result = SIMD64<Scalar>()\n for i in result.indices {\n result[i] = self[Int(index[i]) % scalarCount]\n }\n return result\n }\n}\n\n// Implementations of comparison operations. These should eventually all\n// be replaced with @_semantics to lower directly to vector IR nodes.\nextension SIMD where Scalar: Comparable {\n /// Returns a vector mask with the result of a pointwise less than\n /// comparison.\n @_transparent\n public static func .<(a: Self, b: Self) -> SIMDMask<MaskStorage> {\n var result = SIMDMask<MaskStorage>()\n for i in result.indices { result[i] = a[i] < b[i] }\n return result\n }\n \n /// Returns a vector mask with the result of a pointwise less than or equal\n /// comparison.\n @_transparent\n public static func .<=(a: Self, b: Self) -> SIMDMask<MaskStorage> {\n var result = SIMDMask<MaskStorage>()\n for i in result.indices { result[i] = a[i] <= b[i] }\n return result\n }\n \n /// The least element in the vector.\n @_alwaysEmitIntoClient\n public func min() -> Scalar {\n return indices.reduce(into: self[0]) { $0 = Swift.min($0, self[$1]) }\n }\n \n /// The greatest element in the vector.\n @_alwaysEmitIntoClient\n public func max() -> Scalar {\n return indices.reduce(into: self[0]) { $0 = Swift.max($0, self[$1]) }\n }\n}\n\n// These operations should never need @_semantics; they should be trivial\n// wrappers around the core operations defined above.\nextension SIMD {\n /// Returns a vector mask with the result of a pointwise equality comparison.\n @_transparent\n public static func .==(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {\n return Self(repeating: a) .== b\n }\n\n /// Returns a vector mask with the result of a pointwise inequality comparison.\n @_transparent\n public static func .!=(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {\n return Self(repeating: a) .!= b\n }\n\n /// Returns a vector mask with the result of a pointwise equality comparison.\n @_transparent\n public static func .==(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {\n return a .== Self(repeating: b)\n }\n\n /// Returns a vector mask with the result of a pointwise inequality comparison.\n @_transparent\n public static func .!=(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {\n return a .!= Self(repeating: b)\n }\n \n /// Replaces elements of this vector with `other` in the lanes where `mask`\n /// is `true`.\n ///\n /// Equivalent to:\n /// ```\n /// for i in indices {\n /// if mask[i] { self[i] = other }\n /// }\n /// ```\n @_transparent\n public mutating func replace(with other: Scalar, where mask: SIMDMask<MaskStorage>) {\n replace(with: Self(repeating: other), where: mask)\n }\n \n /// Returns a copy of this vector, with elements replaced by elements of\n /// `other` in the lanes where `mask` is `true`.\n ///\n /// Equivalent to:\n /// ```\n /// var result = Self()\n /// for i in indices {\n /// result[i] = mask[i] ? other[i] : self[i]\n /// }\n /// ```\n @_transparent\n public func replacing(with other: Self, where mask: SIMDMask<MaskStorage>) -> Self {\n var result = self\n result.replace(with: other, where: mask)\n return result\n }\n \n /// Returns a copy of this vector, with elements `other` in the lanes where\n /// `mask` is `true`.\n ///\n /// Equivalent to:\n /// ```\n /// var result = Self()\n /// for i in indices {\n /// result[i] = mask[i] ? other : self[i]\n /// }\n /// ```\n @_transparent\n public func replacing(with other: Scalar, where mask: SIMDMask<MaskStorage>) -> Self {\n return replacing(with: Self(repeating: other), where: mask)\n }\n}\n\nextension SIMD where Scalar: Comparable {\n /// Returns a vector mask with the result of a pointwise greater than or\n /// equal comparison.\n @_transparent\n public static func .>=(a: Self, b: Self) -> SIMDMask<MaskStorage> {\n return b .<= a\n }\n\n /// Returns a vector mask with the result of a pointwise greater than\n /// comparison.\n @_transparent\n public static func .>(a: Self, b: Self) -> SIMDMask<MaskStorage> {\n return b .< a\n }\n\n /// Returns a vector mask with the result of a pointwise less than comparison.\n @_transparent\n public static func .<(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {\n return Self(repeating: a) .< b\n }\n\n /// Returns a vector mask with the result of a pointwise less than or equal\n /// comparison.\n @_transparent\n public static func .<=(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {\n return Self(repeating: a) .<= b\n }\n\n /// Returns a vector mask with the result of a pointwise greater than or\n /// equal comparison.\n @_transparent\n public static func .>=(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {\n return Self(repeating: a) .>= b\n }\n\n /// Returns a vector mask with the result of a pointwise greater than\n /// comparison.\n @_transparent\n public static func .>(a: Scalar, b: Self) -> SIMDMask<MaskStorage> {\n return Self(repeating: a) .> b\n }\n\n /// Returns a vector mask with the result of a pointwise less than comparison.\n @_transparent\n public static func .<(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {\n return a .< Self(repeating: b)\n }\n\n /// Returns a vector mask with the result of a pointwise less than or equal\n /// comparison.\n @_transparent\n public static func .<=(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {\n return a .<= Self(repeating: b)\n }\n \n /// Returns a vector mask with the result of a pointwise greater than or\n /// equal comparison.\n @_transparent\n public static func .>=(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {\n return a .>= Self(repeating: b)\n }\n \n /// Returns a vector mask with the result of a pointwise greater than\n /// comparison.\n @_transparent\n public static func .>(a: Self, b: Scalar) -> SIMDMask<MaskStorage> {\n return a .> Self(repeating: b)\n }\n \n @_alwaysEmitIntoClient\n public mutating func clamp(lowerBound: Self, upperBound: Self) {\n self = self.clamped(lowerBound: lowerBound, upperBound: upperBound)\n }\n\n @_alwaysEmitIntoClient\n public func clamped(lowerBound: Self, upperBound: Self) -> Self {\n return pointwiseMin(upperBound, pointwiseMax(lowerBound, self))\n }\n}\n\nextension SIMD where Scalar: FixedWidthInteger {\n /// A vector with zero in all lanes.\n @_transparent\n public static var zero: Self {\n return Self()\n }\n \n /// A vector with one in all lanes.\n @_alwaysEmitIntoClient\n public static var one: Self {\n return Self(repeating: 1)\n }\n \n /// Returns a vector with random values from within the specified range in\n /// all lanes, using the given generator as a source for randomness.\n @inlinable\n public static func random<T: RandomNumberGenerator>(\n in range: Range<Scalar>,\n using generator: inout T\n ) -> Self {\n var result = Self()\n for i in result.indices {\n result[i] = Scalar.random(in: range, using: &generator)\n }\n return result\n }\n \n /// Returns a vector with random values from within the specified range in\n /// all lanes.\n @inlinable\n public static func random(in range: Range<Scalar>) -> Self {\n var g = SystemRandomNumberGenerator()\n return Self.random(in: range, using: &g)\n }\n\n /// Returns a vector with random values from within the specified range in\n /// all lanes, using the given generator as a source for randomness.\n @inlinable\n public static func random<T: RandomNumberGenerator>(\n in range: ClosedRange<Scalar>,\n using generator: inout T\n ) -> Self {\n var result = Self()\n for i in result.indices {\n result[i] = Scalar.random(in: range, using: &generator)\n }\n return result\n }\n \n /// Returns a vector with random values from within the specified range in\n /// all lanes.\n @inlinable\n public static func random(in range: ClosedRange<Scalar>) -> Self {\n var g = SystemRandomNumberGenerator()\n return Self.random(in: range, using: &g)\n }\n\n}\n\nextension SIMD where Scalar: FloatingPoint {\n /// A vector with zero in all lanes.\n @_transparent\n public static var zero: Self {\n return Self()\n }\n \n /// A vector with one in all lanes.\n @_alwaysEmitIntoClient\n public static var one: Self {\n return Self(repeating: 1)\n }\n \n @_alwaysEmitIntoClient\n public mutating func clamp(lowerBound: Self, upperBound: Self) {\n self = self.clamped(lowerBound: lowerBound, upperBound: upperBound)\n }\n\n @_alwaysEmitIntoClient\n public func clamped(lowerBound: Self, upperBound: Self) -> Self {\n return pointwiseMin(upperBound, pointwiseMax(lowerBound, self))\n }\n}\n\nextension SIMD\nwhere Scalar: BinaryFloatingPoint, Scalar.RawSignificand: FixedWidthInteger {\n /// Returns a vector with random values from within the specified range in\n /// all lanes, using the given generator as a source for randomness.\n @inlinable\n public static func random<T: RandomNumberGenerator>(\n in range: Range<Scalar>,\n using generator: inout T\n ) -> Self {\n var result = Self()\n for i in result.indices {\n result[i] = Scalar.random(in: range, using: &generator)\n }\n return result\n }\n \n /// Returns a vector with random values from within the specified range in\n /// all lanes.\n @inlinable\n public static func random(in range: Range<Scalar>) -> Self {\n var g = SystemRandomNumberGenerator()\n return Self.random(in: range, using: &g)\n }\n \n /// Returns a vector with random values from within the specified range in\n /// all lanes, using the given generator as a source for randomness.\n @inlinable\n public static func random<T: RandomNumberGenerator>(\n in range: ClosedRange<Scalar>,\n using generator: inout T\n ) -> Self {\n var result = Self()\n for i in result.indices {\n result[i] = Scalar.random(in: range, using: &generator)\n }\n return result\n }\n \n /// Returns a vector with random values from within the specified range in\n /// all lanes.\n @inlinable\n public static func random(in range: ClosedRange<Scalar>) -> Self {\n var g = SystemRandomNumberGenerator()\n return Self.random(in: range, using: &g)\n }\n}\n\n@frozen\npublic struct SIMDMask<Storage>: SIMD\n where Storage: SIMD,\n Storage.Scalar: FixedWidthInteger & SignedInteger {\n \n public var _storage: Storage\n \n public typealias MaskStorage = Storage\n \n public typealias Scalar = Bool\n\n @_transparent\n public init() {\n _storage = Storage()\n }\n\n @_transparent\n public var scalarCount: Int {\n return _storage.scalarCount\n }\n\n @_transparent\n public init(_ _storage: Storage) {\n self._storage = _storage\n }\n \n public subscript(index: Int) -> Bool {\n @_transparent\n get {\n _precondition(indices.contains(index))\n return _storage[index] < 0\n }\n @_transparent\n set {\n _precondition(indices.contains(index))\n _storage[index] = newValue ? -1 : 0\n }\n }\n}\n\nextension SIMDMask: Sendable where Storage: Sendable {}\n\nextension SIMDMask {\n /// Returns a vector mask with `true` or `false` randomly assigned in each\n /// lane, using the given generator as a source for randomness.\n @inlinable\n public static func random<T: RandomNumberGenerator>(using generator: inout T) -> SIMDMask {\n var result = SIMDMask()\n for i in result.indices { result[i] = Bool.random(using: &generator) }\n return result\n }\n \n /// Returns a vector mask with `true` or `false` randomly assigned in each\n /// lane.\n @inlinable\n public static func random() -> SIMDMask {\n var g = SystemRandomNumberGenerator()\n return SIMDMask.random(using: &g)\n }\n}\n\n// Implementations of integer operations. These should eventually all\n// be replaced with @_semantics to lower directly to vector IR nodes.\nextension SIMD where Scalar: FixedWidthInteger {\n @_transparent\n public var leadingZeroBitCount: Self {\n var result = Self()\n for i in indices { result[i] = Scalar(self[i].leadingZeroBitCount) }\n return result\n }\n \n @_transparent\n public var trailingZeroBitCount: Self {\n var result = Self()\n for i in indices { result[i] = Scalar(self[i].trailingZeroBitCount) }\n return result\n }\n \n @_transparent\n public var nonzeroBitCount: Self {\n var result = Self()\n for i in indices { result[i] = Scalar(self[i].nonzeroBitCount) }\n return result\n }\n \n @_transparent\n public static prefix func ~(a: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = ~a[i] }\n return result\n }\n \n @_transparent\n public static func &(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] & b[i] }\n return result\n }\n \n @_transparent\n public static func ^(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] ^ b[i] }\n return result\n }\n \n @_transparent\n public static func |(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] | b[i] }\n return result\n }\n \n @_transparent\n public static func &<<(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] &<< b[i] }\n return result\n }\n \n @_transparent\n public static func &>>(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] &>> b[i] }\n return result\n }\n \n @_transparent\n public static func &+(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] &+ b[i] }\n return result\n }\n \n @_transparent\n public static func &-(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] &- b[i] }\n return result\n }\n \n @_transparent\n public static func &*(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] &* b[i] }\n return result\n }\n \n @_transparent\n public static func /(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] / b[i] }\n return result\n }\n \n @_transparent\n public static func %(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] % b[i] }\n return result\n }\n \n /// Returns the sum of the scalars in the vector, computed with wrapping\n /// addition.\n ///\n /// Equivalent to `indices.reduce(into: 0) { $0 &+= self[$1] }`.\n @_alwaysEmitIntoClient\n public func wrappedSum() -> Scalar {\n var result: Scalar = 0\n for i in indices {\n result &+= self[i]\n }\n return result\n }\n}\n\n// Implementations of floating-point operations. These should eventually all\n// be replaced with @_semantics to lower directly to vector IR nodes.\nextension SIMD where Scalar: FloatingPoint {\n @_transparent\n public static func +(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] + b[i] }\n return result\n }\n \n @_transparent\n public static func -(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] - b[i] }\n return result\n }\n \n @_transparent\n public static func *(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] * b[i] }\n return result\n }\n \n @_transparent\n public static func /(a: Self, b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = a[i] / b[i] }\n return result\n }\n \n @_transparent\n public func addingProduct(_ a: Self, _ b: Self) -> Self {\n var result = Self()\n for i in result.indices { result[i] = self[i].addingProduct(a[i], b[i]) }\n return result\n }\n \n @_transparent\n public func squareRoot( ) -> Self {\n var result = Self()\n for i in result.indices { result[i] = self[i].squareRoot() }\n return result\n }\n \n /// A vector formed by rounding each lane of the source vector to an integral\n /// value according to the specified rounding `rule`.\n @_transparent\n public func rounded(_ rule: FloatingPointRoundingRule) -> Self {\n var result = Self()\n for i in result.indices { result[i] = self[i].rounded(rule) }\n return result\n }\n \n /// The least scalar in the vector.\n @_alwaysEmitIntoClient\n public func min() -> Scalar {\n return indices.reduce(into: self[0]) { $0 = Scalar.minimum($0, self[$1]) }\n }\n \n /// The greatest scalar in the vector.\n @_alwaysEmitIntoClient\n public func max() -> Scalar {\n return indices.reduce(into: self[0]) { $0 = Scalar.maximum($0, self[$1]) }\n }\n \n /// The sum of the scalars in the vector.\n @_alwaysEmitIntoClient\n public func sum() -> Scalar {\n // Implementation note: this eventually be defined to lower to either\n // llvm.experimental.vector.reduce.fadd or an explicit tree-sum. Open-\n // coding the tree sum is problematic, we probably need to define a\n // Swift Builtin to support it.\n //\n // Use -0 so that LLVM can optimize away initial value + self[0].\n var result = -Scalar.zero\n for i in indices {\n result += self[i]\n }\n return result\n }\n}\n\nextension SIMDMask {\n /// A vector mask that is the pointwise logical negation of the input.\n ///\n /// Equivalent to:\n /// ```\n /// var result = SIMDMask<${Vector}>()\n /// for i in result.indices {\n /// result[i] = !a[i]\n /// }\n /// ```\n @_transparent\n public static prefix func .!(a: SIMDMask) -> SIMDMask {\n return SIMDMask(~a._storage)\n }\n \n /// A vector mask that is the pointwise logical conjunction of the inputs.\n ///\n /// Equivalent to:\n /// ```\n /// var result = SIMDMask<${Vector}>()\n /// for i in result.indices {\n /// result[i] = a[i] && b[i]\n /// }\n /// ```\n ///\n /// Note that unlike the scalar `&&` operator, the SIMD `.&` operator\n /// always fully evaluates both arguments.\n @_transparent\n public static func .&(a: SIMDMask, b: SIMDMask) -> SIMDMask {\n return SIMDMask(a._storage & b._storage)\n }\n \n /// A vector mask that is the pointwise exclusive or of the inputs.\n ///\n /// Equivalent to:\n /// ```\n /// var result = SIMDMask<${Vector}>()\n /// for i in result.indices {\n /// result[i] = a[i] != b[i]\n /// }\n /// ```\n @_transparent\n public static func .^(a: SIMDMask, b: SIMDMask) -> SIMDMask {\n return SIMDMask(a._storage ^ b._storage)\n }\n \n /// A vector mask that is the pointwise logical disjunction of the inputs.\n ///\n /// Equivalent to:\n /// ```\n /// var result = SIMDMask<${Vector}>()\n /// for i in result.indices {\n /// result[i] = a[i] || b[i]\n /// }\n /// ```\n ///\n /// Note that unlike the scalar `||` operator, the SIMD `.|` operator\n /// always fully evaluates both arguments.\n @_transparent\n public static func .|(a: SIMDMask, b: SIMDMask) -> SIMDMask {\n return SIMDMask(a._storage | b._storage)\n }\n}\n\n// These operations should never need @_semantics; they should be trivial\n// wrappers around the core operations defined above.\nextension SIMD where Scalar: FixedWidthInteger {\n \n @_transparent\n public static func &(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) & b\n }\n \n @_transparent\n public static func ^(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) ^ b\n }\n \n @_transparent\n public static func |(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) | b\n }\n \n @_transparent\n public static func &<<(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) &<< b\n }\n \n @_transparent\n public static func &>>(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) &>> b\n }\n \n @_transparent\n public static func &+(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) &+ b\n }\n \n @_transparent\n public static func &-(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) &- b\n }\n \n @_transparent\n public static func &*(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) &* b\n }\n \n @_transparent\n public static func /(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) / b\n }\n \n @_transparent\n public static func %(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) % b\n }\n \n @_transparent\n public static func &(a: Self, b: Scalar) -> Self {\n return a & Self(repeating: b)\n }\n \n @_transparent\n public static func ^(a: Self, b: Scalar) -> Self {\n return a ^ Self(repeating: b)\n }\n \n @_transparent\n public static func |(a: Self, b: Scalar) -> Self {\n return a | Self(repeating: b)\n }\n \n @_transparent\n public static func &<<(a: Self, b: Scalar) -> Self {\n return a &<< Self(repeating: b)\n }\n \n @_transparent\n public static func &>>(a: Self, b: Scalar) -> Self {\n return a &>> Self(repeating: b)\n }\n \n @_transparent\n public static func &+(a: Self, b: Scalar) -> Self {\n return a &+ Self(repeating: b)\n }\n \n @_transparent\n public static func &-(a: Self, b: Scalar) -> Self {\n return a &- Self(repeating: b)\n }\n \n @_transparent\n public static func &*(a: Self, b: Scalar) -> Self {\n return a &* Self(repeating: b)\n }\n \n @_transparent\n public static func /(a: Self, b: Scalar) -> Self {\n return a / Self(repeating: b)\n }\n \n @_transparent\n public static func %(a: Self, b: Scalar) -> Self {\n return a % Self(repeating: b)\n }\n \n @_transparent\n public static func &=(a: inout Self, b: Self) {\n a = a & b\n }\n \n @_transparent\n public static func ^=(a: inout Self, b: Self) {\n a = a ^ b\n }\n \n @_transparent\n public static func |=(a: inout Self, b: Self) {\n a = a | b\n }\n \n @_transparent\n public static func &<<=(a: inout Self, b: Self) {\n a = a &<< b\n }\n \n @_transparent\n public static func &>>=(a: inout Self, b: Self) {\n a = a &>> b\n }\n \n @_transparent\n public static func &+=(a: inout Self, b: Self) {\n a = a &+ b\n }\n \n @_transparent\n public static func &-=(a: inout Self, b: Self) {\n a = a &- b\n }\n \n @_transparent\n public static func &*=(a: inout Self, b: Self) {\n a = a &* b\n }\n \n @_transparent\n public static func /=(a: inout Self, b: Self) {\n a = a / b\n }\n \n @_transparent\n public static func %=(a: inout Self, b: Self) {\n a = a % b\n }\n \n @_transparent\n public static func &=(a: inout Self, b: Scalar) {\n a = a & b\n }\n \n @_transparent\n public static func ^=(a: inout Self, b: Scalar) {\n a = a ^ b\n }\n \n @_transparent\n public static func |=(a: inout Self, b: Scalar) {\n a = a | b\n }\n \n @_transparent\n public static func &<<=(a: inout Self, b: Scalar) {\n a = a &<< b\n }\n \n @_transparent\n public static func &>>=(a: inout Self, b: Scalar) {\n a = a &>> b\n }\n \n @_transparent\n public static func &+=(a: inout Self, b: Scalar) {\n a = a &+ b\n }\n \n @_transparent\n public static func &-=(a: inout Self, b: Scalar) {\n a = a &- b\n }\n \n @_transparent\n public static func &*=(a: inout Self, b: Scalar) {\n a = a &* b\n }\n \n @_transparent\n public static func /=(a: inout Self, b: Scalar) {\n a = a / b\n }\n \n @_transparent\n public static func %=(a: inout Self, b: Scalar) {\n a = a % b\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead")\n public static func +(a: Self, b: Self) -> Self {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead")\n public static func -(a: Self, b: Self) -> Self {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead")\n public static func *(a: Self, b: Self) -> Self {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead")\n public static func +(a: Self, b: Scalar) -> Self {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead")\n public static func -(a: Self, b: Scalar) -> Self {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead")\n public static func *(a: Self, b: Scalar) -> Self {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+' instead")\n public static func +(a: Scalar, b: Self) -> Self {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-' instead")\n public static func -(a: Scalar, b: Self) -> Self {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*' instead")\n public static func *(a: Scalar, b: Self) -> Self {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+=' instead")\n public static func +=(a: inout Self, b: Self) {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-=' instead")\n public static func -=(a: inout Self, b: Self) {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*=' instead")\n public static func *=(a: inout Self, b: Self) {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&+=' instead")\n public static func +=(a: inout Self, b: Scalar) {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&-=' instead")\n public static func -=(a: inout Self, b: Scalar) {\n fatalError()\n }\n \n @available(*, unavailable, message: "integer vector types do not support checked arithmetic; use the wrapping operator '&*=' instead")\n public static func *=(a: inout Self, b: Scalar) {\n fatalError()\n }\n}\n\nextension SIMD where Scalar: FloatingPoint {\n \n @_transparent\n public static prefix func -(a: Self) -> Self {\n return 0 - a\n }\n \n @_transparent\n public static func +(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) + b\n }\n \n @_transparent\n public static func -(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) - b\n }\n \n @_transparent\n public static func *(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) * b\n }\n \n @_transparent\n public static func /(a: Scalar, b: Self) -> Self {\n return Self(repeating: a) / b\n }\n \n @_transparent\n public static func +(a: Self, b: Scalar) -> Self {\n return a + Self(repeating: b)\n }\n \n @_transparent\n public static func -(a: Self, b: Scalar) -> Self {\n return a - Self(repeating: b)\n }\n \n @_transparent\n public static func *(a: Self, b: Scalar) -> Self {\n return a * Self(repeating: b)\n }\n \n @_transparent\n public static func /(a: Self, b: Scalar) -> Self {\n return a / Self(repeating: b)\n }\n \n @_transparent\n public static func +=(a: inout Self, b: Self) {\n a = a + b\n }\n \n @_transparent\n public static func -=(a: inout Self, b: Self) {\n a = a - b\n }\n \n @_transparent\n public static func *=(a: inout Self, b: Self) {\n a = a * b\n }\n \n @_transparent\n public static func /=(a: inout Self, b: Self) {\n a = a / b\n }\n \n @_transparent\n public static func +=(a: inout Self, b: Scalar) {\n a = a + b\n }\n \n @_transparent\n public static func -=(a: inout Self, b: Scalar) {\n a = a - b\n }\n \n @_transparent\n public static func *=(a: inout Self, b: Scalar) {\n a = a * b\n }\n \n @_transparent\n public static func /=(a: inout Self, b: Scalar) {\n a = a / b\n }\n \n @_transparent\n public func addingProduct(_ a: Scalar, _ b: Self) -> Self {\n return self.addingProduct(Self(repeating: a), b)\n }\n \n @_transparent\n public func addingProduct(_ a: Self, _ b: Scalar) -> Self {\n return self.addingProduct(a, Self(repeating: b))\n }\n \n @_transparent\n public mutating func addProduct(_ a: Self, _ b: Self) {\n self = self.addingProduct(a, b)\n }\n \n @_transparent\n public mutating func addProduct(_ a: Scalar, _ b: Self) {\n self = self.addingProduct(a, b)\n }\n \n @_transparent\n public mutating func addProduct(_ a: Self, _ b: Scalar) {\n self = self.addingProduct(a, b)\n }\n \n @_transparent\n public mutating func formSquareRoot( ) {\n self = self.squareRoot()\n }\n \n @_transparent\n public mutating func round(_ rule: FloatingPointRoundingRule) {\n self = self.rounded(rule)\n }\n}\n\nextension SIMDMask {\n /// A vector mask that is the pointwise logical conjunction of the inputs.\n ///\n /// Equivalent to `a ? b : SIMDMask(repeating: false)`.\n @_transparent\n public static func .&(a: Bool, b: SIMDMask) -> SIMDMask {\n return SIMDMask(repeating: a) .& b\n }\n \n /// A vector mask that is the pointwise exclusive or of the inputs.\n ///\n /// Equivalent to `a ? .!b : b`.\n @_transparent\n public static func .^(a: Bool, b: SIMDMask) -> SIMDMask {\n return SIMDMask(repeating: a) .^ b\n }\n \n /// A vector mask that is the pointwise logical disjunction of the inputs.\n ///\n /// Equivalent to `a ? SIMDMask(repeating: true) : b`.\n @_transparent\n public static func .|(a: Bool, b: SIMDMask) -> SIMDMask {\n return SIMDMask(repeating: a) .| b\n }\n \n /// A vector mask that is the pointwise logical conjunction of the inputs.\n ///\n /// Equivalent to `b ? a : SIMDMask(repeating: false)`.\n @_transparent\n public static func .&(a: SIMDMask, b: Bool) -> SIMDMask {\n return a .& SIMDMask(repeating: b)\n }\n \n /// A vector mask that is the pointwise exclusive or of the inputs.\n ///\n /// Equivalent to `b ? .!a : a`.\n @_transparent\n public static func .^(a: SIMDMask, b: Bool) -> SIMDMask {\n return a .^ SIMDMask(repeating: b)\n }\n \n /// A vector mask that is the pointwise logical disjunction of the inputs.\n ///\n /// Equivalent to `b ? SIMDMask(repeating: true) : a`\n @_transparent\n public static func .|(a: SIMDMask, b: Bool) -> SIMDMask {\n return a .| SIMDMask(repeating: b)\n }\n \n /// Replaces `a` with the pointwise logical conjunction of `a` and `b`.\n ///\n /// Equivalent to:\n /// ```\n /// for i in a.indices {\n /// a[i] = a[i] && b[i]\n /// }\n /// ```\n @_transparent\n public static func .&=(a: inout SIMDMask, b: SIMDMask) {\n a = a .& b\n }\n \n /// Replaces `a` with the pointwise exclusive or of `a` and `b`.\n ///\n /// Equivalent to:\n /// ```\n /// for i in a.indices {\n /// a[i] = a[i] != b[i]\n /// }\n /// ```\n @_transparent\n public static func .^=(a: inout SIMDMask, b: SIMDMask) {\n a = a .^ b\n }\n \n /// Replaces `a` with the pointwise logical disjunction of `a` and `b`.\n ///\n /// Equivalent to:\n /// ```\n /// for i in a.indices {\n /// a[i] = a[i] || b[i]\n /// }\n /// ```\n @_transparent\n public static func .|=(a: inout SIMDMask, b: SIMDMask) {\n a = a .| b\n }\n \n /// Replaces `a` with the pointwise logical conjunction of `a` and `b`.\n ///\n /// Equivalent to:\n /// ```\n /// if !b { a = SIMDMask(repeating: false) }\n /// ```\n @_transparent\n public static func .&=(a: inout SIMDMask, b: Bool) {\n a = a .& b\n }\n \n /// Replaces `a` with the pointwise exclusive or of `a` and `b`.\n ///\n /// Equivalent to:\n /// ```\n /// if b { a = .!a }\n /// ```\n @_transparent\n public static func .^=(a: inout SIMDMask, b: Bool) {\n a = a .^ b\n }\n \n /// Replaces `a` with the pointwise logical disjunction of `a` and `b`.\n ///\n /// Equivalent to:\n /// ```\n /// if b { a = SIMDMask(repeating: true) }\n /// ```\n @_transparent\n public static func .|=(a: inout SIMDMask, b: Bool) {\n a = a .| b\n }\n}\n\n/// True if any lane of mask is true.\n@_alwaysEmitIntoClient\npublic func any<Storage>(_ mask: SIMDMask<Storage>) -> Bool {\n return mask._storage.min() < 0\n}\n\n/// True if every lane of mask is true.\n@_alwaysEmitIntoClient\npublic func all<Storage>(_ mask: SIMDMask<Storage>) -> Bool {\n return mask._storage.max() < 0\n}\n\n/// The lanewise minimum of two vectors.\n///\n/// Each element of the result is the minimum of the corresponding elements\n/// of the inputs.\n@_alwaysEmitIntoClient\npublic func pointwiseMin<T>(_ a: T, _ b: T) -> T\nwhere T: SIMD, T.Scalar: Comparable {\n var result = T()\n for i in result.indices {\n result[i] = min(a[i], b[i])\n }\n return result\n}\n\n/// The lanewise maximum of two vectors.\n///\n/// Each element of the result is the minimum of the corresponding elements\n/// of the inputs.\n@_alwaysEmitIntoClient\npublic func pointwiseMax<T>(_ a: T, _ b: T) -> T\nwhere T: SIMD, T.Scalar: Comparable {\n var result = T()\n for i in result.indices {\n result[i] = max(a[i], b[i])\n }\n return result\n}\n\n\n/// The lanewise minimum of two vectors.\n///\n/// Each element of the result is the minimum of the corresponding elements\n/// of the inputs.\n@_alwaysEmitIntoClient\npublic func pointwiseMin<T>(_ a: T, _ b: T) -> T\nwhere T: SIMD, T.Scalar: FloatingPoint {\n var result = T()\n for i in result.indices {\n result[i] = T.Scalar.minimum(a[i], b[i])\n }\n return result\n}\n\n/// The lanewise maximum of two vectors.\n///\n/// Each element of the result is the maximum of the corresponding elements\n/// of the inputs.\n@_alwaysEmitIntoClient\npublic func pointwiseMax<T>(_ a: T, _ b: T) -> T\nwhere T: SIMD, T.Scalar: FloatingPoint {\n var result = T()\n for i in result.indices {\n result[i] = T.Scalar.maximum(a[i], b[i])\n }\n return result\n}\n\n// Break the ambiguity between AdditiveArithmetic and SIMD for += and -=\nextension SIMD where Self: AdditiveArithmetic, Self.Scalar: FloatingPoint {\n @_alwaysEmitIntoClient\n public static func +=(a: inout Self, b: Self) {\n a = a + b\n }\n\n @_alwaysEmitIntoClient\n public static func -=(a: inout Self, b: Self) {\n a = a - b\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_SIMDVector.swift
cpp_apple_swift_stdlib_public_core_SIMDVector.swift
Swift
45,304
0.95
0.058349
0.25608
awesome-app
192
2023-12-21T03:32:04.890214
MIT
false
b6a790a2d41e1b527146db747b2d067b
//===----------------------------------------------------------------------===//\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 file implements SipHash-2-4 and SipHash-1-3\n/// (https://131002.net/siphash/).\n///\n/// This file is based on the reference C implementation, which was released\n/// to public domain by:\n///\n/// * Jean-Philippe Aumasson <jeanphilippe.aumasson@gmail.com>\n/// * Daniel J. Bernstein <djb@cr.yp.to>\n//===----------------------------------------------------------------------===//\n\nextension Hasher {\n // FIXME: Remove @usableFromInline and @frozen once Hasher is resilient.\n // rdar://problem/38549901\n @usableFromInline @frozen\n internal struct _State {\n // "somepseudorandomlygeneratedbytes"\n private var v0: UInt64 = 0x736f6d6570736575\n private var v1: UInt64 = 0x646f72616e646f6d\n private var v2: UInt64 = 0x6c7967656e657261\n private var v3: UInt64 = 0x7465646279746573\n // The fields below are reserved for future use. They aren't currently used.\n private var v4: UInt64 = 0\n private var v5: UInt64 = 0\n private var v6: UInt64 = 0\n private var v7: UInt64 = 0\n\n @inline(__always)\n internal init(rawSeed: (UInt64, UInt64)) {\n v3 ^= rawSeed.1\n v2 ^= rawSeed.0\n v1 ^= rawSeed.1\n v0 ^= rawSeed.0\n }\n }\n}\n\nextension Hasher._State {\n @inline(__always)\n private static func _rotateLeft(_ x: UInt64, by amount: UInt64) -> UInt64 {\n return (x &<< amount) | (x &>> (64 - amount))\n }\n\n @inline(__always)\n private mutating func _round() {\n v0 = v0 &+ v1\n v1 = Hasher._State._rotateLeft(v1, by: 13)\n v1 ^= v0\n v0 = Hasher._State._rotateLeft(v0, by: 32)\n v2 = v2 &+ v3\n v3 = Hasher._State._rotateLeft(v3, by: 16)\n v3 ^= v2\n v0 = v0 &+ v3\n v3 = Hasher._State._rotateLeft(v3, by: 21)\n v3 ^= v0\n v2 = v2 &+ v1\n v1 = Hasher._State._rotateLeft(v1, by: 17)\n v1 ^= v2\n v2 = Hasher._State._rotateLeft(v2, by: 32)\n }\n\n @inline(__always)\n private func _extract() -> UInt64 {\n return v0 ^ v1 ^ v2 ^ v3\n }\n}\n\nextension Hasher._State {\n @inline(__always)\n internal mutating func compress(_ m: UInt64) {\n v3 ^= m\n _round()\n v0 ^= m\n }\n\n @inline(__always)\n internal mutating func finalize(tailAndByteCount: UInt64) -> UInt64 {\n compress(tailAndByteCount)\n v2 ^= 0xff\n for _ in 0..<3 {\n _round()\n }\n return _extract()\n }\n}\n\nextension Hasher._State {\n @inline(__always)\n internal init() {\n self.init(rawSeed: Hasher._executionSeed)\n }\n\n @inline(__always)\n internal init(seed: Int) {\n let executionSeed = Hasher._executionSeed\n // Prevent sign-extending the supplied seed; this makes testing slightly\n // easier.\n let seed = UInt(bitPattern: seed)\n self.init(rawSeed: (\n executionSeed.0 ^ UInt64(truncatingIfNeeded: seed),\n executionSeed.1))\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_SipHash.swift
cpp_apple_swift_stdlib_public_core_SipHash.swift
Swift
3,235
0.8
0.035398
0.25
awesome-app
643
2024-07-12T18:44:39.304731
MIT
false
19ecdeeeaf9cda0a0dc91d5a4357f886
//===----------------------------------------------------------------------===//\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/// A view into a subsequence of elements of another collection.\n///\n/// A slice stores a base collection and the start and end indices of the view.\n/// It does not copy the elements from the collection into separate storage.\n/// Thus, creating a slice has O(1) complexity.\n///\n/// Slices Share Indices\n/// --------------------\n///\n/// Indices of a slice can be used interchangeably with indices of the base\n/// collection. An element of a slice is located under the same index in the\n/// slice and in the base collection, as long as neither the collection nor\n/// the slice has been 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 Semantics\n/// ------------------------\n///\n/// A slice inherits the value or reference semantics of its base collection.\n/// That is, if a `Slice` instance is wrapped around a mutable collection that\n/// has value semantics, such as an array, mutating the original collection\n/// would trigger a copy of that collection, and not affect the base\n/// collection stored inside 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/// Use slices only for transient computation. A slice may hold a reference to\n/// the entire storage of a larger collection, not just to the portion it\n/// presents, even after the base collection's lifetime ends. Long-term\n/// storage of a slice may therefore prolong the lifetime of elements that are\n/// no longer otherwise accessible, which can erroneously appear to be memory\n/// leakage.\n///\n/// - Note: Using a `Slice` instance with a mutable collection requires that\n/// the base collection's `subscript(_: Index)` setter does not invalidate\n/// indices. If mutations need to invalidate indices in your custom\n/// collection type, don't use `Slice` as its subsequence type. Instead,\n/// define your own subsequence type that takes your index invalidation\n/// requirements into account.\n@frozen // generic-performance\npublic struct Slice<Base: Collection> {\n public var _startIndex: Base.Index\n public var _endIndex: Base.Index\n\n @usableFromInline // generic-performance\n internal var _base: Base\n\n /// Creates a view into the given collection that allows access to elements\n /// within the specified range.\n ///\n /// It is unusual to need to call this method directly. Instead, create a\n /// slice of a collection by using the collection's range-based subscript or\n /// by using methods that return a subsequence.\n ///\n /// let singleDigits = 0...9\n /// let subSequence = singleDigits.dropFirst(5)\n /// print(Array(subSequence))\n /// // Prints "[5, 6, 7, 8, 9]"\n ///\n /// In this example, the expression `singleDigits.dropFirst(5))` is\n /// equivalent to calling this initializer with `singleDigits` and a\n /// range covering the last five items of `singleDigits.indices`.\n ///\n /// - Parameters:\n /// - base: The collection to create a view into.\n /// - bounds: The range of indices to allow access to in the new slice.\n @inlinable // generic-performance\n public init(base: Base, bounds: Range<Base.Index>) {\n self._base = base\n self._startIndex = bounds.lowerBound\n self._endIndex = bounds.upperBound\n }\n\n /// The underlying collection of the slice.\n ///\n /// You can use a slice's `base` property to access its base collection. The\n /// following example declares `singleDigits`, a range of single digit\n /// integers, and then drops the first element to create a slice of that\n /// range, `singleNonZeroDigits`. The `base` property of the slice is equal\n /// to `singleDigits`.\n ///\n /// let singleDigits = 0..<10\n /// let singleNonZeroDigits = singleDigits.dropFirst()\n /// // singleNonZeroDigits is a Slice<Range<Int>>\n ///\n /// print(singleNonZeroDigits.count)\n /// // Prints "9"\n /// print(singleNonZeroDigits.base.count)\n /// // Prints "10"\n /// print(singleDigits == singleNonZeroDigits.base)\n /// // Prints "true"\n @inlinable // generic-performance\n public var base: Base {\n return _base\n }\n\n @_alwaysEmitIntoClient @inline(__always)\n internal var _bounds: Range<Base.Index> {\n unsafe Range(_uncheckedBounds: (_startIndex, _endIndex))\n }\n}\n\nextension Slice: Collection {\n public typealias Index = Base.Index\n public typealias Indices = Base.Indices\n public typealias Element = Base.Element\n public typealias SubSequence = Slice<Base>\n public typealias Iterator = IndexingIterator<Slice<Base>>\n\n @inlinable // generic-performance\n public var startIndex: Index {\n return _startIndex\n }\n\n @inlinable // generic-performance\n public var endIndex: Index {\n return _endIndex\n }\n\n @inlinable // generic-performance\n public subscript(index: Index) -> Base.Element {\n get {\n _failEarlyRangeCheck(index, bounds: _bounds)\n return _base[index]\n }\n }\n\n @inlinable // generic-performance\n public subscript(bounds: Range<Index>) -> Slice<Base> {\n get {\n _failEarlyRangeCheck(bounds, bounds: _bounds)\n return Slice(base: _base, bounds: bounds)\n }\n }\n\n public var indices: Indices {\n return _base.indices[_bounds]\n }\n\n @inlinable // generic-performance\n public func index(after i: Index) -> Index {\n // FIXME: swift-3-indexing-model: range check.\n return _base.index(after: i)\n }\n\n @inlinable // generic-performance\n public func formIndex(after i: inout Index) {\n // FIXME: swift-3-indexing-model: range check.\n _base.formIndex(after: &i)\n }\n\n @inlinable // generic-performance\n public func index(_ i: Index, offsetBy n: Int) -> Index {\n // FIXME: swift-3-indexing-model: range check.\n return _base.index(i, offsetBy: n)\n }\n\n @inlinable // generic-performance\n public func index(\n _ i: Index, offsetBy n: Int, limitedBy limit: Index\n ) -> Index? {\n // FIXME: swift-3-indexing-model: range check.\n return _base.index(i, offsetBy: n, limitedBy: limit)\n }\n\n @inlinable // generic-performance\n public func distance(from start: Index, to end: Index) -> Int {\n // FIXME: swift-3-indexing-model: range check.\n return _base.distance(from: start, to: end)\n }\n\n @inlinable // generic-performance\n public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {\n _base._failEarlyRangeCheck(index, bounds: bounds)\n }\n\n @inlinable // generic-performance\n public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {\n _base._failEarlyRangeCheck(range, bounds: bounds)\n }\n\n @_alwaysEmitIntoClient @inlinable\n public func withContiguousStorageIfAvailable<R>(\n _ body: (UnsafeBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n try _base.withContiguousStorageIfAvailable { buffer in\n let start = _base.distance(from: _base.startIndex, to: _startIndex)\n let count = _base.distance(from: _startIndex, to: _endIndex)\n let slice = unsafe UnsafeBufferPointer(rebasing: buffer[start ..< start + count])\n return try unsafe body(slice)\n }\n }\n}\n\nextension Slice {\n @_alwaysEmitIntoClient\n public __consuming func _copyContents(\n initializing buffer: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {\n if let (_, copied) = unsafe self.withContiguousStorageIfAvailable({\n unsafe $0._copyContents(initializing: buffer)\n }) {\n let position = index(startIndex, offsetBy: copied)\n return (Iterator(_elements: self, _position: position), copied)\n }\n\n return unsafe _copySequenceContents(initializing: buffer)\n }\n}\n\nextension Slice: BidirectionalCollection where Base: BidirectionalCollection {\n @inlinable // generic-performance\n public func index(before i: Index) -> Index {\n // FIXME: swift-3-indexing-model: range check.\n return _base.index(before: i)\n }\n\n @inlinable // generic-performance\n public func formIndex(before i: inout Index) {\n // FIXME: swift-3-indexing-model: range check.\n _base.formIndex(before: &i)\n }\n}\n\n\nextension Slice: MutableCollection where Base: MutableCollection {\n @inlinable // generic-performance\n public subscript(index: Index) -> Base.Element {\n get {\n _failEarlyRangeCheck(index, bounds: _bounds)\n return _base[index]\n }\n set {\n _failEarlyRangeCheck(index, bounds: _bounds)\n _base[index] = newValue\n // MutableSlice requires that the underlying collection's subscript\n // setter does not invalidate indices, so our `startIndex` and `endIndex`\n // continue to be valid.\n }\n }\n\n @inlinable // generic-performance\n public subscript(bounds: Range<Index>) -> Slice<Base> {\n get {\n _failEarlyRangeCheck(bounds, bounds: _bounds)\n return Slice(base: _base, bounds: bounds)\n }\n set {\n _writeBackMutableSlice(&self, bounds: bounds, slice: newValue)\n }\n }\n\n @_alwaysEmitIntoClient @inlinable\n public mutating func withContiguousMutableStorageIfAvailable<R>(\n _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R\n ) rethrows -> R? {\n // We're calling `withContiguousMutableStorageIfAvailable` twice here so\n // that we don't calculate index distances unless we know we'll use them.\n // The expectation here is that the base collection will make itself\n // contiguous on the first try and the second call will be relatively cheap.\n guard unsafe _base.withContiguousMutableStorageIfAvailable({ _ in }) != nil\n else {\n return nil\n }\n let start = _base.distance(from: _base.startIndex, to: _startIndex)\n let count = _base.distance(from: _startIndex, to: _endIndex)\n return try unsafe _base.withContiguousMutableStorageIfAvailable { buffer in\n var slice = unsafe UnsafeMutableBufferPointer(\n rebasing: buffer[start ..< start + count])\n let copy = unsafe slice\n defer {\n unsafe _precondition(\n slice.baseAddress == copy.baseAddress &&\n slice.count == copy.count,\n "Slice.withContiguousMutableStorageIfAvailable: replacing the buffer is not allowed")\n }\n return try unsafe body(&slice)\n }\n }\n}\n\n\nextension Slice: RandomAccessCollection where Base: RandomAccessCollection { }\n\nextension Slice: RangeReplaceableCollection\n where Base: RangeReplaceableCollection {\n @inlinable // generic-performance\n public init() {\n self._base = Base()\n self._startIndex = _base.startIndex\n self._endIndex = _base.endIndex\n }\n\n @inlinable // generic-performance\n public init(repeating repeatedValue: Base.Element, count: Int) {\n self._base = Base(repeating: repeatedValue, count: count)\n self._startIndex = _base.startIndex\n self._endIndex = _base.endIndex\n }\n\n @inlinable // generic-performance\n public init<S>(_ elements: S) where S: Sequence, S.Element == Base.Element {\n self._base = Base(elements)\n self._startIndex = _base.startIndex\n self._endIndex = _base.endIndex\n }\n\n @inlinable // generic-performance\n public mutating func replaceSubrange<C>(\n _ subRange: Range<Index>, with newElements: C\n ) where C: Collection, C.Element == Base.Element {\n\n // FIXME: swift-3-indexing-model: range check.\n let sliceOffset =\n _base.distance(from: _base.startIndex, to: _startIndex)\n let newSliceCount =\n _base.distance(from: _startIndex, to: subRange.lowerBound)\n + _base.distance(from: subRange.upperBound, to: _endIndex)\n + newElements.count\n _base.replaceSubrange(subRange, with: newElements)\n _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset)\n _endIndex = _base.index(_startIndex, offsetBy: newSliceCount)\n }\n\n @inlinable // generic-performance\n public mutating func insert(_ newElement: Base.Element, at i: Index) {\n // FIXME: swift-3-indexing-model: range check.\n let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex)\n let newSliceCount = count + 1\n _base.insert(newElement, at: i)\n _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset)\n _endIndex = _base.index(_startIndex, offsetBy: newSliceCount)\n }\n\n @inlinable // generic-performance\n public mutating func insert<S>(contentsOf newElements: S, at i: Index)\n where S: Collection, S.Element == Base.Element {\n\n // FIXME: swift-3-indexing-model: range check.\n let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex)\n let newSliceCount = count + newElements.count\n _base.insert(contentsOf: newElements, at: i)\n _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset)\n _endIndex = _base.index(_startIndex, offsetBy: newSliceCount)\n }\n\n @inlinable // generic-performance\n public mutating func remove(at i: Index) -> Base.Element {\n // FIXME: swift-3-indexing-model: range check.\n let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex)\n let newSliceCount = count - 1\n let result = _base.remove(at: i)\n _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset)\n _endIndex = _base.index(_startIndex, offsetBy: newSliceCount)\n return result\n }\n\n @inlinable // generic-performance\n public mutating func removeSubrange(_ bounds: Range<Index>) {\n // FIXME: swift-3-indexing-model: range check.\n let sliceOffset = _base.distance(from: _base.startIndex, to: _startIndex)\n let newSliceCount =\n count - distance(from: bounds.lowerBound, to: bounds.upperBound)\n _base.removeSubrange(bounds)\n _startIndex = _base.index(_base.startIndex, offsetBy: sliceOffset)\n _endIndex = _base.index(_startIndex, offsetBy: newSliceCount)\n }\n}\n\nextension Slice\n where Base: RangeReplaceableCollection, Base: BidirectionalCollection {\n \n @inlinable // generic-performance\n public mutating func replaceSubrange<C>(\n _ subRange: Range<Index>, with newElements: C\n ) where C: Collection, C.Element == Base.Element {\n // FIXME: swift-3-indexing-model: range check.\n if subRange.lowerBound == _base.startIndex {\n let newSliceCount =\n _base.distance(from: _startIndex, to: subRange.lowerBound)\n + _base.distance(from: subRange.upperBound, to: _endIndex)\n + newElements.count\n _base.replaceSubrange(subRange, with: newElements)\n _startIndex = _base.startIndex\n _endIndex = _base.index(_startIndex, offsetBy: newSliceCount)\n } else {\n let shouldUpdateStartIndex = subRange.lowerBound == _startIndex\n let lastValidIndex = _base.index(before: subRange.lowerBound)\n let newEndIndexOffset =\n _base.distance(from: subRange.upperBound, to: _endIndex)\n + newElements.count + 1\n _base.replaceSubrange(subRange, with: newElements)\n if shouldUpdateStartIndex {\n _startIndex = _base.index(after: lastValidIndex)\n }\n _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset)\n }\n }\n\n @inlinable // generic-performance\n public mutating func insert(_ newElement: Base.Element, at i: Index) {\n // FIXME: swift-3-indexing-model: range check.\n if i == _base.startIndex {\n let newSliceCount = count + 1\n _base.insert(newElement, at: i)\n _startIndex = _base.startIndex\n _endIndex = _base.index(_startIndex, offsetBy: newSliceCount)\n } else {\n let shouldUpdateStartIndex = i == _startIndex\n let lastValidIndex = _base.index(before: i)\n let newEndIndexOffset = _base.distance(from: i, to: _endIndex) + 2\n _base.insert(newElement, at: i)\n if shouldUpdateStartIndex {\n _startIndex = _base.index(after: lastValidIndex)\n }\n _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset)\n }\n }\n\n @inlinable // generic-performance\n public mutating func insert<S>(contentsOf newElements: S, at i: Index)\n where S: Collection, S.Element == Base.Element {\n // FIXME: swift-3-indexing-model: range check.\n if i == _base.startIndex {\n let newSliceCount = count + newElements.count\n _base.insert(contentsOf: newElements, at: i)\n _startIndex = _base.startIndex\n _endIndex = _base.index(_startIndex, offsetBy: newSliceCount)\n } else {\n let shouldUpdateStartIndex = i == _startIndex\n let lastValidIndex = _base.index(before: i)\n let newEndIndexOffset =\n _base.distance(from: i, to: _endIndex)\n + newElements.count + 1\n _base.insert(contentsOf: newElements, at: i)\n if shouldUpdateStartIndex {\n _startIndex = _base.index(after: lastValidIndex)\n }\n _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset)\n }\n }\n\n @inlinable // generic-performance\n public mutating func remove(at i: Index) -> Base.Element {\n // FIXME: swift-3-indexing-model: range check.\n if i == _base.startIndex {\n let newSliceCount = count - 1\n let result = _base.remove(at: i)\n _startIndex = _base.startIndex\n _endIndex = _base.index(_startIndex, offsetBy: newSliceCount)\n return result\n } else {\n let shouldUpdateStartIndex = i == _startIndex\n let lastValidIndex = _base.index(before: i)\n let newEndIndexOffset = _base.distance(from: i, to: _endIndex)\n let result = _base.remove(at: i)\n if shouldUpdateStartIndex {\n _startIndex = _base.index(after: lastValidIndex)\n }\n _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset)\n return result\n }\n }\n\n @inlinable // generic-performance\n public mutating func removeSubrange(_ bounds: Range<Index>) {\n // FIXME: swift-3-indexing-model: range check.\n if bounds.lowerBound == _base.startIndex {\n let newSliceCount =\n count - _base.distance(from: bounds.lowerBound, to: bounds.upperBound)\n _base.removeSubrange(bounds)\n _startIndex = _base.startIndex\n _endIndex = _base.index(_startIndex, offsetBy: newSliceCount)\n } else {\n let shouldUpdateStartIndex = bounds.lowerBound == _startIndex\n let lastValidIndex = _base.index(before: bounds.lowerBound)\n let newEndIndexOffset =\n _base.distance(from: bounds.lowerBound, to: _endIndex)\n - _base.distance(from: bounds.lowerBound, to: bounds.upperBound)\n + 1\n _base.removeSubrange(bounds)\n if shouldUpdateStartIndex {\n _startIndex = _base.index(after: lastValidIndex)\n }\n _endIndex = _base.index(lastValidIndex, offsetBy: newEndIndexOffset)\n }\n }\n}\n\nextension Slice: Sendable\nwhere Base: Sendable, Base.Index: Sendable { }\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Slice.swift
cpp_apple_swift_stdlib_public_core_Slice.swift
Swift
19,948
0.95
0.043152
0.289528
vue-tools
501
2024-06-25T07:53:50.898164
BSD-3-Clause
false
d67af06e021d0f72c431528cc4acf1b7
//===--- SliceBuffer.swift - Backing storage for ArraySlice<Element> ------===//\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/// Buffer type for `ArraySlice<Element>`.\n@frozen\n@usableFromInline\n@safe\ninternal struct _SliceBuffer<Element>\n : _ArrayBufferProtocol,\n RandomAccessCollection\n{\n #if $Embedded\n @usableFromInline\n typealias AnyObject = Builtin.NativeObject\n #endif\n\n internal typealias NativeStorage = _ContiguousArrayStorage<Element>\n @usableFromInline\n internal typealias NativeBuffer = _ContiguousArrayBuffer<Element>\n\n /// An object that keeps the elements stored in this buffer alive.\n @usableFromInline\n internal var owner: AnyObject\n\n @usableFromInline\n internal let subscriptBaseAddress: UnsafeMutablePointer<Element>\n\n /// The position of the first element in a non-empty collection.\n ///\n /// In an empty collection, `startIndex == endIndex`.\n @usableFromInline\n internal var startIndex: Int\n\n /// [63:1: 63-bit index][0: has a native buffer]\n @usableFromInline\n internal var endIndexAndFlags: UInt\n\n @inlinable\n internal init(\n owner: AnyObject,\n subscriptBaseAddress: UnsafeMutablePointer<Element>,\n startIndex: Int,\n endIndexAndFlags: UInt\n ) {\n self.owner = owner\n unsafe self.subscriptBaseAddress = subscriptBaseAddress\n self.startIndex = startIndex\n self.endIndexAndFlags = endIndexAndFlags\n }\n\n @inlinable\n internal init(\n owner: AnyObject, subscriptBaseAddress: UnsafeMutablePointer<Element>,\n indices: Range<Int>, hasNativeBuffer: Bool\n ) {\n self.owner = owner\n unsafe self.subscriptBaseAddress = subscriptBaseAddress\n self.startIndex = indices.lowerBound\n let bufferFlag = UInt(hasNativeBuffer ? 1 : 0)\n self.endIndexAndFlags = (UInt(indices.upperBound) << 1) | bufferFlag\n _invariantCheck()\n }\n\n @inlinable\n internal init() {\n let empty = _ContiguousArrayBuffer<Element>()\n #if $Embedded\n self.owner = Builtin.castToNativeObject(_emptyArrayStorage)\n #else\n self.owner = _emptyArrayStorage\n #endif\n unsafe self.subscriptBaseAddress = empty.firstElementAddress\n self.startIndex = empty.startIndex\n self.endIndexAndFlags = 1\n _invariantCheck()\n }\n\n @inlinable\n internal init(_buffer buffer: NativeBuffer, shiftedToStartIndex: Int) {\n let shift = buffer.startIndex - shiftedToStartIndex\n unsafe self.init(\n owner: buffer.owner,\n subscriptBaseAddress: buffer.subscriptBaseAddress + shift,\n indices: shiftedToStartIndex..<shiftedToStartIndex + buffer.count,\n hasNativeBuffer: true)\n }\n\n @inlinable // FIXME(sil-serialize-all)\n internal func _invariantCheck() {\n let isNative = _hasNativeBuffer\n let isNativeStorage: Bool\n #if !$Embedded\n isNativeStorage = owner is __ContiguousArrayStorageBase\n #else\n isNativeStorage = true\n #endif\n _internalInvariant(isNativeStorage == isNative)\n if isNative {\n _internalInvariant(count <= nativeBuffer.count)\n }\n }\n\n @inlinable\n internal var _hasNativeBuffer: Bool {\n return (endIndexAndFlags & 1) != 0\n }\n\n @inlinable\n internal var nativeBuffer: NativeBuffer {\n _internalInvariant(_hasNativeBuffer)\n #if !$Embedded\n return NativeBuffer(\n owner as? __ContiguousArrayStorageBase ?? _emptyArrayStorage)\n #else\n return NativeBuffer(unsafe unsafeBitCast(_nativeObject(toNative: owner),\n to: __ContiguousArrayStorageBase.self))\n #endif\n }\n\n @inlinable\n internal var nativeOwner: AnyObject {\n _internalInvariant(_hasNativeBuffer, "Expect a native array")\n return owner\n }\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` and `insertCount <= newValues.count`.\n @inlinable\n internal mutating func replaceSubrange<C>(\n _ subrange: Range<Int>,\n with insertCount: Int,\n elementsOf newValues: __owned C\n ) where C: Collection, C.Element == Element {\n\n _invariantCheck()\n _internalInvariant(insertCount <= newValues.count)\n\n _internalInvariant(_hasNativeBuffer)\n _internalInvariant(isUniquelyReferenced())\n\n let eraseCount = subrange.count\n let growth = insertCount - eraseCount\n let oldCount = count\n\n var native = nativeBuffer\n let hiddenElementCount = unsafe firstElementAddress - native.firstElementAddress\n\n _internalInvariant(native.count + growth <= native.capacity)\n\n let start = subrange.lowerBound - startIndex + hiddenElementCount\n let end = subrange.upperBound - startIndex + hiddenElementCount\n native.replaceSubrange(\n start..<end,\n with: insertCount,\n elementsOf: newValues)\n\n self.endIndex = self.startIndex + oldCount + growth\n\n _invariantCheck()\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 return unsafe UnsafeRawPointer(firstElementAddress)\n }\n\n @inlinable\n internal var firstElementAddress: UnsafeMutablePointer<Element> {\n return unsafe subscriptBaseAddress + startIndex\n }\n\n @inlinable\n internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {\n return unsafe firstElementAddress\n }\n\n //===--- Non-essential bits ---------------------------------------------===//\n\n @inlinable\n internal mutating func requestUniqueMutableBackingBuffer(\n minimumCapacity: Int\n ) -> NativeBuffer? {\n _invariantCheck()\n // Note: with COW support it's already guaranteed to have a uniquely\n // referenced buffer. This check is only needed for backward compatibility.\n if _fastPath(isUniquelyReferenced()) {\n if capacity >= minimumCapacity {\n // Since we have the last reference, drop any inaccessible\n // trailing elements in the underlying storage. That will\n // tend to reduce shuffling of later elements. Since this\n // function isn't called for subscripting, this won't slow\n // down that case.\n var native = nativeBuffer\n let offset = unsafe self.firstElementAddress - native.firstElementAddress\n let backingCount = native.count\n let myCount = count\n\n if _slowPath(backingCount > myCount + offset) {\n native.replaceSubrange(\n (myCount+offset)..<backingCount,\n with: 0,\n elementsOf: EmptyCollection())\n }\n _invariantCheck()\n return native\n }\n }\n return nil\n }\n\n @inlinable\n internal mutating func isMutableAndUniquelyReferenced() -> Bool {\n // This is a performance optimization that ensures that the copy of self\n // that occurs at -Onone is destroyed before we call\n // isUniquelyReferenced. This code used to be:\n //\n // return _hasNativeBuffer && isUniquelyReferenced()\n //\n // https://github.com/apple/swift/issues/48987\n if !_hasNativeBuffer {\n return false\n }\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 _invariantCheck()\n if _fastPath(_hasNativeBuffer && nativeBuffer.count == count) {\n return nativeBuffer\n }\n return nil\n }\n\n @inlinable\n @discardableResult\n internal __consuming func _copyContents(\n subRange bounds: Range<Int>,\n initializing target: UnsafeMutablePointer<Element>\n ) -> UnsafeMutablePointer<Element> {\n _invariantCheck()\n _internalInvariant(bounds.lowerBound >= startIndex)\n _internalInvariant(bounds.upperBound >= bounds.lowerBound)\n _internalInvariant(bounds.upperBound <= endIndex)\n let c = bounds.count\n unsafe target.initialize(from: subscriptBaseAddress + bounds.lowerBound, count: c)\n return unsafe target + c\n }\n\n @inlinable\n internal __consuming func _copyContents(\n initializing buffer: UnsafeMutableBufferPointer<Element>\n ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {\n _invariantCheck()\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: startIndex + c), c)\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 _hasNativeBuffer\n }\n\n @inlinable\n internal var count: Int {\n get {\n return endIndex - startIndex\n }\n set {\n let growth = newValue - count\n if growth != 0 {\n nativeBuffer.mutableCount += growth\n self.endIndex += growth\n }\n _invariantCheck()\n }\n }\n\n /// Traps unless the given `index` is valid for subscripting, i.e.\n /// `startIndex ≤ index < endIndex`\n @inlinable\n internal func _checkValidSubscript(_ index: Int) {\n _precondition(\n index >= startIndex && index < endIndex, "Index out of bounds")\n }\n\n @inlinable\n internal var capacity: Int {\n let count = self.count\n if _slowPath(!_hasNativeBuffer) {\n return count\n }\n let n = nativeBuffer\n let nativeEnd = unsafe n.firstElementAddress + n.count\n if unsafe (firstElementAddress + count) == nativeEnd {\n return count + (n.capacity - n.count)\n }\n return count\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 and for\n /// backward compatibility.\n /// To guard a buffer mutation, use `beginCOWMutation`.\n @inlinable\n internal mutating func isUniquelyReferenced() -> Bool {\n return isKnownUniquelyReferenced(&owner)\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 !_hasNativeBuffer {\n return false\n }\n if Bool(Builtin.beginCOWMutation(&owner)) {\n#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED\n nativeBuffer.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 nativeBuffer.isImmutable = true\n#endif\n Builtin.endCOWMutation(&owner)\n }\n\n @inlinable\n internal func getElement(_ i: Int) -> Element {\n _internalInvariant(i >= startIndex, "slice index is out of range (before startIndex)")\n _internalInvariant(i < endIndex, "slice index is out of range")\n return unsafe subscriptBaseAddress[i]\n }\n\n /// Access the element at `position`.\n ///\n /// - Precondition: `position` is a valid position in `self` and\n /// `position != endIndex`.\n @inlinable\n internal subscript(position: Int) -> Element {\n get {\n return getElement(position)\n }\n nonmutating set {\n _internalInvariant(position >= startIndex, "slice index is out of range (before startIndex)")\n _internalInvariant(position < endIndex, "slice index is out of range")\n unsafe subscriptBaseAddress[position] = newValue\n }\n }\n\n @inlinable\n internal subscript(bounds: Range<Int>) -> _SliceBuffer {\n get {\n _internalInvariant(bounds.lowerBound >= startIndex)\n _internalInvariant(bounds.upperBound >= bounds.lowerBound)\n _internalInvariant(bounds.upperBound <= endIndex)\n return unsafe _SliceBuffer(\n owner: owner,\n subscriptBaseAddress: subscriptBaseAddress,\n indices: bounds,\n hasNativeBuffer: _hasNativeBuffer)\n }\n set {\n fatalError("not implemented")\n }\n }\n\n //===--- Collection conformance -------------------------------------===//\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 internal var endIndex: Int {\n get {\n return Int(endIndexAndFlags >> 1)\n }\n set {\n endIndexAndFlags = (UInt(newValue) << 1) | (_hasNativeBuffer ? 1 : 0)\n }\n }\n\n @usableFromInline\n internal typealias Indices = Range<Int>\n\n //===--- misc -----------------------------------------------------------===//\n // Superseded by the typed-throws version of this function, but retained\n // for ABI reasons.\n @usableFromInline\n @_silgen_name("$ss12_SliceBufferV010withUnsafeB7Pointeryqd__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("$ss12_SliceBufferV017withUnsafeMutableB7Pointeryqd__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 @inlinable\n internal func unsafeCastElements<T>(to type: T.Type) -> _SliceBuffer<T> {\n _internalInvariant(_isClassOrObjCExistential(T.self))\n let baseAddress = unsafe UnsafeMutableRawPointer(self.subscriptBaseAddress)\n .assumingMemoryBound(to: T.self)\n return unsafe _SliceBuffer<T>(\n owner: self.owner,\n subscriptBaseAddress: baseAddress,\n startIndex: self.startIndex,\n endIndexAndFlags: self.endIndexAndFlags)\n }\n}\n\n@available(*, unavailable)\nextension _SliceBuffer: Sendable {}\n\nextension _SliceBuffer {\n @inlinable\n internal __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {\n if _hasNativeBuffer {\n let n = nativeBuffer\n if count == n.count {\n return ContiguousArray(_buffer: n)\n }\n }\n\n let result = _ContiguousArrayBuffer<Element>(\n _uninitializedCount: count,\n minimumCapacity: 0)\n unsafe result.firstElementAddress.initialize(\n from: firstElementAddress, count: count)\n return ContiguousArray(_buffer: result)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_SliceBuffer.swift
cpp_apple_swift_stdlib_public_core_SliceBuffer.swift
Swift
16,259
0.95
0.079922
0.217865
node-utils
670
2025-04-26T23:43:09.259230
BSD-3-Clause
false
1da95e308e55fcc426ccccae95315d31
//===----------------------------------------------------------------------===//\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// The code units in _SmallString are always stored in memory in the same order\n// that they would be stored in an array. This means that on big-endian\n// platforms the order of the bytes in storage is reversed compared to\n// _StringObject whereas on little-endian platforms the order is the same.\n//\n// Memory layout:\n//\n// |0 1 2 3 4 5 6 7 8 9 A B C D E F| ← hexadecimal offset in bytes\n// | _storage.0 | _storage.1 | ← raw bits\n// | code units | | ← encoded layout\n// ↑ ↑\n// first (leftmost) code unit discriminator (incl. count)\n//\n// On Android AArch64, there is one less byte available because the discriminator\n// is stored in the penultimate code unit instead, to match where it's stored\n// for large strings.\n@frozen @usableFromInline\ninternal struct _SmallString {\n @usableFromInline\n internal typealias RawBitPattern = (UInt64, UInt64)\n\n // Small strings are values; store them raw\n @usableFromInline\n internal var _storage: RawBitPattern\n\n @inlinable @inline(__always)\n internal var rawBits: RawBitPattern { return _storage }\n\n @inlinable\n internal var leadingRawBits: UInt64 {\n @inline(__always) get { return _storage.0 }\n @inline(__always) set { _storage.0 = newValue }\n }\n\n @inlinable\n internal var trailingRawBits: UInt64 {\n @inline(__always) get { return _storage.1 }\n @inline(__always) set { _storage.1 = newValue }\n }\n\n @inlinable @inline(__always)\n internal init(rawUnchecked bits: RawBitPattern) {\n self._storage = bits\n }\n\n @inlinable @inline(__always)\n internal init(raw bits: RawBitPattern) {\n self.init(rawUnchecked: bits)\n _invariantCheck()\n }\n\n @inlinable @inline(__always)\n internal init(_ object: _StringObject) {\n _internalInvariant(object.isSmall)\n // On big-endian platforms the byte order is the reverse of _StringObject.\n let leading = object.rawBits.0.littleEndian\n let trailing = object.rawBits.1.littleEndian\n self.init(raw: (leading, trailing))\n }\n\n @inlinable @inline(__always)\n internal init() {\n self.init(_StringObject(empty:()))\n }\n}\n\nextension _SmallString {\n @inlinable @inline(__always)\n internal static var capacity: Int {\n#if _pointerBitWidth(_32) || _pointerBitWidth(_16)\n return 10\n#elseif os(Android) && arch(arm64)\n return 14\n#elseif _pointerBitWidth(_64)\n return 15\n#else\n#error("Unknown platform")\n#endif\n }\n\n // Get an integer equivalent to the _StringObject.discriminatedObjectRawBits\n // computed property.\n @inlinable @inline(__always)\n internal var rawDiscriminatedObject: UInt64 {\n // Reverse the bytes on big-endian systems.\n return _storage.1.littleEndian\n }\n\n @inlinable @inline(__always)\n internal var capacity: Int { return _SmallString.capacity }\n\n @inlinable @inline(__always)\n internal var count: Int {\n return _StringObject.getSmallCount(fromRaw: rawDiscriminatedObject)\n }\n\n @inlinable @inline(__always)\n internal var unusedCapacity: Int { return capacity &- count }\n\n @inlinable @inline(__always)\n internal var isASCII: Bool {\n return _StringObject.getSmallIsASCII(fromRaw: rawDiscriminatedObject)\n }\n\n // Give raw, nul-terminated code units. This is only for limited internal\n // usage: it always clears the discriminator and count (in case it's full)\n @inlinable @inline(__always)\n internal var zeroTerminatedRawCodeUnits: RawBitPattern {\n#if os(Android) && arch(arm64)\n let smallStringCodeUnitMask = ~UInt64(0xFFFF).bigEndian // zero last two bytes\n#else\n let smallStringCodeUnitMask = ~UInt64(0xFF).bigEndian // zero last byte\n#endif\n return (self._storage.0, self._storage.1 & smallStringCodeUnitMask)\n }\n\n internal func computeIsASCII() -> Bool {\n let asciiMask: UInt64 = 0x8080_8080_8080_8080\n let raw = zeroTerminatedRawCodeUnits\n return (raw.0 | raw.1) & asciiMask == 0\n }\n}\n\n// Internal invariants\nextension _SmallString {\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(count <= _SmallString.capacity)\n _internalInvariant(isASCII == computeIsASCII())\n\n // No bits should be set between the last code unit and the discriminator\n var copy = self\n unsafe withUnsafeBytes(of: &copy._storage) {\n unsafe _internalInvariant(\n $0[count..<_SmallString.capacity].allSatisfy { $0 == 0 })\n }\n }\n #endif // INTERNAL_CHECKS_ENABLED\n\n internal func _dump() {\n #if INTERNAL_CHECKS_ENABLED\n print("""\n smallUTF8: count: \(self.count), codeUnits: \(\n self.map { String($0, radix: 16) }.joined()\n )\n """)\n #endif // INTERNAL_CHECKS_ENABLED\n }\n}\n\n// Provide a RAC interface\nextension _SmallString: RandomAccessCollection, MutableCollection {\n @usableFromInline\n internal typealias Index = Int\n\n @usableFromInline\n internal typealias Element = UInt8\n\n @usableFromInline\n internal typealias SubSequence = _SmallString\n\n @inlinable @inline(__always)\n internal var startIndex: Int { return 0 }\n\n @inlinable @inline(__always)\n internal var endIndex: Int { return count }\n\n @inlinable\n internal subscript(_ idx: Int) -> UInt8 {\n @inline(__always) get {\n _internalInvariant(idx >= 0 && idx <= 15)\n if idx < 8 {\n return leadingRawBits._uncheckedGetByte(at: idx)\n } else {\n return trailingRawBits._uncheckedGetByte(at: idx &- 8)\n }\n }\n @inline(__always) set {\n _internalInvariant(idx >= 0 && idx <= 15)\n if idx < 8 {\n leadingRawBits._uncheckedSetByte(at: idx, to: newValue)\n } else {\n trailingRawBits._uncheckedSetByte(at: idx &- 8, to: newValue)\n }\n }\n }\n\n @inlinable @inline(__always)\n internal subscript(_ bounds: Range<Index>) -> SubSequence {\n get {\n // TODO(String performance): In-vector-register operation\n return self.withUTF8 { utf8 in\n let rebased = unsafe UnsafeBufferPointer(rebasing: utf8[bounds])\n return unsafe _SmallString(rebased)._unsafelyUnwrappedUnchecked\n }\n }\n // This setter is required for _SmallString to be a valid MutableCollection.\n // Since _SmallString is internal and this setter unused, we cheat.\n @_alwaysEmitIntoClient set { fatalError() }\n @_alwaysEmitIntoClient _modify { fatalError() }\n }\n}\n\nextension _SmallString {\n @inlinable @inline(__always)\n @safe\n internal func withUTF8<Result>(\n _ f: (UnsafeBufferPointer<UInt8>) throws -> Result\n ) rethrows -> Result {\n let count = self.count\n var raw = self.zeroTerminatedRawCodeUnits\n return try unsafe Swift._withUnprotectedUnsafeBytes(of: &raw) {\n let rawPtr = unsafe $0.baseAddress._unsafelyUnwrappedUnchecked\n // Rebind the underlying (UInt64, UInt64) tuple to UInt8 for the\n // duration of the closure. Accessing self after this rebind is undefined.\n let ptr = unsafe rawPtr.bindMemory(to: UInt8.self, capacity: count)\n defer {\n // Restore the memory type of self._storage\n _ = unsafe rawPtr.bindMemory(to: RawBitPattern.self, capacity: 1)\n }\n return try unsafe f(unsafe UnsafeBufferPointer(_uncheckedStart: ptr, count: count))\n }\n }\n\n // Overwrite stored code units, including uninitialized. `f` should return the\n // new count. This will re-establish the invariant after `f` that all bits\n // between the last code unit and the discriminator are unset.\n @inline(__always)\n fileprivate mutating func withMutableCapacity(\n _ f: (UnsafeMutableRawBufferPointer) throws -> Int\n ) rethrows {\n let len = try unsafe withUnsafeMutableBytes(of: &_storage) {\n try unsafe f(.init(start: $0.baseAddress, count: _SmallString.capacity))\n }\n\n if len <= 0 {\n _debugPrecondition(len == 0)\n self = _SmallString()\n return\n }\n _SmallString.zeroTrailingBytes(of: &_storage, from: len)\n self = _SmallString(leading: _storage.0, trailing: _storage.1, count: len)\n }\n\n @inlinable\n @_alwaysEmitIntoClient\n internal static func zeroTrailingBytes(\n of storage: inout RawBitPattern, from index: Int\n ) {\n _internalInvariant(index > 0)\n _internalInvariant(index <= _SmallString.capacity)\n // FIXME: Verify this on big-endian architecture\n let mask0 = (UInt64(bitPattern: ~0) &>> (8 &* ( 8 &- Swift.min(index, 8))))\n let mask1 = (UInt64(bitPattern: ~0) &>> (8 &* (16 &- Swift.max(index, 8))))\n storage.0 &= (index <= 0) ? 0 : mask0.littleEndian\n storage.1 &= (index <= 8) ? 0 : mask1.littleEndian\n }\n}\n\n// Creation\nextension _SmallString {\n @inlinable @inline(__always)\n internal init(leading: UInt64, trailing: UInt64, count: Int) {\n _internalInvariant(count <= _SmallString.capacity)\n\n let isASCII = (leading | trailing) & 0x8080_8080_8080_8080 == 0\n let discriminator = _StringObject.Nibbles\n .small(withCount: count, isASCII: isASCII)\n .littleEndian // reversed byte order on big-endian platforms\n _internalInvariant(trailing & discriminator == 0)\n\n self.init(raw: (leading, trailing | discriminator))\n _internalInvariant(self.count == count)\n }\n\n // Direct from UTF-8\n @inlinable @inline(__always)\n internal init?(_ input: UnsafeBufferPointer<UInt8>) {\n if input.isEmpty {\n self.init()\n return\n }\n\n let count = input.count\n guard count <= _SmallString.capacity else { return nil }\n\n // TODO(SIMD): The below can be replaced with just be a masked unaligned\n // vector load\n let ptr = unsafe input.baseAddress._unsafelyUnwrappedUnchecked\n let leading = unsafe _bytesToUInt64(ptr, Swift.min(input.count, 8))\n let trailing = unsafe count > 8 ? _bytesToUInt64(ptr + 8, count &- 8) : 0\n\n self.init(leading: leading, trailing: trailing, count: count)\n }\n\n @inline(__always)\n internal init(\n initializingUTF8With initializer: (\n _ buffer: UnsafeMutableBufferPointer<UInt8>\n ) throws -> Int\n ) rethrows {\n self.init()\n try unsafe self.withMutableCapacity {\n try unsafe $0.withMemoryRebound(to: UInt8.self, initializer)\n }\n self._invariantCheck()\n }\n\n @usableFromInline // @testable\n internal init?(_ base: _SmallString, appending other: _SmallString) {\n let totalCount = base.count + other.count\n guard totalCount <= _SmallString.capacity else { return nil }\n\n // TODO(SIMD): The below can be replaced with just be a couple vector ops\n\n var result = base\n var writeIdx = base.count\n for readIdx in 0..<other.count {\n result[writeIdx] = other[readIdx]\n writeIdx &+= 1\n }\n _internalInvariant(writeIdx == totalCount)\n\n let (leading, trailing) = result.zeroTerminatedRawCodeUnits\n self.init(leading: leading, trailing: trailing, count: totalCount)\n }\n}\n\n#if _runtime(_ObjC) && _pointerBitWidth(_64)\n// Cocoa interop\nextension _SmallString {\n // Resiliently create from a tagged cocoa string\n //\n @_effects(readonly) // @opaque\n @usableFromInline // testable\n internal init?(taggedCocoa cocoa: AnyObject) {\n self.init()\n var success = true\n unsafe self.withMutableCapacity {\n /*\n For regular NSTaggedPointerStrings we will always succeed here, but\n tagged NSLocalizedStrings may not fit in a SmallString\n */\n if let len = unsafe _bridgeTagged(cocoa, intoUTF8: $0) {\n return len\n }\n success = false\n return 0\n }\n if !success {\n return nil\n }\n self._invariantCheck()\n }\n \n @_effects(readonly) // @opaque\n internal init?(taggedASCIICocoa cocoa: AnyObject) {\n self.init()\n var success = true\n unsafe self.withMutableCapacity {\n /*\n For regular NSTaggedPointerStrings we will always succeed here, but\n tagged NSLocalizedStrings may not fit in a SmallString\n */\n if let len = unsafe _bridgeTaggedASCII(cocoa, intoUTF8: $0) {\n return len\n }\n success = false\n return 0\n }\n if !success {\n return nil\n }\n self._invariantCheck()\n }\n}\n#endif\n\nextension UInt64 {\n // Fetches the `i`th byte in memory order. On little-endian systems the byte\n // at i=0 is the least significant byte (LSB) while on big-endian systems the\n // byte at i=7 is the LSB.\n @inlinable @inline(__always)\n internal func _uncheckedGetByte(at i: Int) -> UInt8 {\n _internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride)\n#if _endian(big)\n let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8\n#else\n let shift = UInt64(truncatingIfNeeded: i) &* 8\n#endif\n return UInt8(truncatingIfNeeded: (self &>> shift))\n }\n\n // Sets the `i`th byte in memory order. On little-endian systems the byte\n // at i=0 is the least significant byte (LSB) while on big-endian systems the\n // byte at i=7 is the LSB.\n @inlinable @inline(__always)\n internal mutating func _uncheckedSetByte(at i: Int, to value: UInt8) {\n _internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride)\n#if _endian(big)\n let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8\n#else\n let shift = UInt64(truncatingIfNeeded: i) &* 8\n#endif\n let valueMask: UInt64 = 0xFF &<< shift\n self = (self & ~valueMask) | (UInt64(truncatingIfNeeded: value) &<< shift)\n }\n}\n\n@inlinable @inline(__always)\ninternal func _bytesToUInt64(\n _ input: UnsafePointer<UInt8>,\n _ c: Int\n) -> UInt64 {\n // FIXME: This should be unified with _loadPartialUnalignedUInt64LE.\n // Unfortunately that causes regressions in literal concatenation tests. (Some\n // owned to guaranteed specializations don't get inlined.)\n var r: UInt64 = 0\n var shift: Int = 0\n for idx in 0..<c {\n r = unsafe r | (UInt64(input[idx]) &<< shift)\n shift = shift &+ 8\n }\n // Convert from little-endian to host byte order.\n return r.littleEndian\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_SmallString.swift
cpp_apple_swift_stdlib_public_core_SmallString.swift
Swift
14,214
0.95
0.070295
0.231552
python-kit
470
2024-07-14T10:09:09.512542
Apache-2.0
false
1ff2fa671e4ea711cc4640faab1a5603
//===----------------------------------------------------------------------===//\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//===----------------------------------------------------------------------===//\n// sorted()/sort()\n//===----------------------------------------------------------------------===//\n\nextension Sequence where Element: Comparable {\n /// Returns the elements of the sequence, sorted.\n ///\n /// You can sort any sequence of elements that conform to the `Comparable`\n /// protocol by calling this method. Elements are sorted in ascending order.\n ///\n /// Here's an example of sorting a list of students' names. Strings in Swift\n /// conform to the `Comparable` protocol, so the names are sorted in\n /// ascending order according to the less-than operator (`<`).\n ///\n /// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]\n /// let sortedStudents = students.sorted()\n /// print(sortedStudents)\n /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"\n ///\n /// To sort the elements of your sequence in descending order, pass the\n /// greater-than operator (`>`) to the `sorted(by:)` method.\n ///\n /// let descendingStudents = students.sorted(by: >)\n /// print(descendingStudents)\n /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"\n ///\n /// The sorting algorithm is guaranteed to be stable. A stable sort\n /// preserves the relative order of elements that compare as equal.\n ///\n /// - Returns: A sorted array of the sequence's elements.\n ///\n /// - Complexity: O(*n* log *n*), where *n* is the length of the sequence.\n @inlinable\n public func sorted() -> [Element] {\n return sorted(by: <)\n }\n}\n\nextension Sequence {\n /// Returns the elements of the sequence, sorted using the given predicate as\n /// the comparison between elements.\n ///\n /// When you want to sort a sequence of elements that don't conform to the\n /// `Comparable` protocol, pass a predicate to this method that returns\n /// `true` when the first element should be ordered before the second. The\n /// elements of the resulting array are ordered according to the given\n /// predicate.\n ///\n /// In the following example, the predicate provides an ordering for an array\n /// of a custom `HTTPResponse` type. The predicate orders errors before\n /// successes and sorts the error responses by their error code.\n ///\n /// enum HTTPResponse {\n /// case ok\n /// case error(Int)\n /// }\n ///\n /// let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]\n /// let sortedResponses = responses.sorted {\n /// switch ($0, $1) {\n /// // Order errors by code\n /// case let (.error(aCode), .error(bCode)):\n /// return aCode < bCode\n ///\n /// // All successes are equivalent, so none is before any other\n /// case (.ok, .ok): return false\n ///\n /// // Order errors before successes\n /// case (.error, .ok): return true\n /// case (.ok, .error): return false\n /// }\n /// }\n /// print(sortedResponses)\n /// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"\n ///\n /// You also use this method to sort elements that conform to the\n /// `Comparable` protocol in descending order. To sort your sequence in\n /// descending order, pass the greater-than operator (`>`) as the\n /// `areInIncreasingOrder` parameter.\n ///\n /// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]\n /// let descendingStudents = students.sorted(by: >)\n /// print(descendingStudents)\n /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"\n ///\n /// Calling the related `sorted()` method is equivalent to calling this\n /// method and passing the less-than operator (`<`) as the predicate.\n ///\n /// print(students.sorted())\n /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"\n /// print(students.sorted(by: <))\n /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"\n ///\n /// The predicate must be a *strict weak ordering* over the elements. That\n /// is, for any elements `a`, `b`, and `c`, the following conditions must\n /// hold:\n ///\n /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)\n /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are\n /// both `true`, then `areInIncreasingOrder(a, c)` is also `true`.\n /// (Transitive comparability)\n /// - Two elements are *incomparable* if neither is ordered before the other\n /// according to the predicate. If `a` and `b` are incomparable, and `b`\n /// and `c` are incomparable, then `a` and `c` are also incomparable.\n /// (Transitive incomparability)\n ///\n /// The sorting algorithm is guaranteed to be stable. A stable sort\n /// preserves the relative order of elements for which\n /// `areInIncreasingOrder` does not establish an order.\n ///\n /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its\n /// first argument should be ordered before its second argument;\n /// otherwise, `false`.\n /// - Returns: A sorted array of the sequence's elements.\n ///\n /// - Complexity: O(*n* log *n*), where *n* is the length of the sequence.\n @inlinable\n public func sorted(\n by areInIncreasingOrder:\n (Element, Element) throws -> Bool\n ) rethrows -> [Element] {\n var result = ContiguousArray(self)\n try result.sort(by: areInIncreasingOrder)\n return Array(result)\n }\n}\n\nextension MutableCollection\nwhere Self: RandomAccessCollection, Element: Comparable {\n /// Sorts the collection in place.\n ///\n /// You can sort any mutable collection of elements that conform to the\n /// `Comparable` protocol by calling this method. Elements are sorted in\n /// ascending order.\n ///\n /// Here's an example of sorting a list of students' names. Strings in Swift\n /// conform to the `Comparable` protocol, so the names are sorted in\n /// ascending order according to the less-than operator (`<`).\n ///\n /// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]\n /// students.sort()\n /// print(students)\n /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"\n ///\n /// To sort the elements of your collection in descending order, pass the\n /// greater-than operator (`>`) to the `sort(by:)` method.\n ///\n /// students.sort(by: >)\n /// print(students)\n /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"\n ///\n /// The sorting algorithm is guaranteed to be stable. A stable sort\n /// preserves the relative order of elements that compare as equal.\n ///\n /// - Complexity: O(*n* log *n*), where *n* is the length of the collection.\n @inlinable\n public mutating func sort() {\n sort(by: <)\n }\n}\n\nextension MutableCollection where Self: RandomAccessCollection {\n /// Sorts the collection in place, using the given predicate as the\n /// comparison between elements.\n ///\n /// When you want to sort a collection of elements that don't conform to\n /// the `Comparable` protocol, pass a closure to this method that returns\n /// `true` when the first element should be ordered before the second.\n ///\n /// In the following example, the closure provides an ordering for an array\n /// of a custom enumeration that describes an HTTP response. The predicate\n /// orders errors before successes and sorts the error responses by their\n /// error code.\n ///\n /// enum HTTPResponse {\n /// case ok\n /// case error(Int)\n /// }\n ///\n /// var responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]\n /// responses.sort {\n /// switch ($0, $1) {\n /// // Order errors by code\n /// case let (.error(aCode), .error(bCode)):\n /// return aCode < bCode\n ///\n /// // All successes are equivalent, so none is before any other\n /// case (.ok, .ok): return false\n ///\n /// // Order errors before successes\n /// case (.error, .ok): return true\n /// case (.ok, .error): return false\n /// }\n /// }\n /// print(responses)\n /// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"\n ///\n /// Alternatively, use this method to sort a collection of elements that do\n /// conform to `Comparable` when you want the sort to be descending instead\n /// of ascending. Pass the greater-than operator (`>`) operator as the\n /// predicate.\n ///\n /// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]\n /// students.sort(by: >)\n /// print(students)\n /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"\n ///\n /// `areInIncreasingOrder` must be a *strict weak ordering* over the\n /// elements. That is, for any elements `a`, `b`, and `c`, the following\n /// conditions must hold:\n ///\n /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)\n /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are\n /// both `true`, then `areInIncreasingOrder(a, c)` is also `true`.\n /// (Transitive comparability)\n /// - Two elements are *incomparable* if neither is ordered before the other\n /// according to the predicate. If `a` and `b` are incomparable, and `b`\n /// and `c` are incomparable, then `a` and `c` are also incomparable.\n /// (Transitive incomparability)\n ///\n /// The sorting algorithm is guaranteed to be stable. A stable sort\n /// preserves the relative order of elements for which\n /// `areInIncreasingOrder` does not establish an order.\n ///\n /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its\n /// first argument should be ordered before its second argument;\n /// otherwise, `false`. If `areInIncreasingOrder` throws an error during\n /// the sort, the elements may be in a different order, but none will be\n /// lost.\n ///\n /// - Complexity: O(*n* log *n*), where *n* is the length of the collection.\n @inlinable\n public mutating func sort(\n by areInIncreasingOrder: (Element, Element) throws -> Bool\n ) rethrows {\n let didSortUnsafeBuffer: Void? =\n try unsafe withContiguousMutableStorageIfAvailable { buffer in\n try unsafe buffer._stableSortImpl(by: areInIncreasingOrder)\n }\n if didSortUnsafeBuffer == nil {\n // Fallback since we can't use an unsafe buffer: sort into an outside\n // array, then copy elements back in.\n let sortedElements = try sorted(by: areInIncreasingOrder)\n for (i, j) in zip(indices, sortedElements.indices) {\n self[i] = sortedElements[j]\n }\n }\n }\n}\n\nextension MutableCollection where Self: BidirectionalCollection {\n /// Sorts `self[range]` according to `areInIncreasingOrder`. Stable.\n ///\n /// - Precondition: `sortedEnd != range.lowerBound`\n /// - Precondition: `elements[..<sortedEnd]` are already in order.\n @inlinable\n internal mutating func _insertionSort(\n within range: Range<Index>,\n sortedEnd: Index,\n by areInIncreasingOrder: (Element, Element) throws -> Bool\n ) rethrows {\n var sortedEnd = sortedEnd\n \n // Continue sorting until the sorted elements cover the whole sequence.\n while sortedEnd != range.upperBound {\n var i = sortedEnd\n // Look backwards for `self[i]`'s position in the sorted sequence,\n // moving each element forward to make room.\n repeat {\n let j = index(before: i)\n \n // If `self[i]` doesn't belong before `self[j]`, we've found\n // its position.\n if try !areInIncreasingOrder(self[i], self[j]) {\n break\n }\n \n swapAt(i, j)\n i = j\n } while i != range.lowerBound\n \n formIndex(after: &sortedEnd)\n }\n }\n \n /// Sorts `self[range]` according to `areInIncreasingOrder`. Stable.\n @inlinable\n public // @testable\n mutating func _insertionSort(\n within range: Range<Index>,\n by areInIncreasingOrder: (Element, Element) throws -> Bool\n ) rethrows {\n if range.isEmpty {\n return\n }\n \n // One element is trivially already-sorted, so the actual sort can\n // start on the second element.\n let sortedEnd = index(after: range.lowerBound)\n try _insertionSort(\n within: range, sortedEnd: sortedEnd, by: areInIncreasingOrder)\n }\n \n /// Reverses the elements in the given range.\n @inlinable\n internal mutating func _reverse(\n within range: Range<Index>\n ) {\n var f = range.lowerBound\n var l = range.upperBound\n while f < l {\n formIndex(before: &l)\n swapAt(f, l)\n formIndex(after: &f)\n }\n }\n}\n\n// FIXME(ABI): unused return value\n/// Merges the elements in the ranges `lo..<mid` and `mid..<hi` using `buffer`\n/// as out-of-place storage. Stable.\n///\n/// The unused return value is legacy ABI. It was originally added as a\n/// workaround for a compiler bug (now fixed). See\n/// https://github.com/apple/swift/issues/57100 (rdar://45044610).\n///\n/// - Precondition: `lo..<mid` and `mid..<hi` must already be sorted according\n/// to `areInIncreasingOrder`.\n/// - Precondition: `buffer` must point to a region of memory at least as large\n/// as `min(mid - lo, hi - mid)`.\n/// - Postcondition: `lo..<hi` is sorted according to `areInIncreasingOrder`.\n@discardableResult\n@inlinable\ninternal func _merge<Element>(\n low: UnsafeMutablePointer<Element>,\n mid: UnsafeMutablePointer<Element>,\n high: UnsafeMutablePointer<Element>,\n buffer: UnsafeMutablePointer<Element>,\n by areInIncreasingOrder: (Element, Element) throws -> Bool\n) rethrows -> Bool {\n let lowCount = unsafe mid - low\n let highCount = unsafe high - mid\n \n var destLow = unsafe low // Lower bound of uninitialized storage\n var bufferLow = unsafe buffer // Lower bound of the initialized buffer\n var bufferHigh = unsafe buffer // Upper bound of the initialized buffer\n\n // When we exit the merge, move any remaining elements from the buffer back\n // into `destLow` (aka the collection we're sorting). The buffer can have\n // remaining elements if `areIncreasingOrder` throws, or more likely if the\n // merge runs out of elements from the array before exhausting the buffer.\n defer {\n unsafe destLow.moveInitialize(from: bufferLow, count: bufferHigh - bufferLow)\n }\n \n if lowCount < highCount {\n // Move the lower group of elements into the buffer, then traverse from\n // low to high in both the buffer and the higher group of elements.\n //\n // After moving elements, the storage and buffer look like this, where\n // `x` is uninitialized memory:\n //\n // Storage: [x, x, x, x, x, 6, 8, 8, 10, 12, 15]\n // ^ ^\n // destLow srcLow\n //\n // Buffer: [4, 4, 7, 8, 9, x, ...]\n // ^ ^\n // bufferLow bufferHigh\n unsafe buffer.moveInitialize(from: low, count: lowCount)\n unsafe bufferHigh = unsafe bufferLow + lowCount\n \n var srcLow = unsafe mid\n\n // Each iteration moves the element that compares lower into `destLow`,\n // preferring the buffer when equal to maintain stability. Elements are\n // moved from either `bufferLow` or `srcLow`, with those pointers\n // incrementing as elements are moved.\n while unsafe bufferLow < bufferHigh && srcLow < high {\n if try unsafe areInIncreasingOrder(srcLow.pointee, bufferLow.pointee) {\n unsafe destLow.moveInitialize(from: srcLow, count: 1)\n unsafe srcLow += 1\n } else {\n unsafe destLow.moveInitialize(from: bufferLow, count: 1)\n unsafe bufferLow += 1\n }\n unsafe destLow += 1\n }\n } else {\n // Move the higher group of elements into the buffer, then traverse from\n // high to low in both the buffer and the lower group of elements.\n //\n // After moving elements, the storage and buffer look like this, where\n // `x` is uninitialized memory:\n //\n // Storage: [4, 4, 7, 8, 9, 16, x, x, x, x, x]\n // ^ ^\n // srcHigh/destLow destHigh (past the end)\n //\n // Buffer: [8, 8, 10, 12, 15, x, ...]\n // ^ ^\n // bufferLow bufferHigh\n unsafe buffer.moveInitialize(from: mid, count: highCount)\n unsafe bufferHigh = unsafe bufferLow + highCount\n \n var destHigh = unsafe high\n var srcHigh = unsafe mid\n unsafe destLow = unsafe mid\n\n // Each iteration moves the element that compares higher into `destHigh`,\n // preferring the buffer when equal to maintain stability. Elements are\n // moved from either `bufferHigh - 1` or `srcHigh - 1`, with those\n // pointers decrementing as elements are moved.\n //\n // Note: At the start of each iteration, each `...High` pointer points one\n // past the element they're referring to.\n while unsafe bufferHigh > bufferLow && srcHigh > low {\n unsafe destHigh -= 1\n if try unsafe areInIncreasingOrder(\n (bufferHigh - 1).pointee, (srcHigh - 1).pointee\n ) {\n unsafe srcHigh -= 1\n unsafe destHigh.moveInitialize(from: srcHigh, count: 1)\n \n // Moved an element from the lower initialized portion to the upper,\n // sorted, initialized portion, so `destLow` moves down one.\n unsafe destLow -= 1\n } else {\n unsafe bufferHigh -= 1\n unsafe destHigh.moveInitialize(from: bufferHigh, count: 1)\n }\n }\n }\n\n return true\n}\n\n/// Calculates an optimal minimum run length for sorting a collection.\n///\n/// "... pick a minrun in range(32, 65) such that N/minrun is exactly a power\n/// of 2, or if that isn't possible, is close to, but strictly less than, a\n/// power of 2. This is easier to do than it may sound: take the first 6 bits\n/// of N, and add 1 if any of the remaining bits are set."\n/// - From the Timsort introduction, at\n/// https://svn.python.org/projects/python/trunk/Objects/listsort.txt\n///\n/// - Parameter c: The number of elements in a collection.\n/// - Returns: If `c <= 64`, returns `c`. Otherwise, returns a value in\n/// `32...64`.\n@inlinable\ninternal func _minimumMergeRunLength(_ c: Int) -> Int {\n // Max out at `2^6 == 64` elements\n let bitsToUse = 6\n \n if c < 1 << bitsToUse {\n return c\n }\n let offset = (Int.bitWidth - bitsToUse) - c.leadingZeroBitCount\n let mask = (1 << offset) - 1\n return c >> offset + (c & mask == 0 ? 0 : 1)\n}\n\n/// Returns the end of the next in-order run along with a Boolean value\n/// indicating whether the elements in `start..<end` are in descending order.\n///\n/// - Precondition: `start < elements.endIndex`\n@inlinable\ninternal func _findNextRun<C: RandomAccessCollection>(\n in elements: C,\n from start: C.Index,\n by areInIncreasingOrder: (C.Element, C.Element) throws -> Bool\n) rethrows -> (end: C.Index, descending: Bool) {\n _internalInvariant(start < elements.endIndex)\n\n var previous = start\n var current = elements.index(after: start)\n guard current < elements.endIndex else {\n // This is a one-element run, so treating it as ascending saves a\n // meaningless call to `reverse()`.\n return (current, false)\n }\n\n // Check whether the run beginning at `start` is ascending or descending.\n // An ascending run can include consecutive equal elements, but because a\n // descending run will be reversed, it must be strictly descending.\n let isDescending =\n try areInIncreasingOrder(elements[current], elements[previous])\n \n // Advance `current` until there's a break in the ascending / descending\n // pattern.\n repeat {\n previous = current\n elements.formIndex(after: &current)\n } while try current < elements.endIndex &&\n isDescending == areInIncreasingOrder(elements[current], elements[previous])\n \n return(current, isDescending)\n}\n\nextension UnsafeMutableBufferPointer {\n // FIXME(ABI): unused return value\n /// Merges the elements at `runs[i]` and `runs[i - 1]`, using `buffer` as\n /// out-of-place storage.\n ///\n /// The unused return value is legacy ABI. It was originally added as a\n /// workaround for a compiler bug (now fixed). See\n /// https://github.com/apple/swift/issues/57100 (rdar://45044610).\n ///\n /// - Precondition: `runs.count > 1` and `i > 0`\n /// - Precondition: `buffer` must have at least\n /// `min(runs[i].count, runs[i - 1].count)` uninitialized elements.\n @discardableResult\n @inlinable\n internal mutating func _mergeRuns(\n _ runs: inout [Range<Index>],\n at i: Int,\n buffer: UnsafeMutablePointer<Element>,\n by areInIncreasingOrder: (Element, Element) throws -> Bool\n ) rethrows -> Bool {\n _internalInvariant(runs[i - 1].upperBound == runs[i].lowerBound)\n let low = runs[i - 1].lowerBound\n let middle = runs[i].lowerBound\n let high = runs[i].upperBound\n \n try unsafe _merge(\n low: baseAddress! + low,\n mid: baseAddress! + middle,\n high: baseAddress! + high,\n buffer: buffer,\n by: areInIncreasingOrder)\n \n runs[i - 1] = low..<high\n runs.remove(at: i)\n\n return true\n }\n\n // FIXME(ABI): unused return value\n /// Merges upper elements of `runs` until the required invariants are\n /// satisfied.\n ///\n /// The unused return value is legacy ABI. It was originally added as a\n /// workaround for a compiler bug (now fixed). See\n /// https://github.com/apple/swift/issues/57100 (rdar://45044610).\n ///\n /// - Precondition: `buffer` must have at least\n /// `min(runs[i].count, runs[i - 1].count)` uninitialized elements.\n /// - Precondition: The ranges in `runs` must be consecutive, such that for\n /// any i, `runs[i].upperBound == runs[i + 1].lowerBound`.\n @discardableResult\n @inlinable\n internal mutating func _mergeTopRuns(\n _ runs: inout [Range<Index>],\n buffer: UnsafeMutablePointer<Element>,\n by areInIncreasingOrder: (Element, Element) throws -> Bool\n ) rethrows -> Bool {\n // The invariants for the `runs` array are:\n // (a) - for all i in 2..<runs.count:\n // - runs[i - 2].count > runs[i - 1].count + runs[i].count\n // (b) - for c = runs.count - 1:\n // - runs[c - 1].count > runs[c].count\n //\n // Loop until the invariant is satisfied for the top four elements of\n // `runs`. Because this method is called for every added run, and only\n // the top three runs are ever merged, this guarantees the invariant holds\n // for the whole array.\n //\n // At all times, `runs` is one of the following, where W, X, Y, and Z are\n // the counts of their respective ranges:\n // - [ ...?, W, X, Y, Z ]\n // - [ X, Y, Z ]\n // - [ Y, Z ]\n //\n // If W > X + Y, X > Y + Z, and Y > Z, then the invariants are satisfied\n // for the entirety of `runs`.\n \n // The invariant is always in place for a single element.\n while runs.count > 1 {\n var lastIndex = runs.count - 1\n \n // Check for the three invariant-breaking conditions, and break out of\n // the while loop if none are met.\n if lastIndex >= 3 &&\n (runs[lastIndex - 3].count <=\n runs[lastIndex - 2].count + runs[lastIndex - 1].count)\n {\n // Second-to-last three runs do not follow W > X + Y.\n // Always merge Y with the smaller of X or Z.\n if runs[lastIndex - 2].count < runs[lastIndex].count {\n lastIndex -= 1\n }\n } else if lastIndex >= 2 &&\n (runs[lastIndex - 2].count <=\n runs[lastIndex - 1].count + runs[lastIndex].count)\n {\n // Last three runs do not follow X > Y + Z.\n // Always merge Y with the smaller of X or Z.\n if runs[lastIndex - 2].count < runs[lastIndex].count {\n lastIndex -= 1\n }\n } else if runs[lastIndex - 1].count <= runs[lastIndex].count {\n // Last two runs do not follow Y > Z, so merge Y and Z.\n // This block is intentionally blank--the merge happens below.\n } else {\n // All invariants satisfied!\n break\n }\n \n // Merge the runs at `i` and `i - 1`.\n try unsafe _mergeRuns(\n &runs, at: lastIndex, buffer: buffer, by: areInIncreasingOrder)\n }\n\n return true\n }\n\n // FIXME(ABI): unused return value\n /// Merges elements of `runs` until only one run remains.\n ///\n /// The unused return value is legacy ABI. It was originally added as a\n /// workaround for a compiler bug (now fixed). See\n /// https://github.com/apple/swift/issues/57100 (rdar://45044610).\n ///\n /// - Precondition: `buffer` must have at least\n /// `min(runs[i].count, runs[i - 1].count)` uninitialized elements.\n /// - Precondition: The ranges in `runs` must be consecutive, such that for\n /// any i, `runs[i].upperBound == runs[i + 1].lowerBound`.\n @discardableResult\n @inlinable\n internal mutating func _finalizeRuns(\n _ runs: inout [Range<Index>],\n buffer: UnsafeMutablePointer<Element>,\n by areInIncreasingOrder: (Element, Element) throws -> Bool\n ) rethrows -> Bool {\n while runs.count > 1 {\n try unsafe _mergeRuns(\n &runs, at: runs.count - 1, buffer: buffer, by: areInIncreasingOrder)\n }\n\n return true\n }\n \n /// Sorts the elements of this buffer according to `areInIncreasingOrder`,\n /// using a stable, adaptive merge sort.\n ///\n /// The adaptive algorithm used is Timsort, modified to perform a straight\n /// merge of the elements using a temporary buffer.\n @inlinable\n public mutating func _stableSortImpl(\n by areInIncreasingOrder: (Element, Element) throws -> Bool\n ) rethrows {\n let minimumRunLength = _minimumMergeRunLength(count)\n if count <= minimumRunLength {\n try unsafe _insertionSort(\n within: startIndex..<endIndex, by: areInIncreasingOrder)\n return\n }\n\n // Use array's allocating initializer to create a temporary buffer---this\n // keeps the buffer allocation going through the same tail-allocated path\n // as other allocating methods.\n //\n // There's no need to set the initialized count within the initializing\n // closure, since the buffer is guaranteed to be uninitialized at exit.\n _ = try unsafe Array<Element>(_unsafeUninitializedCapacity: count / 2) {\n buffer, _ in\n var runs: [Range<Index>] = []\n \n var start = startIndex\n while start < endIndex {\n // Find the next consecutive run, reversing it if necessary.\n var (end, descending) =\n unsafe try _findNextRun(in: self, from: start, by: areInIncreasingOrder)\n if descending {\n unsafe _reverse(within: start..<end)\n }\n \n // If the current run is shorter than the minimum length, use the\n // insertion sort to extend it.\n if end < endIndex && end - start < minimumRunLength {\n let newEnd = Swift.min(endIndex, start + minimumRunLength)\n try unsafe _insertionSort(\n within: start..<newEnd, sortedEnd: end, by: areInIncreasingOrder)\n end = newEnd\n }\n \n // Append this run and merge down as needed to maintain the `runs`\n // invariants.\n runs.append(start..<end)\n try unsafe _mergeTopRuns(\n &runs, buffer: buffer.baseAddress!, by: areInIncreasingOrder)\n start = end\n }\n \n try unsafe _finalizeRuns(\n &runs, buffer: buffer.baseAddress!, by: areInIncreasingOrder)\n _internalInvariant(runs.count == 1, "Didn't complete final merge")\n }\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Sort.swift
cpp_apple_swift_stdlib_public_core_Sort.swift
Swift
27,826
0.95
0.115007
0.583459
react-lib
419
2024-08-05T07:34:24.156481
MIT
false
3c27e5905ce78c6ac24ce1989605107a
//===--- MutableRawSpan.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 - 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 SPAN_COMPATIBILITY_STUB\nimport Swift\n#endif\n\n// A MutableRawSpan represents a span of memory which\n// contains initialized `Element` instances.\n@safe\n@frozen\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\npublic struct MutableRawSpan: ~Copyable & ~Escapable {\n @usableFromInline\n internal let _pointer: UnsafeMutableRawPointer?\n\n @usableFromInline\n internal let _count: Int\n\n @_alwaysEmitIntoClient\n internal func _start() -> UnsafeMutableRawPointer {\n unsafe _pointer._unsafelyUnwrappedUnchecked\n }\n\n @unsafe\n @_unsafeNonescapableResult\n @_alwaysEmitIntoClient\n @lifetime(borrow pointer)\n internal init(\n _unchecked pointer: UnsafeMutableRawPointer?,\n byteCount: Int\n ) {\n unsafe _pointer = pointer\n _count = byteCount\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableRawSpan: @unchecked Sendable {}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableRawSpan {\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow bytes)\n public init(\n _unsafeBytes bytes: UnsafeMutableRawBufferPointer\n ) {\n let (baseAddress, count) = (bytes.baseAddress, bytes.count)\n let span = unsafe MutableRawSpan(_unchecked: baseAddress, byteCount: count)\n self = unsafe _overrideLifetime(span, borrowing: bytes)\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow bytes)\n public init(\n _unsafeBytes bytes: borrowing Slice<UnsafeMutableRawBufferPointer>\n ) {\n let rebased = unsafe UnsafeMutableRawBufferPointer(rebasing: bytes)\n let span = unsafe MutableRawSpan(_unsafeBytes: rebased)\n self = unsafe _overrideLifetime(span, borrowing: bytes)\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow pointer)\n public init(\n _unsafeStart pointer: UnsafeMutableRawPointer,\n byteCount: Int\n ) {\n _precondition(byteCount >= 0, "Count must not be negative")\n unsafe self.init(_unchecked: pointer, byteCount: byteCount)\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow elements)\n public init<Element: BitwiseCopyable>(\n _unsafeElements elements: UnsafeMutableBufferPointer<Element>\n ) {\n let bytes = UnsafeMutableRawBufferPointer(elements)\n let span = unsafe MutableRawSpan(_unsafeBytes: bytes)\n self = unsafe _overrideLifetime(span, borrowing: elements)\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow elements)\n public init<Element: BitwiseCopyable>(\n _unsafeElements elements: borrowing Slice<UnsafeMutableBufferPointer<Element>>\n ) {\n let rebased = unsafe UnsafeMutableBufferPointer(rebasing: elements)\n let span = unsafe MutableRawSpan(_unsafeElements: rebased)\n self = unsafe _overrideLifetime(span, borrowing: elements)\n }\n\n @_alwaysEmitIntoClient\n @lifetime(&elements)\n public init<Element: BitwiseCopyable>(\n _elements elements: inout MutableSpan<Element>\n ) {\n let (start, count) = unsafe (elements._pointer, elements._count)\n let span = unsafe MutableRawSpan(\n _unchecked: start,\n byteCount: count == 1 ? MemoryLayout<Element>.size\n : count &* MemoryLayout<Element>.stride\n )\n self = unsafe _overrideLifetime(span, mutating: &elements)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableRawSpan {\n @_alwaysEmitIntoClient\n public var byteCount: Int { _count }\n\n @_alwaysEmitIntoClient\n public var isEmpty: Bool { byteCount == 0 }\n\n @_alwaysEmitIntoClient\n public var byteOffsets: Range<Int> {\n unsafe Range(_uncheckedBounds: (0, byteCount))\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableRawSpan {\n\n @_alwaysEmitIntoClient\n public func withUnsafeBytes<E: Error, Result: ~Copyable>(\n _ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result\n ) throws(E) -> Result {\n guard let pointer = unsafe _pointer, _count > 0 else {\n return try unsafe body(.init(start: nil, count: 0))\n }\n return try unsafe body(.init(start: pointer, count: _count))\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func withUnsafeMutableBytes<E: Error, Result: ~Copyable>(\n _ body: (UnsafeMutableRawBufferPointer) throws(E) -> Result\n ) throws(E) -> Result {\n guard let pointer = unsafe _pointer, _count > 0 else {\n return try unsafe body(.init(start: nil, count: 0))\n }\n return try unsafe body(.init(start: pointer, count: _count))\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension RawSpan {\n\n @_alwaysEmitIntoClient\n @lifetime(borrow mutableRawSpan)\n public init(_mutableRawSpan mutableRawSpan: borrowing MutableRawSpan) {\n let (start, count) = unsafe (mutableRawSpan._start(), mutableRawSpan._count)\n let span = unsafe RawSpan(_unsafeStart: start, byteCount: count)\n self = unsafe _overrideLifetime(span, borrowing: mutableRawSpan)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableRawSpan {\n\n public var bytes: RawSpan {\n @_alwaysEmitIntoClient\n @lifetime(borrow self)\n borrowing get {\n return RawSpan(_mutableRawSpan: self)\n }\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow self)\n public borrowing func _unsafeView<T: BitwiseCopyable>(\n as type: T.Type\n ) -> Span<T> {\n let bytes = unsafe UnsafeRawBufferPointer(start: _pointer, count: _count)\n let span = unsafe Span<T>(_unsafeBytes: bytes)\n return unsafe _overrideLifetime(span, borrowing: self)\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(&self)\n public mutating func _unsafeMutableView<T: BitwiseCopyable>(\n as type: T.Type\n ) -> MutableSpan<T> {\n let bytes = unsafe UnsafeMutableRawBufferPointer(\n start: _pointer, count: _count\n )\n let span = unsafe MutableSpan<T>(_unsafeBytes: bytes)\n return unsafe _overrideLifetime(span, mutating: &self)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableRawSpan {\n\n /// Returns a new instance of the given type, constructed from the raw memory\n /// at the specified offset.\n ///\n /// The memory at this pointer plus `offset` must be properly aligned for\n /// accessing `T` and initialized to `T` or another type that is layout\n /// compatible with `T`.\n ///\n /// This is an unsafe operation. Failure to meet the preconditions\n /// above may produce an invalid value of `T`.\n ///\n /// - Parameters:\n /// - offset: The offset from this pointer, in bytes. `offset` must be\n /// nonnegative. The default is zero.\n /// - type: The type of the instance to create.\n /// - Returns: A new instance of type `T`, read from the raw bytes at\n /// `offset`. The returned instance is memory-managed and unassociated\n /// with the value in the memory referenced by this pointer.\n @unsafe\n @_alwaysEmitIntoClient\n public func unsafeLoad<T>(\n fromByteOffset offset: Int = 0, as: T.Type\n ) -> T {\n _precondition(\n UInt(bitPattern: offset) <= UInt(bitPattern: _count) &&\n MemoryLayout<T>.size <= (_count &- offset),\n "Byte offset range out of bounds"\n )\n return unsafe unsafeLoad(fromUncheckedByteOffset: offset, as: T.self)\n }\n\n /// Returns a new instance of the given type, constructed from the raw memory\n /// at the specified offset.\n ///\n /// The memory at this pointer plus `offset` must be properly aligned for\n /// accessing `T` and initialized to `T` or another type that is layout\n /// compatible with `T`.\n ///\n /// This is an unsafe operation. This function does not validate the bounds\n /// of the memory access, and failure to meet the preconditions\n /// above may produce an invalid value of `T`.\n ///\n /// - Parameters:\n /// - offset: The offset from this pointer, in bytes. `offset` must be\n /// nonnegative. The default is zero.\n /// - type: The type of the instance to create.\n /// - Returns: A new instance of type `T`, read from the raw bytes at\n /// `offset`. The returned instance is memory-managed and unassociated\n /// with the value in the memory referenced by this pointer.\n @unsafe\n @_alwaysEmitIntoClient\n public func unsafeLoad<T>(\n fromUncheckedByteOffset offset: Int, as: T.Type\n ) -> T {\n unsafe _start().load(fromByteOffset: offset, as: T.self)\n }\n\n /// Returns a new instance of the given type, constructed from the raw memory\n /// at the specified offset.\n ///\n /// The memory at this pointer plus `offset` must be initialized to `T`\n /// or another type that is layout compatible with `T`.\n ///\n /// This is an unsafe operation. Failure to meet the preconditions\n /// above may produce an invalid value of `T`.\n ///\n /// - Parameters:\n /// - offset: The offset from this pointer, in bytes. `offset` must be\n /// nonnegative. The default is zero.\n /// - type: The type of the instance to create.\n /// - Returns: A new instance of type `T`, read from the raw bytes at\n /// `offset`. The returned instance isn't associated\n /// with the value in the range of memory referenced by this pointer.\n @unsafe\n @_alwaysEmitIntoClient\n public func unsafeLoadUnaligned<T: BitwiseCopyable>(\n fromByteOffset offset: Int = 0, as: T.Type\n ) -> T {\n _precondition(\n UInt(bitPattern: offset) <= UInt(bitPattern: _count) &&\n MemoryLayout<T>.size <= (_count &- offset),\n "Byte offset range out of bounds"\n )\n return unsafe unsafeLoadUnaligned(fromUncheckedByteOffset: offset, as: T.self)\n }\n\n /// Returns a new instance of the given type, constructed from the raw memory\n /// at the specified offset.\n ///\n /// The memory at this pointer plus `offset` must be initialized to `T`\n /// or another type that is layout compatible with `T`.\n ///\n /// This is an unsafe operation. This function does not validate the bounds\n /// of the memory access, and failure to meet the preconditions\n /// above may produce an invalid value of `T`.\n ///\n /// - Parameters:\n /// - offset: The offset from this pointer, in bytes. `offset` must be\n /// nonnegative. The default is zero.\n /// - type: The type of the instance to create.\n /// - Returns: A new instance of type `T`, read from the raw bytes at\n /// `offset`. The returned instance isn't associated\n /// with the value in the range of memory referenced by this pointer.\n @unsafe\n @_alwaysEmitIntoClient\n public func unsafeLoadUnaligned<T: BitwiseCopyable>(\n fromUncheckedByteOffset offset: Int, as: T.Type\n ) -> T {\n unsafe _start().loadUnaligned(fromByteOffset: offset, as: T.self)\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func storeBytes<T: BitwiseCopyable>(\n of value: T, toByteOffset offset: Int = 0, as type: T.Type\n ) {\n _precondition(\n UInt(bitPattern: offset) <= UInt(bitPattern: _count) &&\n MemoryLayout<T>.size <= (_count &- offset),\n "Byte offset range out of bounds"\n )\n unsafe storeBytes(of: value, toUncheckedByteOffset: offset, as: type)\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func storeBytes<T: BitwiseCopyable>(\n of value: T, toUncheckedByteOffset offset: Int, as type: T.Type\n ) {\n unsafe _start().storeBytes(of: value, toByteOffset: offset, as: type)\n }\n}\n\n// FIXME: The functions in this extension crash the SIL optimizer when built inside\n// the stub. But these declarations don't generate a public symbol anyway.\n#if !SPAN_COMPATIBILITY_STUB\n\n//MARK: copyMemory\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableRawSpan {\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update<S: Sequence>(\n from source: S\n ) -> (unwritten: S.Iterator, byteOffset: Int) where S.Element: BitwiseCopyable {\n var iterator = source.makeIterator()\n let offset = update(from: &iterator)\n return (iterator, offset)\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update<Element: BitwiseCopyable>(\n from elements: inout some IteratorProtocol<Element>\n ) -> Int {\n var offset = 0\n while offset + MemoryLayout<Element>.stride <= _count {\n guard let element = elements.next() else { break }\n unsafe storeBytes(\n of: element, toUncheckedByteOffset: offset, as: Element.self\n )\n offset &+= MemoryLayout<Element>.stride\n }\n return offset\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update<C: Collection>(\n fromContentsOf source: C\n ) -> Int where C.Element: BitwiseCopyable {\n let newOffset = source.withContiguousStorageIfAvailable {\n self.update(fromContentsOf: unsafe RawSpan(_unsafeElements: $0))\n }\n if let newOffset { return newOffset }\n\n var elements = source.makeIterator()\n let lastOffset = update(from: &elements)\n _precondition(\n elements.next() == nil,\n "destination span cannot contain every element from source."\n )\n return lastOffset\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update<Element: BitwiseCopyable>(\n fromContentsOf source: Span<Element>\n ) -> Int {\n// update(from: source.bytes)\n unsafe source.withUnsafeBytes {\n unsafe update(fromContentsOf: $0)\n }\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update<Element: BitwiseCopyable>(\n fromContentsOf source: borrowing MutableSpan<Element>\n ) -> Int {\n// update(from: source.span.bytes)\n unsafe source.withUnsafeBytes {\n unsafe update(fromContentsOf: $0)\n }\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(\n fromContentsOf source: RawSpan\n ) -> Int {\n if source.byteCount == 0 { return 0 }\n unsafe source.withUnsafeBytes {\n unsafe _start().copyMemory(from: $0.baseAddress!, byteCount: $0.count)\n }\n return source.byteCount\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(\n fromContentsOf source: borrowing MutableRawSpan\n ) -> Int {\n update(fromContentsOf: source.bytes)\n }\n}\n#endif\n\n// MARK: sub-spans\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableRawSpan {\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `MutableSpan`.\n ///\n /// - Returns: A `MutableSpan` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(_ bounds: Range<Int>) -> Self {\n _precondition(\n UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&\n UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),\n "Index range out of bounds"\n )\n return unsafe extracting(unchecked: bounds)\n }\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// This function does not validate `bounds`; this is an unsafe operation.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `MutableSpan`.\n ///\n /// - Returns: A `MutableSpan` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(unchecked bounds: Range<Int>) -> Self {\n let newStart = unsafe _pointer?.advanced(by: bounds.lowerBound)\n let newSpan = unsafe Self(_unchecked: newStart, byteCount: bounds.count)\n return unsafe _overrideLifetime(newSpan, mutating: &self)\n }\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `MutableSpan`.\n ///\n /// - Returns: A `MutableSpan` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(\n _ bounds: some RangeExpression<Int>\n ) -> Self {\n extracting(bounds.relative(to: byteOffsets))\n }\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// This function does not validate `bounds`; this is an unsafe operation.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `MutableSpan`.\n ///\n /// - Returns: A `MutableSpan` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(unchecked bounds: ClosedRange<Int>) -> Self {\n let range = unsafe Range(\n _uncheckedBounds: (bounds.lowerBound, bounds.upperBound+1)\n )\n return unsafe extracting(unchecked: range)\n }\n\n /// Constructs a new span over all the items of this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Returns: A `MutableSpan` over all the items of this span.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(_: UnboundedRange) -> Self {\n let newSpan = unsafe Self(_unchecked: _start(), byteCount: _count)\n return unsafe _overrideLifetime(newSpan, mutating: &self)\n }\n}\n\n// MARK: prefixes and suffixes\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableRawSpan {\n\n /// Returns a span containing the initial elements of this span,\n /// up to the specified maximum length.\n ///\n /// If the maximum length exceeds the length of this span,\n /// the result contains all the elements.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter maxLength: The maximum number of elements to return.\n /// `maxLength` must be greater than or equal to zero.\n /// - Returns: A span with at most `maxLength` elements.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(first maxLength: Int) -> Self {\n _precondition(maxLength >= 0, "Can't have a prefix of negative length")\n let newCount = min(maxLength, byteCount)\n let newSpan = unsafe Self(_unchecked: _pointer, byteCount: newCount)\n return unsafe _overrideLifetime(newSpan, mutating: &self)\n }\n\n /// Returns a span over all but the given number of trailing elements.\n ///\n /// If the number of elements to drop exceeds the number of elements in\n /// the span, the result is an empty span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter k: The number of elements to drop off the end of\n /// the span. `k` must be greater than or equal to zero.\n /// - Returns: A span leaving off the specified number of elements at the end.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(droppingLast k: Int) -> Self {\n _precondition(k >= 0, "Can't drop a negative number of elements")\n let droppedCount = min(k, byteCount)\n let newCount = byteCount &- droppedCount\n let newSpan = unsafe Self(_unchecked: _pointer, byteCount: newCount)\n return unsafe _overrideLifetime(newSpan, mutating: &self)\n }\n\n /// Returns a span containing the final elements of the span,\n /// up to the given maximum length.\n ///\n /// If the maximum length exceeds the length of this span,\n /// the result contains all the elements.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter maxLength: The maximum number of elements to return.\n /// `maxLength` must be greater than or equal to zero.\n /// - Returns: A span with at most `maxLength` elements.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(last maxLength: Int) -> Self {\n _precondition(maxLength >= 0, "Can't have a suffix of negative length")\n let newCount = min(maxLength, byteCount)\n let newStart = unsafe _pointer?.advanced(by: byteCount &- newCount)\n let newSpan = unsafe Self(_unchecked: newStart, byteCount: newCount)\n return unsafe _overrideLifetime(newSpan, copying: self)\n }\n\n /// Returns a span over all but the given number of initial elements.\n ///\n /// If the number of elements to drop exceeds the number of elements in\n /// the span, the result is an empty span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter k: The number of elements to drop from the beginning of\n /// the span. `k` must be greater than or equal to zero.\n /// - Returns: A span starting after the specified number of elements.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(droppingFirst k: Int) -> Self {\n _precondition(k >= 0, "Can't drop a negative number of bytes")\n let droppedCount = min(k, byteCount)\n let newStart = unsafe _pointer?.advanced(by: droppedCount)\n let newCount = byteCount &- droppedCount\n let newSpan = unsafe Self(_unchecked: newStart, byteCount: newCount)\n return unsafe _overrideLifetime(newSpan, mutating: &self)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Span_MutableRawSpan.swift
cpp_apple_swift_stdlib_public_core_Span_MutableRawSpan.swift
Swift
23,815
0.95
0.025373
0.34846
react-lib
580
2024-03-06T06:53:46.680515
MIT
false
c380e1539d316ca6847b2aefbe1dca5c
//===--- MutableSpan.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 - 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 SPAN_COMPATIBILITY_STUB\nimport Swift\n#endif\n\n// A MutableSpan<Element> represents a span of memory which\n// contains initialized `Element` instances.\n@safe\n@frozen\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\npublic struct MutableSpan<Element: ~Copyable>\n: ~Copyable, ~Escapable {\n @usableFromInline\n internal let _pointer: UnsafeMutableRawPointer?\n\n @usableFromInline\n internal let _count: Int\n\n @_alwaysEmitIntoClient\n internal func _start() -> UnsafeMutableRawPointer {\n unsafe _pointer._unsafelyUnwrappedUnchecked\n }\n\n @unsafe\n @_unsafeNonescapableResult\n @_alwaysEmitIntoClient\n @lifetime(borrow start)\n internal init(\n _unchecked start: UnsafeMutableRawPointer?,\n count: Int\n ) {\n unsafe _pointer = start\n _count = count\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan: @unchecked Sendable where Element: Sendable {}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: ~Copyable {\n\n @unsafe\n @_unsafeNonescapableResult\n @usableFromInline\n @lifetime(borrow elements)\n internal init(\n _unchecked elements: UnsafeMutableBufferPointer<Element>\n ) {\n unsafe _pointer = .init(elements.baseAddress)\n _count = elements.count\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n public init(\n _unsafeElements buffer: UnsafeMutableBufferPointer<Element>\n ) {\n _precondition(\n ((Int(bitPattern: buffer.baseAddress) &\n (MemoryLayout<Element>.alignment &- 1)) == 0),\n "baseAddress must be properly aligned to access Element"\n )\n let ms = unsafe MutableSpan<Element>(_unchecked: buffer)\n self = unsafe _overrideLifetime(ms, borrowing: buffer)\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow start)\n public init(\n _unsafeStart start: UnsafeMutablePointer<Element>,\n count: Int\n ) {\n _precondition(count >= 0, "Count must not be negative")\n let buffer = unsafe UnsafeMutableBufferPointer(start: start, count: count)\n let ms = unsafe MutableSpan(_unsafeElements: buffer)\n self = unsafe _overrideLifetime(ms, borrowing: start)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan {\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow elements)\n public init(\n _unsafeElements elements: borrowing Slice<UnsafeMutableBufferPointer<Element>>\n ) {\n let rb = unsafe UnsafeMutableBufferPointer(rebasing: elements)\n let ms = unsafe MutableSpan(_unsafeElements: rb)\n self = unsafe _overrideLifetime(ms, borrowing: elements)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: BitwiseCopyable {\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n public init(\n _unsafeBytes buffer: UnsafeMutableRawBufferPointer\n ) {\n _precondition(\n ((Int(bitPattern: buffer.baseAddress) &\n (MemoryLayout<Element>.alignment &- 1)) == 0),\n "baseAddress must be properly aligned to access Element"\n )\n let (byteCount, stride) = (buffer.count, MemoryLayout<Element>.stride)\n let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride)\n _precondition(remainder == 0, "Span must contain a whole number of elements")\n let elements = unsafe UnsafeMutableBufferPointer<Element>(\n start: buffer.baseAddress?.assumingMemoryBound(to: Element.self),\n count: count\n )\n let ms = unsafe MutableSpan(_unsafeElements: elements)\n self = unsafe _overrideLifetime(ms, borrowing: buffer)\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow pointer)\n public init(\n _unsafeStart pointer: UnsafeMutableRawPointer,\n byteCount: Int\n ) {\n _precondition(byteCount >= 0, "Count must not be negative")\n let bytes = unsafe UnsafeMutableRawBufferPointer(\n start: pointer, count: byteCount\n )\n let ms = unsafe MutableSpan(_unsafeBytes: bytes)\n self = unsafe _overrideLifetime(ms, borrowing: pointer)\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n public init(\n _unsafeBytes buffer: borrowing Slice<UnsafeMutableRawBufferPointer>\n ) {\n let bytes = unsafe UnsafeMutableRawBufferPointer(rebasing: buffer)\n let ms = unsafe MutableSpan(_unsafeBytes: bytes)\n self = unsafe _overrideLifetime(ms, borrowing: buffer)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span where Element: ~Copyable {\n\n @_alwaysEmitIntoClient\n @lifetime(borrow mutableSpan)\n public init(_mutableSpan mutableSpan: borrowing MutableSpan<Element>) {\n let pointer =\n unsafe mutableSpan._pointer?.assumingMemoryBound(to: Element.self)\n let buffer = unsafe UnsafeBufferPointer(\n start: pointer, count: mutableSpan.count\n )\n let span = unsafe Span(_unsafeElements: buffer)\n self = unsafe _overrideLifetime(span, borrowing: mutableSpan)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: ~Copyable {\n\n @_alwaysEmitIntoClient\n public var span: Span<Element> {\n @lifetime(borrow self)\n borrowing get {\n Span(_mutableSpan: self)\n }\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension RawSpan {\n\n @_alwaysEmitIntoClient\n @lifetime(borrow mutableSpan)\n public init<Element: BitwiseCopyable>(\n _mutableSpan mutableSpan: borrowing MutableSpan<Element>\n ) {\n let pointer = unsafe mutableSpan._pointer\n let byteCount = mutableSpan.count &* MemoryLayout<Element>.stride\n let buffer = unsafe UnsafeRawBufferPointer(start: pointer, count: byteCount)\n let rawSpan = unsafe RawSpan(_unsafeBytes: buffer)\n self = unsafe _overrideLifetime(rawSpan, borrowing: mutableSpan)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: ~Copyable {\n\n @_alwaysEmitIntoClient\n public var _description: String {\n let addr = unsafe String(\n UInt(bitPattern: _pointer), radix: 16, uppercase: false\n )\n return "(0x\(addr), \(_count))"\n }\n}\n\n//MARK: Collection, RandomAccessCollection\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: ~Copyable {\n\n @_alwaysEmitIntoClient\n public var count: Int { _count }\n\n @_alwaysEmitIntoClient\n public var isEmpty: Bool { _count == 0 }\n\n public typealias Index = Int\n\n @_alwaysEmitIntoClient\n public var indices: Range<Index> {\n unsafe Range(_uncheckedBounds: (0, _count))\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: BitwiseCopyable {\n\n /// Construct a RawSpan over the memory represented by this span\n ///\n /// - Returns: a RawSpan over the memory represented by this span\n @_alwaysEmitIntoClient\n public var bytes: RawSpan {\n @lifetime(borrow self)\n borrowing get {\n RawSpan(_mutableSpan: self)\n }\n }\n\n /// Construct a MutableRawSpan over the memory represented by this span\n ///\n /// - Returns: a MutableRawSpan over the memory represented by this span\n @_alwaysEmitIntoClient\n public var mutableBytes: MutableRawSpan {\n @lifetime(&self)\n mutating get {\n MutableRawSpan(_elements: &self)\n }\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: ~Copyable {\n\n /// Accesses the element at the specified position in the `Span`.\n ///\n /// - Parameter position: The offset of the element to access. `position`\n /// must be greater or equal to zero, and less than `count`.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public subscript(_ position: Index) -> Element {\n unsafeAddress {\n _precondition(indices.contains(position), "index out of bounds")\n return unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: position))\n }\n @lifetime(self: copy self)\n unsafeMutableAddress {\n _precondition(indices.contains(position), "index out of bounds")\n return unsafe _unsafeAddressOfElement(unchecked: position)\n }\n }\n\n /// Accesses the element at the specified position in the `Span`.\n ///\n /// This subscript does not validate `position`; this is an unsafe operation.\n ///\n /// - Parameter position: The offset of the element to access. `position`\n /// must be greater or equal to zero, and less than `count`.\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n public subscript(unchecked position: Index) -> Element {\n unsafeAddress {\n unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: position))\n }\n @lifetime(self: copy self)\n unsafeMutableAddress {\n unsafe _unsafeAddressOfElement(unchecked: position)\n }\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n internal func _unsafeAddressOfElement(\n unchecked position: Index\n ) -> UnsafeMutablePointer<Element> {\n let elementOffset = position &* MemoryLayout<Element>.stride\n let address = unsafe _start().advanced(by: elementOffset)\n return unsafe address.assumingMemoryBound(to: Element.self)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: ~Copyable {\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func swapAt(_ i: Index, _ j: Index) {\n _precondition(indices.contains(Index(i)))\n _precondition(indices.contains(Index(j)))\n unsafe swapAt(unchecked: i, unchecked: j)\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func swapAt(unchecked i: Index, unchecked j: Index) {\n let pi = unsafe _unsafeAddressOfElement(unchecked: i)\n let pj = unsafe _unsafeAddressOfElement(unchecked: j)\n let temporary = unsafe pi.move()\n unsafe pi.initialize(to: pj.move())\n unsafe pj.initialize(to: consume temporary)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: BitwiseCopyable {\n\n /// Accesses the element at the specified position in the `Span`.\n ///\n /// - Parameter position: The offset of the element to access. `position`\n /// must be greater or equal to zero, and less than `count`.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public subscript(_ position: Index) -> Element {\n get {\n _precondition(indices.contains(position), "index out of bounds")\n return unsafe self[unchecked: position]\n }\n @lifetime(self: copy self)\n set {\n _precondition(indices.contains(position), "index out of bounds")\n unsafe self[unchecked: position] = newValue\n }\n }\n\n /// Accesses the element at the specified position in the `Span`.\n ///\n /// This subscript does not validate `position`; this is an unsafe operation.\n ///\n /// - Parameter position: The offset of the element to access. `position`\n /// must be greater or equal to zero, and less than `count`.\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n public subscript(unchecked position: Index) -> Element {\n get {\n let offset = position&*MemoryLayout<Element>.stride\n return unsafe _start().loadUnaligned(\n fromByteOffset: offset, as: Element.self\n )\n }\n @lifetime(self: copy self)\n set {\n let offset = position&*MemoryLayout<Element>.stride\n unsafe _start().storeBytes(\n of: newValue, toByteOffset: offset, as: Element.self\n )\n }\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: ~Copyable {\n\n //FIXME: mark closure parameter as non-escaping\n @_alwaysEmitIntoClient\n public func withUnsafeBufferPointer<E: Error, Result: ~Copyable>(\n _ body: (_ buffer: UnsafeBufferPointer<Element>) throws(E) -> Result\n ) throws(E) -> Result {\n try unsafe Span(_mutableSpan: self).withUnsafeBufferPointer(body)\n }\n\n //FIXME: mark closure parameter as non-escaping\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func withUnsafeMutableBufferPointer<\n E: Error, Result: ~Copyable\n >(\n _ body: (UnsafeMutableBufferPointer<Element>) throws(E) -> Result\n ) throws(E) -> Result {\n guard let pointer = unsafe _pointer, count > 0 else {\n return try unsafe body(.init(start: nil, count: 0))\n }\n // bind memory by hand to sidestep alignment concerns\n let binding = Builtin.bindMemory(\n pointer._rawValue, count._builtinWordValue, Element.self\n )\n defer { Builtin.rebindMemory(pointer._rawValue, binding) }\n return try unsafe body(.init(start: .init(pointer._rawValue), count: count))\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: BitwiseCopyable {\n\n //FIXME: mark closure parameter as non-escaping\n @_alwaysEmitIntoClient\n public func withUnsafeBytes<E: Error, Result: ~Copyable>(\n _ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result\n ) throws(E) -> Result {\n try unsafe RawSpan(_mutableSpan: self).withUnsafeBytes(body)\n }\n\n //FIXME: mark closure parameter as non-escaping\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func withUnsafeMutableBytes<E: Error, Result: ~Copyable>(\n _ body: (_ buffer: UnsafeMutableRawBufferPointer) throws(E) -> Result\n ) throws(E) -> Result {\n let bytes = unsafe UnsafeMutableRawBufferPointer(\n start: (_count == 0) ? nil : _start(),\n count: _count &* MemoryLayout<Element>.stride\n )\n return try unsafe body(bytes)\n }\n}\n\n//MARK: bulk-update functions\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan {\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(repeating repeatedValue: consuming Element) {\n unsafe _start().withMemoryRebound(to: Element.self, capacity: count) {\n unsafe $0.update(repeating: repeatedValue, count: count)\n }\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update<S: Sequence>(\n from source: S\n ) -> (unwritten: S.Iterator, index: Index) where S.Element == Element {\n var iterator = source.makeIterator()\n let index = update(from: &iterator)\n return (iterator, index)\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(\n from elements: inout some IteratorProtocol<Element>\n ) -> Index {\n var index = 0\n while index < _count {\n guard let element = elements.next() else { break }\n unsafe self[unchecked: index] = element\n index &+= 1\n }\n return index\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(\n fromContentsOf source: some Collection<Element>\n ) -> Index {\n let updated = source.withContiguousStorageIfAvailable {\n self.update(fromContentsOf: unsafe Span(_unsafeElements: $0))\n }\n if let updated {\n return updated\n }\n\n //TODO: use _copyContents here\n\n var iterator = source.makeIterator()\n let index = update(from: &iterator)\n _precondition(\n iterator.next() == nil,\n "destination buffer view cannot contain every element from source."\n )\n return index\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(fromContentsOf source: Span<Element>) -> Index {\n guard !source.isEmpty else { return 0 }\n _precondition(\n source.count <= self.count,\n "destination span cannot contain every element from source."\n )\n unsafe _start().withMemoryRebound(\n to: Element.self, capacity: source.count\n ) { dest in\n unsafe source.withUnsafeBufferPointer {\n unsafe dest.update(from: $0.baseAddress!, count: $0.count)\n }\n }\n return source.count\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(\n fromContentsOf source: borrowing MutableSpan<Element>\n ) -> Index {\n update(fromContentsOf: source.span)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: ~Copyable {\n\n// @_alwaysEmitIntoClient\n// public mutating func moveUpdate(\n// fromContentsOf source: consuming OutputSpan<Element>\n// ) -> Index {\n// guard !source.isEmpty else { return 0 }\n// _precondition(\n// source.count <= self.count,\n// "destination span cannot contain every element from source."\n// )\n// let buffer = unsafe source.relinquishBorrowedMemory()\n// // we must now deinitialize the returned UMBP\n// unsafe _start().moveInitializeMemory(\n// as: Element.self, from: buffer.baseAddress!, count: buffer.count\n// )\n// return buffer.count\n// }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func moveUpdate(\n fromContentsOf source: UnsafeMutableBufferPointer<Element>\n ) -> Index {\n// let source = OutputSpan(_initializing: source, initialized: source.count)\n// return self.moveUpdate(fromContentsOf: source)\n unsafe withUnsafeMutableBufferPointer {\n unsafe $0.moveUpdate(fromContentsOf: source)\n }\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan {\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func moveUpdate(\n fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>\n ) -> Index {\n unsafe moveUpdate(fromContentsOf: .init(rebasing: source))\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: BitwiseCopyable {\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(\n repeating repeatedValue: Element\n ) where Element: BitwiseCopyable {\n guard count > 0 else { return }\n // rebind _start manually in order to avoid assumptions about alignment.\n let rp = unsafe _start()._rawValue\n let binding = Builtin.bindMemory(rp, count._builtinWordValue, Element.self)\n let rebound = unsafe UnsafeMutablePointer<Element>(rp)\n unsafe rebound.update(repeating: repeatedValue, count: count)\n Builtin.rebindMemory(rp, binding)\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update<S: Sequence>(\n from source: S\n ) -> (unwritten: S.Iterator, index: Index)\n where S.Element == Element, Element: BitwiseCopyable {\n var iterator = source.makeIterator()\n let index = update(from: &iterator)\n return (iterator, index)\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(\n from elements: inout some IteratorProtocol<Element>\n ) -> Index {\n var index = 0\n while index < _count {\n guard let element = elements.next() else { break }\n unsafe self[unchecked: index] = element\n index &+= 1\n }\n return index\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(\n fromContentsOf source: some Collection<Element>\n ) -> Index where Element: BitwiseCopyable {\n let updated = source.withContiguousStorageIfAvailable {\n self.update(fromContentsOf: unsafe Span(_unsafeElements: $0))\n }\n if let updated {\n return updated\n }\n\n //TODO: use _copyContents here\n\n var iterator = source.makeIterator()\n let index = update(from: &iterator)\n _precondition(\n iterator.next() == nil,\n "destination buffer view cannot contain every element from source."\n )\n return index\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(\n fromContentsOf source: Span<Element>\n ) -> Index where Element: BitwiseCopyable {\n guard !source.isEmpty else { return 0 }\n _precondition(\n source.count <= self.count,\n "destination span cannot contain every element from source."\n )\n unsafe source.withUnsafeBufferPointer {\n unsafe _start().copyMemory(\n from: $0.baseAddress!,\n byteCount: $0.count &* MemoryLayout<Element>.stride\n )\n }\n return source.count\n }\n\n @_alwaysEmitIntoClient\n @lifetime(self: copy self)\n public mutating func update(\n fromContentsOf source: borrowing MutableSpan<Element>\n ) -> Index where Element: BitwiseCopyable {\n update(fromContentsOf: source.span)\n }\n}\n\n// MARK: sub-spans\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: ~Copyable {\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `MutableSpan`.\n ///\n /// - Returns: A `MutableSpan` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(_ bounds: Range<Index>) -> Self {\n _precondition(\n UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&\n UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),\n "Index range out of bounds"\n )\n return unsafe extracting(unchecked: bounds)\n }\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// This function does not validate `bounds`; this is an unsafe operation.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `MutableSpan`.\n ///\n /// - Returns: A `MutableSpan` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(unchecked bounds: Range<Index>) -> Self {\n let delta = bounds.lowerBound &* MemoryLayout<Element>.stride\n let newStart = unsafe _pointer?.advanced(by: delta)\n let newSpan = unsafe Self(_unchecked: newStart, count: bounds.count)\n return unsafe _overrideLifetime(newSpan, mutating: &self)\n }\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `MutableSpan`.\n ///\n /// - Returns: A `MutableSpan` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(\n _ bounds: some RangeExpression<Index>\n ) -> Self {\n extracting(bounds.relative(to: indices))\n }\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// This function does not validate `bounds`; this is an unsafe operation.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `MutableSpan`.\n ///\n /// - Returns: A `MutableSpan` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(\n unchecked bounds: ClosedRange<Index>\n ) -> Self {\n let range = unsafe Range(\n _uncheckedBounds: (bounds.lowerBound, bounds.upperBound&+1)\n )\n return unsafe extracting(unchecked: range)\n }\n\n /// Constructs a new span over all the items of this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Returns: A `MutableSpan` over all the items of this span.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(_: UnboundedRange) -> Self {\n let newSpan = unsafe Self(_unchecked: _start(), count: _count)\n return unsafe _overrideLifetime(newSpan, mutating: &self)\n }\n}\n\n// MARK: prefixes and suffixes\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension MutableSpan where Element: ~Copyable {\n\n /// Returns a span containing the initial elements of this span,\n /// up to the specified maximum length.\n ///\n /// If the maximum length exceeds the length of this span,\n /// the result contains all the elements.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter maxLength: The maximum number of elements to return.\n /// `maxLength` must be greater than or equal to zero.\n /// - Returns: A span with at most `maxLength` elements.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(first maxLength: Int) -> Self {\n _precondition(maxLength >= 0, "Can't have a prefix of negative length")\n let newCount = min(maxLength, count)\n let newSpan = unsafe Self(_unchecked: _pointer, count: newCount)\n return unsafe _overrideLifetime(newSpan, mutating: &self)\n }\n\n /// Returns a span over all but the given number of trailing elements.\n ///\n /// If the number of elements to drop exceeds the number of elements in\n /// the span, the result is an empty span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter k: The number of elements to drop off the end of\n /// the span. `k` must be greater than or equal to zero.\n /// - Returns: A span leaving off the specified number of elements at the end.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(droppingLast k: Int) -> Self {\n _precondition(k >= 0, "Can't drop a negative number of elements")\n let droppedCount = min(k, count)\n let newCount = count &- droppedCount\n let newSpan = unsafe Self(_unchecked: _pointer, count: newCount)\n return unsafe _overrideLifetime(newSpan, mutating: &self)\n }\n\n /// Returns a span containing the final elements of the span,\n /// up to the given maximum length.\n ///\n /// If the maximum length exceeds the length of this span,\n /// the result contains all the elements.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter maxLength: The maximum number of elements to return.\n /// `maxLength` must be greater than or equal to zero.\n /// - Returns: A span with at most `maxLength` elements.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(last maxLength: Int) -> Self {\n _precondition(maxLength >= 0, "Can't have a suffix of negative length")\n let newCount = min(maxLength, count)\n let offset = (count &- newCount) * MemoryLayout<Element>.stride\n let newStart = unsafe _pointer?.advanced(by: offset)\n let newSpan = unsafe Self(_unchecked: newStart, count: newCount)\n return unsafe _overrideLifetime(newSpan, mutating: &self)\n }\n\n /// Returns a span over all but the given number of initial elements.\n ///\n /// If the number of elements to drop exceeds the number of elements in\n /// the span, the result is an empty span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter k: The number of elements to drop from the beginning of\n /// the span. `k` must be greater than or equal to zero.\n /// - Returns: A span starting after the specified number of elements.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(&self)\n mutating public func extracting(droppingFirst k: Int) -> Self {\n _precondition(k >= 0, "Can't drop a negative number of elements")\n let droppedCount = min(k, count)\n let offset = droppedCount * MemoryLayout<Element>.stride\n let newStart = unsafe _pointer?.advanced(by: offset)\n let newCount = count &- droppedCount\n let newSpan = unsafe Self(_unchecked: newStart, count: newCount)\n return unsafe _overrideLifetime(newSpan, mutating: &self)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Span_MutableSpan.swift
cpp_apple_swift_stdlib_public_core_Span_MutableSpan.swift
Swift
30,714
0.95
0.015402
0.244256
awesome-app
721
2024-12-04T11:00:01.661631
BSD-3-Clause
false
ec294f9febd50288f98011326d829966
//===--- RawSpan.swift ----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 - 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 SPAN_COMPATIBILITY_STUB\nimport Swift\n#endif\n\n/// `RawSpan` represents a contiguous region of memory\n/// which contains initialized bytes.\n///\n/// A `RawSpan` instance is a non-owning, non-escaping view into memory.\n/// When a `RawSpan` is created, it inherits the lifetime of the container\n/// owning the contiguous memory, ensuring temporal safety and avoiding\n/// use-after-free errors. Operations on `RawSpan` are bounds-checked,\n/// ensuring spcial safety and avoiding buffer overflow errors.\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\n@frozen\n@safe\npublic struct RawSpan: ~Escapable, Copyable, BitwiseCopyable {\n\n /// The starting address of this `RawSpan`.\n ///\n /// `_pointer` can be `nil` if and only if `_count` equals 0.\n /// Otherwise, `_pointer` must point to memory that will remain\n /// valid and not mutated as long as this `Span` exists.\n /// The memory at `_pointer` must consist of `_count` initialized bytes.\n @usableFromInline\n internal let _pointer: UnsafeRawPointer?\n\n @unsafe\n @_alwaysEmitIntoClient\n internal func _start() -> UnsafeRawPointer {\n unsafe _pointer._unsafelyUnwrappedUnchecked\n }\n\n /// The number of bytes in this `RawSpan`.\n ///\n /// If `_count` equals 0, then `_pointer` may be either `nil` or valid.\n /// Any `_count` greater than 0 indicates a valid non-nil `_pointer`.\n /// Any `_count` less than 0 is invalid and is undefined behaviour.\n @usableFromInline\n internal let _count: Int\n\n @_alwaysEmitIntoClient\n @inline(__always)\n @lifetime(immortal)\n internal init() {\n unsafe _pointer = nil\n _count = 0\n }\n\n /// Unsafely create a `RawSpan` over initialized memory.\n ///\n /// `pointer` must point to a region of `byteCount` initialized bytes,\n /// or may be `nil` if `count` is 0.\n ///\n /// The region of `byteCount` bytes of memory starting at `pointer`\n /// must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - pointer: a pointer to the first initialized byte.\n /// - byteCount: the number of initialized bytes in the span.\n @unsafe\n @_alwaysEmitIntoClient\n @inline(__always)\n @lifetime(borrow pointer)\n internal init(\n _unchecked pointer: UnsafeRawPointer?,\n byteCount: Int\n ) {\n unsafe _pointer = pointer\n _count = byteCount\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension RawSpan: @unchecked Sendable {}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension RawSpan {\n\n /// Unsafely create a `RawSpan` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `RawSpan`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeRawBufferPointer` to initialized memory.\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n public init(\n _unsafeBytes buffer: UnsafeRawBufferPointer\n ) {\n let baseAddress = buffer.baseAddress\n let span = unsafe RawSpan(_unchecked: baseAddress, byteCount: buffer.count)\n // As a trivial value, 'baseAddress' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `RawSpan` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `RawSpan`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeRawBufferPointer` to initialized memory.\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n public init(\n _unsafeBytes buffer: borrowing Slice<UnsafeRawBufferPointer>\n ) {\n let rawBuffer = unsafe UnsafeRawBufferPointer(rebasing: buffer)\n let span = unsafe RawSpan(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `RawSpan` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `RawSpan`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeRawBufferPointer` to initialized memory.\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n public init(\n _unsafeBytes buffer: UnsafeMutableRawBufferPointer\n ) {\n let rawBuffer = UnsafeRawBufferPointer(buffer)\n let span = unsafe RawSpan(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `RawSpan` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `RawSpan`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeRawBufferPointer` to initialized memory.\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n public init(\n _unsafeBytes buffer: borrowing Slice<UnsafeMutableRawBufferPointer>\n ) {\n let rawBuffer = UnsafeRawBufferPointer(\n unsafe UnsafeMutableRawBufferPointer(rebasing: buffer)\n )\n let span = unsafe RawSpan(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `RawSpan` over initialized memory.\n ///\n /// The region of memory representing `byteCount` bytes starting at `pointer`\n /// must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `RawSpan`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - pointer: a pointer to the first initialized byte.\n /// - byteCount: the number of initialized bytes in the span.\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow pointer)\n public init(\n _unsafeStart pointer: UnsafeRawPointer,\n byteCount: Int\n ) {\n _precondition(byteCount >= 0, "Count must not be negative")\n unsafe self.init(_unchecked: pointer, byteCount: byteCount)\n }\n\n /// Unsafely create a `RawSpan` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `RawSpan`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeRawBufferPointer` to initialized memory.\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n public init<T: BitwiseCopyable>(\n _unsafeElements buffer: UnsafeBufferPointer<T>\n ) {\n let rawBuffer = UnsafeRawBufferPointer(buffer)\n let span = unsafe RawSpan(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `RawSpan` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `RawSpan`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeRawBufferPointer` to initialized memory.\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n public init<T: BitwiseCopyable>(\n _unsafeElements buffer: borrowing Slice<UnsafeBufferPointer<T>>\n ) {\n let rawBuffer = UnsafeRawBufferPointer(unsafe .init(rebasing: buffer))\n let span = unsafe RawSpan(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `RawSpan` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `RawSpan`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeRawBufferPointer` to initialized memory.\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n public init<T: BitwiseCopyable>(\n _unsafeElements buffer: UnsafeMutableBufferPointer<T>\n ) {\n let rawBuffer = UnsafeRawBufferPointer(buffer)\n let span = unsafe RawSpan(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `RawSpan` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `RawSpan`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeRawBufferPointer` to initialized memory.\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n public init<T: BitwiseCopyable>(\n _unsafeElements buffer: borrowing Slice<UnsafeMutableBufferPointer<T>>\n ) {\n let rawBuffer = UnsafeRawBufferPointer(\n unsafe UnsafeMutableBufferPointer(rebasing: buffer)\n )\n let span = unsafe RawSpan(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `RawSpan` over initialized memory.\n ///\n /// The region of memory representing `byteCount` bytes starting at `pointer`\n /// must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `RawSpan`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - pointer: a pointer to the first initialized byte.\n /// - byteCount: the number of initialized bytes in the span.\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(borrow pointer)\n public init<T: BitwiseCopyable>(\n _unsafeStart pointer: UnsafePointer<T>,\n count: Int\n ) {\n _precondition(count >= 0, "Count must not be negative")\n unsafe self.init(\n _unchecked: pointer, byteCount: count * MemoryLayout<T>.stride\n )\n }\n\n /// Create a `RawSpan` over the memory represented by a `Span<T>`\n ///\n /// - Parameters:\n /// - span: An existing `Span<T>`, which will define both this\n /// `RawSpan`'s lifetime and the memory it represents.\n @_alwaysEmitIntoClient\n @lifetime(copy span)\n public init<Element: BitwiseCopyable>(\n _elements span: Span<Element>\n ) {\n let pointer = unsafe span._pointer\n let rawSpan = unsafe RawSpan(\n _unchecked: pointer,\n byteCount: span.count == 1 ? MemoryLayout<Element>.size\n : span.count &* MemoryLayout<Element>.stride\n )\n self = unsafe _overrideLifetime(rawSpan, copying: span)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension RawSpan {\n\n /// The number of bytes in the span.\n ///\n /// To check whether the span is empty, use its `isEmpty` property\n /// instead of comparing `count` to zero.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public var byteCount: Int { _count }\n\n /// A Boolean value indicating whether the span is empty.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public var isEmpty: Bool { byteCount == 0 }\n\n /// The indices that are valid for subscripting the span, in ascending\n /// order.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public var byteOffsets: Range<Int> {\n unsafe Range(_uncheckedBounds: (0, byteCount))\n }\n}\n\n// MARK: extracting sub-spans\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension RawSpan {\n\n /// Constructs a new span over the bytes within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first byte is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `RawSpan`.\n ///\n /// - Returns: A span over the bytes within `bounds`\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(_ bounds: Range<Int>) -> Self {\n _precondition(\n UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&\n UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),\n "Byte offset range out of bounds"\n )\n return unsafe _extracting(unchecked: bounds)\n }\n\n /// Constructs a new span over the bytes within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first byte is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// This function does not validate `bounds`; this is an unsafe operation.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `RawSpan`.\n ///\n /// - Returns: A span over the bytes within `bounds`\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(unchecked bounds: Range<Int>) -> Self {\n let newStart = unsafe _pointer?.advanced(by: bounds.lowerBound)\n let newSpan = unsafe RawSpan(_unchecked: newStart, byteCount: bounds.count)\n return unsafe _overrideLifetime(newSpan, copying: self)\n }\n\n /// Constructs a new span over the bytes within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first byte is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `RawSpan`.\n ///\n /// - Returns: A span over the bytes within `bounds`\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(_ bounds: some RangeExpression<Int>) -> Self {\n _extracting(bounds.relative(to: byteOffsets))\n }\n\n /// Constructs a new span over the bytes within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first byte is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// This function does not validate `bounds`; this is an unsafe operation.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `RawSpan`.\n ///\n /// - Returns: A span over the bytes within `bounds`\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(\n unchecked bounds: ClosedRange<Int>\n ) -> Self {\n let range = unsafe Range(\n _uncheckedBounds: (bounds.lowerBound, bounds.upperBound + 1)\n )\n return unsafe _extracting(unchecked: range)\n }\n\n /// Constructs a new span over all the bytes of this span.\n ///\n /// The returned span's first byte is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Returns: A span over all the bytes of this span.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(_: UnboundedRange) -> Self {\n self\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension RawSpan {\n\n /// Calls the given closure with a pointer to the underlying bytes of\n /// the viewed contiguous storage.\n ///\n /// The buffer pointer passed as an argument to `body` is valid only\n /// during the execution of `withUnsafeBytes(_:)`.\n /// Do not store or return the pointer for later use.\n ///\n /// Note: For an empty `RawSpan`, the closure always receives a `nil` pointer.\n ///\n /// - Parameter body: A closure with an `UnsafeRawBufferPointer`\n /// parameter that points to the viewed contiguous storage.\n /// If `body` has a return value, that value is also\n /// used as the return value for the `withUnsafeBytes(_:)` method.\n /// The closure's parameter is valid only for the duration of\n /// its execution.\n /// - Returns: The return value of the `body` closure parameter.\n @_alwaysEmitIntoClient\n public func withUnsafeBytes<E: Error, Result: ~Copyable>(\n _ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result\n ) throws(E) -> Result {\n guard let _pointer = unsafe _pointer, byteCount > 0 else {\n return try unsafe body(.init(start: nil, count: 0))\n }\n return try unsafe body(.init(start: _pointer, count: byteCount))\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension RawSpan {\n\n /// View the bytes of this span as type `T`\n ///\n /// This is the equivalent of `unsafeBitCast(_:to:)`. The\n /// underlying bytes must be initialized as type `T`, be\n /// initialized to a type that is layout-compatible with `T`,\n /// or the function mapping bit patterns of length `8*MemoryLayout<T>.size`\n /// to instances of `T` must be surjective.\n ///\n /// This is an unsafe operation. Failure to meet the preconditions\n /// above may produce invalid values of `T`.\n ///\n /// - Parameters:\n /// - type: The type as which to view the bytes of this span.\n /// - Returns: A typed span viewing these bytes as instances of `T`.\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n consuming public func _unsafeView<T: BitwiseCopyable>(\n as type: T.Type\n ) -> Span<T> {\n let rawBuffer = unsafe UnsafeRawBufferPointer(start: _pointer, count: _count)\n let newSpan = unsafe Span<T>(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'self'. Make the dependence explicit.\n return unsafe _overrideLifetime(newSpan, copying: self)\n }\n}\n\n// MARK: load\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension RawSpan {\n\n /// Returns a new instance of the given type, constructed from the raw memory\n /// at the specified offset.\n ///\n /// The memory at this pointer plus `offset` must be properly aligned for\n /// accessing `T` and initialized to `T` or another type that is layout\n /// compatible with `T`.\n ///\n /// This is an unsafe operation. Failure to meet the preconditions\n /// above may produce an invalid value of `T`.\n ///\n /// - Parameters:\n /// - offset: The offset from this pointer, in bytes. `offset` must be\n /// nonnegative. The default is zero.\n /// - type: The type of the instance to create.\n /// - Returns: A new instance of type `T`, read from the raw bytes at\n /// `offset`. The returned instance is memory-managed and unassociated\n /// with the value in the memory referenced by this pointer.\n @unsafe\n @_alwaysEmitIntoClient\n public func unsafeLoad<T>(\n fromByteOffset offset: Int = 0, as: T.Type\n ) -> T {\n _precondition(\n UInt(bitPattern: offset) <= UInt(bitPattern: _count) &&\n MemoryLayout<T>.size <= (_count &- offset),\n "Byte offset range out of bounds"\n )\n return unsafe unsafeLoad(fromUncheckedByteOffset: offset, as: T.self)\n }\n\n /// Returns a new instance of the given type, constructed from the raw memory\n /// at the specified offset.\n ///\n /// The memory at this pointer plus `offset` must be properly aligned for\n /// accessing `T` and initialized to `T` or another type that is layout\n /// compatible with `T`.\n ///\n /// This is an unsafe operation. This function does not validate the bounds\n /// of the memory access, and failure to meet the preconditions\n /// above may produce an invalid value of `T`.\n ///\n /// - Parameters:\n /// - offset: The offset from this pointer, in bytes. `offset` must be\n /// nonnegative. The default is zero.\n /// - type: The type of the instance to create.\n /// - Returns: A new instance of type `T`, read from the raw bytes at\n /// `offset`. The returned instance is memory-managed and unassociated\n /// with the value in the memory referenced by this pointer.\n @unsafe\n @_alwaysEmitIntoClient\n public func unsafeLoad<T>(\n fromUncheckedByteOffset offset: Int, as: T.Type\n ) -> T {\n unsafe _start().load(fromByteOffset: offset, as: T.self)\n }\n\n /// Returns a new instance of the given type, constructed from the raw memory\n /// at the specified offset.\n ///\n /// The memory at this pointer plus `offset` must be initialized to `T`\n /// or another type that is layout compatible with `T`.\n ///\n /// This is an unsafe operation. Failure to meet the preconditions\n /// above may produce an invalid value of `T`.\n ///\n /// - Parameters:\n /// - offset: The offset from this pointer, in bytes. `offset` must be\n /// nonnegative. The default is zero.\n /// - type: The type of the instance to create.\n /// - Returns: A new instance of type `T`, read from the raw bytes at\n /// `offset`. The returned instance isn't associated\n /// with the value in the range of memory referenced by this pointer.\n @unsafe\n @_alwaysEmitIntoClient\n public func unsafeLoadUnaligned<T: BitwiseCopyable>(\n fromByteOffset offset: Int = 0, as: T.Type\n ) -> T {\n _precondition(\n UInt(bitPattern: offset) <= UInt(bitPattern: _count) &&\n MemoryLayout<T>.size <= (_count &- offset),\n "Byte offset range out of bounds"\n )\n return unsafe unsafeLoadUnaligned(\n fromUncheckedByteOffset: offset, as: T.self\n )\n }\n\n /// Returns a new instance of the given type, constructed from the raw memory\n /// at the specified offset.\n ///\n /// The memory at this pointer plus `offset` must be initialized to `T`\n /// or another type that is layout compatible with `T`.\n ///\n /// This is an unsafe operation. This function does not validate the bounds\n /// of the memory access, and failure to meet the preconditions\n /// above may produce an invalid value of `T`.\n ///\n /// - Parameters:\n /// - offset: The offset from this pointer, in bytes. `offset` must be\n /// nonnegative. The default is zero.\n /// - type: The type of the instance to create.\n /// - Returns: A new instance of type `T`, read from the raw bytes at\n /// `offset`. The returned instance isn't associated\n /// with the value in the range of memory referenced by this pointer.\n @unsafe\n @_alwaysEmitIntoClient\n public func unsafeLoadUnaligned<T: BitwiseCopyable>(\n fromUncheckedByteOffset offset: Int, as: T.Type\n ) -> T {\n unsafe _start().loadUnaligned(fromByteOffset: offset, as: T.self)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension RawSpan {\n /// Returns a Boolean value indicating whether two `RawSpan` instances\n /// refer to the same region in memory.\n @_alwaysEmitIntoClient\n public func isIdentical(to other: Self) -> Bool {\n unsafe (self._pointer == other._pointer) && (self._count == other._count)\n }\n\n /// Returns the offsets where the memory of `span` is located within\n /// the memory represented by `self`\n ///\n /// Note: `span` must be a subrange of `self`\n ///\n /// Parameters:\n /// - span: a subrange of `self`\n /// Returns: A range of offsets within `self`\n @_alwaysEmitIntoClient\n public func byteOffsets(of other: borrowing Self) -> Range<Int>? {\n if other._count > _count { return nil }\n guard let spanStart = unsafe other._pointer, _count > 0 else {\n return unsafe _pointer == other._pointer ? 0..<0 : nil\n }\n let start = unsafe _start()\n let spanEnd = unsafe spanStart + other._count\n if unsafe spanStart < start || (start + _count) < spanEnd { return nil }\n let lower = unsafe start.distance(to: spanStart)\n return unsafe Range(_uncheckedBounds: (lower, lower &+ other._count))\n }\n}\n\n// MARK: prefixes and suffixes\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension RawSpan {\n\n /// Returns a span containing the initial bytes of this span,\n /// up to the specified maximum byte count.\n ///\n /// If the maximum length exceeds the length of this span,\n /// the result contains all the bytes.\n ///\n /// The returned span's first byte is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter maxLength: The maximum number of bytes to return.\n /// `maxLength` must be greater than or equal to zero.\n /// - Returns: A span with at most `maxLength` bytes.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(first maxLength: Int) -> Self {\n _precondition(maxLength >= 0, "Can't have a prefix of negative length")\n let newCount = min(maxLength, byteCount)\n return unsafe Self(_unchecked: _pointer, byteCount: newCount)\n }\n\n /// Returns a span over all but the given number of trailing bytes.\n ///\n /// If the number of elements to drop exceeds the number of elements in\n /// the span, the result is an empty span.\n ///\n /// The returned span's first byte is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter k: The number of bytes to drop off the end of\n /// the span. `k` must be greater than or equal to zero.\n /// - Returns: A span leaving off the specified number of bytes at the end.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(droppingLast k: Int) -> Self {\n _precondition(k >= 0, "Can't drop a negative number of bytes")\n let droppedCount = min(k, byteCount)\n let count = byteCount &- droppedCount\n return unsafe Self(_unchecked: _pointer, byteCount: count)\n }\n\n /// Returns a span containing the trailing bytes of the span,\n /// up to the given maximum length.\n ///\n /// If the maximum length exceeds the length of this span,\n /// the result contains all the bytes.\n ///\n /// The returned span's first byte is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter maxLength: The maximum number of bytes to return.\n /// `maxLength` must be greater than or equal to zero.\n /// - Returns: A span with at most `maxLength` bytes.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(last maxLength: Int) -> Self {\n _precondition(maxLength >= 0, "Can't have a suffix of negative length")\n let newCount = min(maxLength, byteCount)\n let newStart = unsafe _pointer?.advanced(by: byteCount &- newCount)\n let newSpan = unsafe Self(_unchecked: newStart, byteCount: newCount)\n // As a trivial value, 'newStart' does not formally depend on the\n // lifetime of 'self'. Make the dependence explicit.\n return unsafe _overrideLifetime(newSpan, copying: self)\n }\n\n /// Returns a span over all but the given number of initial bytes.\n ///\n /// If the number of elements to drop exceeds the number of bytes in\n /// the span, the result is an empty span.\n ///\n /// The returned span's first byte is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter k: The number of bytes to drop from the beginning of\n /// the span. `k` must be greater than or equal to zero.\n /// - Returns: A span starting after the specified number of bytes.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(droppingFirst k: Int) -> Self {\n _precondition(k >= 0, "Can't drop a negative number of bytes")\n let droppedCount = min(k, byteCount)\n let newStart = unsafe _pointer?.advanced(by: droppedCount)\n let newCount = byteCount &- droppedCount\n let newSpan = unsafe Self(_unchecked: newStart, byteCount: newCount)\n // As a trivial value, 'newStart' does not formally depend on the\n // lifetime of 'self'. Make the dependence explicit.\n return unsafe _overrideLifetime(newSpan, copying: self)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Span_RawSpan.swift
cpp_apple_swift_stdlib_public_core_Span_RawSpan.swift
Swift
30,292
0.95
0.026482
0.539491
react-lib
453
2024-10-05T09:19:47.483109
Apache-2.0
false
bfef01b577ddddbab867e59bf935867e
//===--- Span.swift -------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 - 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 SPAN_COMPATIBILITY_STUB\nimport Swift\n#endif\n\n/// `Span<Element>` represents a contiguous region of memory\n/// which contains initialized instances of `Element`.\n///\n/// A `Span` instance is a non-owning, non-escaping view into memory.\n/// When a `Span` is created, it inherits the lifetime of the container\n/// owning the contiguous memory, ensuring temporal safety and avoiding\n/// use-after-free errors. Operations on `Span` are bounds-checked,\n/// ensuring spcial safety and avoiding buffer overflow errors.\n@frozen\n@safe\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\npublic struct Span<Element: ~Copyable>: ~Escapable, Copyable, BitwiseCopyable {\n\n /// The starting address of this `Span`.\n ///\n /// `_pointer` can be `nil` if and only if `_count` equals 0.\n /// Otherwise, `_pointer` must point to memory that will remain\n /// valid and not mutated as long as this `Span` exists.\n /// The memory at `_pointer` must be initialized\n /// as `_count` instances of `Element`.\n @usableFromInline\n internal let _pointer: UnsafeRawPointer?\n\n @unsafe\n @_alwaysEmitIntoClient\n internal func _start() -> UnsafeRawPointer {\n unsafe _pointer._unsafelyUnwrappedUnchecked\n }\n\n /// The number of elements in this `Span`.\n ///\n /// If `_count` equals 0, then `_pointer` may be either `nil` or valid.\n /// Any `_count` greater than 0 indicates a valid non-nil `_pointer`.\n /// Any `_count` less than 0 is invalid and is undefined behaviour.\n @usableFromInline\n internal let _count: Int\n\n @_alwaysEmitIntoClient\n @inline(__always)\n @lifetime(immortal)\n internal init() {\n unsafe _pointer = nil\n _count = 0\n }\n\n /// Unsafely create a `Span` over initialized memory.\n ///\n /// `pointer` must point to a region of `count` initialized instances,\n /// or may be `nil` if `count` is 0.\n ///\n /// The region of memory representing `count` instances starting at `pointer`\n /// must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - pointer: a pointer to the first initialized element.\n /// - count: the number of initialized elements in the span.\n @unsafe\n @_alwaysEmitIntoClient\n @inline(__always)\n @lifetime(borrow pointer)\n internal init(\n _unchecked pointer: UnsafeRawPointer?,\n count: Int\n ) {\n unsafe _pointer = pointer\n _count = count\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span: @unchecked Sendable where Element: Sendable & ~Copyable {}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span where Element: ~Copyable {\n\n /// Unsafely create a `Span` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeBufferPointer` to initialized elements.\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n @unsafe\n public init(\n _unsafeElements buffer: UnsafeBufferPointer<Element>\n ) {\n //FIXME: Workaround for https://github.com/swiftlang/swift/issues/77235\n let baseAddress = unsafe UnsafeRawPointer(buffer.baseAddress)\n _precondition(\n ((Int(bitPattern: baseAddress) &\n (MemoryLayout<Element>.alignment &- 1)) == 0),\n "baseAddress must be properly aligned to access Element"\n )\n let span = unsafe Span(_unchecked: baseAddress, count: buffer.count)\n // As a trivial value, 'baseAddress' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `Span` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeMutableBufferPointer` to initialized elements.\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n @unsafe\n public init(\n _unsafeElements buffer: UnsafeMutableBufferPointer<Element>\n ) {\n let buf = UnsafeBufferPointer(buffer)\n let span = unsafe Span(_unsafeElements: buf)\n // As a trivial value, 'buf' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `Span` over initialized memory.\n ///\n /// The region of memory representing `count` instances starting at `pointer`\n /// must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - pointer: a pointer to the first initialized element.\n /// - count: the number of initialized elements in the span.\n @_alwaysEmitIntoClient\n @lifetime(borrow pointer)\n @unsafe\n public init(\n _unsafeStart pointer: UnsafePointer<Element>,\n count: Int\n ) {\n _precondition(count >= 0, "Count must not be negative")\n let buf = unsafe UnsafeBufferPointer(start: pointer, count: count)\n let span = unsafe Span(_unsafeElements: buf)\n // As a trivial value, 'buf' does not formally depend on the\n // lifetime of 'pointer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: pointer)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span /*where Element: Copyable*/ {\n\n /// Unsafely create a `Span` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeBufferPointer` to initialized elements.\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n @unsafe\n public init(\n _unsafeElements buffer: borrowing Slice<UnsafeBufferPointer<Element>>\n ) {\n let buf = unsafe UnsafeBufferPointer(rebasing: buffer)\n let span = unsafe Span(_unsafeElements: buf)\n // As a trivial value, 'buf' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `Span` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// - Parameters:\n /// - buffer: an `UnsafeMutableBufferPointer` to initialized elements.\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n @unsafe\n public init(\n _unsafeElements buffer: borrowing Slice<UnsafeMutableBufferPointer<Element>>\n ) {\n let buf = unsafe UnsafeBufferPointer(rebasing: buffer)\n let span = unsafe Span(_unsafeElements: buf)\n // As a trivial value, 'buf' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span where Element: BitwiseCopyable {\n\n /// Unsafely create a `Span` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// `buffer` must be correctly aligned for accessing\n /// an element of type `Element`, and must contain a number of bytes\n /// that is an exact multiple of `Element`'s stride.\n ///\n /// - Parameters:\n /// - buffer: a buffer to initialized elements.\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n @unsafe\n public init(\n _unsafeBytes buffer: UnsafeRawBufferPointer\n ) {\n //FIXME: Workaround for https://github.com/swiftlang/swift/issues/77235\n let baseAddress = buffer.baseAddress\n _precondition(\n ((Int(bitPattern: baseAddress) &\n (MemoryLayout<Element>.alignment &- 1)) == 0),\n "baseAddress must be properly aligned to access Element"\n )\n let (byteCount, stride) = (buffer.count, MemoryLayout<Element>.stride)\n let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride)\n _precondition(\n remainder == 0, "Span must contain a whole number of elements"\n )\n let span = unsafe Span(_unchecked: baseAddress, count: count)\n // As a trivial value, 'baseAddress' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `Span` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// `buffer` must be correctly aligned for accessing\n /// an element of type `Element`, and must contain a number of bytes\n /// that is an exact multiple of `Element`'s stride.\n ///\n /// - Parameters:\n /// - buffer: a buffer to initialized elements.\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n @unsafe\n public init(\n _unsafeBytes buffer: UnsafeMutableRawBufferPointer\n ) {\n let rawBuffer = UnsafeRawBufferPointer(buffer)\n let span = unsafe Span(_unsafeBytes: rawBuffer)\n // As a trivial value, 'buf' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `Span` over initialized memory.\n ///\n /// The region of memory representing the instances starting at `pointer`\n /// must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// `pointer` must be correctly aligned for accessing\n /// an element of type `Element`, and `byteCount`\n /// must be an exact multiple of `Element`'s stride.\n ///\n /// - Parameters:\n /// - pointer: a pointer to the first initialized element.\n /// - byteCount: the number of initialized elements in the span.\n @_alwaysEmitIntoClient\n @lifetime(borrow pointer)\n @unsafe\n public init(\n _unsafeStart pointer: UnsafeRawPointer,\n byteCount: Int\n ) {\n _precondition(byteCount >= 0, "Count must not be negative")\n let rawBuffer = unsafe UnsafeRawBufferPointer(\n start: pointer, count: byteCount\n )\n let span = unsafe Span(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'pointer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: pointer)\n }\n\n /// Unsafely create a `Span` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// `buffer` must be correctly aligned for accessing\n /// an element of type `Element`, and must contain a number of bytes\n /// that is an exact multiple of `Element`'s stride.\n ///\n /// - Parameters:\n /// - buffer: a buffer to initialized elements.\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n @unsafe\n public init(\n _unsafeBytes buffer: borrowing Slice<UnsafeRawBufferPointer>\n ) {\n let rawBuffer = unsafe UnsafeRawBufferPointer(rebasing: buffer)\n let span = unsafe Span(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Unsafely create a `Span` over initialized memory.\n ///\n /// The memory in `buffer` must remain valid, initialized and immutable\n /// throughout the lifetime of the newly-created `Span`.\n /// Failure to maintain this invariant results in undefined behaviour.\n ///\n /// `buffer` must be correctly aligned for accessing\n /// an element of type `Element`, and must contain a number of bytes\n /// that is an exact multiple of `Element`'s stride.\n ///\n /// - Parameters:\n /// - buffer: a buffer to initialized elements.\n @_alwaysEmitIntoClient\n @lifetime(borrow buffer)\n @unsafe\n public init(\n _unsafeBytes buffer: borrowing Slice<UnsafeMutableRawBufferPointer>\n ) {\n let rawBuffer = unsafe UnsafeRawBufferPointer(rebasing: buffer)\n let span = unsafe Span(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, borrowing: buffer)\n }\n\n /// Create a `Span` over the bytes represented by a `RawSpan`\n ///\n /// - Parameters:\n /// - bytes: An existing `RawSpan`, which will define both this\n /// `Span`'s lifetime and the memory it represents.\n @_alwaysEmitIntoClient\n @lifetime(copy bytes)\n public init(_bytes bytes: consuming RawSpan) {\n let rawBuffer = unsafe UnsafeRawBufferPointer(\n start: bytes._pointer, count: bytes.byteCount\n )\n let span = unsafe Span(_unsafeBytes: rawBuffer)\n // As a trivial value, 'rawBuffer' does not formally depend on the\n // lifetime of 'bytes'. Make the dependence explicit.\n self = unsafe _overrideLifetime(span, copying: bytes)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span where Element: ~Copyable {\n\n /// The number of elements in the span.\n ///\n /// To check whether the span is empty, use its `isEmpty` property\n /// instead of comparing `count` to zero.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @_semantics("fixed_storage.get_count")\n public var count: Int { _count }\n\n /// A Boolean value indicating whether the span is empty.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public var isEmpty: Bool { _count == 0 }\n\n /// The representation for a position in `Span`.\n public typealias Index = Int\n\n /// The indices that are valid for subscripting the span, in ascending\n /// order.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public var indices: Range<Index> {\n unsafe Range(_uncheckedBounds: (0, _count))\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span where Element: ~Copyable {\n @_semantics("fixed_storage.check_index")\n @inline(__always)\n @_alwaysEmitIntoClient\n internal func _checkIndex(_ position: Index) {\n _precondition(indices.contains(position), "Index out of bounds")\n }\n\n /// Accesses the element at the specified position in the `Span`.\n ///\n /// - Parameter position: The offset of the element to access. `position`\n /// must be greater or equal to zero, and less than `count`.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public subscript(_ position: Index) -> Element {\n //FIXME: change to unsafeRawAddress when ready\n unsafeAddress {\n _checkIndex(position)\n return unsafe _unsafeAddressOfElement(unchecked: position)\n }\n }\n\n /// Accesses the element at the specified position in the `Span`.\n ///\n /// This subscript does not validate `position`. Using this subscript\n /// with an invalid `position` results in undefined behaviour.\n ///\n /// - Parameter position: The offset of the element to access. `position`\n /// must be greater or equal to zero, and less than `count`.\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n public subscript(unchecked position: Index) -> Element {\n //FIXME: change to unsafeRawAddress when ready\n unsafeAddress {\n unsafe _unsafeAddressOfElement(unchecked: position)\n }\n }\n\n @unsafe\n @_alwaysEmitIntoClient\n internal func _unsafeAddressOfElement(\n unchecked position: Index\n ) -> UnsafePointer<Element> {\n let elementOffset = position &* MemoryLayout<Element>.stride\n let address = unsafe _start().advanced(by: elementOffset)\n return unsafe address.assumingMemoryBound(to: Element.self)\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span where Element: BitwiseCopyable {\n /// Accesses the element at the specified position in the `Span`.\n ///\n /// - Parameter position: The offset of the element to access. `position`\n /// must be greater or equal to zero, and less than `count`.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n public subscript(_ position: Index) -> Element {\n get {\n _checkIndex(position)\n return unsafe self[unchecked: position]\n }\n }\n\n /// Accesses the element at the specified position in the `Span`.\n ///\n /// This subscript does not validate `position`. Using this subscript\n /// with an invalid `position` results in undefined behaviour.\n ///\n /// - Parameter position: The offset of the element to access. `position`\n /// must be greater or equal to zero, and less than `count`.\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n public subscript(unchecked position: Index) -> Element {\n get {\n let elementOffset = position &* MemoryLayout<Element>.stride\n let address = unsafe _start().advanced(by: elementOffset)\n return unsafe address.loadUnaligned(as: Element.self)\n }\n }\n}\n\n@available(SwiftStdlib 6.2, *)\nextension Span where Element: BitwiseCopyable {\n\n public var bytes: RawSpan {\n @lifetime(copy self)\n @_alwaysEmitIntoClient\n get {\n let rawSpan = RawSpan(_elements: self)\n return unsafe _overrideLifetime(rawSpan, copying: self)\n }\n }\n}\n\n// MARK: sub-spans\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span where Element: ~Copyable {\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `Span`.\n ///\n /// - Returns: A `Span` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(_ bounds: Range<Index>) -> Self {\n _precondition(\n UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&\n UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),\n "Index range out of bounds"\n )\n return unsafe _extracting(unchecked: bounds)\n }\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// This function does not validate `bounds`; this is an unsafe operation.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `Span`.\n ///\n /// - Returns: A `Span` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(unchecked bounds: Range<Index>) -> Self {\n let delta = bounds.lowerBound &* MemoryLayout<Element>.stride\n let newStart = unsafe _pointer?.advanced(by: delta)\n let newSpan = unsafe Span(_unchecked: newStart, count: bounds.count)\n // As a trivial value, 'newStart' does not formally depend on the\n // lifetime of 'self'. Make the dependence explicit.\n return unsafe _overrideLifetime(newSpan, copying: self)\n }\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `Span`.\n ///\n /// - Returns: A `Span` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(\n _ bounds: some RangeExpression<Index>\n ) -> Self {\n _extracting(bounds.relative(to: indices))\n }\n\n /// Constructs a new span over the items within the supplied range of\n /// positions within this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// This function does not validate `bounds`; this is an unsafe operation.\n ///\n /// - Parameter bounds: A valid range of positions. Every position in\n /// this range must be within the bounds of this `Span`.\n ///\n /// - Returns: A `Span` over the items within `bounds`\n ///\n /// - Complexity: O(1)\n @unsafe\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(\n unchecked bounds: ClosedRange<Index>\n ) -> Self {\n let range = unsafe Range(\n _uncheckedBounds: (bounds.lowerBound, bounds.upperBound + 1)\n )\n return unsafe _extracting(unchecked: range)\n }\n\n /// Constructs a new span over all the items of this span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Returns: A `Span` over all the items of this span.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(_: UnboundedRange) -> Self {\n self\n }\n}\n\n// MARK: UnsafeBufferPointer access hatch\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span where Element: ~Copyable {\n\n /// Calls a closure with a pointer to the viewed contiguous storage.\n ///\n /// The buffer pointer passed as an argument to `body` is valid only\n /// during the execution of `withUnsafeBufferPointer(_:)`.\n /// Do not store or return the pointer for later use.\n ///\n /// Note: For an empty `Span`, the closure always receives a `nil` pointer.\n ///\n /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter\n /// that points to the viewed contiguous storage. If `body` has\n /// a return value, that value is also used as the return value\n /// for the `withUnsafeBufferPointer(_:)` method. The closure's\n /// parameter is valid only for the duration of its execution.\n /// - Returns: The return value of the `body` closure parameter.\n @_alwaysEmitIntoClient\n public func withUnsafeBufferPointer<E: Error, Result: ~Copyable>(\n _ body: (_ buffer: UnsafeBufferPointer<Element>) throws(E) -> Result\n ) throws(E) -> Result {\n guard let pointer = unsafe _pointer, _count > 0 else {\n return try unsafe body(.init(start: nil, count: 0))\n }\n // manual memory rebinding to avoid recalculating the alignment checks\n let binding = Builtin.bindMemory(\n pointer._rawValue, count._builtinWordValue, Element.self\n )\n defer { Builtin.rebindMemory(pointer._rawValue, binding) }\n return try unsafe body(.init(start: .init(pointer._rawValue), count: count))\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span where Element: BitwiseCopyable {\n\n /// Calls the given closure with a pointer to the underlying bytes of\n /// the viewed contiguous storage.\n ///\n /// The buffer pointer passed as an argument to `body` is valid only\n /// during the execution of `withUnsafeBytes(_:)`.\n /// Do not store or return the pointer for later use.\n ///\n /// Note: For an empty `Span`, the closure always receives a `nil` pointer.\n ///\n /// - Parameter body: A closure with an `UnsafeRawBufferPointer`\n /// parameter that points to the viewed contiguous storage.\n /// If `body` has a return value, that value is also\n /// used as the return value for the `withUnsafeBytes(_:)` method.\n /// The closure's parameter is valid only for the duration of\n /// its execution.\n /// - Returns: The return value of the `body` closure parameter.\n @_alwaysEmitIntoClient\n public func withUnsafeBytes<E: Error, Result: ~Copyable>(\n _ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result\n ) throws(E) -> Result {\n guard let _pointer = unsafe _pointer, _count > 0 else {\n return try unsafe body(.init(start: nil, count: 0))\n }\n return try unsafe body(\n .init(start: _pointer, count: _count &* MemoryLayout<Element>.stride)\n )\n }\n}\n\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span where Element: ~Copyable {\n /// Returns a Boolean value indicating whether two `Span` instances\n /// refer to the same region in memory.\n @_alwaysEmitIntoClient\n public func isIdentical(to other: Self) -> Bool {\n unsafe (self._pointer == other._pointer) && (self._count == other._count)\n }\n\n /// Returns the indices within `self` where the memory represented by `span`\n /// is located, or `nil` if `span` is not located within `self`.\n ///\n /// Parameters:\n /// - span: a span that may be a subrange of `self`\n /// Returns: A range of indices within `self`, or `nil`\n @_alwaysEmitIntoClient\n public func indices(of other: borrowing Self) -> Range<Index>? {\n if other._count > _count { return nil }\n guard let spanStart = unsafe other._pointer, _count > 0 else {\n return unsafe _pointer == other._pointer ? 0..<0 : nil\n }\n let start = unsafe _start()\n let stride = MemoryLayout<Element>.stride\n let spanEnd = unsafe spanStart + stride &* other._count\n if unsafe spanStart < start || spanEnd > (start + stride &* _count) {\n return nil\n }\n let byteOffset = unsafe start.distance(to: spanStart)\n let (lower, r) = byteOffset.quotientAndRemainder(dividingBy: stride)\n guard r == 0 else { return nil }\n return unsafe Range(_uncheckedBounds: (lower, lower &+ other._count))\n }\n}\n\n// MARK: prefixes and suffixes\n@available(SwiftCompatibilitySpan 5.0, *)\n@_originallyDefinedIn(module: "Swift;CompatibilitySpan", SwiftCompatibilitySpan 6.2)\nextension Span where Element: ~Copyable {\n\n /// Returns a span containing the initial elements of this span,\n /// up to the specified maximum length.\n ///\n /// If the maximum length exceeds the length of this span,\n /// the result contains all the elements.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter maxLength: The maximum number of elements to return.\n /// `maxLength` must be greater than or equal to zero.\n /// - Returns: A span with at most `maxLength` elements.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(first maxLength: Int) -> Self {\n _precondition(maxLength >= 0, "Can't have a prefix of negative length")\n let newCount = min(maxLength, count)\n return unsafe Self(_unchecked: _pointer, count: newCount)\n }\n\n /// Returns a span over all but the given number of trailing elements.\n ///\n /// If the number of elements to drop exceeds the number of elements in\n /// the span, the result is an empty span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter k: The number of elements to drop off the end of\n /// the span. `k` must be greater than or equal to zero.\n /// - Returns: A span leaving off the specified number of elements at the end.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(droppingLast k: Int) -> Self {\n _precondition(k >= 0, "Can't drop a negative number of elements")\n let droppedCount = min(k, count)\n return unsafe Self(_unchecked: _pointer, count: count &- droppedCount)\n }\n\n /// Returns a span containing the final elements of the span,\n /// up to the given maximum length.\n ///\n /// If the maximum length exceeds the length of this span,\n /// the result contains all the elements.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter maxLength: The maximum number of elements to return.\n /// `maxLength` must be greater than or equal to zero.\n /// - Returns: A span with at most `maxLength` elements.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(last maxLength: Int) -> Self {\n _precondition(maxLength >= 0, "Can't have a suffix of negative length")\n let newCount = min(maxLength, count)\n let offset = (count &- newCount) * MemoryLayout<Element>.stride\n let newStart = unsafe _pointer?.advanced(by: offset)\n let newSpan = unsafe Span(_unchecked: newStart, count: newCount)\n // As a trivial value, 'newStart' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n return unsafe _overrideLifetime(newSpan, copying: self)\n }\n\n /// Returns a span over all but the given number of initial elements.\n ///\n /// If the number of elements to drop exceeds the number of elements in\n /// the span, the result is an empty span.\n ///\n /// The returned span's first item is always at offset 0; unlike buffer\n /// slices, extracted spans do not share their indices with the\n /// span from which they are extracted.\n ///\n /// - Parameter k: The number of elements to drop from the beginning of\n /// the span. `k` must be greater than or equal to zero.\n /// - Returns: A span starting after the specified number of elements.\n ///\n /// - Complexity: O(1)\n @_alwaysEmitIntoClient\n @lifetime(copy self)\n public func _extracting(droppingFirst k: Int) -> Self {\n _precondition(k >= 0, "Can't drop a negative number of elements")\n let droppedCount = min(k, count)\n let offset = droppedCount &* MemoryLayout<Element>.stride\n let newStart = unsafe _pointer?.advanced(by: offset)\n let newCount = count &- droppedCount\n let newSpan = unsafe Span(_unchecked: newStart, count: newCount)\n // As a trivial value, 'newStart' does not formally depend on the\n // lifetime of 'buffer'. Make the dependence explicit.\n return unsafe _overrideLifetime(newSpan, copying: self)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Span_Span.swift
cpp_apple_swift_stdlib_public_core_Span_Span.swift
Swift
32,352
0.95
0.035419
0.498113
node-utils
454
2025-03-12T13:37:40.070029
GPL-3.0
false
935b976af709411e44dc58c74a3d117a
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2022 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 immutable arbitrary-precision signed integer.\n///\n/// `StaticBigInt` is primarily intended to be used as the associated type of an\n/// `ExpressibleByIntegerLiteral` conformance.\n///\n/// extension UInt256: ExpressibleByIntegerLiteral {\n/// public init(integerLiteral value: StaticBigInt) {\n/// precondition(\n/// value.signum() >= 0 && value.bitWidth <= 1 + Self.bitWidth,\n/// "integer overflow: '\(value)' as '\(Self.self)'"\n/// )\n/// self.words = Words()\n/// for wordIndex in 0..<Words.count {\n/// self.words[wordIndex] = value[wordIndex]\n/// }\n/// }\n/// }\n@available(SwiftStdlib 5.8, *)\n@frozen\npublic struct StaticBigInt:\n _ExpressibleByBuiltinIntegerLiteral,\n ExpressibleByIntegerLiteral,\n Sendable\n{\n @available(SwiftStdlib 5.8, *)\n @usableFromInline\n internal let _value: Builtin.IntLiteral\n\n @available(SwiftStdlib 5.8, *)\n @inlinable\n public init(_builtinIntegerLiteral value: Builtin.IntLiteral) {\n _value = value\n }\n}\n\n//===----------------------------------------------------------------------===//\n// MARK: - Binary Representation\n//===----------------------------------------------------------------------===//\n\n@available(SwiftStdlib 5.8, *)\nextension StaticBigInt {\n\n /// Indicates the value's sign.\n ///\n /// - Returns: `-1` if the value is less than zero, `0` if it is equal to\n /// zero, or `+1` if it is greater than zero.\n @available(SwiftStdlib 5.8, *)\n @inlinable\n public func signum() -> Int {\n _isNegative ? -1 : (bitWidth == 1) ? 0 : +1\n }\n\n @available(SwiftStdlib 5.8, *)\n @inlinable\n internal var _isNegative: Bool {\n#if compiler(>=5.8) && $BuiltinIntLiteralAccessors\n Bool(Builtin.isNegative_IntLiteral(_value))\n#else\n fatalError("Swift compiler is incompatible with this SDK version")\n#endif\n }\n\n /// Returns the minimal number of bits in this value's binary representation,\n /// including the sign bit, and excluding the sign extension.\n ///\n /// The following examples show the least significant byte of each value's\n /// binary representation, separated (by an underscore) into excluded and\n /// included bits. Negative values are in two's complement.\n ///\n /// * `-4` (`0b11111_100`) is 3 bits.\n /// * `-3` (`0b11111_101`) is 3 bits.\n /// * `-2` (`0b111111_10`) is 2 bits.\n /// * `-1` (`0b1111111_1`) is 1 bit.\n /// * `+0` (`0b0000000_0`) is 1 bit.\n /// * `+1` (`0b000000_01`) is 2 bits.\n /// * `+2` (`0b00000_010`) is 3 bits.\n /// * `+3` (`0b00000_011`) is 3 bits.\n @available(SwiftStdlib 5.8, *)\n @inlinable\n public var bitWidth: Int {\n#if compiler(>=5.8) && $BuiltinIntLiteralAccessors\n Int(Builtin.bitWidth_IntLiteral(_value))\n#else\n fatalError("Swift compiler is incompatible with this SDK version")\n#endif\n }\n\n /// Returns a 32-bit or 64-bit word of this value's binary representation.\n ///\n /// The words are ordered from least significant to most significant, with\n /// an infinite sign extension. Negative values are in two's complement.\n ///\n /// let negative: StaticBigInt = -0x0011223344556677_8899AABBCCDDEEFF\n /// negative.signum() //-> -1\n /// negative.bitWidth //-> 118\n /// negative[0] //-> 0x7766554433221101\n /// negative[1] //-> 0xFFEEDDCCBBAA9988\n /// negative[2] //-> 0xFFFFFFFFFFFFFFFF\n ///\n /// let positive: StaticBigInt = 0x0011223344556677_8899AABBCCDDEEFF\n /// positive.signum() //-> +1\n /// positive.bitWidth //-> 118\n /// positive[0] //-> 0x8899AABBCCDDEEFF\n /// positive[1] //-> 0x0011223344556677\n /// positive[2] //-> 0x0000000000000000\n ///\n /// - Parameter wordIndex: A nonnegative zero-based offset.\n @available(SwiftStdlib 5.8, *)\n @inlinable\n public subscript(_ wordIndex: Int) -> UInt {\n _precondition(wordIndex >= 0, "Negative word index")\n let bitIndex = wordIndex.multipliedReportingOverflow(by: UInt.bitWidth)\n guard !bitIndex.overflow, bitIndex.partialValue < bitWidth else {\n return _isNegative ? ~0 : 0\n }\n#if compiler(>=5.8) && $BuiltinIntLiteralAccessors\n return UInt(\n Builtin.wordAtIndex_IntLiteral(_value, wordIndex._builtinWordValue)\n )\n#else\n fatalError("Swift compiler is incompatible with this SDK version")\n#endif\n }\n}\n\n//===----------------------------------------------------------------------===//\n// MARK: - Textual Representation\n//===----------------------------------------------------------------------===//\n\n@available(SwiftStdlib 5.8, *)\nextension StaticBigInt: CustomDebugStringConvertible {\n\n @available(SwiftStdlib 5.8, *)\n public var debugDescription: String {\n let isNegative = _isNegative\n let indicator = isNegative ? "-0x" : "+0x"\n\n // Equivalent to `ceil(bitWidthExcludingSignBit / fourBitsPerHexDigit)`.\n // Underestimated for `-(16 ** y)` values (e.g. "-0x1", "-0x10", "-0x100").\n let capacity = indicator.utf8.count + (((bitWidth - 1) + 3) / 4)\n var result = unsafe String(unsafeUninitializedCapacity: capacity) { utf8 in\n\n // Pre-initialize with zeros, ignoring extra capacity.\n var utf8 = unsafe utf8.prefix(capacity)\n unsafe utf8.initialize(repeating: UInt8(ascii: "0"))\n\n // Use a 32-bit element type, to generate small hexadecimal strings.\n typealias Element = UInt32\n let hexDigitsPerElement = Element.bitWidth / 4\n _internalInvariant(hexDigitsPerElement <= _SmallString.capacity)\n _internalInvariant(UInt.bitWidth.isMultiple(of: Element.bitWidth))\n\n // Lazily compute the magnitude, starting with the least significant bits.\n var overflow = isNegative\n for bitIndex in stride(from: 0, to: bitWidth, by: Element.bitWidth) {\n let wordIndex = bitIndex >> UInt.bitWidth.trailingZeroBitCount\n var element = Element(_truncatingBits: self[wordIndex] &>> bitIndex)\n if isNegative {\n element = ~element\n if overflow {\n (element, overflow) = element.addingReportingOverflow(1)\n }\n }\n\n // Overwrite trailing zeros with hexadecimal digits.\n let hexDigits = String(element, radix: 16, uppercase: true).utf8\n _ = unsafe utf8.suffix(hexDigits.count).update(fromContentsOf: hexDigits)\n unsafe utf8 = unsafe utf8.dropLast(hexDigitsPerElement)\n }\n return capacity\n }\n\n // Overwrite leading zeros with the "±0x" indicator.\n if let upToIndex = result.firstIndex(where: { $0 != "0" }) {\n result.replaceSubrange(..<upToIndex, with: indicator)\n } else {\n result = "+0x0"\n }\n return result\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\n@available(SwiftStdlib 5.8, *)\nextension StaticBigInt: CustomReflectable {\n\n @available(SwiftStdlib 5.8, *)\n public var customMirror: Mirror {\n Mirror(self, unlabeledChildren: EmptyCollection<Void>())\n }\n}\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StaticBigInt.swift
cpp_apple_swift_stdlib_public_core_StaticBigInt.swift
Swift
7,408
0.8
0.073529
0.491892
react-lib
247
2023-11-01T21:41:49.354531
BSD-3-Clause
false
6a85f1f6cb1bfc0be68300746d9ca792
//===--- StaticPrint.swift ------------------------------------------------===//\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\n#if SWIFT_STDLIB_STATIC_PRINT\n\nimport SwiftShims\n\nextension String {\n /// Replace all percents "%" in the string by "%%" so that the string can be\n /// interpreted as a C format string. This function is constant evaluable\n /// and its semantics is modeled within the evaluator.\n @inlinable\n internal var percentEscapedString: String {\n @_semantics("string.escapePercent.get")\n @_effects(readonly)\n @_optimize(none)\n get {\n return self\n .split(separator: "%", omittingEmptySubsequences: false)\n .joined(separator: "%%")\n }\n }\n}\n\nextension ConstantVPrintFInterpolation {\n\n /// Defines interpolation for UnsafeRawBufferPointer.\n ///\n /// Do not call this function directly.\n ///\n /// - Parameters:\n /// - pointer: The interpolated expression of type `UnsafeRawBufferPointer`,\n /// which is autoclosured.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ pointer: @autoclosure @escaping () -> UnsafeRawBufferPointer\n ) {\n appendInterpolation(pointer().baseAddress!)\n }\n\n /// Defines interpolation for UnsafeRawPointer.\n ///\n /// Do not call this function directly.\n ///\n /// - Parameters:\n /// - pointer: The interpolated expression of type `UnsafeRawPointer`, which is autoclosured.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ pointer: @autoclosure @escaping () -> UnsafeRawPointer\n ) {\n formatString += "%p"\n arguments.append(pointer)\n }\n}\n\n@frozen\npublic struct ConstantVPrintFIntegerFormatting {\n /// The base to use for the string representation. `radix` must be at least 2\n /// and at most 36. The default is 10.\n @usableFromInline\n internal var radix: Int\n\n /// When set, a `+` will be printed for all non-negative integers.\n @usableFromInline\n internal var explicitPositiveSign: Bool\n\n /// When set, a prefix: 0b or 0o or 0x will be added when the radix is 2, 8 or\n /// 16 respectively.\n @usableFromInline\n internal var includePrefix: Bool\n\n /// Whether to use uppercase letters to represent numerals\n /// greater than 9 (default is to use lowercase).\n @usableFromInline\n internal var uppercase: Bool\n\n /// Minimum number of digits to display. Numbers having fewer digits than\n /// minDigits will be displayed with leading zeros.\n @usableFromInline\n internal var minDigits: (() -> Int)?\n\n /// Initializes all stored properties.\n ///\n /// - Parameters:\n /// - radix: The base to use for the string representation. `radix` must be\n /// at least 2 and at most 36. The default is 10.\n /// - explicitPositiveSign: Pass `true` to add a + sign to non-negative\n /// numbers. Default is `false`.\n /// - includePrefix: Pass `true` to add a prefix: 0b, 0o, 0x to corresponding\n /// radices. Default is `false`.\n /// - uppercase: Pass `true` to use uppercase letters to represent numerals\n /// greater than 9, or `false` to use lowercase letters. The default is\n /// `false`.\n /// - minDigits: minimum number of digits to display. Numbers will be\n /// prefixed with zeros if necessary to meet the minimum. The default is 1.\n @_transparent\n @usableFromInline\n internal init(\n radix: Int = 10,\n explicitPositiveSign: Bool = false,\n includePrefix: Bool = false,\n uppercase: Bool = false,\n minDigits: (() -> Int)?\n ) {\n self.radix = radix\n self.explicitPositiveSign = explicitPositiveSign\n self.includePrefix = includePrefix\n self.uppercase = uppercase\n self.minDigits = minDigits\n }\n\n /// Displays an interpolated integer as a decimal number with the specified number\n /// of digits and an optional sign.\n ///\n /// The parameter `explicitPositiveSign` must be a boolean literal. The\n /// parameter `minDigits` can be an arbitrary expression.\n ///\n /// - Parameters:\n /// - explicitPositiveSign: Pass `true` to add a + sign to non-negative\n /// numbers.\n /// - minDigits: minimum number of digits to display. Numbers will be\n /// prefixed with zeros if necessary to meet the minimum.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n public static func decimal(\n explicitPositiveSign: Bool = false,\n minDigits: @escaping @autoclosure () -> Int\n ) -> ConstantVPrintFIntegerFormatting {\n return ConstantVPrintFIntegerFormatting(\n radix: 10,\n explicitPositiveSign: explicitPositiveSign,\n minDigits: minDigits)\n }\n\n /// Displays an interpolated integer as a decimal number with an optional sign.\n ///\n /// The parameter `explicitPositiveSign` must be a boolean literal.\n ///\n /// - Parameters:\n /// - explicitPositiveSign: Pass `true` to add a + sign to non-negative\n /// numbers.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n public static func decimal(\n explicitPositiveSign: Bool = false\n ) -> ConstantVPrintFIntegerFormatting {\n return ConstantVPrintFIntegerFormatting(\n radix: 10,\n explicitPositiveSign: explicitPositiveSign,\n minDigits: nil)\n }\n\n /// Displays an interpolated integer as a decimal number. This is the default format for\n /// integers.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n public static var decimal: ConstantVPrintFIntegerFormatting { .decimal() }\n\n /// Displays an interpolated unsigned integer as a hexadecimal number with the\n /// specified parameters. This formatting option should be used only with unsigned\n /// integers.\n ///\n /// All parameters except `minDigits` should be boolean literals. `minDigits`\n /// can be an arbitrary expression.\n ///\n /// - Parameters:\n /// - explicitPositiveSign: Pass `true` to add a + sign to non-negative\n /// numbers.\n /// - includePrefix: Pass `true` to add a prefix 0x.\n /// - uppercase: Pass `true` to use uppercase letters to represent numerals\n /// greater than 9, or `false` to use lowercase letters. The default is `false`.\n /// - minDigits: minimum number of digits to display. Numbers will be\n /// prefixed with zeros if necessary to meet the minimum.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n public static func hex(\n explicitPositiveSign: Bool = false,\n includePrefix: Bool = false,\n uppercase: Bool = false,\n minDigits: @escaping @autoclosure () -> Int\n ) -> ConstantVPrintFIntegerFormatting {\n return ConstantVPrintFIntegerFormatting(\n radix: 16,\n explicitPositiveSign: explicitPositiveSign,\n includePrefix: includePrefix,\n uppercase: uppercase,\n minDigits: minDigits)\n }\n\n /// Displays an interpolated unsigned integer as a hexadecimal number with the specified\n /// parameters. This formatting option should be used only with unsigned integers.\n ///\n /// All parameters should be boolean literals.\n ///\n /// - Parameters:\n /// - explicitPositiveSign: Pass `true` to add a + sign to non-negative\n /// numbers.\n /// - includePrefix: Pass `true` to add a prefix 0x.\n /// - uppercase: Pass `true` to use uppercase letters to represent numerals\n /// greater than 9, or `false` to use lowercase letters. The default is `false`.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n public static func hex(\n explicitPositiveSign: Bool = false,\n includePrefix: Bool = false,\n uppercase: Bool = false\n ) -> ConstantVPrintFIntegerFormatting {\n return ConstantVPrintFIntegerFormatting(\n radix: 16,\n explicitPositiveSign: explicitPositiveSign,\n includePrefix: includePrefix,\n uppercase: uppercase,\n minDigits: nil)\n }\n\n /// Displays an interpolated unsigned integer as a hexadecimal number.\n /// This formatting option should be used only with unsigned integers.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n public static var hex: ConstantVPrintFIntegerFormatting { .hex() }\n\n /// Displays an interpolated unsigned integer as an octal number with the specified\n /// parameters. This formatting option should be used only with unsigned\n /// integers.\n ///\n /// All parameters except `minDigits` should be boolean literals. `minDigits`\n /// can be an arbitrary expression.\n ///\n /// - Parameters:\n /// - explicitPositiveSign: Pass `true` to add a + sign to non-negative\n /// numbers.\n /// - includePrefix: Pass `true` to add a prefix 0o.\n /// - uppercase: Pass `true` to use uppercase letters to represent numerals\n /// greater than 9, or `false` to use lowercase letters. The default is `false`.\n /// - minDigits: minimum number of digits to display. Numbers will be\n /// prefixed with zeros if necessary to meet the minimum.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n public static func octal(\n explicitPositiveSign: Bool = false,\n includePrefix: Bool = false,\n uppercase: Bool = false,\n minDigits: @autoclosure @escaping () -> Int\n ) -> ConstantVPrintFIntegerFormatting {\n ConstantVPrintFIntegerFormatting(\n radix: 8,\n explicitPositiveSign: explicitPositiveSign,\n includePrefix: includePrefix,\n uppercase: uppercase,\n minDigits: minDigits)\n }\n\n /// Displays an interpolated unsigned integer as an octal number with the specified parameters.\n /// This formatting option should be used only with unsigned integers.\n ///\n /// All parameters must be boolean literals.\n ///\n /// - Parameters:\n /// - explicitPositiveSign: Pass `true` to add a + sign to non-negative\n /// numbers.\n /// - includePrefix: Pass `true` to add a prefix 0o.\n /// - uppercase: Pass `true` to use uppercase letters to represent numerals\n /// greater than 9, or `false` to use lowercase letters.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n public static func octal(\n explicitPositiveSign: Bool = false,\n includePrefix: Bool = false,\n uppercase: Bool = false\n ) -> ConstantVPrintFIntegerFormatting {\n ConstantVPrintFIntegerFormatting(\n radix: 8,\n explicitPositiveSign: explicitPositiveSign,\n includePrefix: includePrefix,\n uppercase: uppercase,\n minDigits: nil)\n }\n\n /// Displays an interpolated unsigned integer as an octal number.\n /// This formatting option should be used only with unsigned integers.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n public static var octal: ConstantVPrintFIntegerFormatting { .octal() }\n}\n\nextension ConstantVPrintFIntegerFormatting {\n /// The prefix for the radix in the Swift literal syntax.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n internal var _prefix: String {\n guard includePrefix else { return "" }\n switch radix {\n case 2: return "0b"\n case 8: return "0o"\n case 16: return "0x"\n default: return ""\n }\n }\n}\n\n\nextension ConstantVPrintFIntegerFormatting {\n\n /// Returns a fprintf-compatible length modifier for a given argument type.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n internal static func formatSpecifierLengthModifier<I: FixedWidthInteger>(\n _ type: I.Type\n ) -> String? {\n // IEEE Std 1003.1-2017, length modifiers:\n switch type {\n // hh - d, i, o, u, x, or X conversion specifier applies to\n // (signed|unsigned) char\n case is CChar.Type: return "hh"\n case is CUnsignedChar.Type: return "hh"\n\n // h - d, i, o, u, x, or X conversion specifier applies to\n // (signed|unsigned) short\n case is CShort.Type: return "h"\n case is CUnsignedShort.Type: return "h"\n\n case is CInt.Type: return ""\n case is CUnsignedInt.Type: return ""\n\n // l - d, i, o, u, x, or X conversion specifier applies to\n // (signed|unsigned) long\n case is CLong.Type: return "l"\n case is CUnsignedLong.Type: return "l"\n\n // ll - d, i, o, u, x, or X conversion specifier applies to\n // (signed|unsigned) long long\n case is CLongLong.Type: return "ll"\n case is CUnsignedLongLong.Type: return "ll"\n\n default: return nil\n }\n }\n\n /// Constructs an os_log format specifier for the given `type`.\n @_semantics("constant_evaluable")\n @_alwaysEmitIntoClient\n @_optimize(none)\n @_effects(readonly)\n internal func formatSpecifier<I: FixedWidthInteger>(\n for type: I.Type,\n attributes: String\n ) -> String {\n // Based on IEEE Std 1003.1-2017\n // `d`/`i` is the only signed integral conversions allowed\n if (type.isSigned && radix != 10) {\n fatalError("Signed integers must be formatted using .decimal")\n }\n\n // IEEE: Each conversion specification is introduced by the '%' character\n // after which the following appear in sequence:\n // 1. Zero or more flags (in any order), which modify the meaning of the\n // conversion specification.\n // 2. An optional minimum field width (for alignment). If the converted\n // value has fewer bytes than the field width, it shall be padded with\n // <space> characters by default on the left; it shall be padded on the\n // right if the left-adjustment flag ( '-' ), is given to the\n // field width.\n // 3. An optional precision that gives the minimum number of digits to\n // display for the d, i, o, u, x, and X conversion specifiers.\n // 4. An optional length modifier that specifies the size of the argument.\n // 5. A conversion specifier character that indicates the type of\n // conversion to be applied.\n\n // Use Swift style prefixes rather than fprintf style prefixes.\n var specification = _prefix\n specification += "%"\n\n //\n // 1. Flags\n //\n // Use `+` flag if signed, otherwise prefix a literal `+` for unsigned.\n if explicitPositiveSign {\n // IEEE: `+` The result of a signed conversion shall always begin with a\n // sign ( '+' or '-' )\n if type.isSigned {\n specification += "+"\n } else {\n var newSpecification = "+"\n newSpecification += specification\n specification = newSpecification\n }\n }\n\n // 3. Precision\n\n // Default precision for integers is 1, otherwise use requested precision.\n // The precision could be a dynamic value.\n // Therefore, use a star here and pass it as an additional argument.\n if let _ = minDigits {\n specification += ".*"\n }\n\n // 4. Length modifier\n guard let lengthModifier =\n ConstantVPrintFIntegerFormatting.formatSpecifierLengthModifier(type) else {\n fatalError("Integer type has unknown byte length")\n }\n specification += lengthModifier\n\n // 5. The conversion specifier\n switch radix {\n case 10:\n specification += type.isSigned ? "d" : "u"\n case 8:\n specification += "o"\n case 16:\n specification += uppercase ? "X" : "x"\n default:\n fatalError("radix must be 10, 8 or 16")\n }\n return specification\n }\n}\n\n@frozen\n@usableFromInline\ninternal struct ConstantVPrintFArguments {\n @usableFromInline\n internal var argumentClosures: [(([Int]) -> ()) -> ()]\n\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n internal init() {\n argumentClosures = []\n }\n\n /// `append` for other types must be implemented by extensions.\n}\n\nextension ConstantVPrintFInterpolation {\n\n /// Defines interpolation for expressions of type Int.\n ///\n /// Do not call this function directly. It will be called automatically when interpolating\n /// a value of type `Int` in the string interpolations passed to the log APIs.\n ///\n /// - Parameters:\n /// - number: The interpolated expression of type Int, which is autoclosured.\n /// - format: A formatting option available for integer types, defined by the\n /// type: `ConstantVPrintFIntegerFormatting`. The default is `.decimal`.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ number: @autoclosure @escaping () -> Int,\n format: ConstantVPrintFIntegerFormatting = .decimal\n ) {\n appendInteger(number, format: format)\n }\n\n // Define appendInterpolation overloads for fixed-size integers.\n\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ number: @autoclosure @escaping () -> Int8,\n format: ConstantVPrintFIntegerFormatting = .decimal\n ) {\n appendInteger(number, format: format)\n }\n\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ number: @autoclosure @escaping () -> Int16,\n format: ConstantVPrintFIntegerFormatting = .decimal\n ) {\n appendInteger(number, format: format)\n }\n\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ number: @autoclosure @escaping () -> Int32,\n format: ConstantVPrintFIntegerFormatting = .decimal\n ) {\n appendInteger(number, format: format)\n }\n\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ number: @autoclosure @escaping () -> Int64,\n format: ConstantVPrintFIntegerFormatting = .decimal\n ) {\n appendInteger(number, format: format)\n }\n\n /// Defines interpolation for expressions of type UInt.\n ///\n /// Do not call this function directly. It will be called automatically when interpolating\n /// a value of type `Int` in the string interpolations passed to the log APIs.\n ///\n /// - Parameters:\n /// - number: The interpolated expression of type UInt, which is autoclosured.\n /// - format: A formatting option available for integer types, defined by the\n /// type `ConstantVPrintFIntegerFormatting`.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ number: @autoclosure @escaping () -> UInt,\n format: ConstantVPrintFIntegerFormatting = .decimal\n ) {\n appendInteger(number, format: format)\n }\n\n // Define appendInterpolation overloads for unsigned integers.\n\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ number: @autoclosure @escaping () -> UInt8,\n format: ConstantVPrintFIntegerFormatting = .decimal\n ) {\n appendInteger(number, format: format)\n }\n\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ number: @autoclosure @escaping () -> UInt16,\n format: ConstantVPrintFIntegerFormatting = .decimal\n ) {\n appendInteger(number, format: format)\n }\n\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ number: @autoclosure @escaping () -> UInt32,\n format: ConstantVPrintFIntegerFormatting = .decimal\n ) {\n appendInteger(number, format: format)\n }\n\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ number: @autoclosure @escaping () -> UInt64,\n format: ConstantVPrintFIntegerFormatting = .decimal\n ) {\n appendInteger(number, format: format)\n }\n\n /// Defines interpolation for expressions of type Int.\n ///\n /// Do not call this function directly. It will be called automatically when interpolating\n /// a value of type `Int` in the string interpolations passed to the log APIs.\n ///\n /// - Parameters:\n /// - number: The interpolated expression of type Int, which is autoclosured.\n /// - format: A formatting option available for integer types, defined by the\n /// type: `ConstantVPrintFIntegerFormatting`. The default is `.decimal`.\n /// - attributes: A string that specifies an attribute for the interpolated value,\n /// which can be used to provide additional information about the interpolated\n /// value to tools such as Xcode that can process and render os_log and os_signpost\n /// messages. An example of an attribute is "xcode:size-in-bytes". If the target tool\n /// that processes these messages doesn't understand the attribute it would be ignored.\n @_semantics("constant_evaluable")\n @_alwaysEmitIntoClient\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation<T: FixedWidthInteger>(\n _ number: @autoclosure @escaping () -> T,\n format: ConstantVPrintFIntegerFormatting = .decimal,\n attributes: String\n ) {\n appendInteger(number, format: format, attributes: attributes)\n }\n\n /// Given an integer, create and append a format specifier for the integer to the\n /// format string property. Also, append the integer along with necessary headers\n /// to the ConstantVPrintFArguments property.\n @_semantics("constant_evaluable")\n @_alwaysEmitIntoClient\n @_optimize(none)\n internal mutating func appendInteger<T>(\n _ number: @escaping () -> T,\n format: ConstantVPrintFIntegerFormatting,\n attributes: String = ""\n ) where T: FixedWidthInteger {\n formatString += format.formatSpecifier(for: T.self, attributes: attributes)\n arguments.append(number)\n }\n}\n\n@frozen\npublic struct ConstantVPrintFInterpolation : StringInterpolationProtocol {\n /// A format string constructed from the given string interpolation to be\n /// passed to vprintf\n @usableFromInline\n internal var formatString: String\n\n @usableFromInline\n internal var arguments: ConstantVPrintFArguments\n\n // Some methods defined below are marked @_optimize(none) to prevent inlining\n // of string internals (such as String._StringGuts) which will interfere with\n // constant evaluation and folding. Note that these methods will be inlined,\n // constant evaluated/folded and optimized in the context of a caller.\n\n @_semantics("oslog.interpolation.init")\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n public init(literalCapacity: Int, interpolationCount: Int) {\n // Since the format string and the arguments array are fully constructed\n // at compile time, the parameters are ignored.\n formatString = ""\n arguments = ConstantVPrintFArguments()\n }\n\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n public mutating func appendLiteral(_ literal: String) {\n formatString += literal.percentEscapedString\n }\n\n /// `appendInterpolation` conformances will be added by extensions to this type.\n}\n\nextension ConstantVPrintFInterpolation {\n /// Defines interpolation for expressions of type String.\n ///\n /// Do not call this function directly. It will be called automatically when interpolating\n /// a value of type `String` in the string interpolations passed to the log APIs.\n ///\n /// - Parameters:\n /// - argumentString: The interpolated expression of type String, which is autoclosured.\n @_semantics("constant_evaluable")\n @_alwaysEmitIntoClient\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ argumentString: @autoclosure @escaping () -> String\n ) {\n formatString += "%s"\n arguments.append(argumentString)\n }\n}\n\nextension ConstantVPrintFInterpolation {\n\n /// Defines interpolation for values conforming to CustomStringConvertible. The values\n /// are displayed using the description methods on them.\n ///\n /// Do not call this function directly. It will be called automatically when interpolating\n /// a value conforming to CustomStringConvertible in the string interpolations passed\n /// to the log APIs.\n ///\n /// - Parameters:\n /// - value: The interpolated expression conforming to CustomStringConvertible.\n @_optimize(none)\n @_transparent\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation<T : CustomStringConvertible>(\n _ value: @autoclosure @escaping () -> T\n ) {\n appendInterpolation(value().description)\n }\n\n /// Defines interpolation for meta-types.\n ///\n /// Do not call this function directly. It will be called automatically when interpolating\n /// a value of type `Any.Type` in the string interpolations passed to the log APIs.\n ///\n /// - Parameters:\n /// - value: An interpolated expression of type Any.Type, which is autoclosured.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n @_semantics("oslog.requires_constant_arguments")\n public mutating func appendInterpolation(\n _ value: @autoclosure @escaping () -> Any.Type\n ) {\n appendInterpolation(_typeName(value(), qualified: false))\n }\n}\n\nextension UnsafeRawPointer: CVarArg {\n /// Transform `self` into a series of machine words that can be\n /// appropriately interpreted by C varargs.\n @inlinable // c-abi\n public var _cVarArgEncoding: [Int] {\n return _encodeBitsAsWords(self)\n }\n}\n\nextension ConstantVPrintFArguments {\n /// Append an (autoclosured) interpolated expression of type `UnsafeRawPointer`, passed\n /// to `ConstantVPrintFMessage.appendInterpolation`, to the array of closures tracked\n /// by this instance.\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n internal mutating func append(_ value: @escaping () -> UnsafeRawPointer) {\n argumentClosures.append({ continuation in\n continuation(value()._cVarArgEncoding)\n })\n }\n}\n\nextension ConstantVPrintFArguments {\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n internal mutating func append(_ value: @escaping () -> String) {\n argumentClosures.append({ continuation in\n value().withCString { str in\n continuation(str._cVarArgEncoding)\n }\n })\n }\n}\n\nextension ConstantVPrintFArguments {\n @_semantics("constant_evaluable")\n @inlinable\n @_optimize(none)\n internal mutating func append<T>(\n _ value: @escaping () -> T\n ) where T: FixedWidthInteger {\n argumentClosures.append({ continuation in\n continuation(_encodeBitsAsWords(value()))\n })\n }\n}\n\n@frozen @_semantics("oslog.message.type")\npublic struct ConstantVPrintFMessage :\n ExpressibleByStringInterpolation, ExpressibleByStringLiteral\n{\n public let interpolation: ConstantVPrintFInterpolation\n\n @inlinable\n @_optimize(none)\n @_semantics("oslog.message.init_interpolation")\n @_semantics("constant_evaluable")\n public init(stringInterpolation: ConstantVPrintFInterpolation) {\n var s = stringInterpolation\n s.appendLiteral("\n")\n self.interpolation = s\n }\n\n @inlinable\n @_optimize(none)\n @_semantics("oslog.message.init_stringliteral")\n @_semantics("constant_evaluable")\n public init(stringLiteral value: String) {\n var s = ConstantVPrintFInterpolation(\n literalCapacity: 1,\n interpolationCount: 0\n )\n s.appendLiteral(value)\n s.appendLiteral("\n")\n self.interpolation = s\n }\n}\n\ninternal func constant_vprintf_backend_recurse(\n fmt: UnsafePointer<CChar>,\n argumentClosures: ArraySlice<(([Int]) -> ()) -> ()>,\n args: inout [CVarArg]\n) {\n if let closure = argumentClosures.first {\n closure { newArg in\n args.append(contentsOf: newArg)\n constant_vprintf_backend_recurse(\n fmt: fmt,\n argumentClosures: argumentClosures.dropFirst(),\n args: &args\n )\n }\n } else {\n _ = withVaList(args) { valist in\n _swift_stdlib_vprintf(fmt, valist)\n }\n }\n}\n\n@inline(never) @usableFromInline\ninternal func constant_vprintf_backend(\n fmt: UnsafePointer<CChar>,\n argumentClosures: [(([Int]) -> ()) -> ()]\n) {\n var args:[CVarArg] = []\n if let closure = argumentClosures.first {\n closure { newArg in\n args.append(contentsOf: newArg)\n constant_vprintf_backend_recurse(\n fmt: fmt,\n argumentClosures: argumentClosures.dropFirst(),\n args: &args\n )\n }\n } else {\n constant_vprintf_backend_recurse(\n fmt: fmt,\n argumentClosures: ArraySlice(argumentClosures),\n args: &args\n )\n }\n}\n\n@_semantics("oslog.requires_constant_arguments")\n@inlinable\n@_transparent\n@_alwaysEmitIntoClient\n@_optimize(none)\npublic func print(_ message: ConstantVPrintFMessage) {\n let formatString = message.interpolation.formatString\n let argumentClosures = message.interpolation.arguments.argumentClosures\n if Bool(_builtinBooleanLiteral: Builtin.ifdef_SWIFT_STDLIB_PRINT_DISABLED()) { return }\n let formatStringPointer = _getGlobalStringTablePointer(formatString)\n constant_vprintf_backend(\n fmt: formatStringPointer,\n argumentClosures: argumentClosures\n )\n}\n\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StaticPrint.swift
cpp_apple_swift_stdlib_public_core_StaticPrint.swift
Swift
29,387
0.95
0.065292
0.306533
react-lib
75
2025-03-13T07:25:41.901915
MIT
false
521321dd8ee498e514093bc3d461dcc5
//===----------------------------------------------------------------------===//\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// Implementation Note: Because StaticString is used in the\n// implementation of _precondition(), _fatalErrorMessage(), etc., we\n// keep it extremely close to the bare metal. In particular, because\n// we store only Builtin types, we are guaranteed that no assertions\n// are involved in its construction. This feature is crucial for\n// preventing infinite recursion even in non-asserting cases.\n//\n//===----------------------------------------------------------------------===//\n\n/// A string type designed to represent text that is known at compile time.\n///\n/// Instances of the `StaticString` type are immutable.\n///\n/// `StaticString` provides only low-level access to its contents, unlike\n/// Swift's more commonly used `String` type. A static string can use\n/// either of the following as its storage:\n///\n/// * a pointer to a null-terminated sequence of UTF-8 code units:\n///\n/// let emoji: StaticString = "\u{1F600}"\n/// emoji.hasPointerRepresentation //-> true\n/// emoji.isASCII //-> false\n/// emoji.unicodeScalar //-> Fatal error!\n/// emoji.utf8CodeUnitCount //-> 4\n/// emoji.utf8Start[0] //-> 0xF0\n/// emoji.utf8Start[1] //-> 0x9F\n/// emoji.utf8Start[2] //-> 0x98\n/// emoji.utf8Start[3] //-> 0x80\n/// emoji.utf8Start[4] //-> 0x00\n///\n/// * a single Unicode scalar value, under very limited circumstances:\n///\n/// struct MyStaticScalar: ExpressibleByUnicodeScalarLiteral {\n/// typealias UnicodeScalarLiteralType = StaticString\n/// let value: StaticString\n/// init(unicodeScalarLiteral value: StaticString) {\n/// self.value = value\n/// }\n/// }\n///\n/// let emoji: StaticString = MyStaticScalar("\u{1F600}").value\n/// emoji.hasPointerRepresentation //-> false\n/// emoji.isASCII //-> false\n/// emoji.unicodeScalar.value //-> 0x1F600\n/// emoji.utf8CodeUnitCount //-> Fatal error!\n/// emoji.utf8Start //-> Fatal error!\n///\n/// You can use the `withUTF8Buffer(_:)` method to access a static string's\n/// contents, regardless of which representation the static string uses.\n///\n/// emoji.withUTF8Buffer { utf8 in\n/// utf8.count //-> 4\n/// utf8[0] //-> 0xF0\n/// utf8[1] //-> 0x9F\n/// utf8[2] //-> 0x98\n/// utf8[3] //-> 0x80\n/// utf8[4] //-> Fatal error!\n/// }\n@frozen\npublic struct StaticString: Sendable {\n\n /// Either a pointer to the start of UTF-8 data, represented as an integer,\n /// or an integer representation of a single Unicode scalar.\n @usableFromInline\n internal var _startPtrOrData: Builtin.Word\n\n /// If `_startPtrOrData` is a pointer, contains the length of the UTF-8 data\n /// in bytes (excluding the null terminator).\n @usableFromInline\n internal var _utf8CodeUnitCount: Builtin.Word\n\n /// Extra flags:\n ///\n /// - bit 0: set to 0 if `_startPtrOrData` is a pointer, or to 1 if it is a\n /// Unicode scalar.\n ///\n /// - bit 1: set to 1 if `_startPtrOrData` either points to an ASCII code unit\n /// sequence, or stores an ASCII scalar value.\n @usableFromInline\n internal var _flags: Builtin.Int8\n\n /// Creates an empty static string.\n @_transparent\n public init() {\n self = ""\n }\n\n @usableFromInline @_transparent\n internal init(\n _start: Builtin.RawPointer,\n utf8CodeUnitCount: Builtin.Word,\n isASCII: Builtin.Int1\n ) {\n // We don't go through UnsafePointer here to make things simpler for alias\n // analysis. A higher-level algorithm may be trying to make sure an\n // unrelated buffer is not accessed or freed.\n self._startPtrOrData = Builtin.ptrtoint_Word(_start)\n self._utf8CodeUnitCount = utf8CodeUnitCount\n self._flags = Bool(isASCII)\n ? (0x2 as UInt8)._value\n : (0x0 as UInt8)._value\n }\n\n @usableFromInline @_transparent\n internal init(\n unicodeScalar: Builtin.Int32\n ) {\n self._startPtrOrData = UInt(UInt32(unicodeScalar))._builtinWordValue\n self._utf8CodeUnitCount = 0._builtinWordValue\n self._flags = Unicode.Scalar(_builtinUnicodeScalarLiteral: unicodeScalar).isASCII\n ? (0x3 as UInt8)._value\n : (0x1 as UInt8)._value\n }\n\n /// A pointer to a null-terminated sequence of UTF-8 code units.\n ///\n /// - Important: Accessing this property when `hasPointerRepresentation` is\n /// `false` triggers a runtime error.\n @_transparent\n public var utf8Start: UnsafePointer<UInt8> {\n _precondition(\n hasPointerRepresentation,\n "StaticString should have pointer representation")\n return unsafe UnsafePointer(bitPattern: UInt(_startPtrOrData))!\n }\n\n /// A single Unicode scalar value.\n ///\n /// - Important: Accessing this property when `hasPointerRepresentation` is\n /// `true` triggers a runtime error.\n @_transparent\n public var unicodeScalar: Unicode.Scalar {\n _precondition(\n !hasPointerRepresentation,\n "StaticString should have Unicode scalar representation")\n return Unicode.Scalar(UInt32(UInt(_startPtrOrData)))!\n }\n\n /// The number of UTF-8 code units (excluding the null terminator).\n ///\n /// - Important: Accessing this property when `hasPointerRepresentation` is\n /// `false` triggers a runtime error.\n @_transparent\n public var utf8CodeUnitCount: Int {\n _precondition(\n hasPointerRepresentation,\n "StaticString should have pointer representation")\n return Int(_utf8CodeUnitCount)\n }\n\n @_alwaysEmitIntoClient @_transparent\n internal var unsafeRawPointer: Builtin.RawPointer {\n return Builtin.inttoptr_Word(_startPtrOrData)\n }\n\n /// A Boolean value that indicates whether the static string stores a\n /// pointer to a null-terminated sequence of UTF-8 code units.\n ///\n /// If `hasPointerRepresentation` is `false`, the static string stores a\n /// single Unicode scalar value.\n @_transparent\n public var hasPointerRepresentation: Bool {\n return (UInt8(_flags) & 0x1) == 0\n }\n\n /// A Boolean value that indicates whether the static string represents only\n /// ASCII code units (or an ASCII scalar value).\n @_transparent\n public var isASCII: Bool {\n return (UInt8(_flags) & 0x2) != 0\n }\n\n /// Invokes the given closure with a buffer containing the static string's\n /// UTF-8 code unit sequence (excluding the null terminator).\n ///\n /// This method works regardless of whether the static string stores a\n /// pointer or a single Unicode scalar value.\n ///\n /// The pointer argument to `body` is valid only during the execution of\n /// `withUTF8Buffer(_:)`. Do not store or return the pointer for later use.\n ///\n /// - Parameter body: A closure that takes a buffer pointer to the static\n /// string's UTF-8 code unit sequence as its sole argument. If the closure\n /// has a return value, that value is also used as the return value of the\n /// `withUTF8Buffer(_:)` method. The pointer argument is valid only for the\n /// duration of the method's execution.\n /// - Returns: The return value, if any, of the `body` closure.\n @_transparent\n @safe\n public func withUTF8Buffer<R>(\n _ body: (UnsafeBufferPointer<UInt8>) -> R\n ) -> R {\n if hasPointerRepresentation {\n return unsafe body(UnsafeBufferPointer(\n start: utf8Start, count: utf8CodeUnitCount))\n } else {\n #if $Embedded\n fatalError("non-pointer representation not supported in embedded Swift")\n #else\n return unicodeScalar.withUTF8CodeUnits { unsafe body($0) }\n #endif\n }\n }\n}\n\nextension StaticString: _ExpressibleByBuiltinUnicodeScalarLiteral {\n\n @_effects(readonly)\n @_transparent\n public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {\n self = StaticString(unicodeScalar: value)\n }\n}\n\nextension StaticString: ExpressibleByUnicodeScalarLiteral {\n\n /// Creates an instance initialized to a single Unicode scalar.\n ///\n /// Do not call this initializer directly. It may be used by the compiler\n /// when you initialize a static string with a Unicode scalar.\n @_effects(readonly)\n @_transparent\n public init(unicodeScalarLiteral value: StaticString) {\n self = value\n }\n}\n\nextension StaticString: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {\n\n @_effects(readonly)\n @_transparent\n public init(\n _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,\n utf8CodeUnitCount: Builtin.Word,\n isASCII: Builtin.Int1\n ) {\n self = StaticString(\n _builtinStringLiteral: start,\n utf8CodeUnitCount: utf8CodeUnitCount,\n isASCII: isASCII\n )\n }\n}\n\nextension StaticString: ExpressibleByExtendedGraphemeClusterLiteral {\n\n /// Creates an instance initialized to a single character that is made up of\n /// one or more Unicode scalar values.\n ///\n /// Do not call this initializer directly. It may be used by the compiler\n /// when you initialize a static string using an extended grapheme cluster.\n @_effects(readonly)\n @_transparent\n public init(extendedGraphemeClusterLiteral value: StaticString) {\n self = value\n }\n}\n\nextension StaticString: _ExpressibleByBuiltinStringLiteral {\n\n @_effects(readonly)\n @_transparent\n public init(\n _builtinStringLiteral start: Builtin.RawPointer,\n utf8CodeUnitCount: Builtin.Word,\n isASCII: Builtin.Int1\n ) {\n self = StaticString(\n _start: start,\n utf8CodeUnitCount: utf8CodeUnitCount,\n isASCII: isASCII)\n }\n}\n\nextension StaticString: ExpressibleByStringLiteral {\n\n /// Creates an instance initialized to the value of a string literal.\n ///\n /// Do not call this initializer directly. It may be used by the compiler\n /// when you initialize a static string using a string literal.\n @_effects(readonly)\n @_transparent\n public init(stringLiteral value: StaticString) {\n self = value\n }\n}\n\nextension StaticString: CustomStringConvertible {\n\n /// A textual representation of the static string.\n public var description: String {\n return withUTF8Buffer { unsafe String._uncheckedFromUTF8($0) }\n }\n}\n\nextension StaticString: CustomDebugStringConvertible {\n\n /// A textual representation of the static string, suitable for debugging.\n public var debugDescription: String {\n return self.description.debugDescription\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension StaticString: CustomReflectable {\n\n public var customMirror: Mirror {\n return Mirror(reflecting: description)\n }\n}\n#endif\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StaticString.swift
cpp_apple_swift_stdlib_public_core_StaticString.swift
Swift
11,001
0.8
0.043344
0.474227
react-lib
757
2024-02-18T04:52:10.837140
GPL-3.0
false
8d93c5bce194c6c543778eaf535c09fb
//===--- Stride.swift - Components for stride(...) iteration --------------===//\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 representing continuous, one-dimensional values that can be offset\n/// and measured.\n///\n/// You can use a type that conforms to the `Strideable` protocol with the\n/// `stride(from:to:by:)` and `stride(from:through:by:)` functions. For\n/// example, you can use `stride(from:to:by:)` to iterate over an\n/// interval of floating-point values:\n///\n/// for radians in stride(from: 0.0, to: .pi * 2, by: .pi / 2) {\n/// let degrees = Int(radians * 180 / .pi)\n/// print("Degrees: \(degrees), radians: \(radians)")\n/// }\n/// // Degrees: 0, radians: 0.0\n/// // Degrees: 90, radians: 1.5707963267949\n/// // Degrees: 180, radians: 3.14159265358979\n/// // Degrees: 270, radians: 4.71238898038469\n///\n/// The last parameter of these functions is of the associated `Stride`\n/// type---the type that represents the distance between any two instances of\n/// the `Strideable` type.\n///\n/// Types that have an integer `Stride` can be used as the boundaries of a\n/// countable range or as the lower bound of an iterable one-sided range. For\n/// example, you can iterate over a range of `Int` and use sequence and\n/// collection methods.\n///\n/// var sum = 0\n/// for x in 1...100 {\n/// sum += x\n/// }\n/// // sum == 5050\n///\n/// let digits = (0..<10).map(String.init)\n/// // ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]\n///\n/// Conforming to the Strideable Protocol\n/// =====================================\n///\n/// To add `Strideable` conformance to a custom type, choose a `Stride` type\n/// that can represent the distance between two instances and implement the\n/// `advanced(by:)` and `distance(to:)` methods. For example, this\n/// hypothetical `Date` type stores its value as the number of days before or\n/// after January 1, 2000:\n///\n/// struct Date: Equatable, CustomStringConvertible {\n/// var daysAfterY2K: Int\n///\n/// var description: String {\n/// // ...\n/// }\n/// }\n///\n/// The `Stride` type for `Date` is `Int`, inferred from the parameter and\n/// return types of `advanced(by:)` and `distance(to:)`:\n///\n/// extension Date: Strideable {\n/// func advanced(by n: Int) -> Date {\n/// var result = self\n/// result.daysAfterY2K += n\n/// return result\n/// }\n///\n/// func distance(to other: Date) -> Int {\n/// return other.daysAfterY2K - self.daysAfterY2K\n/// }\n/// }\n///\n/// The `Date` type can now be used with the `stride(from:to:by:)` and\n/// `stride(from:through:by:)` functions and as the bounds of an iterable\n/// range.\n///\n/// let startDate = Date(daysAfterY2K: 0) // January 1, 2000\n/// let endDate = Date(daysAfterY2K: 15) // January 16, 2000\n///\n/// for date in stride(from: startDate, to: endDate, by: 7) {\n/// print(date)\n/// }\n/// // January 1, 2000\n/// // January 8, 2000\n/// // January 15, 2000\n///\n/// - Important: The `Strideable` protocol provides default implementations for\n/// the equal-to (`==`) and less-than (`<`) operators that depend on the\n/// `Stride` type's implementations. If a type conforming to `Strideable` is\n/// its own `Stride` type, it must provide concrete implementations of the\n/// two operators to avoid infinite recursion.\npublic protocol Strideable<Stride>: Comparable {\n /// A type that represents the distance between two values.\n associatedtype Stride: SignedNumeric, Comparable\n\n /// Returns the distance from this value to the given value, expressed as a \n /// stride.\n ///\n /// If this type's `Stride` type conforms to `BinaryInteger`, then for two\n /// values `x` and `y`, and a distance `n = x.distance(to: y)`,\n /// `x.advanced(by: n) == y`. Using this method with types that have a\n /// noninteger `Stride` may result in an approximation.\n ///\n /// - Parameter other: The value to calculate the distance to.\n /// - Returns: The distance from this value to `other`.\n ///\n /// - Complexity: O(1)\n func distance(to other: Self) -> Stride\n\n /// Returns a value that is offset the specified distance from this value.\n ///\n /// Use the `advanced(by:)` method in generic code to offset a value by a\n /// specified distance. If you're working directly with numeric values, use\n /// the addition operator (`+`) instead of this method.\n ///\n /// func addOne<T: Strideable>(to x: T) -> T\n /// where T.Stride: ExpressibleByIntegerLiteral\n /// {\n /// return x.advanced(by: 1)\n /// }\n ///\n /// let x = addOne(to: 5)\n /// // x == 6\n /// let y = addOne(to: 3.5)\n /// // y = 4.5\n ///\n /// If this type's `Stride` type conforms to `BinaryInteger`, then for a\n /// value `x`, a distance `n`, and a value `y = x.advanced(by: n)`,\n /// `x.distance(to: y) == n`. Using this method with types that have a\n /// noninteger `Stride` may result in an approximation. If the result of\n /// advancing by `n` is not representable as a value of this type, then a\n /// runtime error may occur.\n ///\n /// - Parameter n: The distance to advance this value.\n /// - Returns: A value that is offset from this value by `n`.\n ///\n /// - Complexity: O(1)\n func advanced(by n: Stride) -> Self\n\n /// Returns the next result of striding by a specified distance.\n ///\n /// This method is an implementation detail of `Strideable`; do not call it\n /// directly.\n ///\n /// While striding, `_step(after:from:by:)` is called at each step to\n /// determine the next result. At the first step, the value of `current` is\n /// `(index: 0, value: start)`. At each subsequent step, the value of\n /// `current` is the result returned by this method in the immediately\n /// preceding step.\n ///\n /// If the result of advancing by a given `distance` is not representable as a\n /// value of this type, then a runtime error may occur.\n ///\n /// Implementing `_step(after:from:by:)` to Customize Striding Behavior\n /// ===================================================================\n ///\n /// The default implementation of this method calls `advanced(by:)` to offset\n /// `current.value` by a specified `distance`. No attempt is made to count the\n /// number of prior steps, and the result's `index` is always `nil`.\n ///\n /// To avoid incurring runtime errors that arise from advancing past\n /// representable bounds, a conforming type can signal that the result of\n /// advancing by a given `distance` is not representable by using `Int.min` as\n /// a sentinel value for the result's `index`. In that case, the result's\n /// `value` must be either the minimum representable value of this type if\n /// `distance` is less than zero or the maximum representable value of this\n /// type otherwise. Fixed-width integer types make use of arithmetic\n /// operations reporting overflow to implement this customization.\n ///\n /// A conforming type may use any positive value for the result's `index` as\n /// an opaque state that is private to that type. For example, floating-point\n /// types increment `index` with each step so that the corresponding `value`\n /// can be computed by multiplying the number of steps by the specified\n /// `distance`. Serially calling `advanced(by:)` would accumulate\n /// floating-point rounding error at each step, which is avoided by this\n /// customization.\n ///\n /// - Parameters:\n /// - current: The result returned by this method in the immediately\n /// preceding step while striding, or `(index: 0, value: start)` if there\n /// have been no preceding steps.\n /// - start: The starting value used for the striding sequence.\n /// - distance: The amount to step by with each iteration of the striding\n /// sequence.\n /// - Returns: A tuple of `index` and `value`; `index` may be `nil`, any\n /// positive value as an opaque state private to the conforming type, or\n /// `Int.min` to signal that the notional result of advancing by `distance`\n /// is unrepresentable, and `value` is the next result after `current.value`\n /// while striding from `start` by `distance`.\n ///\n /// - Complexity: O(1)\n static func _step(\n after current: (index: Int?, value: Self),\n from start: Self, by distance: Self.Stride\n ) -> (index: Int?, value: Self)\n}\n\nextension Strideable {\n @inlinable\n public static func < (x: Self, y: Self) -> Bool {\n return x.distance(to: y) > 0\n }\n\n @inlinable\n public static func == (x: Self, y: Self) -> Bool {\n return x.distance(to: y) == 0\n }\n}\n\nextension Strideable {\n @inlinable // protocol-only\n public static func _step(\n after current: (index: Int?, value: Self),\n from start: Self, by distance: Self.Stride\n ) -> (index: Int?, value: Self) {\n return (nil, current.value.advanced(by: distance))\n }\n}\n\nextension Strideable where Self: FixedWidthInteger & SignedInteger {\n @_alwaysEmitIntoClient\n public static func _step(\n after current: (index: Int?, value: Self),\n from start: Self, by distance: Self.Stride\n ) -> (index: Int?, value: Self) {\n let value = current.value\n let (partialValue, overflow) =\n Self.bitWidth >= Self.Stride.bitWidth ||\n (value < (0 as Self)) == (distance < (0 as Self.Stride))\n ? value.addingReportingOverflow(Self(distance))\n : (Self(Self.Stride(value) + distance), false)\n return overflow\n ? (.min, distance < (0 as Self.Stride) ? .min : .max)\n : (nil, partialValue)\n }\n}\n\nextension Strideable where Self: FixedWidthInteger & UnsignedInteger {\n @_alwaysEmitIntoClient\n public static func _step(\n after current: (index: Int?, value: Self),\n from start: Self, by distance: Self.Stride\n ) -> (index: Int?, value: Self) {\n let (partialValue, overflow) = distance < (0 as Self.Stride)\n ? current.value.subtractingReportingOverflow(Self(-distance))\n : current.value.addingReportingOverflow(Self(distance))\n return overflow\n ? (.min, distance < (0 as Self.Stride) ? .min : .max)\n : (nil, partialValue)\n }\n}\n\nextension Strideable where Stride: FloatingPoint {\n @inlinable // protocol-only\n public static func _step(\n after current: (index: Int?, value: Self),\n from start: Self, by distance: Self.Stride\n ) -> (index: Int?, value: Self) {\n if let i = current.index {\n // When Stride is a floating-point type, we should avoid accumulating\n // rounding error from repeated addition.\n return (i + 1, start.advanced(by: Stride(i + 1) * distance))\n }\n return (nil, current.value.advanced(by: distance))\n }\n}\n\nextension Strideable where Self: FloatingPoint, Self == Stride {\n @inlinable // protocol-only\n public static func _step(\n after current: (index: Int?, value: Self),\n from start: Self, by distance: Self.Stride\n ) -> (index: Int?, value: Self) {\n if let i = current.index {\n // When both Self and Stride are the same floating-point type, we should\n // take advantage of fused multiply-add (where supported) to eliminate\n // intermediate rounding error.\n return (i + 1, start.addingProduct(Stride(i + 1), distance))\n }\n return (nil, current.value.advanced(by: distance))\n }\n}\n\n/// An iterator for a `StrideTo` instance.\n@frozen\npublic struct StrideToIterator<Element: Strideable> {\n @usableFromInline\n internal let _start: Element\n\n @usableFromInline\n internal let _end: Element\n\n @usableFromInline\n internal let _stride: Element.Stride\n\n @usableFromInline\n internal var _current: (index: Int?, value: Element)\n\n @inlinable\n internal init(_start: Element, end: Element, stride: Element.Stride) {\n self._start = _start\n _end = end\n _stride = stride\n _current = (0, _start)\n }\n}\n\nextension StrideToIterator: 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 mutating func next() -> Element? {\n let result = _current.value\n if _stride > 0 ? result >= _end : result <= _end {\n return nil\n }\n _current = Element._step(after: _current, from: _start, by: _stride)\n return result\n }\n}\n\n// FIXME: should really be a Collection, as it is multipass\n/// A sequence of values formed by striding over a half-open interval.\n///\n/// Use the `stride(from:to:by:)` function to create `StrideTo` instances.\n@frozen\npublic struct StrideTo<Element: Strideable> {\n @usableFromInline\n internal let _start: Element\n\n @usableFromInline\n internal let _end: Element\n\n @usableFromInline\n internal let _stride: Element.Stride\n\n @inlinable\n internal init(_start: Element, end: Element, stride: Element.Stride) {\n _precondition(stride != 0, "Stride size must not be zero")\n // At start, striding away from end is allowed; it just makes for an\n // already-empty Sequence.\n self._start = _start\n self._end = end\n self._stride = stride\n }\n}\n\nextension StrideTo: Sequence {\n /// Returns an iterator over the elements of this sequence.\n ///\n /// - Complexity: O(1).\n @inlinable\n public __consuming func makeIterator() -> StrideToIterator<Element> {\n return StrideToIterator(_start: _start, end: _end, stride: _stride)\n }\n\n // FIXME(conditional-conformances): this is O(N) instead of O(1), leaving it\n // here until a proper Collection conformance is possible\n @inlinable\n public var underestimatedCount: Int {\n var it = self.makeIterator()\n var count = 0\n while it.next() != nil {\n count += 1\n }\n return count\n }\n\n @inlinable\n public func _customContainsEquatableElement(\n _ element: Element\n ) -> Bool? {\n if _stride < 0 {\n if element <= _end || _start < element { return false }\n } else {\n if element < _start || _end <= element { return false }\n }\n // TODO: Additional implementation work will avoid always falling back to the\n // predicate version of `contains` when the sequence *does* contain `element`.\n return nil\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension StrideTo: CustomReflectable {\n public var customMirror: Mirror {\n return Mirror(self, children: ["from": _start, "to": _end, "by": _stride])\n }\n}\n#endif\n\n// FIXME(conditional-conformances): This does not yet compile (https://github.com/apple/swift/issues/49024).\n#if false\nextension StrideTo: RandomAccessCollection\nwhere Element.Stride: BinaryInteger {\n public typealias Index = Int\n public typealias SubSequence = Slice<StrideTo<Element>>\n public typealias Indices = Range<Int>\n\n @inlinable\n public var startIndex: Index { return 0 }\n\n @inlinable\n public var endIndex: Index { return count }\n\n @inlinable\n public var count: Int {\n let distance = _start.distance(to: _end)\n guard distance != 0 && (distance < 0) == (_stride < 0) else { return 0 }\n return Int((distance - 1) / _stride) + 1\n }\n\n public subscript(position: Index) -> Element {\n _failEarlyRangeCheck(position, bounds: startIndex..<endIndex)\n return _start.advanced(by: Element.Stride(position) * _stride)\n }\n\n public subscript(bounds: Range<Index>) -> Slice<StrideTo<Element>> {\n _failEarlyRangeCheck(bounds, bounds: startIndex ..< endIndex)\n return Slice(base: self, bounds: bounds)\n }\n\n @inlinable\n public func index(before i: Index) -> Index {\n _failEarlyRangeCheck(i, bounds: startIndex + 1...endIndex)\n return i - 1\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n _failEarlyRangeCheck(i, bounds: startIndex - 1..<endIndex)\n return i + 1\n }\n}\n#endif\n\n/// Returns a sequence from a starting value to, but not including, an end\n/// value, stepping by the specified amount.\n///\n/// You can use this function to stride over values of any type that conforms\n/// to the `Strideable` protocol, such as integers or floating-point types.\n/// Starting with `start`, each successive value of the sequence adds `stride`\n/// until the next value would be equal to or beyond `end`.\n///\n/// for radians in stride(from: 0.0, to: .pi * 2, by: .pi / 2) {\n/// let degrees = Int(radians * 180 / .pi)\n/// print("Degrees: \(degrees), radians: \(radians)")\n/// }\n/// // Degrees: 0, radians: 0.0\n/// // Degrees: 90, radians: 1.5707963267949\n/// // Degrees: 180, radians: 3.14159265358979\n/// // Degrees: 270, radians: 4.71238898038469\n///\n/// You can use `stride(from:to:by:)` to create a sequence that strides upward\n/// or downward. Pass a negative value as `stride` to create a sequence from a\n/// higher start to a lower end:\n///\n/// for countdown in stride(from: 3, to: 0, by: -1) {\n/// print("\(countdown)...")\n/// }\n/// // 3...\n/// // 2...\n/// // 1...\n///\n/// If you pass a value as `stride` that moves away from `end`, the sequence\n/// contains no values.\n///\n/// for x in stride(from: 0, to: 10, by: -1) {\n/// print(x)\n/// }\n/// // Nothing is printed.\n///\n/// - Parameters:\n/// - start: The starting value to use for the sequence. If the sequence\n/// contains any values, the first one is `start`.\n/// - end: An end value to limit the sequence. `end` is never an element of\n/// the resulting sequence.\n/// - stride: The amount to step by with each iteration. A positive `stride`\n/// iterates upward; a negative `stride` iterates downward.\n/// - Returns: A sequence from `start` toward, but not including, `end`. Each\n/// value in the sequence steps by `stride`.\n@inlinable\npublic func stride<T>(\n from start: T, to end: T, by stride: T.Stride\n) -> StrideTo<T> {\n return StrideTo(_start: start, end: end, stride: stride)\n}\n\n/// An iterator for a `StrideThrough` instance.\n@frozen\npublic struct StrideThroughIterator<Element: Strideable> {\n @usableFromInline\n internal let _start: Element\n\n @usableFromInline\n internal let _end: Element\n\n @usableFromInline\n internal let _stride: Element.Stride\n\n @usableFromInline\n internal var _current: (index: Int?, value: Element)\n\n @usableFromInline\n internal var _didReturnEnd: Bool = false\n\n @inlinable\n internal init(_start: Element, end: Element, stride: Element.Stride) {\n self._start = _start\n _end = end\n _stride = stride\n _current = (0, _start)\n }\n}\n\nextension StrideThroughIterator: 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 mutating func next() -> Element? {\n let result = _current.value\n if _stride > 0 ? result >= _end : result <= _end {\n // Note the `>=` and `<=` operators above. When `result == _end`, the\n // following check is needed to prevent advancing `_current` past the\n // representable bounds of the `Strideable` type unnecessarily.\n //\n // If the `Strideable` type is a fixed-width integer, overflowed results\n // are represented using a sentinel value for `_current.index`, `Int.min`.\n if result == _end && !_didReturnEnd && _current.index != .min {\n _didReturnEnd = true\n return result\n }\n return nil\n }\n _current = Element._step(after: _current, from: _start, by: _stride)\n return result\n }\n}\n\n// FIXME: should really be a Collection, as it is multipass\n/// A sequence of values formed by striding over a closed interval.\n///\n/// Use the `stride(from:through:by:)` function to create `StrideThrough` \n/// instances.\n@frozen\npublic struct StrideThrough<Element: Strideable> {\n @usableFromInline\n internal let _start: Element\n @usableFromInline\n internal let _end: Element\n @usableFromInline\n internal let _stride: Element.Stride\n \n @inlinable\n internal init(_start: Element, end: Element, stride: Element.Stride) {\n _precondition(stride != 0, "Stride size must not be zero")\n self._start = _start\n self._end = end\n self._stride = stride\n }\n}\n\nextension StrideThrough: Sequence {\n /// Returns an iterator over the elements of this sequence.\n ///\n /// - Complexity: O(1).\n @inlinable\n public __consuming func makeIterator() -> StrideThroughIterator<Element> {\n return StrideThroughIterator(_start: _start, end: _end, stride: _stride)\n }\n\n // FIXME(conditional-conformances): this is O(N) instead of O(1), leaving it\n // here until a proper Collection conformance is possible\n @inlinable\n public var underestimatedCount: Int {\n var it = self.makeIterator()\n var count = 0\n while it.next() != nil {\n count += 1\n }\n return count\n }\n\n @inlinable\n public func _customContainsEquatableElement(\n _ element: Element\n ) -> Bool? {\n if _stride < 0 {\n if element < _end || _start < element { return false }\n } else {\n if element < _start || _end < element { return false }\n }\n // TODO: Additional implementation work will avoid always falling back to the\n // predicate version of `contains` when the sequence *does* contain `element`.\n return nil\n }\n}\n\n#if SWIFT_ENABLE_REFLECTION\nextension StrideThrough: CustomReflectable {\n public var customMirror: Mirror {\n return Mirror(self,\n children: ["from": _start, "through": _end, "by": _stride])\n }\n}\n#endif\n\n// FIXME(conditional-conformances): This does not yet compile (https://github.com/apple/swift/issues/49024).\n#if false\nextension StrideThrough: RandomAccessCollection\nwhere Element.Stride: BinaryInteger {\n public typealias Index = ClosedRangeIndex<Int>\n public typealias SubSequence = Slice<StrideThrough<Element>>\n\n @inlinable\n public var startIndex: Index {\n let distance = _start.distance(to: _end)\n return distance == 0 || (distance < 0) == (_stride < 0)\n ? ClosedRangeIndex(0)\n : ClosedRangeIndex()\n }\n\n @inlinable\n public var endIndex: Index { return ClosedRangeIndex() }\n\n @inlinable\n public var count: Int {\n let distance = _start.distance(to: _end)\n guard distance != 0 else { return 1 }\n guard (distance < 0) == (_stride < 0) else { return 0 }\n return Int(distance / _stride) + 1\n }\n\n public subscript(position: Index) -> Element {\n let offset = Element.Stride(position._dereferenced) * _stride\n return _start.advanced(by: offset)\n }\n\n public subscript(bounds: Range<Index>) -> Slice<StrideThrough<Element>> {\n return Slice(base: self, bounds: bounds)\n }\n\n @inlinable\n public func index(before i: Index) -> Index {\n switch i._value {\n case .inRange(let n):\n _precondition(n > 0, "Incrementing past start index")\n return ClosedRangeIndex(n - 1)\n case .pastEnd:\n _precondition(_end >= _start, "Incrementing past start index")\n return ClosedRangeIndex(count - 1)\n }\n }\n\n @inlinable\n public func index(after i: Index) -> Index {\n switch i._value {\n case .inRange(let n):\n return n == (count - 1)\n ? ClosedRangeIndex()\n : ClosedRangeIndex(n + 1)\n case .pastEnd:\n _preconditionFailure("Incrementing past end index")\n }\n }\n}\n#endif\n\n/// Returns a sequence from a starting value toward, and possibly including, an end\n/// value, stepping by the specified amount.\n///\n/// You can use this function to stride over values of any type that conforms\n/// to the `Strideable` protocol, such as integers or floating-point types.\n/// Starting with `start`, each successive value of the sequence adds `stride`\n/// until the next value would be beyond `end`.\n///\n/// for radians in stride(from: 0.0, through: .pi * 2, by: .pi / 2) {\n/// let degrees = Int(radians * 180 / .pi)\n/// print("Degrees: \(degrees), radians: \(radians)")\n/// }\n/// // Degrees: 0, radians: 0.0\n/// // Degrees: 90, radians: 1.5707963267949\n/// // Degrees: 180, radians: 3.14159265358979\n/// // Degrees: 270, radians: 4.71238898038469\n/// // Degrees: 360, radians: 6.28318530717959\n///\n/// You can use `stride(from:through:by:)` to create a sequence that strides \n/// upward or downward. Pass a negative value as `stride` to create a sequence \n/// from a higher start to a lower end:\n///\n/// for countdown in stride(from: 3, through: 1, by: -1) {\n/// print("\(countdown)...")\n/// }\n/// // 3...\n/// // 2...\n/// // 1...\n///\n/// The value you pass as `end` is not guaranteed to be included in the \n/// sequence. If stepping from `start` by `stride` does not produce `end`, \n/// the last value in the sequence will be one step before going beyond `end`.\n///\n/// for multipleOfThree in stride(from: 3, through: 10, by: 3) {\n/// print(multipleOfThree)\n/// }\n/// // 3\n/// // 6\n/// // 9\n///\n/// If you pass a value as `stride` that moves away from `end`, the sequence \n/// contains no values.\n///\n/// for x in stride(from: 0, through: 10, by: -1) {\n/// print(x)\n/// }\n/// // Nothing is printed.\n///\n/// - Parameters:\n/// - start: The starting value to use for the sequence. If the sequence\n/// contains any values, the first one is `start`.\n/// - end: An end value to limit the sequence. `end` is an element of\n/// the resulting sequence if and only if it can be produced from `start` \n/// using steps of `stride`.\n/// - stride: The amount to step by with each iteration. A positive `stride`\n/// iterates upward; a negative `stride` iterates downward.\n/// - Returns: A sequence from `start` toward, and possibly including, `end`. \n/// Each value in the sequence is separated by `stride`.\n@inlinable\npublic func stride<T>(\n from start: T, through end: T, by stride: T.Stride\n) -> StrideThrough<T> {\n return StrideThrough(_start: start, end: end, stride: stride)\n}\n\nextension StrideToIterator: Sendable\n where Element: Sendable, Element.Stride: Sendable { }\nextension StrideTo: Sendable\n where Element: Sendable, Element.Stride: Sendable { }\nextension StrideThroughIterator: Sendable\n where Element: Sendable, Element.Stride: Sendable { }\nextension StrideThrough: Sendable\n where Element: Sendable, Element.Stride: Sendable { }\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_Stride.swift
cpp_apple_swift_stdlib_public_core_Stride.swift
Swift
26,410
0.95
0.075798
0.502158
python-kit
249
2023-10-21T12:20:24.751608
Apache-2.0
false
0c41127a160e657b417e3bba3dc73b9d
//===----------------------------------------------------------------------===//\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\nimport SwiftShims\n\n/// A Unicode string value that is a collection of characters.\n///\n/// A string is a series of characters, such as `"Swift"`, that forms a\n/// collection. Strings in Swift are Unicode correct and locale insensitive,\n/// and are designed to be efficient. The `String` type bridges with the\n/// Objective-C class `NSString` and offers interoperability with C functions\n/// that works with strings.\n///\n/// You can create new strings using string literals or string interpolations.\n/// A *string literal* is a series of characters enclosed in quotes.\n///\n/// let greeting = "Welcome!"\n///\n/// *String interpolations* are string literals that evaluate any included\n/// expressions and convert the results to string form. String interpolations\n/// give you an easy way to build a string from multiple pieces. Wrap each\n/// expression in a string interpolation in parentheses, prefixed by a\n/// backslash.\n///\n/// let name = "Rosa"\n/// let personalizedGreeting = "Welcome, \(name)!"\n/// // personalizedGreeting == "Welcome, Rosa!"\n///\n/// let price = 2\n/// let number = 3\n/// let cookiePrice = "\(number) cookies: $\(price * number)."\n/// // cookiePrice == "3 cookies: $6."\n///\n/// Combine strings using the concatenation operator (`+`).\n///\n/// let longerGreeting = greeting + " We're glad you're here!"\n/// // longerGreeting == "Welcome! We're glad you're here!"\n///\n/// Multiline string literals are enclosed in three double quotation marks\n/// (`"""`), with each delimiter on its own line. Indentation is stripped from\n/// each line of a multiline string literal to match the indentation of the\n/// closing delimiter.\n///\n/// let banner = """\n/// __,\n/// ( o /) _/_\n/// `. , , , , // /\n/// (___)(_(_/_(_ //_ (__\n/// /)\n/// (/\n/// """\n///\n/// Modifying and Comparing Strings\n/// ===============================\n///\n/// Strings always have value semantics. Modifying a copy of a string leaves\n/// the original unaffected.\n///\n/// var otherGreeting = greeting\n/// otherGreeting += " Have a nice time!"\n/// // otherGreeting == "Welcome! Have a nice time!"\n///\n/// print(greeting)\n/// // Prints "Welcome!"\n///\n/// Comparing strings for equality using the equal-to operator (`==`) or a\n/// relational operator (like `<` or `>=`) is always performed using Unicode\n/// canonical representation. As a result, different representations of a\n/// string compare as being equal.\n///\n/// let cafe1 = "Cafe\u{301}"\n/// let cafe2 = "Café"\n/// print(cafe1 == cafe2)\n/// // Prints "true"\n///\n/// The Unicode scalar value `"\u{301}"` modifies the preceding character to\n/// include an accent, so `"e\u{301}"` has the same canonical representation\n/// as the single Unicode scalar value `"é"`.\n///\n/// Basic string operations are not sensitive to locale settings, ensuring that\n/// string comparisons and other operations always have a single, stable\n/// result, allowing strings to be used as keys in `Dictionary` instances and\n/// for other purposes.\n///\n/// Accessing String Elements\n/// =========================\n///\n/// A string is a collection of *extended grapheme clusters*, which approximate\n/// human-readable characters. Many individual characters, such as "é", "김",\n/// and "🇮🇳", can be made up of multiple Unicode scalar values. These scalar\n/// values are combined by Unicode's boundary algorithms into extended\n/// grapheme clusters, represented by the Swift `Character` type. Each element\n/// of a string is represented by a `Character` instance.\n///\n/// For example, to retrieve the first word of a longer string, you can search\n/// for a space and then create a substring from a prefix of the string up to\n/// that point:\n///\n/// let name = "Marie Curie"\n/// let firstSpace = name.firstIndex(of: " ") ?? name.endIndex\n/// let firstName = name[..<firstSpace]\n/// // firstName == "Marie"\n///\n/// The `firstName` constant is an instance of the `Substring` type---a type\n/// that represents substrings of a string while sharing the original string's\n/// storage. Substrings present the same interface as strings.\n///\n/// print("\(name)'s first name has \(firstName.count) letters.")\n/// // Prints "Marie Curie's first name has 5 letters."\n///\n/// Accessing a String's Unicode Representation\n/// ===========================================\n///\n/// If you need to access the contents of a string as encoded in different\n/// Unicode encodings, use one of the string's `unicodeScalars`, `utf16`, or\n/// `utf8` properties. Each property provides access to a view of the string\n/// as a series of code units, each encoded in a different Unicode encoding.\n///\n/// To demonstrate the different views available for every string, the\n/// following examples use this `String` instance:\n///\n/// let cafe = "Cafe\u{301} du 🌍"\n/// print(cafe)\n/// // Prints "Café du 🌍"\n///\n/// The `cafe` string is a collection of the nine characters that are visible\n/// when the string is displayed.\n///\n/// print(cafe.count)\n/// // Prints "9"\n/// print(Array(cafe))\n/// // Prints "["C", "a", "f", "é", " ", "d", "u", " ", "🌍"]"\n///\n/// Unicode Scalar View\n/// -------------------\n///\n/// A string's `unicodeScalars` property is a collection of Unicode scalar\n/// values, the 21-bit codes that are the basic unit of Unicode. Each scalar\n/// value is represented by a `Unicode.Scalar` instance and is equivalent to a\n/// UTF-32 code unit.\n///\n/// print(cafe.unicodeScalars.count)\n/// // Prints "10"\n/// print(Array(cafe.unicodeScalars))\n/// // Prints "["C", "a", "f", "e", "\u{0301}", " ", "d", "u", " ", "\u{0001F30D}"]"\n/// print(cafe.unicodeScalars.map { $0.value })\n/// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 127757]"\n///\n/// The `unicodeScalars` view's elements comprise each Unicode scalar value in\n/// the `cafe` string. In particular, because `cafe` was declared using the\n/// decomposed form of the `"é"` character, `unicodeScalars` contains the\n/// scalar values for both the letter `"e"` (101) and the accent character\n/// `"´"` (769).\n///\n/// UTF-16 View\n/// -----------\n///\n/// A string's `utf16` property is a collection of UTF-16 code units, the\n/// 16-bit encoding form of the string's Unicode scalar values. Each code unit\n/// is stored as a `UInt16` instance.\n///\n/// print(cafe.utf16.count)\n/// // Prints "11"\n/// print(Array(cafe.utf16))\n/// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 55356, 57101]"\n///\n/// The elements of the `utf16` view are the code units for the string when\n/// encoded in UTF-16. These elements match those accessed through indexed\n/// `NSString` APIs.\n///\n/// let nscafe = cafe as NSString\n/// print(nscafe.length)\n/// // Prints "11"\n/// print(nscafe.character(at: 3))\n/// // Prints "101"\n///\n/// UTF-8 View\n/// ----------\n///\n/// A string's `utf8` property is a collection of UTF-8 code units, the 8-bit\n/// encoding form of the string's Unicode scalar values. Each code unit is\n/// stored as a `UInt8` instance.\n///\n/// print(cafe.utf8.count)\n/// // Prints "14"\n/// print(Array(cafe.utf8))\n/// // Prints "[67, 97, 102, 101, 204, 129, 32, 100, 117, 32, 240, 159, 140, 141]"\n///\n/// The elements of the `utf8` view are the code units for the string when\n/// encoded in UTF-8. This representation matches the one used when `String`\n/// instances are passed to C APIs.\n///\n/// let cLength = strlen(cafe)\n/// print(cLength)\n/// // Prints "14"\n///\n/// Measuring the Length of a String\n/// ================================\n///\n/// When you need to know the length of a string, you must first consider what\n/// you'll use the length for. Are you measuring the number of characters that\n/// will be displayed on the screen, or are you measuring the amount of\n/// storage needed for the string in a particular encoding? A single string\n/// can have greatly differing lengths when measured by its different views.\n///\n/// For example, an ASCII character like the capital letter *A* is represented\n/// by a single element in each of its four views. The Unicode scalar value of\n/// *A* is `65`, which is small enough to fit in a single code unit in both\n/// UTF-16 and UTF-8.\n///\n/// let capitalA = "A"\n/// print(capitalA.count)\n/// // Prints "1"\n/// print(capitalA.unicodeScalars.count)\n/// // Prints "1"\n/// print(capitalA.utf16.count)\n/// // Prints "1"\n/// print(capitalA.utf8.count)\n/// // Prints "1"\n///\n/// On the other hand, an emoji flag character is constructed from a pair of\n/// Unicode scalar values, like `"\u{1F1F5}"` and `"\u{1F1F7}"`. Each of these\n/// scalar values, in turn, is too large to fit into a single UTF-16 or UTF-8\n/// code unit. As a result, each view of the string `"🇵🇷"` reports a different\n/// length.\n///\n/// let flag = "🇵🇷"\n/// print(flag.count)\n/// // Prints "1"\n/// print(flag.unicodeScalars.count)\n/// // Prints "2"\n/// print(flag.utf16.count)\n/// // Prints "4"\n/// print(flag.utf8.count)\n/// // Prints "8"\n///\n/// To check whether a string is empty, use its `isEmpty` property instead of\n/// comparing the length of one of the views to `0`. Unlike with `isEmpty`,\n/// calculating a view's `count` property requires iterating through the\n/// elements of the string.\n///\n/// Accessing String View Elements\n/// ==============================\n///\n/// To find individual elements of a string, use the appropriate view for your\n/// task. For example, to retrieve the first word of a longer string, you can\n/// search the string for a space and then create a new string from a prefix\n/// of the string up to that point.\n///\n/// let name = "Marie Curie"\n/// let firstSpace = name.firstIndex(of: " ") ?? name.endIndex\n/// let firstName = name[..<firstSpace]\n/// print(firstName)\n/// // Prints "Marie"\n///\n/// Strings and their views share indices, so you can access the UTF-8 view of\n/// the `name` string using the same `firstSpace` index.\n///\n/// print(Array(name.utf8[..<firstSpace]))\n/// // Prints "[77, 97, 114, 105, 101]"\n///\n/// Note that an index into one view may not have an exact corresponding\n/// position in another view. For example, the `flag` string declared above\n/// comprises a single character, but is composed of eight code units when\n/// encoded as UTF-8. The following code creates constants for the first and\n/// second positions in the `flag.utf8` view. Accessing the `utf8` view with\n/// these indices yields the first and second code UTF-8 units.\n///\n/// let firstCodeUnit = flag.startIndex\n/// let secondCodeUnit = flag.utf8.index(after: firstCodeUnit)\n/// // flag.utf8[firstCodeUnit] == 240\n/// // flag.utf8[secondCodeUnit] == 159\n///\n/// When used to access the elements of the `flag` string itself, however, the\n/// `secondCodeUnit` index does not correspond to the position of a specific\n/// character. Instead of only accessing the specific UTF-8 code unit, that\n/// index is treated as the position of the character at the index's encoded\n/// offset. In the case of `secondCodeUnit`, that character is still the flag\n/// itself.\n///\n/// // flag[firstCodeUnit] == "🇵🇷"\n/// // flag[secondCodeUnit] == "🇵🇷"\n///\n/// If you need to validate that an index from one string's view corresponds\n/// with an exact position in another view, use the index's\n/// `samePosition(in:)` method or the `init(_:within:)` initializer.\n///\n/// if let exactIndex = secondCodeUnit.samePosition(in: flag) {\n/// print(flag[exactIndex])\n/// } else {\n/// print("No exact match for this position.")\n/// }\n/// // Prints "No exact match for this position."\n///\n/// Performance Optimizations\n/// =========================\n///\n/// Although strings in Swift have value semantics, strings use a copy-on-write\n/// strategy to store their data in a buffer. This buffer can then be shared\n/// by different copies of a string. A string's data is only copied lazily,\n/// upon mutation, when more than one string instance is using the same\n/// buffer. Therefore, the first in any sequence of mutating operations may\n/// cost O(*n*) time and space.\n///\n/// When a string's contiguous storage fills up, a new buffer must be allocated\n/// and data must be moved to the new storage. String buffers use an\n/// exponential growth strategy that makes appending to a string a constant\n/// time operation when averaged over many append operations.\n///\n/// Bridging Between String and NSString\n/// ====================================\n///\n/// Any `String` instance can be bridged to `NSString` using the type-cast\n/// operator (`as`), and any `String` instance that originates in Objective-C\n/// may use an `NSString` instance as its storage. Because any arbitrary\n/// subclass of `NSString` can become a `String` instance, there are no\n/// guarantees about representation or efficiency when a `String` instance is\n/// backed by `NSString` storage. Because `NSString` is immutable, it is just\n/// as though the storage was shared by a copy. The first in any sequence of\n/// mutating operations causes elements to be copied into unique, contiguous\n/// storage which may cost O(*n*) time and space, where *n* is the length of\n/// the string's encoded representation (or more, if the underlying `NSString`\n/// has unusual performance characteristics).\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], [Unicode scalar\n/// values][scalars], and [canonical equivalence][equivalence].\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/// [equivalence]: http://www.unicode.org/glossary/#canonical_equivalent\n@frozen\n@_eagerMove\npublic struct String {\n public // @SPI(Foundation)\n var _guts: _StringGuts\n\n @inlinable @inline(__always)\n internal init(_ _guts: _StringGuts) {\n self._guts = _guts\n _invariantCheck()\n }\n\n // This is intentionally a static function and not an initializer, because\n // an initializer would conflict with the Int-parsing initializer, when used\n // as function name, e.g.\n // [1, 2, 3].map(String.init)\n @_alwaysEmitIntoClient\n @_semantics("string.init_empty_with_capacity")\n @_semantics("inline_late")\n @inlinable\n internal static func _createEmpty(withInitialCapacity: Int) -> String {\n return String(_StringGuts(_initialCapacity: withInitialCapacity))\n }\n\n /// Creates an empty string.\n ///\n /// Using this initializer is equivalent to initializing a string with an\n /// empty string literal.\n ///\n /// let empty = ""\n /// let alsoEmpty = String()\n @inlinable @inline(__always)\n @_semantics("string.init_empty")\n public init() { self.init(_StringGuts()) }\n}\n\nextension String: Sendable { }\n\nextension String {\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 }\n #endif // INTERNAL_CHECKS_ENABLED\n\n public func _dump() {\n #if INTERNAL_CHECKS_ENABLED\n _guts._dump()\n #endif // INTERNAL_CHECKS_ENABLED\n }\n}\n\nextension String {\n /// Returns a boolean value indicating whether this string is identical to\n /// `other`.\n ///\n /// Two string values are identical if there is no way to distinguish between\n /// them.\n ///\n /// Comparing strings this way includes comparing (normally) hidden\n /// implementation details such as the memory location of any underlying\n /// string storage object. Therefore, identical strings are guaranteed to\n /// compare equal with `==`, but not all equal strings are considered\n /// identical.\n ///\n /// - Performance: O(1)\n @_alwaysEmitIntoClient\n public func _isIdentical(to other: Self) -> Bool {\n self._guts.rawBits == other._guts.rawBits\n }\n}\n\nextension String {\n // This force type-casts element to UInt8, since we cannot currently\n // communicate to the type checker that we proved this with our dynamic\n // check in String(decoding:as:).\n @_alwaysEmitIntoClient\n @inline(never) // slow-path\n internal static func _fromNonContiguousUnsafeBitcastUTF8Repairing<\n C: Collection\n >(_ input: C) -> (result: String, repairsMade: Bool) {\n _internalInvariant(C.Element.self == UInt8.self)\n return unsafe Array(input).withUnsafeBufferPointer {\n unsafe UnsafeRawBufferPointer($0).withMemoryRebound(to: UInt8.self) {\n unsafe String._fromUTF8Repairing($0)\n }\n }\n }\n\n\n /// Creates a string from the given Unicode code units in the specified\n /// encoding.\n ///\n /// - Parameters:\n /// - codeUnits: A collection of code units encoded in the encoding\n /// specified in `sourceEncoding`.\n /// - sourceEncoding: The encoding in which `codeUnits` should be\n /// interpreted.\n @inlinable\n @inline(__always) // Eliminate dynamic type check when possible\n public init<C: Collection, Encoding: Unicode.Encoding>(\n decoding codeUnits: C, as sourceEncoding: Encoding.Type\n ) where C.Iterator.Element == Encoding.CodeUnit {\n guard _fastPath(sourceEncoding == UTF8.self) else {\n self = String._fromCodeUnits(\n codeUnits, encoding: sourceEncoding, repair: true)!.0\n return\n }\n\n // Fast path for user-defined Collections and typed contiguous collections.\n //\n // Note: this comes first, as the optimizer nearly always has insight into\n // wCSIA, but cannot prove that a type does not have conformance to\n // _HasContiguousBytes.\n if let str = codeUnits.withContiguousStorageIfAvailable({\n (buffer: UnsafeBufferPointer<C.Element>) -> String in\n Builtin.onFastPath() // encourage SIL Optimizer to inline this closure :-(\n let rawBufPtr = UnsafeRawBufferPointer(buffer)\n return unsafe String._fromUTF8Repairing(\n UnsafeBufferPointer(\n start: rawBufPtr.baseAddress?.assumingMemoryBound(to: UInt8.self),\n count: rawBufPtr.count)).0\n }) {\n self = str\n return\n }\n\n #if !$Embedded\n // Fast path for untyped raw storage and known stdlib types\n if let contigBytes = codeUnits as? _HasContiguousBytes,\n contigBytes._providesContiguousBytesNoCopy\n {\n self = contigBytes.withUnsafeBytes { rawBufPtr in\n Builtin.onFastPath() // encourage SIL Optimizer to inline this closure\n return unsafe String._fromUTF8Repairing(\n UnsafeBufferPointer(\n start: rawBufPtr.baseAddress?.assumingMemoryBound(to: UInt8.self),\n count: rawBufPtr.count)).0\n }\n return\n }\n #endif\n\n self = String._fromNonContiguousUnsafeBitcastUTF8Repairing(codeUnits).0\n }\n\n /// Creates a new string by copying and validating the sequence of\n /// code units passed in, according to the specified encoding.\n ///\n /// This initializer does not try to repair ill-formed code unit sequences.\n /// If any are found, the result of the initializer is `nil`.\n ///\n /// The following example calls this initializer with the contents of two\n /// different arrays---first with a well-formed UTF-8 code unit sequence and\n /// then with an ill-formed UTF-16 code unit sequence.\n ///\n /// let validUTF8: [UInt8] = [67, 97, 0, 102, 195, 169]\n /// let valid = String(validating: validUTF8, as: UTF8.self)\n /// print(valid ?? "nil")\n /// // Prints "Café"\n ///\n /// let invalidUTF16: [UInt16] = [0x41, 0x42, 0xd801]\n /// let invalid = String(validating: invalidUTF16, as: UTF16.self)\n /// print(invalid ?? "nil")\n /// // Prints "nil"\n ///\n /// - Parameters:\n /// - codeUnits: A sequence of code units that encode a `String`\n /// - encoding: A conformer to `Unicode.Encoding` to be used\n /// to decode `codeUnits`.\n @inlinable\n @available(SwiftStdlib 6.0, *)\n public init?<Encoding: Unicode.Encoding>(\n validating codeUnits: some Sequence<Encoding.CodeUnit>,\n as encoding: Encoding.Type\n ) {\n let contiguousResult = codeUnits.withContiguousStorageIfAvailable {\n unsafe String._validate($0, as: Encoding.self)\n }\n if let validationResult = contiguousResult {\n guard let validatedString = validationResult else {\n return nil\n }\n self = validatedString\n return\n }\n\n // slow-path\n var transcoded: [UTF8.CodeUnit] = []\n transcoded.reserveCapacity(codeUnits.underestimatedCount)\n var isASCII = true\n let error = transcode(\n codeUnits.makeIterator(),\n from: Encoding.self,\n to: UTF8.self,\n stoppingOnError: true,\n into: {\n uint8 in\n transcoded.append(uint8)\n if isASCII && (uint8 & 0x80) == 0x80 { isASCII = false }\n }\n )\n if error { return nil }\n self = unsafe transcoded.withUnsafeBufferPointer{\n unsafe String._uncheckedFromUTF8($0, asciiPreScanResult: isASCII)\n }\n }\n\n /// Creates a new string by copying and validating the sequence of\n /// code units passed in, according to the specified encoding.\n ///\n /// This initializer does not try to repair ill-formed code unit sequences.\n /// If any are found, the result of the initializer is `nil`.\n ///\n /// The following example calls this initializer with the contents of two\n /// different arrays---first with a well-formed UTF-8 code unit sequence and\n /// then with an ill-formed ASCII code unit sequence.\n ///\n /// let validUTF8: [Int8] = [67, 97, 0, 102, -61, -87]\n /// let valid = String(validating: validUTF8, as: UTF8.self)\n /// print(valid ?? "nil")\n /// // Prints "Café"\n ///\n /// let invalidASCII: [Int8] = [67, 97, -5]\n /// let invalid = String(validating: invalidASCII, as: Unicode.ASCII.self)\n /// print(invalid ?? "nil")\n /// // Prints "nil"\n ///\n /// - Parameters:\n /// - codeUnits: A sequence of code units that encode a `String`\n /// - encoding: A conformer to `Unicode.Encoding` that can decode\n /// `codeUnits` as `UInt8`\n @inlinable\n @available(SwiftStdlib 6.0, *)\n public init?<Encoding>(\n validating codeUnits: some Sequence<Int8>,\n as encoding: Encoding.Type\n ) where Encoding: Unicode.Encoding, Encoding.CodeUnit == UInt8 {\n let contiguousResult = codeUnits.withContiguousStorageIfAvailable {\n unsafe $0.withMemoryRebound(to: UInt8.self) {\n unsafe String._validate($0, as: Encoding.self)\n }\n }\n if let validationResult = contiguousResult {\n guard let validatedString = validationResult else {\n return nil\n }\n self = validatedString\n return\n }\n\n // slow-path\n let uint8s = codeUnits.lazy.map(UInt8.init(bitPattern:))\n self.init(validating: uint8s, as: Encoding.self)\n }\n\n /// Creates a new string with the specified capacity in UTF-8 code units, and\n /// then calls the given closure with a buffer covering the string's\n /// uninitialized memory.\n ///\n /// The closure should return the number of initialized code units,\n /// or 0 if it couldn't initialize the buffer (for example if the\n /// requested capacity was too small).\n ///\n /// This method replaces ill-formed UTF-8 sequences with the Unicode\n /// replacement character (`"\u{FFFD}"`). This may require resizing\n /// the buffer beyond its original capacity.\n ///\n /// The following examples use this initializer with the contents of two\n /// different `UInt8` arrays---the first with a well-formed UTF-8 code unit\n /// sequence, and the second with an ill-formed sequence at the end.\n ///\n /// let validUTF8: [UInt8] = [0x43, 0x61, 0x66, 0xC3, 0xA9]\n /// let invalidUTF8: [UInt8] = [0x43, 0x61, 0x66, 0xC3]\n ///\n /// let cafe1 = String(unsafeUninitializedCapacity: validUTF8.count) {\n /// _ = $0.initialize(from: validUTF8)\n /// return validUTF8.count\n /// }\n /// // cafe1 == "Café"\n ///\n /// let cafe2 = String(unsafeUninitializedCapacity: invalidUTF8.count) {\n /// _ = $0.initialize(from: invalidUTF8)\n /// return invalidUTF8.count\n /// }\n /// // cafe2 == "Caf�"\n ///\n /// let empty = String(unsafeUninitializedCapacity: 16) { _ in\n /// // Can't initialize the buffer (e.g. the capacity is too small).\n /// return 0\n /// }\n /// // empty == ""\n ///\n /// - Parameters:\n /// - capacity: The number of UTF-8 code units worth of memory to allocate\n /// for the string (excluding the null terminator).\n /// - initializer: A closure that accepts a buffer covering uninitialized\n /// memory with room for `capacity` UTF-8 code units, initializes\n /// that memory, and returns the number of initialized elements.\n @inline(__always)\n @available(SwiftStdlib 5.3, *)\n public init(\n unsafeUninitializedCapacity capacity: Int,\n initializingUTF8With initializer: (\n _ buffer: UnsafeMutableBufferPointer<UInt8>\n ) throws -> Int\n ) rethrows {\n self = try unsafe String(\n _uninitializedCapacity: capacity,\n initializingUTF8With: initializer\n )\n }\n\n @inline(__always)\n internal init(\n _uninitializedCapacity capacity: Int,\n initializingUTF8With initializer: (\n _ buffer: UnsafeMutableBufferPointer<UInt8>\n ) throws -> Int\n ) rethrows {\n if _fastPath(capacity <= _SmallString.capacity) {\n let smol = try unsafe _SmallString(initializingUTF8With: {\n try unsafe initializer(.init(start: $0.baseAddress, count: capacity))\n })\n // Fast case where we fit in a _SmallString and don't need UTF8 validation\n if _fastPath(smol.isASCII) {\n self = String(_StringGuts(smol))\n } else {\n // We succeeded in making a _SmallString, but may need to repair UTF8\n self = smol.withUTF8 { unsafe String._fromUTF8Repairing($0).result }\n }\n return\n }\n\n self = try unsafe String._fromLargeUTF8Repairing(\n uninitializedCapacity: capacity,\n initializingWith: initializer)\n }\n\n /// Calls the given closure with a pointer to the contents of the string,\n /// represented as a null-terminated sequence of UTF-8 code units.\n ///\n /// The pointer passed as an argument to `body` is valid only during the\n /// execution of `withCString(_:)`. Do not store or return the pointer for\n /// later use.\n ///\n /// - Parameter body: A closure with a pointer parameter that points to a\n /// null-terminated sequence of UTF-8 code units. If `body` has a return\n /// value, that value is also used as the return value for the\n /// `withCString(_:)` method. The pointer argument is valid only for the\n /// duration of the method's execution.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @inlinable // fast-path: already C-string compatible\n public func withCString<Result>(\n _ body: (UnsafePointer<Int8>) throws -> Result\n ) rethrows -> Result {\n return try unsafe _guts.withCString(body)\n }\n\n /// Calls the given closure with a pointer to the contents of the string,\n /// represented as a null-terminated sequence of code units.\n ///\n /// The pointer passed as an argument to `body` is valid only during the\n /// execution of `withCString(encodedAs:_:)`. Do not store or return the\n /// pointer for later use.\n ///\n /// - Parameters:\n /// - body: A closure with a pointer parameter that points to a\n /// null-terminated sequence of code units. If `body` has a return\n /// value, that value is also used as the return value for the\n /// `withCString(encodedAs:_:)` method. The pointer argument is valid\n /// only for the duration of the method's execution.\n /// - targetEncoding: The encoding in which the code units should be\n /// interpreted.\n /// - Returns: The return value, if any, of the `body` closure parameter.\n @inlinable\n @inline(__always) // Eliminate dynamic type check when possible\n public func withCString<Result, TargetEncoding: Unicode.Encoding>(\n encodedAs targetEncoding: TargetEncoding.Type,\n _ body: (UnsafePointer<TargetEncoding.CodeUnit>) throws -> Result\n ) rethrows -> Result {\n if targetEncoding == UTF8.self {\n return try unsafe self.withCString {\n (cPtr: UnsafePointer<CChar>) -> Result in\n _internalInvariant(UInt8.self == TargetEncoding.CodeUnit.self)\n let ptr = unsafe UnsafeRawPointer(cPtr).assumingMemoryBound(\n to: TargetEncoding.CodeUnit.self)\n return try unsafe body(ptr)\n }\n }\n return try unsafe _slowWithCString(encodedAs: targetEncoding, body)\n }\n\n @usableFromInline @inline(never) // slow-path\n @_effects(releasenone)\n internal func _slowWithCString<Result, TargetEncoding: Unicode.Encoding>(\n encodedAs targetEncoding: TargetEncoding.Type,\n _ body: (UnsafePointer<TargetEncoding.CodeUnit>) throws -> Result\n ) rethrows -> Result {\n var copy = self\n return try copy.withUTF8 { utf8 in\n var arg = Array<TargetEncoding.CodeUnit>()\n arg.reserveCapacity(1 &+ self._guts.count / 4)\n let repaired = unsafe transcode(\n utf8.makeIterator(),\n from: UTF8.self,\n to: targetEncoding,\n stoppingOnError: false,\n into: { arg.append($0) })\n arg.append(TargetEncoding.CodeUnit(0))\n _internalInvariant(!repaired)\n return try unsafe body(arg)\n }\n }\n}\n\nextension String: _ExpressibleByBuiltinUnicodeScalarLiteral {\n @_effects(readonly)\n @inlinable @inline(__always)\n public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {\n self.init(Unicode.Scalar(_unchecked: UInt32(value)))\n }\n\n @inlinable @inline(__always)\n public init(_ scalar: Unicode.Scalar) {\n self = scalar.withUTF8CodeUnits { unsafe String._uncheckedFromUTF8($0) }\n }\n}\n\nextension String: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {\n @inlinable @inline(__always)\n @_effects(readonly) @_semantics("string.makeUTF8")\n public init(\n _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,\n utf8CodeUnitCount: Builtin.Word,\n isASCII: Builtin.Int1\n ) {\n self.init(\n _builtinStringLiteral: start,\n utf8CodeUnitCount: utf8CodeUnitCount,\n isASCII: isASCII)\n }\n}\n\nextension String: _ExpressibleByBuiltinStringLiteral {\n @inlinable @inline(__always)\n @_effects(readonly) @_semantics("string.makeUTF8")\n public init(\n _builtinStringLiteral start: Builtin.RawPointer,\n utf8CodeUnitCount: Builtin.Word,\n isASCII: Builtin.Int1\n ) {\n let bufPtr = unsafe UnsafeBufferPointer(\n start: UnsafeRawPointer(start).assumingMemoryBound(to: UInt8.self),\n count: Int(utf8CodeUnitCount))\n if let smol = unsafe _SmallString(bufPtr) {\n self = String(_StringGuts(smol))\n return\n }\n unsafe self.init(_StringGuts(bufPtr, isASCII: Bool(isASCII)))\n }\n}\n\nextension String: ExpressibleByStringLiteral {\n /// Creates an instance initialized to the given string value.\n ///\n /// Do not call this initializer directly. It is used by the compiler when you\n /// initialize a string using a string literal. For example:\n ///\n /// let nextStop = "Clark & Lake"\n ///\n /// This assignment to the `nextStop` constant calls this string literal\n /// initializer behind the scenes.\n @inlinable @inline(__always)\n public init(stringLiteral value: String) {\n self = value\n }\n}\n\nextension String: CustomDebugStringConvertible {\n /// A representation of the string that is suitable for debugging.\n public var debugDescription: String {\n func hasBreak(between left: String, and right: Unicode.Scalar) -> Bool {\n // Note: we know `left` ends with an ASCII character, so we only need to\n // look at its last scalar.\n var state = _GraphemeBreakingState()\n return state.shouldBreak(between: left.unicodeScalars.last!, and: right)\n }\n\n // Prevent unquoted scalars in the string from combining with the opening\n // `"` or the tail of the preceding quoted scalar.\n var result = "\""\n var wantBreak = true // true if next scalar must not combine with the last\n for us in self.unicodeScalars {\n if let escaped = us._escaped(asASCII: false) {\n result += escaped\n wantBreak = true\n } else if wantBreak && !hasBreak(between: result, and: us) {\n result += us.escaped(asASCII: true)\n wantBreak = true\n } else {\n result.unicodeScalars.append(us)\n wantBreak = false\n }\n }\n // Also prevent the last scalar from combining with the closing `"`.\n var suffix = "\"".unicodeScalars\n while !result.isEmpty {\n // Append first scalar of suffix, then check if it combines.\n result.unicodeScalars.append(suffix.first!)\n let i = result.index(before: result.endIndex)\n let j = result.unicodeScalars.index(before: result.endIndex)\n if i >= j {\n // All good; append the rest and we're done.\n result.unicodeScalars.append(contentsOf: suffix.dropFirst())\n break\n }\n // Cancel appending the scalar, then quote the last scalar in `result` and\n // prepend it to `suffix`.\n result.unicodeScalars.removeLast()\n let last = result.unicodeScalars.removeLast()\n suffix.insert(\n contentsOf: last.escaped(asASCII: true).unicodeScalars,\n at: suffix.startIndex)\n }\n return result\n }\n}\n\nextension String {\n @inlinable // Forward inlinability to append\n @_effects(readonly) @_semantics("string.concat")\n public static func + (lhs: String, rhs: String) -> String {\n var result = lhs\n result.append(rhs)\n return result\n }\n\n // String append\n @inlinable // Forward inlinability to append\n @_semantics("string.plusequals")\n public static func += (lhs: inout String, rhs: String) {\n lhs.append(rhs)\n }\n}\n\nextension Sequence where Element: StringProtocol {\n /// Returns a new string by concatenating the elements of the sequence,\n /// adding the given separator between each element.\n ///\n /// The following example shows how an array of strings can be joined to a\n /// single, comma-separated string:\n ///\n /// let cast = ["Vivien", "Marlon", "Kim", "Karl"]\n /// let list = cast.joined(separator: ", ")\n /// print(list)\n /// // Prints "Vivien, Marlon, Kim, Karl"\n ///\n /// - Parameter separator: A string to insert between each of the elements\n /// in this sequence. The default separator is an empty string.\n /// - Returns: A single, concatenated string.\n @_specialize(where Self == Array<Substring>)\n @_specialize(where Self == Array<String>)\n public func joined(separator: String = "") -> String {\n return _joined(separator: separator)\n }\n\n @inline(__always) // Pick up @_specialize and devirtualize from two callers\n internal func _joined(separator: String) -> String {\n // A likely-under-estimate, but lets us skip some of the growth curve\n // for large Sequences.\n let underestimatedCap =\n (1 &+ separator._guts.count) &* self.underestimatedCount\n var result = ""\n result.reserveCapacity(underestimatedCap)\n if separator.isEmpty {\n for x in self {\n result.append(x._ephemeralString)\n }\n return result\n }\n\n var iter = makeIterator()\n if let first = iter.next() {\n result.append(first._ephemeralString)\n while let next = iter.next() {\n result.append(separator)\n result.append(next._ephemeralString)\n }\n }\n return result\n }\n}\n\n// This overload is necessary because String now conforms to\n// BidirectionalCollection, and there are other `joined` overloads that are\n// considered more specific. See Flatten.swift.gyb.\nextension BidirectionalCollection where Element == String {\n /// Returns a new string by concatenating the elements of the sequence,\n /// adding the given separator between each element.\n ///\n /// The following example shows how an array of strings can be joined to a\n /// single, comma-separated string:\n ///\n /// let cast = ["Vivien", "Marlon", "Kim", "Karl"]\n /// let list = cast.joined(separator: ", ")\n /// print(list)\n /// // Prints "Vivien, Marlon, Kim, Karl"\n ///\n /// - Parameter separator: A string to insert between each of the elements\n /// in this sequence. The default separator is an empty string.\n /// - Returns: A single, concatenated string.\n @_specialize(where Self == Array<String>)\n public func joined(separator: String = "") -> String {\n return _joined(separator: separator)\n }\n}\n\n// Unicode algorithms\nextension String {\n @inline(__always)\n internal func _uppercaseASCII(_ x: UInt8) -> UInt8 {\n /// A "table" for which ASCII characters need to be upper cased.\n /// To determine which bit corresponds to which ASCII character, subtract 1\n /// from the ASCII value of that character and divide by 2. The bit is set if\n /// that character is a lower case character; otherwise, it's not set.\n let _lowercaseTable: UInt64 =\n 0b0001_1111_1111_1111_0000_0000_0000_0000 &<< 32\n\n // Lookup if it should be shifted in our ascii table, then we subtract 0x20 if\n // it should, 0x0 if not.\n // This code is equivalent to:\n // This code is equivalent to:\n // switch sourcex {\n // case let x where (x >= 0x41 && x <= 0x5a):\n // return x &- 0x20\n // case let x:\n // return x\n // }\n let isLower = _lowercaseTable &>> UInt64(((x &- 1) & 0b0111_1111) &>> 1)\n let toSubtract = (isLower & 0x1) &<< 5\n return x &- UInt8(truncatingIfNeeded: toSubtract)\n }\n\n @inline(__always)\n internal func _lowercaseASCII(_ x: UInt8) -> UInt8 {\n /// A "table" for which ASCII characters need to be lower cased.\n /// To determine which bit corresponds to which ASCII character, subtract 1\n /// from the ASCII value of that character and divide by 2. The bit is set if\n /// that character is a upper case character; otherwise, it's not set.\n let _uppercaseTable: UInt64 =\n 0b0000_0000_0000_0000_0001_1111_1111_1111 &<< 32\n\n // Lookup if it should be shifted in our ascii table, then we add 0x20 if\n // it should, 0x0 if not.\n // This code is equivalent to:\n // This code is equivalent to:\n // switch sourcex {\n // case let x where (x >= 0x41 && x <= 0x5a):\n // return x &- 0x20\n // case let x:\n // return x\n // }\n let isUpper = _uppercaseTable &>> UInt64(((x &- 1) & 0b0111_1111) &>> 1)\n let toAdd = (isUpper & 0x1) &<< 5\n return x &+ UInt8(truncatingIfNeeded: toAdd)\n }\n\n\n /// Returns a lowercase version of the string.\n ///\n /// Here's an example of transforming a string to all lowercase letters.\n ///\n /// let cafe = "BBQ Café 🍵"\n /// print(cafe.lowercased())\n /// // Prints "bbq café 🍵"\n ///\n /// - Returns: A lowercase copy of the string.\n ///\n /// - Complexity: O(*n*)\n @_effects(releasenone)\n public func lowercased() -> String {\n if _fastPath(_guts.isFastASCII) {\n return unsafe _guts.withFastUTF8 { utf8 in\n return unsafe String(_uninitializedCapacity: utf8.count) { buffer in\n for i in 0 ..< utf8.count {\n unsafe buffer[i] = unsafe _lowercaseASCII(utf8[i])\n }\n return utf8.count\n }\n }\n }\n\n var result = ""\n result.reserveCapacity(utf8.count)\n\n for scalar in unicodeScalars {\n result += scalar.properties.lowercaseMapping\n }\n\n return result\n }\n\n /// Returns an uppercase version of the string.\n ///\n /// The following example transforms a string to uppercase letters:\n ///\n /// let cafe = "Café 🍵"\n /// print(cafe.uppercased())\n /// // Prints "CAFÉ 🍵"\n ///\n /// - Returns: An uppercase copy of the string.\n ///\n /// - Complexity: O(*n*)\n @_effects(releasenone)\n public func uppercased() -> String {\n if _fastPath(_guts.isFastASCII) {\n return unsafe _guts.withFastUTF8 { utf8 in\n return unsafe String(_uninitializedCapacity: utf8.count) { buffer in\n for i in 0 ..< utf8.count {\n unsafe buffer[i] = unsafe _uppercaseASCII(utf8[i])\n }\n return utf8.count\n }\n }\n }\n\n var result = ""\n result.reserveCapacity(utf8.count)\n\n for scalar in unicodeScalars {\n result += scalar.properties.uppercaseMapping\n }\n\n return result\n }\n\n /// Creates an instance from the description of a given\n /// `LosslessStringConvertible` instance.\n @inlinable @inline(__always)\n public init<T: LosslessStringConvertible>(_ value: T) {\n self = value.description\n }\n}\n\nextension String: CustomStringConvertible {\n /// The value of this string.\n ///\n /// Using this property directly is discouraged. Instead, use simple\n /// assignment to create a new constant or variable equal to this string.\n @inlinable\n public var description: String { return self }\n}\n\nextension String {\n public // @testable\n var _nfcCodeUnits: [UInt8] {\n var codeUnits = [UInt8]()\n _withNFCCodeUnits {\n codeUnits.append($0)\n }\n return codeUnits\n }\n\n public // @testable\n func _withNFCCodeUnits(_ f: (UInt8) throws -> Void) rethrows {\n try _gutsSlice._withNFCCodeUnits(f)\n }\n}\n\n\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_String.swift
cpp_apple_swift_stdlib_public_core_String.swift
Swift
41,801
0.95
0.085202
0.586957
awesome-app
258
2024-04-02T08:31:06.274332
MIT
false
b35235ff2d4180fceb42b2a4b3901c3a
//===----------------------------------------------------------------------===//\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// @opaque\ninternal final class _StringBreadcrumbs {\n /// The distance between successive breadcrumbs, measured in UTF-16 code\n /// units.\n internal static var breadcrumbStride: Int { 64 }\n\n internal var utf16Length: Int\n\n // TODO: does this need to be a pair?.... Can we be smaller than Int?\n internal var crumbs: [String.Index]\n\n // TODO: Does this need to be inout, unique, or how will we be enforcing\n // atomicity?\n internal init(_ str: String) {\n let stride = _StringBreadcrumbs.breadcrumbStride\n\n self.crumbs = []\n\n if str.isEmpty {\n self.utf16Length = 0\n return\n }\n\n self.crumbs.reserveCapacity(\n (str._guts.count / 3) / stride)\n\n // TODO(String performance): More efficient implementation of initial scan.\n // We'll also want to benchmark this initial scan in order to track changes.\n\n let utf16 = str.utf16\n var i = 0\n var curIdx = utf16.startIndex\n while curIdx != utf16.endIndex {\n if i % stride == 0 { //i.isMultiple(of: stride) {\n self.crumbs.append(curIdx)\n }\n i = i &+ 1\n curIdx = utf16.index(after: curIdx)\n }\n\n // Corner case: index(_:offsetBy:) can produce the endIndex\n if i % stride == 0 {\n self.crumbs.append(utf16.endIndex)\n }\n\n self.utf16Length = i\n _internalInvariant(self.crumbs.count == 1 + (self.utf16Length / stride))\n\n _invariantCheck(for: str)\n }\n}\n\nextension _StringBreadcrumbs {\n internal var stride: Int {\n @inline(__always) get { return _StringBreadcrumbs.breadcrumbStride }\n }\n\n // Fetch the lower-bound index corresponding to the given offset, returning\n // the index and the remaining offset to adjust\n internal func getBreadcrumb(\n forOffset offset: Int\n ) -> (lowerBound: String.Index, remaining: Int) {\n return (crumbs[offset / stride], offset % stride)\n }\n\n // Fetch the lower-bound offset corresponding to the given index, returning\n // the lower-bound and its offset\n internal func getBreadcrumb(\n forIndex idx: String.Index\n ) -> (lowerBound: String.Index, offset: Int) {\n var lowerBound = idx._encodedOffset / 3 / stride\n var upperBound = Swift.min(1 + (idx._encodedOffset / stride), crumbs.count)\n _internalInvariant(crumbs[lowerBound] <= idx)\n _internalInvariant(upperBound == crumbs.count || crumbs[upperBound] >= idx)\n\n while (upperBound &- lowerBound) > 1 {\n let mid = lowerBound + ((upperBound &- lowerBound) / 2)\n if crumbs[mid] <= idx { lowerBound = mid } else { upperBound = mid }\n }\n\n let crumb = crumbs[lowerBound]\n _internalInvariant(crumb <= idx)\n _internalInvariant(lowerBound == crumbs.count-1 || crumbs[lowerBound+1] > idx)\n\n return (crumb, lowerBound &* stride)\n }\n\n #if !INTERNAL_CHECKS_ENABLED\n @nonobjc @inline(__always) internal func _invariantCheck(for str: String) {}\n #else\n @nonobjc @inline(never) @_effects(releasenone)\n internal func _invariantCheck(for str: String) {\n _internalInvariant(self.utf16Length == str.utf16._distance(\n from: str.startIndex, to: str.endIndex),\n "Stale breadcrumbs")\n }\n #endif // INTERNAL_CHECKS_ENABLED\n}\n\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringBreadcrumbs.swift
cpp_apple_swift_stdlib_public_core_StringBreadcrumbs.swift
Swift
3,624
0.95
0.116071
0.296703
react-lib
343
2024-02-16T04:17:29.438182
Apache-2.0
false
b6694f1750489a757f4d9fb884478eff
//===----------------------------------------------------------------------===//\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/// Effectively an untyped NSString that doesn't require foundation.\n@usableFromInline\ninternal typealias _CocoaString = AnyObject\n\n#if _runtime(_ObjC)\n\n// Swift's String bridges NSString via this protocol and these\n// variables, allowing the core stdlib to remain decoupled from\n// Foundation.\n\n@objc private protocol _StringSelectorHolder : _NSCopying {\n\n @objc var length: Int { get }\n\n @objc var hash: UInt { get }\n\n @objc(characterAtIndex:)\n func character(at offset: Int) -> UInt16\n\n @objc(getCharacters:range:)\n func getCharacters(\n _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange\n )\n\n @objc(_fastCStringContents:)\n func _fastCStringContents(\n _ requiresNulTermination: Int8\n ) -> UnsafePointer<CChar>?\n\n @objc(_fastCharacterContents)\n func _fastCharacterContents() -> UnsafePointer<UInt16>?\n\n @objc(getBytes:maxLength:usedLength:encoding:options:range:remainingRange:)\n func getBytes(_ buffer: UnsafeMutableRawPointer?,\n maxLength maxBufferCount: Int,\n usedLength usedBufferCount: UnsafeMutablePointer<Int>?,\n encoding: UInt,\n options: UInt,\n range: _SwiftNSRange,\n remaining leftover: UnsafeMutablePointer<_SwiftNSRange>?) -> Int8\n\n @objc(compare:options:range:locale:)\n func compare(_ string: _CocoaString,\n options: UInt,\n range: _SwiftNSRange,\n locale: AnyObject?) -> Int\n\n @objc(newTaggedNSStringWithASCIIBytes_:length_:)\n func createTaggedString(bytes: UnsafePointer<UInt8>,\n count: Int) -> AnyObject?\n}\n\n/*\n Passing a _CocoaString through _objc() lets you call ObjC methods that the\n compiler doesn't know about, via the protocol above. In order to get good\n performance, you need a double indirection like this:\n\n func a -> _objc -> func a'\n\n because any refcounting @_effects on 'a' will be lost when _objc breaks ARC's\n knowledge that the _CocoaString and _StringSelectorHolder are the same object.\n */\n@inline(__always)\nprivate func _objc(_ str: _CocoaString) -> _StringSelectorHolder {\n return unsafe unsafeBitCast(str, to: _StringSelectorHolder.self)\n}\n\n@_effects(releasenone)\nprivate func _copyNSString(_ str: _StringSelectorHolder) -> _CocoaString {\n return unsafe str.copy(with: nil)\n}\n\n@usableFromInline // @testable\n@_effects(releasenone)\ninternal func _stdlib_binary_CFStringCreateCopy(\n _ source: _CocoaString\n) -> _CocoaString {\n return _copyNSString(_objc(source))\n}\n\n@_effects(readonly)\nprivate func _NSStringLen(_ str: _StringSelectorHolder) -> Int {\n return str.length\n}\n\n@usableFromInline // @testable\n@_effects(readonly)\ninternal func _stdlib_binary_CFStringGetLength(\n _ source: _CocoaString\n) -> Int {\n return _NSStringLen(_objc(source))\n}\n\n@_effects(readonly)\ninternal func _isNSString(_ str:AnyObject) -> Bool {\n return _swift_stdlib_isNSString(str) != 0\n}\n\n@_effects(readonly)\nprivate func _NSStringCharactersPtr(_ str: _StringSelectorHolder) -> UnsafeMutablePointer<UTF16.CodeUnit>? {\n return unsafe UnsafeMutablePointer(mutating: str._fastCharacterContents())\n}\n\nprivate func _stdlib_binary_createIndirectTaggedPointerNSString(\n ptr: UnsafePointer<UInt8>,\n count: Int\n) -> UnsafeRawPointer? {\n return unsafe _swift_stdlib_CreateIndirectTaggedPointerString(ptr, count);\n}\n\n@usableFromInline // @testable\n@_effects(readonly)\ninternal func _stdlib_binary_CFStringGetCharactersPtr(\n _ source: _CocoaString\n) -> UnsafeMutablePointer<UTF16.CodeUnit>? {\n return unsafe _NSStringCharactersPtr(_objc(source))\n}\n\n@_effects(releasenone)\nprivate func _NSStringGetCharacters(\n from source: _StringSelectorHolder,\n range: Range<Int>,\n into destination: UnsafeMutablePointer<UTF16.CodeUnit>\n) {\n unsafe source.getCharacters(destination, range: _SwiftNSRange(\n location: range.startIndex,\n length: range.count)\n )\n}\n\n/// Copies a slice of a _CocoaString into contiguous storage of sufficient\n/// capacity.\n@_effects(releasenone)\ninternal func _cocoaStringCopyCharacters(\n from source: _CocoaString,\n range: Range<Int>,\n into destination: UnsafeMutablePointer<UTF16.CodeUnit>\n) {\n unsafe _NSStringGetCharacters(from: _objc(source), range: range, into: destination)\n}\n\n@_effects(readonly)\nprivate func _NSStringGetCharacter(\n _ target: _StringSelectorHolder, _ position: Int\n) -> UTF16.CodeUnit {\n return target.character(at: position)\n}\n\n@_effects(readonly)\ninternal func _cocoaStringSubscript(\n _ target: _CocoaString, _ position: Int\n) -> UTF16.CodeUnit {\n return _NSStringGetCharacter(_objc(target), position)\n}\n\n@_effects(releasenone)\nprivate func _NSStringCopyBytes(\n _ o: _StringSelectorHolder,\n encoding: UInt,\n into bufPtr: UnsafeMutableRawBufferPointer\n) -> Int? {\n let ptr = unsafe bufPtr.baseAddress._unsafelyUnwrappedUnchecked\n let len = o.length\n var remainingRange = _SwiftNSRange(location: 0, length: 0)\n var usedLen = 0\n let success = unsafe 0 != o.getBytes(\n ptr,\n maxLength: bufPtr.count,\n usedLength: &usedLen,\n encoding: encoding,\n options: 0,\n range: _SwiftNSRange(location: 0, length: len),\n remaining: &remainingRange\n )\n if success && remainingRange.length == 0 {\n return usedLen\n }\n return nil\n}\n\n@_effects(releasenone)\ninternal func _cocoaStringCopyUTF8(\n _ target: _CocoaString,\n into bufPtr: UnsafeMutableRawBufferPointer\n) -> Int? {\n return unsafe _NSStringCopyBytes(\n _objc(target),\n encoding: _cocoaUTF8Encoding,\n into: bufPtr\n )\n}\n\n@_effects(releasenone)\ninternal func _cocoaStringCopyASCII(\n _ target: _CocoaString,\n into bufPtr: UnsafeMutableRawBufferPointer\n) -> Int? {\n return unsafe _NSStringCopyBytes(\n _objc(target),\n encoding: _cocoaASCIIEncoding,\n into: bufPtr\n )\n}\n\n@_effects(readonly)\nprivate func _NSStringUTF8Count(\n _ o: _StringSelectorHolder,\n range: Range<Int>\n) -> Int? {\n var remainingRange = _SwiftNSRange(location: 0, length: 0)\n var usedLen = 0\n let success = unsafe 0 != o.getBytes(\n UnsafeMutableRawPointer(Builtin.inttoptr_Word(0._builtinWordValue)),\n maxLength: 0,\n usedLength: &usedLen,\n encoding: _cocoaUTF8Encoding,\n options: 0,\n range: _SwiftNSRange(location: range.startIndex, length: range.count),\n remaining: &remainingRange\n )\n if success && remainingRange.length == 0 {\n return usedLen\n }\n return nil\n}\n\n@_effects(readonly)\ninternal func _cocoaStringUTF8Count(\n _ target: _CocoaString,\n range: Range<Int>\n) -> Int? {\n if range.isEmpty { return 0 }\n return _NSStringUTF8Count(_objc(target), range: range)\n}\n\n@_effects(readonly)\nprivate func _NSStringCompare(\n _ o: _StringSelectorHolder, _ other: _CocoaString\n) -> Int {\n let range = _SwiftNSRange(location: 0, length: o.length)\n let options = UInt(2) /* NSLiteralSearch*/\n return o.compare(other, options: options, range: range, locale: nil)\n}\n\n@_effects(readonly)\ninternal func _cocoaStringCompare(\n _ string: _CocoaString, _ other: _CocoaString\n) -> Int {\n return _NSStringCompare(_objc(string), other)\n}\n\n@_effects(readonly)\ninternal func _cocoaHashString(\n _ string: _CocoaString\n) -> UInt {\n return _swift_stdlib_CFStringHashNSString(string)\n}\n\n@_effects(readonly)\ninternal func _cocoaHashASCIIBytes(\n _ bytes: UnsafePointer<UInt8>, length: Int\n) -> UInt {\n return unsafe _swift_stdlib_CFStringHashCString(bytes, length)\n}\n\n// These "trampolines" are effectively objc_msgSend_super.\n// They bypass our implementations to use NSString's.\n\n@_effects(readonly)\ninternal func _cocoaCStringUsingEncodingTrampoline(\n _ string: _CocoaString, _ encoding: UInt\n) -> UnsafePointer<UInt8>? {\n return unsafe _swift_stdlib_NSStringCStringUsingEncodingTrampoline(string, encoding)\n}\n\n@_effects(releasenone)\ninternal func _cocoaGetCStringTrampoline(\n _ string: _CocoaString,\n _ buffer: UnsafeMutablePointer<UInt8>,\n _ maxLength: Int,\n _ encoding: UInt\n) -> Int8 {\n return unsafe Int8(_swift_stdlib_NSStringGetCStringTrampoline(\n string, buffer, maxLength, encoding))\n}\n\n//\n// Conversion from NSString to Swift's native representation.\n//\n\nprivate var kCFStringEncodingASCII: _swift_shims_CFStringEncoding {\n @inline(__always) get { return 0x0600 }\n}\n\nprivate var kCFStringEncodingUTF8: _swift_shims_CFStringEncoding {\n @inline(__always) get { return 0x8000100 }\n}\n\ninternal enum _KnownCocoaString {\n case storage\n case shared\n case cocoa\n#if _pointerBitWidth(_64)\n case tagged\n#endif\n\n @inline(__always)\n init(_ str: _CocoaString) {\n\n#if _pointerBitWidth(_64)\n if _isObjCTaggedPointer(str) {\n self = .tagged\n return\n }\n#endif\n\n switch unsafe unsafeBitCast(_swift_classOfObjCHeapObject(str), to: UInt.self) {\n case unsafe unsafeBitCast(__StringStorage.self, to: UInt.self):\n self = .storage\n case unsafe unsafeBitCast(__SharedStringStorage.self, to: UInt.self):\n self = .shared\n default:\n self = .cocoa\n }\n }\n}\n\n#if _pointerBitWidth(_64)\n// Resiliently write a tagged _CocoaString's contents into a buffer.\n// The Foundation overlay takes care of bridging tagged pointer strings before\n// they reach us, but this may still be called by older code, or by strings\n// entering our domain via the arguments to -isEqual:, etc...\n@_effects(releasenone) // @opaque\ninternal func _bridgeTagged(\n _ cocoa: _CocoaString,\n intoUTF8 bufPtr: UnsafeMutableRawBufferPointer\n) -> Int? {\n _internalInvariant(_isObjCTaggedPointer(cocoa))\n return unsafe _cocoaStringCopyUTF8(cocoa, into: bufPtr)\n}\n\n@_effects(releasenone) // @opaque\ninternal func _bridgeTaggedASCII(\n _ cocoa: _CocoaString,\n intoUTF8 bufPtr: UnsafeMutableRawBufferPointer\n) -> Int? {\n _internalInvariant(_isObjCTaggedPointer(cocoa))\n return unsafe _cocoaStringCopyASCII(cocoa, into: bufPtr)\n}\n#endif\n\n@_effects(readonly)\nprivate func _NSStringASCIIPointer(_ str: _StringSelectorHolder) -> UnsafePointer<UInt8>? {\n //TODO(String bridging): Unconditionally asking for nul-terminated contents is\n // overly conservative and hurts perf with some NSStrings\n return unsafe str._fastCStringContents(1)?._asUInt8\n}\n\n@_effects(readonly)\nprivate func _NSStringUTF8Pointer(_ str: _StringSelectorHolder) -> UnsafePointer<UInt8>? {\n //We don't have a way to ask for UTF8 here currently\n return unsafe _NSStringASCIIPointer(str)\n}\n\n@_effects(readonly)\ninternal func _getNSCFConstantStringContentsPointer(\n _ cocoa: AnyObject\n) -> UnsafePointer<UInt8> {\n return unsafe unsafeBitCast(\n cocoa,\n to: UnsafePointer<_swift_shims_builtin_CFString>.self\n ).pointee.str\n}\n\n@_effects(readonly) // @opaque\nprivate func _withCocoaASCIIPointer<R>(\n _ str: _CocoaString,\n requireStableAddress: Bool,\n work: (UnsafePointer<UInt8>) -> R?\n) -> R? {\n #if _pointerBitWidth(_64)\n if _isObjCTaggedPointer(str) {\n if requireStableAddress {\n return nil // tagged pointer strings don't support _fastCStringContents\n }\n if let smol = _SmallString(taggedASCIICocoa: str) {\n return unsafe _StringGuts(smol).withFastUTF8 {\n unsafe work($0.baseAddress._unsafelyUnwrappedUnchecked)\n }\n }\n }\n #endif\n defer { _fixLifetime(str) }\n if let ptr = unsafe _NSStringASCIIPointer(_objc(str)) {\n return unsafe work(ptr)\n }\n return nil\n}\n\n@_effects(readonly) // @opaque\nprivate func _withCocoaUTF8Pointer<R>(\n _ str: _CocoaString,\n requireStableAddress: Bool,\n work: (UnsafePointer<UInt8>) -> R?\n) -> R? {\n #if _pointerBitWidth(_64)\n if _isObjCTaggedPointer(str) {\n if requireStableAddress {\n return nil // tagged pointer strings don't support _fastCStringContents\n }\n if let smol = _SmallString(taggedCocoa: str) {\n return unsafe _StringGuts(smol).withFastUTF8 {\n unsafe work($0.baseAddress._unsafelyUnwrappedUnchecked)\n }\n }\n }\n #endif\n defer { _fixLifetime(str) }\n if let ptr = unsafe _NSStringUTF8Pointer(_objc(str)) {\n return unsafe work(ptr)\n }\n return nil\n}\n\n@_effects(readonly) // @opaque\ninternal func withCocoaASCIIPointer<R>(\n _ str: _CocoaString,\n work: (UnsafePointer<UInt8>) -> R?\n) -> R? {\n return unsafe _withCocoaASCIIPointer(str, requireStableAddress: false, work: work)\n}\n\n@_effects(readonly) // @opaque\ninternal func withCocoaUTF8Pointer<R>(\n _ str: _CocoaString,\n work: (UnsafePointer<UInt8>) -> R?\n) -> R? {\n return unsafe _withCocoaUTF8Pointer(str, requireStableAddress: false, work: work)\n}\n\n@_effects(readonly)\ninternal func stableCocoaASCIIPointer(_ str: _CocoaString)\n -> UnsafePointer<UInt8>? {\n return unsafe _withCocoaASCIIPointer(str, requireStableAddress: true, work: { unsafe $0 })\n}\n\n@_effects(readonly)\ninternal func stableCocoaUTF8Pointer(_ str: _CocoaString)\n -> UnsafePointer<UInt8>? {\n return unsafe _withCocoaUTF8Pointer(str, requireStableAddress: true, work: { unsafe $0 })\n}\n\n@unsafe\nprivate enum CocoaStringPointer {\n case ascii(UnsafePointer<UInt8>)\n case utf8(UnsafePointer<UInt8>)\n case utf16(UnsafePointer<UInt16>)\n case none\n}\n\n@_effects(readonly)\nprivate func _getCocoaStringPointer(\n _ cfImmutableValue: _CocoaString\n) -> CocoaStringPointer {\n if let ascii = unsafe stableCocoaASCIIPointer(cfImmutableValue) {\n return unsafe .ascii(ascii)\n }\n // We could ask for UTF16 here via _stdlib_binary_CFStringGetCharactersPtr,\n // but we currently have no use for it\n return unsafe .none\n}\n\n#if !$Embedded\n@usableFromInline\n@_effects(releasenone) // @opaque\ninternal func _bridgeCocoaString(_ cocoaString: _CocoaString) -> _StringGuts {\n switch _KnownCocoaString(cocoaString) {\n case .storage:\n return unsafe _unsafeUncheckedDowncast(\n cocoaString, to: __StringStorage.self).asString._guts\n case .shared:\n return unsafe _unsafeUncheckedDowncast(\n cocoaString, to: __SharedStringStorage.self).asString._guts\n#if _pointerBitWidth(_64)\n case .tagged:\n // Foundation should be taking care of tagged pointer strings before they\n // reach here, so the only ones reaching this point should be back deployed,\n // which will never have tagged pointer strings that aren't small, hence\n // the force unwrap here.\n return _StringGuts(_SmallString(taggedCocoa: cocoaString)!)\n#endif\n case .cocoa:\n // "Copy" it into a value to be sure nobody will modify behind\n // our backs. In practice, when value is already immutable, this\n // just does a retain.\n //\n // TODO: Only in certain circumstances should we emit this call:\n // 1) If it's immutable, just retain it.\n // 2) If it's mutable with no associated information, then a copy must\n // happen; might as well eagerly bridge it in.\n // 3) If it's mutable with associated information, must make the call\n let immutableCopy\n = _stdlib_binary_CFStringCreateCopy(cocoaString)\n\n#if _pointerBitWidth(_64)\n if _isObjCTaggedPointer(immutableCopy) {\n // Copying a tagged pointer can produce a tagged pointer, but only if it's\n // small enough to definitely fit in a _SmallString\n return unsafe _StringGuts(\n _SmallString(taggedCocoa: immutableCopy).unsafelyUnwrapped\n )\n }\n#endif\n\n let (fastUTF8, isASCII): (Bool, Bool)\n switch unsafe _getCocoaStringPointer(immutableCopy) {\n case .ascii(_): (fastUTF8, isASCII) = (true, true)\n case .utf8(_): (fastUTF8, isASCII) = (true, false)\n default: (fastUTF8, isASCII) = (false, false)\n }\n let length = _stdlib_binary_CFStringGetLength(immutableCopy)\n\n return _StringGuts(\n cocoa: immutableCopy,\n providesFastUTF8: fastUTF8,\n isASCII: isASCII,\n length: length)\n }\n}\n\nextension String {\n @available(SwiftStdlib 6.1, *)\n @_spi(Foundation)\n public init<Encoding: Unicode.Encoding>(\n _immortalCocoaString: AnyObject,\n count: Int,\n encoding: Encoding.Type\n ) {\n if encoding == Unicode.ASCII.self || encoding == Unicode.UTF8.self {\n self._guts = _StringGuts(\n constantCocoa: _immortalCocoaString,\n providesFastUTF8: true,\n isASCII: encoding == Unicode.ASCII.self,\n length: count)\n } else {\n _precondition(encoding == Unicode.UTF16.self)\n // Only need the very last bit of _bridgeCocoaString here,\n // since we know the fast paths don't apply\n self._guts = _StringGuts(\n cocoa: _immortalCocoaString,\n providesFastUTF8: false,\n isASCII: false,\n length: count)\n }\n }\n \n @_spi(Foundation)\n public init(_cocoaString: AnyObject) {\n self._guts = _bridgeCocoaString(_cocoaString)\n }\n}\n#endif\n\n@_effects(releasenone)\nprivate func _createNSString(\n _ receiver: _StringSelectorHolder,\n _ ptr: UnsafePointer<UInt8>,\n _ count: Int,\n _ encoding: UInt32\n) -> AnyObject? {\n return unsafe receiver.createTaggedString(bytes: ptr, count: count)\n}\n\n@_effects(releasenone)\nprivate func _createCFString(\n _ ptr: UnsafePointer<UInt8>,\n _ count: Int,\n _ encoding: UInt32\n) -> AnyObject? {\n return unsafe _createNSString(\n unsafeBitCast(__StringStorage.self as AnyClass, to: _StringSelectorHolder.self),\n ptr,\n count,\n encoding\n )\n}\n\n#if !$Embedded\nextension String {\n @_effects(releasenone)\n public // SPI(Foundation)\n func _bridgeToObjectiveCImpl() -> AnyObject {\n\n _connectOrphanedFoundationSubclassesIfNeeded()\n\n // Smol ASCII a) may bridge to tagged pointers, b) can't contain a BOM\n if _guts.isSmallASCII {\n let maybeTagged = _guts.asSmall.withUTF8 { bufPtr in\n return unsafe _createCFString(\n bufPtr.baseAddress._unsafelyUnwrappedUnchecked,\n bufPtr.count,\n kCFStringEncodingUTF8\n )\n }\n if let tagged = maybeTagged { return tagged }\n }\n\n if _guts.isSmall {\n // We can't form a tagged pointer String, so grow to a non-small String,\n // and bridge that instead. Also avoids CF deleting any BOM that may be\n // present\n var copy = self\n // TODO: small capacity minimum is lifted, just need to make native\n copy._guts.grow(_SmallString.capacity + 1)\n _internalInvariant(!copy._guts.isSmall)\n return copy._bridgeToObjectiveCImpl()\n }\n if _guts._object.isImmortal && !_guts._object.largeFastIsConstantCocoa {\n if _guts.isASCII && _guts._object.isFastZeroTerminated {\n let ptr = unsafe _guts._object.fastUTF8.baseAddress!\n let count = _guts.count\n if let indirect = unsafe _stdlib_binary_createIndirectTaggedPointerNSString(\n ptr: ptr, count: count\n ) {\n return unsafe unsafeBitCast(indirect, to: AnyObject.self)\n }\n }\n let gutsCountAndFlags = _guts._object._countAndFlags\n return unsafe __SharedStringStorage(\n immortal: _guts._object.fastUTF8.baseAddress!,\n countAndFlags: _StringObject.CountAndFlags(\n sharedCount: _guts.count, isASCII: gutsCountAndFlags.isASCII))\n }\n\n _internalInvariant(_guts._object.hasObjCBridgeableObject,\n "Unknown non-bridgeable object case")\n return _guts._object.objCBridgeableObject\n }\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("_SwiftCreateBridgedString")\n@usableFromInline\ninternal func _SwiftCreateBridgedString_DoNotCall(\n bytes: UnsafePointer<UInt8>,\n length: Int,\n encoding: _swift_shims_CFStringEncoding\n) -> Unmanaged<AnyObject> {\n let bufPtr = unsafe UnsafeBufferPointer(start: bytes, count: length)\n let str:String\n switch encoding {\n case kCFStringEncodingUTF8:\n str = unsafe String(decoding: bufPtr, as: Unicode.UTF8.self)\n case kCFStringEncodingASCII:\n str = unsafe String(decoding: bufPtr, as: Unicode.ASCII.self)\n default:\n fatalError("Unsupported encoding in shim")\n }\n return unsafe Unmanaged<AnyObject>.passRetained(str._bridgeToObjectiveCImpl())\n}\n\n@available(SwiftStdlib 6.1, *)\n@_spi(Foundation) public func _SwiftCreateImmortalString_ForFoundation(\n buffer: UnsafeBufferPointer<UInt8>,\n isASCII: Bool\n) -> String? {\n switch unsafe validateUTF8(buffer) {\n case .success(let extraInfo):\n return unsafe String(_StringGuts(buffer, isASCII: extraInfo.isASCII))\n default:\n return nil\n }\n}\n\n// At runtime, this class is derived from `__SwiftNativeNSStringBase`,\n// which is derived from `NSString`.\n//\n// The @_swift_native_objc_runtime_base attribute\n// This allows us to subclass an Objective-C class and use the fast Swift\n// memory allocator.\n@objc @_swift_native_objc_runtime_base(__SwiftNativeNSStringBase)\n@_spi(Foundation) public class __SwiftNativeNSString {\n @objc internal init() {}\n deinit {}\n}\n\n@available(*, unavailable)\nextension __SwiftNativeNSString: Sendable {}\n\n// Called by the SwiftObject implementation to get the description of a value\n// as an NSString.\n@_silgen_name("swift_stdlib_getDescription")\npublic func _getDescription<T>(_ x: T) -> AnyObject {\n return String(reflecting: x)._bridgeToObjectiveCImpl()\n}\n\n@_silgen_name("swift_stdlib_NSStringFromUTF8")\n@usableFromInline //this makes the symbol available to the runtime :(\n@available(SwiftStdlib 5.2, *)\ninternal func _NSStringFromUTF8(_ s: UnsafePointer<UInt8>, _ len: Int)\n -> AnyObject {\n return unsafe String(\n decoding: UnsafeBufferPointer(start: s, count: len),\n as: UTF8.self\n )._bridgeToObjectiveCImpl()\n}\n#endif\n\n#else // !_runtime(_ObjC)\n\ninternal class __SwiftNativeNSString {\n internal init() {}\n deinit {}\n}\n\n#endif\n\n// Special-case Index <-> Offset converters for bridging and use in accelerating\n// the UTF16View in general.\nextension StringProtocol {\n @_specialize(where Self == String)\n @_specialize(where Self == Substring)\n public // SPI(Foundation)\n func _toUTF16Offset(_ idx: Index) -> Int {\n return self.utf16.distance(from: self.utf16.startIndex, to: idx)\n }\n\n @_specialize(where Self == String)\n @_specialize(where Self == Substring)\n public // SPI(Foundation)\n func _toUTF16Index(_ offset: Int) -> Index {\n return self.utf16.index(self.utf16.startIndex, offsetBy: offset)\n }\n\n public // SPI(Foundation)\n func _toUTF16Offsets(_ indices: Range<Index>) -> Range<Int> {\n if Self.self == String.self {\n let s = unsafe unsafeBitCast(self, to: String.self)\n return s.utf16._offsetRange(for: indices, from: s.startIndex)\n }\n if Self.self == Substring.self {\n let s = unsafe unsafeBitCast(self, to: Substring.self)\n return s._slice._base.utf16._offsetRange(for: indices, from: s.startIndex)\n }\n let startOffset = _toUTF16Offset(indices.lowerBound)\n let endOffset = _toUTF16Offset(indices.upperBound)\n return unsafe Range(uncheckedBounds: (lower: startOffset, upper: endOffset))\n }\n\n public // SPI(Foundation)\n func _toUTF16Indices(_ range: Range<Int>) -> Range<Index> {\n#if hasFeature(Macros)\n if Self.self == String.self {\n let s = unsafe unsafeBitCast(self, to: String.self)\n return s.utf16._indexRange(for: range, from: s.startIndex)\n }\n if Self.self == Substring.self {\n let s = unsafe unsafeBitCast(self, to: Substring.self)\n return s._slice._base.utf16._indexRange(for: range, from: s.startIndex)\n }\n#endif\n let lowerbound = _toUTF16Index(range.lowerBound)\n let upperbound = _toUTF16Index(range.upperBound)\n return unsafe Range(uncheckedBounds: (lower: lowerbound, upper: upperbound))\n }\n}\n\nextension String {\n public // @testable / @benchmarkable\n func _copyUTF16CodeUnits(\n into buffer: UnsafeMutableBufferPointer<UInt16>,\n range: Range<Int>\n ) {\n _internalInvariant(buffer.count >= range.count)\n let indexRange = self._toUTF16Indices(range)\n unsafe self.utf16._nativeCopy(into: buffer, alignedRange: indexRange)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringBridge.swift
cpp_apple_swift_stdlib_public_core_StringBridge.swift
Swift
23,983
0.95
0.074214
0.128713
python-kit
834
2023-09-03T01:06:49.335403
MIT
false
1382d7aa41b6230d23aee6459e75c361
//===--- StringCharacterView.swift - String's Collection of Characters ----===//\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// String is a collection of characters.\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftShims\n\nextension String: BidirectionalCollection {\n public typealias SubSequence = Substring\n public typealias Element = Character\n\n /// The position of the first character in a nonempty string.\n ///\n /// In an empty string, `startIndex` is equal to `endIndex`.\n @inlinable @inline(__always)\n public var startIndex: Index { return _guts.startIndex }\n\n /// A string's "past the end" position---that is, the position one greater\n /// than the last valid subscript argument.\n ///\n /// In an empty string, `endIndex` is equal to `startIndex`.\n @inlinable @inline(__always)\n public var endIndex: Index { return _guts.endIndex }\n\n /// The number of characters in a string.\n ///\n /// To check whether a string is empty,\n /// use its `isEmpty` property instead of comparing `count` to zero.\n ///\n /// - Complexity: O(n), where n is the length of the string.\n @inline(__always)\n public var count: Int {\n return distance(from: startIndex, to: endIndex)\n }\n\n /// Return true if and only if `i` is a valid index in this substring,\n /// that is to say, it exactly addresses one of the `Character`s in it.\n internal func _isValidIndex(_ i: Index) -> Bool {\n return (\n _guts.hasMatchingEncoding(i)\n && i._encodedOffset <= _guts.count\n && _guts.isOnGraphemeClusterBoundary(i))\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 value immediately after `i`.\n public func index(after i: Index) -> Index {\n let i = _guts.validateCharacterIndex(i)\n return _uncheckedIndex(after: i)\n }\n\n /// A version of `index(after:)` that assumes that the given index:\n ///\n /// - has the right encoding,\n /// - is within bounds, and\n /// - is scalar aligned.\n internal func _uncheckedIndex(after i: Index) -> Index {\n _internalInvariant(_guts.hasMatchingEncoding(i))\n _internalInvariant(i < endIndex)\n _internalInvariant(i._isCharacterAligned)\n\n // TODO: known-ASCII fast path, single-scalar-grapheme fast path, etc.\n let stride = _characterStride(startingAt: i)\n let nextOffset = i._encodedOffset &+ stride\n let nextIndex = Index(_encodedOffset: nextOffset)._characterAligned\n let nextStride = _characterStride(startingAt: nextIndex)\n let r = Index(encodedOffset: nextOffset, characterStride: nextStride)\n return _guts.markEncoding(r._characterAligned)\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 value immediately before `i`.\n public func index(before i: Index) -> Index {\n // FIXME: This method used to not properly validate indices before 5.7;\n // temporarily allow older binaries to keep invoking undefined behavior as\n // before.\n let i = _guts.validateInclusiveCharacterIndex_5_7(i)\n\n // Note: Aligning an index may move it closer towards the `startIndex`, so\n // the `i > startIndex` check needs to come after rounding.\n _precondition(\n ifLinkedOnOrAfter: .v5_7_0,\n i > startIndex, "String index is out of bounds")\n\n return _uncheckedIndex(before: i)\n }\n\n /// A version of `index(before:)` that assumes that the given index:\n ///\n /// - has the right encoding,\n /// - is within bounds, and\n /// - is character aligned.\n internal func _uncheckedIndex(before i: Index) -> Index {\n _internalInvariant(_guts.hasMatchingEncoding(i))\n _internalInvariant(i > startIndex && i <= endIndex)\n _internalInvariant(i._isCharacterAligned)\n\n // TODO: known-ASCII fast path, single-scalar-grapheme fast path, etc.\n let stride = _characterStride(endingAt: i)\n let priorOffset = i._encodedOffset &- stride\n\n let r = Index(encodedOffset: priorOffset, characterStride: stride)\n return _guts.markEncoding(r._characterAligned)\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`.\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 /// - Complexity: O(*n*), where *n* is the absolute value of `distance`.\n public func index(_ i: Index, offsetBy distance: Int) -> Index {\n // Note: prior to Swift 5.7, this method used to be inlinable, forwarding to\n // `_index(_:offsetBy:)`.\n\n // TODO: known-ASCII and single-scalar-grapheme fast path, etc.\n\n // FIXME: This method used to not properly validate indices before 5.7;\n // temporarily allow older binaries to keep invoking undefined behavior as\n // before.\n var i = _guts.validateInclusiveCharacterIndex_5_7(i)\n\n if distance >= 0 {\n for _ in stride(from: 0, to: distance, by: 1) {\n _precondition(i < endIndex, "String index is out of bounds")\n i = _uncheckedIndex(after: i)\n }\n } else {\n for _ in stride(from: 0, to: distance, by: -1) {\n _precondition(i > startIndex, "String index is out of bounds")\n i = _uncheckedIndex(before: i)\n }\n }\n return i\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`.\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(*n*), where *n* is the absolute value of `distance`.\n public func index(\n _ i: Index, offsetBy distance: Int, limitedBy limit: Index\n ) -> Index? {\n // Note: Prior to Swift 5.7, this function used to be inlinable, forwarding\n // to `BidirectionalCollection._index(_:offsetBy:limitedBy:)`.\n // Unfortunately, that approach isn't compatible with SE-0180, as it doesn't\n // support cases where `i` or `limit` aren't character aligned.\n\n // TODO: known-ASCII and single-scalar-grapheme fast path, etc.\n\n // Per SE-0180, `i` and `limit` are allowed to fall in between grapheme\n // breaks, in which case this function must still terminate without trapping\n // and return a result that makes sense.\n\n // Note: `limit` is intentionally not scalar (or character-) aligned to\n // ensure our behavior exactly matches the documentation above. We do need\n // to ensure it has a matching encoding, though. The same goes for `start`,\n // which is used to determine whether the limit applies at all.\n\n let limit = _guts.ensureMatchingEncoding(limit)\n let start = _guts.ensureMatchingEncoding(i)\n\n // FIXME: This method used to not properly validate indices before 5.7;\n // temporarily allow older binaries to keep invoking undefined behavior as\n // before.\n var i = _guts.validateInclusiveCharacterIndex_5_7(i)\n\n if distance >= 0 {\n for _ in stride(from: 0, to: distance, by: 1) {\n guard limit < start || i < limit else { return nil }\n _precondition(i < endIndex, "String index is out of bounds")\n i = _uncheckedIndex(after: i)\n }\n guard limit < start || i <= limit else { return nil }\n } else {\n for _ in stride(from: 0, to: distance, by: -1) {\n guard limit > start || i > limit else { return nil }\n _precondition(i > startIndex, "String index is out of bounds")\n i = _uncheckedIndex(before: i)\n }\n guard limit > start || i >= limit else { return nil }\n }\n return i\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 ///\n /// - Complexity: O(*n*), where *n* is the resulting distance.\n public func distance(from start: Index, to end: Index) -> Int {\n // Note: Prior to Swift 5.7, this function used to be inlinable, forwarding\n // to `BidirectionalCollection._distance(from:to:)`.\n\n // FIXME: This method used to not properly validate indices before 5.7;\n // temporarily allow older binaries to keep invoking undefined behavior as\n // before.\n let start = _guts.validateInclusiveCharacterIndex_5_7(start)\n let end = _guts.validateInclusiveCharacterIndex_5_7(end)\n\n // Per SE-0180, `start` and `end` are allowed to fall in between Character\n // boundaries, in which case this function must still terminate without\n // trapping and return a result that makes sense.\n var i = start._encodedOffset\n var count = 0\n if start < end {\n while i < end._encodedOffset { // Note `<` instead of `==`\n count &+= 1\n /*\n For the purposes of this loop, this should be equivalent to\n _uncheckedIndex(after: i). We don't need to spend time setting up\n actual Indexes when we only care about counting strides.\n */\n i &+= _guts._opaqueCharacterStride(startingAt: i)\n }\n } else if start > end {\n while i > end._encodedOffset { // Note `<` instead of `==`\n count &-= 1\n i &-= _guts._opaqueCharacterStride(endingAt: i)\n }\n }\n return count\n }\n\n /// Accesses the character at the given position.\n ///\n /// You can use the same indices for subscripting a string and its substring.\n /// For example, this code finds the first letter after the first space:\n ///\n /// let str = "Greetings, friend! How are you?"\n /// let firstSpace = str.firstIndex(of: " ") ?? str.endIndex\n /// let substr = str[firstSpace...]\n /// if let nextCapital = substr.firstIndex(where: { $0 >= "A" && $0 <= "Z" }) {\n /// print("Capital after a space: \(str[nextCapital])")\n /// }\n /// // Prints "Capital after a space: H"\n ///\n /// - Parameter i: A valid index of the string. `i` must be less than the\n /// string's end index.\n public subscript(i: Index) -> Character {\n // Prior to Swift 5.7, this function used to be inlinable.\n\n // Note: SE-0180 requires us not to round `i` down to the nearest whole\n // `Character` boundary.\n let i = _guts.validateScalarIndex(i)\n let distance = _characterStride(startingAt: i)\n return _guts.errorCorrectedCharacter(\n startingAt: i._encodedOffset, endingAt: i._encodedOffset &+ distance)\n }\n\n /// Return the length of the `Character` starting at the given index, measured\n /// in encoded code units, and without looking back at any scalar that\n /// precedes `i`.\n ///\n /// Note: if `i` isn't `Character`-aligned, then this operation must still\n /// finish successfully and return the length of the grapheme cluster starting\n /// at `i` _as if the string started on that scalar_. (This can be different\n /// from the length of the whole character when the preceding scalars are\n /// present!)\n ///\n /// This method is called from inlinable `subscript` implementations in\n /// current and previous versions of the stdlib, which require this contract\n /// not to be violated.\n @usableFromInline\n @inline(__always)\n internal func _characterStride(startingAt i: Index) -> Int {\n // Prior to Swift 5.7, this function used to be inlinable.\n _internalInvariant_5_1(i._isScalarAligned)\n\n // Fast check if it's already been measured, otherwise check resiliently\n if let d = i.characterStride { return d }\n\n if i == endIndex { return 0 }\n\n return _guts._opaqueCharacterStride(startingAt: i._encodedOffset)\n }\n\n @usableFromInline\n @inline(__always)\n internal func _characterStride(endingAt i: Index) -> Int {\n // Prior to Swift 5.7, this function used to be inlinable.\n _internalInvariant_5_1(i._isScalarAligned)\n\n if i == startIndex { return 0 }\n\n return _guts._opaqueCharacterStride(endingAt: i._encodedOffset)\n }\n}\n\nextension String {\n @frozen\n public struct Iterator: IteratorProtocol, Sendable {\n @usableFromInline\n internal var _guts: _StringGuts\n\n @usableFromInline\n internal var _position: Int = 0\n\n @usableFromInline\n internal var _end: Int\n\n @inlinable\n internal init(_ guts: _StringGuts) {\n self._end = guts.count\n self._guts = guts\n }\n\n public mutating func next() -> Character? {\n // Prior to Swift 5.7, this function used to be inlinable.\n guard _fastPath(_position < _end) else { return nil }\n\n let len = _guts._opaqueCharacterStride(startingAt: _position)\n let nextPosition = _position &+ len\n let result = _guts.errorCorrectedCharacter(\n startingAt: _position, endingAt: nextPosition)\n _position = nextPosition\n return result\n }\n }\n\n @inlinable\n public __consuming func makeIterator() -> Iterator {\n return Iterator(_guts)\n }\n}\n\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringCharacterView.swift
cpp_apple_swift_stdlib_public_core_StringCharacterView.swift
Swift
15,369
0.95
0.083123
0.547009
python-kit
957
2025-02-08T00:52:16.366742
BSD-3-Clause
false
5ed56272d6f9899c543cf7fbae974ee3
//===----------------------------------------------------------------------===//\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\nextension StringProtocol {\n @inlinable\n @_specialize(where Self == String, RHS == String)\n @_specialize(where Self == String, RHS == Substring)\n @_specialize(where Self == Substring, RHS == String)\n @_specialize(where Self == Substring, RHS == Substring)\n @_effects(readonly)\n public static func == <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {\n return _stringCompare(\n lhs._wholeGuts, lhs._offsetRange,\n rhs._wholeGuts, rhs._offsetRange,\n expecting: .equal)\n }\n\n @inlinable @inline(__always) // forward to other operator\n @_effects(readonly)\n public static func != <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {\n return !(lhs == rhs)\n }\n\n @inlinable\n @_specialize(where Self == String, RHS == String)\n @_specialize(where Self == String, RHS == Substring)\n @_specialize(where Self == Substring, RHS == String)\n @_specialize(where Self == Substring, RHS == Substring)\n @_effects(readonly)\n public static func < <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {\n return _stringCompare(\n lhs._wholeGuts, lhs._offsetRange,\n rhs._wholeGuts, rhs._offsetRange,\n expecting: .less)\n }\n\n @inlinable @inline(__always) // forward to other operator\n @_effects(readonly)\n public static func > <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {\n return rhs < lhs\n }\n\n @inlinable @inline(__always) // forward to other operator\n @_effects(readonly)\n public static func <= <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {\n return !(rhs < lhs)\n }\n\n @inlinable @inline(__always) // forward to other operator\n @_effects(readonly)\n public static func >= <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {\n return !(lhs < rhs)\n }\n}\n\nextension String: Equatable {\n @inlinable @inline(__always) // For the bitwise comparison\n @_effects(readonly)\n @_semantics("string.equals")\n public static func == (lhs: String, rhs: String) -> Bool {\n return _stringCompare(lhs._guts, rhs._guts, expecting: .equal)\n }\n}\n\nextension String: Comparable {\n @inlinable @inline(__always) // For the bitwise comparison\n @_effects(readonly)\n public static func < (lhs: String, rhs: String) -> Bool {\n return _stringCompare(lhs._guts, rhs._guts, expecting: .less)\n }\n}\n\nextension Substring: Equatable {}\n\n// TODO: Generalize `~=` over `StringProtocol` (https://github.com/apple/swift/issues/54896)\n// Below are concrete overloads to give us most of the benefit without potential\n// harm to expression type checking performance.\nextension String {\n @_alwaysEmitIntoClient\n @inline(__always)\n @_effects(readonly)\n public static func ~= (lhs: String, rhs: Substring) -> Bool {\n return lhs == rhs\n }\n}\nextension Substring {\n @_alwaysEmitIntoClient\n @inline(__always)\n @_effects(readonly)\n public static func ~= (lhs: Substring, rhs: String) -> Bool {\n return lhs == rhs\n }\n}\n\n\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringComparable.swift
cpp_apple_swift_stdlib_public_core_StringComparable.swift
Swift
3,398
0.95
0.018868
0.150538
vue-tools
988
2023-11-11T09:26:10.417633
Apache-2.0
false
b8e0e790c17d6ad5b5d9d1dc5c2c3417
//===----------------------------------------------------------------------===//\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@inlinable @inline(__always) // top-level fastest-paths\n@_effects(readonly)\ninternal func _stringCompare(\n _ lhs: _StringGuts, _ rhs: _StringGuts, expecting: _StringComparisonResult\n) -> Bool {\n if lhs.rawBits == rhs.rawBits { return expecting == .equal }\n return _stringCompareWithSmolCheck(lhs, rhs, expecting: expecting)\n}\n\n@usableFromInline\n@_effects(readonly)\ninternal func _stringCompareWithSmolCheck(\n _ lhs: _StringGuts, _ rhs: _StringGuts, expecting: _StringComparisonResult\n) -> Bool {\n // ASCII small-string fast-path:\n if lhs.isSmallASCII && rhs.isSmallASCII {\n let lhsRaw = lhs.asSmall._storage\n let rhsRaw = rhs.asSmall._storage\n\n if lhsRaw.0 != rhsRaw.0 {\n return _lexicographicalCompare(\n lhsRaw.0.bigEndian, rhsRaw.0.bigEndian, expecting: expecting)\n }\n return _lexicographicalCompare(\n lhsRaw.1.bigEndian, rhsRaw.1.bigEndian, expecting: expecting)\n }\n\n return _stringCompareInternal(lhs, rhs, expecting: expecting)\n}\n\n@inline(never) // Keep `_stringCompareWithSmolCheck` fast-path fast\n@usableFromInline\n@_effects(readonly)\ninternal func _stringCompareInternal(\n _ lhs: _StringGuts, _ rhs: _StringGuts, expecting: _StringComparisonResult\n) -> Bool {\n guard _fastPath(lhs.isFastUTF8 && rhs.isFastUTF8) else {\n return _stringCompareSlow(lhs, rhs, expecting: expecting)\n }\n\n let isNFC = lhs.isNFC && rhs.isNFC\n return unsafe lhs.withFastUTF8 { lhsUTF8 in\n return unsafe rhs.withFastUTF8 { rhsUTF8 in\n return unsafe _stringCompareFastUTF8(\n lhsUTF8, rhsUTF8, expecting: expecting, bothNFC: isNFC)\n }\n }\n}\n\n@inlinable @inline(__always) // top-level fastest-paths\n@_effects(readonly)\ninternal func _stringCompare(\n _ lhs: _StringGuts, _ lhsRange: Range<Int>,\n _ rhs: _StringGuts, _ rhsRange: Range<Int>,\n expecting: _StringComparisonResult\n) -> Bool {\n if lhs.rawBits == rhs.rawBits && lhsRange == rhsRange {\n return expecting == .equal\n }\n return _stringCompareInternal(\n lhs, lhsRange, rhs, rhsRange, expecting: expecting)\n}\n\n@usableFromInline\n@_effects(readonly)\ninternal func _stringCompareInternal(\n _ lhs: _StringGuts, _ lhsRange: Range<Int>,\n _ rhs: _StringGuts, _ rhsRange: Range<Int>,\n expecting: _StringComparisonResult\n) -> Bool {\n guard _fastPath(lhs.isFastUTF8 && rhs.isFastUTF8) else {\n return _stringCompareSlow(\n lhs, lhsRange, rhs, rhsRange, expecting: expecting)\n }\n\n let isNFC = lhs.isNFC && rhs.isNFC\n return unsafe lhs.withFastUTF8(range: lhsRange) { lhsUTF8 in\n return unsafe rhs.withFastUTF8(range: rhsRange) { rhsUTF8 in\n return unsafe _stringCompareFastUTF8(\n lhsUTF8, rhsUTF8, expecting: expecting, bothNFC: isNFC)\n }\n }\n}\n\n@_effects(readonly)\ninternal func _stringCompareFastUTF8(\n _ utf8Left: UnsafeBufferPointer<UInt8>,\n _ utf8Right: UnsafeBufferPointer<UInt8>,\n expecting: _StringComparisonResult,\n bothNFC: Bool\n) -> Bool {\n if _fastPath(bothNFC) {\n /*\n If we know both Strings are NFC *and* we're just checking\n equality, then we can early-out without looking at the contents\n if the UTF8 counts are different (without the NFC req, equal \n characters can have different counts). It might be nicer to do \n this in _binaryCompare, but we have the information about what \n operation we're trying to do at this level.\n */\n if expecting == .equal && utf8Left.count != utf8Right.count {\n return false\n }\n let cmp = unsafe _binaryCompare(utf8Left, utf8Right)\n return _lexicographicalCompare(cmp, 0, expecting: expecting)\n }\n\n return unsafe _stringCompareFastUTF8Abnormal(\n utf8Left, utf8Right, expecting: expecting)\n}\n\n@_effects(readonly)\nprivate func _stringCompareFastUTF8Abnormal(\n _ utf8Left: UnsafeBufferPointer<UInt8>,\n _ utf8Right: UnsafeBufferPointer<UInt8>,\n expecting: _StringComparisonResult\n) -> Bool {\n // Do a binary-equality prefix scan, to skip over long common prefixes.\n guard let diffIdx = unsafe _findDiffIdx(utf8Left, utf8Right) else {\n // We finished one of our inputs.\n //\n // TODO: This gives us a consistent and good ordering, but technically it\n // could differ from our stated ordering if combination with a prior scalar\n // did not produce a greater-value scalar. Consider checking normality.\n return _lexicographicalCompare(\n utf8Left.count, utf8Right.count, expecting: expecting)\n }\n\n let scalarDiffIdx = unsafe _scalarAlign(utf8Left, diffIdx)\n unsafe _internalInvariant(scalarDiffIdx == _scalarAlign(utf8Right, diffIdx))\n\n let (leftScalar, leftLen) = unsafe _decodeScalar(utf8Left, startingAt: scalarDiffIdx)\n let (rightScalar, rightLen) = unsafe _decodeScalar(\n utf8Right, startingAt: scalarDiffIdx)\n\n // Very frequent fast-path: point of binary divergence is a NFC single-scalar\n // segment. Check that we diverged at the start of a segment, and the next\n // scalar is both NFC and its own segment.\n if unsafe _fastPath(\n leftScalar._isNFCStarter && rightScalar._isNFCStarter &&\n utf8Left.hasNormalizationBoundary(before: scalarDiffIdx &+ leftLen) &&\n utf8Right.hasNormalizationBoundary(before: scalarDiffIdx &+ rightLen)\n ) {\n guard expecting == .less else {\n // We diverged\n _internalInvariant(expecting == .equal)\n return false\n }\n return _lexicographicalCompare(\n leftScalar.value, rightScalar.value, expecting: .less)\n }\n\n // Back up to the nearest normalization boundary before doing a slow\n // normalizing compare.\n let boundaryIdx = unsafe Swift.min(\n _findBoundary(utf8Left, before: diffIdx),\n _findBoundary(utf8Right, before: diffIdx))\n _internalInvariant(boundaryIdx <= diffIdx)\n\n return unsafe _stringCompareSlow(\n UnsafeBufferPointer(rebasing: utf8Left[boundaryIdx...]),\n UnsafeBufferPointer(rebasing: utf8Right[boundaryIdx...]),\n expecting: expecting)\n}\n\n@_effects(readonly)\nprivate func _stringCompareSlow(\n _ lhs: _StringGuts, _ rhs: _StringGuts, expecting: _StringComparisonResult\n) -> Bool {\n return _stringCompareSlow(\n lhs, 0..<lhs.count, rhs, 0..<rhs.count, expecting: expecting)\n}\n\n@_effects(readonly)\nprivate func _stringCompareSlow(\n _ lhs: _StringGuts, _ lhsRange: Range<Int>,\n _ rhs: _StringGuts, _ rhsRange: Range<Int>,\n expecting: _StringComparisonResult\n) -> Bool {\n // TODO: Just call the normalizer directly with range\n\n return _StringGutsSlice(lhs, lhsRange).compare(\n with: _StringGutsSlice(rhs, rhsRange),\n expecting: expecting)\n}\n\n@_effects(readonly)\nprivate func _stringCompareSlow(\n _ leftUTF8: UnsafeBufferPointer<UInt8>,\n _ rightUTF8: UnsafeBufferPointer<UInt8>,\n expecting: _StringComparisonResult\n) -> Bool {\n // TODO: Just call the normalizer directly\n\n let left = unsafe _StringGutsSlice(_StringGuts(leftUTF8, isASCII: false))\n let right = unsafe _StringGutsSlice(_StringGuts(rightUTF8, isASCII: false))\n return left.compare(with: right, expecting: expecting)\n}\n\n// Return the point of binary divergence. If they have no binary difference\n// (even if one is longer), returns nil.\n@_effects(readonly)\nprivate func _findDiffIdx(\n _ left: UnsafeBufferPointer<UInt8>, _ right: UnsafeBufferPointer<UInt8>\n) -> Int? {\n let count = Swift.min(left.count, right.count)\n var idx = 0\n while idx < count {\n guard unsafe left[_unchecked: idx] == right[_unchecked: idx] else {\n return idx\n }\n idx &+= 1\n }\n return nil\n}\n\n@_effects(readonly)\n@inline(__always)\nprivate func _lexicographicalCompare<I: FixedWidthInteger>(\n _ lhs: I, _ rhs: I, expecting: _StringComparisonResult\n) -> Bool {\n return expecting == .equal ? lhs == rhs : lhs < rhs\n}\n\n@_effects(readonly)\nprivate func _findBoundary(\n _ utf8: UnsafeBufferPointer<UInt8>, before: Int\n) -> Int {\n var idx = before\n _internalInvariant(idx >= 0)\n\n // End of string is a normalization boundary\n guard idx < utf8.count else {\n _internalInvariant(before == utf8.count)\n return utf8.count\n }\n\n // Back up to scalar boundary\n while unsafe UTF8.isContinuation(utf8[_unchecked: idx]) {\n idx &-= 1\n }\n\n while true {\n if idx == 0 { return 0 }\n\n let scalar = unsafe _decodeScalar(utf8, startingAt: idx).0\n\n if scalar._isNFCStarter {\n return idx\n }\n\n unsafe idx &-= _utf8ScalarLength(utf8, endingAt: idx)\n }\n fatalError()\n}\n\n@frozen\n@usableFromInline\ninternal enum _StringComparisonResult {\n case equal\n case less\n\n @inlinable @inline(__always)\n internal init(signedNotation int: Int) {\n _internalInvariant(int <= 0)\n self = int == 0 ? .equal : .less\n }\n\n @inlinable @inline(__always)\n static func ==(\n _ lhs: _StringComparisonResult, _ rhs: _StringComparisonResult\n ) -> Bool {\n switch (lhs, rhs) {\n case (.equal, .equal): return true\n case (.less, .less): return true\n default: return false\n }\n }\n}\n\n// Perform a binary comparison of bytes in memory. Return value is negative if\n// less, 0 if equal, positive if greater.\n@_effects(readonly)\ninternal func _binaryCompare<UInt8>(\n _ lhs: UnsafeBufferPointer<UInt8>, _ rhs: UnsafeBufferPointer<UInt8>\n) -> Int {\n var cmp = unsafe Int(truncatingIfNeeded:\n _swift_stdlib_memcmp(\n lhs.baseAddress._unsafelyUnwrappedUnchecked,\n rhs.baseAddress._unsafelyUnwrappedUnchecked,\n Swift.min(lhs.count, rhs.count)))\n if cmp == 0 {\n cmp = lhs.count &- rhs.count\n }\n return cmp\n}\n\n// Double dispatch functions\nextension _StringGutsSlice {\n @_effects(readonly)\n internal func compare(\n with other: _StringGutsSlice, expecting: _StringComparisonResult\n ) -> Bool {\n if _fastPath(self.isFastUTF8 && other.isFastUTF8) {\n Builtin.onFastPath() // aggressively inline / optimize\n let isEqual = unsafe self.withFastUTF8 { utf8Self in\n return unsafe other.withFastUTF8 { utf8Other in\n return unsafe 0 == _binaryCompare(utf8Self, utf8Other)\n }\n }\n if isEqual { return expecting == .equal }\n }\n\n return _slowCompare(with: other, expecting: expecting)\n }\n\n @inline(never) // opaque slow-path\n @_effects(readonly)\n internal func _slowCompare(\n with other: _StringGutsSlice,\n expecting: _StringComparisonResult\n ) -> Bool {\n var iter1 = Substring(self).unicodeScalars._internalNFC.makeIterator()\n var iter2 = Substring(other).unicodeScalars._internalNFC.makeIterator()\n\n var scalar1: Unicode.Scalar? = nil\n var scalar2: Unicode.Scalar? = nil\n\n while true {\n scalar1 = iter1.next()\n scalar2 = iter2.next()\n\n if scalar1 == nil || scalar2 == nil {\n break\n }\n\n if scalar1 == scalar2 {\n continue\n }\n\n if scalar1! < scalar2! {\n return expecting == .less\n } else {\n return false\n }\n }\n\n // If both of them ran out of scalars, then these are completely equal.\n if scalar1 == nil, scalar2 == nil {\n return expecting == .equal\n }\n\n // Otherwise, one of these strings has more scalars, so the one with less\n // scalars is considered "less" than.\n if end < other.end {\n return expecting == .less\n }\n\n return false\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringComparison.swift
cpp_apple_swift_stdlib_public_core_StringComparison.swift
Swift
11,527
0.95
0.08
0.115854
vue-tools
515
2023-12-28T14:47:41.452760
MIT
false
c7e1f0a1a2f2209b16e8a34a5a74bfeb
//===----------------------------------------------------------------------===//\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// String Creation Helpers\n//===----------------------------------------------------------------------===//\n\ninternal func _allASCII(_ input: UnsafeBufferPointer<UInt8>) -> Bool {\n if input.isEmpty { return true }\n\n // NOTE: Avoiding for-in syntax to avoid bounds checks\n //\n // TODO(String performance): SIMD-ize\n //\n let count = input.count\n var ptr = unsafe UnsafeRawPointer(input.baseAddress._unsafelyUnwrappedUnchecked)\n\n let asciiMask64 = 0x8080_8080_8080_8080 as UInt64\n let asciiMask32 = UInt32(truncatingIfNeeded: asciiMask64)\n let asciiMask16 = UInt16(truncatingIfNeeded: asciiMask64)\n let asciiMask8 = UInt8(truncatingIfNeeded: asciiMask64)\n \n let end128 = unsafe ptr + count & ~(MemoryLayout<(UInt64, UInt64)>.stride &- 1)\n let end64 = unsafe ptr + count & ~(MemoryLayout<UInt64>.stride &- 1)\n let end32 = unsafe ptr + count & ~(MemoryLayout<UInt32>.stride &- 1)\n let end16 = unsafe ptr + count & ~(MemoryLayout<UInt16>.stride &- 1)\n let end = unsafe ptr + count\n\n \n while unsafe ptr < end128 {\n let pair = unsafe ptr.loadUnaligned(as: (UInt64, UInt64).self)\n let result = (pair.0 | pair.1) & asciiMask64\n guard result == 0 else { return false }\n unsafe ptr = unsafe ptr + MemoryLayout<(UInt64, UInt64)>.stride\n }\n \n // If we had enough bytes for two iterations of this, we would have hit\n // the loop above, so we only need to do this once\n if unsafe ptr < end64 {\n let value = unsafe ptr.loadUnaligned(as: UInt64.self)\n guard value & asciiMask64 == 0 else { return false }\n unsafe ptr = unsafe ptr + MemoryLayout<UInt64>.stride\n }\n \n if unsafe ptr < end32 {\n let value = unsafe ptr.loadUnaligned(as: UInt32.self)\n guard value & asciiMask32 == 0 else { return false }\n unsafe ptr = unsafe ptr + MemoryLayout<UInt32>.stride\n }\n \n if unsafe ptr < end16 {\n let value = unsafe ptr.loadUnaligned(as: UInt16.self)\n guard value & asciiMask16 == 0 else { return false }\n unsafe ptr = unsafe ptr + MemoryLayout<UInt16>.stride\n }\n\n if unsafe ptr < end {\n let value = unsafe ptr.loadUnaligned(fromByteOffset: 0, as: UInt8.self)\n guard value & asciiMask8 == 0 else { return false }\n }\n unsafe _internalInvariant(ptr == end || ptr + 1 == end)\n return true\n}\n\nextension String {\n\n internal static func _uncheckedFromASCII(\n _ input: UnsafeBufferPointer<UInt8>\n ) -> String {\n if let smol = unsafe _SmallString(input) {\n return String(_StringGuts(smol))\n }\n\n let storage = unsafe __StringStorage.create(initializingFrom: input, isASCII: true)\n return storage.asString\n }\n\n @usableFromInline\n internal static func _fromASCII(\n _ input: UnsafeBufferPointer<UInt8>\n ) -> String {\n unsafe _internalInvariant(_allASCII(input), "not actually ASCII")\n return unsafe _uncheckedFromASCII(input)\n }\n\n internal static func _fromASCIIValidating(\n _ input: UnsafeBufferPointer<UInt8>\n ) -> String? {\n if unsafe _fastPath(_allASCII(input)) {\n return unsafe _uncheckedFromASCII(input)\n }\n return nil\n }\n\n public // SPI(Foundation)\n static func _tryFromUTF8(_ input: UnsafeBufferPointer<UInt8>) -> String? {\n guard case .success(let extraInfo) = unsafe validateUTF8(input) else {\n return nil\n }\n\n return unsafe String._uncheckedFromUTF8(input, isASCII: extraInfo.isASCII)\n }\n\n @usableFromInline\n internal static func _fromUTF8Repairing(\n _ input: UnsafeBufferPointer<UInt8>\n ) -> (result: String, repairsMade: Bool) {\n switch unsafe validateUTF8(input) {\n case .success(let extraInfo):\n return unsafe (String._uncheckedFromUTF8(\n input, asciiPreScanResult: extraInfo.isASCII\n ), false)\n case .error(_, let initialRange):\n return unsafe (repairUTF8(input, firstKnownBrokenRange: initialRange), true)\n }\n }\n\n internal static func _fromLargeUTF8Repairing(\n uninitializedCapacity capacity: Int,\n initializingWith initializer: (\n _ buffer: UnsafeMutableBufferPointer<UInt8>\n ) throws -> Int\n ) rethrows -> String {\n let result = try unsafe __StringStorage.create(\n uninitializedCodeUnitCapacity: capacity,\n initializingUncheckedUTF8With: initializer)\n\n switch unsafe validateUTF8(result.codeUnits) {\n case .success(let info):\n result._updateCountAndFlags(\n newCount: result.count,\n newIsASCII: info.isASCII\n )\n return result.asString\n case .error(_, let initialRange):\n defer { _fixLifetime(result) }\n //This could be optimized to use excess tail capacity\n return unsafe repairUTF8(result.codeUnits, firstKnownBrokenRange: initialRange)\n }\n }\n\n @usableFromInline\n internal static func _uncheckedFromUTF8(\n _ input: UnsafeBufferPointer<UInt8>\n ) -> String {\n return unsafe _uncheckedFromUTF8(input, isASCII: _allASCII(input))\n }\n\n @usableFromInline\n internal static func _uncheckedFromUTF8(\n _ input: UnsafeBufferPointer<UInt8>,\n isASCII: Bool\n ) -> String {\n if let smol = unsafe _SmallString(input) {\n return String(_StringGuts(smol))\n }\n\n let storage = unsafe __StringStorage.create(\n initializingFrom: input, isASCII: isASCII)\n return storage.asString\n }\n\n // If we've already pre-scanned for ASCII, just supply the result\n @usableFromInline\n internal static func _uncheckedFromUTF8(\n _ input: UnsafeBufferPointer<UInt8>, asciiPreScanResult: Bool\n ) -> String {\n if let smol = unsafe _SmallString(input) {\n return String(_StringGuts(smol))\n }\n\n let isASCII = asciiPreScanResult\n let storage = unsafe __StringStorage.create(\n initializingFrom: input, isASCII: isASCII)\n return storage.asString\n }\n\n @usableFromInline\n internal static func _uncheckedFromUTF16(\n _ input: UnsafeBufferPointer<UInt16>\n ) -> String {\n // TODO(String Performance): Attempt to form smol strings\n\n // TODO(String performance): Skip intermediary array, transcode directly\n // into a StringStorage space.\n var contents: [UInt8] = []\n contents.reserveCapacity(input.count)\n let repaired = unsafe transcode(\n input.makeIterator(),\n from: UTF16.self,\n to: UTF8.self,\n stoppingOnError: false,\n into: { contents.append($0) })\n _internalInvariant(!repaired, "Error present")\n\n return unsafe contents.withUnsafeBufferPointer { unsafe String._uncheckedFromUTF8($0) }\n }\n\n @inline(never) // slow path\n private static func _slowFromCodeUnits<\n Input: Collection,\n Encoding: Unicode.Encoding\n >(\n _ input: Input,\n encoding: Encoding.Type,\n repair: Bool\n ) -> (String, repairsMade: Bool)?\n where Input.Element == Encoding.CodeUnit {\n // TODO(String Performance): Attempt to form smol strings\n\n // TODO(String performance): Skip intermediary array, transcode directly\n // into a StringStorage space.\n var contents: [UInt8] = []\n contents.reserveCapacity(input.underestimatedCount)\n let repaired = transcode(\n input.makeIterator(),\n from: Encoding.self,\n to: UTF8.self,\n stoppingOnError: false,\n into: { contents.append($0) })\n guard repair || !repaired else { return nil }\n\n let str = unsafe contents.withUnsafeBufferPointer { unsafe String._uncheckedFromUTF8($0) }\n return (str, repaired)\n }\n\n @usableFromInline @inline(never) // can't be inlined w/out breaking ABI\n @_specialize(\n where Input == UnsafeBufferPointer<UInt8>, Encoding == Unicode.ASCII)\n @_specialize(\n where Input == Array<UInt8>, Encoding == Unicode.ASCII)\n internal static func _fromCodeUnits<\n Input: Collection,\n Encoding: Unicode.Encoding\n >(\n _ input: Input,\n encoding: Encoding.Type,\n repair: Bool\n ) -> (String, repairsMade: Bool)?\n where Input.Element == Encoding.CodeUnit {\n guard _fastPath(encoding == Unicode.ASCII.self) else {\n return _slowFromCodeUnits(input, encoding: encoding, repair: repair)\n }\n\n // Helper to simplify early returns\n func resultOrSlow(_ resultOpt: String?) -> (String, repairsMade: Bool)? {\n guard let result = resultOpt else {\n return _slowFromCodeUnits(input, encoding: encoding, repair: repair)\n }\n return (result, repairsMade: false)\n }\n\n #if !$Embedded\n // Fast path for untyped raw storage and known stdlib types\n if let contigBytes = input as? _HasContiguousBytes,\n contigBytes._providesContiguousBytesNoCopy {\n return resultOrSlow(contigBytes.withUnsafeBytes { rawBufPtr in\n let buffer = unsafe UnsafeBufferPointer(\n start: rawBufPtr.baseAddress?.assumingMemoryBound(to: UInt8.self),\n count: rawBufPtr.count)\n return unsafe String._fromASCIIValidating(buffer)\n })\n }\n #endif\n\n // Fast path for user-defined Collections\n if let strOpt = input.withContiguousStorageIfAvailable({\n (buffer: UnsafeBufferPointer<Input.Element>) -> String? in\n return unsafe String._fromASCIIValidating(\n UnsafeRawBufferPointer(buffer).bindMemory(to: UInt8.self))\n }) {\n return resultOrSlow(strOpt)\n }\n\n return unsafe resultOrSlow(Array(input).withUnsafeBufferPointer {\n let buffer = unsafe UnsafeRawBufferPointer($0).bindMemory(to: UInt8.self)\n return unsafe String._fromASCIIValidating(buffer)\n })\n }\n\n public // @testable\n static func _fromInvalidUTF16(\n _ utf16: UnsafeBufferPointer<UInt16>\n ) -> String {\n return unsafe String._fromCodeUnits(utf16, encoding: UTF16.self, repair: true)!.0\n }\n\n @usableFromInline\n internal static func _fromSubstring(\n _ substring: __shared Substring\n ) -> String {\n if substring._offsetRange == substring.base._offsetRange {\n return substring.base\n }\n\n return String._copying(substring)\n }\n\n @_alwaysEmitIntoClient\n @inline(never) // slow-path\n internal static func _copying(_ str: String) -> String {\n return String._copying(str[...])\n }\n @_alwaysEmitIntoClient\n @inline(never) // slow-path\n internal static func _copying(_ str: Substring) -> String {\n if _fastPath(str._wholeGuts.isFastUTF8) {\n return unsafe str._wholeGuts.withFastUTF8(range: str._offsetRange) {\n unsafe String._uncheckedFromUTF8($0)\n }\n }\n return unsafe Array(str.utf8).withUnsafeBufferPointer {\n unsafe String._uncheckedFromUTF8($0)\n }\n }\n\n @usableFromInline\n @available(SwiftStdlib 6.0, *)\n internal static func _validate<Encoding: Unicode.Encoding>(\n _ input: UnsafeBufferPointer<Encoding.CodeUnit>,\n as encoding: Encoding.Type\n ) -> String? {\n if encoding.CodeUnit.self == UInt8.self {\n let bytes = unsafe _identityCast(input, to: UnsafeBufferPointer<UInt8>.self)\n if encoding.self == UTF8.self {\n guard case .success(let info) = unsafe validateUTF8(bytes) else { return nil }\n return unsafe String._uncheckedFromUTF8(bytes, asciiPreScanResult: info.isASCII)\n } else if encoding.self == Unicode.ASCII.self {\n guard unsafe _allASCII(bytes) else { return nil }\n return unsafe String._uncheckedFromASCII(bytes)\n }\n }\n\n // slow-path\n var isASCII = true\n var buffer: UnsafeMutableBufferPointer<UInt8>\n unsafe buffer = UnsafeMutableBufferPointer.allocate(capacity: input.count*3)\n var written = buffer.startIndex\n\n var parser = Encoding.ForwardParser()\n var input = unsafe input.makeIterator()\n\n transcodingLoop:\n while true {\n switch unsafe parser.parseScalar(from: &input) {\n case .valid(let s):\n let scalar = Encoding.decode(s)\n guard let utf8 = Unicode.UTF8.encode(scalar) else {\n // transcoding error: clean up and return nil\n fallthrough\n }\n if buffer.count < written + utf8.count {\n let newCapacity = buffer.count + (buffer.count >> 1)\n let copy: UnsafeMutableBufferPointer<UInt8>\n unsafe copy = UnsafeMutableBufferPointer.allocate(capacity: newCapacity)\n let copied = unsafe copy.moveInitialize(\n fromContentsOf: buffer.prefix(upTo: written)\n )\n unsafe buffer.deallocate()\n unsafe buffer = unsafe copy\n written = copied\n }\n if isASCII && utf8.count > 1 {\n isASCII = false\n }\n written = unsafe buffer.suffix(from: written).initialize(fromContentsOf: utf8)\n break\n case .error:\n // validation error: clean up and return nil\n unsafe buffer.prefix(upTo: written).deinitialize()\n unsafe buffer.deallocate()\n return nil\n case .emptyInput:\n break transcodingLoop\n }\n }\n\n let storage = unsafe buffer.baseAddress.map {\n unsafe __SharedStringStorage(\n _mortal: $0,\n countAndFlags: _StringObject.CountAndFlags(\n count: buffer.startIndex.distance(to: written),\n isASCII: isASCII,\n isNFC: isASCII,\n isNativelyStored: false,\n isTailAllocated: false\n )\n )\n }\n return storage?.asString\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringCreate.swift
cpp_apple_swift_stdlib_public_core_StringCreate.swift
Swift
13,399
0.8
0.080201
0.09887
react-lib
38
2023-11-11T15:16:54.142997
Apache-2.0
false
84e4e0d60adec0d2e8d38454115d330d
//===----------------------------------------------------------------------===//\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\nimport SwiftShims\n\n/// CR and LF are common special cases in grapheme breaking logic\nprivate var _CR: UInt8 { return 0x0D }\nprivate var _LF: UInt8 { return 0x0A }\n\n/// Perform a quick-check to determine if there's a grapheme-break between two\n/// scalars, without consulting the data tables. Returns true if there\n/// definitely is a break, false if there definitely is none, and nil if a\n/// break couldn't be determined\ninternal func _quickHasGraphemeBreakBetween(\n _ lhs: Unicode.Scalar, _ rhs: Unicode.Scalar\n) -> Bool? {\n // GB3:\n // CR-LF is a special case: no break between these\n if lhs == Unicode.Scalar(_CR) && rhs == Unicode.Scalar(_LF) {\n return false\n }\n\n // Whether the given scalar, when it appears paired with another scalar\n // satisfying this property, has a grapheme break between it and the other\n // scalar.\n func hasBreakWhenPaired(_ x: Unicode.Scalar) -> Bool {\n // TODO: This doesn't generate optimal code, tune/re-write at a lower\n // level.\n //\n // NOTE: Order of case ranges affects codegen, and thus performance. All\n // things being equal, keep existing order below.\n switch x.value {\n // Unified CJK Han ideographs, common and some supplemental, amongst\n // others:\n // U+3400 ~ U+A4CF\n case 0x3400...0xa4cf: return true\n\n // Repeat sub-300 check, this is beneficial for common cases of Latin\n // characters embedded within non-Latin script (e.g. newlines, spaces,\n // proper nouns and/or jargon, punctuation).\n //\n // NOTE: CR-LF special case has already been checked.\n case 0x0000...0x02ff: return true\n\n // Non-combining kana:\n // U+3041 ~ U+3096\n // U+30A1 ~ U+30FC\n case 0x3041...0x3096: return true\n case 0x30a1...0x30fc: return true\n\n // Non-combining modern (and some archaic) Cyrillic:\n // U+0400 ~ U+0482 (first half of Cyrillic block)\n case 0x0400...0x0482: return true\n\n // Modern Arabic, excluding extenders and prependers:\n // U+061D ~ U+064A\n case 0x061d...0x064a: return true\n\n // Precomposed Hangul syllables:\n // U+AC00 ~ U+D7AF\n case 0xac00...0xd7af: return true\n\n // Common general use punctuation, excluding extenders:\n // U+2010 ~ U+2029\n case 0x2010...0x2029: return true\n\n // CJK punctuation characters, excluding extenders:\n // U+3000 ~ U+3029\n case 0x3000...0x3029: return true\n\n // Full-width forms:\n // U+FF01 ~ U+FF9D\n case 0xFF01...0xFF9D: return true\n\n default: return false\n }\n }\n if hasBreakWhenPaired(lhs) && hasBreakWhenPaired(rhs) {\n return true\n }\n return nil\n}\n\nextension _StringGuts {\n @inline(__always)\n internal func roundDownToNearestCharacter(\n _ i: String.Index\n ) -> String.Index {\n _internalInvariant(i._isScalarAligned)\n _internalInvariant(hasMatchingEncoding(i))\n _internalInvariant(i._encodedOffset <= count)\n\n let offset = i._encodedOffset\n if _fastPath(i._isCharacterAligned) { return i }\n if offset == 0 || offset == count { return i._characterAligned }\n return _slowRoundDownToNearestCharacter(i)\n }\n\n @inline(never)\n internal func _slowRoundDownToNearestCharacter(\n _ i: String.Index\n ) -> String.Index {\n let offset = i._encodedOffset\n let start = offset - _opaqueCharacterStride(endingAt: offset)\n let stride = _opaqueCharacterStride(startingAt: start)\n _internalInvariant(offset <= start + stride,\n "Grapheme breaking inconsistency")\n if offset >= start + stride {\n // Already aligned, or grapheme breaking returned an unexpected result.\n return i._characterAligned\n }\n let r = String.Index(encodedOffset: start, characterStride: stride)\n return markEncoding(r._characterAligned)\n }\n\n @inline(__always)\n internal func roundDownToNearestCharacter(\n _ i: String.Index,\n in bounds: Range<String.Index>\n ) -> String.Index {\n _internalInvariant(\n bounds.lowerBound._isScalarAligned && bounds.upperBound._isScalarAligned)\n _internalInvariant(\n hasMatchingEncoding(bounds.lowerBound)\n && hasMatchingEncoding(bounds.upperBound))\n _internalInvariant(bounds.upperBound <= endIndex)\n\n _internalInvariant(i._isScalarAligned)\n _internalInvariant(hasMatchingEncoding(i))\n _internalInvariant(i >= bounds.lowerBound && i <= bounds.upperBound)\n\n // We can only use the `_isCharacterAligned` bit if the start index is also\n // character-aligned.\n if _fastPath(\n bounds.lowerBound._isCharacterAligned && i._isCharacterAligned\n ) {\n return i\n }\n if i == bounds.lowerBound || i == bounds.upperBound { return i }\n return _slowRoundDownToNearestCharacter(i, in: bounds)\n }\n\n @inline(never)\n internal func _slowRoundDownToNearestCharacter(\n _ i: String.Index,\n in bounds: Range<String.Index>\n ) -> String.Index {\n let offset = i._encodedOffset\n\n let offsetBounds = bounds._encodedOffsetRange\n let prior =\n offset - _opaqueCharacterStride(endingAt: offset, in: offsetBounds)\n let stride = _opaqueCharacterStride(startingAt: prior)\n _internalInvariant(offset <= prior + stride,\n "Grapheme breaking inconsistency")\n if offset >= prior + stride {\n // Already aligned, or grapheme breaking returned an unexpected result.\n return i\n }\n var r = String.Index(encodedOffset: prior, characterStride: stride)\n if bounds.lowerBound._isCharacterAligned {\n r = r._characterAligned\n } else {\n r = r._scalarAligned\n }\n return markEncoding(r)\n }\n}\n\nextension _StringGuts {\n @usableFromInline @inline(never)\n @_effects(releasenone)\n internal func isOnGraphemeClusterBoundary(_ i: String.Index) -> Bool {\n if i._isCharacterAligned { return true }\n\n guard i.transcodedOffset == 0 else { return false }\n\n let offset = i._encodedOffset\n if offset == 0 || offset == self.count { return true }\n\n guard isOnUnicodeScalarBoundary(i) else { return false }\n\n let nearest = roundDownToNearestCharacter(i._scalarAligned)\n return i == nearest\n }\n}\n\nextension _StringGuts {\n /// Return the length of the extended grapheme cluster starting at offset `i`,\n /// assuming it falls on a grapheme cluster boundary.\n ///\n /// Note: This does not look behind at data preceding `i`, so if `i` is not on\n /// a grapheme cluster boundary, then it may return results that are\n /// inconsistent with `_opaqueCharacterStride(endingAt:)`. On the other hand,\n /// this behavior makes this suitable for use in substrings whose start index\n /// itself does not fall on a cluster boundary.\n @usableFromInline @inline(__always)\n @_effects(releasenone)\n internal func _opaqueCharacterStride(startingAt i: Int) -> Int {\n _internalInvariant(i < endIndex._encodedOffset)\n if isFastUTF8 {\n let fast = unsafe withFastUTF8 { utf8 in\n if i &+ 1 == utf8.count { return true }\n let pair = unsafe UnsafeRawPointer(\n utf8.baseAddress.unsafelyUnwrapped\n ).loadUnaligned(fromByteOffset: i, as: UInt16.self)\n //& 0x8080 == 0 is "both not ASCII", != 0x0A0D is "not CRLF"\n return pair & 0x8080 == 0 && pair != 0x0A0D\n }\n if _fastPath(fast) {\n _internalInvariant(_opaqueComplexCharacterStride(startingAt: i) == 1)\n return 1\n }\n }\n \n return _opaqueComplexCharacterStride(startingAt: i)\n }\n\n @_effects(releasenone) @inline(never)\n internal func _opaqueComplexCharacterStride(startingAt i: Int) -> Int {\n if _slowPath(isForeign) {\n return _foreignOpaqueCharacterStride(startingAt: i)\n }\n\n let nextIdx = unsafe withFastUTF8 { utf8 in\n nextBoundary(startingAt: i) { j in\n _internalInvariant(j >= 0)\n guard j < utf8.count else { return nil }\n let (scalar, len) = unsafe _decodeScalar(utf8, startingAt: j)\n return (scalar, j &+ len)\n }\n }\n\n return nextIdx &- i\n }\n\n /// Return the length of the extended grapheme cluster ending at offset `i`,\n /// or if `i` happens to be in the middle of a grapheme cluster, find and\n /// return the distance to its start.\n ///\n /// Note: unlike `_opaqueCharacterStride(startingAt:)`, this method always\n /// finds a correct grapheme cluster boundary.\n\n @usableFromInline @inline(__always)\n @_effects(releasenone)\n internal func _opaqueCharacterStride(endingAt i: Int) -> Int {\n if i <= 1 {\n return i\n }\n if isFastUTF8 {\n let fast = unsafe withFastUTF8 { utf8 in\n let pair = unsafe UnsafeRawPointer(\n utf8.baseAddress.unsafelyUnwrapped\n ).loadUnaligned(fromByteOffset: i &- 2, as: UInt16.self)\n //& 0x8080 == 0 is "both not ASCII", != 0x0A0D is "not CRLF"\n return pair & 0x8080 == 0 && pair != 0x0A0D\n }\n if _fastPath(fast) {\n _internalInvariant(_opaqueComplexCharacterStride(endingAt: i) == 1)\n return 1\n }\n }\n\n return _opaqueComplexCharacterStride(endingAt: i)\n }\n\n @_effects(releasenone) @inline(never)\n internal func _opaqueComplexCharacterStride(endingAt i: Int) -> Int {\n if _slowPath(isForeign) {\n return _foreignOpaqueCharacterStride(endingAt: i)\n }\n\n let previousIdx = unsafe withFastUTF8 { utf8 in\n previousBoundary(endingAt: i) { j in\n _internalInvariant(j <= utf8.count)\n guard j > 0 else { return nil }\n let (scalar, len) = unsafe _decodeScalar(utf8, endingAt: j)\n return (scalar, j &- len)\n }\n }\n\n return i &- previousIdx\n }\n\n /// Return the length of the extended grapheme cluster ending at offset `i` in\n /// bounds, or if `i` happens to be in the middle of a grapheme cluster, find\n /// and return the distance to its start.\n ///\n /// Note: unlike `_opaqueCharacterStride(startingAt:)`, this method always\n /// finds a correct grapheme cluster boundary within the substring defined by\n /// the specified bounds.\n @_effects(releasenone)\n internal func _opaqueCharacterStride(\n endingAt i: Int,\n in bounds: Range<Int>\n ) -> Int {\n _internalInvariant(i > bounds.lowerBound && i <= bounds.upperBound)\n if _slowPath(isForeign) {\n return _foreignOpaqueCharacterStride(endingAt: i, in: bounds)\n }\n\n let previousIdx = unsafe withFastUTF8 { utf8 in\n previousBoundary(endingAt: i) { j in\n _internalInvariant(j <= bounds.upperBound)\n guard j > bounds.lowerBound else { return nil }\n let (scalar, len) = unsafe _decodeScalar(utf8, endingAt: j)\n return (scalar, j &- len)\n }\n }\n\n _internalInvariant(bounds.contains(previousIdx))\n return i &- previousIdx\n }\n\n @inline(never)\n @_effects(releasenone)\n private func _foreignOpaqueCharacterStride(startingAt i: Int) -> Int {\n#if _runtime(_ObjC)\n _internalInvariant(isForeign)\n\n let nextIdx = nextBoundary(startingAt: i) { j in\n _internalInvariant(j >= 0)\n guard j < count else { return nil }\n let scalars = String.UnicodeScalarView(self)\n let idx = String.Index(_encodedOffset: j)\n\n let scalar = scalars[idx]\n let nextIdx = scalars.index(after: idx)\n\n return (scalar, nextIdx._encodedOffset)\n }\n\n return nextIdx &- i\n#else\n fatalError("No foreign strings on Linux in this version of Swift")\n#endif\n }\n\n @inline(never)\n @_effects(releasenone)\n private func _foreignOpaqueCharacterStride(\n startingAt i: Int,\n in bounds: Range<Int>\n ) -> Int {\n#if _runtime(_ObjC)\n _internalInvariant(isForeign)\n _internalInvariant(bounds.contains(i))\n\n let nextIdx = nextBoundary(startingAt: i) { j in\n _internalInvariant(j >= bounds.lowerBound)\n guard j < bounds.upperBound else { return nil }\n let scalars = String.UnicodeScalarView(self)\n let idx = String.Index(_encodedOffset: j)\n\n let scalar = scalars[idx]\n let nextIdx = scalars.index(after: idx)\n\n return (scalar, nextIdx._encodedOffset)\n }\n\n return nextIdx &- i\n#else\n fatalError("No foreign strings on Linux in this version of Swift")\n#endif\n }\n\n @inline(never)\n @_effects(releasenone)\n private func _foreignOpaqueCharacterStride(endingAt i: Int) -> Int {\n#if _runtime(_ObjC)\n _internalInvariant(isForeign)\n\n let previousIdx = previousBoundary(endingAt: i) { j in\n _internalInvariant(j <= self.count)\n guard j > 0 else { return nil }\n let scalars = String.UnicodeScalarView(self)\n let idx = String.Index(_encodedOffset: j)\n\n let previousIdx = scalars.index(before: idx)\n let scalar = scalars[previousIdx]\n\n return (scalar, previousIdx._encodedOffset)\n }\n\n return i &- previousIdx\n#else\n fatalError("No foreign strings on Linux in this version of Swift")\n#endif\n }\n\n @inline(never)\n @_effects(releasenone)\n private func _foreignOpaqueCharacterStride(\n endingAt i: Int,\n in bounds: Range<Int>\n ) -> Int {\n#if _runtime(_ObjC)\n _internalInvariant(isForeign)\n _internalInvariant(i > bounds.lowerBound && i <= bounds.upperBound)\n\n let previousIdx = previousBoundary(endingAt: i) { j in\n _internalInvariant(j <= bounds.upperBound)\n guard j > bounds.lowerBound else { return nil }\n let scalars = String.UnicodeScalarView(self)\n let idx = String.Index(_encodedOffset: j)\n\n let previousIdx = scalars.index(before: idx)\n\n let scalar = scalars[previousIdx]\n return (scalar, previousIdx._encodedOffset)\n }\n\n return i &- previousIdx\n#else\n fatalError("No foreign strings on Linux in this version of Swift")\n#endif\n }\n}\n\nextension Unicode.Scalar {\n fileprivate var _isInCBConsonant: Bool {\n _swift_stdlib_isInCB_Consonant(value)\n }\n\n fileprivate var _isInCBExtend: Bool {\n // Assuming that we're already an Extend or ZWJ...\n !(_isInCBConsonant || _isInCBLinker || value == 0x200C)\n }\n\n fileprivate var _isInCBLinker: Bool {\n switch value {\n // Devanagari\n case 0x94D:\n return true\n // Bengali\n case 0x9CD:\n return true\n // Gujarati\n case 0xACD:\n return true\n // Oriya\n case 0xB4D:\n return true\n // Telugu\n case 0xC4D:\n return true\n // Malayalam\n case 0xD4D:\n return true\n\n default:\n return false\n }\n }\n}\n\ninternal struct _GraphemeBreakingState: Sendable, Equatable {\n // When we're looking through an indic sequence, one of the requirements is\n // that there is at LEAST 1 InCB=Linker present between two InCB=Consonant.\n // This value helps ensure that when we ultimately need to decide whether or\n // not to break that we've at least seen 1 when walking.\n var hasSeenInCBLinker = false\n\n // When walking forwards in a string, we need to know whether or not we've\n // entered an emoji sequence to be able to eventually break after all of the\n // emoji's various extenders and zero width joiners. This bit allows us to\n // keep track of whether or not we're still in an emoji sequence when deciding\n // to break.\n var isInEmojiSequence = false\n\n // Similar to emoji sequences, we need to know not to break an Indic grapheme\n // sequence. This sequence is (potentially) composed of many scalars and isn't\n // as trivial as comparing two grapheme properties.\n var isInIndicSequence = false\n\n // When walking forward in a string, we need to not break on emoji flag\n // sequences. Emoji flag sequences are composed of 2 regional indicators, so\n // when we see our first (.regionalIndicator, .regionalIndicator) decision,\n // we need to know to return false in this case. However, if the next scalar\n // is another regional indicator, we reach the same decision rule, but in this\n // case we actually need to break there's a boundary between emoji flag\n // sequences.\n var shouldBreakRI = false\n}\n\nextension _GraphemeBreakingState: CustomStringConvertible {\n var description: String {\n var r = "["\n if hasSeenInCBLinker { r += "L" }\n if isInEmojiSequence { r += "E" }\n if isInIndicSequence { r += "I" }\n if shouldBreakRI { r += "R" }\n r += "]"\n return r\n }\n}\n\nextension Unicode {\n /// A state machine for recognizing character (i.e., extended grapheme\n /// cluster) boundaries in an arbitrary series of Unicode scalars.\n ///\n /// To detect grapheme breaks in a sequence of Unicode scalars, feed each of\n /// them to the `hasBreak(before:)` method. The method returns true if the\n /// sequence has a grapheme break preceding the given value.\n ///\n /// The results produced by this state machine are guaranteed to match the way\n /// `String` splits its contents into `Character` values.\n @available(SwiftStdlib 5.8, *)\n public // SPI(Foundation) FIXME: We need API for this\n struct _CharacterRecognizer: Sendable {\n internal var _previous: Unicode.Scalar\n internal var _state: _GraphemeBreakingState\n\n /// Refactoring TODO: should we use a quick check result?\n ///\n /// Returns a non-nil value if it can be determined whether there is a\n /// grapheme break between `scalar1` and `scalar2` without knowing anything\n /// about the scalars that precede `scalar1`. This can optionally be used as\n /// a fast (but incomplete) test before spinning up a full state machine\n /// session.\n @_effects(releasenone)\n public static func quickBreak(\n between scalar1: Unicode.Scalar,\n and scalar2: Unicode.Scalar\n ) -> Bool? {\n _quickHasGraphemeBreakBetween(scalar1, scalar2)\n }\n\n /// Initialize a new character recognizer at the _start of text_ (sot)\n /// position.\n ///\n /// The resulting state machine will report a grapheme break on the\n /// first scalar that is fed to it.\n public init() {\n _state = _GraphemeBreakingState()\n // To avoid having to handle the empty case specially, we use NUL as the\n // placeholder before the first scalar. NUL is a control character, so per\n // rule GB5, it will induce an unconditional grapheme break before the\n // first actual scalar, emulating GB1.\n _previous = Unicode.Scalar(0 as UInt8)\n }\n\n /// Feeds the next scalar to the state machine, returning a Boolean value\n /// indicating whether it starts a new extended grapheme cluster.\n ///\n /// This method will always report a break the first time it is called\n /// on a newly initialized recognizer.\n ///\n /// The state machine does not carry information across character\n /// boundaries. I.e., if this method returns true, then `self` after the\n /// call is equivalent to feeding the same scalar to a newly initialized\n /// recognizer instance.\n @_effects(releasenone)\n public mutating func hasBreak(\n before next: Unicode.Scalar\n ) -> Bool {\n let r = _state.shouldBreak(between: _previous, and: next)\n if r {\n _state = _GraphemeBreakingState()\n }\n _previous = next\n return r\n }\n\n /// Decode the scalars in the given UTF-8 buffer and feed them to the\n /// recognizer up to and including the scalar following the first grapheme\n /// break. If the buffer contains a grapheme break, then this function\n /// returns the index range of the scalar that follows the first one;\n /// otherwise it returns `nil`.\n ///\n /// On return, the state of the recognizer is updated to reflect the scalars\n /// up to and including the returned one. You can detect additional grapheme\n /// breaks by feeding the recognizer subsequent data.\n ///\n /// - Parameter buffer: A buffer containing valid UTF-8 data, starting and\n /// ending on Unicode scalar boundaries.\n ///\n /// - Parameter start: A valid index into `buffer`, addressing the first\n /// code unit of a UTF-8 scalar in the buffer, or the end.\n ///\n /// - Returns: The index range of the scalar that follows the first grapheme\n /// break in the buffer, if there is one. If the buffer contains no\n /// grapheme breaks, then this function returns `nil`.\n ///\n /// - Warning: This function does not validate that the buffer contains\n /// valid UTF-8 data; its behavior is undefined if given invalid input.\n @_effects(releasenone)\n public mutating func _firstBreak(\n inUncheckedUnsafeUTF8Buffer buffer: UnsafeBufferPointer<UInt8>,\n startingAt start: Int = 0\n ) -> Range<Int>? {\n var i = start\n while i < buffer.endIndex {\n let (next, n) = unsafe _decodeScalar(buffer, startingAt: i)\n if hasBreak(before: next) {\n return unsafe Range(_uncheckedBounds: (i, i &+ n))\n }\n i &+= n\n }\n return nil\n }\n }\n}\n\n@available(SwiftStdlib 5.9, *)\nextension Unicode._CharacterRecognizer: Equatable {\n public static func ==(left: Self, right: Self) -> Bool {\n left._previous == right._previous && left._state == right._state\n }\n}\n\n@available(SwiftStdlib 5.9, *)\nextension Unicode._CharacterRecognizer: CustomStringConvertible {\n public var description: String {\n return "\(_state)U+\(String(_previous.value, radix: 16, uppercase: true))"\n }\n}\n\n\nextension _StringGuts {\n // Returns the stride of the grapheme cluster starting at offset `index`,\n // assuming it is on a grapheme cluster boundary.\n //\n // This method never looks at data below `index`. If `index` isn't on a\n // grapheme cluster boundary, then the result may not be consistent with the\n // actual breaks in the string. `Substring` relies on this to generate the\n // right breaks if its start index isn't aligned on one -- in this case, the\n // substring's breaks may not match the ones in its base string.\n internal func nextBoundary(\n startingAt index: Int,\n nextScalar: (Int) -> (scalar: Unicode.Scalar, end: Int)?\n ) -> Int {\n _internalInvariant(index < endIndex._encodedOffset)\n return _nextGraphemeClusterBoundary(startingAt: index, nextScalar: nextScalar)\n }\n}\n\ninternal func _nextGraphemeClusterBoundary(\n startingAt index: Int,\n nextScalar: (Int) -> (scalar: Unicode.Scalar, end: Int)?\n) -> Int {\n\n // Note: If `index` isn't already on a boundary, then starting with an empty\n // state here sometimes leads to this method returning results that diverge\n // from the true breaks in the string.\n var state = _GraphemeBreakingState()\n var (scalar, index) = nextScalar(index)!\n\n while true {\n guard let (scalar2, nextIndex) = nextScalar(index) else { break }\n if state.shouldBreak(between: scalar, and: scalar2) {\n break\n }\n index = nextIndex\n scalar = scalar2\n }\n\n return index\n}\n\nextension _StringGuts {\n fileprivate func previousBoundary(\n endingAt index: Int,\n previousScalar: (Int) -> (scalar: Unicode.Scalar, start: Int)?\n ) -> Int {\n _previousGraphemeClusterBoundary(endingAt: index, previousScalar: previousScalar)\n }\n\n}\n\n// Returns the stride of the grapheme cluster ending at offset `index`.\n//\n// This method uses `previousScalar` to looks back in the string as far as\n// necessary to find a correct grapheme cluster boundary, whether or not\n// `index` happens to be on a boundary itself.\ninternal func _previousGraphemeClusterBoundary(\n endingAt index: Int,\n previousScalar: (Int) -> (scalar: Unicode.Scalar, start: Int)?\n) -> Int {\n // FIXME: This requires potentially arbitrary lookback in each iteration,\n // leading to quadratic behavior in some edge cases. Ideally lookback should\n // only be done once per cluster (or in the case of RI sequences, once per\n // flag sequence). One way to avoid most quadratic behavior is to replace\n // this implementation with a scheme that first searches backwards for a\n // safe point then iterates forward using the regular `shouldBreak` until we\n // reach `index`, as recommended in section 6.4 of TR#29.\n //\n // https://www.unicode.org/reports/tr29/#Random_Access\n\n var (scalar2, index) = previousScalar(index)!\n\n while true {\n guard let (scalar1, previousIndex) = previousScalar(index) else { break }\n if _shouldBreakWithLookback(\n between: scalar1, and: scalar2, at: index, with: previousScalar\n ) {\n break\n }\n index = previousIndex\n scalar2 = scalar1\n }\n\n return index\n}\n\nextension _GraphemeBreakingState {\n // Return true if there is an extended grapheme cluster boundary between two\n // scalars, based on state information previously collected about preceding\n // scalars.\n //\n // This method never looks at scalars other than the two that are explicitly\n // passed to it. The `state` parameter is assumed to hold all contextual\n // information necessary to make a correct decision; it gets updated with more\n // data as needed.\n //\n // This is based on the Unicode Annex #29 for [Grapheme Cluster Boundary\n // Rules](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules).\n internal mutating func shouldBreak(\n between scalar1: Unicode.Scalar,\n and scalar2: Unicode.Scalar\n ) -> Bool {\n if let result = _quickHasGraphemeBreakBetween(scalar1, scalar2) {\n return result\n }\n\n let x = Unicode._GraphemeBreakProperty(from: scalar1)\n \n // GB4 handled here because we don't need to know `y` for this case\n if x == .control {\n return true\n }\n \n // This variable and the defer statement help toggle the isInEmojiSequence\n // state variable to false after every decision of 'shouldBreak'. If we\n // happen to see a rhs .extend or .zwj, then it's a signal that we should\n // continue treating the current grapheme cluster as an emoji sequence.\n var enterEmojiSequence = false\n\n // Very similar to emoji sequences, but for Indic grapheme sequences.\n var enterIndicSequence = false\n\n defer {\n isInEmojiSequence = enterEmojiSequence\n isInIndicSequence = enterIndicSequence\n }\n \n let y = Unicode._GraphemeBreakProperty(from: scalar2)\n\n switch (x, y) {\n\n // Fast path: If we know our scalars have no properties the decision is\n // trivial and we don't need to crawl to the default statement.\n case (.any, .any):\n return true\n\n // (GB4 is handled above)\n\n // GB5\n case (_, .control):\n return true\n\n // GB6\n case (.l, .l),\n (.l, .v),\n (.l, .lv),\n (.l, .lvt):\n return false\n\n // GB7\n case (.lv, .v),\n (.v, .v),\n (.lv, .t),\n (.v, .t):\n return false\n\n // GB8\n case (.lvt, .t),\n (.t, .t):\n return false\n\n // GB9 (partial GB9c and partial GB11)\n case (_, .extend),\n (_, .zwj):\n\n // Prepare for recognizing GB11, by remembering if we're in an emoji\n // sequence.\n //\n // GB11: Extended_Pictographic Extend* ZWJ × Extended_Pictographic\n //\n // If our left-side scalar is a pictograph, then it starts a new emoji\n // sequence; the sequence continues through subsequent extend/extend and\n // extend/zwj pairs.\n if (\n x == .extendedPictographic || (isInEmojiSequence && x == .extend)\n ) {\n enterEmojiSequence = true\n }\n\n // GB9c: InCB=Consonant [InCB=Extend InCB=Linker]* InCB=Linker [InCB=Extend InCB=Linker]* × InCB=Consonant\n //\n // If our lhs is an InCB=Consonant and our rhs is either an InCB=Extend or\n // an InCB=Linker, then enter into an indic sequence and mark if scalar 2\n // is a linker and that we've seen a linker.\n //\n // If the lhs is not an InCB=Consonant, then check if we're currently in\n // an indic sequence to properly propagate that back to the state.\n // Otherwise, we're not in an indic sequence, but our rhs is still an\n // extension scalar so don't break regardless right here. If we are in an\n // indic sequence, tell the state that we've seen a linker if our rhs is\n // one.\n switch (scalar1._isInCBConsonant, scalar2._isInCBExtend, scalar2._isInCBLinker) {\n // (InCB=Consonant, InCB=Extend)\n case (true, true, false):\n enterIndicSequence = true\n\n // (InCB=Consonant, InCB=Linker)\n case (true, false, true):\n enterIndicSequence = true\n hasSeenInCBLinker = true\n\n // (_, InCB=Extend)\n case (false, true, false):\n guard isInIndicSequence else {\n break\n }\n\n enterIndicSequence = true\n\n // (_, InCB=Linker)\n case (false, false, true):\n guard isInIndicSequence else {\n break\n }\n\n enterIndicSequence = true\n hasSeenInCBLinker = true\n\n default:\n break\n }\n\n return false\n\n // GB9a\n case (_, .spacingMark):\n return false\n\n // GB9b\n case (.prepend, _):\n return false\n\n // GB11\n case (.zwj, .extendedPictographic):\n return !isInEmojiSequence\n\n // GB12 & GB13\n case (.regionalIndicator, .regionalIndicator):\n defer {\n shouldBreakRI.toggle()\n }\n\n return shouldBreakRI\n\n // GB999\n default:\n // GB9c\n if isInIndicSequence, hasSeenInCBLinker, scalar2._isInCBConsonant {\n hasSeenInCBLinker = false\n return false\n }\n\n return true\n }\n }\n}\n\n// Return true if there is an extended grapheme cluster boundary between two\n// scalars, with no previous knowledge about preceding scalars.\n//\n// This method looks back as far as it needs to determine the correct\n// placement of boundaries.\n//\n// This is based off of the Unicode Annex #29 for [Grapheme Cluster Boundary\n// Rules](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules).\nfileprivate func _shouldBreakWithLookback(\n between scalar1: Unicode.Scalar,\n and scalar2: Unicode.Scalar,\n at index: Int,\n with previousScalar: (Int) -> (scalar: Unicode.Scalar, start: Int)?\n) -> Bool {\n if let result = _quickHasGraphemeBreakBetween(scalar1, scalar2) {\n return result\n }\n\n let x = Unicode._GraphemeBreakProperty(from: scalar1)\n let y = Unicode._GraphemeBreakProperty(from: scalar2)\n\n switch (x, y) {\n\n // Fast path: If we know our scalars have no properties the decision is\n // trivial and we don't need to crawl to the default statement.\n case (.any, .any):\n return true\n\n // GB4\n case (.control, _):\n return true\n\n // GB5\n case (_, .control):\n return true\n\n // GB6\n case (.l, .l),\n (.l, .v),\n (.l, .lv),\n (.l, .lvt):\n return false\n\n // GB7\n case (.lv, .v),\n (.v, .v),\n (.lv, .t),\n (.v, .t):\n return false\n\n // GB8\n case (.lvt, .t),\n (.t, .t):\n return false\n\n // GB9\n case (_, .extend),\n (_, .zwj):\n return false\n\n // GB9a\n case (_, .spacingMark):\n return false\n\n // GB9b\n case (.prepend, _):\n return false\n\n // GB11\n case (.zwj, .extendedPictographic):\n return !_checkIfInEmojiSequence(at: index, with: previousScalar)\n\n // GB12 & GB13\n case (.regionalIndicator, .regionalIndicator):\n return _countRIs(at: index, with: previousScalar)\n\n // GB999\n default:\n // GB9c\n //\n // Check if our rhs is an InCB=Consonant first because we can more easily\n // exit out of this branch in most cases. Otherwise, this is a consonant.\n // Check that the lhs is an InCB=Extend or InCB=Linker (we have to check\n // if it's an .extend or .zwj first because _isInCBExtend assumes that it\n // is true).\n if scalar2._isInCBConsonant,\n (x == .extend || x == .zwj),\n (scalar1._isInCBExtend || scalar1._isInCBLinker) {\n return !_checkIfInIndicSequence(at: index, with: previousScalar)\n }\n\n return true\n }\n}\n\n// When walking backwards, it's impossible to know whether we were in an emoji\n// sequence without walking further backwards. This walks the string backwards\n// enough until we figure out whether or not to break our\n// (.zwj, .extendedPictographic) question. For example:\n//\n// Scalar view #1:\n//\n// [.control, .zwj, .extendedPictographic]\n// ^\n// | = To determine whether or not we break here, we need\n// to see the previous scalar's grapheme property.\n// ^\n// | = This is neither .extendedPictographic nor .extend, thus we\n// were never in an emoji sequence, so break between the .zwj\n// and .extendedPictographic.\n//\n// Scalar view #2:\n//\n// [.extendedPictographic, .zwj, .extendedPictographic]\n// ^\n// | = Same as above, move backwards one to\n// view the previous scalar's property.\n// ^\n// | = This is an .extendedPictographic, so this indicates that\n// we are in an emoji sequence, so we should NOT break\n// between the .zwj and .extendedPictographic.\n//\n// Scalar view #3:\n//\n// [.extendedPictographic, .extend, .extend, .zwj, .extendedPictographic]\n// ^\n// | = Same as above\n// ^\n// | = This is an .extend which means\n// there is a potential emoji\n// sequence, walk further backwards\n// to find an .extendedPictographic.\n//\n// <-- = Another extend, go backwards more.\n// ^\n// | = We found our starting .extendedPictographic letting us\n// know that we are in an emoji sequence so our initial\n// break question is answered as NO.\nfileprivate func _checkIfInEmojiSequence(\n at index: Int,\n with previousScalar: (Int) -> (scalar: Unicode.Scalar, start: Int)?\n) -> Bool {\n guard var i = previousScalar(index)?.start else { return false }\n while let prev = previousScalar(i) {\n i = prev.start\n let gbp = Unicode._GraphemeBreakProperty(from: prev.scalar)\n\n switch gbp {\n case .extend:\n continue\n case .extendedPictographic:\n return true\n default:\n return false\n }\n }\n return false\n}\n\n// When walking backwards, it's impossible to know whether we break when we\n// see our first (InCB=Extend, InCB=Consonant) or (InCB=Linker, InCB=Consonant)\n// without walking further backwards. This walks the string backwards enough\n// until we figure out whether or not to break this indic sequence. For example:\n//\n// Scalar view #1:\n//\n// [InCB=Linker, InCB=Extend, InCB=Consonant]\n// ^\n// | = To be able to know whether or not to\n// break these two, we need to walk\n// backwards to determine if this is a\n// legitimate indic sequence.\n// ^\n// | = The scalar sequence ends without a starting InCB=Consonant,\n// so this is in fact not an indic sequence, so we can break the two.\n//\n// Scalar view #2:\n//\n// [InCB=Consonant, InCB=Linker, InCB=Extend, InCB=Consonant]\n// ^\n// | = Same as above\n// ^\n// | = This is a Linker, so we at least have seen\n// 1 to be able to return true if we see a\n// consonant later.\n// ^\n// | = Is a consonant and we've seen a linker, so this is a\n// legitimate indic sequence, so do NOT break the initial question.\nfileprivate func _checkIfInIndicSequence(\n at index: Int,\n with previousScalar: (Int) -> (scalar: Unicode.Scalar, start: Int)?\n) -> Bool {\n guard let p = previousScalar(index) else { return false }\n\n var hasSeenInCBLinker = p.scalar._isInCBLinker\n var i = p.start\n\n while let (scalar, prev) = previousScalar(i) {\n i = prev\n\n if scalar._isInCBConsonant {\n return hasSeenInCBLinker\n }\n\n let gbp = Unicode._GraphemeBreakProperty(from: scalar)\n\n guard gbp == .extend || gbp == .zwj else {\n return false\n }\n\n switch (scalar._isInCBExtend, scalar._isInCBLinker) {\n case (false, false):\n return false\n\n case (false, true):\n hasSeenInCBLinker = true\n\n case (true, false):\n continue\n\n case (true, true):\n // This case should never happen, but if it does then just be cautious\n // and say this is invalid.\n return false\n }\n }\n\n return false\n}\n\n// When walking backwards, it's impossible to know whether we break when we\n// see our first (.regionalIndicator, .regionalIndicator) without walking\n// further backwards. This walks the string backwards enough until we figure\n// out whether or not to break these RIs. For example:\n//\n// Scalar view #1:\n//\n// [.control, .regionalIndicator, .regionalIndicator]\n// ^\n// | = To be able to know whether or not to\n// break these two, we need to walk\n// backwards to determine if there were\n// any previous .regionalIndicators in\n// a row.\n// ^\n// | = Not a .regionalIndicator, so our total riCount is 0 and 0 is\n// even thus we do not break.\n//\n// Scalar view #2:\n//\n// [.control, .regionalIndicator, .regionalIndicator, .regionalIndicator]\n// ^\n// | = Same as above\n// ^\n// | = This is a .regionalIndicator, so continue\n// walking backwards for more of them. riCount is\n// now equal to 1.\n// ^\n// | = Not a .regionalIndicator. riCount = 1 which is odd, so break\n// the last two .regionalIndicators.\nfileprivate func _countRIs(\n at index: Int,\n with previousScalar: (Int) -> (scalar: Unicode.Scalar, start: Int)?\n) -> Bool {\n guard let p = previousScalar(index) else { return false }\n var i = p.start\n var riCount = 0\n while let p = previousScalar(i) {\n i = p.start\n\n let gbp = Unicode._GraphemeBreakProperty(from: p.scalar)\n guard gbp == .regionalIndicator else {\n break\n }\n\n riCount += 1\n }\n return riCount & 1 != 0\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringGraphemeBreaking.swift
cpp_apple_swift_stdlib_public_core_StringGraphemeBreaking.swift
Swift
38,605
0.95
0.081615
0.378085
node-utils
110
2024-09-29T21:05:40.404231
BSD-3-Clause
false
47960a6a83c62141a6c0ffb7314a2db4
//===----------------------------------------------------------------------===//\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\nimport SwiftShims\n\n//\n// StringGuts is a parameterization over String's representations. It provides\n// functionality and guidance for efficiently working with Strings.\n//\n@frozen\npublic // SPI(corelibs-foundation)\nstruct _StringGuts: @unchecked Sendable {\n @usableFromInline\n internal var _object: _StringObject\n\n @inlinable @inline(__always)\n internal init(_ object: _StringObject) {\n self._object = object\n _invariantCheck()\n }\n\n // Empty string\n @inlinable @inline(__always)\n init() {\n self.init(_StringObject(empty: ()))\n }\n}\n\n// Raw\nextension _StringGuts {\n @inlinable @inline(__always)\n internal var rawBits: _StringObject.RawBitPattern {\n return _object.rawBits\n }\n}\n\n// Creation\nextension _StringGuts {\n @inlinable @inline(__always)\n internal init(_ smol: _SmallString) {\n self.init(_StringObject(smol))\n }\n\n @inlinable @inline(__always)\n internal init(_ bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool) {\n unsafe self.init(_StringObject(immortal: bufPtr, isASCII: isASCII))\n }\n\n @inline(__always)\n internal init(_ storage: __StringStorage) {\n self.init(_StringObject(storage))\n }\n\n internal init(_ storage: __SharedStringStorage) {\n self.init(_StringObject(storage))\n }\n \n#if !$Embedded\ninternal init(\n constantCocoa cocoa: AnyObject,\n providesFastUTF8: Bool,\n isASCII: Bool,\n length: Int\n) {\n self.init(_StringObject(\n constantCocoa: cocoa,\n providesFastUTF8: providesFastUTF8,\n isASCII: isASCII,\n length: length))\n}\n#endif\n\n #if !$Embedded\n internal init(\n cocoa: AnyObject, providesFastUTF8: Bool, isASCII: Bool, length: Int\n ) {\n self.init(_StringObject(\n cocoa: cocoa,\n providesFastUTF8: providesFastUTF8,\n isASCII: isASCII,\n length: length))\n }\n #endif\n}\n\n// Queries\nextension _StringGuts {\n // The number of code units\n @inlinable @inline(__always)\n internal var count: Int { return _object.count }\n\n @inlinable @inline(__always)\n internal var isEmpty: Bool { return count == 0 }\n\n @inlinable @inline(__always)\n internal var isSmall: Bool { return _object.isSmall }\n\n @inline(__always)\n internal var isSmallASCII: Bool {\n return _object.isSmall && _object.smallIsASCII\n }\n\n @inlinable @inline(__always)\n internal var asSmall: _SmallString {\n return _SmallString(_object)\n }\n\n @inlinable @inline(__always)\n internal var isASCII: Bool {\n return _object.isASCII\n }\n\n @inlinable @inline(__always)\n internal var isFastASCII: Bool {\n return isFastUTF8 && _object.isASCII\n }\n\n @inline(__always)\n internal var isNFC: Bool { return _object.isNFC }\n\n @inline(__always)\n internal var isNFCFastUTF8: Bool {\n // TODO(String micro-performance): Consider a dedicated bit for this\n return _object.isNFC && isFastUTF8\n }\n\n internal var hasNativeStorage: Bool { return _object.hasNativeStorage }\n\n internal var hasSharedStorage: Bool { return _object.hasSharedStorage }\n\n // Whether this string has breadcrumbs\n internal var hasBreadcrumbs: Bool {\n return hasSharedStorage\n || (hasNativeStorage && _object.withNativeStorage { $0.hasBreadcrumbs })\n }\n}\n\n//\nextension _StringGuts {\n // Whether we can provide fast access to contiguous UTF-8 code units\n @_transparent\n @inlinable\n internal var isFastUTF8: Bool { return _fastPath(_object.providesFastUTF8) }\n\n // A String which does not provide fast access to contiguous UTF-8 code units\n @inlinable @inline(__always)\n internal var isForeign: Bool {\n return _slowPath(_object.isForeign)\n }\n\n @inlinable @inline(__always)\n internal func withFastUTF8<R>(\n _ f: (UnsafeBufferPointer<UInt8>) throws -> R\n ) rethrows -> R {\n _internalInvariant(isFastUTF8)\n\n if self.isSmall { return try _SmallString(_object).withUTF8(f) }\n\n defer { _fixLifetime(self) }\n return try unsafe f(_object.fastUTF8)\n }\n\n @inlinable @inline(__always)\n internal func withFastUTF8<R>(\n range: Range<Int>,\n _ f: (UnsafeBufferPointer<UInt8>) throws -> R\n ) rethrows -> R {\n return try unsafe self.withFastUTF8 { wholeUTF8 in\n return try unsafe f(unsafe UnsafeBufferPointer(rebasing: wholeUTF8[range]))\n }\n }\n\n @inlinable @inline(__always)\n internal func withFastCChar<R>(\n _ f: (UnsafeBufferPointer<CChar>) throws -> R\n ) rethrows -> R {\n return try unsafe self.withFastUTF8 { utf8 in\n return try unsafe utf8.withMemoryRebound(to: CChar.self, f)\n }\n }\n}\n\n// Internal invariants\nextension _StringGuts {\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 #if _pointerBitWidth(_64)\n _internalInvariant(MemoryLayout<String>.size == 16, """\n the runtime is depending on this, update Reflection.mm and \\n this if you change it\n """)\n #elseif _pointerBitWidth(_32) || _pointerBitWidth(_16)\n _internalInvariant(MemoryLayout<String>.size == 12, """\n the runtime is depending on this, update Reflection.mm and \\n this if you change it\n """)\n #else\n #error("Unknown platform")\n #endif\n }\n #endif // INTERNAL_CHECKS_ENABLED\n\n internal func _dump() { _object._dump() }\n}\n\n// C String interop\nextension _StringGuts {\n @inlinable @inline(__always) // fast-path: already C-string compatible\n internal func withCString<Result>(\n _ body: (UnsafePointer<Int8>) throws -> Result\n ) rethrows -> Result {\n if _slowPath(!_object.isFastZeroTerminated) {\n return try unsafe _slowWithCString(body)\n }\n\n return try unsafe self.withFastCChar {\n return try unsafe body($0.baseAddress._unsafelyUnwrappedUnchecked)\n }\n }\n\n @inline(never) // slow-path\n @usableFromInline\n internal func _slowWithCString<Result>(\n _ body: (UnsafePointer<Int8>) throws -> Result\n ) rethrows -> Result {\n _internalInvariant(!_object.isFastZeroTerminated)\n return try unsafe String(self).utf8CString.withUnsafeBufferPointer {\n let ptr = unsafe $0.baseAddress._unsafelyUnwrappedUnchecked\n return try unsafe body(ptr)\n }\n }\n}\n\nextension _StringGuts {\n // Copy UTF-8 contents. Returns number written or nil if not enough space.\n // Contents of the buffer are unspecified if nil is returned.\n @inlinable\n internal func copyUTF8(into mbp: UnsafeMutableBufferPointer<UInt8>) -> Int? {\n let ptr = unsafe mbp.baseAddress._unsafelyUnwrappedUnchecked\n if _fastPath(self.isFastUTF8) {\n return unsafe self.withFastUTF8 { utf8 in\n guard utf8.count <= mbp.count else { return nil }\n\n let utf8Start = unsafe utf8.baseAddress._unsafelyUnwrappedUnchecked\n unsafe ptr.initialize(from: utf8Start, count: utf8.count)\n return utf8.count\n }\n }\n\n return unsafe _foreignCopyUTF8(into: mbp)\n }\n @_effects(releasenone)\n @usableFromInline @inline(never) // slow-path\n internal func _foreignCopyUTF8(\n into mbp: UnsafeMutableBufferPointer<UInt8>\n ) -> Int? {\n #if _runtime(_ObjC)\n // Currently, foreign means NSString\n let res = _object.withCocoaObject {\n unsafe _cocoaStringCopyUTF8($0, into: UnsafeMutableRawBufferPointer(mbp))\n }\n if let res { return res }\n\n // If the NSString contains invalid UTF8 (e.g. unpaired surrogates), we\n // can get nil from cocoaStringCopyUTF8 in situations where a character by\n // character loop would get something more useful like repaired contents\n var ptr = unsafe mbp.baseAddress._unsafelyUnwrappedUnchecked\n var numWritten = 0\n for cu in String(self).utf8 {\n guard numWritten < mbp.count else { return nil }\n unsafe ptr.initialize(to: cu)\n unsafe ptr += 1\n numWritten += 1\n }\n \n return numWritten\n #else\n fatalError("No foreign strings on Linux in this version of Swift")\n #endif\n }\n\n @inline(__always)\n internal var utf8Count: Int {\n if _fastPath(self.isFastUTF8) { return count }\n return String(self).utf8.count\n }\n}\n\n// Index\nextension _StringGuts {\n @usableFromInline\n internal typealias Index = String.Index\n\n @inlinable @inline(__always)\n internal var startIndex: String.Index {\n // The start index is always `Character` aligned.\n Index(_encodedOffset: 0)._characterAligned._encodingIndependent\n }\n\n @inlinable @inline(__always)\n internal var endIndex: String.Index {\n // The end index is always `Character` aligned.\n markEncoding(Index(_encodedOffset: self.count)._characterAligned)\n }\n}\n\n// Encoding\nextension _StringGuts {\n /// Returns whether this string has a UTF-8 storage representation.\n /// If this returns false, then the string is encoded in UTF-16.\n ///\n /// This always returns a value corresponding to the string's actual encoding.\n @_alwaysEmitIntoClient\n @inline(__always)\n internal var isUTF8: Bool { _object.isUTF8 }\n\n @_alwaysEmitIntoClient // Swift 5.7\n @inline(__always)\n internal func markEncoding(_ i: String.Index) -> String.Index {\n isUTF8 ? i._knownUTF8 : i._knownUTF16\n }\n\n /// Returns true if the encoding of the given index isn't known to be in\n /// conflict with this string's encoding.\n ///\n /// If the index was created by code that was built on a stdlib below 5.7,\n /// then this check may incorrectly return true on a mismatching index, but it\n /// is guaranteed to never incorrectly return false. If all loaded binaries\n /// were built in 5.7+, then this method is guaranteed to always return the\n /// correct value.\n @_alwaysEmitIntoClient @inline(__always)\n internal func hasMatchingEncoding(_ i: String.Index) -> Bool {\n i._hasMatchingEncoding(isUTF8: isUTF8)\n }\n\n /// Return an index whose encoding can be assumed to match that of `self`,\n /// trapping if `i` has an incompatible encoding.\n ///\n /// If `i` is UTF-8 encoded, but `self` is an UTF-16 string, then trap.\n ///\n /// If `i` is UTF-16 encoded, but `self` is an UTF-8 string, then transcode\n /// `i`'s offset to UTF-8 and return the resulting index. This allows the use\n /// of indices from a bridged Cocoa string after the string has been converted\n /// to a native Swift string. (Such indices are technically still considered\n /// invalid, but we allow this specific case to keep compatibility with\n /// existing code that assumes otherwise.)\n ///\n /// Detecting an encoding mismatch isn't always possible -- older binaries did\n /// not set the flags that this method relies on. However, false positives\n /// cannot happen: if this method detects a mismatch, then it is guaranteed to\n /// be a real one.\n @_alwaysEmitIntoClient\n @inline(__always)\n internal func ensureMatchingEncoding(_ i: Index) -> Index {\n if _fastPath(hasMatchingEncoding(i)) { return i }\n return _slowEnsureMatchingEncoding(i)\n }\n\n @_alwaysEmitIntoClient\n @inline(never)\n @_effects(releasenone)\n internal func _slowEnsureMatchingEncoding(_ i: Index) -> Index {\n // Attempt to recover from mismatched encodings between a string and its\n // index.\n\n if isUTF8 {\n // Attempt to use an UTF-16 index on a UTF-8 string.\n //\n // This can happen if `self` was originally verbatim-bridged, and someone\n // mistakenly attempts to keep using an old index after a mutation. This\n // is technically an error, but trapping here would trigger a lot of\n // broken code that previously happened to work "fine" on e.g. ASCII\n // strings. Instead, attempt to convert the offset to UTF-8 code units by\n // transcoding the string. This can be slow, but it often results in a\n // usable index, even if non-ASCII characters are present. (UTF-16\n // breadcrumbs help reduce the severity of the slowdown.)\n\n // FIXME: Consider emitting a runtime warning here.\n // FIXME: Consider performing a linked-on-or-after check & trapping if the\n // client executable was built on some particular future Swift release.\n let utf16 = String.UTF16View(self)\n var r = utf16.index(utf16.startIndex, offsetBy: i._encodedOffset)\n if i.transcodedOffset != 0 {\n r = r.encoded(offsetBy: i.transcodedOffset)\n } else {\n // Preserve alignment bits if possible.\n r = r._copyingAlignment(from: i)\n }\n return r._knownUTF8\n }\n\n // Attempt to use an UTF-8 index on a UTF-16 string. This is rarer, but it\n // can still happen when e.g. people apply an index they got from\n // `AttributedString` on the original (bridged) string that they constructed\n // it from.\n let utf8 = String.UTF8View(self)\n var r = utf8.index(utf8.startIndex, offsetBy: i._encodedOffset)\n if i.transcodedOffset != 0 {\n r = r.encoded(offsetBy: i.transcodedOffset)\n } else {\n // Preserve alignment bits if possible.\n r = r._copyingAlignment(from: i)\n }\n return r._knownUTF16\n }\n}\n\n#if _runtime(_ObjC)\nextension _StringGuts {\n\n private static var _associationKey: UnsafeRawPointer {\n struct AssociationKey {}\n // We never dereference this, we only use this address as a unique key\n return unsafe unsafeBitCast(\n ObjectIdentifier(AssociationKey.self),\n to: UnsafeRawPointer.self\n )\n }\n\n private func _getAssociatedStorage() -> __StringStorage? {\n _internalInvariant(_object.hasObjCBridgeableObject)\n let getter = unsafe unsafeBitCast(\n getGetAssociatedObjectPtr(),\n to: (@convention(c)(\n AnyObject,\n UnsafeRawPointer\n ) -> UnsafeRawPointer?).self\n )\n\n if let assocPtr = unsafe getter(\n _object.objCBridgeableObject,\n Self._associationKey\n ) {\n let storage: __StringStorage\n storage = unsafe Unmanaged.fromOpaque(assocPtr).takeUnretainedValue()\n return storage\n }\n return nil\n }\n\n private func _setAssociatedStorage(_ storage: __StringStorage) {\n _internalInvariant(_object.hasObjCBridgeableObject)\n let setter = unsafe unsafeBitCast(\n getSetAssociatedObjectPtr(),\n to: (@convention(c)(\n AnyObject,\n UnsafeRawPointer,\n AnyObject?,\n UInt\n ) -> Void).self\n )\n\n unsafe setter(\n _object.objCBridgeableObject,\n Self._associationKey,\n storage,\n 1 //OBJC_ASSOCIATION_RETAIN_NONATOMIC\n )\n }\n\n internal func _getOrAllocateAssociatedStorage() -> __StringStorage {\n _internalInvariant(_object.hasObjCBridgeableObject)\n let unwrapped: __StringStorage\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 storage = _getAssociatedStorage() {\n unwrapped = storage\n } else {\n let lock = _object.objCBridgeableObject\n objc_sync_enter(lock)\n if let storage = _getAssociatedStorage() {\n unwrapped = storage\n } else {\n var contents = String.UnicodeScalarView()\n // always reserve a capacity larger than a small string\n contents.reserveCapacity(\n Swift.max(_SmallString.capacity + 1, count + count >> 1)\n )\n for c in String.UnicodeScalarView(self) {\n contents.append(c)\n }\n _precondition(contents._guts._object.hasNativeStorage)\n unwrapped = (consume contents)._guts._object.nativeStorage\n _setAssociatedStorage(unwrapped)\n }\n defer { _fixLifetime(unwrapped) }\n objc_sync_exit(lock)\n }\n return unwrapped\n }\n}\n#endif\n\n// Old SPI(corelibs-foundation)\nextension _StringGuts {\n public // SPI(corelibs-foundation)\n var _isContiguousASCII: Bool {\n return !isSmall && isFastUTF8 && isASCII\n }\n\n // FIXME: Previously used by swift-corelibs-foundation. Aging for removal.\n @available(*, unavailable)\n public var _isContiguousUTF16: Bool {\n return false\n }\n\n // FIXME: Mark as obsoleted. Still used by swift-corelibs-foundation.\n @available(*, deprecated)\n public var startASCII: UnsafeMutablePointer<UInt8> {\n return unsafe UnsafeMutablePointer(mutating: _object.fastUTF8.baseAddress!)\n }\n\n // FIXME: Previously used by swift-corelibs-foundation. Aging for removal.\n @available(*, unavailable)\n public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> {\n fatalError("Not contiguous UTF-16")\n }\n}\n\n// FIXME: Previously used by swift-corelibs-foundation. Aging for removal.\n@available(*, unavailable)\npublic func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? {\n guard let s = unsafe p else { return nil }\n let bytesToCopy = unsafe UTF8._nullCodeUnitOffset(in: s) + 1 // +1 for the terminating NUL\n let result = unsafe [CChar](unsafeUninitializedCapacity: bytesToCopy) { buf, initedCount in\n unsafe buf.baseAddress!.update(from: s, count: bytesToCopy)\n initedCount = bytesToCopy\n }\n return result\n}\n\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringGuts.swift
cpp_apple_swift_stdlib_public_core_StringGuts.swift
Swift
17,136
0.95
0.095588
0.235908
awesome-app
501
2023-08-28T20:16:59.051069
MIT
false
8b4469a5d41ee6b04fbc113248f2d9a3
//===----------------------------------------------------------------------===//\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// COW helpers\nextension _StringGuts {\n internal var nativeCapacity: Int? {\n @inline(never)\n @_effects(releasenone)\n get {\n guard hasNativeStorage else { return nil }\n return _object.withNativeStorage { $0.capacity }\n }\n }\n\n internal var nativeUnusedCapacity: Int? {\n @inline(never)\n @_effects(releasenone)\n get {\n guard hasNativeStorage else { return nil }\n return _object.withNativeStorage { $0.unusedCapacity }\n }\n }\n\n // If natively stored and uniquely referenced, return the storage's total\n // capacity. Otherwise, nil.\n internal var uniqueNativeCapacity: Int? {\n @inline(never)\n @_effects(releasenone)\n mutating get {\n guard isUniqueNative else { return nil }\n return _object.withNativeStorage { $0.capacity }\n }\n }\n\n // If natively stored and uniquely referenced, return the storage's spare\n // capacity. Otherwise, nil.\n internal var uniqueNativeUnusedCapacity: Int? {\n @inline(never)\n @_effects(releasenone)\n mutating get {\n guard isUniqueNative else { return nil }\n return _object.withNativeStorage { $0.unusedCapacity }\n }\n }\n\n @usableFromInline // @testable\n internal var isUniqueNative: Bool {\n @inline(__always) mutating get {\n // Note: mutating so that self is `inout`.\n guard hasNativeStorage else { return false }\n defer { _fixLifetime(self) }\n var bits: UInt = _object.largeAddressBits\n return _isUnique_native(&bits)\n }\n }\n}\n\n// Range-replaceable operation support\nextension _StringGuts {\n @inline(__always)\n internal mutating func updateNativeStorage<R>(\n _ body: (__StringStorage) -> R\n ) -> R {\n let (r, cf) = self._object.withNativeStorage {\n let r = body($0)\n let cf = $0._countAndFlags\n return (r, cf)\n }\n // We need to pick up new count/flags from the modified storage.\n self._object._setCountAndFlags(to: cf)\n return r\n }\n\n @inlinable\n internal init(_initialCapacity capacity: Int) {\n self.init()\n if _slowPath(capacity > _SmallString.capacity) {\n self.grow(capacity) // TODO: no factor should be applied\n }\n }\n\n internal mutating func reserveCapacity(_ n: Int) {\n // Check if there's nothing to do\n if n <= _SmallString.capacity { return }\n if let currentCap = self.uniqueNativeCapacity, currentCap >= n { return }\n\n // Grow\n self.grow(n) // TODO: no factor should be applied\n }\n\n // Grow to accommodate at least `n` code units\n @usableFromInline\n internal mutating func grow(_ n: Int) {\n defer {\n self._invariantCheck()\n _internalInvariant(\n self.uniqueNativeCapacity != nil && self.uniqueNativeCapacity! >= n)\n }\n\n _internalInvariant(\n self.uniqueNativeCapacity == nil || self.uniqueNativeCapacity! < n)\n\n // If unique and native, apply a 2x growth factor to avoid problematic\n // performance when used in a loop. If one if those doesn't apply, we\n // can just use the requested capacity (at least the current utf-8 count).\n // TODO: Don't do this! Growth should only happen for append...\n let growthTarget: Int\n if let capacity = self.uniqueNativeCapacity {\n growthTarget = Swift.max(n, capacity * 2)\n } else {\n growthTarget = Swift.max(n, self.utf8Count)\n }\n\n // `isFastUTF8` is not the same as `isNative`. It can include small\n // strings or foreign strings that provide contiguous UTF-8 access.\n if _fastPath(isFastUTF8) {\n let isASCII = self.isASCII\n let storage = unsafe self.withFastUTF8 {\n unsafe __StringStorage.create(\n initializingFrom: $0,\n codeUnitCapacity: growthTarget,\n isASCII: isASCII)\n }\n\n self = _StringGuts(storage)\n return\n }\n\n _foreignGrow(growthTarget)\n }\n\n @inline(never) // slow-path\n private mutating func _foreignGrow(_ n: Int) {\n let newString = unsafe String(_uninitializedCapacity: n) { buffer in\n guard let count = unsafe _foreignCopyUTF8(into: buffer) else {\n fatalError("String capacity was smaller than required")\n }\n return count\n }\n self = newString._guts\n }\n\n // Ensure unique native storage with sufficient capacity for the following\n // append.\n private mutating func prepareForAppendInPlace(\n totalCount: Int,\n otherUTF8Count otherCount: Int\n ) {\n defer {\n _internalInvariant(self.uniqueNativeUnusedCapacity != nil,\n "growth should produce uniqueness")\n _internalInvariant(self.uniqueNativeUnusedCapacity! >= otherCount,\n "growth should produce enough capacity")\n }\n\n // See if we can accommodate without growing or copying. If we have\n // sufficient capacity, we do not need to grow, and we can skip the copy if\n // unique. Otherwise, growth is required.\n let sufficientCapacity: Bool\n if let unused = self.nativeUnusedCapacity, unused >= otherCount {\n sufficientCapacity = true\n } else {\n sufficientCapacity = false\n }\n\n if self.isUniqueNative && sufficientCapacity {\n return\n }\n\n // If we have to resize anyway, and we fit in smol, we should have made one\n _internalInvariant(totalCount > _SmallString.capacity)\n\n // Non-unique storage: just make a copy of the appropriate size, otherwise\n // grow like an array.\n let growthTarget: Int\n if sufficientCapacity {\n growthTarget = totalCount\n } else {\n growthTarget = Swift.max(\n totalCount, _growArrayCapacity(nativeCapacity ?? 0))\n }\n self.grow(growthTarget) // NOTE: this already has exponential growth...\n }\n\n internal mutating func append(_ other: _StringGuts) {\n if self.isSmall && other.isSmall {\n if let smol = _SmallString(self.asSmall, appending: other.asSmall) {\n self = _StringGuts(smol)\n return\n }\n }\n append(_StringGutsSlice(other))\n }\n\n @inline(never)\n @_effects(readonly)\n private func _foreignConvertedToSmall() -> _SmallString {\n let smol = unsafe String(_uninitializedCapacity: _SmallString.capacity) { buffer in\n guard let count = unsafe _foreignCopyUTF8(into: buffer) else {\n fatalError("String capacity was smaller than required")\n }\n return count\n }\n _internalInvariant(smol._guts.isSmall)\n return smol._guts.asSmall\n }\n\n private func _convertedToSmall() -> _SmallString {\n _internalInvariant(utf8Count <= _SmallString.capacity)\n if _fastPath(isSmall) {\n return asSmall\n }\n if isFastUTF8 {\n return unsafe withFastUTF8 { unsafe _SmallString($0)! }\n }\n return _foreignConvertedToSmall()\n }\n\n internal mutating func append(_ slicedOther: _StringGutsSlice) {\n defer { self._invariantCheck() }\n\n let otherCount = slicedOther.utf8Count\n\n let totalCount = utf8Count + otherCount\n\n /*\n Goal: determine if we need to allocate new native capacity\n Possible scenarios in which we need to allocate:\n • Not uniquely owned and native: we can't use the capacity to grow into,\n have to become unique + native by allocating\n • Not enough capacity: have to allocate to grow\n\n Special case: a non-smol String that can fit in a smol String but doesn't\n meet the above criteria shouldn't throw away its buffer just to be smol.\n The reasoning here is that it may be bridged or have reserveCapacity'd\n in preparation for appending more later, in which case we would end up\n have to allocate anyway to convert back from smol.\n\n If we would have to re-allocate anyway then that's not a problem and we\n should just be smol.\n\n e.g. consider\n var str = "" // smol\n str.reserveCapacity(100) // large native unique\n str += "<html>" // don't convert back to smol here!\n str += htmlContents // because this would have to anyway!\n */\n let hasEnoughUsableSpace = isUniqueNative &&\n nativeUnusedCapacity! >= otherCount\n let shouldBeSmol = totalCount <= _SmallString.capacity &&\n (isSmall || !hasEnoughUsableSpace)\n\n if shouldBeSmol {\n let smolSelf = _convertedToSmall()\n let smolOther = String(Substring(slicedOther))._guts._convertedToSmall()\n // TODO: In-register slicing\n self = _StringGuts(_SmallString(smolSelf, appending: smolOther)!)\n return\n }\n\n prepareForAppendInPlace(totalCount: totalCount, otherUTF8Count: otherCount)\n\n if slicedOther.isFastUTF8 {\n let otherIsASCII = slicedOther.isASCII\n unsafe slicedOther.withFastUTF8 { otherUTF8 in\n unsafe self.appendInPlace(otherUTF8, isASCII: otherIsASCII)\n }\n return\n }\n\n _foreignAppendInPlace(slicedOther)\n }\n\n internal mutating func appendInPlace(\n _ other: UnsafeBufferPointer<UInt8>, isASCII: Bool\n ) {\n updateNativeStorage { unsafe $0.appendInPlace(other, isASCII: isASCII) }\n }\n\n @inline(never) // slow-path\n private mutating func _foreignAppendInPlace(_ other: _StringGutsSlice) {\n _internalInvariant(!other.isFastUTF8)\n _internalInvariant(self.uniqueNativeUnusedCapacity != nil)\n\n var iter = Substring(other).utf8.makeIterator()\n updateNativeStorage { $0.appendInPlace(&iter, isASCII: other.isASCII) }\n }\n\n internal mutating func clear() {\n guard isUniqueNative else {\n self = _StringGuts()\n return\n }\n\n // Reset the count\n updateNativeStorage { $0.clear() }\n }\n\n internal mutating func remove(from lower: Index, to upper: Index) {\n let lowerOffset = lower._encodedOffset\n let upperOffset = upper._encodedOffset\n _internalInvariant(lower.transcodedOffset == 0 && upper.transcodedOffset == 0)\n _internalInvariant(lowerOffset <= upperOffset && upperOffset <= self.count)\n\n if isUniqueNative {\n updateNativeStorage { $0.remove(from: lowerOffset, to: upperOffset) }\n return\n }\n\n // TODO(cleanup): Add append on guts taking range, use that\n var result = String()\n // FIXME: It should be okay to get rid of excess capacity\n // here. rdar://problem/45635432\n result.reserveCapacity(\n nativeCapacity ?? (count &- (upperOffset &- lowerOffset)))\n result.append(contentsOf: String(self)[..<lower])\n result.append(contentsOf: String(self)[upper...])\n self = result._guts\n }\n\n // - Returns: The encoded offset range of the replaced contents in the result.\n @discardableResult\n internal mutating func replaceSubrange<C>(\n _ bounds: Range<Index>,\n with newElements: C\n ) -> Range<Int>\n where C: Collection, C.Iterator.Element == Character {\n if isUniqueNative {\n if let repl = newElements as? String {\n if repl._guts.isFastUTF8 {\n return unsafe repl._guts.withFastUTF8 {\n unsafe uniqueNativeReplaceSubrange(\n bounds, with: $0, isASCII: repl._guts.isASCII)\n }\n }\n } else if let repl = newElements as? Substring {\n if repl._wholeGuts.isFastUTF8 {\n return unsafe repl._wholeGuts.withFastUTF8(range: repl._offsetRange) {\n unsafe uniqueNativeReplaceSubrange(\n bounds, with: $0, isASCII: repl._wholeGuts.isASCII)\n }\n }\n }\n return uniqueNativeReplaceSubrange(\n bounds, with: newElements.lazy.flatMap { $0.utf8 })\n }\n\n var result = String()\n // FIXME: It should be okay to get rid of excess capacity\n // here. rdar://problem/45635432\n if let capacity = self.nativeCapacity {\n result.reserveCapacity(capacity)\n }\n let selfStr = String(self)\n result.append(contentsOf: selfStr[..<bounds.lowerBound])\n let i = result._guts.count\n result.append(contentsOf: newElements)\n let j = result._guts.count\n result.append(contentsOf: selfStr[bounds.upperBound...])\n self = result._guts\n return unsafe Range(_uncheckedBounds: (i, j))\n }\n\n // - Returns: The encoded offset range of the replaced contents in the result.\n @discardableResult\n internal mutating func replaceSubrange<C>(\n _ bounds: Range<Index>,\n with newElements: C\n ) -> Range<Int>\n where C: Collection, C.Iterator.Element == UnicodeScalar {\n if isUniqueNative {\n if let repl = newElements as? String.UnicodeScalarView {\n if repl._guts.isFastUTF8 {\n return unsafe repl._guts.withFastUTF8 {\n unsafe uniqueNativeReplaceSubrange(\n bounds, with: $0, isASCII: repl._guts.isASCII)\n }\n }\n } else if let repl = newElements as? Substring.UnicodeScalarView {\n if repl._wholeGuts.isFastUTF8 {\n return unsafe repl._wholeGuts.withFastUTF8(range: repl._offsetRange) {\n unsafe uniqueNativeReplaceSubrange(\n bounds, with: $0, isASCII: repl._wholeGuts.isASCII)\n }\n }\n }\n if #available(SwiftStdlib 5.1, *) {\n return uniqueNativeReplaceSubrange(\n bounds, with: newElements.lazy.flatMap { $0.utf8 })\n } else {\n // FIXME: The stdlib should not have a deployment target this ancient.\n let c = newElements.reduce(0) { $0 + UTF8.width($1) }\n var utf8: [UInt8] = []\n utf8.reserveCapacity(c)\n utf8 = newElements.reduce(into: utf8) { utf8, next in\n next.withUTF8CodeUnits { unsafe utf8.append(contentsOf: $0) }\n }\n return uniqueNativeReplaceSubrange(bounds, with: utf8)\n }\n }\n\n var result = String.UnicodeScalarView()\n // FIXME: It should be okay to get rid of excess capacity\n // here. rdar://problem/45635432\n if let capacity = self.nativeCapacity {\n result.reserveCapacity(capacity)\n }\n let selfStr = String.UnicodeScalarView(self)\n result.append(contentsOf: selfStr[..<bounds.lowerBound])\n let i = result._guts.count\n result.append(contentsOf: newElements)\n let j = result._guts.count\n result.append(contentsOf: selfStr[bounds.upperBound...])\n self = result._guts\n return unsafe Range(_uncheckedBounds: (i, j))\n }\n\n // - Returns: The encoded offset range of the replaced contents in the result.\n internal mutating func uniqueNativeReplaceSubrange(\n _ bounds: Range<Index>,\n with codeUnits: UnsafeBufferPointer<UInt8>,\n isASCII: Bool\n ) -> Range<Int> {\n let neededCapacity =\n bounds.lowerBound._encodedOffset\n + codeUnits.count + (self.count - bounds.upperBound._encodedOffset)\n reserveCapacity(neededCapacity)\n\n _internalInvariant(bounds.lowerBound.transcodedOffset == 0)\n _internalInvariant(bounds.upperBound.transcodedOffset == 0)\n\n let start = bounds.lowerBound._encodedOffset\n let end = bounds.upperBound._encodedOffset\n updateNativeStorage {\n unsafe $0.replace(from: start, to: end, with: codeUnits)\n }\n return unsafe Range(_uncheckedBounds: (start, start + codeUnits.count))\n }\n\n // - Returns: The encoded offset range of the replaced contents in the result.\n internal mutating func uniqueNativeReplaceSubrange<C: Collection>(\n _ bounds: Range<Index>,\n with codeUnits: C\n ) -> Range<Int>\n where C.Element == UInt8 {\n let replCount = codeUnits.count\n\n let neededCapacity =\n bounds.lowerBound._encodedOffset\n + replCount + (self.count - bounds.upperBound._encodedOffset)\n reserveCapacity(neededCapacity)\n\n _internalInvariant(bounds.lowerBound.transcodedOffset == 0)\n _internalInvariant(bounds.upperBound.transcodedOffset == 0)\n\n let start = bounds.lowerBound._encodedOffset\n let end = bounds.upperBound._encodedOffset\n updateNativeStorage {\n $0.replace(\n from: start, to: end, with: codeUnits, replacementCount: replCount)\n }\n return unsafe Range(_uncheckedBounds: (start, start + replCount))\n }\n\n /// Run `body` to mutate the given `subrange` of this string within\n /// `startIndex ..< endIndex`, then update `startIndex` and `endIndex` to be\n /// valid positions in the resulting string, addressing the same (logical)\n /// locations as in the original string.\n ///\n /// This is used by both `Substring` and `Substring.UnicodeScalarView` to\n /// implement their `replaceSubrange` methods.\n ///\n /// - Parameter subrange: A scalar-aligned offset range in this string.\n /// - Parameter startIndex: The start index of the substring that performs\n /// this operation.\n /// - Parameter endIndex: The end index of the substring that performs this\n /// operations.\n /// - Parameter body: The mutation operation to execute on `self`. The\n /// returned offset range must correspond to `subrange` in the resulting\n /// string.\n internal mutating func mutateSubrangeInSubstring(\n subrange: Range<Index>,\n startIndex: inout Index,\n endIndex: inout Index,\n with body: (inout _StringGuts) -> Range<Int>\n ) {\n _internalInvariant(\n subrange.lowerBound >= startIndex && subrange.upperBound <= endIndex)\n\n guard _fastPath(isUTF8) else {\n // UTF-16 string. The mutation will convert this to the native UTF-8\n // encoding, so we need to do some extra work to preserve our bounds.\n let utf8StartOffset = String(self).utf8.distance(\n from: self.startIndex, to: startIndex)\n let oldUTF8Count = String(self).utf8.distance(\n from: startIndex, to: endIndex)\n\n let oldUTF8SubrangeCount = String(self).utf8.distance(\n from: subrange.lowerBound, to: subrange.upperBound)\n\n let newUTF8Subrange = body(&self)\n _internalInvariant(isUTF8)\n\n let newUTF8Count =\n oldUTF8Count + newUTF8Subrange.count - oldUTF8SubrangeCount\n\n var newStride = 0\n\n if !newUTF8Subrange.isEmpty {\n // Get the character stride in the entire string, not just the substring.\n // (Characters in a substring may end beyond the bounds of it.)\n newStride = _opaqueCharacterStride(startingAt: utf8StartOffset)\n }\n\n startIndex = String.Index(\n encodedOffset: utf8StartOffset,\n transcodedOffset: 0,\n characterStride: newStride)._scalarAligned._knownUTF8\n if isOnGraphemeClusterBoundary(startIndex) {\n startIndex = startIndex._characterAligned\n }\n\n endIndex = String.Index(\n encodedOffset: utf8StartOffset + newUTF8Count,\n transcodedOffset: 0)._scalarAligned._knownUTF8\n return\n }\n\n // UTF-8 string.\n\n let oldRange = subrange._encodedOffsetRange\n let newRange = body(&self)\n\n let oldBounds = unsafe Range(\n _uncheckedBounds: (startIndex._encodedOffset, endIndex._encodedOffset))\n let newBounds = unsafe Range(_uncheckedBounds: (\n oldBounds.lowerBound,\n oldBounds.upperBound &+ newRange.count &- oldRange.count))\n\n // Update `startIndex` if necessary. The replacement may have invalidated\n // its cached character stride and character alignment flag, but not its\n // stored offset, encoding, or scalar alignment.\n //\n // We are exploiting the fact that mutating the string _after_ the scalar\n // following the end of the character at `startIndex` cannot possibly change\n // the length of that character. (This is true because `index(after:)` never\n // needs to look ahead by more than one Unicode scalar.)\n let oldStride = startIndex.characterStride ?? 0\n if oldRange.lowerBound <= oldBounds.lowerBound &+ oldStride {\n var newStride = 0\n\n if !newBounds.isEmpty {\n // Get the character stride in the entire string, not just the substring.\n // (Characters in a substring may end beyond the bounds of it.)\n newStride = _opaqueCharacterStride(startingAt: newBounds.lowerBound)\n }\n\n var newStart = String.Index(\n encodedOffset: newBounds.lowerBound,\n characterStride: newStride\n )._scalarAligned._knownUTF8\n\n // Preserve character alignment flag if possible\n if startIndex._isCharacterAligned,\n (oldRange.lowerBound > oldBounds.lowerBound ||\n isOnGraphemeClusterBoundary(newStart)) {\n newStart = newStart._characterAligned\n }\n\n startIndex = newStart\n }\n\n // Update `endIndex`.\n if newBounds.upperBound != endIndex._encodedOffset {\n endIndex = Index(\n _encodedOffset: newBounds.upperBound\n )._scalarAligned._knownUTF8\n }\n }\n}\n\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringGutsRangeReplaceable.swift
cpp_apple_swift_stdlib_public_core_StringGutsRangeReplaceable.swift
Swift
20,497
0.95
0.077966
0.16441
awesome-app
766
2024-10-12T01:37:25.016047
Apache-2.0
false
c2617fa9aec8d263295fc5e2e911671a
//===----------------------------------------------------------------------===//\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// TODO(String performance): Unfortunately, this slice struct seems to add\n// overhead. We may want to wean ourselves off of this and have all users just\n// also store a range.\n\n// A sliced _StringGuts, convenient for unifying String/Substring comparison,\n// hashing, and RRC.\ninternal struct _StringGutsSlice {\n internal var _guts: _StringGuts\n\n internal var _offsetRange: Range<Int>\n\n @inline(__always)\n internal init(_ guts: _StringGuts) {\n self._guts = guts\n self._offsetRange = unsafe Range(_uncheckedBounds: (0, guts.count))\n }\n\n @inline(__always)\n internal init(_ guts: _StringGuts, _ offsetRange: Range<Int>) {\n _internalInvariant(\n offsetRange.lowerBound >= 0 && offsetRange.upperBound <= guts.count)\n self._guts = guts\n self._offsetRange = offsetRange\n }\n\n internal var start: Int {\n @inline(__always) get { return _offsetRange.lowerBound }\n }\n\n internal var end: Int {\n @inline(__always) get { return _offsetRange.upperBound }\n }\n\n internal var count: Int {\n @inline(__always) get { return _offsetRange.count }\n }\n\n internal var isNFCFastUTF8: Bool {\n @inline(__always) get { return _guts.isNFCFastUTF8 }\n }\n\n internal var isASCII: Bool {\n @inline(__always) get { return _guts.isASCII }\n }\n\n internal var isFastUTF8: Bool {\n @inline(__always) get { return _guts.isFastUTF8 }\n }\n\n internal var utf8Count: Int {\n @inline(__always) get {\n if _fastPath(self.isFastUTF8) {\n return _offsetRange.count\n }\n return Substring(self).utf8.count\n }\n }\n\n internal var range: Range<String.Index> {\n @inline(__always) get {\n let lower = String.Index(_encodedOffset: _offsetRange.lowerBound)\n ._scalarAligned\n let higher = String.Index(_encodedOffset: _offsetRange.upperBound)\n ._scalarAligned\n return unsafe Range(_uncheckedBounds: (lower, higher))\n }\n }\n\n @inline(__always)\n internal func withFastUTF8<R>(\n _ f: (UnsafeBufferPointer<UInt8>) throws -> R\n ) rethrows -> R {\n return try unsafe _guts.withFastUTF8(range: _offsetRange, f)\n }\n\n @_effects(releasenone)\n internal func foreignErrorCorrectedScalar(\n startingAt idx: String.Index\n ) -> (Unicode.Scalar, scalarLength: Int) {\n let (scalar, len) = _guts.foreignErrorCorrectedScalar(startingAt: idx)\n if _slowPath(idx.encoded(offsetBy: len) > range.upperBound) { \n return (Unicode.Scalar._replacementCharacter, 1)\n }\n return (scalar, len)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringGutsSlice.swift
cpp_apple_swift_stdlib_public_core_StringGutsSlice.swift
Swift
2,971
0.8
0.061224
0.192771
react-lib
540
2024-12-14T10:39:20.214739
GPL-3.0
false
a6205d2467b1668443632705db2479de
//===----------------------------------------------------------------------===//\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\nextension String: 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 public func hash(into hasher: inout Hasher) {\n if _fastPath(self._guts.isNFCFastUTF8) {\n unsafe self._guts.withFastUTF8 {\n unsafe hasher.combine(bytes: UnsafeRawBufferPointer($0))\n }\n hasher.combine(0xFF as UInt8) // terminator\n } else {\n _gutsSlice._normalizedHash(into: &hasher)\n }\n }\n}\n\nextension StringProtocol {\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 @_specialize(where Self == String)\n @_specialize(where Self == Substring)\n public func hash(into hasher: inout Hasher) {\n _gutsSlice._normalizedHash(into: &hasher)\n }\n}\n\nextension _StringGutsSlice {\n @_effects(releasenone) @inline(never) // slow-path\n internal func _normalizedHash(into hasher: inout Hasher) {\n if self.isNFCFastUTF8 {\n unsafe self.withFastUTF8 {\n unsafe hasher.combine(bytes: UnsafeRawBufferPointer($0))\n }\n } else {\n _withNFCCodeUnits {\n hasher.combine($0)\n }\n }\n hasher.combine(0xFF as UInt8) // terminator\n }\n}\n\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringHashable.swift
cpp_apple_swift_stdlib_public_core_StringHashable.swift
Swift
1,920
0.95
0.065574
0.375
awesome-app
921
2024-11-03T17:25:15.034495
GPL-3.0
false
2c1cea5de4ec0c6ab2a20d4a1cf120be
//===--- StringIndex.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/*\n\nString's Index has the following layout:\n\n ┌──────────┬────────────────╥────────────────┬───────╥───────┐\n │ b63:b16 │ b15:b14 ║ b13:b8 │ b7:b4 ║ b3:b0 │\n ├──────────┼────────────────╫────────────────┼───────╫───────┤\n │ position │ transc. offset ║ grapheme cache │ rsvd ║ flags │\n └──────────┴────────────────╨────────────────┴───────╨───────┘\n └────── resilient ───────┘\n\nPosition, transcoded offset, and flags are fully exposed in the ABI. Grapheme\ncache and reserved bits are partially resilient: the fact that there are 11 bits\nwith a default value of `0` is ABI, but not the layout, construction, or\ninterpretation of those bits. All use of grapheme cache should be behind\nnon-inlinable function calls. Inlinable code should not set a non-zero value to\nresilient bits: doing so breaks future evolution as the meaning of those bits\nisn't frozen.\n\n- position aka `encodedOffset`: A 48-bit offset into the string's code units\n\n- transcoded offset: a 2-bit sub-scalar offset, derived from transcoding\n\n<resilience barrier>\n\n- grapheme cache: A 6-bit value remembering the distance to the next extended\n grapheme cluster boundary, or 0 if unknown. The value stored (if any) must be\n calculated assuming that the index addresses a boundary itself, i.e., without\n looking back at scalars preceding the index. (Substrings that don't start on a\n `Character` boundary heavily rely on this.)\n\n- reserved: 4 unused bits available for future flags etc. The meaning of each\n bit may change between stdlib versions. These must be set to zero if\n constructing an index in inlinable code.\n\n<resilience barrier>\n\n * b0: `_isScalarAligned`\n\n If set, index is known to be on a Unicode scalar boundary (see below).\n (Introduced in Swift 5.1)\n\n * b1: `_isCharacterAligned`\n\n If set, the index is known to be on an extended grapheme cluster\n boundary (i.e., on a Swift `Character`.)\n (Introduced in Swift 5.7)\n\n * b2: UTF-8 encoding\n\n If set, the position is known to be expressed in UTF-8 code units.\n (Introduced in Swift 5.7)\n\n * b3: UTF-16 encoding\n\n If set, the position is known to be expressed in UTF-16 code units.\n (Introduced in Swift 5.7)\n\nBefore Swift 5.7, bits b1, b2 and b3 used to be part of the resilient slice. See\nthe notes on Character Alignment and Index Encoding below to see how this works.\n\n*/\nextension String {\n /// A position of a character or code unit in a string.\n @frozen\n public struct Index: Sendable {\n @usableFromInline\n internal var _rawBits: UInt64\n\n @inlinable @inline(__always)\n init(_ raw: UInt64) {\n self._rawBits = raw\n self._invariantCheck()\n }\n }\n}\n\nextension String.Index {\n @inlinable @inline(__always)\n internal var orderingValue: UInt64 { return _rawBits &>> 14 }\n\n // Whether this is at the canonical "start" position, that is encoded AND\n // transcoded offset of 0.\n @inlinable @inline(__always)\n internal var isZeroPosition: Bool { return orderingValue == 0 }\n\n /// The UTF-16 code unit offset corresponding to this index.\n public func utf16Offset<S: StringProtocol>(in s: S) -> Int {\n return s.utf16.distance(from: s.utf16.startIndex, to: self)\n }\n\n /// The offset into a string's code units for this index.\n @available(swift, deprecated: 4.2, message: """\n encodedOffset has been deprecated as most common usage is incorrect. \\n Use utf16Offset(in:) to achieve the same behavior.\n """)\n @inlinable\n public var encodedOffset: Int { return _encodedOffset }\n\n @inlinable @inline(__always)\n internal var _encodedOffset: Int {\n return Int(truncatingIfNeeded: _rawBits &>> 16)\n }\n\n @inlinable @inline(__always)\n internal var transcodedOffset: Int {\n return Int(truncatingIfNeeded: orderingValue & 0x3)\n }\n\n @usableFromInline\n internal var characterStride: Int? {\n let value = (_rawBits & 0x3F00) &>> 8\n return value > 0 ? Int(truncatingIfNeeded: value) : nil\n }\n\n @inlinable @inline(__always)\n internal init(encodedOffset: Int, transcodedOffset: Int) {\n let pos = UInt64(truncatingIfNeeded: encodedOffset)\n let trans = UInt64(truncatingIfNeeded: transcodedOffset)\n _internalInvariant(pos == pos & 0x0000_FFFF_FFFF_FFFF)\n _internalInvariant(trans <= 3)\n\n self.init((pos &<< 16) | (trans &<< 14))\n }\n\n /// Creates a new index at the specified UTF-16 code unit offset\n ///\n /// - Parameter offset: An offset in UTF-16 code units.\n public init<S: StringProtocol>(utf16Offset offset: Int, in s: S) {\n let (start, end) = (s.utf16.startIndex, s.utf16.endIndex)\n guard offset >= 0,\n let idx = s.utf16.index(start, offsetBy: offset, limitedBy: end)\n else {\n self = end.nextEncoded\n return\n }\n self = idx\n }\n\n /// Creates a new index at the specified code unit offset.\n ///\n /// - Parameter offset: An offset in code units.\n @available(swift, deprecated: 4.2, message: """\n encodedOffset has been deprecated as most common usage is incorrect. \\n Use String.Index(utf16Offset:in:) to achieve the same behavior.\n """)\n @inlinable\n public init(encodedOffset offset: Int) {\n self.init(_encodedOffset: offset)\n }\n\n @inlinable @inline(__always)\n internal init(_encodedOffset offset: Int) {\n self.init(encodedOffset: offset, transcodedOffset: 0)\n }\n\n @usableFromInline\n internal init(\n encodedOffset: Int, transcodedOffset: Int, characterStride: Int\n ) {\n self.init(encodedOffset: encodedOffset, transcodedOffset: transcodedOffset)\n if _slowPath(characterStride > 0x3F) { return }\n self._rawBits |= UInt64(truncatingIfNeeded: characterStride &<< 8)\n self._invariantCheck()\n }\n\n @usableFromInline\n internal init(encodedOffset pos: Int, characterStride char: Int) {\n self.init(encodedOffset: pos, transcodedOffset: 0, characterStride: char)\n }\n\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(_encodedOffset >= 0)\n if self._isCharacterAligned {\n _internalInvariant(_isScalarAligned)\n }\n if self._isScalarAligned {\n _internalInvariant_5_1(transcodedOffset == 0)\n }\n }\n #endif // INTERNAL_CHECKS_ENABLED\n}\n\n// Creation helpers, which will make migration easier if we decide to use and\n// propagate the reserved bits.\nextension String.Index {\n @inlinable @inline(__always)\n internal var strippingTranscoding: String.Index {\n return String.Index(_encodedOffset: self._encodedOffset)\n }\n\n @inlinable @inline(__always)\n internal var nextEncoded: String.Index {\n _internalInvariant(self.transcodedOffset == 0)\n return String.Index(_encodedOffset: self._encodedOffset &+ 1)\n }\n\n @inlinable @inline(__always)\n internal var priorEncoded: String.Index {\n _internalInvariant(self.transcodedOffset == 0)\n return String.Index(_encodedOffset: self._encodedOffset &- 1)\n }\n\n @inlinable @inline(__always)\n internal var nextTranscoded: String.Index {\n return String.Index(\n encodedOffset: self._encodedOffset,\n transcodedOffset: self.transcodedOffset &+ 1)\n }\n\n @inlinable @inline(__always)\n internal var priorTranscoded: String.Index {\n return String.Index(\n encodedOffset: self._encodedOffset,\n transcodedOffset: self.transcodedOffset &- 1)\n }\n\n\n // Get an index with an encoded offset relative to this one.\n // Note: strips any transcoded offset.\n @inlinable @inline(__always)\n internal func encoded(offsetBy n: Int) -> String.Index {\n return String.Index(_encodedOffset: self._encodedOffset &+ n)\n }\n\n @inlinable @inline(__always)\n internal func transcoded(withOffset n: Int) -> String.Index {\n _internalInvariant(self.transcodedOffset == 0)\n return String.Index(encodedOffset: self._encodedOffset, transcodedOffset: n)\n }\n}\n\nextension String.Index {\n @_alwaysEmitIntoClient @inline(__always) // Swift 5.7\n internal static var __scalarAlignmentBit: UInt64 { 0x1 }\n\n @_alwaysEmitIntoClient @inline(__always) // Swift 5.7\n internal static var __characterAlignmentBit: UInt64 { 0x2 }\n\n @_alwaysEmitIntoClient @inline(__always) // Swift 5.7\n internal static var __utf8Bit: UInt64 { 0x4 }\n\n @_alwaysEmitIntoClient @inline(__always) // Swift 5.7\n internal static var __utf16Bit: UInt64 { 0x8 }\n\n @_alwaysEmitIntoClient @inline(__always) // Swift 5.7\n internal static func __encodingBit(utf16: Bool) -> UInt64 {\n let utf16 = Int8(Builtin.zext_Int1_Int8(utf16._value))\n return __utf8Bit &<< utf16\n }\n}\n\n/*\n Index Scalar Alignment\n\n SE-0180 unifies the Index type of String and all its views and allows\n non-scalar-aligned indices to be used across views. In order to guarantee\n behavior, we often have to check and perform scalar alignment. To speed up\n these checks, we allocate a bit denoting known-to-be-scalar-aligned, so that\n the alignment check can skip the load. The below shows what views need to\n check for alignment before they can operate, and whether the indices they\n produce are aligned.\n\n ┌───────────────╥───────────────────────────┬─────────────────────────┐\n │ View ║ Requires Scalar Alignment │ Produces Scalar Aligned │\n ╞═══════════════╬═══════════════════════════╪═════════════════════════╡\n │ Native UTF8 ║ no │ no │\n ├───────────────╫───────────────────────────┼─────────────────────────┤\n │ Native UTF16 ║ yes │ no │\n ╞═══════════════╬═══════════════════════════╪═════════════════════════╡\n │ Foreign UTF8 ║ yes │ no │\n ├───────────────╫───────────────────────────┼─────────────────────────┤\n │ Foreign UTF16 ║ no │ no │\n ╞═══════════════╬═══════════════════════════╪═════════════════════════╡\n │ UnicodeScalar ║ yes │ yes │\n ├───────────────╫───────────────────────────┼─────────────────────────┤\n │ Character ║ yes │ yes │\n └───────────────╨───────────────────────────┴─────────────────────────┘\n\n The "requires scalar alignment" applies to any operation taking a String.Index\n that's not defined entirely in terms of other operations taking a\n String.Index. These include:\n\n * index(after:)\n * index(before:)\n * subscript\n * distance(from:to:) (since `to` is compared against directly)\n * UTF16View._nativeGetOffset(for:)\n\n*/\nextension String.Index {\n @_alwaysEmitIntoClient // Swift 5.1\n @inline(__always)\n internal var _isScalarAligned: Bool {\n 0 != _rawBits & Self.__scalarAlignmentBit\n }\n\n @_alwaysEmitIntoClient // Swift 5.1\n @inline(__always)\n internal var _scalarAligned: String.Index {\n var idx = self\n idx._rawBits |= Self.__scalarAlignmentBit\n idx._invariantCheck()\n return idx\n }\n}\n\n// ### Character (a.k.a. Extended Grapheme Cluster) Alignment\n//\n// Swift 5.7 assigned a new bit denoting that an index is known to be\n// `Character`-aligned. This is used to enable more reliable detection &\n// handling of extended grapheme cluster boundaries in indexing edge cases\n// introduced by SE-0180, without slowing down the usual case, when code isn't\n// interchanging indices between views.\n//\n// Beware! In substrings whose bounds aren't `Character`-aligned, extended\n// grapheme breaks are sometimes in different places than in their base string.\n// (The sequence of characters in a substring depend only on the Unicode scalars\n// that make up its contents, not on their surrounding context.) Therefore, such\n// substrings must not look at or set this bit: indices must be reliably\n// interchangeable between strings and their associated substrings, even if the\n// latter are irregular.\n//\n// Note that `startIndex` and `endIndex` have fully inlinable implementations.\n// This means that when code built on older releases runs on 5.7, this bit may\n// not be set on these, even though they are always `Character`-aligned. This is\n// fine -- `index(after:)` and `index(before:)` still do the right thing with\n// minimal/no performance loss. (The start/end index is handled specially.)\nextension String.Index {\n @_alwaysEmitIntoClient // Swift 5.7\n @inline(__always)\n internal var _isCharacterAligned: Bool {\n 0 != _rawBits & Self.__characterAlignmentBit\n }\n\n /// Return the same index with both the scalar- and `Character`-aligned bits\n /// set.\n ///\n /// (`Character` alignment implies scalar alignment.)\n @_alwaysEmitIntoClient // Swift 5.7\n @inline(__always)\n internal var _characterAligned: String.Index {\n let r = _rawBits | Self.__characterAlignmentBit | Self.__scalarAlignmentBit\n let idx = Self(r)\n idx._invariantCheck()\n return idx\n }\n}\n\nextension String.Index {\n @_alwaysEmitIntoClient // Swift 5.7\n internal func _copyingAlignment(from index: Self) -> Self {\n let mask = Self.__scalarAlignmentBit | Self.__characterAlignmentBit\n return Self((_rawBits & ~mask) | (index._rawBits & mask))\n }\n}\n\n// ### Index Encoding\n//\n// Swift 5.7 introduced bookkeeping to keep track of the Unicode encoding\n// associated with the position value in String indices. Indices whose position\n// is an offset into UTF-8 storage come with the corresponding flag set, and a\n// separate flag is set for UTF-16 indices. (Only foreign strings can be UTF-16\n// encoded. As of 5.7, all foreign strings are UTF-16; but this is subject to\n// change later if we ever decide to implement additional foreign forms.)\n//\n// In releases before 5.7, the bits corresponding to these flags were considered\n// reserved, and they were both set to zero in inlinable code. This means that\n// (on ABI stable platforms at least) we cannot assume that either of these bits\n// will be reliably set. If they are both clear, then we must fall back to\n// assuming that the index has the right encoding for whatever string it is used\n// on. However, if either of these bits are set, then the other bit's value is\n// also reliable -- whether it's set or cleared.\n//\n// The indices of ASCII strings are encoding-independent, i.e. transcoding such\n// strings from UTF-8 to UTF-16 (or vice versa) does not change the position\n// value of any of their indices. Therefore it isn't an error for an index to\n// have both of these flags set. (The start index of every string also behaves\n// this way: position zero is the same no matter how what encoding is used for\n// the rest of string.)\n//\n// These two bits (along with the isForeignUTF8 flag in StringObject) allow\n// newer versions of the Standard Library to more reliably catch runtime errors\n// where client code is applying an index from a UTF-16 string to a UTF-8 one,\n// or vice versa. This typically happens when indices from a UTF-16 Cocoa string\n// that was verbatim bridged into Swift are accidentally applied to a mutated\n// version of the same string. (The mutation turns it into a UTF-8 native\n// string, where the same numerical offsets might correspond to wildly different\n// logical positions.)\n//\n// Such code has always been broken, as the old indices are documented to be no\n// longer valid after the mutation; however, in previous releases such cases\n// weren't reliably detected, and if the code was only ever tested on ASCII\n// strings, then the bug could lie dormant for a long time. (Until the code\n// encounters a non-ASCII character and someone gets surprised that the results\n// no longer make sense.)\n//\n// As more code gets rebuilt with Swift 5.7+, the stdlib will gradually become\n// able to reliably catch and correct all such issues. The error cases are\n// handled in `_StringGuts.ensureMatchingEncoding(_:)`; see there for the sordid\n// details.\nextension String.Index {\n @_alwaysEmitIntoClient // Swift 5.7\n @inline(__always)\n internal var _encodingBits: UInt64 {\n _rawBits & (Self.__utf8Bit | Self.__utf16Bit)\n }\n\n /// Returns true if the position in this index can be interpreted as an offset\n /// into UTF-8-encoded string storage.\n ///\n /// (This returns true if either we know for sure that this is an UTF-8 index,\n /// or if we don't have enough information to determine its encoding.)\n @_alwaysEmitIntoClient // Swift 5.7\n @inline(__always)\n internal var _canBeUTF8: Bool {\n // The only way an index cannot be UTF-8 is it has only the UTF-16 flag set.\n _encodingBits != Self.__utf16Bit\n }\n\n /// Returns true if the position in this index can be interpreted as offset\n /// into UTF-16-encoded string storage.\n ///\n /// (This returns true if either we know for sure that this is an UTF-16\n /// index, or if we don't have enough information to determine its\n /// encoding.)\n @_alwaysEmitIntoClient // Swift 5.7\n @inline(__always)\n internal var _canBeUTF16: Bool {\n // The only way an index cannot be UTF-16 is it has only the UTF-8 flag set.\n _encodingBits != Self.__utf8Bit\n }\n\n /// Returns true if the encoding of this index isn't known to be in conflict\n /// with the specified encoding.\n ///\n /// If the index was created by code that was built on a stdlib below 5.7,\n /// then this check may incorrectly return true on a mismatching index, but it\n /// is guaranteed to never incorrectly return false. If all loaded binaries\n /// were built in 5.7+, then this method is guaranteed to always return the\n /// correct value.\n @_alwaysEmitIntoClient // Swift 5.7\n @inline(__always)\n internal func _hasMatchingEncoding(isUTF8 utf8: Bool) -> Bool {\n _encodingBits != Self.__encodingBit(utf16: utf8)\n }\n\n /// Returns the same index with the UTF-8 bit set.\n @_alwaysEmitIntoClient // Swift 5.7\n @inline(__always)\n internal var _knownUTF8: Self { Self(_rawBits | Self.__utf8Bit) }\n\n /// Returns the same index with the UTF-16 bit set.\n @_alwaysEmitIntoClient // Swift 5.7\n @inline(__always)\n internal var _knownUTF16: Self { Self(_rawBits | Self.__utf16Bit) }\n\n /// Returns the same index with both UTF-8 & UTF-16 bits set.\n @_alwaysEmitIntoClient // Swift 5.7\n @inline(__always)\n internal var _encodingIndependent: Self {\n Self(_rawBits | Self.__utf8Bit | Self.__utf16Bit)\n }\n\n @_alwaysEmitIntoClient // Swift 5.7\n internal func _copyingEncoding(from index: Self) -> Self {\n let mask = Self.__utf8Bit | Self.__utf16Bit\n return Self((_rawBits & ~mask) | (index._rawBits & mask))\n }\n}\n\nextension String.Index: Equatable {\n @inlinable @inline(__always)\n public static func == (lhs: String.Index, rhs: String.Index) -> Bool {\n return lhs.orderingValue == rhs.orderingValue\n }\n}\n\nextension String.Index: Comparable {\n @inlinable @inline(__always)\n public static func < (lhs: String.Index, rhs: String.Index) -> Bool {\n return lhs.orderingValue < rhs.orderingValue\n }\n}\n\nextension String.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(orderingValue)\n }\n}\n\nextension String.Index {\n @_alwaysEmitIntoClient\n internal var _encodingDescription: String {\n switch (_rawBits & Self.__utf8Bit != 0, _rawBits & Self.__utf16Bit != 0) {\n case (false, false): return "unknown"\n case (true, false): return "utf8"\n case (false, true): return "utf16"\n case (true, true): return "any"\n }\n }\n\n /// A textual representation of this instance, intended for debugging.\n ///\n /// - Important: The contents of the returned string are not guaranteed to\n /// remain stable: they may arbitrarily change in any Swift release.\n @_alwaysEmitIntoClient // FIXME: Use @backDeployed\n @inline(never)\n public var debugDescription: String {\n // 23[utf8]+1\n var d = "\(_encodedOffset)[\(_encodingDescription)]"\n if transcodedOffset != 0 {\n d += "+\(transcodedOffset)"\n }\n return d\n }\n}\n\n@available(SwiftStdlib 6.1, *)\nextension String.Index: CustomDebugStringConvertible {}\n\nextension String.Index {\n /// A textual representation of this instance, intended for debugging.\n ///\n /// - Important: The contents of the returned string are not guaranteed to\n /// remain stable: they may arbitrarily change in any Swift release.\n @_alwaysEmitIntoClient\n @available(*, deprecated, renamed: "debugDescription")\n public var _description: String {\n debugDescription\n }\n\n /// A textual representation of this instance, intended for debugging.\n ///\n /// - Important: The contents of the returned string are not guaranteed to\n /// remain stable: they may arbitrarily change in any Swift release.\n @_alwaysEmitIntoClient\n @available(*, deprecated, renamed: "debugDescription")\n public var _debugDescription: String {\n debugDescription\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringIndex.swift
cpp_apple_swift_stdlib_public_core_StringIndex.swift
Swift
22,949
0.95
0.072438
0.312245
vue-tools
396
2024-05-24T22:57:20.752568
GPL-3.0
false
b7396bc1bd010a6627c005983d7a3ff3
//===----------------------------------------------------------------------===//\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\nextension String.Index {\n /// Creates an index in the given string that corresponds exactly to the\n /// specified position.\n ///\n /// If the index passed as `sourcePosition` represents the start of an\n /// extended grapheme cluster---the element type of a string---then the\n /// initializer succeeds.\n ///\n /// The following example converts the position of the Unicode scalar `"e"`\n /// into its corresponding position in the string. The character at that\n /// position is the composed `"é"` character.\n ///\n /// let cafe = "Cafe\u{0301}"\n /// print(cafe)\n /// // Prints "Café"\n ///\n /// let scalarsIndex = cafe.unicodeScalars.firstIndex(of: "e")!\n /// let stringIndex = String.Index(scalarsIndex, within: cafe)!\n ///\n /// print(cafe[...stringIndex])\n /// // Prints "Café"\n ///\n /// If the index passed as `sourcePosition` doesn't have an exact\n /// corresponding position in `target`, the result of the initializer is\n /// `nil`. For example, an attempt to convert the position of the combining\n /// acute accent (`"\u{0301}"`) fails. Combining Unicode scalars do not have\n /// their own position in a string.\n ///\n /// let nextScalarsIndex = cafe.unicodeScalars.index(after: scalarsIndex)\n /// let nextStringIndex = String.Index(nextScalarsIndex, within: cafe)\n ///\n /// print(nextStringIndex)\n /// // Prints "nil"\n ///\n /// - Parameters:\n /// - sourcePosition: A position in a view of the `target` parameter.\n /// `sourcePosition` must be a valid index of at least one of the views\n /// of `target`.\n /// - target: The string referenced by the resulting index.\n public init?(_ sourcePosition: String.Index, within target: String) {\n // As a special exception, we allow `sourcePosition` to be an UTF-16 index\n // when `self` is a UTF-8 string (or vice versa), to preserve compatibility\n // with (broken) code that keeps using indices from a bridged string after\n // converting the string to a native representation. Such indices are\n // invalid, but returning nil here can break code that appeared to work fine\n // for ASCII strings in Swift releases prior to 5.7.\n let i = target._guts.ensureMatchingEncoding(sourcePosition)\n guard target._isValidIndex(i) else { return nil }\n self = i._characterAligned\n }\n\n /// Creates an index in the given string that corresponds exactly to the\n /// specified position.\n ///\n /// If the index passed as `sourcePosition` represents the start of an\n /// extended grapheme cluster---the element type of a string---then the\n /// initializer succeeds.\n ///\n /// The following example converts the position of the Unicode scalar `"e"`\n /// into its corresponding position in the string. The character at that\n /// position is the composed `"é"` character.\n ///\n /// let cafe = "Cafe\u{0301}"\n /// print(cafe)\n /// // Prints "Café"\n ///\n /// let scalarsIndex = cafe.unicodeScalars.firstIndex(of: "e")!\n /// let stringIndex = String.Index(scalarsIndex, within: cafe)!\n ///\n /// print(cafe[...stringIndex])\n /// // Prints "Café"\n ///\n /// If the index passed as `sourcePosition` doesn't have an exact\n /// corresponding position in `target`, the result of the initializer is\n /// `nil`. For example, an attempt to convert the position of the combining\n /// acute accent (`"\u{0301}"`) fails. Combining Unicode scalars do not have\n /// their own position in a string.\n ///\n /// let nextScalarsIndex = cafe.unicodeScalars.index(after: scalarsIndex)\n /// let nextStringIndex = String.Index(nextScalarsIndex, within: cafe)\n ///\n /// print(nextStringIndex)\n /// // Prints "nil"\n ///\n /// - Parameters:\n /// - sourcePosition: A position in a view of the `target` parameter.\n /// `sourcePosition` must be a valid index of at least one of the views\n /// of `target`.\n /// - target: The string referenced by the resulting index.\n @available(SwiftStdlib 5.1, *)\n public init?<S: StringProtocol>(\n _ sourcePosition: String.Index, within target: S\n ) {\n if let str = target as? String {\n self.init(sourcePosition, within: str)\n return\n }\n if let str = target as? Substring {\n // As a special exception, we allow `sourcePosition` to be an UTF-16 index\n // when `self` is a UTF-8 string (or vice versa), to preserve\n // compatibility with (broken) code that keeps using indices from a\n // bridged string after converting the string to a native representation.\n // Such indices are invalid, but returning nil here can break code that\n // appeared to work fine for ASCII strings in Swift releases prior to 5.7.\n let i = str._wholeGuts.ensureMatchingEncoding(sourcePosition)\n guard str._isValidIndex(i) else { return nil }\n self = i\n return\n }\n self.init(sourcePosition, within: String(target))\n }\n\n /// Returns the position in the given UTF-8 view that corresponds exactly to\n /// this index.\n ///\n /// This example first finds the position of the character `"é"`, and then\n /// uses this method find the same position in the string's `utf8` view.\n ///\n /// let cafe = "Café"\n /// if let i = cafe.firstIndex(of: "é") {\n /// let j = i.samePosition(in: cafe.utf8)!\n /// print(Array(cafe.utf8[j...]))\n /// }\n /// // Prints "[195, 169]"\n ///\n /// - Parameter utf8: The view to use for the index conversion. This index\n /// must be a valid index of at least one view of the string shared by\n /// `utf8`.\n /// - Returns: The position in `utf8` that corresponds exactly to this index.\n /// If this index does not have an exact corresponding position in `utf8`,\n /// this method returns `nil`. For example, an attempt to convert the\n /// position of a UTF-16 trailing surrogate returns `nil`.\n public func samePosition(\n in utf8: String.UTF8View\n ) -> String.UTF8View.Index? {\n return String.UTF8View.Index(self, within: utf8)\n }\n\n /// Returns the position in the given UTF-16 view that corresponds exactly to\n /// this index.\n ///\n /// The index must be a valid index of `String(utf16)`.\n ///\n /// This example first finds the position of the character `"é"` and then\n /// uses this method find the same position in the string's `utf16` view.\n ///\n /// let cafe = "Café"\n /// if let i = cafe.firstIndex(of: "é") {\n /// let j = i.samePosition(in: cafe.utf16)!\n /// print(cafe.utf16[j])\n /// }\n /// // Prints "233"\n ///\n /// - Parameter utf16: The view to use for the index conversion. This index\n /// must be a valid index of at least one view of the string shared by\n /// `utf16`.\n /// - Returns: The position in `utf16` that corresponds exactly to this\n /// index. If this index does not have an exact corresponding position in\n /// `utf16`, this method returns `nil`. For example, an attempt to convert\n /// the position of a UTF-8 continuation byte returns `nil`.\n public func samePosition(\n in utf16: String.UTF16View\n ) -> String.UTF16View.Index? {\n return String.UTF16View.Index(self, within: utf16)\n }\n}\n\nextension String {\n /// Returns the largest valid index in `self` that does not exceed the given\n /// position.\n ///\n /// let cafe = "Cafe\u{301}" // "Café"\n /// let accent = cafe.unicodeScalars.firstIndex(of: "\u{301")!\n /// let char = cafe._index(roundingDown: accent)\n /// print(cafe[char]) // "é"\n ///\n /// `String` methods such as `index(after:)` and `distance(from:to:)`\n /// implicitly round their input indices down to the nearest valid index:\n ///\n /// let i = cafe.index(before: char)\n /// let j = cafe.index(before: accent)\n /// print(cafe[i], cafe[j]) // "f f"\n /// print(i == j) // true\n ///\n /// This operation lets you perform this rounding yourself. For example, this\n /// can be used to safely check if `index(before:)` would consider some\n /// arbitrary index equivalent to the start index before calling it.\n ///\n /// - Parameter i: An index that is valid in at least one view of this string.\n /// - Returns: The largest valid index within this string that doesn't exceed\n /// `i`.\n @available(SwiftStdlib 5.8, *)\n public // SPI(Foundation) FIXME: This should be API\n func _index(roundingDown i: Index) -> Index {\n _guts.validateInclusiveCharacterIndex(i)\n }\n}\n\nextension Substring {\n /// Returns the largest valid index in `self` that does not exceed the given\n /// position.\n ///\n /// `Substring` methods such as `index(after:)` and `distance(from:to:)`\n /// implicitly round their input indices down to the nearest valid index.\n /// This operation lets you perform this rounding yourself. For example, this\n /// can be used to safely check if `index(before:)` would consider some\n /// arbitrary index equivalent to the start index before calling it.\n ///\n /// - Parameter i: An index that is valid in at least one view of this\n /// substring.\n /// - Returns: The largest valid index within this substring that doesn't\n /// exceed `i`.\n @available(SwiftStdlib 5.8, *)\n public // SPI(Foundation) FIXME: This should be API\n func _index(roundingDown i: Index) -> Index {\n _wholeGuts.validateInclusiveCharacterIndex(i, in: _bounds)\n }\n}\n\nextension String.UnicodeScalarView {\n /// Returns the largest valid index in `self` that does not exceed the given\n /// position.\n ///\n /// Methods such as `index(after:)` and `distance(from:to:)` implicitly round\n /// their input indices down to the nearest valid index. This operation lets\n /// you perform this rounding yourself. For example, this can be used to\n /// safely check if `index(before:)` would consider some arbitrary index\n /// equivalent to the start index before calling it.\n ///\n /// - Parameter i: An index that is valid in at least one view of the string\n /// shared by this view.\n /// - Returns: The largest valid index within this view that doesn't exceed\n /// `i`.\n @_alwaysEmitIntoClient\n public // SPI(Foundation) FIXME: This should be API\n func _index(roundingDown i: Index) -> Index {\n _guts.validateInclusiveScalarIndex(i)\n }\n}\n\nextension Substring.UnicodeScalarView {\n /// Returns the largest valid index in `self` that does not exceed the given\n /// position.\n ///\n /// Methods such as `index(after:)` and `distance(from:to:)` implicitly round\n /// their input indices down to the nearest valid index. This operation lets\n /// you perform this rounding yourself. For example, this can be used to\n /// safely check if `index(before:)` would consider some arbitrary index\n /// equivalent to the start index before calling it.\n ///\n /// - Parameter i: An index that is valid in at least one view of the\n /// substring shared by this view.\n /// - Returns: The largest valid index within this view that doesn't exceed\n /// `i`.\n @_alwaysEmitIntoClient\n public // SPI(Foundation) FIXME: This should be API\n func _index(roundingDown i: Index) -> Index {\n _wholeGuts.validateInclusiveScalarIndex(i, in: _bounds)\n }\n}\n\nextension String.UTF8View {\n /// Returns the largest valid index in `self` that does not exceed the given\n /// position.\n ///\n /// Methods such as `index(after:)` and `distance(from:to:)` implicitly round\n /// their input indices down to the nearest valid index. This operation lets\n /// you perform this rounding yourself. For example, this can be used to\n /// safely check if `index(before:)` would consider some arbitrary index\n /// equivalent to the start index before calling it.\n ///\n /// - Parameter i: An index that is valid in at least one view of the\n /// substring shared by this view.\n /// - Returns: The largest valid index within this view that doesn't exceed\n /// `i`.\n @_alwaysEmitIntoClient\n public // SPI(Foundation) FIXME: This should be API\n func _index(roundingDown i: Index) -> Index {\n let i = _guts.validateInclusiveSubscalarIndex(i)\n guard _guts.isForeign else { return i.strippingTranscoding._knownUTF8 }\n return _utf8AlignForeignIndex(i)\n }\n}\n\nextension Substring.UTF8View {\n /// Returns the largest valid index in `self` that does not exceed the given\n /// position.\n ///\n /// Methods such as `index(after:)` and `distance(from:to:)` implicitly round\n /// their input indices down to the nearest valid index. This operation lets\n /// you perform this rounding yourself. For example, this can be used to\n /// safely check if `index(before:)` would consider some arbitrary index\n /// equivalent to the start index before calling it.\n ///\n /// - Parameter i: An index that is valid in at least one view of the\n /// substring shared by this view.\n /// - Returns: The largest valid index within this view that doesn't exceed\n /// `i`.\n @_alwaysEmitIntoClient\n public // SPI(Foundation) FIXME: This should be API\n func _index(roundingDown i: Index) -> Index {\n let i = _wholeGuts.validateInclusiveSubscalarIndex(i, in: _bounds)\n guard _wholeGuts.isForeign else { return i.strippingTranscoding._knownUTF8 }\n return _slice._base._utf8AlignForeignIndex(i)\n }\n}\n\nextension String.UTF16View {\n /// Returns the valid index in `self` that this view considers equivalent to\n /// the given index.\n ///\n /// Indices in the UTF-8 view that address positions between Unicode scalars\n /// are rounded down to the nearest scalar boundary; other indices are left as\n /// is.\n ///\n /// - Parameter i: An index that is valid in at least one view of the\n /// substring shared by this view.\n /// - Returns: The valid index in `self` that this view considers equivalent\n /// to `i`.\n @_alwaysEmitIntoClient\n public // SPI(Foundation) FIXME: This should be API\n func _index(roundingDown i: Index) -> Index {\n let i = _guts.validateInclusiveSubscalarIndex(i)\n if _guts.isForeign { return i.strippingTranscoding._knownUTF16 }\n return _utf16AlignNativeIndex(i)\n }\n}\n\nextension Substring.UTF16View {\n /// Returns the valid index in `self` that this view considers equivalent to\n /// the given index.\n ///\n /// Indices in the UTF-8 view that address positions between Unicode scalars\n /// are rounded down to the nearest scalar boundary; other indices are left as\n /// is.\n ///\n /// - Parameter i: An index that is valid in at least one view of the\n /// substring shared by this view.\n /// - Returns: The valid index in `self` that this view considers equivalent\n /// to `i`.\n @_alwaysEmitIntoClient\n public // SPI(Foundation) FIXME: This should be API\n func _index(roundingDown i: Index) -> Index {\n let i = _wholeGuts.validateInclusiveSubscalarIndex(i, in: _bounds)\n if _wholeGuts.isForeign { return i.strippingTranscoding._knownUTF16 }\n return _slice._base._utf16AlignNativeIndex(i)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringIndexConversions.swift
cpp_apple_swift_stdlib_public_core_StringIndexConversions.swift
Swift
15,356
0.8
0.05
0.721264
python-kit
187
2023-09-23T23:43:14.360813
Apache-2.0
false
beef8ec574fb0288938df63f2f02b0ff
//===----------------------------------------------------------------------===//\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// Index validation\nextension _StringGuts {\n @_alwaysEmitIntoClient @inline(__always)\n internal func isFastScalarIndex(_ i: String.Index) -> Bool {\n hasMatchingEncoding(i) && i._isScalarAligned\n }\n\n @_alwaysEmitIntoClient @inline(__always)\n internal func isFastCharacterIndex(_ i: String.Index) -> Bool {\n hasMatchingEncoding(i) && i._isCharacterAligned\n }\n}\n\n// Subscalar index validation (UTF-8 & UTF-16 views)\nextension _StringGuts {\n @_alwaysEmitIntoClient\n internal func validateSubscalarIndex(_ i: String.Index) -> String.Index {\n let i = ensureMatchingEncoding(i)\n _precondition(i._encodedOffset < count, "String index is out of bounds")\n return i\n }\n\n @_alwaysEmitIntoClient\n internal func validateSubscalarIndex(\n _ i: String.Index,\n in bounds: Range<String.Index>\n ) -> String.Index {\n _internalInvariant(bounds.upperBound <= endIndex)\n\n let i = ensureMatchingEncoding(i)\n _precondition(i >= bounds.lowerBound && i < bounds.upperBound,\n "Substring index is out of bounds")\n return i\n }\n\n @_alwaysEmitIntoClient\n internal func validateInclusiveSubscalarIndex(\n _ i: String.Index\n ) -> String.Index {\n let i = ensureMatchingEncoding(i)\n _precondition(i._encodedOffset <= count, "String index is out of bounds")\n return i\n }\n\n @_alwaysEmitIntoClient\n internal func validateInclusiveSubscalarIndex(\n _ i: String.Index,\n in bounds: Range<String.Index>\n ) -> String.Index {\n _internalInvariant(bounds.upperBound <= endIndex)\n\n let i = ensureMatchingEncoding(i)\n _precondition(i >= bounds.lowerBound && i <= bounds.upperBound,\n "Substring index is out of bounds")\n return i\n }\n\n @_alwaysEmitIntoClient\n internal func validateSubscalarRange(\n _ range: Range<String.Index>\n ) -> Range<String.Index> {\n let upper = ensureMatchingEncoding(range.upperBound)\n let lower = ensureMatchingEncoding(range.lowerBound)\n\n // Note: if only `lower` was miscoded, then the range invariant `lower <=\n // upper` may no longer hold after the above conversions, so we need to\n // re-check it here.\n _precondition(upper <= endIndex && lower <= upper,\n "String index range is out of bounds")\n\n return unsafe Range(_uncheckedBounds: (lower, upper))\n }\n\n @_alwaysEmitIntoClient\n internal func validateSubscalarRange(\n _ range: Range<String.Index>,\n in bounds: Range<String.Index>\n ) -> Range<String.Index> {\n _internalInvariant(bounds.upperBound <= endIndex)\n\n let upper = ensureMatchingEncoding(range.upperBound)\n let lower = ensureMatchingEncoding(range.lowerBound)\n\n // Note: if only `lower` was miscoded, then the range invariant `lower <=\n // upper` may no longer hold after the above conversions, so we need to\n // re-check it here.\n _precondition(\n lower >= bounds.lowerBound\n && lower <= upper\n && upper <= bounds.upperBound,\n "Substring index range is out of bounds")\n\n return unsafe Range(_uncheckedBounds: (lower, upper))\n }\n}\n\n// Scalar index validation (Unicode scalar views)\nextension _StringGuts {\n /// Validate `i` and adjust its position toward the start, returning the\n /// resulting index or trapping as appropriate. If this function returns, then\n /// the returned value\n ///\n /// - has an encoding that matches this string,\n /// - is within the bounds of this string, and\n /// - is aligned on a scalar boundary.\n @_alwaysEmitIntoClient\n internal func validateScalarIndex(_ i: String.Index) -> String.Index {\n if isFastScalarIndex(i) {\n _precondition(i._encodedOffset < count, "String index is out of bounds")\n return i\n }\n\n return scalarAlign(validateSubscalarIndex(i))\n }\n\n /// Validate `i` and adjust its position toward the start, returning the\n /// resulting index or trapping as appropriate. If this function returns, then\n /// the returned value\n ///\n /// - has an encoding that matches this string,\n /// - is within `start ..< end`, and\n /// - is aligned on a scalar boundary.\n @_alwaysEmitIntoClient\n internal func validateScalarIndex(\n _ i: String.Index,\n in bounds: Range<String.Index>\n ) -> String.Index {\n _internalInvariant(bounds.upperBound <= endIndex)\n\n if isFastScalarIndex(i) {\n _precondition(i >= bounds.lowerBound && i < bounds.upperBound,\n "Substring index is out of bounds")\n return i\n }\n\n return scalarAlign(validateSubscalarIndex(i, in: bounds))\n }\n}\n\nextension _StringGuts {\n /// Validate `i` and adjust its position toward the start, returning the\n /// resulting index or trapping as appropriate. If this function returns, then\n /// the returned value\n ///\n /// - has an encoding that matches this string,\n /// - is within the bounds of this string (including the `endIndex`), and\n /// - is aligned on a scalar boundary.\n @_alwaysEmitIntoClient\n internal func validateInclusiveScalarIndex(\n _ i: String.Index\n ) -> String.Index {\n if isFastScalarIndex(i) {\n _precondition(i._encodedOffset <= count, "String index is out of bounds")\n return i\n }\n\n return scalarAlign(validateInclusiveSubscalarIndex(i))\n }\n\n /// Validate `i` and adjust its position toward the start, returning the\n /// resulting index or trapping as appropriate. If this function returns, then\n /// the returned value\n ///\n /// - has an encoding that matches this string,\n /// - is within the bounds of this string (including the `endIndex`), and\n /// - is aligned on a scalar boundary.\n @_alwaysEmitIntoClient\n internal func validateInclusiveScalarIndex(\n _ i: String.Index,\n in bounds: Range<String.Index>\n ) -> String.Index {\n _internalInvariant(bounds.upperBound <= endIndex)\n\n if isFastScalarIndex(i) {\n _precondition(i >= bounds.lowerBound && i <= bounds.upperBound,\n "Substring index is out of bounds")\n return i\n }\n\n return scalarAlign(validateInclusiveSubscalarIndex(i, in: bounds))\n }\n}\n\nextension _StringGuts {\n /// Validate `range` and adjust the position of its bounds, returning the\n /// resulting range or trapping as appropriate. If this function returns, then\n /// the bounds of the returned value\n ///\n /// - have an encoding that matches this string,\n /// - are within the bounds of this string, and\n /// - are aligned on a scalar boundary.\n internal func validateScalarRange(\n _ range: Range<String.Index>\n ) -> Range<String.Index> {\n if\n isFastScalarIndex(range.lowerBound), isFastScalarIndex(range.upperBound)\n {\n _precondition(range.upperBound._encodedOffset <= count,\n "String index range is out of bounds")\n return range\n }\n\n let r = validateSubscalarRange(range)\n return unsafe Range(\n _uncheckedBounds: (scalarAlign(r.lowerBound), scalarAlign(r.upperBound)))\n }\n\n /// Validate `range` and adjust the position of its bounds, returning the\n /// resulting range or trapping as appropriate. If this function returns, then\n /// the bounds of the returned value\n ///\n /// - have an encoding that matches this string,\n /// - are within `start ..< end`, and\n /// - are aligned on a scalar boundary.\n internal func validateScalarRange(\n _ range: Range<String.Index>,\n in bounds: Range<String.Index>\n ) -> Range<String.Index> {\n _internalInvariant(bounds.upperBound <= endIndex)\n\n if\n isFastScalarIndex(range.lowerBound), isFastScalarIndex(range.upperBound)\n {\n _precondition(\n range.lowerBound >= bounds.lowerBound\n && range.upperBound <= bounds.upperBound,\n "String index range is out of bounds")\n return range\n }\n\n let r = validateSubscalarRange(range, in: bounds)\n let upper = scalarAlign(r.upperBound)\n let lower = scalarAlign(r.lowerBound)\n return unsafe Range(_uncheckedBounds: (lower, upper))\n }\n}\n\n// Character index validation (String & Substring)\nextension _StringGuts {\n internal func validateCharacterIndex(_ i: String.Index) -> String.Index {\n if isFastCharacterIndex(i) {\n _precondition(i._encodedOffset < count, "String index is out of bounds")\n return i\n }\n return roundDownToNearestCharacter(scalarAlign(validateSubscalarIndex(i)))\n }\n\n internal func validateCharacterIndex(\n _ i: String.Index,\n in bounds: Range<String.Index>\n ) -> String.Index {\n _internalInvariant(bounds.upperBound <= endIndex)\n\n if isFastCharacterIndex(i) {\n _precondition(i >= bounds.lowerBound && i < bounds.upperBound,\n "Substring index is out of bounds")\n return i\n }\n\n return roundDownToNearestCharacter(\n scalarAlign(validateSubscalarIndex(i, in: bounds)),\n in: bounds)\n }\n\n internal func validateInclusiveCharacterIndex(\n _ i: String.Index\n ) -> String.Index {\n if isFastCharacterIndex(i) {\n _precondition(i._encodedOffset <= count, "String index is out of bounds")\n return i\n }\n\n return roundDownToNearestCharacter(\n scalarAlign(validateInclusiveSubscalarIndex(i)))\n }\n\n internal func validateInclusiveCharacterIndex(\n _ i: String.Index,\n in bounds: Range<String.Index>\n ) -> String.Index {\n _internalInvariant(bounds.upperBound <= endIndex)\n\n if isFastCharacterIndex(i) {\n _precondition(i >= bounds.lowerBound && i <= bounds.upperBound,\n "Substring index is out of bounds")\n return i\n }\n\n return roundDownToNearestCharacter(\n scalarAlign(validateInclusiveSubscalarIndex(i, in: bounds)),\n in: bounds)\n }\n}\n\n// Temporary additions to deal with binary compatibility issues with existing\n// binaries that accidentally pass invalid indices to String APIs in cases that\n// were previously undiagnosed.\n//\n// FIXME: Remove these after a release or two.\nextension _StringGuts {\n /// A version of `validateInclusiveSubscalarIndex` that only traps if the main\n /// executable was linked with Swift Stdlib version 5.7 or better. This is\n /// used to work around binary compatibility problems with existing apps that\n /// pass invalid indices to String APIs.\n internal func validateInclusiveSubscalarIndex_5_7(\n _ i: String.Index\n ) -> String.Index {\n let i = ensureMatchingEncoding(i)\n _precondition(\n ifLinkedOnOrAfter: .v5_7_0,\n i._encodedOffset <= count,\n "String index is out of bounds")\n return i\n }\n\n /// A version of `validateInclusiveScalarIndex` that only traps if the main\n /// executable was linked with Swift Stdlib version 5.7 or better. This is\n /// used to work around binary compatibility problems with existing apps that\n /// pass invalid indices to String APIs.\n internal func validateInclusiveScalarIndex_5_7(\n _ i: String.Index\n ) -> String.Index {\n if isFastScalarIndex(i) {\n _precondition(\n ifLinkedOnOrAfter: .v5_7_0,\n i._encodedOffset <= count,\n "String index is out of bounds")\n return i\n }\n\n return scalarAlign(validateInclusiveSubscalarIndex_5_7(i))\n }\n\n /// A version of `validateSubscalarRange` that only traps if the main\n /// executable was linked with Swift Stdlib version 5.7 or better. This is\n /// used to work around binary compatibility problems with existing apps that\n /// pass invalid indices to String APIs.\n internal func validateSubscalarRange_5_7(\n _ range: Range<String.Index>\n ) -> Range<String.Index> {\n let upper = ensureMatchingEncoding(range.upperBound)\n let lower = ensureMatchingEncoding(range.lowerBound)\n\n _precondition(upper <= endIndex && lower <= upper,\n "String index range is out of bounds")\n\n return unsafe Range(_uncheckedBounds: (lower, upper))\n }\n\n /// A version of `validateScalarRange` that only traps if the main executable\n /// was linked with Swift Stdlib version 5.7 or better. This is used to work\n /// around binary compatibility problems with existing apps that pass invalid\n /// indices to String APIs.\n internal func validateScalarRange_5_7(\n _ range: Range<String.Index>\n ) -> Range<String.Index> {\n if\n isFastScalarIndex(range.lowerBound), isFastScalarIndex(range.upperBound)\n {\n _precondition(\n ifLinkedOnOrAfter: .v5_7_0,\n range.upperBound._encodedOffset <= count,\n "String index range is out of bounds")\n return range\n }\n\n let r = validateSubscalarRange_5_7(range)\n return unsafe Range(\n _uncheckedBounds: (scalarAlign(r.lowerBound), scalarAlign(r.upperBound)))\n }\n\n /// A version of `validateInclusiveCharacterIndex` that only traps if the main\n /// executable was linked with Swift Stdlib version 5.7 or better. This is\n /// used to work around binary compatibility problems with existing apps that\n /// pass invalid indices to String APIs.\n internal func validateInclusiveCharacterIndex_5_7(\n _ i: String.Index\n ) -> String.Index {\n if isFastCharacterIndex(i) {\n _precondition(\n ifLinkedOnOrAfter: .v5_7_0,\n i._encodedOffset <= count,\n "String index is out of bounds")\n return i\n }\n\n return roundDownToNearestCharacter(\n scalarAlign(validateInclusiveSubscalarIndex_5_7(i)))\n }\n}\n\n// Word index validation (String)\nextension _StringGuts {\n internal func validateWordIndex(\n _ i: String.Index\n ) -> String.Index {\n return roundDownToNearestWord(scalarAlign(validateSubscalarIndex(i)))\n }\n\n internal func validateInclusiveWordIndex(\n _ i: String.Index\n ) -> String.Index {\n return roundDownToNearestWord(\n scalarAlign(validateInclusiveSubscalarIndex(i))\n )\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringIndexValidation.swift
cpp_apple_swift_stdlib_public_core_StringIndexValidation.swift
Swift
13,929
0.95
0.066826
0.241848
awesome-app
695
2023-12-26T08:09:41.359875
MIT
false
1050f418f698827a48d974cbc21b775e
//===--- StringInterpolation.swift - String Interpolation -----------------===//\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/// Represents a string literal with interpolations while it is being built up.\n/// \n/// Do not create an instance of this type directly. It is used by the compiler\n/// when 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/// print(message)\n/// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."\n/// \n/// When implementing an `ExpressibleByStringInterpolation` conformance,\n/// set the `StringInterpolation` associated type to\n/// `DefaultStringInterpolation` to get the same interpolation behavior as\n/// Swift's built-in `String` type and construct a `String` with the results.\n/// If you don't want the default behavior or don't want to construct a\n/// `String`, use a custom type conforming to `StringInterpolationProtocol`\n/// instead.\n/// \n/// Extending default string interpolation behavior\n/// ===============================================\n/// \n/// Code outside the standard library can extend string interpolation on\n/// `String` and many other common types by extending\n/// `DefaultStringInterpolation` and adding an `appendInterpolation(...)`\n/// method. For example:\n/// \n/// extension DefaultStringInterpolation {\n/// fileprivate mutating func appendInterpolation(\n/// escaped value: String, asASCII forceASCII: Bool = false) {\n/// for char in value.unicodeScalars {\n/// appendInterpolation(char.escaped(asASCII: forceASCII))\n/// }\n/// }\n/// }\n/// \n/// print("Escaped string: \(escaped: string)")\n/// \n/// See `StringInterpolationProtocol` for details on `appendInterpolation`\n/// methods.\n/// \n/// `DefaultStringInterpolation` extensions should add only `mutating` members\n/// and should not copy `self` or capture it in an escaping closure.\n@frozen\npublic struct DefaultStringInterpolation: StringInterpolationProtocol, Sendable {\n /// The string contents accumulated by this instance.\n @usableFromInline\n internal var _storage: String\n \n /// Creates a string interpolation with storage pre-sized for a literal\n /// with the indicated attributes.\n /// \n /// Do not call this initializer directly. It is used by the compiler when\n /// interpreting string interpolations.\n @inlinable\n public init(literalCapacity: Int, interpolationCount: Int) {\n let capacityPerInterpolation = 2\n let initialCapacity = literalCapacity +\n interpolationCount * capacityPerInterpolation\n _storage = String._createEmpty(withInitialCapacity: initialCapacity)\n }\n \n /// Appends a literal segment of a string interpolation.\n /// \n /// Do not call this method directly. It is used by the compiler when\n /// interpreting string interpolations.\n @inlinable\n public mutating func appendLiteral(_ literal: String) {\n literal.write(to: &self)\n }\n \n /// Interpolates the given value's textual representation into the\n /// string literal being created.\n /// \n /// Do not call this method directly. It is used by the compiler when\n /// interpreting string interpolations. 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 /// print(message)\n /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."\n @inlinable\n public mutating func appendInterpolation<T>(_ value: T)\n where T: TextOutputStreamable, T: CustomStringConvertible\n {\n value.write(to: &self)\n }\n \n /// Interpolates the given value's textual representation into the\n /// string literal being created.\n /// \n /// Do not call this method directly. It is used by the compiler when\n /// interpreting string interpolations. 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 = "If one cookie costs \(price) dollars, " +\n /// "\(number) cookies cost \(price * number) dollars."\n /// print(message)\n /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."\n @inlinable\n public mutating func appendInterpolation<T>(_ value: T)\n where T: TextOutputStreamable\n {\n value.write(to: &self)\n }\n \n /// Interpolates the given value's textual representation into the\n /// string literal being created.\n /// \n /// Do not call this method directly. It is used by the compiler when\n /// interpreting string interpolations. 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 /// print(message)\n /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."\n @inlinable\n public mutating func appendInterpolation<T>(_ value: T)\n where T: CustomStringConvertible\n {\n value.description.write(to: &self)\n }\n \n /// Interpolates the given value's textual representation into the\n /// string literal being created.\n /// \n /// Do not call this method directly. It is used by the compiler when\n /// interpreting string interpolations. 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 /// print(message)\n /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."\n @inlinable\n public mutating func appendInterpolation<T>(_ value: T) {\n #if !$Embedded\n _print_unlocked(value, &self)\n #else\n "(cannot print value in embedded Swift)".write(to: &self)\n #endif\n }\n\n @_alwaysEmitIntoClient\n @_unavailableInEmbedded\n public mutating func appendInterpolation(_ value: Any.Type) {\n _typeName(value, qualified: false).write(to: &self)\n }\n\n /// Creates a string from this instance, consuming the instance in the\n /// process.\n @inlinable\n internal __consuming func make() -> String {\n return _storage\n }\n}\n\nextension DefaultStringInterpolation: CustomStringConvertible {\n @inlinable\n public var description: String {\n return _storage\n }\n}\n\nextension DefaultStringInterpolation: TextOutputStream {\n @inlinable\n public mutating func write(_ string: String) {\n _storage.append(string)\n }\n \n public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) {\n unsafe _storage._guts.append(_StringGuts(buffer, isASCII: true))\n }\n}\n\n// While not strictly necessary, declaring these is faster than using the\n// default implementation.\nextension String {\n /// Creates a new instance from an interpolated string literal.\n /// \n /// Do not call this initializer directly. It is 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 /// print(message)\n /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."\n @inlinable\n @_effects(readonly)\n public init(stringInterpolation: DefaultStringInterpolation) {\n self = stringInterpolation.make()\n }\n}\n\nextension Substring {\n /// Creates a new instance from an interpolated string literal.\n /// \n /// Do not call this initializer directly. It is 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 /// print(message)\n /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."\n @inlinable\n @_effects(readonly)\n public init(stringInterpolation: DefaultStringInterpolation) {\n self.init(stringInterpolation.make())\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringInterpolation.swift
cpp_apple_swift_stdlib_public_core_StringInterpolation.swift
Swift
10,195
0.8
0.026316
0.694444
node-utils
992
2024-03-21T16:30:48.248365
BSD-3-Clause
false
087a5d9b778cebc9dd917d56f8884f13
//===----------------------------------------------------------------------===//\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\nextension String {\n /// Creates a new string representing the given string repeated the specified\n /// number of times.\n ///\n /// For example, you can use this initializer to create a string with ten\n /// `"ab"` strings in a row.\n ///\n /// let s = String(repeating: "ab", count: 10)\n /// print(s)\n /// // Prints "abababababababababab"\n ///\n /// - Parameters:\n /// - repeatedValue: The string to repeat.\n /// - count: The number of times to repeat `repeatedValue` in the resulting\n /// string.\n public init(repeating repeatedValue: String, count: Int) {\n _precondition(count >= 0, "Negative count not allowed")\n guard count > 1 else {\n self = count == 0 ? "" : repeatedValue\n return\n }\n\n // TODO(String performance): We can directly call appendInPlace\n var result = String()\n result.reserveCapacity(repeatedValue._guts.count &* count)\n for _ in 0..<count {\n result += repeatedValue\n }\n self = result\n }\n\n /// A Boolean value indicating whether a string has no characters.\n @inlinable\n public var isEmpty: Bool {\n @inline(__always) get { return _guts.isEmpty }\n }\n}\n\nextension StringProtocol {\n /// Returns a Boolean value indicating whether the string begins with the\n /// specified prefix.\n ///\n /// The comparison is both case sensitive and Unicode safe. The\n /// case-sensitive comparison will only match strings whose corresponding\n /// characters have the same case.\n ///\n /// let cafe = "Café du Monde"\n ///\n /// // Case sensitive\n /// print(cafe.hasPrefix("café"))\n /// // Prints "false"\n ///\n /// The Unicode-safe comparison matches Unicode extended grapheme clusters\n /// rather than the code points used to compose them. The example below uses\n /// two strings with different forms of the `"é"` character---the first uses\n /// the composed form and the second uses the decomposed form.\n ///\n /// // Unicode safe\n /// let composedCafe = "Café"\n /// let decomposedCafe = "Cafe\u{0301}"\n ///\n /// print(cafe.hasPrefix(composedCafe))\n /// // Prints "true"\n /// print(cafe.hasPrefix(decomposedCafe))\n /// // Prints "true"\n ///\n /// - Parameter prefix: A possible prefix to test against this string.\n /// - Returns: `true` if the string begins with `prefix`; otherwise, `false`.\n @inlinable\n public func hasPrefix<Prefix: StringProtocol>(_ prefix: Prefix) -> Bool {\n return self.starts(with: prefix)\n }\n\n /// Returns a Boolean value indicating whether the string ends with the\n /// specified suffix.\n ///\n /// The comparison is both case sensitive and Unicode safe. The\n /// case-sensitive comparison will only match strings whose corresponding\n /// characters have the same case.\n ///\n /// let plans = "Let's meet at the café"\n ///\n /// // Case sensitive\n /// print(plans.hasSuffix("Café"))\n /// // Prints "false"\n ///\n /// The Unicode-safe comparison matches Unicode extended grapheme clusters\n /// rather than the code points used to compose them. The example below uses\n /// two strings with different forms of the `"é"` character---the first uses\n /// the composed form and the second uses the decomposed form.\n ///\n /// // Unicode safe\n /// let composedCafe = "café"\n /// let decomposedCafe = "cafe\u{0301}"\n ///\n /// print(plans.hasSuffix(composedCafe))\n /// // Prints "true"\n /// print(plans.hasSuffix(decomposedCafe))\n /// // Prints "true"\n ///\n /// - Parameter suffix: A possible suffix to test against this string.\n /// - Returns: `true` if the string ends with `suffix`; otherwise, `false`.\n @inlinable\n public func hasSuffix<Suffix: StringProtocol>(_ suffix: Suffix) -> Bool {\n return self.reversed().starts(with: suffix.reversed())\n }\n}\n\nextension String {\n public func hasPrefix(_ prefix: String) -> Bool {\n if _fastPath(self._guts.isNFCFastUTF8 && prefix._guts.isNFCFastUTF8) {\n guard prefix._guts.count <= self._guts.count else { return false }\n let isPrefix = unsafe prefix._guts.withFastUTF8 { nfcPrefix in\n let prefixEnd = nfcPrefix.count\n return unsafe self._guts.withFastUTF8(range: 0..<prefixEnd) { nfcSlicedSelf in\n return unsafe _binaryCompare(nfcSlicedSelf, nfcPrefix) == 0\n }\n }\n let endIndex = Index(_encodedOffset: prefix._guts.count)\n // In addition to a byte comparison check, we also need to check that\n // the prefix ends on a grapheme cluster boundary of the String\n return isPrefix && self._guts.isOnGraphemeClusterBoundary(endIndex)\n }\n\n return starts(with: prefix)\n }\n\n public func hasSuffix(_ suffix: String) -> Bool {\n if _fastPath(self._guts.isNFCFastUTF8 && suffix._guts.isNFCFastUTF8) {\n let suffixStart = self._guts.count - suffix._guts.count\n guard suffixStart >= 0 else { return false }\n let isSuffix = unsafe suffix._guts.withFastUTF8 { nfcSuffix in\n return unsafe self._guts.withFastUTF8(range: suffixStart..<self._guts.count) {\n nfcSlicedSelf in return unsafe _binaryCompare(nfcSlicedSelf, nfcSuffix) == 0\n }\n }\n let startIndex = Index(_encodedOffset: suffixStart)\n // In addition to a byte comparison check, we also need to check that\n // the suffix starts on a grapheme cluster boundary of the String\n return isSuffix && self._guts.isOnGraphemeClusterBoundary(startIndex)\n }\n\n return self.reversed().starts(with: suffix.reversed())\n }\n}\n\n// Conversions to string from other types.\nextension String {\n /// Creates a string representing the given value in base 10, or some other\n /// specified base.\n ///\n /// The following example converts the maximal `Int` value to a string and\n /// prints its length:\n ///\n /// let max = String(Int.max)\n /// print("\(max) has \(max.count) digits.")\n /// // Prints "9223372036854775807 has 19 digits."\n ///\n /// Numerals greater than 9 are represented as Roman letters. These letters\n /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`.\n ///\n /// let v = 999_999\n /// print(String(v, radix: 2))\n /// // Prints "11110100001000111111"\n ///\n /// print(String(v, radix: 16))\n /// // Prints "f423f"\n /// print(String(v, radix: 16, uppercase: true))\n /// // Prints "F423F"\n ///\n /// - Parameters:\n /// - value: The value to convert to a string.\n /// - radix: The base to use for the string representation. `radix` must be\n /// at least 2 and at most 36. The default is 10.\n /// - uppercase: Pass `true` to use uppercase letters to represent numerals\n /// greater than 9, or `false` to use lowercase letters. The default is\n /// `false`.\n public init<T: BinaryInteger>(\n _ value: T, radix: Int = 10, uppercase: Bool = false\n ) {\n self = value._description(radix: radix, uppercase: uppercase)\n }\n}\n
dataset_sample\swift\swift\cpp_apple_swift_stdlib_public_core_StringLegacy.swift
cpp_apple_swift_stdlib_public_core_StringLegacy.swift
Swift
7,432
0.95
0.045685
0.639785
vue-tools
986
2023-11-07T21:15:13.991715
Apache-2.0
false
033658f0eb9e4610ca6ac829612ec222