diff options
author | Duncan P. N. Exon Smith <dexonsmith@apple.com> | 2020-12-03 19:26:56 -0800 |
---|---|---|
committer | Duncan P. N. Exon Smith <dexonsmith@apple.com> | 2020-12-08 15:25:03 -0800 |
commit | caab41c08e36872d91dddd4a05a5d98948802ac7 (patch) | |
tree | 1e24e0ae07014365e87b575efa8bec83d762c6ef | |
parent | e8021f34e1bae8537aba3c834ff0a9a73ad93405 (diff) | |
download | llvm-caab41c08e36872d91dddd4a05a5d98948802ac7.zip llvm-caab41c08e36872d91dddd4a05a5d98948802ac7.tar.gz llvm-caab41c08e36872d91dddd4a05a5d98948802ac7.tar.bz2 |
ADT: Add hash_value overload for Optional
Add a `hash_value` for Optional so that other data structures with
optional fields can easily hash them. I have a use for this in an
upcoming patch.
Differential Revision: https://reviews.llvm.org/D92676
-rw-r--r-- | llvm/include/llvm/ADT/Optional.h | 5 | ||||
-rw-r--r-- | llvm/unittests/ADT/OptionalTest.cpp | 17 |
2 files changed, 22 insertions, 0 deletions
diff --git a/llvm/include/llvm/ADT/Optional.h b/llvm/include/llvm/ADT/Optional.h index be32178..daa9ee6 100644 --- a/llvm/include/llvm/ADT/Optional.h +++ b/llvm/include/llvm/ADT/Optional.h @@ -15,6 +15,7 @@ #ifndef LLVM_ADT_OPTIONAL_H #define LLVM_ADT_OPTIONAL_H +#include "llvm/ADT/Hashing.h" #include "llvm/ADT/None.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/type_traits.h" @@ -299,6 +300,10 @@ public: #endif }; +template <class T> llvm::hash_code hash_value(const Optional<T> &O) { + return O ? hash_combine(true, *O) : hash_value(false); +} + template <typename T, typename U> constexpr bool operator==(const Optional<T> &X, const Optional<U> &Y) { if (X && Y) diff --git a/llvm/unittests/ADT/OptionalTest.cpp b/llvm/unittests/ADT/OptionalTest.cpp index 17a7640..c7fa796 100644 --- a/llvm/unittests/ADT/OptionalTest.cpp +++ b/llvm/unittests/ADT/OptionalTest.cpp @@ -599,4 +599,21 @@ TEST(OptionalTest, UseInUnitTests) { EXPECT_NONFATAL_FAILURE(EXPECT_EQ(llvm::None, Comparable::get()), "object"); } +TEST(OptionalTest, HashValue) { + // Check that None, false, and true all hash differently. + Optional<bool> B, B0 = false, B1 = true; + EXPECT_NE(hash_value(B0), hash_value(B)); + EXPECT_NE(hash_value(B1), hash_value(B)); + EXPECT_NE(hash_value(B1), hash_value(B0)); + + // Check that None, 0, and 1 all hash differently. + Optional<int> I, I0 = 0, I1 = 1; + EXPECT_NE(hash_value(I0), hash_value(I)); + EXPECT_NE(hash_value(I1), hash_value(I)); + EXPECT_NE(hash_value(I1), hash_value(I0)); + + // Check None hash the same way regardless of type. + EXPECT_EQ(hash_value(B), hash_value(I)); +} + } // end anonymous namespace |