tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

FloatingPoint.cpp (1460B)


      1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
      2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
      3 /* This Source Code Form is subject to the terms of the Mozilla Public
      4 * License, v. 2.0. If a copy of the MPL was not distributed with this
      5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      6 
      7 /* Implementations of FloatingPoint functions */
      8 
      9 #include "mozilla/FloatingPoint.h"
     10 
     11 #include <cfloat>  // for FLT_MAX
     12 #include <cmath>
     13 
     14 namespace mozilla {
     15 
     16 bool IsFloat32Representable(double aValue) {
     17  // NaNs and infinities are representable.
     18  if (!std::isfinite(aValue)) {
     19    return true;
     20  }
     21 
     22  // If it exceeds finite |float| range, casting to |double| is always undefined
     23  // behavior per C++11 [conv.double]p1 last sentence.
     24  if (Abs(aValue) > FLT_MAX) {
     25    return false;
     26  }
     27 
     28  // But if it's within finite range, then either it's 1) an exact value and so
     29  // representable, or 2) it's "between two adjacent destination values" and
     30  // safe to cast to "an implementation-defined choice of either of those
     31  // values".
     32  auto valueAsFloat = static_cast<float>(aValue);
     33 
     34  // Per [conv.fpprom] this never changes value.
     35  auto valueAsFloatAsDouble = static_cast<double>(valueAsFloat);
     36 
     37  // Finally, in 1) exact representable value equals exact representable value,
     38  // or 2) *changed* value does not equal original value, ergo unrepresentable.
     39  return valueAsFloatAsDouble == aValue;
     40 }
     41 
     42 } /* namespace mozilla */