Skip to content

Conversation

kazutakahirata
Copy link
Contributor

We can avoid repeating the same code in count by delegating to
contains.

While I am at it, this patch adds [[nodiscard] to contains and count.

We can avoid repeating the same code in count by delegating to
contains.

While I am at it, this patch adds [[nodiscard] to contains and count.
@llvmbot
Copy link
Member

llvmbot commented Aug 28, 2025

@llvm/pr-subscribers-llvm-adt

Author: Kazu Hirata (kazutakahirata)

Changes

We can avoid repeating the same code in count by delegating to
contains.

While I am at it, this patch adds [[nodiscard] to contains and count.


Full diff: https://github.com/llvm/llvm-project/pull/155789.diff

1 Files Affected:

  • (modified) llvm/include/llvm/ADT/SetVector.h (+3-7)
diff --git a/llvm/include/llvm/ADT/SetVector.h b/llvm/include/llvm/ADT/SetVector.h
index 85d4f2d5ee28a..ecd39f2809fb8 100644
--- a/llvm/include/llvm/ADT/SetVector.h
+++ b/llvm/include/llvm/ADT/SetVector.h
@@ -261,7 +261,7 @@ class SetVector {
   }
 
   /// Check if the SetVector contains the given key.
-  bool contains(const key_type &key) const {
+  [[nodiscard]] bool contains(const key_type &key) const {
     if constexpr (canBeSmall())
       if (isSmall())
         return is_contained(vector_, key);
@@ -271,12 +271,8 @@ class SetVector {
 
   /// Count the number of elements of a given key in the SetVector.
   /// \returns 0 if the element is not in the SetVector, 1 if it is.
-  size_type count(const key_type &key) const {
-    if constexpr (canBeSmall())
-      if (isSmall())
-        return is_contained(vector_, key);
-
-    return set_.count(key);
+  [[nodiscard]] size_type count(const key_type &key) const {
+    return contains(key) ? 1 : 0;
   }
 
   /// Completely clear the SetVector

Copy link
Member

@kuhar kuhar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, I really like the nodiscard attributes

@kazutakahirata kazutakahirata merged commit 026918d into llvm:main Aug 28, 2025
11 checks passed
@kazutakahirata kazutakahirata deleted the cleanup_20250827_SetVector_contains branch August 28, 2025 14:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants