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

via libcxx-commits libcxx-commits at lists.llvm.org
Fri Nov 1 09:58:18 PDT 2024


Author: Louis Dionne
Date: 2024-11-01T12:58:15-04:00
New Revision: d301b59b7b4582b0119281308e86b7c0b3f77a54

URL: https://github.com/llvm/llvm-project/commit/d301b59b7b4582b0119281308e86b7c0b3f77a54
DIFF: https://github.com/llvm/llvm-project/commit/d301b59b7b4582b0119281308e86b7c0b3f77a54.diff

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

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.

Added: 
    

Modified: 
    libcxx/include/__functional/hash.h

Removed: 
    


################################################################################
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 <>


        


More information about the libcxx-commits mailing list