optimize contains method in CxxSet

This commit is contained in:
Crazy凡
2025-11-13 00:25:48 +08:00
parent 33b40cbbe6
commit f4eecc9fba
2 changed files with 15 additions and 20 deletions

View File

@@ -996,11 +996,6 @@ void swift::conformToCxxSetIfNeeded(ClangImporter::Implementation &impl,
insert->getResultInterfaceType());
impl.addSynthesizedProtocolAttrs(decl, {KnownProtocolKind::CxxSet});
// If this isn't a std::multiset, try to also synthesize the conformance to
// CxxUniqueSet.
if (!isStdDecl(clangDecl, {"set", "unordered_set"}))
return;
ProtocolDecl *cxxInputIteratorProto =
ctx.getProtocol(KnownProtocolKind::UnsafeCxxInputIterator);
if (!cxxInputIteratorProto)
@@ -1025,6 +1020,12 @@ void swift::conformToCxxSetIfNeeded(ClangImporter::Implementation &impl,
rawIteratorTy);
impl.addSynthesizedTypealias(decl, ctx.getIdentifier("RawMutableIterator"),
rawMutableIteratorTy);
// If this isn't a std::multiset, try to also synthesize the conformance to
// CxxUniqueSet.
if (!isStdDecl(clangDecl, {"set", "unordered_set"}))
return;
impl.addSynthesizedProtocolAttrs(decl, {KnownProtocolKind::CxxUniqueSet});
}

View File

@@ -19,16 +19,22 @@
public protocol CxxSet<Element>: ExpressibleByArrayLiteral {
associatedtype Element
associatedtype Size: BinaryInteger
associatedtype RawIterator: UnsafeCxxInputIterator
where RawIterator.Pointee == Element
associatedtype RawMutableIterator: UnsafeCxxInputIterator
where RawMutableIterator.Pointee == Element
// std::pair<iterator, bool> for std::set and std::unordered_set
// iterator for std::multiset
associatedtype InsertionResult
associatedtype InsertionResult
init()
func __endUnsafe() -> RawIterator
func __findUnsafe(_ value: Element) -> RawIterator
@discardableResult
mutating func __insertUnsafe(_ element: Element) -> InsertionResult
func count(_ element: Element) -> Size
}
@@ -56,7 +62,7 @@ extension CxxSet {
/// in the set.
@inlinable
public func contains(_ element: Element) -> Bool {
return count(element) > 0
return self.__findUnsafe(element) != self.__endUnsafe()
}
}
@@ -65,23 +71,11 @@ extension CxxSet {
/// C++ standard library types such as `std::set` and `std::unordered_set`
/// conform to this protocol.
public protocol CxxUniqueSet<Element>: CxxSet {
override associatedtype Element
override associatedtype Size: BinaryInteger
associatedtype RawIterator: UnsafeCxxInputIterator
where RawIterator.Pointee == Element
associatedtype RawMutableIterator: UnsafeCxxInputIterator
where RawMutableIterator.Pointee == Element
override associatedtype InsertionResult
where InsertionResult: CxxPair<RawMutableIterator, Bool>
@discardableResult
mutating func __findUnsafe(_ value: Element) -> RawIterator
@discardableResult
mutating func __eraseUnsafe(_ iter: RawIterator) -> RawMutableIterator
@discardableResult
mutating func __endUnsafe() -> RawIterator
}
extension CxxUniqueSet {