forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBoxing.swift
235 lines (200 loc) · 8.85 KB
/
Boxing.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if NS_BUILDING_FOUNDATION_NETWORKING
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
#endif
/// A class type which acts as a handle (pointer-to-pointer) to a Foundation reference type which has only a mutable class (e.g., NSURLComponents).
///
/// Note: This assumes that the result of calling copy() is mutable. The documentation says that classes which do not have a mutable/immutable distinction should just adopt NSCopying instead of NSMutableCopying.
internal final class _MutableHandle<MutableType : NSObject> where MutableType : NSCopying {
@usableFromInline internal var _pointer : MutableType
init(reference : MutableType) {
_pointer = reference.copy() as! MutableType
}
init(adoptingReference reference: MutableType) {
_pointer = reference
}
/// Apply a closure to the reference type.
func map<ReturnType>(_ whatToDo : (MutableType) throws -> ReturnType) rethrows -> ReturnType {
return try whatToDo(_pointer)
}
func _copiedReference() -> MutableType {
return _pointer.copy() as! MutableType
}
func _uncopiedReference() -> MutableType {
return _pointer
}
}
/// Describes common operations for Foundation struct types that are bridged to a mutable object (e.g. NSURLComponents).
internal protocol _MutableBoxing : ReferenceConvertible {
var _handle : _MutableHandle<ReferenceType> { get set }
/// Apply a mutating closure to the reference type, regardless if it is mutable or immutable.
///
/// This function performs the correct copy-on-write check for efficient mutation.
mutating func _applyMutation<ReturnType>(_ whatToDo : (ReferenceType) -> ReturnType) -> ReturnType
}
extension _MutableBoxing {
@inline(__always)
mutating func _applyMutation<ReturnType>(_ whatToDo : (ReferenceType) -> ReturnType) -> ReturnType {
// Only create a new box if we are not uniquely referenced
if !isKnownUniquelyReferenced(&_handle) {
let ref = _handle._pointer
_handle = _MutableHandle(reference: ref)
}
return whatToDo(_handle._pointer)
}
}
internal enum _MutableUnmanagedWrapper<ImmutableType : NSObject, MutableType : NSObject> where MutableType : NSMutableCopying {
case Immutable(Unmanaged<ImmutableType>)
case Mutable(Unmanaged<MutableType>)
}
internal protocol _SwiftNativeFoundationType: AnyObject {
associatedtype ImmutableType : NSObject
associatedtype MutableType : NSObject, NSMutableCopying
var __wrapped : _MutableUnmanagedWrapper<ImmutableType, MutableType> { get }
init(unmanagedImmutableObject: Unmanaged<ImmutableType>)
init(unmanagedMutableObject: Unmanaged<MutableType>)
func mutableCopy(with zone : NSZone) -> Any
func hash(into hasher: inout Hasher)
var hashValue: Int { get }
var description: String { get }
var debugDescription: String { get }
func releaseWrappedObject()
}
extension _SwiftNativeFoundationType {
@inline(__always)
func _mapUnmanaged<ReturnType>(_ whatToDo : (ImmutableType) throws -> ReturnType) rethrows -> ReturnType {
defer { _fixLifetime(self) }
switch __wrapped {
case .Immutable(let i):
return try i._withUnsafeGuaranteedRef {
_onFastPath()
return try whatToDo($0)
}
case .Mutable(let m):
return try m._withUnsafeGuaranteedRef {
_onFastPath()
return try whatToDo(_unsafeReferenceCast($0, to: ImmutableType.self))
}
}
}
func releaseWrappedObject() {
switch __wrapped {
case .Immutable(let i):
i.release()
case .Mutable(let m):
m.release()
}
}
func mutableCopy(with zone : NSZone) -> Any {
return _mapUnmanaged { ($0 as NSObject).mutableCopy() }
}
func hash(into hasher: inout Hasher) {
_mapUnmanaged { hasher.combine($0) }
}
var hashValue: Int {
return _mapUnmanaged { return $0.hashValue }
}
var description: String {
return _mapUnmanaged { return $0.description }
}
var debugDescription: String {
return _mapUnmanaged { return $0.debugDescription }
}
func isEqual(_ other: AnyObject) -> Bool {
return _mapUnmanaged { return $0.isEqual(other) }
}
}
internal protocol _MutablePairBoxing {
associatedtype WrappedSwiftNSType : _SwiftNativeFoundationType
var _wrapped : WrappedSwiftNSType { get set }
}
extension _MutablePairBoxing {
@inline(__always)
func _mapUnmanaged<ReturnType>(_ whatToDo : (WrappedSwiftNSType.ImmutableType) throws -> ReturnType) rethrows -> ReturnType {
// We are using Unmanaged. Make sure that the owning container class
// 'self' is guaranteed to be alive by extending the lifetime of 'self'
// to the end of the scope of this function.
// Note: At the time of this writing using withExtendedLifetime here
// instead of _fixLifetime causes different ARC pair matching behavior
// foiling optimization. This is why we explicitly use _fixLifetime here
// instead.
defer { _fixLifetime(self) }
let unmanagedHandle = Unmanaged.passUnretained(_wrapped)
let wrapper = unmanagedHandle._withUnsafeGuaranteedRef { $0.__wrapped }
switch (wrapper) {
case .Immutable(let i):
return try i._withUnsafeGuaranteedRef {
return try whatToDo($0)
}
case .Mutable(let m):
return try m._withUnsafeGuaranteedRef {
return try whatToDo(_unsafeReferenceCast($0, to: WrappedSwiftNSType.ImmutableType.self))
}
}
}
@inline(__always)
mutating func _applyUnmanagedMutation<ReturnType>(_ whatToDo : (WrappedSwiftNSType.MutableType) throws -> ReturnType) rethrows -> ReturnType {
// We are using Unmanaged. Make sure that the owning container class
// 'self' is guaranteed to be alive by extending the lifetime of 'self'
// to the end of the scope of this function.
// Note: At the time of this writing using withExtendedLifetime here
// instead of _fixLifetime causes different ARC pair matching behavior
// foiling optimization. This is why we explicitly use _fixLifetime here
// instead.
defer { _fixLifetime(self) }
var unique = true
let _unmanagedHandle = Unmanaged.passUnretained(_wrapped)
let wrapper = _unmanagedHandle._withUnsafeGuaranteedRef { $0.__wrapped }
// This check is done twice because: <rdar://problem/24939065> Value kept live for too long causing uniqueness check to fail
switch (wrapper) {
case .Immutable:
break
case .Mutable:
unique = isKnownUniquelyReferenced(&_wrapped)
}
switch (wrapper) {
case .Immutable(let i):
// We need to become mutable; by creating a new instance we also become unique
let copy = Unmanaged.passRetained(i._withUnsafeGuaranteedRef {
return _unsafeReferenceCast($0.mutableCopy(), to: WrappedSwiftNSType.MutableType.self) }
)
// Be sure to set the var before calling out; otherwise references to the struct in the closure may be looking at the old value
_wrapped = WrappedSwiftNSType(unmanagedMutableObject: copy)
return try copy._withUnsafeGuaranteedRef {
_onFastPath()
return try whatToDo($0)
}
case .Mutable(let m):
// Only create a new box if we are not uniquely referenced
if !unique {
let copy = Unmanaged.passRetained(m._withUnsafeGuaranteedRef {
return _unsafeReferenceCast($0.mutableCopy(), to: WrappedSwiftNSType.MutableType.self)
})
_wrapped = WrappedSwiftNSType(unmanagedMutableObject: copy)
return try copy._withUnsafeGuaranteedRef {
_onFastPath()
return try whatToDo($0)
}
} else {
return try m._withUnsafeGuaranteedRef {
_onFastPath()
return try whatToDo($0)
}
}
}
}
}