[libcxx-commits] [PATCH] D66836: [libc++] Add `__truncating_cast` for safely casting float types to integers

Steve Canon via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Wed Aug 28 12:36:54 PDT 2019


scanon added inline comments.


================
Comment at: include/math.h:1582
+  const _RealT __trunc_r = __builtin_trunc(__r);
+  if (__trunc_r >= ::nextafter(static_cast<_RealT>(_MaxVal), INFINITY)) {
+    return _Lim::max();
----------------
EricWF wrote:
> scanon wrote:
> > zoecarver wrote:
> > > Maybe change `INFINITY` to `std::numeric_limits< _RealT >::infinity()`
> > Why isn't this just `__trunc_r > _MaxVal`?
> Consider `long long` and `double`. `MaxVal - numeric_limits<long long>::max() == 1024`, and we want values between `MaxVal` and `::max()` to round down. So instead we essentially check for `__r >= numeric_limits<long long>::max() + 1`. This approach seems more accurate.
> Consider long long and double. MaxVal - numeric_limits<long long>::max() == 1024, and we want values between MaxVal and ::max() to round down. So instead we essentially check for __r >= numeric_limits<long long>::max() + 1

Yes, but there are no values between MaxVal and ::max() in the floating-point format; if there were, they would be MaxVal instead. So you can ditch the nextafter and just use `> static_cast<_FloatT>(MaxVal)`.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D66836/new/

https://reviews.llvm.org/D66836





More information about the libcxx-commits mailing list