Skip to content

Commit d2d3c0c

Browse files
committed
[stdlib] Implement Set.contains without retrieving the stored value
1 parent 2213b4e commit d2d3c0c

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

stdlib/public/core/Set.swift

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ extension Set: Sequence {
258258
/// - Complexity: O(1)
259259
@inlinable
260260
public func contains(_ member: Element) -> Bool {
261-
return _variant.maybeGet(member) != nil
261+
return _variant.contains(member)
262262
}
263263

264264
@inlinable
@@ -1499,6 +1499,7 @@ internal protocol _SetBuffer { // FIXME: Remove or refactor for Set.
14991499
func index(forKey key: Element) -> Index?
15001500
var count: Int { get }
15011501

1502+
func contains(_ member: Element) -> Bool
15021503
func assertingGet(at i: Index) -> Element
15031504
func maybeGet(_ key: Element) -> Element?
15041505
}
@@ -2235,6 +2236,16 @@ extension _NativeSet/*: _SetBuffer*/ where Element: Hashable {
22352236
return found ? i : nil
22362237
}
22372238

2239+
@inlinable
2240+
@inline(__always)
2241+
internal func contains(_ member: Element) -> Bool {
2242+
if count == 0 {
2243+
// Fast path that avoids computing the hash of the key.
2244+
return false
2245+
}
2246+
return _find(member).found
2247+
}
2248+
22382249
@inlinable // FIXME(sil-serialize-all)
22392250
@inline(__always)
22402251
internal func maybeGet(_ key: Element) -> Element? {
@@ -2560,6 +2571,11 @@ internal struct _CocoaSet: _SetBuffer {
25602571
return object.count
25612572
}
25622573

2574+
@inlinable
2575+
internal func contains(_ element: AnyObject) -> Bool {
2576+
return object.member(element) != nil
2577+
}
2578+
25632579
@inlinable // FIXME(sil-serialize-all)
25642580
internal func assertingGet(at i: Index) -> AnyObject {
25652581
let value: AnyObject? = i.allKeys[i.currentKeyIndex]
@@ -2890,6 +2906,23 @@ extension Set._Variant: _SetBuffer {
28902906
}
28912907
}
28922908

2909+
@inlinable
2910+
@inline(__always)
2911+
internal func contains(_ member: Element) -> Bool {
2912+
if _fastPath(guaranteedNative) {
2913+
return asNative.contains(member)
2914+
}
2915+
switch self {
2916+
case .native(let native):
2917+
return native.contains(member)
2918+
#if _runtime(_ObjC)
2919+
case .cocoa(let cocoa):
2920+
let cocoaKey = _bridgeAnythingToObjectiveC(member)
2921+
return cocoa.contains(cocoaKey)
2922+
#endif
2923+
}
2924+
}
2925+
28932926
#if _runtime(_ObjC)
28942927
@inline(never)
28952928
@usableFromInline

0 commit comments

Comments
 (0)