forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNSSet.swift
662 lines (567 loc) · 22.2 KB
/
NSSet.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
// 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
//
import CoreFoundation
open class NSSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
private let _cfinfo = _CFInfo(typeID: CFSetGetTypeID())
internal var _storage: Set<NSObject>
open var count: Int {
guard type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self || type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
return _storage.count
}
open func member(_ object: Any) -> Any? {
guard type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self || type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
let value = __SwiftValue.store(object)
guard let idx = _storage.firstIndex(of: value) else { return nil }
return _storage[idx]
}
open func objectEnumerator() -> NSEnumerator {
guard type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self || type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
return NSGeneratorEnumerator(_storage.map { __SwiftValue.fetch(nonOptional: $0) }.makeIterator())
}
public convenience override init() {
self.init(objects: [], count: 0)
}
public init(objects: UnsafePointer<AnyObject>!, count cnt: Int) {
_storage = Set(minimumCapacity: cnt)
super.init()
let buffer = UnsafeBufferPointer(start: objects, count: cnt)
for obj in buffer {
_storage.insert(__SwiftValue.store(obj))
}
}
public convenience init(array: [Any]) {
let buffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: array.count)
for (idx, element) in array.enumerated() {
buffer.advanced(by: idx).initialize(to: __SwiftValue.store(element))
}
self.init(objects: buffer, count: array.count)
buffer.deinitialize(count: array.count)
buffer.deallocate()
}
public convenience init(set: Set<AnyHashable>) {
self.init(set: set, copyItems: false)
}
public convenience init(set anSet: NSSet) {
self.init(array: anSet.allObjects)
}
public convenience init(set: Set<AnyHashable>, copyItems flag: Bool) {
if flag {
self.init(array: set.map {
if let item = $0 as? NSObject {
return item.copy()
} else {
return $0
}
})
} else {
self.init(array: Array(set))
}
}
public convenience init(object: Any) {
self.init(array: [object])
}
internal class func _objects(from aDecoder: NSCoder, allowDecodingNonindexedArrayKey: Bool = true) -> [NSObject] {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if (allowDecodingNonindexedArrayKey && type(of: aDecoder) == NSKeyedUnarchiver.self) || aDecoder.containsValue(forKey: "NS.objects") {
let objects = aDecoder._decodeArrayOfObjectsForKey("NS.objects")
return objects as! [NSObject]
} else {
var objects: [NSObject] = []
var count = 0
var key: String { return "NS.object.\(count)" }
while aDecoder.containsValue(forKey: key) {
let object = aDecoder.decodeObject(forKey: key)
objects.append(object as! NSObject)
count += 1
}
return objects
}
}
public required convenience init?(coder aDecoder: NSCoder) {
self.init(array: NSSet._objects(from: aDecoder))
}
open func encode(with aCoder: NSCoder) {
// The encoding of a NSSet is identical to the encoding of an NSArray of its contents
self.allObjects._nsObject.encode(with: aCoder)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSSet.self {
// return self for immutable type
return self
} else if type(of: self) === NSMutableSet.self {
let set = NSSet()
set._storage = self._storage
return set
}
return NSSet(array: self.allObjects)
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self {
// always create and return an NSMutableSet
let mutableSet = NSMutableSet()
mutableSet._storage = self._storage
return mutableSet
}
return NSMutableSet(array: self.allObjects)
}
public static var supportsSecureCoding: Bool {
return true
}
override open var description: String {
return description(withLocale: nil)
}
open func description(withLocale locale: Locale?) -> String {
return description(withLocale: locale, indent: 0)
}
private func description(withLocale locale: Locale?, indent level: Int) -> String {
var descriptions = [String]()
for obj in self._storage {
if let string = obj as? String {
descriptions.append(string)
} else if let array = obj as? [Any] {
descriptions.append(NSArray(array: array).description(withLocale: locale, indent: level + 1))
} else if let dict = obj as? [AnyHashable : Any] {
descriptions.append(dict._bridgeToObjectiveC().description(withLocale: locale, indent: level + 1))
} else if let set = obj as? Set<AnyHashable> {
descriptions.append(set._bridgeToObjectiveC().description(withLocale: locale, indent: level + 1))
} else {
descriptions.append("\(obj)")
}
}
var indent = ""
for _ in 0..<level {
indent += " "
}
var result = indent + "{(\n"
for idx in 0..<self.count {
result += indent + " " + descriptions[idx]
if idx + 1 < self.count {
result += ",\n"
} else {
result += "\n"
}
}
result += indent + ")}"
return result
}
override open var _cfTypeID: CFTypeID {
return CFSetGetTypeID()
}
open override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as NSSet:
// Check that this isn't a subclass — if both self and other are subclasses, this would otherwise turn into an infinite loop if other.isEqual(_:) calls super.
if (type(of: self) == NSSet.self || type(of: self) == NSMutableSet.self) &&
(type(of: other) != NSSet.self && type(of: other) != NSMutableSet.self) {
return other.isEqual(self) // This ensures NSCountedSet overriding this method is respected no matter which side of the equality it appears on.
} else {
return isEqual(to: Set._unconditionallyBridgeFromObjectiveC(other))
}
case let other as Set<AnyHashable>:
return isEqual(to: other)
default:
return false
}
}
open override var hash: Int {
return self.count
}
open var allObjects: [Any] {
if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self {
return _storage.map { __SwiftValue.fetch(nonOptional: $0) }
} else {
let enumerator = objectEnumerator()
var items = [Any]()
while let val = enumerator.nextObject() {
items.append(val)
}
return items
}
}
open func anyObject() -> Any? {
return objectEnumerator().nextObject()
}
open func contains(_ anObject: Any) -> Bool {
return member(anObject) != nil
}
open func intersects(_ otherSet: Set<AnyHashable>) -> Bool {
if count < otherSet.count {
for item in self {
if otherSet.contains(item as! AnyHashable) {
return true
}
}
return false
} else {
return otherSet.contains { obj in contains(obj) }
}
}
open func isEqual(to otherSet: Set<AnyHashable>) -> Bool {
return count == otherSet.count && isSubset(of: otherSet)
}
open func isSubset(of otherSet: Set<AnyHashable>) -> Bool {
// If self is larger then self cannot be a subset of otherSet
if count > otherSet.count {
return false
}
// `true` if we don't contain any object that `otherSet` doesn't contain.
for item in self {
if !otherSet.contains(item as! AnyHashable) {
return false
}
}
return true
}
open func adding(_ anObject: Any) -> Set<AnyHashable> {
return self.addingObjects(from: [anObject])
}
open func addingObjects(from other: Set<AnyHashable>) -> Set<AnyHashable> {
var result = Set<AnyHashable>(minimumCapacity: Swift.max(count, other.count))
if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self {
result.formUnion(_storage.map { __SwiftValue.fetch(nonOptional: $0) as! AnyHashable })
} else {
for case let obj as NSObject in self {
_ = result.insert(obj)
}
}
return result.union(other)
}
open func addingObjects(from other: [Any]) -> Set<AnyHashable> {
var result = Set<AnyHashable>(minimumCapacity: count)
if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self {
result.formUnion(_storage.map { __SwiftValue.fetch(nonOptional: $0) as! AnyHashable })
} else {
for case let obj as AnyHashable in self {
result.insert(obj)
}
}
for case let obj as AnyHashable in other {
result.insert(obj)
}
return result
}
open func enumerateObjects(_ block: (Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
enumerateObjects(options: [], using: block)
}
open func enumerateObjects(options opts: NSEnumerationOptions = [], using block: (Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
var stop : ObjCBool = false
for obj in self {
withUnsafeMutablePointer(to: &stop) { stop in
block(obj, stop)
}
if stop.boolValue {
break
}
}
}
open func objects(passingTest predicate: (Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
return objects(options: [], passingTest: predicate)
}
open func objects(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
var result = Set<AnyHashable>()
enumerateObjects(options: opts) { obj, stopp in
if predicate(obj, stopp) {
result.insert(obj as! AnyHashable)
}
}
return result
}
open func sortedArray(using sortDescriptors: [NSSortDescriptor]) -> [Any] {
return allObjects._nsObject.sortedArray(using: sortDescriptors)
}
}
extension NSSet : _CFBridgeable, _SwiftBridgeable {
internal var _cfObject: CFSet { return unsafeBitCast(self, to: CFSet.self) }
internal var _swiftObject: Set<NSObject> { return Set._unconditionallyBridgeFromObjectiveC(self) }
}
extension CFSet : _NSBridgeable, _SwiftBridgeable {
internal var _nsObject: NSSet { return unsafeBitCast(self, to: NSSet.self) }
internal var _swiftObject: Set<NSObject> { return _nsObject._swiftObject }
}
extension NSMutableSet {
internal var _cfMutableObject: CFMutableSet { return unsafeBitCast(self, to: CFMutableSet.self) }
}
extension Set : _NSBridgeable, _CFBridgeable {
internal var _nsObject: NSSet { return _bridgeToObjectiveC() }
internal var _cfObject: CFSet { return _nsObject._cfObject }
}
extension NSSet : Sequence {
public typealias Iterator = NSEnumerator.Iterator
public func makeIterator() -> Iterator {
return self.objectEnumerator().makeIterator()
}
}
extension NSSet: CustomReflectable {
public var customMirror: Mirror {
return Mirror(reflecting: self._storage)
}
}
open class NSMutableSet : NSSet {
open func add(_ object: Any) {
guard type(of: self) === NSMutableSet.self else {
NSRequiresConcreteImplementation()
}
_storage.insert(__SwiftValue.store(object))
}
open func remove(_ object: Any) {
guard type(of: self) === NSMutableSet.self else {
NSRequiresConcreteImplementation()
}
_storage.remove(__SwiftValue.store(object))
}
override public init(objects: UnsafePointer<AnyObject>!, count cnt: Int) {
super.init(objects: objects, count: cnt)
}
public convenience init() {
self.init(capacity: 0)
}
public required init(capacity numItems: Int) {
super.init(objects: [], count: 0)
}
public required convenience init?(coder aDecoder: NSCoder) {
self.init(array: NSSet._objects(from: aDecoder))
}
open func addObjects(from array: [Any]) {
if type(of: self) === NSMutableSet.self {
for case let obj in array {
_storage.insert(__SwiftValue.store(obj))
}
} else {
array.forEach(add)
}
}
open func intersect(_ otherSet: Set<AnyHashable>) {
if type(of: self) === NSMutableSet.self {
_storage.formIntersection(otherSet.map { __SwiftValue.store($0) })
} else {
for obj in self {
if !otherSet.contains(obj as! AnyHashable) {
remove(obj)
}
}
}
}
open func minus(_ otherSet: Set<AnyHashable>) {
if type(of: self) === NSMutableSet.self {
_storage.subtract(otherSet.map { __SwiftValue.store($0) })
} else {
otherSet.forEach(remove)
}
}
open func removeAllObjects() {
if type(of: self) === NSMutableSet.self {
_storage.removeAll()
} else {
forEach(remove)
}
}
open func union(_ otherSet: Set<AnyHashable>) {
if type(of: self) === NSMutableSet.self {
_storage.formUnion(otherSet.map { __SwiftValue.store($0) })
} else {
otherSet.forEach(add)
}
}
open func setSet(_ otherSet: Set<AnyHashable>) {
if type(of: self) === NSMutableSet.self {
_storage = Set(otherSet.map { __SwiftValue.store($0) })
} else {
removeAllObjects()
union(otherSet)
}
}
}
/**************** Counted Set ****************/
open class NSCountedSet : NSMutableSet {
// Note: in 5.0 and earlier, _table contained the object's exact count.
// In 5.1 and earlier, it contains the count minus one. This allows us to have a quick 'is this set just like a regular NSSet' flag (if this table is empty, then all objects in it exist at most once in it.)
internal var _table: [NSObject: Int] = [:]
public required init(capacity numItems: Int) {
_table = Dictionary<NSObject, Int>()
super.init(capacity: numItems)
}
public convenience init() {
self.init(capacity: 0)
}
public convenience init(array: [Any]) {
self.init(capacity: array.count)
for object in array {
add(__SwiftValue.store(object))
}
}
public convenience init(set: Set<AnyHashable>) {
self.init(array: Array(set))
}
private enum NSCodingKeys {
static let maximumAllowedCount = UInt.max >> 4
static let countKey = "NS.count"
static func objectKey(atIndex index: Int64) -> String { return "NS.object\(index)" }
static func objectCountKey(atIndex index: Int64) -> String { return "NS.count\(index)" }
}
public required convenience init?(coder: NSCoder) {
func fail(_ message: String) {
coder.failWithError(NSError(domain: NSCocoaErrorDomain, code: NSCoderReadCorruptError, userInfo: [NSLocalizedDescriptionKey: message]))
}
guard coder.allowsKeyedCoding else {
fail("NSCountedSet requires keyed coding to be archived.")
return nil
}
let count = coder.decodeInt64(forKey: NSCodingKeys.countKey)
guard count >= 0, UInt(count) <= NSCodingKeys.maximumAllowedCount else {
fail("cannot decode set with \(count) elements in this version")
return nil
}
var objects: [(object: Any, count: Int64)] = []
for i in 0 ..< count {
let objectKey = NSCodingKeys.objectKey(atIndex: i)
let countKey = NSCodingKeys.objectCountKey(atIndex: i)
guard coder.containsValue(forKey: objectKey) && coder.containsValue(forKey: countKey) else {
fail("Mismatch in count stored (\(count)) vs. count present (\(i))")
return nil
}
guard let object = coder.decodeObject(forKey: objectKey) else {
fail("Decode failure at index \(i) - item nil")
return nil
}
let itemCount = coder.decodeInt64(forKey: countKey)
guard itemCount > 0 else {
fail("Decode failure at index \(i) - itemCount zero")
return nil
}
guard UInt(itemCount) <= NSCodingKeys.maximumAllowedCount else {
fail("Cannot store \(itemCount) instances of item \(object) in this version")
return nil
}
objects.append((object, itemCount))
}
self.init()
for value in objects {
for _ in 0 ..< value.count {
add(value.object)
}
}
}
open override func encode(with coder: NSCoder) {
func fail(_ message: String) {
coder.failWithError(NSError(domain: NSCocoaErrorDomain, code: NSCoderReadCorruptError, userInfo: [NSLocalizedDescriptionKey: message]))
}
guard coder.allowsKeyedCoding else {
fail("NSCountedSet requires keyed coding to be archived.")
return
}
coder.encode(Int64(self.count), forKey: NSCodingKeys.countKey)
var index: Int64 = 0
for object in self {
coder.encode(object, forKey: NSCodingKeys.objectKey(atIndex: index))
coder.encode(Int64(count(for: object)), forKey: NSCodingKeys.objectCountKey(atIndex: index))
index += 1
}
}
open override func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSCountedSet.self {
let countedSet = NSCountedSet()
countedSet._storage = self._storage
countedSet._table = self._table
return countedSet
}
return NSCountedSet(array: self.allObjects)
}
open override func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSCountedSet.self {
let countedSet = NSCountedSet()
countedSet._storage = self._storage
countedSet._table = self._table
return countedSet
}
return NSCountedSet(array: self.allObjects)
}
open func count(for object: Any) -> Int {
guard type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
let value = __SwiftValue.store(object)
if let count = _table[value] {
return count + 1
} else if _storage.contains(value) {
return 1
} else {
return 0
}
}
open override func add(_ object: Any) {
guard type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
let value = __SwiftValue.store(object)
if _storage.contains(value) {
_table[value, default: 0] += 1
} else {
_storage.insert(value)
}
}
open override func remove(_ object: Any) {
guard type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
let value = __SwiftValue.store(object)
if let count = _table[value] {
precondition(count > 0)
_table[value] = count == 1 ? nil : count - 1
} else if _storage.contains(value) {
_table.removeValue(forKey: value)
_storage.remove(value)
}
}
open override func removeAllObjects() {
if type(of: self) === NSCountedSet.self {
_storage.removeAll()
_table.removeAll()
} else {
forEach(remove)
}
}
open override func isEqual(_ value: Any?) -> Bool {
if let countedSet = value as? NSCountedSet {
guard count == countedSet.count else { return false }
for object in self {
if !countedSet.contains(object) || count(for: object) != countedSet.count(for: object) {
return false
}
}
return true
}
if _table.isEmpty {
return super.isEqual(value)
} else {
return false
}
}
// The hash of a NSSet in s-c-f is its count, which is the same among equal NSCountedSets as well,
// so just using the superclass's implementation works fine.
}
extension NSSet : _StructTypeBridgeable {
public typealias _StructType = Set<AnyHashable>
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}