[libcxx-commits] [libcxx] [libc++][NFC] Add a static assertion to document an assumption in std::hash (PR #114440)

via libcxx-commits libcxx-commits at lists.llvm.org
Thu Oct 31 11:13:28 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libcxx

Author: Louis Dionne (ldionne)

<details>
<summary>Changes</summary>

The implementation of std::hash for unsigned long makes the (correct) assumption that size_t is at least as large as unsigned long. If that were not the case on a platform, the implementation of std::hash for unsigned long would be absolutely terrible. Add a static assertion to document that assumption.

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


1 Files Affected:

- (modified) libcxx/include/__functional/hash.h (+5-1) 


``````````diff
diff --git a/libcxx/include/__functional/hash.h b/libcxx/include/__functional/hash.h
index f7b89f759b5f5c..87009dfa62ef59 100644
--- a/libcxx/include/__functional/hash.h
+++ b/libcxx/include/__functional/hash.h
@@ -406,7 +406,11 @@ struct _LIBCPP_TEMPLATE_VIS hash<long> : public __unary_function<long, size_t> {
 
 template <>
 struct _LIBCPP_TEMPLATE_VIS hash<unsigned long> : public __unary_function<unsigned long, size_t> {
-  _LIBCPP_HIDE_FROM_ABI size_t operator()(unsigned long __v) const _NOEXCEPT { return static_cast<size_t>(__v); }
+  _LIBCPP_HIDE_FROM_ABI size_t operator()(unsigned long __v) const _NOEXCEPT {
+    static_assert(sizeof(size_t) >= sizeof(unsigned long),
+                  "This would be a terrible hash function on a platform where size_t is smaller than unsigned long");
+    return static_cast<size_t>(__v);
+  }
 };
 
 template <>

``````````

</details>


https://github.com/llvm/llvm-project/pull/114440


More information about the libcxx-commits mailing list