forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashedCollections.swift.gyb
4159 lines (3651 loc) · 125 KB
/
HashedCollections.swift.gyb
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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 SwiftShims
// General Mutable, Value-Type Collections
// =================================================
//
// Basic copy-on-write (COW) requires a container's data to be copied
// into new storage before it is modified, to avoid changing the data
// of other containers that may share the data. There is one
// exception: when we know the container has the only reference to the
// data, we can elide the copy. This COW optimization is crucial for
// the performance of mutating algorithms.
//
// Some container elements (Characters in a String, key/value pairs in
// an open-addressing hash table) are not traversable with a fixed
// size offset, so incrementing/decrementing indices requires looking
// at the contents of the container. The current interface for
// incrementing/decrementing indices of an CollectionType is the usual ++i,
// --i. Therefore, for memory safety, the indices need to keep a
// reference to the container's underlying data so that it can be
// inspected. But having multiple outstanding references to the
// underlying data defeats the COW optimization.
//
// The way out is to count containers referencing the data separately
// from indices that reference the data. When deciding to elide the
// copy and modify the data directly---as long as we don't violate
// memory safety of any outstanding indices---we only need to be
// sure that no other containers are referencing the data.
//
// Implementation notes
// ====================
//
// `Dictionary` uses two storage schemes: native storage and Cocoa storage.
//
// Native storage is a hash table with open addressing and linear probing. The
// bucket array forms a logical ring (e.g., a chain can wrap around the end of
// buckets array to the beginning of it).
//
// The logical bucket array is implemented as three arrays: Key, Value, and a
// bitmap that marks valid entries. An invalid entry marks the end of a chain.
// There is always at least one invalid entry among the buckets. `Dictionary`
// does not use tombstones.
//
// In addition to the native storage `Dictionary` can also wrap an
// `NSDictionary` in order to allow brdidging `NSDictionary` to `Dictionary` in
// `O(1)`.
//
// Currently native storage uses a data structure like this::
//
// Dictionary<K,V> (a struct)
// +----------------------------------------------+
// | [ _VariantDictionaryStorage<K,V> (an enum) ] |
// +---|------------------------------------------+
// /
// |
// V _NativeDictionaryStorageOwner<K,V> (a class)
// +-----------------------------------------------------------+
// | [refcount#1] [ _NativeDictionaryStorage<K,V> (a struct) ] |
// +----------------|------------------------------------------+
// |
// +--------------+
// |
// V _NativeDictionaryStorageImpl<K,V> (a class)
// +-----------------------------------------+
// | [refcount#2] [...element storage...] |
// +-----------------------------------------+
// ^
// +---+
// | Dictionary<K,V>.Index (an enum)
// +-----|--------------------------------------------+
// | | _NativeDictionaryIndex<K,V> (a struct) |
// | +---|------------------------------------------+ |
// | | [ _NativeDictionaryStorage<K,V> (a struct) ] | |
// | +----------------------------------------------+ |
// +--------------------------------------------------+
//
// We would like to optimize by allocating the `_NativeDictionaryStorageOwner`
// /inside/ the `_NativeDictionaryStorageImpl`, and override the `dealloc`
// method of `_NativeDictionaryStorageOwner` to do nothing but release its
// reference.
//
// Dictionary<K,V> (a struct)
// +----------------------------------------------+
// | [ _VariantDictionaryStorage<K,V> (an enum) ] |
// +---|------------------------------------------+
// /
// | +---+
// | V | _NativeDictionaryStorageImpl<K,V> (a class)
// +---|--------------|----------------------------------------------+
// | | | |
// | | [refcount#2] | |
// | | | |
// | V | _NativeDictionaryStorageOwner<K,V> (a class) |
// | +----------------|------------------------------------------+ |
// | | [refcount#1] [ _NativeDictionaryStorage<K,V> (a struct) ] | |
// | +-----------------------------------------------------------+ |
// | |
// | [...element storage...] |
// +-----------------------------------------------------------------+
//
//
// Cocoa storage uses a data structure like this::
//
// Dictionary<K,V> (a struct)
// +----------------------------------------------+
// | _VariantDictionaryStorage<K,V> (an enum) |
// | +----------------------------------------+ |
// | | [ _CocoaDictionaryStorage (a struct) ] | |
// | +---|------------------------------------+ |
// +-----|----------------------------------------+
// |
// +---+
// |
// V NSDictionary (a class)
// +--------------+
// | [refcount#1] |
// +--------------+
// ^
// +-+
// | Dictionary<K,V>.Index (an enum)
// +---|-----------------------------------+
// | | _CocoaDictionaryIndex (a struct) |
// | +-|-----------------------------+ |
// | | * [ all keys ] [ next index ] | |
// | +-------------------------------+ |
// +---------------------------------------+
//
// `_NativeDictionaryStorageOwner` is an `NSDictionary` subclass. It can
// be returned to Objective-C during bridging if both `Key` and `Value`
// bridge verbatim.
//
// Index Invalidation
// ------------------
//
// Indexing a container, `c[i]`, uses the integral offset stored in the index
// to access the elements referenced by the container. The buffer referenced
// by the index is only used to increment and decrement the index. Most of the
// time, these two buffers will be identical, but they need not always be. For
// example, if one ensures that a `Dictionary` has sufficient capacity to avoid
// reallocation on the next element insertion, the following works ::
//
// var (i, found) = d.find(k) // i is associated with d's buffer
// if found {
// var e = d // now d is sharing its data with e
// e[newKey] = newValue // e now has a unique copy of the data
// return e[i] // use i to access e
// }
//
// The result should be a set of iterator invalidation rules familiar to anyone
// familiar with the C++ standard library. Note that because all accesses to a
// dictionary buffer are bounds-checked, this scheme never compromises memory
// safety.
//
// Bridging
// ========
//
// Bridging `NSDictionary` to `Dictionary`
// ---------------------------------------
//
// `NSDictionary` bridges to `Dictionary<NSObject, AnyObject>` in `O(1)`,
// without memory allocation.
//
// Bridging `Dictionary` to `NSDictionary`
// ---------------------------------------
//
// `Dictionary<K, V>` bridges to `NSDictionary` iff both `K` and `V` are
// bridged. Otherwise, a runtime error is raised.
//
// * if both `K` and `V` are bridged verbatim, then `Dictionary<K, V>` bridges
// to `NSDictionary` in `O(1)`, without memory allocation. Access to
// elements does not cause memory allocation.
//
// * otherwise, `K` and/or `V` are unconditionally or conditionally bridged.
// In this case, `Dictionary<K, V>` is bridged to `NSDictionary` in `O(1)`,
// without memory allocation. Complete bridging is performed when the first
// access to elements happens. The bridged `NSDictionary` has a cache of
// pointers it returned, so that:
// - Every time keys or values are accessed on the bridged `NSDictionary`,
// new objects are not created.
// - Accessing the same element (key or value) multiple times will return
// the same pointer.
//
// Bridging `NSSet` to `Set` and vice versa
// ----------------------------------------
//
// Bridging guarantees for `Set<Element>` are the same as for
// `Dictionary<Element, ()>`.
//
/// This protocol is only used for compile-time checks that
/// every storage type implements all required operations.
internal protocol _HashStorageType {
typealias Key
typealias Value
typealias Index
typealias SequenceElement
var startIndex: Index { get }
var endIndex: Index { get }
@warn_unused_result
func indexForKey(key: Key) -> Index?
@warn_unused_result
func assertingGet(i: Index) -> SequenceElement
@warn_unused_result
func assertingGet(key: Key) -> Value
@warn_unused_result
func maybeGet(key: Key) -> Value?
mutating func updateValue(value: Value, forKey: Key) -> Value?
mutating func removeAtIndex(index: Index) -> SequenceElement
mutating func removeValueForKey(key: Key) -> Value?
mutating func removeAll(keepCapacity keepCapacity: Bool)
var count: Int { get }
@warn_unused_result
static func fromArray(elements: [SequenceElement]) -> Self
}
/// The inverse of the default hash table load factor. Factored out so that it
/// can be used in multiple places in the implementation and stay consistent.
/// Should not be used outside `Dictionary` implementation.
@_transparent
internal var _hashContainerDefaultMaxLoadFactorInverse: Double {
return 1.0 / 0.75
}
#if _runtime(_ObjC)
/// Call `[lhs isEqual: rhs]`.
///
/// This function is part of the runtime because `Bool` type is bridged to
/// `ObjCBool`, which is in Foundation overlay.
@_silgen_name("swift_stdlib_NSObject_isEqual")
internal func _stdlib_NSObject_isEqual(lhs: AnyObject, _ rhs: AnyObject) -> Bool
#endif
//===--- Hacks and workarounds --------------------------------------------===//
/// Like `UnsafeMutablePointer<Unmanaged<AnyObject>>`, or `id
/// __unsafe_unretained *` in Objective-C ARC.
internal struct _UnmanagedAnyObjectArray {
// `UnsafeMutablePointer<Unmanaged<AnyObject>>` fails because of:
// <rdar://problem/16836348> IRGen: Couldn't find conformance
/// Underlying pointer, typed as an integer to escape from reference
/// counting.
internal var value: UnsafeMutablePointer<Int>
internal init(_ up: UnsafeMutablePointer<AnyObject>) {
self.value = UnsafeMutablePointer(up)
}
internal subscript(i: Int) -> AnyObject {
get {
return _reinterpretCastToAnyObject(value[i])
}
nonmutating set(newValue) {
value[i] = unsafeBitCast(newValue, Int.self)
}
}
}
//===--- APIs unique to Set<Element> --------------------------------------===//
/// A collection of unique `Element` instances with no defined ordering.
public struct Set<Element : Hashable> :
Hashable, CollectionType, ArrayLiteralConvertible {
@available(*, unavailable, renamed="Element")
public typealias T = Element
internal typealias _Self = Set<Element>
internal typealias _VariantStorage = _VariantSetStorage<Element>
internal typealias _NativeStorage = _NativeSetStorage<Element>
public typealias Index = SetIndex<Element>
internal var _variantStorage: _VariantStorage
/// Create an empty set with at least the given number of
/// elements worth of storage. The actual capacity will be the
/// smallest power of 2 that's >= `minimumCapacity`.
public init(minimumCapacity: Int) {
_variantStorage =
_VariantStorage.Native(
_NativeStorage.Owner(minimumCapacity: minimumCapacity))
}
/// Private initializer.
internal init(_nativeStorage: _NativeSetStorage<Element>) {
_variantStorage = _VariantStorage.Native(
_NativeStorage.Owner(nativeStorage: _nativeStorage))
}
/// Private initializer.
internal init(_nativeStorageOwner: _NativeSetStorageOwner<Element>) {
_variantStorage = .Native(_nativeStorageOwner)
}
//
// All APIs below should dispatch to `_variantStorage`, without doing any
// additional processing.
//
#if _runtime(_ObjC)
/// Private initializer used for bridging.
///
/// Only use this initializer when both conditions are true:
///
/// * it is statically known that the given `NSSet` is immutable;
/// * `Element` is bridged verbatim to Objective-C (i.e.,
/// is a reference type).
public init(_immutableCocoaSet: _NSSetType) {
_sanityCheck(_isBridgedVerbatimToObjectiveC(Element.self),
"Set can be backed by NSSet _variantStorage only when the member type can be bridged verbatim to Objective-C")
_variantStorage = _VariantSetStorage.Cocoa(
_CocoaSetStorage(cocoaSet: _immutableCocoaSet))
}
#endif
/// The position of the first element in a non-empty set.
///
/// This is identical to `endIndex` in an empty set.
///
/// - Complexity: Amortized O(1) if `self` does not wrap a bridged
/// `NSSet`, O(N) otherwise.
public var startIndex: Index {
return _variantStorage.startIndex
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
///
/// - Complexity: Amortized O(1) if `self` does not wrap a bridged
/// `NSSet`, O(N) otherwise.
public var endIndex: Index {
return _variantStorage.endIndex
}
/// Returns `true` if the set contains a member.
@warn_unused_result
public func contains(member: Element) -> Bool {
return _variantStorage.maybeGet(member) != nil
}
/// Returns the `Index` of a given member, or `nil` if the member is not
/// present in the set.
@warn_unused_result
public func indexOf(member: Element) -> Index? {
return _variantStorage.indexForKey(member)
}
/// Insert a member into the set.
public mutating func insert(member: Element) {
_variantStorage.updateValue(member, forKey: member)
}
/// Remove the member from the set and return it if it was present.
public mutating func remove(member: Element) -> Element? {
return _variantStorage.removeValueForKey(member)
}
/// Remove the member referenced by the given index.
public mutating func removeAtIndex(index: Index) -> Element {
return _variantStorage.removeAtIndex(index)
}
/// Erase all the elements. If `keepCapacity` is `true`, `capacity`
/// will not decrease.
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
_variantStorage.removeAll(keepCapacity: keepCapacity)
}
/// Remove a member from the set and return it.
///
/// - Requires: `count > 0`.
public mutating func removeFirst() -> Element {
_precondition(count > 0, "can't removeFirst from an empty Set")
let member = first!
remove(member)
return member
}
/// The number of members in the set.
///
/// - Complexity: O(1).
public var count: Int {
return _variantStorage.count
}
//
// `SequenceType` conformance
//
/// Access the member at `position`.
///
/// - Complexity: O(1).
public subscript(position: Index) -> Element {
return _variantStorage.assertingGet(position)
}
/// Return a *generator* over the members.
///
/// - Complexity: O(1).
public func generate() -> SetGenerator<Element> {
return _variantStorage.generate()
}
//
// `ArrayLiteralConvertible` conformance
//
public init(arrayLiteral elements: Element...) {
self.init(_nativeStorage: _NativeSetStorage.fromArray(elements))
}
//
// APIs below this comment should be implemented strictly in terms of
// *public* APIs above. `_variantStorage` should not be accessed directly.
//
// This separates concerns for testing. Tests for the following APIs need
// not to concern themselves with testing correctness of behavior of
// underlying storage (and different variants of it), only correctness of the
// API itself.
//
/// Create an empty `Set`.
public init() {
self = Set<Element>(minimumCapacity: 0)
}
/// Create a `Set` from a finite sequence of items.
public init<S : SequenceType where S.Generator.Element == Element>(_ sequence: S) {
self.init()
if let s = sequence as? Set<Element> {
// If this sequence is actually a native `Set`, then we can quickly
// adopt its native storage and let COW handle uniquing only
// if necessary.
switch (s._variantStorage) {
case .Native(let owner):
_variantStorage = .Native(owner)
case .Cocoa(let owner):
_variantStorage = .Cocoa(owner)
}
} else {
for item in sequence {
insert(item)
}
}
}
/// Returns true if the set is a subset of a finite sequence as a `Set`.
@warn_unused_result
public func isSubsetOf<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) -> Bool {
let other = sequence as? Set<Element> ?? Set(sequence)
let (isSubset, isEqual) = _compareSets(self, other)
return isSubset || isEqual
}
/// Returns true if the set is a subset of a finite sequence as a `Set`
/// but not equal.
@warn_unused_result
public func isStrictSubsetOf<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) -> Bool {
let other = sequence as? Set<Element> ?? Set(sequence)
let (isSubset, isEqual) = _compareSets(self, other)
return isSubset && !isEqual
}
/// Returns true if the set is a superset of a finite sequence as a `Set`.
@warn_unused_result
public func isSupersetOf<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) -> Bool {
let other = sequence as? Set<Element> ?? Set(sequence)
return other.isSubsetOf(self)
}
/// Returns true if the set is a superset of a finite sequence as a `Set`
/// but not equal.
@warn_unused_result
public func isStrictSupersetOf<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) -> Bool {
let other = sequence as? Set<Element> ?? Set(sequence)
return other.isStrictSubsetOf(self)
}
/// Returns true if no members in the set are in a finite sequence as a `Set`.
@warn_unused_result
public func isDisjointWith<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) -> Bool {
let other = sequence as? Set<Element> ?? Set(sequence)
for member in self {
if other.contains(member) {
return false
}
}
return true
}
/// Return a new `Set` with items in both this set and a finite sequence.
@warn_unused_result
public func union<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) -> Set<Element> {
var newSet = self
newSet.unionInPlace(sequence)
return newSet
}
/// Insert elements of a finite sequence into this `Set`.
public mutating func unionInPlace<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) {
for item in sequence {
insert(item)
}
}
/// Return a new set with elements in this set that do not occur
/// in a finite sequence.
@warn_unused_result
public func subtract<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) -> Set<Element> {
var newSet = self
newSet.subtractInPlace(sequence)
return newSet
}
/// Remove all members in the set that occur in a finite sequence.
public mutating func subtractInPlace<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) {
for item in sequence {
remove(item)
}
}
/// Return a new set with elements common to this set and a finite sequence.
@warn_unused_result
public func intersect<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) -> Set<Element> {
let other = sequence as? Set<Element> ?? Set(sequence)
var newSet = Set<Element>()
for member in self {
if other.contains(member) {
newSet.insert(member)
}
}
return newSet
}
/// Remove any members of this set that aren't also in a finite sequence.
public mutating func intersectInPlace<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) {
// Because `intersect` needs to both modify and iterate over
// the left-hand side, the index may become invalidated during
// traversal so an intermediate set must be created.
//
// FIXME(performance): perform this operation at a lower level
// to avoid invalidating the index and avoiding a copy.
let result = self.intersect(sequence)
// The result can only have fewer or the same number of elements.
// If no elements were removed, don't perform a reassignment
// as this may cause an unnecessary uniquing COW.
if result.count != count {
self = result
}
}
/// Return a new set with elements that are either in the set or a finite
/// sequence but do not occur in both.
@warn_unused_result
public func exclusiveOr<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) -> Set<Element> {
var newSet = self
newSet.exclusiveOrInPlace(sequence)
return newSet
}
/// For each element of a finite sequence, remove it from the set if it is a
/// common element, otherwise add it to the set. Repeated elements of the
/// sequence will be ignored.
public mutating func exclusiveOrInPlace<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) {
let other = sequence as? Set<Element> ?? Set(sequence)
for member in other {
if contains(member) {
remove(member)
} else {
insert(member)
}
}
}
public var hashValue: Int {
// FIXME: <rdar://problem/18915294> Cache Set<T> hashValue
var result: Int = _mixInt(0)
for member in self {
result ^= _mixInt(member.hashValue)
}
return result
}
//
// `SequenceType` conformance
//
@warn_unused_result
public func _customContainsEquatableElement(member: Element) -> Bool? {
return contains(member)
}
@warn_unused_result
public func _customIndexOfEquatableElement(member: Element) -> Index?? {
return Optional(indexOf(member))
}
//
// CollectionType conformance
//
/// `true` if the set is empty.
public var isEmpty: Bool {
return count == 0
}
/// The first element obtained when iterating, or `nil` if `self` is
/// empty. Equivalent to `self.generate().next()`.
public var first: Element? {
return count > 0 ? self[startIndex] : .None
}
}
/// Check for both subset and equality relationship between
/// a set and some sequence (which may itself be a `Set`).
///
/// (isSubset: lhs ⊂ rhs, isEqual: lhs ⊂ rhs and |lhs| = |rhs|)
@warn_unused_result
internal func _compareSets<Element>(lhs: Set<Element>, _ rhs: Set<Element>)
-> (isSubset: Bool, isEqual: Bool) {
for member in lhs {
if !rhs.contains(member) {
return (false, false)
}
}
return (true, lhs.count == rhs.count)
}
@warn_unused_result
public func == <Element : Hashable>(lhs: Set<Element>, rhs: Set<Element>) -> Bool {
switch (lhs._variantStorage, rhs._variantStorage) {
case (.Native(let lhsNativeOwner), .Native(let rhsNativeOwner)):
let lhsNative = lhsNativeOwner.nativeStorage
let rhsNative = rhsNativeOwner.nativeStorage
// FIXME(performance): early exit if lhs and rhs reference the same
// storage?
if lhsNative.count != rhsNative.count {
return false
}
for member in lhs {
let (_, found) = rhsNative._find(member, rhsNative._bucket(member))
if !found {
return false
}
}
return true
case (_VariantSetStorage.Cocoa(let lhsCocoa),
_VariantSetStorage.Cocoa(let rhsCocoa)):
#if _runtime(_ObjC)
return _stdlib_NSObject_isEqual(lhsCocoa.cocoaSet, rhsCocoa.cocoaSet)
#else
_sanityCheckFailure("internal error: unexpected cocoa set")
#endif
case (_VariantSetStorage.Native(let lhsNativeOwner),
_VariantSetStorage.Cocoa(let rhsCocoa)):
#if _runtime(_ObjC)
let lhsNative = lhsNativeOwner.nativeStorage
if lhsNative.count != rhsCocoa.count {
return false
}
let endIndex = lhsNative.endIndex
for var i = lhsNative.startIndex; i != endIndex; ++i {
let key = lhsNative.assertingGet(i)
let bridgedKey: AnyObject = _bridgeToObjectiveCUnconditional(key)
let optRhsValue: AnyObject? = rhsCocoa.maybeGet(bridgedKey)
if let rhsValue = optRhsValue {
if key == _forceBridgeFromObjectiveC(rhsValue, Element.self) {
continue
}
}
return false
}
return true
#else
_sanityCheckFailure("internal error: unexpected cocoa set")
#endif
case (_VariantSetStorage.Cocoa, _VariantSetStorage.Native):
#if _runtime(_ObjC)
return rhs == lhs
#else
_sanityCheckFailure("internal error: unexpected cocoa set")
#endif
}
}
extension Set : CustomStringConvertible, CustomDebugStringConvertible {
@warn_unused_result
private func makeDescription(isDebug isDebug: Bool) -> String {
var result = isDebug ? "Set([" : "["
var first = true
for member in self {
if first {
first = false
} else {
result += ", "
}
debugPrint(member, terminator: "", toStream: &result)
}
result += isDebug ? "])" : "]"
return result
}
/// A textual representation of `self`.
public var description: String {
return makeDescription(isDebug: false)
}
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
return makeDescription(isDebug: true)
}
}
#if _runtime(_ObjC)
@_silgen_name("swift_stdlib_CFSetGetValues")
func _stdlib_CFSetGetValues(nss: _NSSetType, _: UnsafeMutablePointer<AnyObject>)
/// Equivalent to `NSSet.allObjects`, but does not leave objects on the
/// autorelease pool.
internal func _stdlib_NSSet_allObjects(nss: _NSSetType) ->
_HeapBuffer<Int, AnyObject> {
let count = nss.count
let buffer = _HeapBuffer<Int, AnyObject>(
_HeapBufferStorage<Int, AnyObject>.self, count, count)
_stdlib_CFSetGetValues(nss, buffer.baseAddress)
return buffer
}
#endif
//===--- Compiler conversion/casting entry points for Set<Element> --------===//
#if _runtime(_ObjC)
/// Perform a non-bridged upcast that always succeeds.
///
/// - Requires: `BaseValue` is a base class or base `@objc`
/// protocol (such as `AnyObject`) of `DerivedValue`.
@warn_unused_result
public func _setUpCast<DerivedValue, BaseValue>(source: Set<DerivedValue>)
-> Set<BaseValue> {
_sanityCheck(_isClassOrObjCExistential(BaseValue.self))
_sanityCheck(_isClassOrObjCExistential(DerivedValue.self))
var builder = _SetBuilder<BaseValue>(count: source.count)
for member in source {
builder.add(member: unsafeBitCast(member, BaseValue.self))
}
return builder.take()
}
/// Implements an unconditional upcast that involves bridging.
///
/// The cast can fail if bridging fails.
///
/// - Precondition: `SwiftValue` is bridged to Objective-C
/// and requires non-trivial bridging.
@warn_unused_result
public func _setBridgeToObjectiveC<SwiftValue, ObjCValue>(
source: Set<SwiftValue>
) -> Set<ObjCValue> {
_sanityCheck(_isClassOrObjCExistential(ObjCValue.self))
_sanityCheck(!_isBridgedVerbatimToObjectiveC(SwiftValue.self))
var result = Set<ObjCValue>(minimumCapacity: source.count)
let valueBridgesDirectly =
_isBridgedVerbatimToObjectiveC(SwiftValue.self) ==
_isBridgedVerbatimToObjectiveC(ObjCValue.self)
for member in source {
var bridgedMember: ObjCValue
if valueBridgesDirectly {
bridgedMember = unsafeBitCast(member, ObjCValue.self)
} else {
let bridged: AnyObject? = _bridgeToObjectiveC(member)
_precondition(bridged != nil,
"set member cannot be bridged to Objective-C")
bridgedMember = unsafeBitCast(bridged!, ObjCValue.self)
}
result.insert(bridgedMember)
}
return result
}
/// Implements a forced downcast. This operation should have O(1) complexity.
///
/// The cast can fail if bridging fails. The actual checks and bridging can be
/// deferred.
///
/// - Precondition: `DerivedValue` is a subtype of `BaseValue` and both
/// are reference types.
@warn_unused_result
public func _setDownCast<BaseValue, DerivedValue>(source: Set<BaseValue>)
-> Set<DerivedValue> {
_sanityCheck(_isClassOrObjCExistential(BaseValue.self))
_sanityCheck(_isClassOrObjCExistential(DerivedValue.self))
switch source._variantStorage {
case _VariantSetStorage.Native(let nativeOwner):
return Set(
_immutableCocoaSet:
unsafeBitCast(nativeOwner, _NSSetType.self))
case _VariantSetStorage.Cocoa(let cocoaStorage):
return Set(
_immutableCocoaSet:
unsafeBitCast(cocoaStorage, _NSSetType.self))
}
}
/// Implements a conditional downcast.
///
/// If the cast fails, the function returns `.None`. All checks should be
/// performed eagerly.
///
/// - Precondition: `DerivedValue` is a subtype of `BaseValue` and both
/// are reference types.
@warn_unused_result
public func _setDownCastConditional<BaseValue, DerivedValue>(
source: Set<BaseValue>
) -> Set<DerivedValue>? {
_sanityCheck(_isClassOrObjCExistential(BaseValue.self))
_sanityCheck(_isClassOrObjCExistential(DerivedValue.self))
var result = Set<DerivedValue>(minimumCapacity: source.count)
for member in source {
if let derivedMember = member as? DerivedValue {
result.insert(derivedMember)
continue
}
return .None
}
return result
}
/// Implements an unconditional downcast that involves bridging.
///
/// - Precondition: At least one of `SwiftValue` is a bridged value
/// type, and the corresponding `ObjCValue` is a reference type.
@warn_unused_result
public func _setBridgeFromObjectiveC<ObjCValue, SwiftValue>(
source: Set<ObjCValue>
) -> Set<SwiftValue> {
let result: Set<SwiftValue>? = _setBridgeFromObjectiveCConditional(source)
_precondition(result != nil, "This set cannot be bridged from Objective-C")
return result!
}
/// Implements a conditional downcast that involves bridging.
///
/// If the cast fails, the function returns `.None`. All checks should be
/// performed eagerly.
///
/// - Precondition: At least one of `SwiftValue` is a bridged value
/// type, and the corresponding `ObjCValue` is a reference type.
@warn_unused_result
public func _setBridgeFromObjectiveCConditional<
ObjCValue, SwiftValue
>(
source: Set<ObjCValue>
) -> Set<SwiftValue>? {
_sanityCheck(_isClassOrObjCExistential(ObjCValue.self))
_sanityCheck(!_isBridgedVerbatimToObjectiveC(SwiftValue.self))
let valueBridgesDirectly =
_isBridgedVerbatimToObjectiveC(SwiftValue.self) ==
_isBridgedVerbatimToObjectiveC(ObjCValue.self)
var result = Set<SwiftValue>(minimumCapacity: source.count)
for value in source {
// Downcast the value.
var resultValue: SwiftValue
if valueBridgesDirectly {
if let bridgedValue = value as? SwiftValue {
resultValue = bridgedValue
} else {
return nil
}
} else {
if let bridgedValue = _conditionallyBridgeFromObjectiveC(
_reinterpretCastToAnyObject(value), SwiftValue.self) {
resultValue = bridgedValue
} else {
return nil
}
}
result.insert(resultValue)
}
return result
}
#endif
//===--- APIs unique to Dictionary<Key, Value> ----------------------------===//
/// A hash-based mapping from `Key` to `Value` instances. Also a
/// collection of key-value pairs with no defined ordering.
public struct Dictionary<Key : Hashable, Value> :
CollectionType, DictionaryLiteralConvertible {
internal typealias _Self = Dictionary<Key, Value>
internal typealias _VariantStorage = _VariantDictionaryStorage<Key, Value>
internal typealias _NativeStorage = _NativeDictionaryStorage<Key, Value>
public typealias Element = (Key, Value)
public typealias Index = DictionaryIndex<Key, Value>
internal var _variantStorage: _VariantStorage
/// Create an empty dictionary.
public init() {
self = Dictionary<Key, Value>(minimumCapacity: 0)
}
/// Create a dictionary with at least the given number of
/// elements worth of storage. The actual capacity will be the
/// smallest power of 2 that's >= `minimumCapacity`.
public init(minimumCapacity: Int) {
_variantStorage =
.Native(_NativeStorage.Owner(minimumCapacity: minimumCapacity))
}
/// Private initializer.
internal init(_nativeStorage: _NativeDictionaryStorage<Key, Value>) {
_variantStorage =
.Native(_NativeStorage.Owner(nativeStorage: _nativeStorage))
}
/// Private initializer.
internal init(_nativeStorageOwner:
_NativeDictionaryStorageOwner<Key, Value>) {
_variantStorage = .Native(_nativeStorageOwner)
}
#if _runtime(_ObjC)
/// Private initializer used for bridging.
///
/// Only use this initializer when both conditions are true:
///
/// * it is statically known that the given `NSDictionary` is immutable;
/// * `Key` and `Value` are bridged verbatim to Objective-C (i.e.,
/// are reference types).
public init(_immutableCocoaDictionary: _NSDictionaryType) {
_sanityCheck(
_isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self),
"Dictionary can be backed by NSDictionary storage only when both key and value are bridged verbatim to Objective-C")
_variantStorage = .Cocoa(
_CocoaDictionaryStorage(cocoaDictionary: _immutableCocoaDictionary))
}
#endif