[libcxx-commits] [libcxx] [libc++] Optimizations for uniform_int_distribution (PR #140161)
via libcxx-commits
libcxx-commits at lists.llvm.org
Sun Jun 15 17:50:33 PDT 2025
================
@@ -64,7 +64,7 @@ class __independent_bits_engine {
_LIBCPP_HIDE_FROM_ABI __independent_bits_engine(_Engine& __e, size_t __w);
----------------
LRFLEW wrote:
I went ahead and added the asserts to to the constructor, since they do make sense to add. The implementation does result in UB if they're violated, so it's reasonable to assert them.
The assumption *shouldn't* be affected by user choices. The less strict assumption `0 <= w <= numeric_limits<result_type>::digits` is based on the purpose of `w`. A negative value for `w` would mean sampling a negative number of bits, which doesn't make sense, and a value of `w` larger than `numeric_limits<result_type>::digits` means the result type cannot fit the requested number of random bits. In either case, the parameter is an error, and shouldn't occur due to the definition of `w` being `w = floor(log_2(__p.b() - __p.a() + 1))` (with the intermediary value `__p.b() - __p.a() + 1` specifically cast to the type used for `result_type`).
This PR makes the additional assumption that `w != 0`. This can only be safely made because the only way that it could occur in `uniform_int_distribution::operator()` is when `__p.b() == __p.a()`, and that case has its own early conditional return statement, so `__independent_bits_engine` is never constructed with `w == 0`.
https://github.com/llvm/llvm-project/pull/140161
More information about the libcxx-commits
mailing list