[libcxx-commits] [libcxx] linear_congruential_engine: add using more precision to prevent overflow (PR #81583)
via libcxx-commits
libcxx-commits at lists.llvm.org
Sat Apr 13 17:05:37 PDT 2024
================
@@ -30,28 +30,45 @@ template <unsigned long long __a,
unsigned long long __c,
unsigned long long __m,
unsigned long long _Mp,
- bool _MightOverflow = (__a != 0 && __m != 0 && __m - 1 > (_Mp - __c) / __a),
- bool _OverflowOK = ((__m & (__m - 1)) == 0ull), // m = 2^n
- bool _SchrageOK = (__a != 0 && __m != 0 && __m % __a <= __m / __a)> // r <= q
+ bool _HasOverflow = (__a != 0ull && (__m & (__m - 1ull)) != 0ull), // a != 0, m != 0, m != 2^n
+ bool _Full = (!_HasOverflow || __m - 1ull <= (_Mp - __c) / __a), // (a * x + c) % m works
+ bool _Part = (!_HasOverflow || __m - 1ull <= _Mp / __a), // (a * x) % m works
+ bool _Schrage = (_HasOverflow && __m % __a <= __m / __a)> // r <= q
struct __lce_alg_picker {
- static_assert(!_MightOverflow || _OverflowOK || _SchrageOK,
- "The current values of a, c, and m cannot generate a number "
- "within bounds of linear_congruential_engine.");
+ static _LIBCPP_CONSTEXPR const int __mode = _Full ? 0 : _Part ? 1 : _Schrage ? 2 : 3;
- static _LIBCPP_CONSTEXPR const bool __use_schrage = _MightOverflow && !_OverflowOK && _SchrageOK;
+#ifdef _LIBCPP_HAS_NO_INT128
+ static_assert(_Mp != (unsigned long long)(~0) || _Full || _Part || _Schrage,
+ "The current values for a, c, and m are not currently supported on platforms without __int128");
+#endif
};
template <unsigned long long __a,
unsigned long long __c,
unsigned long long __m,
unsigned long long _Mp,
- bool _UseSchrage = __lce_alg_picker<__a, __c, __m, _Mp>::__use_schrage>
+ int _Mode = __lce_alg_picker<__a, __c, __m, _Mp>::__mode>
struct __lce_ta;
// 64
+#ifndef _LIBCPP_HAS_NO_INT128
+template <unsigned long long _Ap, unsigned long long _Cp, unsigned long long _Mp>
+struct __lce_ta<_Ap, _Cp, _Mp, (unsigned long long)(~0), 3> {
+ typedef unsigned long long result_type;
+ _LIBCPP_HIDE_FROM_ABI static result_type next(result_type __xp) {
+ __extension__ typedef unsigned __int128 calc_type;
----------------
LRFLEW wrote:
I used `typedef` here mostly because this header uses `typedef` in a number of places (eg. all the `result_type` typedefs), most likely due to its origin as a TR1 header. I went ahead and changed this one instance to use `using` because I do think it looks better, but haven't touched any of the other `typedef` statements in this header.
Similarly, I hadn't __uglified the type name due to the un-uglified `result_type` type definitions for the `__lce_ta` specializations. I went ahead and made that change for this type definition, though.
https://github.com/llvm/llvm-project/pull/81583
More information about the libcxx-commits
mailing list