[libcxx-commits] [libcxx] [libc++][NFC] Add a static assertion to document an assumption in std::hash (PR #114440)
Louis Dionne via libcxx-commits
libcxx-commits at lists.llvm.org
Thu Oct 31 11:12:48 PDT 2024
https://github.com/ldionne created https://github.com/llvm/llvm-project/pull/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.
>From 28ce5673b27fb9b0660acf1f88555b8b5aff3a10 Mon Sep 17 00:00:00 2001
From: Louis Dionne <ldionne.2 at gmail.com>
Date: Thu, 31 Oct 2024 14:10:37 -0400
Subject: [PATCH] [libc++][NFC] Add a static assertion to document an
assumption in std::hash
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.
---
libcxx/include/__functional/hash.h | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
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