|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +/// A C++ type that can be converted to a Swift collection. |
| 14 | +public protocol CxxConvertibleToCollection { |
| 15 | + associatedtype RawIterator: UnsafeCxxInputIterator |
| 16 | + |
| 17 | + /// Do not implement this function manually in Swift. |
| 18 | + mutating func __beginUnsafe() -> RawIterator |
| 19 | + |
| 20 | + /// Do not implement this function manually in Swift. |
| 21 | + mutating func __endUnsafe() -> RawIterator |
| 22 | +} |
| 23 | + |
| 24 | +@inlinable @inline(__always) |
| 25 | +internal func forEachElement<C: CxxConvertibleToCollection>( |
| 26 | + of c: C, |
| 27 | + body: (C.RawIterator.Pointee) -> Void |
| 28 | +) { |
| 29 | + var mutableC = c |
| 30 | + withExtendedLifetime(mutableC) { |
| 31 | + var rawIterator = mutableC.__beginUnsafe() |
| 32 | + let endIterator = mutableC.__endUnsafe() |
| 33 | + while rawIterator != endIterator { |
| 34 | + body(rawIterator.pointee) |
| 35 | + rawIterator = rawIterator.successor() |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +extension Array { |
| 41 | + /// Creates an array containing the elements of a C++ collection. |
| 42 | + /// |
| 43 | + /// This initializer copies each element of the C++ collection to a new Swift |
| 44 | + /// array. |
| 45 | + /// |
| 46 | + /// - Complexity: O(*n*), where *n* is the number of elements in the C++ |
| 47 | + /// collection. |
| 48 | + public init<C: CxxConvertibleToCollection>(_ c: C) |
| 49 | + where C.RawIterator.Pointee == Element { |
| 50 | + |
| 51 | + self.init() |
| 52 | + forEachElement(of: c) { self.append($0) } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +extension Set { |
| 57 | + /// Creates an set containing the elements of a C++ collection. |
| 58 | + /// |
| 59 | + /// This initializer copies each element of the C++ collection to a new Swift |
| 60 | + /// set. |
| 61 | + /// |
| 62 | + /// - Complexity: O(*n*), where *n* is the number of elements in the C++ |
| 63 | + /// collection. |
| 64 | + public init<C: CxxConvertibleToCollection>(_ c: C) |
| 65 | + where C.RawIterator.Pointee == Element { |
| 66 | + |
| 67 | + self.init() |
| 68 | + forEachElement(of: c) { self.insert($0) } |
| 69 | + } |
| 70 | +} |
0 commit comments