Changeset 242048 in webkit


Ignore:
Timestamp:
Feb 25, 2019 10:59:01 AM (5 years ago)
Author:
commit-queue@webkit.org
Message:

Update double-conversion to the latest version
https://bugs.webkit.org/show_bug.cgi?id=194994

Import the latest version of the double-conversion library based on
https://github.com/google/double-conversion/commit/990c44707c70832dc1ce1578048c2198bafd3307

In additon to importing the code, the following changes were applied (or re-applied) to maintain
parity with what we had previously:

  • Add #include "config.h" to each cpp file.
  • Put everything inside the WTF namespace.
  • Changed all in library includes to be of the form #include <wtf/dtoa/FILE.h>.
  • Renamed double_conversion::Vector<> to double_conversion::BufferReference<>.
  • Replaced duplicated functions with ASCIICType.h variants
  • Made CachedPower table a constexpr.
  • Exported (via WTF_EXPORT_PRIVATE) several functions in double-conversion.h.
  • Made substantial changes to StringToDoubleConverter to avoid unnecessary overhead of parameterization, as we only ever want one configuration. Instead of constructing a configured class and calling StringToDouble on it, StringToDouble is now a static function. This allows a bunch of now dead code (hex support, octal support, etc.) to be eliminated. As StringToDoubleConverter now supports single precision floats, some additional templating of StringToIeee was added to avoid extra unnecessary branching.
  • Added RemoveCharacters function to double_conversion::StringBuilder.

Patch by Sam Weinig <sam@webkit.org> on 2019-02-25
Reviewed by Darin Adler.

  • WTF.xcodeproj/project.pbxproj:
  • wtf/CMakeLists.txt:
  • wtf/dtoa/AUTHORS: Added.
  • wtf/dtoa/README: Removed.
  • wtf/dtoa/README.md: Added.
  • wtf/dtoa/bignum-dtoa.cc:
  • wtf/dtoa/bignum-dtoa.h:
  • wtf/dtoa/bignum.cc:
  • wtf/dtoa/bignum.h:

(WTF::double_conversion::Bignum::Times10):
(WTF::double_conversion::Bignum::Equal):
(WTF::double_conversion::Bignum::LessEqual):
(WTF::double_conversion::Bignum::Less):
(WTF::double_conversion::Bignum::PlusEqual):
(WTF::double_conversion::Bignum::PlusLessEqual):
(WTF::double_conversion::Bignum::PlusLess):
(WTF::double_conversion::Bignum::EnsureCapacity):
(WTF::double_conversion::Bignum::BigitLength const):

  • wtf/dtoa/cached-powers.cc:
  • wtf/dtoa/cached-powers.h:
  • wtf/dtoa/diy-fp.cc:
  • wtf/dtoa/diy-fp.h:

(WTF::double_conversion::DiyFp::DiyFp):
(WTF::double_conversion::DiyFp::Subtract):
(WTF::double_conversion::DiyFp::Minus):
(WTF::double_conversion::DiyFp::Times):
(WTF::double_conversion::DiyFp::Normalize):
(WTF::double_conversion::DiyFp::f const):
(WTF::double_conversion::DiyFp::e const):
(WTF::double_conversion::DiyFp::set_f):
(WTF::double_conversion::DiyFp::set_e):

  • wtf/dtoa/double-conversion.cc:
  • wtf/dtoa/double-conversion.h:

(WTF::double_conversion::DoubleToStringConverter::DoubleToStringConverter):
(WTF::double_conversion::DoubleToStringConverter::ToShortest const):
(WTF::double_conversion::DoubleToStringConverter::ToShortestSingle const):
(WTF::double_conversion::StringToDoubleConverter::StringToDoubleConverter):

  • wtf/dtoa/double.h: Removed.
  • wtf/dtoa/fast-dtoa.cc:
  • wtf/dtoa/fast-dtoa.h:
  • wtf/dtoa/fixed-dtoa.cc:
  • wtf/dtoa/fixed-dtoa.h:
  • wtf/dtoa/ieee.h: Added.

(WTF::double_conversion::double_to_uint64):
(WTF::double_conversion::uint64_to_double):
(WTF::double_conversion::float_to_uint32):
(WTF::double_conversion::uint32_to_float):
(WTF::double_conversion::Double::Double):
(WTF::double_conversion::Double::AsDiyFp const):
(WTF::double_conversion::Double::AsNormalizedDiyFp const):
(WTF::double_conversion::Double::AsUint64 const):
(WTF::double_conversion::Double::NextDouble const):
(WTF::double_conversion::Double::PreviousDouble const):
(WTF::double_conversion::Double::Exponent const):
(WTF::double_conversion::Double::Significand const):
(WTF::double_conversion::Double::IsDenormal const):
(WTF::double_conversion::Double::IsSpecial const):
(WTF::double_conversion::Double::IsNan const):
(WTF::double_conversion::Double::IsInfinite const):
(WTF::double_conversion::Double::Sign const):
(WTF::double_conversion::Double::UpperBoundary const):
(WTF::double_conversion::Double::NormalizedBoundaries const):
(WTF::double_conversion::Double::LowerBoundaryIsCloser const):
(WTF::double_conversion::Double::value const):
(WTF::double_conversion::Double::SignificandSizeForOrderOfMagnitude):
(WTF::double_conversion::Double::Infinity):
(WTF::double_conversion::Double::NaN):
(WTF::double_conversion::Double::DiyFpToUint64):
(WTF::double_conversion::Single::Single):
(WTF::double_conversion::Single::AsDiyFp const):
(WTF::double_conversion::Single::AsUint32 const):
(WTF::double_conversion::Single::Exponent const):
(WTF::double_conversion::Single::Significand const):
(WTF::double_conversion::Single::IsDenormal const):
(WTF::double_conversion::Single::IsSpecial const):
(WTF::double_conversion::Single::IsNan const):
(WTF::double_conversion::Single::IsInfinite const):
(WTF::double_conversion::Single::Sign const):
(WTF::double_conversion::Single::NormalizedBoundaries const):
(WTF::double_conversion::Single::UpperBoundary const):
(WTF::double_conversion::Single::LowerBoundaryIsCloser const):
(WTF::double_conversion::Single::value const):
(WTF::double_conversion::Single::Infinity):
(WTF::double_conversion::Single::NaN):

  • wtf/dtoa/strtod.cc:
  • wtf/dtoa/strtod.h:
  • wtf/dtoa/utils.h:

(abort_noreturn):
(WTF::double_conversion::Max):
(WTF::double_conversion::Min):
(WTF::double_conversion::StrLength):
(WTF::double_conversion::BufferReference::BufferReference):
(WTF::double_conversion::BufferReference::SubVector):
(WTF::double_conversion::BufferReference::length const):
(WTF::double_conversion::BufferReference::is_empty const):
(WTF::double_conversion::BufferReference::start const):
(WTF::double_conversion::BufferReference::operator[] const):
(WTF::double_conversion::BufferReference::first):
(WTF::double_conversion::BufferReference::last):
(WTF::double_conversion::StringBuilder::StringBuilder):
(WTF::double_conversion::StringBuilder::~StringBuilder):
(WTF::double_conversion::StringBuilder::size const):
(WTF::double_conversion::StringBuilder::position const):
(WTF::double_conversion::StringBuilder::Reset):
(WTF::double_conversion::StringBuilder::AddCharacter):
(WTF::double_conversion::StringBuilder::AddString):
(WTF::double_conversion::StringBuilder::AddSubstring):
(WTF::double_conversion::StringBuilder::AddPadding):
(WTF::double_conversion::StringBuilder::RemoveCharacters):
(WTF::double_conversion::StringBuilder::Finalize):
(WTF::double_conversion::StringBuilder::is_finalized const):
(WTF::double_conversion::BitCast):
(WTF::double_conversion::BufferReference::SubBufferReference): Deleted.
(WTF::double_conversion::StringBuilder::SetPosition): Deleted.

Location:
trunk/Source/WTF
Files:
3 added
2 deleted
20 edited

Legend:

Unmodified
Added
Removed
  • trunk/Source/WTF/ChangeLog

    r242014 r242048  
     12019-02-25  Sam Weinig  <sam@webkit.org>
     2
     3        Update double-conversion to the latest version
     4        https://bugs.webkit.org/show_bug.cgi?id=194994
     5
     6        Import the latest version of the double-conversion library based on
     7        https://github.com/google/double-conversion/commit/990c44707c70832dc1ce1578048c2198bafd3307
     8
     9        In additon to importing the code, the following changes were applied (or re-applied) to maintain
     10        parity with what we had previously:
     11             - Add #include "config.h" to each cpp file.
     12             - Put everything inside the WTF namespace.
     13             - Changed all in library includes to be of the form #include <wtf/dtoa/FILE.h>.
     14             - Renamed double_conversion::Vector<> to double_conversion::BufferReference<>.
     15             - Replaced duplicated functions with ASCIICType.h variants
     16             - Made CachedPower table a constexpr.
     17             - Exported (via WTF_EXPORT_PRIVATE) several functions in double-conversion.h.
     18             - Made substantial changes to StringToDoubleConverter to avoid unnecessary overhead of
     19               parameterization, as we only ever want one configuration. Instead of constructing a
     20               configured class and calling StringToDouble on it, StringToDouble is now a static
     21               function. This allows a bunch of now dead code (hex support, octal support, etc.) to
     22               be eliminated. As StringToDoubleConverter now supports single precision floats, some
     23               additional templating of StringToIeee was added to avoid extra unnecessary branching.
     24             - Added RemoveCharacters function to double_conversion::StringBuilder.
     25
     26        Reviewed by Darin Adler.
     27
     28        * WTF.xcodeproj/project.pbxproj:
     29        * wtf/CMakeLists.txt:
     30        * wtf/dtoa/AUTHORS: Added.
     31        * wtf/dtoa/README: Removed.
     32        * wtf/dtoa/README.md: Added.
     33        * wtf/dtoa/bignum-dtoa.cc:
     34        * wtf/dtoa/bignum-dtoa.h:
     35        * wtf/dtoa/bignum.cc:
     36        * wtf/dtoa/bignum.h:
     37        (WTF::double_conversion::Bignum::Times10):
     38        (WTF::double_conversion::Bignum::Equal):
     39        (WTF::double_conversion::Bignum::LessEqual):
     40        (WTF::double_conversion::Bignum::Less):
     41        (WTF::double_conversion::Bignum::PlusEqual):
     42        (WTF::double_conversion::Bignum::PlusLessEqual):
     43        (WTF::double_conversion::Bignum::PlusLess):
     44        (WTF::double_conversion::Bignum::EnsureCapacity):
     45        (WTF::double_conversion::Bignum::BigitLength const):
     46        * wtf/dtoa/cached-powers.cc:
     47        * wtf/dtoa/cached-powers.h:
     48        * wtf/dtoa/diy-fp.cc:
     49        * wtf/dtoa/diy-fp.h:
     50        (WTF::double_conversion::DiyFp::DiyFp):
     51        (WTF::double_conversion::DiyFp::Subtract):
     52        (WTF::double_conversion::DiyFp::Minus):
     53        (WTF::double_conversion::DiyFp::Times):
     54        (WTF::double_conversion::DiyFp::Normalize):
     55        (WTF::double_conversion::DiyFp::f const):
     56        (WTF::double_conversion::DiyFp::e const):
     57        (WTF::double_conversion::DiyFp::set_f):
     58        (WTF::double_conversion::DiyFp::set_e):
     59        * wtf/dtoa/double-conversion.cc:
     60        * wtf/dtoa/double-conversion.h:
     61        (WTF::double_conversion::DoubleToStringConverter::DoubleToStringConverter):
     62        (WTF::double_conversion::DoubleToStringConverter::ToShortest const):
     63        (WTF::double_conversion::DoubleToStringConverter::ToShortestSingle const):
     64        (WTF::double_conversion::StringToDoubleConverter::StringToDoubleConverter):
     65        * wtf/dtoa/double.h: Removed.
     66        * wtf/dtoa/fast-dtoa.cc:
     67        * wtf/dtoa/fast-dtoa.h:
     68        * wtf/dtoa/fixed-dtoa.cc:
     69        * wtf/dtoa/fixed-dtoa.h:
     70        * wtf/dtoa/ieee.h: Added.
     71        (WTF::double_conversion::double_to_uint64):
     72        (WTF::double_conversion::uint64_to_double):
     73        (WTF::double_conversion::float_to_uint32):
     74        (WTF::double_conversion::uint32_to_float):
     75        (WTF::double_conversion::Double::Double):
     76        (WTF::double_conversion::Double::AsDiyFp const):
     77        (WTF::double_conversion::Double::AsNormalizedDiyFp const):
     78        (WTF::double_conversion::Double::AsUint64 const):
     79        (WTF::double_conversion::Double::NextDouble const):
     80        (WTF::double_conversion::Double::PreviousDouble const):
     81        (WTF::double_conversion::Double::Exponent const):
     82        (WTF::double_conversion::Double::Significand const):
     83        (WTF::double_conversion::Double::IsDenormal const):
     84        (WTF::double_conversion::Double::IsSpecial const):
     85        (WTF::double_conversion::Double::IsNan const):
     86        (WTF::double_conversion::Double::IsInfinite const):
     87        (WTF::double_conversion::Double::Sign const):
     88        (WTF::double_conversion::Double::UpperBoundary const):
     89        (WTF::double_conversion::Double::NormalizedBoundaries const):
     90        (WTF::double_conversion::Double::LowerBoundaryIsCloser const):
     91        (WTF::double_conversion::Double::value const):
     92        (WTF::double_conversion::Double::SignificandSizeForOrderOfMagnitude):
     93        (WTF::double_conversion::Double::Infinity):
     94        (WTF::double_conversion::Double::NaN):
     95        (WTF::double_conversion::Double::DiyFpToUint64):
     96        (WTF::double_conversion::Single::Single):
     97        (WTF::double_conversion::Single::AsDiyFp const):
     98        (WTF::double_conversion::Single::AsUint32 const):
     99        (WTF::double_conversion::Single::Exponent const):
     100        (WTF::double_conversion::Single::Significand const):
     101        (WTF::double_conversion::Single::IsDenormal const):
     102        (WTF::double_conversion::Single::IsSpecial const):
     103        (WTF::double_conversion::Single::IsNan const):
     104        (WTF::double_conversion::Single::IsInfinite const):
     105        (WTF::double_conversion::Single::Sign const):
     106        (WTF::double_conversion::Single::NormalizedBoundaries const):
     107        (WTF::double_conversion::Single::UpperBoundary const):
     108        (WTF::double_conversion::Single::LowerBoundaryIsCloser const):
     109        (WTF::double_conversion::Single::value const):
     110        (WTF::double_conversion::Single::Infinity):
     111        (WTF::double_conversion::Single::NaN):
     112        * wtf/dtoa/strtod.cc:
     113        * wtf/dtoa/strtod.h:
     114        * wtf/dtoa/utils.h:
     115        (abort_noreturn):
     116        (WTF::double_conversion::Max):
     117        (WTF::double_conversion::Min):
     118        (WTF::double_conversion::StrLength):
     119        (WTF::double_conversion::BufferReference::BufferReference):
     120        (WTF::double_conversion::BufferReference::SubVector):
     121        (WTF::double_conversion::BufferReference::length const):
     122        (WTF::double_conversion::BufferReference::is_empty const):
     123        (WTF::double_conversion::BufferReference::start const):
     124        (WTF::double_conversion::BufferReference::operator[] const):
     125        (WTF::double_conversion::BufferReference::first):
     126        (WTF::double_conversion::BufferReference::last):
     127        (WTF::double_conversion::StringBuilder::StringBuilder):
     128        (WTF::double_conversion::StringBuilder::~StringBuilder):
     129        (WTF::double_conversion::StringBuilder::size const):
     130        (WTF::double_conversion::StringBuilder::position const):
     131        (WTF::double_conversion::StringBuilder::Reset):
     132        (WTF::double_conversion::StringBuilder::AddCharacter):
     133        (WTF::double_conversion::StringBuilder::AddString):
     134        (WTF::double_conversion::StringBuilder::AddSubstring):
     135        (WTF::double_conversion::StringBuilder::AddPadding):
     136        (WTF::double_conversion::StringBuilder::RemoveCharacters):
     137        (WTF::double_conversion::StringBuilder::Finalize):
     138        (WTF::double_conversion::StringBuilder::is_finalized const):
     139        (WTF::double_conversion::BitCast):
     140        (WTF::double_conversion::BufferReference::SubBufferReference): Deleted.
     141        (WTF::double_conversion::StringBuilder::SetPosition): Deleted.
     142
    11432019-02-20  Darin Adler  <darin@apple.com>
    2144
  • trunk/Source/WTF/WTF.xcodeproj/project.pbxproj

    r241841 r242048  
    410410                7AFEC6AE1EB22AC600DADE36 /* UUID.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UUID.h; sourceTree = "<group>"; };
    411411                7AFEC6B01EB22B5900DADE36 /* UUID.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UUID.cpp; sourceTree = "<group>"; };
     412                7C137941222326C700D7A824 /* AUTHORS */ = {isa = PBXFileReference; lastKnownFileType = text; path = AUTHORS; sourceTree = "<group>"; };
     413                7C137942222326D500D7A824 /* ieee.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ieee.h; sourceTree = "<group>"; };
     414                7C137943222326D500D7A824 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = "<group>"; };
    412415                7C3F72391D78811900674E26 /* Brigand.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Brigand.h; sourceTree = "<group>"; };
    413416                7C9692941F66306E00267A9E /* KeyValuePair.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = KeyValuePair.h; sourceTree = "<group>"; };
     
    510513                A8A4728B151A825A004123FF /* double-conversion.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "double-conversion.cc"; sourceTree = "<group>"; };
    511514                A8A4728C151A825A004123FF /* double-conversion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "double-conversion.h"; sourceTree = "<group>"; };
    512                 A8A4728D151A825A004123FF /* double.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = double.h; sourceTree = "<group>"; };
    513515                A8A4728E151A825A004123FF /* fast-dtoa.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "fast-dtoa.cc"; sourceTree = "<group>"; };
    514516                A8A4728F151A825A004123FF /* fast-dtoa.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "fast-dtoa.h"; sourceTree = "<group>"; };
     
    516518                A8A47291151A825A004123FF /* fixed-dtoa.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "fixed-dtoa.h"; sourceTree = "<group>"; };
    517519                A8A47292151A825A004123FF /* LICENSE */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = LICENSE; sourceTree = "<group>"; };
    518                 A8A47293151A825A004123FF /* README */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README; sourceTree = "<group>"; };
    519520                A8A47294151A825A004123FF /* strtod.cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = strtod.cc; sourceTree = "<group>"; };
    520521                A8A47295151A825A004123FF /* strtod.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = strtod.h; sourceTree = "<group>"; };
     
    12131214                        isa = PBXGroup;
    12141215                        children = (
     1216                                7C137941222326C700D7A824 /* AUTHORS */,
    12151217                                A8A47288151A825A004123FF /* COPYING */,
    12161218                                A8A47292151A825A004123FF /* LICENSE */,
    1217                                 A8A47293151A825A004123FF /* README */,
     1219                                7C137943222326D500D7A824 /* README.md */,
    12181220                                A8A47282151A825A004123FF /* bignum-dtoa.cc */,
    12191221                                A8A47283151A825A004123FF /* bignum-dtoa.h */,
     
    12261228                                A8A4728B151A825A004123FF /* double-conversion.cc */,
    12271229                                A8A4728C151A825A004123FF /* double-conversion.h */,
    1228                                 A8A4728D151A825A004123FF /* double.h */,
    12291230                                A8A4728E151A825A004123FF /* fast-dtoa.cc */,
    12301231                                A8A4728F151A825A004123FF /* fast-dtoa.h */,
    12311232                                A8A47290151A825A004123FF /* fixed-dtoa.cc */,
    12321233                                A8A47291151A825A004123FF /* fixed-dtoa.h */,
     1234                                7C137942222326D500D7A824 /* ieee.h */,
    12331235                                A8A47294151A825A004123FF /* strtod.cc */,
    12341236                                A8A47295151A825A004123FF /* strtod.h */,
  • trunk/Source/WTF/wtf/CMakeLists.txt

    r241751 r242048  
    275275    dtoa/diy-fp.h
    276276    dtoa/double-conversion.h
    277     dtoa/double.h
    278277    dtoa/fast-dtoa.h
    279278    dtoa/fixed-dtoa.h
     279    dtoa/ieee.h
    280280    dtoa/strtod.h
    281281    dtoa/utils.h
  • trunk/Source/WTF/wtf/dtoa/bignum-dtoa.cc

    r147976 r242048  
    2828#include "config.h"
    2929
    30 #include <math.h>
    31 
    32 #include "bignum-dtoa.h"
    33 
    34 #include "bignum.h"
    35 #include "double.h"
     30#include <cmath>
     31
     32#include <wtf/dtoa/bignum-dtoa.h>
     33
     34#include <wtf/dtoa/bignum.h>
     35#include <wtf/dtoa/ieee.h>
    3636
    3737namespace WTF {
    38 
    3938namespace double_conversion {
    40    
    41     static int NormalizedExponent(uint64_t significand, int exponent) {
    42         ASSERT(significand != 0);
    43         while ((significand & Double::kHiddenBit) == 0) {
    44             significand = significand << 1;
    45             exponent = exponent - 1;
     39
     40static int NormalizedExponent(uint64_t significand, int exponent) {
     41  ASSERT(significand != 0);
     42  while ((significand & Double::kHiddenBit) == 0) {
     43    significand = significand << 1;
     44    exponent = exponent - 1;
     45  }
     46  return exponent;
     47}
     48
     49
     50// Forward declarations:
     51// Returns an estimation of k such that 10^(k-1) <= v < 10^k.
     52static int EstimatePower(int exponent);
     53// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
     54// and denominator.
     55static void InitialScaledStartValues(uint64_t significand,
     56                                     int exponent,
     57                                     bool lower_boundary_is_closer,
     58                                     int estimated_power,
     59                                     bool need_boundary_deltas,
     60                                     Bignum* numerator,
     61                                     Bignum* denominator,
     62                                     Bignum* delta_minus,
     63                                     Bignum* delta_plus);
     64// Multiplies numerator/denominator so that its values lies in the range 1-10.
     65// Returns decimal_point s.t.
     66//  v = numerator'/denominator' * 10^(decimal_point-1)
     67//     where numerator' and denominator' are the values of numerator and
     68//     denominator after the call to this function.
     69static void FixupMultiply10(int estimated_power, bool is_even,
     70                            int* decimal_point,
     71                            Bignum* numerator, Bignum* denominator,
     72                            Bignum* delta_minus, Bignum* delta_plus);
     73// Generates digits from the left to the right and stops when the generated
     74// digits yield the shortest decimal representation of v.
     75static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
     76                                   Bignum* delta_minus, Bignum* delta_plus,
     77                                   bool is_even,
     78                                   BufferReference<char> buffer, int* length);
     79// Generates 'requested_digits' after the decimal point.
     80static void BignumToFixed(int requested_digits, int* decimal_point,
     81                          Bignum* numerator, Bignum* denominator,
     82                          BufferReference<char>(buffer), int* length);
     83// Generates 'count' digits of numerator/denominator.
     84// Once 'count' digits have been produced rounds the result depending on the
     85// remainder (remainders of exactly .5 round upwards). Might update the
     86// decimal_point when rounding up (for example for 0.9999).
     87static void GenerateCountedDigits(int count, int* decimal_point,
     88                                  Bignum* numerator, Bignum* denominator,
     89                                  BufferReference<char>(buffer), int* length);
     90
     91
     92void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
     93                BufferReference<char> buffer, int* length, int* decimal_point) {
     94  ASSERT(v > 0);
     95  ASSERT(!Double(v).IsSpecial());
     96  uint64_t significand;
     97  int exponent;
     98  bool lower_boundary_is_closer;
     99  if (mode == BIGNUM_DTOA_SHORTEST_SINGLE) {
     100    float f = static_cast<float>(v);
     101    ASSERT(f == v);
     102    significand = Single(f).Significand();
     103    exponent = Single(f).Exponent();
     104    lower_boundary_is_closer = Single(f).LowerBoundaryIsCloser();
     105  } else {
     106    significand = Double(v).Significand();
     107    exponent = Double(v).Exponent();
     108    lower_boundary_is_closer = Double(v).LowerBoundaryIsCloser();
     109  }
     110  bool need_boundary_deltas =
     111      (mode == BIGNUM_DTOA_SHORTEST || mode == BIGNUM_DTOA_SHORTEST_SINGLE);
     112
     113  bool is_even = (significand & 1) == 0;
     114  int normalized_exponent = NormalizedExponent(significand, exponent);
     115  // estimated_power might be too low by 1.
     116  int estimated_power = EstimatePower(normalized_exponent);
     117
     118  // Shortcut for Fixed.
     119  // The requested digits correspond to the digits after the point. If the
     120  // number is much too small, then there is no need in trying to get any
     121  // digits.
     122  if (mode == BIGNUM_DTOA_FIXED && -estimated_power - 1 > requested_digits) {
     123    buffer[0] = '\0';
     124    *length = 0;
     125    // Set decimal-point to -requested_digits. This is what Gay does.
     126    // Note that it should not have any effect anyways since the string is
     127    // empty.
     128    *decimal_point = -requested_digits;
     129    return;
     130  }
     131
     132  Bignum numerator;
     133  Bignum denominator;
     134  Bignum delta_minus;
     135  Bignum delta_plus;
     136  // Make sure the bignum can grow large enough. The smallest double equals
     137  // 4e-324. In this case the denominator needs fewer than 324*4 binary digits.
     138  // The maximum double is 1.7976931348623157e308 which needs fewer than
     139  // 308*4 binary digits.
     140  ASSERT(Bignum::kMaxSignificantBits >= 324*4);
     141  InitialScaledStartValues(significand, exponent, lower_boundary_is_closer,
     142                           estimated_power, need_boundary_deltas,
     143                           &numerator, &denominator,
     144                           &delta_minus, &delta_plus);
     145  // We now have v = (numerator / denominator) * 10^estimated_power.
     146  FixupMultiply10(estimated_power, is_even, decimal_point,
     147                  &numerator, &denominator,
     148                  &delta_minus, &delta_plus);
     149  // We now have v = (numerator / denominator) * 10^(decimal_point-1), and
     150  //  1 <= (numerator + delta_plus) / denominator < 10
     151  switch (mode) {
     152    case BIGNUM_DTOA_SHORTEST:
     153    case BIGNUM_DTOA_SHORTEST_SINGLE:
     154      GenerateShortestDigits(&numerator, &denominator,
     155                             &delta_minus, &delta_plus,
     156                             is_even, buffer, length);
     157      break;
     158    case BIGNUM_DTOA_FIXED:
     159      BignumToFixed(requested_digits, decimal_point,
     160                    &numerator, &denominator,
     161                    buffer, length);
     162      break;
     163    case BIGNUM_DTOA_PRECISION:
     164      GenerateCountedDigits(requested_digits, decimal_point,
     165                            &numerator, &denominator,
     166                            buffer, length);
     167      break;
     168    default:
     169      UNREACHABLE();
     170  }
     171  buffer[*length] = '\0';
     172}
     173
     174
     175// The procedure starts generating digits from the left to the right and stops
     176// when the generated digits yield the shortest decimal representation of v. A
     177// decimal representation of v is a number lying closer to v than to any other
     178// double, so it converts to v when read.
     179//
     180// This is true if d, the decimal representation, is between m- and m+, the
     181// upper and lower boundaries. d must be strictly between them if !is_even.
     182//           m- := (numerator - delta_minus) / denominator
     183//           m+ := (numerator + delta_plus) / denominator
     184//
     185// Precondition: 0 <= (numerator+delta_plus) / denominator < 10.
     186//   If 1 <= (numerator+delta_plus) / denominator < 10 then no leading 0 digit
     187//   will be produced. This should be the standard precondition.
     188static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
     189                                   Bignum* delta_minus, Bignum* delta_plus,
     190                                   bool is_even,
     191                                   BufferReference<char> buffer, int* length) {
     192  // Small optimization: if delta_minus and delta_plus are the same just reuse
     193  // one of the two bignums.
     194  if (Bignum::Equal(*delta_minus, *delta_plus)) {
     195    delta_plus = delta_minus;
     196  }
     197  *length = 0;
     198  for (;;) {
     199    uint16_t digit;
     200    digit = numerator->DivideModuloIntBignum(*denominator);
     201    ASSERT(digit <= 9);  // digit is a uint16_t and therefore always positive.
     202    // digit = numerator / denominator (integer division).
     203    // numerator = numerator % denominator.
     204    buffer[(*length)++] = static_cast<char>(digit + '0');
     205
     206    // Can we stop already?
     207    // If the remainder of the division is less than the distance to the lower
     208    // boundary we can stop. In this case we simply round down (discarding the
     209    // remainder).
     210    // Similarly we test if we can round up (using the upper boundary).
     211    bool in_delta_room_minus;
     212    bool in_delta_room_plus;
     213    if (is_even) {
     214      in_delta_room_minus = Bignum::LessEqual(*numerator, *delta_minus);
     215    } else {
     216      in_delta_room_minus = Bignum::Less(*numerator, *delta_minus);
     217    }
     218    if (is_even) {
     219      in_delta_room_plus =
     220          Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
     221    } else {
     222      in_delta_room_plus =
     223          Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
     224    }
     225    if (!in_delta_room_minus && !in_delta_room_plus) {
     226      // Prepare for next iteration.
     227      numerator->Times10();
     228      delta_minus->Times10();
     229      // We optimized delta_plus to be equal to delta_minus (if they share the
     230      // same value). So don't multiply delta_plus if they point to the same
     231      // object.
     232      if (delta_minus != delta_plus) {
     233        delta_plus->Times10();
     234      }
     235    } else if (in_delta_room_minus && in_delta_room_plus) {
     236      // Let's see if 2*numerator < denominator.
     237      // If yes, then the next digit would be < 5 and we can round down.
     238      int compare = Bignum::PlusCompare(*numerator, *numerator, *denominator);
     239      if (compare < 0) {
     240        // Remaining digits are less than .5. -> Round down (== do nothing).
     241      } else if (compare > 0) {
     242        // Remaining digits are more than .5 of denominator. -> Round up.
     243        // Note that the last digit could not be a '9' as otherwise the whole
     244        // loop would have stopped earlier.
     245        // We still have an assert here in case the preconditions were not
     246        // satisfied.
     247        ASSERT(buffer[(*length) - 1] != '9');
     248        buffer[(*length) - 1]++;
     249      } else {
     250        // Halfway case.
     251        // TODO(floitsch): need a way to solve half-way cases.
     252        //   For now let's round towards even (since this is what Gay seems to
     253        //   do).
     254
     255        if ((buffer[(*length) - 1] - '0') % 2 == 0) {
     256          // Round down => Do nothing.
     257        } else {
     258          ASSERT(buffer[(*length) - 1] != '9');
     259          buffer[(*length) - 1]++;
    46260        }
    47         return exponent;
     261      }
     262      return;
     263    } else if (in_delta_room_minus) {
     264      // Round down (== do nothing).
     265      return;
     266    } else {  // in_delta_room_plus
     267      // Round up.
     268      // Note again that the last digit could not be '9' since this would have
     269      // stopped the loop earlier.
     270      // We still have an ASSERT here, in case the preconditions were not
     271      // satisfied.
     272      ASSERT(buffer[(*length) -1] != '9');
     273      buffer[(*length) - 1]++;
     274      return;
    48275    }
    49    
    50    
    51     // Forward declarations:
    52     // Returns an estimation of k such that 10^(k-1) <= v < 10^k.
    53     static int EstimatePower(int exponent);
    54     // Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
    55     // and denominator.
    56     static void InitialScaledStartValues(double v,
    57                                          int estimated_power,
    58                                          bool need_boundary_deltas,
    59                                          Bignum* numerator,
    60                                          Bignum* denominator,
    61                                          Bignum* delta_minus,
    62                                          Bignum* delta_plus);
    63     // Multiplies numerator/denominator so that its values lies in the range 1-10.
    64     // Returns decimal_point s.t.
    65     //  v = numerator'/denominator' * 10^(decimal_point-1)
    66     //     where numerator' and denominator' are the values of numerator and
    67     //     denominator after the call to this function.
    68     static void FixupMultiply10(int estimated_power, bool is_even,
    69                                 int* decimal_point,
    70                                 Bignum* numerator, Bignum* denominator,
    71                                 Bignum* delta_minus, Bignum* delta_plus);
    72     // Generates digits from the left to the right and stops when the generated
    73     // digits yield the shortest decimal representation of v.
    74     static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
    75                                        Bignum* delta_minus, Bignum* delta_plus,
    76                                        bool is_even,
    77                                        BufferReference<char> buffer, int* length);
    78     // Generates 'requested_digits' after the decimal point.
    79     static void BignumToFixed(int requested_digits, int* decimal_point,
    80                               Bignum* numerator, Bignum* denominator,
    81                               BufferReference<char>(buffer), int* length);
    82     // Generates 'count' digits of numerator/denominator.
    83     // Once 'count' digits have been produced rounds the result depending on the
    84     // remainder (remainders of exactly .5 round upwards). Might update the
    85     // decimal_point when rounding up (for example for 0.9999).
    86     static void GenerateCountedDigits(int count, int* decimal_point,
    87                                       Bignum* numerator, Bignum* denominator,
    88                                       BufferReference<char>(buffer), int* length);
    89    
    90    
    91     void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
    92                     BufferReference<char> buffer, int* length, int* decimal_point) {
    93         ASSERT(v > 0);
    94         ASSERT(!Double(v).IsSpecial());
    95         uint64_t significand = Double(v).Significand();
    96         bool is_even = (significand & 1) == 0;
    97         int exponent = Double(v).Exponent();
    98         int normalized_exponent = NormalizedExponent(significand, exponent);
    99         // estimated_power might be too low by 1.
    100         int estimated_power = EstimatePower(normalized_exponent);
    101        
    102         // Shortcut for Fixed.
    103         // The requested digits correspond to the digits after the point. If the
    104         // number is much too small, then there is no need in trying to get any
    105         // digits.
    106         if (mode == BIGNUM_DTOA_FIXED && -estimated_power - 1 > requested_digits) {
    107             buffer[0] = '\0';
    108             *length = 0;
    109             // Set decimal-point to -requested_digits. This is what Gay does.
    110             // Note that it should not have any effect anyways since the string is
    111             // empty.
    112             *decimal_point = -requested_digits;
    113             return;
    114         }
    115        
    116         Bignum numerator;
    117         Bignum denominator;
    118         Bignum delta_minus;
    119         Bignum delta_plus;
    120         // Make sure the bignum can grow large enough. The smallest double equals
    121         // 4e-324. In this case the denominator needs fewer than 324*4 binary digits.
    122         // The maximum double is 1.7976931348623157e308 which needs fewer than
    123         // 308*4 binary digits.
    124         ASSERT(Bignum::kMaxSignificantBits >= 324*4);
    125         bool need_boundary_deltas = (mode == BIGNUM_DTOA_SHORTEST);
    126         InitialScaledStartValues(v, estimated_power, need_boundary_deltas,
    127                                  &numerator, &denominator,
    128                                  &delta_minus, &delta_plus);
    129         // We now have v = (numerator / denominator) * 10^estimated_power.
    130         FixupMultiply10(estimated_power, is_even, decimal_point,
    131                         &numerator, &denominator,
    132                         &delta_minus, &delta_plus);
    133         // We now have v = (numerator / denominator) * 10^(decimal_point-1), and
    134         //  1 <= (numerator + delta_plus) / denominator < 10
    135         switch (mode) {
    136             case BIGNUM_DTOA_SHORTEST:
    137                 GenerateShortestDigits(&numerator, &denominator,
    138                                        &delta_minus, &delta_plus,
    139                                        is_even, buffer, length);
    140                 break;
    141             case BIGNUM_DTOA_FIXED:
    142                 BignumToFixed(requested_digits, decimal_point,
    143                               &numerator, &denominator,
    144                               buffer, length);
    145                 break;
    146             case BIGNUM_DTOA_PRECISION:
    147                 GenerateCountedDigits(requested_digits, decimal_point,
    148                                       &numerator, &denominator,
    149                                       buffer, length);
    150                 break;
    151             default:
    152                 UNREACHABLE();
    153         }
    154         buffer[*length] = '\0';
     276  }
     277}
     278
     279
     280// Let v = numerator / denominator < 10.
     281// Then we generate 'count' digits of d = x.xxxxx... (without the decimal point)
     282// from left to right. Once 'count' digits have been produced we decide wether
     283// to round up or down. Remainders of exactly .5 round upwards. Numbers such
     284// as 9.999999 propagate a carry all the way, and change the
     285// exponent (decimal_point), when rounding upwards.
     286static void GenerateCountedDigits(int count, int* decimal_point,
     287                                  Bignum* numerator, Bignum* denominator,
     288                                  BufferReference<char> buffer, int* length) {
     289  ASSERT(count >= 0);
     290  for (int i = 0; i < count - 1; ++i) {
     291    uint16_t digit;
     292    digit = numerator->DivideModuloIntBignum(*denominator);
     293    ASSERT(digit <= 9);  // digit is a uint16_t and therefore always positive.
     294    // digit = numerator / denominator (integer division).
     295    // numerator = numerator % denominator.
     296    buffer[i] = static_cast<char>(digit + '0');
     297    // Prepare for next iteration.
     298    numerator->Times10();
     299  }
     300  // Generate the last digit.
     301  uint16_t digit;
     302  digit = numerator->DivideModuloIntBignum(*denominator);
     303  if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
     304    digit++;
     305  }
     306  ASSERT(digit <= 10);
     307  buffer[count - 1] = static_cast<char>(digit + '0');
     308  // Correct bad digits (in case we had a sequence of '9's). Propagate the
     309  // carry until we hat a non-'9' or til we reach the first digit.
     310  for (int i = count - 1; i > 0; --i) {
     311    if (buffer[i] != '0' + 10) break;
     312    buffer[i] = '0';
     313    buffer[i - 1]++;
     314  }
     315  if (buffer[0] == '0' + 10) {
     316    // Propagate a carry past the top place.
     317    buffer[0] = '1';
     318    (*decimal_point)++;
     319  }
     320  *length = count;
     321}
     322
     323
     324// Generates 'requested_digits' after the decimal point. It might omit
     325// trailing '0's. If the input number is too small then no digits at all are
     326// generated (ex.: 2 fixed digits for 0.00001).
     327//
     328// Input verifies:  1 <= (numerator + delta) / denominator < 10.
     329static void BignumToFixed(int requested_digits, int* decimal_point,
     330                          Bignum* numerator, Bignum* denominator,
     331                          BufferReference<char>(buffer), int* length) {
     332  // Note that we have to look at more than just the requested_digits, since
     333  // a number could be rounded up. Example: v=0.5 with requested_digits=0.
     334  // Even though the power of v equals 0 we can't just stop here.
     335  if (-(*decimal_point) > requested_digits) {
     336    // The number is definitively too small.
     337    // Ex: 0.001 with requested_digits == 1.
     338    // Set decimal-point to -requested_digits. This is what Gay does.
     339    // Note that it should not have any effect anyways since the string is
     340    // empty.
     341    *decimal_point = -requested_digits;
     342    *length = 0;
     343    return;
     344  } else if (-(*decimal_point) == requested_digits) {
     345    // We only need to verify if the number rounds down or up.
     346    // Ex: 0.04 and 0.06 with requested_digits == 1.
     347    ASSERT(*decimal_point == -requested_digits);
     348    // Initially the fraction lies in range (1, 10]. Multiply the denominator
     349    // by 10 so that we can compare more easily.
     350    denominator->Times10();
     351    if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
     352      // If the fraction is >= 0.5 then we have to include the rounded
     353      // digit.
     354      buffer[0] = '1';
     355      *length = 1;
     356      (*decimal_point)++;
     357    } else {
     358      // Note that we caught most of similar cases earlier.
     359      *length = 0;
    155360    }
    156    
    157    
    158     // The procedure starts generating digits from the left to the right and stops
    159     // when the generated digits yield the shortest decimal representation of v. A
    160     // decimal representation of v is a number lying closer to v than to any other
    161     // double, so it converts to v when read.
    162     //
    163     // This is true if d, the decimal representation, is between m- and m+, the
    164     // upper and lower boundaries. d must be strictly between them if !is_even.
    165     //           m- := (numerator - delta_minus) / denominator
    166     //           m+ := (numerator + delta_plus) / denominator
    167     //
    168     // Precondition: 0 <= (numerator+delta_plus) / denominator < 10.
    169     //   If 1 <= (numerator+delta_plus) / denominator < 10 then no leading 0 digit
    170     //   will be produced. This should be the standard precondition.
    171     static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
    172                                        Bignum* delta_minus, Bignum* delta_plus,
    173                                        bool is_even,
    174                                        BufferReference<char> buffer, int* length) {
    175         // Small optimization: if delta_minus and delta_plus are the same just reuse
    176         // one of the two bignums.
    177         if (Bignum::Equal(*delta_minus, *delta_plus)) {
    178             delta_plus = delta_minus;
    179         }
    180         *length = 0;
    181         while (true) {
    182             uint16_t digit;
    183             digit = numerator->DivideModuloIntBignum(*denominator);
    184             ASSERT(digit <= 9);  // digit is a uint16_t and therefore always positive.
    185             // digit = numerator / denominator (integer division).
    186             // numerator = numerator % denominator.
    187             buffer[(*length)++] = digit + '0';
    188            
    189             // Can we stop already?
    190             // If the remainder of the division is less than the distance to the lower
    191             // boundary we can stop. In this case we simply round down (discarding the
    192             // remainder).
    193             // Similarly we test if we can round up (using the upper boundary).
    194             bool in_delta_room_minus;
    195             bool in_delta_room_plus;
    196             if (is_even) {
    197                 in_delta_room_minus = Bignum::LessEqual(*numerator, *delta_minus);
    198             } else {
    199                 in_delta_room_minus = Bignum::Less(*numerator, *delta_minus);
    200             }
    201             if (is_even) {
    202                 in_delta_room_plus =
    203                 Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
    204             } else {
    205                 in_delta_room_plus =
    206                 Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
    207             }
    208             if (!in_delta_room_minus && !in_delta_room_plus) {
    209                 // Prepare for next iteration.
    210                 numerator->Times10();
    211                 delta_minus->Times10();
    212                 // We optimized delta_plus to be equal to delta_minus (if they share the
    213                 // same value). So don't multiply delta_plus if they point to the same
    214                 // object.
    215                 if (delta_minus != delta_plus) {
    216                     delta_plus->Times10();
    217                 }
    218             } else if (in_delta_room_minus && in_delta_room_plus) {
    219                 // Let's see if 2*numerator < denominator.
    220                 // If yes, then the next digit would be < 5 and we can round down.
    221                 int compare = Bignum::PlusCompare(*numerator, *numerator, *denominator);
    222                 if (compare < 0) {
    223                     // Remaining digits are less than .5. -> Round down (== do nothing).
    224                 } else if (compare > 0) {
    225                     // Remaining digits are more than .5 of denominator. -> Round up.
    226                     // Note that the last digit could not be a '9' as otherwise the whole
    227                     // loop would have stopped earlier.
    228                     // We still have an assert here in case the preconditions were not
    229                     // satisfied.
    230                     ASSERT(buffer[(*length) - 1] != '9');
    231                     buffer[(*length) - 1]++;
    232                 } else {
    233                     // Halfway case.
    234                     // TODO(floitsch): need a way to solve half-way cases.
    235                     //   For now let's round towards even (since this is what Gay seems to
    236                     //   do).
    237                    
    238                     if ((buffer[(*length) - 1] - '0') % 2 == 0) {
    239                         // Round down => Do nothing.
    240                     } else {
    241                         ASSERT(buffer[(*length) - 1] != '9');
    242                         buffer[(*length) - 1]++;
    243                     }
    244                 }
    245                 return;
    246             } else if (in_delta_room_minus) {
    247                 // Round down (== do nothing).
    248                 return;
    249             } else {  // in_delta_room_plus
    250                 // Round up.
    251                 // Note again that the last digit could not be '9' since this would have
    252                 // stopped the loop earlier.
    253                 // We still have an ASSERT here, in case the preconditions were not
    254                 // satisfied.
    255                 ASSERT(buffer[(*length) -1] != '9');
    256                 buffer[(*length) - 1]++;
    257                 return;
    258             }
    259         }
     361    return;
     362  } else {
     363    // The requested digits correspond to the digits after the point.
     364    // The variable 'needed_digits' includes the digits before the point.
     365    int needed_digits = (*decimal_point) + requested_digits;
     366    GenerateCountedDigits(needed_digits, decimal_point,
     367                          numerator, denominator,
     368                          buffer, length);
     369  }
     370}
     371
     372
     373// Returns an estimation of k such that 10^(k-1) <= v < 10^k where
     374// v = f * 2^exponent and 2^52 <= f < 2^53.
     375// v is hence a normalized double with the given exponent. The output is an
     376// approximation for the exponent of the decimal approimation .digits * 10^k.
     377//
     378// The result might undershoot by 1 in which case 10^k <= v < 10^k+1.
     379// Note: this property holds for v's upper boundary m+ too.
     380//    10^k <= m+ < 10^k+1.
     381//   (see explanation below).
     382//
     383// Examples:
     384//  EstimatePower(0)   => 16
     385//  EstimatePower(-52) => 0
     386//
     387// Note: e >= 0 => EstimatedPower(e) > 0. No similar claim can be made for e<0.
     388static int EstimatePower(int exponent) {
     389  // This function estimates log10 of v where v = f*2^e (with e == exponent).
     390  // Note that 10^floor(log10(v)) <= v, but v <= 10^ceil(log10(v)).
     391  // Note that f is bounded by its container size. Let p = 53 (the double's
     392  // significand size). Then 2^(p-1) <= f < 2^p.
     393  //
     394  // Given that log10(v) == log2(v)/log2(10) and e+(len(f)-1) is quite close
     395  // to log2(v) the function is simplified to (e+(len(f)-1)/log2(10)).
     396  // The computed number undershoots by less than 0.631 (when we compute log3
     397  // and not log10).
     398  //
     399  // Optimization: since we only need an approximated result this computation
     400  // can be performed on 64 bit integers. On x86/x64 architecture the speedup is
     401  // not really measurable, though.
     402  //
     403  // Since we want to avoid overshooting we decrement by 1e10 so that
     404  // floating-point imprecisions don't affect us.
     405  //
     406  // Explanation for v's boundary m+: the computation takes advantage of
     407  // the fact that 2^(p-1) <= f < 2^p. Boundaries still satisfy this requirement
     408  // (even for denormals where the delta can be much more important).
     409
     410  const double k1Log10 = 0.30102999566398114;  // 1/lg(10)
     411
     412  // For doubles len(f) == 53 (don't forget the hidden bit).
     413  const int kSignificandSize = Double::kSignificandSize;
     414  double estimate = ceil((exponent + kSignificandSize - 1) * k1Log10 - 1e-10);
     415  return static_cast<int>(estimate);
     416}
     417
     418
     419// See comments for InitialScaledStartValues.
     420static void InitialScaledStartValuesPositiveExponent(
     421    uint64_t significand, int exponent,
     422    int estimated_power, bool need_boundary_deltas,
     423    Bignum* numerator, Bignum* denominator,
     424    Bignum* delta_minus, Bignum* delta_plus) {
     425  // A positive exponent implies a positive power.
     426  ASSERT(estimated_power >= 0);
     427  // Since the estimated_power is positive we simply multiply the denominator
     428  // by 10^estimated_power.
     429
     430  // numerator = v.
     431  numerator->AssignUInt64(significand);
     432  numerator->ShiftLeft(exponent);
     433  // denominator = 10^estimated_power.
     434  denominator->AssignPowerUInt16(10, estimated_power);
     435
     436  if (need_boundary_deltas) {
     437    // Introduce a common denominator so that the deltas to the boundaries are
     438    // integers.
     439    denominator->ShiftLeft(1);
     440    numerator->ShiftLeft(1);
     441    // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
     442    // denominator (of 2) delta_plus equals 2^e.
     443    delta_plus->AssignUInt16(1);
     444    delta_plus->ShiftLeft(exponent);
     445    // Same for delta_minus. The adjustments if f == 2^p-1 are done later.
     446    delta_minus->AssignUInt16(1);
     447    delta_minus->ShiftLeft(exponent);
     448  }
     449}
     450
     451
     452// See comments for InitialScaledStartValues
     453static void InitialScaledStartValuesNegativeExponentPositivePower(
     454    uint64_t significand, int exponent,
     455    int estimated_power, bool need_boundary_deltas,
     456    Bignum* numerator, Bignum* denominator,
     457    Bignum* delta_minus, Bignum* delta_plus) {
     458  // v = f * 2^e with e < 0, and with estimated_power >= 0.
     459  // This means that e is close to 0 (have a look at how estimated_power is
     460  // computed).
     461
     462  // numerator = significand
     463  //  since v = significand * 2^exponent this is equivalent to
     464  //  numerator = v * / 2^-exponent
     465  numerator->AssignUInt64(significand);
     466  // denominator = 10^estimated_power * 2^-exponent (with exponent < 0)
     467  denominator->AssignPowerUInt16(10, estimated_power);
     468  denominator->ShiftLeft(-exponent);
     469
     470  if (need_boundary_deltas) {
     471    // Introduce a common denominator so that the deltas to the boundaries are
     472    // integers.
     473    denominator->ShiftLeft(1);
     474    numerator->ShiftLeft(1);
     475    // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
     476    // denominator (of 2) delta_plus equals 2^e.
     477    // Given that the denominator already includes v's exponent the distance
     478    // to the boundaries is simply 1.
     479    delta_plus->AssignUInt16(1);
     480    // Same for delta_minus. The adjustments if f == 2^p-1 are done later.
     481    delta_minus->AssignUInt16(1);
     482  }
     483}
     484
     485
     486// See comments for InitialScaledStartValues
     487static void InitialScaledStartValuesNegativeExponentNegativePower(
     488    uint64_t significand, int exponent,
     489    int estimated_power, bool need_boundary_deltas,
     490    Bignum* numerator, Bignum* denominator,
     491    Bignum* delta_minus, Bignum* delta_plus) {
     492  // Instead of multiplying the denominator with 10^estimated_power we
     493  // multiply all values (numerator and deltas) by 10^-estimated_power.
     494
     495  // Use numerator as temporary container for power_ten.
     496  Bignum* power_ten = numerator;
     497  power_ten->AssignPowerUInt16(10, -estimated_power);
     498
     499  if (need_boundary_deltas) {
     500    // Since power_ten == numerator we must make a copy of 10^estimated_power
     501    // before we complete the computation of the numerator.
     502    // delta_plus = delta_minus = 10^estimated_power
     503    delta_plus->AssignBignum(*power_ten);
     504    delta_minus->AssignBignum(*power_ten);
     505  }
     506
     507  // numerator = significand * 2 * 10^-estimated_power
     508  //  since v = significand * 2^exponent this is equivalent to
     509  // numerator = v * 10^-estimated_power * 2 * 2^-exponent.
     510  // Remember: numerator has been abused as power_ten. So no need to assign it
     511  //  to itself.
     512  ASSERT(numerator == power_ten);
     513  numerator->MultiplyByUInt64(significand);
     514
     515  // denominator = 2 * 2^-exponent with exponent < 0.
     516  denominator->AssignUInt16(1);
     517  denominator->ShiftLeft(-exponent);
     518
     519  if (need_boundary_deltas) {
     520    // Introduce a common denominator so that the deltas to the boundaries are
     521    // integers.
     522    numerator->ShiftLeft(1);
     523    denominator->ShiftLeft(1);
     524    // With this shift the boundaries have their correct value, since
     525    // delta_plus = 10^-estimated_power, and
     526    // delta_minus = 10^-estimated_power.
     527    // These assignments have been done earlier.
     528    // The adjustments if f == 2^p-1 (lower boundary is closer) are done later.
     529  }
     530}
     531
     532
     533// Let v = significand * 2^exponent.
     534// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
     535// and denominator. The functions GenerateShortestDigits and
     536// GenerateCountedDigits will then convert this ratio to its decimal
     537// representation d, with the required accuracy.
     538// Then d * 10^estimated_power is the representation of v.
     539// (Note: the fraction and the estimated_power might get adjusted before
     540// generating the decimal representation.)
     541//
     542// The initial start values consist of:
     543//  - a scaled numerator: s.t. numerator/denominator == v / 10^estimated_power.
     544//  - a scaled (common) denominator.
     545//  optionally (used by GenerateShortestDigits to decide if it has the shortest
     546//  decimal converting back to v):
     547//  - v - m-: the distance to the lower boundary.
     548//  - m+ - v: the distance to the upper boundary.
     549//
     550// v, m+, m-, and therefore v - m- and m+ - v all share the same denominator.
     551//
     552// Let ep == estimated_power, then the returned values will satisfy:
     553//  v / 10^ep = numerator / denominator.
     554//  v's boundarys m- and m+:
     555//    m- / 10^ep == v / 10^ep - delta_minus / denominator
     556//    m+ / 10^ep == v / 10^ep + delta_plus / denominator
     557//  Or in other words:
     558//    m- == v - delta_minus * 10^ep / denominator;
     559//    m+ == v + delta_plus * 10^ep / denominator;
     560//
     561// Since 10^(k-1) <= v < 10^k    (with k == estimated_power)
     562//  or       10^k <= v < 10^(k+1)
     563//  we then have 0.1 <= numerator/denominator < 1
     564//           or    1 <= numerator/denominator < 10
     565//
     566// It is then easy to kickstart the digit-generation routine.
     567//
     568// The boundary-deltas are only filled if the mode equals BIGNUM_DTOA_SHORTEST
     569// or BIGNUM_DTOA_SHORTEST_SINGLE.
     570
     571static void InitialScaledStartValues(uint64_t significand,
     572                                     int exponent,
     573                                     bool lower_boundary_is_closer,
     574                                     int estimated_power,
     575                                     bool need_boundary_deltas,
     576                                     Bignum* numerator,
     577                                     Bignum* denominator,
     578                                     Bignum* delta_minus,
     579                                     Bignum* delta_plus) {
     580  if (exponent >= 0) {
     581    InitialScaledStartValuesPositiveExponent(
     582        significand, exponent, estimated_power, need_boundary_deltas,
     583        numerator, denominator, delta_minus, delta_plus);
     584  } else if (estimated_power >= 0) {
     585    InitialScaledStartValuesNegativeExponentPositivePower(
     586        significand, exponent, estimated_power, need_boundary_deltas,
     587        numerator, denominator, delta_minus, delta_plus);
     588  } else {
     589    InitialScaledStartValuesNegativeExponentNegativePower(
     590        significand, exponent, estimated_power, need_boundary_deltas,
     591        numerator, denominator, delta_minus, delta_plus);
     592  }
     593
     594  if (need_boundary_deltas && lower_boundary_is_closer) {
     595    // The lower boundary is closer at half the distance of "normal" numbers.
     596    // Increase the common denominator and adapt all but the delta_minus.
     597    denominator->ShiftLeft(1);  // *2
     598    numerator->ShiftLeft(1);    // *2
     599    delta_plus->ShiftLeft(1);   // *2
     600  }
     601}
     602
     603
     604// This routine multiplies numerator/denominator so that its values lies in the
     605// range 1-10. That is after a call to this function we have:
     606//    1 <= (numerator + delta_plus) /denominator < 10.
     607// Let numerator the input before modification and numerator' the argument
     608// after modification, then the output-parameter decimal_point is such that
     609//  numerator / denominator * 10^estimated_power ==
     610//    numerator' / denominator' * 10^(decimal_point - 1)
     611// In some cases estimated_power was too low, and this is already the case. We
     612// then simply adjust the power so that 10^(k-1) <= v < 10^k (with k ==
     613// estimated_power) but do not touch the numerator or denominator.
     614// Otherwise the routine multiplies the numerator and the deltas by 10.
     615static void FixupMultiply10(int estimated_power, bool is_even,
     616                            int* decimal_point,
     617                            Bignum* numerator, Bignum* denominator,
     618                            Bignum* delta_minus, Bignum* delta_plus) {
     619  bool in_range;
     620  if (is_even) {
     621    // For IEEE doubles half-way cases (in decimal system numbers ending with 5)
     622    // are rounded to the closest floating-point number with even significand.
     623    in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
     624  } else {
     625    in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
     626  }
     627  if (in_range) {
     628    // Since numerator + delta_plus >= denominator we already have
     629    // 1 <= numerator/denominator < 10. Simply update the estimated_power.
     630    *decimal_point = estimated_power + 1;
     631  } else {
     632    *decimal_point = estimated_power;
     633    numerator->Times10();
     634    if (Bignum::Equal(*delta_minus, *delta_plus)) {
     635      delta_minus->Times10();
     636      delta_plus->AssignBignum(*delta_minus);
     637    } else {
     638      delta_minus->Times10();
     639      delta_plus->Times10();
    260640    }
    261    
    262    
    263     // Let v = numerator / denominator < 10.
    264     // Then we generate 'count' digits of d = x.xxxxx... (without the decimal point)
    265     // from left to right. Once 'count' digits have been produced we decide wether
    266     // to round up or down. Remainders of exactly .5 round upwards. Numbers such
    267     // as 9.999999 propagate a carry all the way, and change the
    268     // exponent (decimal_point), when rounding upwards.
    269     static void GenerateCountedDigits(int count, int* decimal_point,
    270                                       Bignum* numerator, Bignum* denominator,
    271                                       BufferReference<char>(buffer), int* length) {
    272         ASSERT(count >= 0);
    273         for (int i = 0; i < count - 1; ++i) {
    274             uint16_t digit;
    275             digit = numerator->DivideModuloIntBignum(*denominator);
    276             ASSERT(digit <= 9);  // digit is a uint16_t and therefore always positive.
    277             // digit = numerator / denominator (integer division).
    278             // numerator = numerator % denominator.
    279             buffer[i] = digit + '0';
    280             // Prepare for next iteration.
    281             numerator->Times10();
    282         }
    283         // Generate the last digit.
    284         uint16_t digit;
    285         digit = numerator->DivideModuloIntBignum(*denominator);
    286         if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
    287             digit++;
    288         }
    289         buffer[count - 1] = digit + '0';
    290         // Correct bad digits (in case we had a sequence of '9's). Propagate the
    291         // carry until we hat a non-'9' or til we reach the first digit.
    292         for (int i = count - 1; i > 0; --i) {
    293             if (buffer[i] != '0' + 10) break;
    294             buffer[i] = '0';
    295             buffer[i - 1]++;
    296         }
    297         if (buffer[0] == '0' + 10) {
    298             // Propagate a carry past the top place.
    299             buffer[0] = '1';
    300             (*decimal_point)++;
    301         }
    302         *length = count;
    303     }
    304    
    305    
    306     // Generates 'requested_digits' after the decimal point. It might omit
    307     // trailing '0's. If the input number is too small then no digits at all are
    308     // generated (ex.: 2 fixed digits for 0.00001).
    309     //
    310     // Input verifies:  1 <= (numerator + delta) / denominator < 10.
    311     static void BignumToFixed(int requested_digits, int* decimal_point,
    312                               Bignum* numerator, Bignum* denominator,
    313                               BufferReference<char>(buffer), int* length) {
    314         // Note that we have to look at more than just the requested_digits, since
    315         // a number could be rounded up. Example: v=0.5 with requested_digits=0.
    316         // Even though the power of v equals 0 we can't just stop here.
    317         if (-(*decimal_point) > requested_digits) {
    318             // The number is definitively too small.
    319             // Ex: 0.001 with requested_digits == 1.
    320             // Set decimal-point to -requested_digits. This is what Gay does.
    321             // Note that it should not have any effect anyways since the string is
    322             // empty.
    323             *decimal_point = -requested_digits;
    324             *length = 0;
    325             return;
    326         } else if (-(*decimal_point) == requested_digits) {
    327             // We only need to verify if the number rounds down or up.
    328             // Ex: 0.04 and 0.06 with requested_digits == 1.
    329             ASSERT(*decimal_point == -requested_digits);
    330             // Initially the fraction lies in range (1, 10]. Multiply the denominator
    331             // by 10 so that we can compare more easily.
    332             denominator->Times10();
    333             if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
    334                 // If the fraction is >= 0.5 then we have to include the rounded
    335                 // digit.
    336                 buffer[0] = '1';
    337                 *length = 1;
    338                 (*decimal_point)++;
    339             } else {
    340                 // Note that we caught most of similar cases earlier.
    341                 *length = 0;
    342             }
    343             return;
    344         } else {
    345             // The requested digits correspond to the digits after the point.
    346             // The variable 'needed_digits' includes the digits before the point.
    347             int needed_digits = (*decimal_point) + requested_digits;
    348             GenerateCountedDigits(needed_digits, decimal_point,
    349                                   numerator, denominator,
    350                                   buffer, length);
    351         }
    352     }
    353    
    354    
    355     // Returns an estimation of k such that 10^(k-1) <= v < 10^k where
    356     // v = f * 2^exponent and 2^52 <= f < 2^53.
    357     // v is hence a normalized double with the given exponent. The output is an
    358     // approximation for the exponent of the decimal approimation .digits * 10^k.
    359     //
    360     // The result might undershoot by 1 in which case 10^k <= v < 10^k+1.
    361     // Note: this property holds for v's upper boundary m+ too.
    362     //    10^k <= m+ < 10^k+1.
    363     //   (see explanation below).
    364     //
    365     // Examples:
    366     //  EstimatePower(0)   => 16
    367     //  EstimatePower(-52) => 0
    368     //
    369     // Note: e >= 0 => EstimatedPower(e) > 0. No similar claim can be made for e<0.
    370     static int EstimatePower(int exponent) {
    371         // This function estimates log10 of v where v = f*2^e (with e == exponent).
    372         // Note that 10^floor(log10(v)) <= v, but v <= 10^ceil(log10(v)).
    373         // Note that f is bounded by its container size. Let p = 53 (the double's
    374         // significand size). Then 2^(p-1) <= f < 2^p.
    375         //
    376         // Given that log10(v) == log2(v)/log2(10) and e+(len(f)-1) is quite close
    377         // to log2(v) the function is simplified to (e+(len(f)-1)/log2(10)).
    378         // The computed number undershoots by less than 0.631 (when we compute log3
    379         // and not log10).
    380         //
    381         // Optimization: since we only need an approximated result this computation
    382         // can be performed on 64 bit integers. On x86/x64 architecture the speedup is
    383         // not really measurable, though.
    384         //
    385         // Since we want to avoid overshooting we decrement by 1e10 so that
    386         // floating-point imprecisions don't affect us.
    387         //
    388         // Explanation for v's boundary m+: the computation takes advantage of
    389         // the fact that 2^(p-1) <= f < 2^p. Boundaries still satisfy this requirement
    390         // (even for denormals where the delta can be much more important).
    391        
    392         const double k1Log10 = 0.30102999566398114;  // 1/lg(10)
    393        
    394         // For doubles len(f) == 53 (don't forget the hidden bit).
    395         const int kSignificandSize = 53;
    396         double estimate = ceil((exponent + kSignificandSize - 1) * k1Log10 - 1e-10);
    397         return static_cast<int>(estimate);
    398     }
    399    
    400    
    401     // See comments for InitialScaledStartValues.
    402     static void InitialScaledStartValuesPositiveExponent(
    403                                                          double v, int estimated_power, bool need_boundary_deltas,
    404                                                          Bignum* numerator, Bignum* denominator,
    405                                                          Bignum* delta_minus, Bignum* delta_plus) {
    406         // A positive exponent implies a positive power.
    407         ASSERT(estimated_power >= 0);
    408         // Since the estimated_power is positive we simply multiply the denominator
    409         // by 10^estimated_power.
    410        
    411         // numerator = v.
    412         numerator->AssignUInt64(Double(v).Significand());
    413         numerator->ShiftLeft(Double(v).Exponent());
    414         // denominator = 10^estimated_power.
    415         denominator->AssignPowerUInt16(10, estimated_power);
    416        
    417         if (need_boundary_deltas) {
    418             // Introduce a common denominator so that the deltas to the boundaries are
    419             // integers.
    420             denominator->ShiftLeft(1);
    421             numerator->ShiftLeft(1);
    422             // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
    423             // denominator (of 2) delta_plus equals 2^e.
    424             delta_plus->AssignUInt16(1);
    425             delta_plus->ShiftLeft(Double(v).Exponent());
    426             // Same for delta_minus (with adjustments below if f == 2^p-1).
    427             delta_minus->AssignUInt16(1);
    428             delta_minus->ShiftLeft(Double(v).Exponent());
    429            
    430             // If the significand (without the hidden bit) is 0, then the lower
    431             // boundary is closer than just half a ulp (unit in the last place).
    432             // There is only one exception: if the next lower number is a denormal then
    433             // the distance is 1 ulp. This cannot be the case for exponent >= 0 (but we
    434             // have to test it in the other function where exponent < 0).
    435             uint64_t v_bits = Double(v).AsUint64();
    436             if ((v_bits & Double::kSignificandMask) == 0) {
    437                 // The lower boundary is closer at half the distance of "normal" numbers.
    438                 // Increase the common denominator and adapt all but the delta_minus.
    439                 denominator->ShiftLeft(1);  // *2
    440                 numerator->ShiftLeft(1);    // *2
    441                 delta_plus->ShiftLeft(1);   // *2
    442             }
    443         }
    444     }
    445    
    446    
    447     // See comments for InitialScaledStartValues
    448     static void InitialScaledStartValuesNegativeExponentPositivePower(
    449                                                                       double v, int estimated_power, bool need_boundary_deltas,
    450                                                                       Bignum* numerator, Bignum* denominator,
    451                                                                       Bignum* delta_minus, Bignum* delta_plus) {
    452         uint64_t significand = Double(v).Significand();
    453         int exponent = Double(v).Exponent();
    454         // v = f * 2^e with e < 0, and with estimated_power >= 0.
    455         // This means that e is close to 0 (have a look at how estimated_power is
    456         // computed).
    457        
    458         // numerator = significand
    459         //  since v = significand * 2^exponent this is equivalent to
    460         //  numerator = v * / 2^-exponent
    461         numerator->AssignUInt64(significand);
    462         // denominator = 10^estimated_power * 2^-exponent (with exponent < 0)
    463         denominator->AssignPowerUInt16(10, estimated_power);
    464         denominator->ShiftLeft(-exponent);
    465        
    466         if (need_boundary_deltas) {
    467             // Introduce a common denominator so that the deltas to the boundaries are
    468             // integers.
    469             denominator->ShiftLeft(1);
    470             numerator->ShiftLeft(1);
    471             // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
    472             // denominator (of 2) delta_plus equals 2^e.
    473             // Given that the denominator already includes v's exponent the distance
    474             // to the boundaries is simply 1.
    475             delta_plus->AssignUInt16(1);
    476             // Same for delta_minus (with adjustments below if f == 2^p-1).
    477             delta_minus->AssignUInt16(1);
    478            
    479             // If the significand (without the hidden bit) is 0, then the lower
    480             // boundary is closer than just one ulp (unit in the last place).
    481             // There is only one exception: if the next lower number is a denormal
    482             // then the distance is 1 ulp. Since the exponent is close to zero
    483             // (otherwise estimated_power would have been negative) this cannot happen
    484             // here either.
    485             uint64_t v_bits = Double(v).AsUint64();
    486             if ((v_bits & Double::kSignificandMask) == 0) {
    487                 // The lower boundary is closer at half the distance of "normal" numbers.
    488                 // Increase the denominator and adapt all but the delta_minus.
    489                 denominator->ShiftLeft(1);  // *2
    490                 numerator->ShiftLeft(1);    // *2
    491                 delta_plus->ShiftLeft(1);   // *2
    492             }
    493         }
    494     }
    495    
    496    
    497     // See comments for InitialScaledStartValues
    498     static void InitialScaledStartValuesNegativeExponentNegativePower(
    499                                                                       double v, int estimated_power, bool need_boundary_deltas,
    500                                                                       Bignum* numerator, Bignum* denominator,
    501                                                                       Bignum* delta_minus, Bignum* delta_plus) {
    502         const uint64_t kMinimalNormalizedExponent =
    503         UINT64_2PART_C(0x00100000, 00000000);
    504         uint64_t significand = Double(v).Significand();
    505         int exponent = Double(v).Exponent();
    506         // Instead of multiplying the denominator with 10^estimated_power we
    507         // multiply all values (numerator and deltas) by 10^-estimated_power.
    508        
    509         // Use numerator as temporary container for power_ten.
    510         Bignum* power_ten = numerator;
    511         power_ten->AssignPowerUInt16(10, -estimated_power);
    512        
    513         if (need_boundary_deltas) {
    514             // Since power_ten == numerator we must make a copy of 10^estimated_power
    515             // before we complete the computation of the numerator.
    516             // delta_plus = delta_minus = 10^estimated_power
    517             delta_plus->AssignBignum(*power_ten);
    518             delta_minus->AssignBignum(*power_ten);
    519         }
    520        
    521         // numerator = significand * 2 * 10^-estimated_power
    522         //  since v = significand * 2^exponent this is equivalent to
    523         // numerator = v * 10^-estimated_power * 2 * 2^-exponent.
    524         // Remember: numerator has been abused as power_ten. So no need to assign it
    525         //  to itself.
    526         ASSERT(numerator == power_ten);
    527         numerator->MultiplyByUInt64(significand);
    528        
    529         // denominator = 2 * 2^-exponent with exponent < 0.
    530         denominator->AssignUInt16(1);
    531         denominator->ShiftLeft(-exponent);
    532        
    533         if (need_boundary_deltas) {
    534             // Introduce a common denominator so that the deltas to the boundaries are
    535             // integers.
    536             numerator->ShiftLeft(1);
    537             denominator->ShiftLeft(1);
    538             // With this shift the boundaries have their correct value, since
    539             // delta_plus = 10^-estimated_power, and
    540             // delta_minus = 10^-estimated_power.
    541             // These assignments have been done earlier.
    542            
    543             // The special case where the lower boundary is twice as close.
    544             // This time we have to look out for the exception too.
    545             uint64_t v_bits = Double(v).AsUint64();
    546             if ((v_bits & Double::kSignificandMask) == 0 &&
    547                 // The only exception where a significand == 0 has its boundaries at
    548                 // "normal" distances:
    549                 (v_bits & Double::kExponentMask) != kMinimalNormalizedExponent) {
    550                 numerator->ShiftLeft(1);    // *2
    551                 denominator->ShiftLeft(1);  // *2
    552                 delta_plus->ShiftLeft(1);   // *2
    553             }
    554         }
    555     }
    556    
    557    
    558     // Let v = significand * 2^exponent.
    559     // Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
    560     // and denominator. The functions GenerateShortestDigits and
    561     // GenerateCountedDigits will then convert this ratio to its decimal
    562     // representation d, with the required accuracy.
    563     // Then d * 10^estimated_power is the representation of v.
    564     // (Note: the fraction and the estimated_power might get adjusted before
    565     // generating the decimal representation.)
    566     //
    567     // The initial start values consist of:
    568     //  - a scaled numerator: s.t. numerator/denominator == v / 10^estimated_power.
    569     //  - a scaled (common) denominator.
    570     //  optionally (used by GenerateShortestDigits to decide if it has the shortest
    571     //  decimal converting back to v):
    572     //  - v - m-: the distance to the lower boundary.
    573     //  - m+ - v: the distance to the upper boundary.
    574     //
    575     // v, m+, m-, and therefore v - m- and m+ - v all share the same denominator.
    576     //
    577     // Let ep == estimated_power, then the returned values will satisfy:
    578     //  v / 10^ep = numerator / denominator.
    579     //  v's boundarys m- and m+:
    580     //    m- / 10^ep == v / 10^ep - delta_minus / denominator
    581     //    m+ / 10^ep == v / 10^ep + delta_plus / denominator
    582     //  Or in other words:
    583     //    m- == v - delta_minus * 10^ep / denominator;
    584     //    m+ == v + delta_plus * 10^ep / denominator;
    585     //
    586     // Since 10^(k-1) <= v < 10^k    (with k == estimated_power)
    587     //  or       10^k <= v < 10^(k+1)
    588     //  we then have 0.1 <= numerator/denominator < 1
    589     //           or    1 <= numerator/denominator < 10
    590     //
    591     // It is then easy to kickstart the digit-generation routine.
    592     //
    593     // The boundary-deltas are only filled if need_boundary_deltas is set.
    594     static void InitialScaledStartValues(double v,
    595                                          int estimated_power,
    596                                          bool need_boundary_deltas,
    597                                          Bignum* numerator,
    598                                          Bignum* denominator,
    599                                          Bignum* delta_minus,
    600                                          Bignum* delta_plus) {
    601         if (Double(v).Exponent() >= 0) {
    602             InitialScaledStartValuesPositiveExponent(
    603                                                      v, estimated_power, need_boundary_deltas,
    604                                                      numerator, denominator, delta_minus, delta_plus);
    605         } else if (estimated_power >= 0) {
    606             InitialScaledStartValuesNegativeExponentPositivePower(
    607                                                                   v, estimated_power, need_boundary_deltas,
    608                                                                   numerator, denominator, delta_minus, delta_plus);
    609         } else {
    610             InitialScaledStartValuesNegativeExponentNegativePower(
    611                                                                   v, estimated_power, need_boundary_deltas,
    612                                                                   numerator, denominator, delta_minus, delta_plus);
    613         }
    614     }
    615    
    616    
    617     // This routine multiplies numerator/denominator so that its values lies in the
    618     // range 1-10. That is after a call to this function we have:
    619     //    1 <= (numerator + delta_plus) /denominator < 10.
    620     // Let numerator the input before modification and numerator' the argument
    621     // after modification, then the output-parameter decimal_point is such that
    622     //  numerator / denominator * 10^estimated_power ==
    623     //    numerator' / denominator' * 10^(decimal_point - 1)
    624     // In some cases estimated_power was too low, and this is already the case. We
    625     // then simply adjust the power so that 10^(k-1) <= v < 10^k (with k ==
    626     // estimated_power) but do not touch the numerator or denominator.
    627     // Otherwise the routine multiplies the numerator and the deltas by 10.
    628     static void FixupMultiply10(int estimated_power, bool is_even,
    629                                 int* decimal_point,
    630                                 Bignum* numerator, Bignum* denominator,
    631                                 Bignum* delta_minus, Bignum* delta_plus) {
    632         bool in_range;
    633         if (is_even) {
    634             // For IEEE doubles half-way cases (in decimal system numbers ending with 5)
    635             // are rounded to the closest floating-point number with even significand.
    636             in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
    637         } else {
    638             in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
    639         }
    640         if (in_range) {
    641             // Since numerator + delta_plus >= denominator we already have
    642             // 1 <= numerator/denominator < 10. Simply update the estimated_power.
    643             *decimal_point = estimated_power + 1;
    644         } else {
    645             *decimal_point = estimated_power;
    646             numerator->Times10();
    647             if (Bignum::Equal(*delta_minus, *delta_plus)) {
    648                 delta_minus->Times10();
    649                 delta_plus->AssignBignum(*delta_minus);
    650             } else {
    651                 delta_minus->Times10();
    652                 delta_plus->Times10();
    653             }
    654         }
    655     }
    656    
     641  }
     642}
     643
    657644}  // namespace double_conversion
    658 
    659 } // namespace WTF
     645}  // namespace WTF
  • trunk/Source/WTF/wtf/dtoa/bignum-dtoa.h

    r147976 r242048  
    2929#define DOUBLE_CONVERSION_BIGNUM_DTOA_H_
    3030
    31 #include "utils.h"
     31#include <wtf/dtoa/utils.h>
    3232
    3333namespace WTF {
     34namespace double_conversion {
    3435
    35 namespace double_conversion {
    36    
    37     enum BignumDtoaMode {
    38         // Return the shortest correct representation.
    39         // For example the output of 0.299999999999999988897 is (the less accurate but
    40         // correct) 0.3.
    41         BIGNUM_DTOA_SHORTEST,
    42         // Return a fixed number of digits after the decimal point.
    43         // For instance fixed(0.1, 4) becomes 0.1000
    44         // If the input number is big, the output will be big.
    45         BIGNUM_DTOA_FIXED,
    46         // Return a fixed number of digits, no matter what the exponent is.
    47         BIGNUM_DTOA_PRECISION
    48     };
    49    
    50     // Converts the given double 'v' to ascii.
    51     // The result should be interpreted as buffer * 10^(point-length).
    52     // The buffer will be null-terminated.
    53     //
    54     // The input v must be > 0 and different from NaN, and Infinity.
    55     //
    56     // The output depends on the given mode:
    57     //  - SHORTEST: produce the least amount of digits for which the internal
    58     //   identity requirement is still satisfied. If the digits are printed
    59     //   (together with the correct exponent) then reading this number will give
    60     //   'v' again. The buffer will choose the representation that is closest to
    61     //   'v'. If there are two at the same distance, than the number is round up.
    62     //   In this mode the 'requested_digits' parameter is ignored.
    63     //  - FIXED: produces digits necessary to print a given number with
    64     //   'requested_digits' digits after the decimal point. The produced digits
    65     //   might be too short in which case the caller has to fill the gaps with '0's.
    66     //   Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
    67     //   Halfway cases are rounded up. The call toFixed(0.15, 2) thus returns
    68     //     buffer="2", point=0.
    69     //   Note: the length of the returned buffer has no meaning wrt the significance
    70     //   of its digits. That is, just because it contains '0's does not mean that
    71     //   any other digit would not satisfy the internal identity requirement.
    72     //  - PRECISION: produces 'requested_digits' where the first digit is not '0'.
    73     //   Even though the length of produced digits usually equals
    74     //   'requested_digits', the function is allowed to return fewer digits, in
    75     //   which case the caller has to fill the missing digits with '0's.
    76     //   Halfway cases are again rounded up.
    77     // 'BignumDtoa' expects the given buffer to be big enough to hold all digits
    78     // and a terminating null-character.
    79     void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
    80                     BufferReference<char> buffer, int* length, int* point);
    81    
     36enum BignumDtoaMode {
     37  // Return the shortest correct representation.
     38  // For example the output of 0.299999999999999988897 is (the less accurate but
     39  // correct) 0.3.
     40  BIGNUM_DTOA_SHORTEST,
     41  // Same as BIGNUM_DTOA_SHORTEST but for single-precision floats.
     42  BIGNUM_DTOA_SHORTEST_SINGLE,
     43  // Return a fixed number of digits after the decimal point.
     44  // For instance fixed(0.1, 4) becomes 0.1000
     45  // If the input number is big, the output will be big.
     46  BIGNUM_DTOA_FIXED,
     47  // Return a fixed number of digits, no matter what the exponent is.
     48  BIGNUM_DTOA_PRECISION
     49};
     50
     51// Converts the given double 'v' to ascii.
     52// The result should be interpreted as buffer * 10^(point-length).
     53// The buffer will be null-terminated.
     54//
     55// The input v must be > 0 and different from NaN, and Infinity.
     56//
     57// The output depends on the given mode:
     58//  - SHORTEST: produce the least amount of digits for which the internal
     59//   identity requirement is still satisfied. If the digits are printed
     60//   (together with the correct exponent) then reading this number will give
     61//   'v' again. The buffer will choose the representation that is closest to
     62//   'v'. If there are two at the same distance, than the number is round up.
     63//   In this mode the 'requested_digits' parameter is ignored.
     64//  - FIXED: produces digits necessary to print a given number with
     65//   'requested_digits' digits after the decimal point. The produced digits
     66//   might be too short in which case the caller has to fill the gaps with '0's.
     67//   Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
     68//   Halfway cases are rounded up. The call toFixed(0.15, 2) thus returns
     69//     buffer="2", point=0.
     70//   Note: the length of the returned buffer has no meaning wrt the significance
     71//   of its digits. That is, just because it contains '0's does not mean that
     72//   any other digit would not satisfy the internal identity requirement.
     73//  - PRECISION: produces 'requested_digits' where the first digit is not '0'.
     74//   Even though the length of produced digits usually equals
     75//   'requested_digits', the function is allowed to return fewer digits, in
     76//   which case the caller has to fill the missing digits with '0's.
     77//   Halfway cases are again rounded up.
     78// 'BignumDtoa' expects the given buffer to be big enough to hold all digits
     79// and a terminating null-character.
     80void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
     81                BufferReference<char> buffer, int* length, int* point);
     82
    8283}  // namespace double_conversion
    83 
    84 } // namespace WTF
     84}  // namespace WTF
    8585
    8686#endif  // DOUBLE_CONVERSION_BIGNUM_DTOA_H_
  • trunk/Source/WTF/wtf/dtoa/bignum.cc

    r209399 r242048  
    2828#include "config.h"
    2929
    30 #include "bignum.h"
    31 #include "utils.h"
     30#include <wtf/dtoa/bignum.h>
     31
     32#include <wtf/dtoa/utils.h>
    3233#include <wtf/ASCIICType.h>
    3334
    3435namespace WTF {
    35 
    3636namespace double_conversion {
    37    
    38     Bignum::Bignum()
    39     : bigits_(bigits_buffer_, kBigitCapacity), used_digits_(0), exponent_(0) {
    40         for (int i = 0; i < kBigitCapacity; ++i) {
    41             bigits_[i] = 0;
    42         }
    43     }
    44    
    45    
    46     template<typename S>
    47     static int BitSize(S value) {
    48         return 8 * sizeof(value);
    49     }
    50    
    51     // Guaranteed to lie in one Bigit.
    52     void Bignum::AssignUInt16(uint16_t value) {
    53         ASSERT(kBigitSize >= BitSize(value));
    54         Zero();
    55         if (value == 0) return;
    56        
    57         EnsureCapacity(1);
    58         bigits_[0] = value;
    59         used_digits_ = 1;
    60     }
    61    
    62    
    63     void Bignum::AssignUInt64(uint64_t value) {
    64         const int kUInt64Size = 64;
    65        
    66         Zero();
    67         if (value == 0) return;
    68        
    69         int needed_bigits = kUInt64Size / kBigitSize + 1;
    70         EnsureCapacity(needed_bigits);
    71         for (int i = 0; i < needed_bigits; ++i) {
    72             bigits_[i] = static_cast<Chunk>(value & kBigitMask);
    73             value = value >> kBigitSize;
    74         }
    75         used_digits_ = needed_bigits;
    76         Clamp();
    77     }
    78    
    79    
    80     void Bignum::AssignBignum(const Bignum& other) {
    81         exponent_ = other.exponent_;
    82         for (int i = 0; i < other.used_digits_; ++i) {
    83             bigits_[i] = other.bigits_[i];
    84         }
    85         // Clear the excess digits (if there were any).
    86         for (int i = other.used_digits_; i < used_digits_; ++i) {
    87             bigits_[i] = 0;
    88         }
    89         used_digits_ = other.used_digits_;
    90     }
    91    
    92    
    93     static uint64_t ReadUInt64(BufferReference<const char> buffer,
    94                                int from,
    95                                int digits_to_read) {
    96         uint64_t result = 0;
    97         for (int i = 0; i < digits_to_read; ++i) {
    98             int digit = buffer[from + i] - '0';
    99             ASSERT(0 <= digit && digit <= 9);
    100             result = result * 10 + digit;
    101         }
    102         return result;
    103     }
    104    
    105    
    106     void Bignum::AssignDecimalString(BufferReference<const char> value) {
    107         // 2^64 = 18446744073709551616 > 10^19
    108         const int kMaxUint64DecimalDigits = 19;
    109         Zero();
    110         int length = value.length();
    111         int pos = 0;
    112         // Let's just say that each digit needs 4 bits.
    113         while (length >= kMaxUint64DecimalDigits) {
    114             uint64_t digits = ReadUInt64(value, pos, kMaxUint64DecimalDigits);
    115             pos += kMaxUint64DecimalDigits;
    116             length -= kMaxUint64DecimalDigits;
    117             MultiplyByPowerOfTen(kMaxUint64DecimalDigits);
    118             AddUInt64(digits);
    119         }
    120         uint64_t digits = ReadUInt64(value, pos, length);
    121         MultiplyByPowerOfTen(length);
    122         AddUInt64(digits);
    123         Clamp();
    124     }
    125    
    126    
    127     void Bignum::AssignHexString(BufferReference<const char> value) {
    128         Zero();
    129         int length = value.length();
    130        
    131         int needed_bigits = length * 4 / kBigitSize + 1;
    132         EnsureCapacity(needed_bigits);
    133         int string_index = length - 1;
    134         for (int i = 0; i < needed_bigits - 1; ++i) {
    135             // These bigits are guaranteed to be "full".
    136             Chunk current_bigit = 0;
    137             for (int j = 0; j < kBigitSize / 4; j++) {
    138                 current_bigit += toASCIIHexValue(value[string_index--]) << (j * 4);
    139             }
    140             bigits_[i] = current_bigit;
    141         }
    142         used_digits_ = needed_bigits - 1;
    143        
    144         Chunk most_significant_bigit = 0;  // Could be = 0;
    145         for (int j = 0; j <= string_index; ++j) {
    146             most_significant_bigit <<= 4;
    147             most_significant_bigit += toASCIIHexValue(value[j]);
    148         }
    149         if (most_significant_bigit != 0) {
    150             bigits_[used_digits_] = most_significant_bigit;
    151             used_digits_++;
    152         }
    153         Clamp();
    154     }
    155    
    156    
    157     void Bignum::AddUInt64(uint64_t operand) {
    158         if (operand == 0) return;
    159         Bignum other;
    160         other.AssignUInt64(operand);
    161         AddBignum(other);
    162     }
    163    
    164    
    165     void Bignum::AddBignum(const Bignum& other) {
    166         ASSERT(IsClamped());
    167         ASSERT(other.IsClamped());
    168        
    169         // If this has a greater exponent than other append zero-bigits to this.
    170         // After this call exponent_ <= other.exponent_.
    171         Align(other);
    172        
    173         // There are two possibilities:
    174         //   aaaaaaaaaaa 0000  (where the 0s represent a's exponent)
    175         //     bbbbb 00000000
    176         //   ----------------
    177         //   ccccccccccc 0000
    178         // or
    179         //    aaaaaaaaaa 0000
    180         //  bbbbbbbbb 0000000
    181         //  -----------------
    182         //  cccccccccccc 0000
    183         // In both cases we might need a carry bigit.
    184        
    185         EnsureCapacity(1 + Max(BigitLength(), other.BigitLength()) - exponent_);
    186         Chunk carry = 0;
    187         int bigit_pos = other.exponent_ - exponent_;
    188         ASSERT(bigit_pos >= 0);
    189         for (int i = 0; i < other.used_digits_; ++i) {
    190             Chunk sum = bigits_[bigit_pos] + other.bigits_[i] + carry;
    191             bigits_[bigit_pos] = sum & kBigitMask;
    192             carry = sum >> kBigitSize;
    193             bigit_pos++;
    194         }
    195        
    196         while (carry != 0) {
    197             Chunk sum = bigits_[bigit_pos] + carry;
    198             bigits_[bigit_pos] = sum & kBigitMask;
    199             carry = sum >> kBigitSize;
    200             bigit_pos++;
    201         }
    202         used_digits_ = Max(bigit_pos, used_digits_);
    203         ASSERT(IsClamped());
    204     }
    205    
    206    
    207     void Bignum::SubtractBignum(const Bignum& other) {
    208         ASSERT(IsClamped());
    209         ASSERT(other.IsClamped());
    210         // We require this to be bigger than other.
    211         ASSERT(LessEqual(other, *this));
    212        
    213         Align(other);
    214        
    215         int offset = other.exponent_ - exponent_;
    216         Chunk borrow = 0;
    217         int i;
    218         for (i = 0; i < other.used_digits_; ++i) {
    219             ASSERT((borrow == 0) || (borrow == 1));
    220             Chunk difference = bigits_[i + offset] - other.bigits_[i] - borrow;
    221             bigits_[i + offset] = difference & kBigitMask;
    222             borrow = difference >> (kChunkSize - 1);
    223         }
    224         while (borrow != 0) {
    225             Chunk difference = bigits_[i + offset] - borrow;
    226             bigits_[i + offset] = difference & kBigitMask;
    227             borrow = difference >> (kChunkSize - 1);
    228             ++i;
    229         }
    230         Clamp();
    231     }
    232    
    233    
    234     void Bignum::ShiftLeft(int shift_amount) {
    235         if (used_digits_ == 0) return;
    236         exponent_ += shift_amount / kBigitSize;
    237         int local_shift = shift_amount % kBigitSize;
    238         EnsureCapacity(used_digits_ + 1);
    239         BigitsShiftLeft(local_shift);
    240     }
    241    
    242    
    243     void Bignum::MultiplyByUInt32(uint32_t factor) {
    244         if (factor == 1) return;
    245         if (factor == 0) {
    246             Zero();
    247             return;
    248         }
    249         if (used_digits_ == 0) return;
    250        
    251         // The product of a bigit with the factor is of size kBigitSize + 32.
    252         // Assert that this number + 1 (for the carry) fits into double chunk.
    253         ASSERT(kDoubleChunkSize >= kBigitSize + 32 + 1);
    254         DoubleChunk carry = 0;
    255         for (int i = 0; i < used_digits_; ++i) {
    256             DoubleChunk product = static_cast<DoubleChunk>(factor) * bigits_[i] + carry;
    257             bigits_[i] = static_cast<Chunk>(product & kBigitMask);
    258             carry = (product >> kBigitSize);
    259         }
    260         while (carry != 0) {
    261             EnsureCapacity(used_digits_ + 1);
    262             bigits_[used_digits_] = static_cast<Chunk>(carry & kBigitMask);
    263             used_digits_++;
    264             carry >>= kBigitSize;
    265         }
    266     }
    267    
    268    
    269     void Bignum::MultiplyByUInt64(uint64_t factor) {
    270         if (factor == 1) return;
    271         if (factor == 0) {
    272             Zero();
    273             return;
    274         }
    275         ASSERT(kBigitSize < 32);
    276         uint64_t carry = 0;
    277         uint64_t low = factor & 0xFFFFFFFF;
    278         uint64_t high = factor >> 32;
    279         for (int i = 0; i < used_digits_; ++i) {
    280             uint64_t product_low = low * bigits_[i];
    281             uint64_t product_high = high * bigits_[i];
    282             uint64_t tmp = (carry & kBigitMask) + product_low;
    283             bigits_[i] = static_cast<Chunk>(tmp & kBigitMask);
    284             carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
    285             (product_high << (32 - kBigitSize));
    286         }
    287         while (carry != 0) {
    288             EnsureCapacity(used_digits_ + 1);
    289             bigits_[used_digits_] = static_cast<Chunk>(carry & kBigitMask);
    290             used_digits_++;
    291             carry >>= kBigitSize;
    292         }
    293     }
    294    
    295    
    296     void Bignum::MultiplyByPowerOfTen(int exponent) {
    297         const uint64_t kFive27 = UINT64_2PART_C(0x6765c793, fa10079d);
    298         const uint16_t kFive1 = 5;
    299         const uint16_t kFive2 = kFive1 * 5;
    300         const uint16_t kFive3 = kFive2 * 5;
    301         const uint16_t kFive4 = kFive3 * 5;
    302         const uint16_t kFive5 = kFive4 * 5;
    303         const uint16_t kFive6 = kFive5 * 5;
    304         const uint32_t kFive7 = kFive6 * 5;
    305         const uint32_t kFive8 = kFive7 * 5;
    306         const uint32_t kFive9 = kFive8 * 5;
    307         const uint32_t kFive10 = kFive9 * 5;
    308         const uint32_t kFive11 = kFive10 * 5;
    309         const uint32_t kFive12 = kFive11 * 5;
    310         const uint32_t kFive13 = kFive12 * 5;
    311         const uint32_t kFive1_to_12[] =
    312         { kFive1, kFive2, kFive3, kFive4, kFive5, kFive6,
    313             kFive7, kFive8, kFive9, kFive10, kFive11, kFive12 };
    314        
    315         ASSERT(exponent >= 0);
    316         if (exponent == 0) return;
    317         if (used_digits_ == 0) return;
    318        
    319         // We shift by exponent at the end just before returning.
    320         int remaining_exponent = exponent;
    321         while (remaining_exponent >= 27) {
    322             MultiplyByUInt64(kFive27);
    323             remaining_exponent -= 27;
    324         }
    325         while (remaining_exponent >= 13) {
    326             MultiplyByUInt32(kFive13);
    327             remaining_exponent -= 13;
    328         }
    329         if (remaining_exponent > 0) {
    330             MultiplyByUInt32(kFive1_to_12[remaining_exponent - 1]);
    331         }
    332         ShiftLeft(exponent);
    333     }
    334    
    335    
    336     void Bignum::Square() {
    337         ASSERT(IsClamped());
    338         int product_length = 2 * used_digits_;
    339         EnsureCapacity(product_length);
    340        
    341         // Comba multiplication: compute each column separately.
    342         // Example: r = a2a1a0 * b2b1b0.
    343         //    r =  1    * a0b0 +
    344         //        10    * (a1b0 + a0b1) +
    345         //        100   * (a2b0 + a1b1 + a0b2) +
    346         //        1000  * (a2b1 + a1b2) +
    347         //        10000 * a2b2
    348         //
    349         // In the worst case we have to accumulate nb-digits products of digit*digit.
    350         //
    351         // Assert that the additional number of bits in a DoubleChunk are enough to
    352         // sum up used_digits of Bigit*Bigit.
    353         if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_digits_) {
    354             UNIMPLEMENTED();
    355         }
    356         DoubleChunk accumulator = 0;
    357         // First shift the digits so we don't overwrite them.
    358         int copy_offset = used_digits_;
    359         for (int i = 0; i < used_digits_; ++i) {
    360             bigits_[copy_offset + i] = bigits_[i];
    361         }
    362         // We have two loops to avoid some 'if's in the loop.
    363         for (int i = 0; i < used_digits_; ++i) {
    364             // Process temporary digit i with power i.
    365             // The sum of the two indices must be equal to i.
    366             int bigit_index1 = i;
    367             int bigit_index2 = 0;
    368             // Sum all of the sub-products.
    369             while (bigit_index1 >= 0) {
    370                 Chunk chunk1 = bigits_[copy_offset + bigit_index1];
    371                 Chunk chunk2 = bigits_[copy_offset + bigit_index2];
    372                 accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
    373                 bigit_index1--;
    374                 bigit_index2++;
    375             }
    376             bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
    377             accumulator >>= kBigitSize;
    378         }
    379         for (int i = used_digits_; i < product_length; ++i) {
    380             int bigit_index1 = used_digits_ - 1;
    381             int bigit_index2 = i - bigit_index1;
    382             // Invariant: sum of both indices is again equal to i.
    383             // Inner loop runs 0 times on last iteration, emptying accumulator.
    384             while (bigit_index2 < used_digits_) {
    385                 Chunk chunk1 = bigits_[copy_offset + bigit_index1];
    386                 Chunk chunk2 = bigits_[copy_offset + bigit_index2];
    387                 accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
    388                 bigit_index1--;
    389                 bigit_index2++;
    390             }
    391             // The overwritten bigits_[i] will never be read in further loop iterations,
    392             // because bigit_index1 and bigit_index2 are always greater
    393             // than i - used_digits_.
    394             bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
    395             accumulator >>= kBigitSize;
    396         }
    397         // Since the result was guaranteed to lie inside the number the
    398         // accumulator must be 0 now.
    399         ASSERT(accumulator == 0);
    400        
    401         // Don't forget to update the used_digits and the exponent.
    402         used_digits_ = product_length;
    403         exponent_ *= 2;
    404         Clamp();
    405     }
    406    
    407    
    408     void Bignum::AssignPowerUInt16(uint16_t base, int power_exponent) {
    409         ASSERT(base != 0);
    410         ASSERT(power_exponent >= 0);
    411         if (power_exponent == 0) {
    412             AssignUInt16(1);
    413             return;
    414         }
    415         Zero();
    416         int shifts = 0;
    417         // We expect base to be in range 2-32, and most often to be 10.
    418         // It does not make much sense to implement different algorithms for counting
    419         // the bits.
    420         while ((base & 1) == 0) {
    421             base >>= 1;
    422             shifts++;
    423         }
    424         int bit_size = 0;
    425         int tmp_base = base;
    426         while (tmp_base != 0) {
    427             tmp_base >>= 1;
    428             bit_size++;
    429         }
    430         int final_size = bit_size * power_exponent;
    431         // 1 extra bigit for the shifting, and one for rounded final_size.
    432         EnsureCapacity(final_size / kBigitSize + 2);
    433        
    434         // Left to Right exponentiation.
    435         int mask = 1;
    436         while (power_exponent >= mask) mask <<= 1;
    437        
    438         // The mask is now pointing to the bit above the most significant 1-bit of
    439         // power_exponent.
    440         // Get rid of first 1-bit;
    441         mask >>= 2;
    442         uint64_t this_value = base;
    443        
    444         bool delayed_multipliciation = false;
    445         const uint64_t max_32bits = 0xFFFFFFFF;
    446         while (mask != 0 && this_value <= max_32bits) {
    447             this_value = this_value * this_value;
    448             // Verify that there is enough space in this_value to perform the
    449             // multiplication.  The first bit_size bits must be 0.
    450             if ((power_exponent & mask) != 0) {
    451                 uint64_t base_bits_mask =
    452                 ~((static_cast<uint64_t>(1) << (64 - bit_size)) - 1);
    453                 bool high_bits_zero = (this_value & base_bits_mask) == 0;
    454                 if (high_bits_zero) {
    455                     this_value *= base;
    456                 } else {
    457                     delayed_multipliciation = true;
    458                 }
    459             }
    460             mask >>= 1;
    461         }
    462         AssignUInt64(this_value);
    463         if (delayed_multipliciation) {
    464             MultiplyByUInt32(base);
    465         }
    466        
    467         // Now do the same thing as a bignum.
    468         while (mask != 0) {
    469             Square();
    470             if ((power_exponent & mask) != 0) {
    471                 MultiplyByUInt32(base);
    472             }
    473             mask >>= 1;
    474         }
    475        
    476         // And finally add the saved shifts.
    477         ShiftLeft(shifts * power_exponent);
    478     }
    479    
    480    
    481     // Precondition: this/other < 16bit.
    482     uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
    483         ASSERT(IsClamped());
    484         ASSERT(other.IsClamped());
    485         ASSERT(other.used_digits_ > 0);
    486        
    487         // Easy case: if we have less digits than the divisor than the result is 0.
    488         // Note: this handles the case where this == 0, too.
    489         if (BigitLength() < other.BigitLength()) {
    490             return 0;
    491         }
    492        
    493         Align(other);
    494        
    495         uint16_t result = 0;
    496        
    497         // Start by removing multiples of 'other' until both numbers have the same
    498         // number of digits.
    499         while (BigitLength() > other.BigitLength()) {
    500             // This naive approach is extremely inefficient if the this divided other
    501             // might be big. This function is implemented for doubleToString where
    502             // the result should be small (less than 10).
    503             ASSERT(other.bigits_[other.used_digits_ - 1] >= ((1 << kBigitSize) / 16));
    504             // Remove the multiples of the first digit.
    505             // Example this = 23 and other equals 9. -> Remove 2 multiples.
    506             result += bigits_[used_digits_ - 1];
    507             SubtractTimes(other, bigits_[used_digits_ - 1]);
    508         }
    509        
    510         ASSERT(BigitLength() == other.BigitLength());
    511        
    512         // Both bignums are at the same length now.
    513         // Since other has more than 0 digits we know that the access to
    514         // bigits_[used_digits_ - 1] is safe.
    515         Chunk this_bigit = bigits_[used_digits_ - 1];
    516         Chunk other_bigit = other.bigits_[other.used_digits_ - 1];
    517        
    518         if (other.used_digits_ == 1) {
    519             // Shortcut for easy (and common) case.
    520             int quotient = this_bigit / other_bigit;
    521             bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient;
    522             result += quotient;
    523             Clamp();
    524             return result;
    525         }
    526        
    527         int division_estimate = this_bigit / (other_bigit + 1);
    528         result += division_estimate;
    529         SubtractTimes(other, division_estimate);
    530        
    531         if (other_bigit * (division_estimate + 1) > this_bigit) {
    532             // No need to even try to subtract. Even if other's remaining digits were 0
    533             // another subtraction would be too much.
    534             return result;
    535         }
    536        
    537         while (LessEqual(other, *this)) {
    538             SubtractBignum(other);
    539             result++;
    540         }
    541         return result;
    542     }
    543    
    544    
    545     template<typename S>
    546     static int SizeInHexChars(S number) {
    547         ASSERT(number > 0);
    548         int result = 0;
    549         while (number != 0) {
    550             number >>= 4;
    551             result++;
    552         }
    553         return result;
    554     }
    555    
    556    
    557     static char HexCharOfValue(int value) {
    558         ASSERT(0 <= value && value <= 16);
    559         if (value < 10) return value + '0';
    560         return value - 10 + 'A';
    561     }
    562    
    563    
    564     bool Bignum::ToHexString(char* buffer, int buffer_size) const {
    565         ASSERT(IsClamped());
    566         // Each bigit must be printable as separate hex-character.
    567         ASSERT(kBigitSize % 4 == 0);
    568         const int kHexCharsPerBigit = kBigitSize / 4;
    569        
    570         if (used_digits_ == 0) {
    571             if (buffer_size < 2) return false;
    572             buffer[0] = '0';
    573             buffer[1] = '\0';
    574             return true;
    575         }
    576         // We add 1 for the terminating '\0' character.
    577         int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
    578         SizeInHexChars(bigits_[used_digits_ - 1]) + 1;
    579         if (needed_chars > buffer_size) return false;
    580         int string_index = needed_chars - 1;
    581         buffer[string_index--] = '\0';
    582         for (int i = 0; i < exponent_; ++i) {
    583             for (int j = 0; j < kHexCharsPerBigit; ++j) {
    584                 buffer[string_index--] = '0';
    585             }
    586         }
    587         for (int i = 0; i < used_digits_ - 1; ++i) {
    588             Chunk current_bigit = bigits_[i];
    589             for (int j = 0; j < kHexCharsPerBigit; ++j) {
    590                 buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
    591                 current_bigit >>= 4;
    592             }
    593         }
    594         // And finally the last bigit.
    595         Chunk most_significant_bigit = bigits_[used_digits_ - 1];
    596         while (most_significant_bigit != 0) {
    597             buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
    598             most_significant_bigit >>= 4;
    599         }
    600         return true;
    601     }
    602    
    603    
    604     Bignum::Chunk Bignum::BigitAt(int index) const {
    605         if (index >= BigitLength()) return 0;
    606         if (index < exponent_) return 0;
    607         return bigits_[index - exponent_];
    608     }
    609    
    610    
    611     int Bignum::Compare(const Bignum& a, const Bignum& b) {
    612         ASSERT(a.IsClamped());
    613         ASSERT(b.IsClamped());
    614         int bigit_length_a = a.BigitLength();
    615         int bigit_length_b = b.BigitLength();
    616         if (bigit_length_a < bigit_length_b) return -1;
    617         if (bigit_length_a > bigit_length_b) return +1;
    618         for (int i = bigit_length_a - 1; i >= Min(a.exponent_, b.exponent_); --i) {
    619             Chunk bigit_a = a.BigitAt(i);
    620             Chunk bigit_b = b.BigitAt(i);
    621             if (bigit_a < bigit_b) return -1;
    622             if (bigit_a > bigit_b) return +1;
    623             // Otherwise they are equal up to this digit. Try the next digit.
    624         }
    625         return 0;
    626     }
    627    
    628    
    629     int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
    630         ASSERT(a.IsClamped());
    631         ASSERT(b.IsClamped());
    632         ASSERT(c.IsClamped());
    633         if (a.BigitLength() < b.BigitLength()) {
    634             return PlusCompare(b, a, c);
    635         }
    636         if (a.BigitLength() + 1 < c.BigitLength()) return -1;
    637         if (a.BigitLength() > c.BigitLength()) return +1;
    638         // The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
    639         // 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
    640         // of 'a'.
    641         if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength()) {
    642             return -1;
    643         }
    644        
    645         Chunk borrow = 0;
    646         // Starting at min_exponent all digits are == 0. So no need to compare them.
    647         int min_exponent = Min(Min(a.exponent_, b.exponent_), c.exponent_);
    648         for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
    649             Chunk chunk_a = a.BigitAt(i);
    650             Chunk chunk_b = b.BigitAt(i);
    651             Chunk chunk_c = c.BigitAt(i);
    652             Chunk sum = chunk_a + chunk_b;
    653             if (sum > chunk_c + borrow) {
    654                 return +1;
    655             } else {
    656                 borrow = chunk_c + borrow - sum;
    657                 if (borrow > 1) return -1;
    658                 borrow <<= kBigitSize;
    659             }
    660         }
    661         if (borrow == 0) return 0;
    662         return -1;
    663     }
    664    
    665    
    666     void Bignum::Clamp() {
    667         while (used_digits_ > 0 && bigits_[used_digits_ - 1] == 0) {
    668             used_digits_--;
    669         }
    670         if (used_digits_ == 0) {
    671             // Zero.
    672             exponent_ = 0;
    673         }
    674     }
    675    
    676    
    677     bool Bignum::IsClamped() const {
    678         return used_digits_ == 0 || bigits_[used_digits_ - 1] != 0;
    679     }
    680    
    681    
    682     void Bignum::Zero() {
    683         for (int i = 0; i < used_digits_; ++i) {
    684             bigits_[i] = 0;
    685         }
    686         used_digits_ = 0;
    687         exponent_ = 0;
    688     }
    689    
    690    
    691     void Bignum::Align(const Bignum& other) {
    692         if (exponent_ > other.exponent_) {
    693             // If "X" represents a "hidden" digit (by the exponent) then we are in the
    694             // following case (a == this, b == other):
    695             // a:  aaaaaaXXXX   or a:   aaaaaXXX
    696             // b:     bbbbbbX      b: bbbbbbbbXX
    697             // We replace some of the hidden digits (X) of a with 0 digits.
    698             // a:  aaaaaa000X   or a:   aaaaa0XX
    699             int zero_digits = exponent_ - other.exponent_;
    700             EnsureCapacity(used_digits_ + zero_digits);
    701             for (int i = used_digits_ - 1; i >= 0; --i) {
    702                 bigits_[i + zero_digits] = bigits_[i];
    703             }
    704             for (int i = 0; i < zero_digits; ++i) {
    705                 bigits_[i] = 0;
    706             }
    707             used_digits_ += zero_digits;
    708             exponent_ -= zero_digits;
    709             ASSERT(used_digits_ >= 0);
    710             ASSERT(exponent_ >= 0);
    711         }
    712     }
    713    
    714    
    715     void Bignum::BigitsShiftLeft(int shift_amount) {
    716         ASSERT(shift_amount < kBigitSize);
    717         ASSERT(shift_amount >= 0);
    718         Chunk carry = 0;
    719         for (int i = 0; i < used_digits_; ++i) {
    720             Chunk new_carry = bigits_[i] >> (kBigitSize - shift_amount);
    721             bigits_[i] = ((bigits_[i] << shift_amount) + carry) & kBigitMask;
    722             carry = new_carry;
    723         }
    724         if (carry != 0) {
    725             bigits_[used_digits_] = carry;
    726             used_digits_++;
    727         }
    728     }
    729    
    730    
    731     void Bignum::SubtractTimes(const Bignum& other, int factor) {
    732 #ifndef NDEBUG
    733         Bignum a, b;
    734         a.AssignBignum(*this);
    735         b.AssignBignum(other);
    736         b.MultiplyByUInt32(factor);
    737         a.SubtractBignum(b);
    738 #endif
    739         ASSERT(exponent_ <= other.exponent_);
    740         if (factor < 3) {
    741             for (int i = 0; i < factor; ++i) {
    742                 SubtractBignum(other);
    743             }
    744             return;
    745         }
    746         Chunk borrow = 0;
    747         int exponent_diff = other.exponent_ - exponent_;
    748         for (int i = 0; i < other.used_digits_; ++i) {
    749             DoubleChunk product = static_cast<DoubleChunk>(factor) * other.bigits_[i];
    750             DoubleChunk remove = borrow + product;
    751             Chunk difference =
    752                 bigits_[i + exponent_diff] - static_cast<Chunk>(remove & kBigitMask);
    753             bigits_[i + exponent_diff] = difference & kBigitMask;
    754             borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
    755                                         (remove >> kBigitSize));
    756         }
    757         for (int i = other.used_digits_ + exponent_diff; i < used_digits_; ++i) {
    758             if (borrow == 0) return;
    759             Chunk difference = bigits_[i] - borrow;
    760             bigits_[i] = difference & kBigitMask;
    761             borrow = difference >> (kChunkSize - 1);
    762         }
    763         Clamp();
    764         ASSERT(Bignum::Equal(a, *this));
    765     }
    766    
    767    
     37
     38Bignum::Bignum()
     39    : bigits_buffer_(), bigits_(bigits_buffer_, kBigitCapacity), used_digits_(0), exponent_(0) {
     40  for (int i = 0; i < kBigitCapacity; ++i) {
     41    bigits_[i] = 0;
     42  }
     43}
     44
     45
     46template<typename S>
     47static int BitSize(S value) {
     48  (void) value;  // Mark variable as used.
     49  return 8 * sizeof(value);
     50}
     51
     52// Guaranteed to lie in one Bigit.
     53void Bignum::AssignUInt16(uint16_t value) {
     54  ASSERT(kBigitSize >= BitSize(value));
     55  Zero();
     56  if (value == 0) return;
     57
     58  EnsureCapacity(1);
     59  bigits_[0] = value;
     60  used_digits_ = 1;
     61}
     62
     63
     64void Bignum::AssignUInt64(uint64_t value) {
     65  const int kUInt64Size = 64;
     66
     67  Zero();
     68  if (value == 0) return;
     69
     70  int needed_bigits = kUInt64Size / kBigitSize + 1;
     71  EnsureCapacity(needed_bigits);
     72  for (int i = 0; i < needed_bigits; ++i) {
     73    bigits_[i] = value & kBigitMask;
     74    value = value >> kBigitSize;
     75  }
     76  used_digits_ = needed_bigits;
     77  Clamp();
     78}
     79
     80
     81void Bignum::AssignBignum(const Bignum& other) {
     82  exponent_ = other.exponent_;
     83  for (int i = 0; i < other.used_digits_; ++i) {
     84    bigits_[i] = other.bigits_[i];
     85  }
     86  // Clear the excess digits (if there were any).
     87  for (int i = other.used_digits_; i < used_digits_; ++i) {
     88    bigits_[i] = 0;
     89  }
     90  used_digits_ = other.used_digits_;
     91}
     92
     93
     94static uint64_t ReadUInt64(BufferReference<const char> buffer,
     95                           int from,
     96                           int digits_to_read) {
     97  uint64_t result = 0;
     98  for (int i = from; i < from + digits_to_read; ++i) {
     99    int digit = buffer[i] - '0';
     100    ASSERT(0 <= digit && digit <= 9);
     101    result = result * 10 + digit;
     102  }
     103  return result;
     104}
     105
     106
     107void Bignum::AssignDecimalString(BufferReference<const char> value) {
     108  // 2^64 = 18446744073709551616 > 10^19
     109  const int kMaxUint64DecimalDigits = 19;
     110  Zero();
     111  int length = value.length();
     112  unsigned int pos = 0;
     113  // Let's just say that each digit needs 4 bits.
     114  while (length >= kMaxUint64DecimalDigits) {
     115    uint64_t digits = ReadUInt64(value, pos, kMaxUint64DecimalDigits);
     116    pos += kMaxUint64DecimalDigits;
     117    length -= kMaxUint64DecimalDigits;
     118    MultiplyByPowerOfTen(kMaxUint64DecimalDigits);
     119    AddUInt64(digits);
     120  }
     121  uint64_t digits = ReadUInt64(value, pos, length);
     122  MultiplyByPowerOfTen(length);
     123  AddUInt64(digits);
     124  Clamp();
     125}
     126
     127
     128void Bignum::AssignHexString(BufferReference<const char> value) {
     129  Zero();
     130  int length = value.length();
     131
     132  int needed_bigits = length * 4 / kBigitSize + 1;
     133  EnsureCapacity(needed_bigits);
     134  int string_index = length - 1;
     135  for (int i = 0; i < needed_bigits - 1; ++i) {
     136    // These bigits are guaranteed to be "full".
     137    Chunk current_bigit = 0;
     138    for (int j = 0; j < kBigitSize / 4; j++) {
     139      current_bigit += toASCIIHexValue(value[string_index--]) << (j * 4);
     140    }
     141    bigits_[i] = current_bigit;
     142  }
     143  used_digits_ = needed_bigits - 1;
     144
     145  Chunk most_significant_bigit = 0;  // Could be = 0;
     146  for (int j = 0; j <= string_index; ++j) {
     147    most_significant_bigit <<= 4;
     148    most_significant_bigit += toASCIIHexValue(value[j]);
     149  }
     150  if (most_significant_bigit != 0) {
     151    bigits_[used_digits_] = most_significant_bigit;
     152    used_digits_++;
     153  }
     154  Clamp();
     155}
     156
     157
     158void Bignum::AddUInt64(uint64_t operand) {
     159  if (operand == 0) return;
     160  Bignum other;
     161  other.AssignUInt64(operand);
     162  AddBignum(other);
     163}
     164
     165
     166void Bignum::AddBignum(const Bignum& other) {
     167  ASSERT(IsClamped());
     168  ASSERT(other.IsClamped());
     169
     170  // If this has a greater exponent than other append zero-bigits to this.
     171  // After this call exponent_ <= other.exponent_.
     172  Align(other);
     173
     174  // There are two possibilities:
     175  //   aaaaaaaaaaa 0000  (where the 0s represent a's exponent)
     176  //     bbbbb 00000000
     177  //   ----------------
     178  //   ccccccccccc 0000
     179  // or
     180  //    aaaaaaaaaa 0000
     181  //  bbbbbbbbb 0000000
     182  //  -----------------
     183  //  cccccccccccc 0000
     184  // In both cases we might need a carry bigit.
     185
     186  EnsureCapacity(1 + Max(BigitLength(), other.BigitLength()) - exponent_);
     187  Chunk carry = 0;
     188  int bigit_pos = other.exponent_ - exponent_;
     189  ASSERT(bigit_pos >= 0);
     190  for (int i = 0; i < other.used_digits_; ++i) {
     191    Chunk sum = bigits_[bigit_pos] + other.bigits_[i] + carry;
     192    bigits_[bigit_pos] = sum & kBigitMask;
     193    carry = sum >> kBigitSize;
     194    bigit_pos++;
     195  }
     196
     197  while (carry != 0) {
     198    Chunk sum = bigits_[bigit_pos] + carry;
     199    bigits_[bigit_pos] = sum & kBigitMask;
     200    carry = sum >> kBigitSize;
     201    bigit_pos++;
     202  }
     203  used_digits_ = Max(bigit_pos, used_digits_);
     204  ASSERT(IsClamped());
     205}
     206
     207
     208void Bignum::SubtractBignum(const Bignum& other) {
     209  ASSERT(IsClamped());
     210  ASSERT(other.IsClamped());
     211  // We require this to be bigger than other.
     212  ASSERT(LessEqual(other, *this));
     213
     214  Align(other);
     215
     216  int offset = other.exponent_ - exponent_;
     217  Chunk borrow = 0;
     218  int i;
     219  for (i = 0; i < other.used_digits_; ++i) {
     220    ASSERT((borrow == 0) || (borrow == 1));
     221    Chunk difference = bigits_[i + offset] - other.bigits_[i] - borrow;
     222    bigits_[i + offset] = difference & kBigitMask;
     223    borrow = difference >> (kChunkSize - 1);
     224  }
     225  while (borrow != 0) {
     226    Chunk difference = bigits_[i + offset] - borrow;
     227    bigits_[i + offset] = difference & kBigitMask;
     228    borrow = difference >> (kChunkSize - 1);
     229    ++i;
     230  }
     231  Clamp();
     232}
     233
     234
     235void Bignum::ShiftLeft(int shift_amount) {
     236  if (used_digits_ == 0) return;
     237  exponent_ += shift_amount / kBigitSize;
     238  int local_shift = shift_amount % kBigitSize;
     239  EnsureCapacity(used_digits_ + 1);
     240  BigitsShiftLeft(local_shift);
     241}
     242
     243
     244void Bignum::MultiplyByUInt32(uint32_t factor) {
     245  if (factor == 1) return;
     246  if (factor == 0) {
     247    Zero();
     248    return;
     249  }
     250  if (used_digits_ == 0) return;
     251
     252  // The product of a bigit with the factor is of size kBigitSize + 32.
     253  // Assert that this number + 1 (for the carry) fits into double chunk.
     254  ASSERT(kDoubleChunkSize >= kBigitSize + 32 + 1);
     255  DoubleChunk carry = 0;
     256  for (int i = 0; i < used_digits_; ++i) {
     257    DoubleChunk product = static_cast<DoubleChunk>(factor) * bigits_[i] + carry;
     258    bigits_[i] = static_cast<Chunk>(product & kBigitMask);
     259    carry = (product >> kBigitSize);
     260  }
     261  while (carry != 0) {
     262    EnsureCapacity(used_digits_ + 1);
     263    bigits_[used_digits_] = carry & kBigitMask;
     264    used_digits_++;
     265    carry >>= kBigitSize;
     266  }
     267}
     268
     269
     270void Bignum::MultiplyByUInt64(uint64_t factor) {
     271  if (factor == 1) return;
     272  if (factor == 0) {
     273    Zero();
     274    return;
     275  }
     276  ASSERT(kBigitSize < 32);
     277  uint64_t carry = 0;
     278  uint64_t low = factor & 0xFFFFFFFF;
     279  uint64_t high = factor >> 32;
     280  for (int i = 0; i < used_digits_; ++i) {
     281    uint64_t product_low = low * bigits_[i];
     282    uint64_t product_high = high * bigits_[i];
     283    uint64_t tmp = (carry & kBigitMask) + product_low;
     284    bigits_[i] = tmp & kBigitMask;
     285    carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
     286        (product_high << (32 - kBigitSize));
     287  }
     288  while (carry != 0) {
     289    EnsureCapacity(used_digits_ + 1);
     290    bigits_[used_digits_] = carry & kBigitMask;
     291    used_digits_++;
     292    carry >>= kBigitSize;
     293  }
     294}
     295
     296
     297void Bignum::MultiplyByPowerOfTen(int exponent) {
     298  const uint64_t kFive27 = UINT64_2PART_C(0x6765c793, fa10079d);
     299  const uint16_t kFive1 = 5;
     300  const uint16_t kFive2 = kFive1 * 5;
     301  const uint16_t kFive3 = kFive2 * 5;
     302  const uint16_t kFive4 = kFive3 * 5;
     303  const uint16_t kFive5 = kFive4 * 5;
     304  const uint16_t kFive6 = kFive5 * 5;
     305  const uint32_t kFive7 = kFive6 * 5;
     306  const uint32_t kFive8 = kFive7 * 5;
     307  const uint32_t kFive9 = kFive8 * 5;
     308  const uint32_t kFive10 = kFive9 * 5;
     309  const uint32_t kFive11 = kFive10 * 5;
     310  const uint32_t kFive12 = kFive11 * 5;
     311  const uint32_t kFive13 = kFive12 * 5;
     312  const uint32_t kFive1_to_12[] =
     313      { kFive1, kFive2, kFive3, kFive4, kFive5, kFive6,
     314        kFive7, kFive8, kFive9, kFive10, kFive11, kFive12 };
     315
     316  ASSERT(exponent >= 0);
     317  if (exponent == 0) return;
     318  if (used_digits_ == 0) return;
     319
     320  // We shift by exponent at the end just before returning.
     321  int remaining_exponent = exponent;
     322  while (remaining_exponent >= 27) {
     323    MultiplyByUInt64(kFive27);
     324    remaining_exponent -= 27;
     325  }
     326  while (remaining_exponent >= 13) {
     327    MultiplyByUInt32(kFive13);
     328    remaining_exponent -= 13;
     329  }
     330  if (remaining_exponent > 0) {
     331    MultiplyByUInt32(kFive1_to_12[remaining_exponent - 1]);
     332  }
     333  ShiftLeft(exponent);
     334}
     335
     336
     337void Bignum::Square() {
     338  ASSERT(IsClamped());
     339  int product_length = 2 * used_digits_;
     340  EnsureCapacity(product_length);
     341
     342  // Comba multiplication: compute each column separately.
     343  // Example: r = a2a1a0 * b2b1b0.
     344  //    r =  1    * a0b0 +
     345  //        10    * (a1b0 + a0b1) +
     346  //        100   * (a2b0 + a1b1 + a0b2) +
     347  //        1000  * (a2b1 + a1b2) +
     348  //        10000 * a2b2
     349  //
     350  // In the worst case we have to accumulate nb-digits products of digit*digit.
     351  //
     352  // Assert that the additional number of bits in a DoubleChunk are enough to
     353  // sum up used_digits of Bigit*Bigit.
     354  if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_digits_) {
     355    UNIMPLEMENTED();
     356  }
     357  DoubleChunk accumulator = 0;
     358  // First shift the digits so we don't overwrite them.
     359  int copy_offset = used_digits_;
     360  for (int i = 0; i < used_digits_; ++i) {
     361    bigits_[copy_offset + i] = bigits_[i];
     362  }
     363  // We have two loops to avoid some 'if's in the loop.
     364  for (int i = 0; i < used_digits_; ++i) {
     365    // Process temporary digit i with power i.
     366    // The sum of the two indices must be equal to i.
     367    int bigit_index1 = i;
     368    int bigit_index2 = 0;
     369    // Sum all of the sub-products.
     370    while (bigit_index1 >= 0) {
     371      Chunk chunk1 = bigits_[copy_offset + bigit_index1];
     372      Chunk chunk2 = bigits_[copy_offset + bigit_index2];
     373      accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
     374      bigit_index1--;
     375      bigit_index2++;
     376    }
     377    bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
     378    accumulator >>= kBigitSize;
     379  }
     380  for (int i = used_digits_; i < product_length; ++i) {
     381    int bigit_index1 = used_digits_ - 1;
     382    int bigit_index2 = i - bigit_index1;
     383    // Invariant: sum of both indices is again equal to i.
     384    // Inner loop runs 0 times on last iteration, emptying accumulator.
     385    while (bigit_index2 < used_digits_) {
     386      Chunk chunk1 = bigits_[copy_offset + bigit_index1];
     387      Chunk chunk2 = bigits_[copy_offset + bigit_index2];
     388      accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
     389      bigit_index1--;
     390      bigit_index2++;
     391    }
     392    // The overwritten bigits_[i] will never be read in further loop iterations,
     393    // because bigit_index1 and bigit_index2 are always greater
     394    // than i - used_digits_.
     395    bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
     396    accumulator >>= kBigitSize;
     397  }
     398  // Since the result was guaranteed to lie inside the number the
     399  // accumulator must be 0 now.
     400  ASSERT(accumulator == 0);
     401
     402  // Don't forget to update the used_digits and the exponent.
     403  used_digits_ = product_length;
     404  exponent_ *= 2;
     405  Clamp();
     406}
     407
     408
     409void Bignum::AssignPowerUInt16(uint16_t base, int power_exponent) {
     410  ASSERT(base != 0);
     411  ASSERT(power_exponent >= 0);
     412  if (power_exponent == 0) {
     413    AssignUInt16(1);
     414    return;
     415  }
     416  Zero();
     417  int shifts = 0;
     418  // We expect base to be in range 2-32, and most often to be 10.
     419  // It does not make much sense to implement different algorithms for counting
     420  // the bits.
     421  while ((base & 1) == 0) {
     422    base >>= 1;
     423    shifts++;
     424  }
     425  int bit_size = 0;
     426  int tmp_base = base;
     427  while (tmp_base != 0) {
     428    tmp_base >>= 1;
     429    bit_size++;
     430  }
     431  int final_size = bit_size * power_exponent;
     432  // 1 extra bigit for the shifting, and one for rounded final_size.
     433  EnsureCapacity(final_size / kBigitSize + 2);
     434
     435  // Left to Right exponentiation.
     436  int mask = 1;
     437  while (power_exponent >= mask) mask <<= 1;
     438
     439  // The mask is now pointing to the bit above the most significant 1-bit of
     440  // power_exponent.
     441  // Get rid of first 1-bit;
     442  mask >>= 2;
     443  uint64_t this_value = base;
     444
     445  bool delayed_multiplication = false;
     446  const uint64_t max_32bits = 0xFFFFFFFF;
     447  while (mask != 0 && this_value <= max_32bits) {
     448    this_value = this_value * this_value;
     449    // Verify that there is enough space in this_value to perform the
     450    // multiplication.  The first bit_size bits must be 0.
     451    if ((power_exponent & mask) != 0) {
     452      ASSERT(bit_size > 0);
     453      uint64_t base_bits_mask =
     454          ~((static_cast<uint64_t>(1) << (64 - bit_size)) - 1);
     455      bool high_bits_zero = (this_value & base_bits_mask) == 0;
     456      if (high_bits_zero) {
     457        this_value *= base;
     458      } else {
     459        delayed_multiplication = true;
     460      }
     461    }
     462    mask >>= 1;
     463  }
     464  AssignUInt64(this_value);
     465  if (delayed_multiplication) {
     466    MultiplyByUInt32(base);
     467  }
     468
     469  // Now do the same thing as a bignum.
     470  while (mask != 0) {
     471    Square();
     472    if ((power_exponent & mask) != 0) {
     473      MultiplyByUInt32(base);
     474    }
     475    mask >>= 1;
     476  }
     477
     478  // And finally add the saved shifts.
     479  ShiftLeft(shifts * power_exponent);
     480}
     481
     482
     483// Precondition: this/other < 16bit.
     484uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
     485  ASSERT(IsClamped());
     486  ASSERT(other.IsClamped());
     487  ASSERT(other.used_digits_ > 0);
     488
     489  // Easy case: if we have less digits than the divisor than the result is 0.
     490  // Note: this handles the case where this == 0, too.
     491  if (BigitLength() < other.BigitLength()) {
     492    return 0;
     493  }
     494
     495  Align(other);
     496
     497  uint16_t result = 0;
     498
     499  // Start by removing multiples of 'other' until both numbers have the same
     500  // number of digits.
     501  while (BigitLength() > other.BigitLength()) {
     502    // This naive approach is extremely inefficient if `this` divided by other
     503    // is big. This function is implemented for doubleToString where
     504    // the result should be small (less than 10).
     505    ASSERT(other.bigits_[other.used_digits_ - 1] >= ((1 << kBigitSize) / 16));
     506    ASSERT(bigits_[used_digits_ - 1] < 0x10000);
     507    // Remove the multiples of the first digit.
     508    // Example this = 23 and other equals 9. -> Remove 2 multiples.
     509    result += static_cast<uint16_t>(bigits_[used_digits_ - 1]);
     510    SubtractTimes(other, bigits_[used_digits_ - 1]);
     511  }
     512
     513  ASSERT(BigitLength() == other.BigitLength());
     514
     515  // Both bignums are at the same length now.
     516  // Since other has more than 0 digits we know that the access to
     517  // bigits_[used_digits_ - 1] is safe.
     518  Chunk this_bigit = bigits_[used_digits_ - 1];
     519  Chunk other_bigit = other.bigits_[other.used_digits_ - 1];
     520
     521  if (other.used_digits_ == 1) {
     522    // Shortcut for easy (and common) case.
     523    int quotient = this_bigit / other_bigit;
     524    bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient;
     525    ASSERT(quotient < 0x10000);
     526    result += static_cast<uint16_t>(quotient);
     527    Clamp();
     528    return result;
     529  }
     530
     531  int division_estimate = this_bigit / (other_bigit + 1);
     532  ASSERT(division_estimate < 0x10000);
     533  result += static_cast<uint16_t>(division_estimate);
     534  SubtractTimes(other, division_estimate);
     535
     536  if (other_bigit * (division_estimate + 1) > this_bigit) {
     537    // No need to even try to subtract. Even if other's remaining digits were 0
     538    // another subtraction would be too much.
     539    return result;
     540  }
     541
     542  while (LessEqual(other, *this)) {
     543    SubtractBignum(other);
     544    result++;
     545  }
     546  return result;
     547}
     548
     549
     550template<typename S>
     551static int SizeInHexChars(S number) {
     552  ASSERT(number > 0);
     553  int result = 0;
     554  while (number != 0) {
     555    number >>= 4;
     556    result++;
     557  }
     558  return result;
     559}
     560
     561
     562static char HexCharOfValue(int value) {
     563  ASSERT(0 <= value && value <= 16);
     564  if (value < 10) return static_cast<char>(value + '0');
     565  return static_cast<char>(value - 10 + 'A');
     566}
     567
     568
     569bool Bignum::ToHexString(char* buffer, int buffer_size) const {
     570  ASSERT(IsClamped());
     571  // Each bigit must be printable as separate hex-character.
     572  ASSERT(kBigitSize % 4 == 0);
     573  const int kHexCharsPerBigit = kBigitSize / 4;
     574
     575  if (used_digits_ == 0) {
     576    if (buffer_size < 2) return false;
     577    buffer[0] = '0';
     578    buffer[1] = '\0';
     579    return true;
     580  }
     581  // We add 1 for the terminating '\0' character.
     582  int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
     583      SizeInHexChars(bigits_[used_digits_ - 1]) + 1;
     584  if (needed_chars > buffer_size) return false;
     585  int string_index = needed_chars - 1;
     586  buffer[string_index--] = '\0';
     587  for (int i = 0; i < exponent_; ++i) {
     588    for (int j = 0; j < kHexCharsPerBigit; ++j) {
     589      buffer[string_index--] = '0';
     590    }
     591  }
     592  for (int i = 0; i < used_digits_ - 1; ++i) {
     593    Chunk current_bigit = bigits_[i];
     594    for (int j = 0; j < kHexCharsPerBigit; ++j) {
     595      buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
     596      current_bigit >>= 4;
     597    }
     598  }
     599  // And finally the last bigit.
     600  Chunk most_significant_bigit = bigits_[used_digits_ - 1];
     601  while (most_significant_bigit != 0) {
     602    buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
     603    most_significant_bigit >>= 4;
     604  }
     605  return true;
     606}
     607
     608
     609Bignum::Chunk Bignum::BigitAt(int index) const {
     610  if (index >= BigitLength()) return 0;
     611  if (index < exponent_) return 0;
     612  return bigits_[index - exponent_];
     613}
     614
     615
     616int Bignum::Compare(const Bignum& a, const Bignum& b) {
     617  ASSERT(a.IsClamped());
     618  ASSERT(b.IsClamped());
     619  int bigit_length_a = a.BigitLength();
     620  int bigit_length_b = b.BigitLength();
     621  if (bigit_length_a < bigit_length_b) return -1;
     622  if (bigit_length_a > bigit_length_b) return +1;
     623  for (int i = bigit_length_a - 1; i >= Min(a.exponent_, b.exponent_); --i) {
     624    Chunk bigit_a = a.BigitAt(i);
     625    Chunk bigit_b = b.BigitAt(i);
     626    if (bigit_a < bigit_b) return -1;
     627    if (bigit_a > bigit_b) return +1;
     628    // Otherwise they are equal up to this digit. Try the next digit.
     629  }
     630  return 0;
     631}
     632
     633
     634int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
     635  ASSERT(a.IsClamped());
     636  ASSERT(b.IsClamped());
     637  ASSERT(c.IsClamped());
     638  if (a.BigitLength() < b.BigitLength()) {
     639    return PlusCompare(b, a, c);
     640  }
     641  if (a.BigitLength() + 1 < c.BigitLength()) return -1;
     642  if (a.BigitLength() > c.BigitLength()) return +1;
     643  // The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
     644  // 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
     645  // of 'a'.
     646  if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength()) {
     647    return -1;
     648  }
     649
     650  Chunk borrow = 0;
     651  // Starting at min_exponent all digits are == 0. So no need to compare them.
     652  int min_exponent = Min(Min(a.exponent_, b.exponent_), c.exponent_);
     653  for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
     654    Chunk chunk_a = a.BigitAt(i);
     655    Chunk chunk_b = b.BigitAt(i);
     656    Chunk chunk_c = c.BigitAt(i);
     657    Chunk sum = chunk_a + chunk_b;
     658    if (sum > chunk_c + borrow) {
     659      return +1;
     660    } else {
     661      borrow = chunk_c + borrow - sum;
     662      if (borrow > 1) return -1;
     663      borrow <<= kBigitSize;
     664    }
     665  }
     666  if (borrow == 0) return 0;
     667  return -1;
     668}
     669
     670
     671void Bignum::Clamp() {
     672  while (used_digits_ > 0 && bigits_[used_digits_ - 1] == 0) {
     673    used_digits_--;
     674  }
     675  if (used_digits_ == 0) {
     676    // Zero.
     677    exponent_ = 0;
     678  }
     679}
     680
     681
     682bool Bignum::IsClamped() const {
     683  return used_digits_ == 0 || bigits_[used_digits_ - 1] != 0;
     684}
     685
     686
     687void Bignum::Zero() {
     688  for (int i = 0; i < used_digits_; ++i) {
     689    bigits_[i] = 0;
     690  }
     691  used_digits_ = 0;
     692  exponent_ = 0;
     693}
     694
     695
     696void Bignum::Align(const Bignum& other) {
     697  if (exponent_ > other.exponent_) {
     698    // If "X" represents a "hidden" digit (by the exponent) then we are in the
     699    // following case (a == this, b == other):
     700    // a:  aaaaaaXXXX   or a:   aaaaaXXX
     701    // b:     bbbbbbX      b: bbbbbbbbXX
     702    // We replace some of the hidden digits (X) of a with 0 digits.
     703    // a:  aaaaaa000X   or a:   aaaaa0XX
     704    int zero_digits = exponent_ - other.exponent_;
     705    EnsureCapacity(used_digits_ + zero_digits);
     706    for (int i = used_digits_ - 1; i >= 0; --i) {
     707      bigits_[i + zero_digits] = bigits_[i];
     708    }
     709    for (int i = 0; i < zero_digits; ++i) {
     710      bigits_[i] = 0;
     711    }
     712    used_digits_ += zero_digits;
     713    exponent_ -= zero_digits;
     714    ASSERT(used_digits_ >= 0);
     715    ASSERT(exponent_ >= 0);
     716  }
     717}
     718
     719
     720void Bignum::BigitsShiftLeft(int shift_amount) {
     721  ASSERT(shift_amount < kBigitSize);
     722  ASSERT(shift_amount >= 0);
     723  Chunk carry = 0;
     724  for (int i = 0; i < used_digits_; ++i) {
     725    Chunk new_carry = bigits_[i] >> (kBigitSize - shift_amount);
     726    bigits_[i] = ((bigits_[i] << shift_amount) + carry) & kBigitMask;
     727    carry = new_carry;
     728  }
     729  if (carry != 0) {
     730    bigits_[used_digits_] = carry;
     731    used_digits_++;
     732  }
     733}
     734
     735
     736void Bignum::SubtractTimes(const Bignum& other, int factor) {
     737  ASSERT(exponent_ <= other.exponent_);
     738  if (factor < 3) {
     739    for (int i = 0; i < factor; ++i) {
     740      SubtractBignum(other);
     741    }
     742    return;
     743  }
     744  Chunk borrow = 0;
     745  int exponent_diff = other.exponent_ - exponent_;
     746  for (int i = 0; i < other.used_digits_; ++i) {
     747    DoubleChunk product = static_cast<DoubleChunk>(factor) * other.bigits_[i];
     748    DoubleChunk remove = borrow + product;
     749    Chunk difference = bigits_[i + exponent_diff] - (remove & kBigitMask);
     750    bigits_[i + exponent_diff] = difference & kBigitMask;
     751    borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
     752                                (remove >> kBigitSize));
     753  }
     754  for (int i = other.used_digits_ + exponent_diff; i < used_digits_; ++i) {
     755    if (borrow == 0) return;
     756    Chunk difference = bigits_[i] - borrow;
     757    bigits_[i] = difference & kBigitMask;
     758    borrow = difference >> (kChunkSize - 1);
     759  }
     760  Clamp();
     761}
     762
     763
    768764}  // namespace double_conversion
    769 
    770 } // namespace WTF
     765}  // namespace WTF
  • trunk/Source/WTF/wtf/dtoa/bignum.h

    r147976 r242048  
    2929#define DOUBLE_CONVERSION_BIGNUM_H_
    3030
    31 #include "utils.h"
     31#include <wtf/dtoa/utils.h>
    3232
    3333namespace WTF {
     34namespace double_conversion {
    3435
    35 namespace double_conversion {
    36    
    37     class Bignum {
    38     public:
    39         // 3584 = 128 * 28. We can represent 2^3584 > 10^1000 accurately.
    40         // This bignum can encode much bigger numbers, since it contains an
    41         // exponent.
    42         static const int kMaxSignificantBits = 3584;
    43        
    44         Bignum();
    45         void AssignUInt16(uint16_t value);
    46         void AssignUInt64(uint64_t value);
    47         void AssignBignum(const Bignum& other);
    48        
    49         void AssignDecimalString(BufferReference<const char> value);
    50         void AssignHexString(BufferReference<const char> value);
    51        
    52         void AssignPowerUInt16(uint16_t base, int exponent);
    53        
    54         void AddUInt16(uint16_t operand);
    55         void AddUInt64(uint64_t operand);
    56         void AddBignum(const Bignum& other);
    57         // Precondition: this >= other.
    58         void SubtractBignum(const Bignum& other);
    59        
    60         void Square();
    61         void ShiftLeft(int shift_amount);
    62         void MultiplyByUInt32(uint32_t factor);
    63         void MultiplyByUInt64(uint64_t factor);
    64         void MultiplyByPowerOfTen(int exponent);
    65         void Times10() { return MultiplyByUInt32(10); }
    66         // Pseudocode:
    67         //  int result = this / other;
    68         //  this = this % other;
    69         // In the worst case this function is in O(this/other).
    70         uint16_t DivideModuloIntBignum(const Bignum& other);
    71        
    72         bool ToHexString(char* buffer, int buffer_size) const;
    73        
    74         static int Compare(const Bignum& a, const Bignum& b);
    75         static bool Equal(const Bignum& a, const Bignum& b) {
    76             return Compare(a, b) == 0;
    77         }
    78         static bool LessEqual(const Bignum& a, const Bignum& b) {
    79             return Compare(a, b) <= 0;
    80         }
    81         static bool Less(const Bignum& a, const Bignum& b) {
    82             return Compare(a, b) < 0;
    83         }
    84         // Returns Compare(a + b, c);
    85         static int PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c);
    86         // Returns a + b == c
    87         static bool PlusEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
    88             return PlusCompare(a, b, c) == 0;
    89         }
    90         // Returns a + b <= c
    91         static bool PlusLessEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
    92             return PlusCompare(a, b, c) <= 0;
    93         }
    94         // Returns a + b < c
    95         static bool PlusLess(const Bignum& a, const Bignum& b, const Bignum& c) {
    96             return PlusCompare(a, b, c) < 0;
    97         }
    98     private:
    99         typedef uint32_t Chunk;
    100         typedef uint64_t DoubleChunk;
    101        
    102         static const int kChunkSize = sizeof(Chunk) * 8;
    103         static const int kDoubleChunkSize = sizeof(DoubleChunk) * 8;
    104         // With bigit size of 28 we loose some bits, but a double still fits easily
    105         // into two chunks, and more importantly we can use the Comba multiplication.
    106         static const int kBigitSize = 28;
    107         static const Chunk kBigitMask = (1 << kBigitSize) - 1;
    108         // Every instance allocates kBigitLength chunks on the stack. Bignums cannot
    109         // grow. There are no checks if the stack-allocated space is sufficient.
    110         static const int kBigitCapacity = kMaxSignificantBits / kBigitSize;
    111        
    112         void EnsureCapacity(int size) {
    113             if (size > kBigitCapacity) {
    114                 UNREACHABLE();
    115             }
    116         }
    117         void Align(const Bignum& other);
    118         void Clamp();
    119         bool IsClamped() const;
    120         void Zero();
    121         // Requires this to have enough capacity (no tests done).
    122         // Updates used_digits_ if necessary.
    123         // shift_amount must be < kBigitSize.
    124         void BigitsShiftLeft(int shift_amount);
    125         // BigitLength includes the "hidden" digits encoded in the exponent.
    126         int BigitLength() const { return used_digits_ + exponent_; }
    127         Chunk BigitAt(int index) const;
    128         void SubtractTimes(const Bignum& other, int factor);
    129        
    130         Chunk bigits_buffer_[kBigitCapacity];
    131         // A vector backed by bigits_buffer_. This way accesses to the array are
    132         // checked for out-of-bounds errors.
    133         BufferReference<Chunk> bigits_;
    134         int used_digits_;
    135         // The Bignum's value equals value(bigits_) * 2^(exponent_ * kBigitSize).
    136         int exponent_;
    137        
    138         DISALLOW_COPY_AND_ASSIGN(Bignum);
    139     };
    140    
     36class Bignum {
     37 public:
     38  // 3584 = 128 * 28. We can represent 2^3584 > 10^1000 accurately.
     39  // This bignum can encode much bigger numbers, since it contains an
     40  // exponent.
     41  static const int kMaxSignificantBits = 3584;
     42
     43  Bignum();
     44  void AssignUInt16(uint16_t value);
     45  void AssignUInt64(uint64_t value);
     46  void AssignBignum(const Bignum& other);
     47
     48  void AssignDecimalString(BufferReference<const char> value);
     49  void AssignHexString(BufferReference<const char> value);
     50
     51  void AssignPowerUInt16(uint16_t base, int exponent);
     52
     53  void AddUInt64(uint64_t operand);
     54  void AddBignum(const Bignum& other);
     55  // Precondition: this >= other.
     56  void SubtractBignum(const Bignum& other);
     57
     58  void Square();
     59  void ShiftLeft(int shift_amount);
     60  void MultiplyByUInt32(uint32_t factor);
     61  void MultiplyByUInt64(uint64_t factor);
     62  void MultiplyByPowerOfTen(int exponent);
     63  void Times10() { return MultiplyByUInt32(10); }
     64  // Pseudocode:
     65  //  int result = this / other;
     66  //  this = this % other;
     67  // In the worst case this function is in O(this/other).
     68  uint16_t DivideModuloIntBignum(const Bignum& other);
     69
     70  bool ToHexString(char* buffer, int buffer_size) const;
     71
     72  // Returns
     73  //  -1 if a < b,
     74  //   0 if a == b, and
     75  //  +1 if a > b.
     76  static int Compare(const Bignum& a, const Bignum& b);
     77  static bool Equal(const Bignum& a, const Bignum& b) {
     78    return Compare(a, b) == 0;
     79  }
     80  static bool LessEqual(const Bignum& a, const Bignum& b) {
     81    return Compare(a, b) <= 0;
     82  }
     83  static bool Less(const Bignum& a, const Bignum& b) {
     84    return Compare(a, b) < 0;
     85  }
     86  // Returns Compare(a + b, c);
     87  static int PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c);
     88  // Returns a + b == c
     89  static bool PlusEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
     90    return PlusCompare(a, b, c) == 0;
     91  }
     92  // Returns a + b <= c
     93  static bool PlusLessEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
     94    return PlusCompare(a, b, c) <= 0;
     95  }
     96  // Returns a + b < c
     97  static bool PlusLess(const Bignum& a, const Bignum& b, const Bignum& c) {
     98    return PlusCompare(a, b, c) < 0;
     99  }
     100 private:
     101  typedef uint32_t Chunk;
     102  typedef uint64_t DoubleChunk;
     103
     104  static const int kChunkSize = sizeof(Chunk) * 8;
     105  static const int kDoubleChunkSize = sizeof(DoubleChunk) * 8;
     106  // With bigit size of 28 we loose some bits, but a double still fits easily
     107  // into two chunks, and more importantly we can use the Comba multiplication.
     108  static const int kBigitSize = 28;
     109  static const Chunk kBigitMask = (1 << kBigitSize) - 1;
     110  // Every instance allocates kBigitLength chunks on the stack. Bignums cannot
     111  // grow. There are no checks if the stack-allocated space is sufficient.
     112  static const int kBigitCapacity = kMaxSignificantBits / kBigitSize;
     113
     114  void EnsureCapacity(int size) {
     115    if (size > kBigitCapacity) {
     116      UNREACHABLE();
     117    }
     118  }
     119  void Align(const Bignum& other);
     120  void Clamp();
     121  bool IsClamped() const;
     122  void Zero();
     123  // Requires this to have enough capacity (no tests done).
     124  // Updates used_digits_ if necessary.
     125  // shift_amount must be < kBigitSize.
     126  void BigitsShiftLeft(int shift_amount);
     127  // BigitLength includes the "hidden" digits encoded in the exponent.
     128  int BigitLength() const { return used_digits_ + exponent_; }
     129  Chunk BigitAt(int index) const;
     130  void SubtractTimes(const Bignum& other, int factor);
     131
     132  Chunk bigits_buffer_[kBigitCapacity];
     133  // A BufferReference backed by bigits_buffer_. This way accesses to the array are
     134  // checked for out-of-bounds errors.
     135  BufferReference<Chunk> bigits_;
     136  int used_digits_;
     137  // The Bignum's value equals value(bigits_) * 2^(exponent_ * kBigitSize).
     138  int exponent_;
     139
     140  DC_DISALLOW_COPY_AND_ASSIGN(Bignum);
     141};
     142
    141143}  // namespace double_conversion
    142 
    143 } // namespace WTF
     144}  // namespace WTF
    144145
    145146#endif  // DOUBLE_CONVERSION_BIGNUM_H_
  • trunk/Source/WTF/wtf/dtoa/cached-powers.cc

    r219124 r242048  
    2828#include "config.h"
    2929
    30 #include <stdarg.h>
    31 #include <limits.h>
    32 #include <math.h>
     30#include <climits>
     31#include <cmath>
     32#include <cstdarg>
    3333
    34 #include "utils.h"
    35 #include "cached-powers.h"
     34#include <wtf/dtoa/utils.h>
     35
     36#include <wtf/dtoa/cached-powers.h>
    3637
    3738namespace WTF {
     39namespace double_conversion {
    3840
    39 namespace double_conversion {
    40    
    41     struct CachedPower {
    42         uint64_t significand;
    43         int16_t binary_exponent;
    44         int16_t decimal_exponent;
    45     };
    46    
    47     constexpr static const double kD_1_LOG2_10 = 0.30102999566398114;  //  1 / lg(10)
    48     constexpr static const CachedPower kCachedPowers[] = {
    49         {UINT64_2PART_C(0xfa8fd5a0, 081c0288), -1220, -348},
    50         {UINT64_2PART_C(0xbaaee17f, a23ebf76), -1193, -340},
    51         {UINT64_2PART_C(0x8b16fb20, 3055ac76), -1166, -332},
    52         {UINT64_2PART_C(0xcf42894a, 5dce35ea), -1140, -324},
    53         {UINT64_2PART_C(0x9a6bb0aa, 55653b2d), -1113, -316},
    54         {UINT64_2PART_C(0xe61acf03, 3d1a45df), -1087, -308},
    55         {UINT64_2PART_C(0xab70fe17, c79ac6ca), -1060, -300},
    56         {UINT64_2PART_C(0xff77b1fc, bebcdc4f), -1034, -292},
    57         {UINT64_2PART_C(0xbe5691ef, 416bd60c), -1007, -284},
    58         {UINT64_2PART_C(0x8dd01fad, 907ffc3c), -980, -276},
    59         {UINT64_2PART_C(0xd3515c28, 31559a83), -954, -268},
    60         {UINT64_2PART_C(0x9d71ac8f, ada6c9b5), -927, -260},
    61         {UINT64_2PART_C(0xea9c2277, 23ee8bcb), -901, -252},
    62         {UINT64_2PART_C(0xaecc4991, 4078536d), -874, -244},
    63         {UINT64_2PART_C(0x823c1279, 5db6ce57), -847, -236},
    64         {UINT64_2PART_C(0xc2109436, 4dfb5637), -821, -228},
    65         {UINT64_2PART_C(0x9096ea6f, 3848984f), -794, -220},
    66         {UINT64_2PART_C(0xd77485cb, 25823ac7), -768, -212},
    67         {UINT64_2PART_C(0xa086cfcd, 97bf97f4), -741, -204},
    68         {UINT64_2PART_C(0xef340a98, 172aace5), -715, -196},
    69         {UINT64_2PART_C(0xb23867fb, 2a35b28e), -688, -188},
    70         {UINT64_2PART_C(0x84c8d4df, d2c63f3b), -661, -180},
    71         {UINT64_2PART_C(0xc5dd4427, 1ad3cdba), -635, -172},
    72         {UINT64_2PART_C(0x936b9fce, bb25c996), -608, -164},
    73         {UINT64_2PART_C(0xdbac6c24, 7d62a584), -582, -156},
    74         {UINT64_2PART_C(0xa3ab6658, 0d5fdaf6), -555, -148},
    75         {UINT64_2PART_C(0xf3e2f893, dec3f126), -529, -140},
    76         {UINT64_2PART_C(0xb5b5ada8, aaff80b8), -502, -132},
    77         {UINT64_2PART_C(0x87625f05, 6c7c4a8b), -475, -124},
    78         {UINT64_2PART_C(0xc9bcff60, 34c13053), -449, -116},
    79         {UINT64_2PART_C(0x964e858c, 91ba2655), -422, -108},
    80         {UINT64_2PART_C(0xdff97724, 70297ebd), -396, -100},
    81         {UINT64_2PART_C(0xa6dfbd9f, b8e5b88f), -369, -92},
    82         {UINT64_2PART_C(0xf8a95fcf, 88747d94), -343, -84},
    83         {UINT64_2PART_C(0xb9447093, 8fa89bcf), -316, -76},
    84         {UINT64_2PART_C(0x8a08f0f8, bf0f156b), -289, -68},
    85         {UINT64_2PART_C(0xcdb02555, 653131b6), -263, -60},
    86         {UINT64_2PART_C(0x993fe2c6, d07b7fac), -236, -52},
    87         {UINT64_2PART_C(0xe45c10c4, 2a2b3b06), -210, -44},
    88         {UINT64_2PART_C(0xaa242499, 697392d3), -183, -36},
    89         {UINT64_2PART_C(0xfd87b5f2, 8300ca0e), -157, -28},
    90         {UINT64_2PART_C(0xbce50864, 92111aeb), -130, -20},
    91         {UINT64_2PART_C(0x8cbccc09, 6f5088cc), -103, -12},
    92         {UINT64_2PART_C(0xd1b71758, e219652c), -77, -4},
    93         {UINT64_2PART_C(0x9c400000, 00000000), -50, 4},
    94         {UINT64_2PART_C(0xe8d4a510, 00000000), -24, 12},
    95         {UINT64_2PART_C(0xad78ebc5, ac620000), 3, 20},
    96         {UINT64_2PART_C(0x813f3978, f8940984), 30, 28},
    97         {UINT64_2PART_C(0xc097ce7b, c90715b3), 56, 36},
    98         {UINT64_2PART_C(0x8f7e32ce, 7bea5c70), 83, 44},
    99         {UINT64_2PART_C(0xd5d238a4, abe98068), 109, 52},
    100         {UINT64_2PART_C(0x9f4f2726, 179a2245), 136, 60},
    101         {UINT64_2PART_C(0xed63a231, d4c4fb27), 162, 68},
    102         {UINT64_2PART_C(0xb0de6538, 8cc8ada8), 189, 76},
    103         {UINT64_2PART_C(0x83c7088e, 1aab65db), 216, 84},
    104         {UINT64_2PART_C(0xc45d1df9, 42711d9a), 242, 92},
    105         {UINT64_2PART_C(0x924d692c, a61be758), 269, 100},
    106         {UINT64_2PART_C(0xda01ee64, 1a708dea), 295, 108},
    107         {UINT64_2PART_C(0xa26da399, 9aef774a), 322, 116},
    108         {UINT64_2PART_C(0xf209787b, b47d6b85), 348, 124},
    109         {UINT64_2PART_C(0xb454e4a1, 79dd1877), 375, 132},
    110         {UINT64_2PART_C(0x865b8692, 5b9bc5c2), 402, 140},
    111         {UINT64_2PART_C(0xc83553c5, c8965d3d), 428, 148},
    112         {UINT64_2PART_C(0x952ab45c, fa97a0b3), 455, 156},
    113         {UINT64_2PART_C(0xde469fbd, 99a05fe3), 481, 164},
    114         {UINT64_2PART_C(0xa59bc234, db398c25), 508, 172},
    115         {UINT64_2PART_C(0xf6c69a72, a3989f5c), 534, 180},
    116         {UINT64_2PART_C(0xb7dcbf53, 54e9bece), 561, 188},
    117         {UINT64_2PART_C(0x88fcf317, f22241e2), 588, 196},
    118         {UINT64_2PART_C(0xcc20ce9b, d35c78a5), 614, 204},
    119         {UINT64_2PART_C(0x98165af3, 7b2153df), 641, 212},
    120         {UINT64_2PART_C(0xe2a0b5dc, 971f303a), 667, 220},
    121         {UINT64_2PART_C(0xa8d9d153, 5ce3b396), 694, 228},
    122         {UINT64_2PART_C(0xfb9b7cd9, a4a7443c), 720, 236},
    123         {UINT64_2PART_C(0xbb764c4c, a7a44410), 747, 244},
    124         {UINT64_2PART_C(0x8bab8eef, b6409c1a), 774, 252},
    125         {UINT64_2PART_C(0xd01fef10, a657842c), 800, 260},
    126         {UINT64_2PART_C(0x9b10a4e5, e9913129), 827, 268},
    127         {UINT64_2PART_C(0xe7109bfb, a19c0c9d), 853, 276},
    128         {UINT64_2PART_C(0xac2820d9, 623bf429), 880, 284},
    129         {UINT64_2PART_C(0x80444b5e, 7aa7cf85), 907, 292},
    130         {UINT64_2PART_C(0xbf21e440, 03acdd2d), 933, 300},
    131         {UINT64_2PART_C(0x8e679c2f, 5e44ff8f), 960, 308},
    132         {UINT64_2PART_C(0xd433179d, 9c8cb841), 986, 316},
    133         {UINT64_2PART_C(0x9e19db92, b4e31ba9), 1013, 324},
    134         {UINT64_2PART_C(0xeb96bf6e, badf77d9), 1039, 332},
    135         {UINT64_2PART_C(0xaf87023b, 9bf0ee6b), 1066, 340},
    136     };
    137     constexpr static const int kCachedPowersLength { ARRAY_SIZE(kCachedPowers) };
    138     constexpr static const int kCachedPowersOffset { -kCachedPowers[0].decimal_exponent };
    139    
    140     const int PowersOfTenCache::kDecimalExponentDistance { kCachedPowers[1].decimal_exponent - kCachedPowers[0].decimal_exponent };
    141     const int PowersOfTenCache::kMinDecimalExponent { kCachedPowers[0].decimal_exponent };
    142     const int PowersOfTenCache::kMaxDecimalExponent { kCachedPowers[kCachedPowersLength - 1].decimal_exponent };
    143    
    144     void PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
    145                                                                 int min_exponent,
    146                                                                 int max_exponent,
    147                                                                 DiyFp* power,
    148                                                                 int* decimal_exponent) {
    149         UNUSED_PARAM(max_exponent);
    150         int kQ = DiyFp::kSignificandSize;
    151         double k = ceil((min_exponent + kQ - 1) * kD_1_LOG2_10);
    152         int foo = kCachedPowersOffset;
    153         int index =
    154         (foo + static_cast<int>(k) - 1) / kDecimalExponentDistance + 1;
    155         ASSERT(0 <= index && index < kCachedPowersLength);
    156         CachedPower cached_power = kCachedPowers[index];
    157         ASSERT(min_exponent <= cached_power.binary_exponent);
    158         ASSERT(cached_power.binary_exponent <= max_exponent);
    159         *decimal_exponent = cached_power.decimal_exponent;
    160         *power = DiyFp(cached_power.significand, cached_power.binary_exponent);
    161     }
    162    
    163    
    164     void PowersOfTenCache::GetCachedPowerForDecimalExponent(int requested_exponent,
    165                                                             DiyFp* power,
    166                                                             int* found_exponent) {
    167         ASSERT(kMinDecimalExponent <= requested_exponent);
    168         ASSERT(requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance);
    169         int index =
    170         (requested_exponent + kCachedPowersOffset) / kDecimalExponentDistance;
    171         CachedPower cached_power = kCachedPowers[index];
    172         *power = DiyFp(cached_power.significand, cached_power.binary_exponent);
    173         *found_exponent = cached_power.decimal_exponent;
    174         ASSERT(*found_exponent <= requested_exponent);
    175         ASSERT(requested_exponent < *found_exponent + kDecimalExponentDistance);
    176     }
    177    
     41struct CachedPower {
     42  uint64_t significand;
     43  int16_t binary_exponent;
     44  int16_t decimal_exponent;
     45};
     46
     47constexpr static const CachedPower kCachedPowers[] = {
     48  {UINT64_2PART_C(0xfa8fd5a0, 081c0288), -1220, -348},
     49  {UINT64_2PART_C(0xbaaee17f, a23ebf76), -1193, -340},
     50  {UINT64_2PART_C(0x8b16fb20, 3055ac76), -1166, -332},
     51  {UINT64_2PART_C(0xcf42894a, 5dce35ea), -1140, -324},
     52  {UINT64_2PART_C(0x9a6bb0aa, 55653b2d), -1113, -316},
     53  {UINT64_2PART_C(0xe61acf03, 3d1a45df), -1087, -308},
     54  {UINT64_2PART_C(0xab70fe17, c79ac6ca), -1060, -300},
     55  {UINT64_2PART_C(0xff77b1fc, bebcdc4f), -1034, -292},
     56  {UINT64_2PART_C(0xbe5691ef, 416bd60c), -1007, -284},
     57  {UINT64_2PART_C(0x8dd01fad, 907ffc3c), -980, -276},
     58  {UINT64_2PART_C(0xd3515c28, 31559a83), -954, -268},
     59  {UINT64_2PART_C(0x9d71ac8f, ada6c9b5), -927, -260},
     60  {UINT64_2PART_C(0xea9c2277, 23ee8bcb), -901, -252},
     61  {UINT64_2PART_C(0xaecc4991, 4078536d), -874, -244},
     62  {UINT64_2PART_C(0x823c1279, 5db6ce57), -847, -236},
     63  {UINT64_2PART_C(0xc2109436, 4dfb5637), -821, -228},
     64  {UINT64_2PART_C(0x9096ea6f, 3848984f), -794, -220},
     65  {UINT64_2PART_C(0xd77485cb, 25823ac7), -768, -212},
     66  {UINT64_2PART_C(0xa086cfcd, 97bf97f4), -741, -204},
     67  {UINT64_2PART_C(0xef340a98, 172aace5), -715, -196},
     68  {UINT64_2PART_C(0xb23867fb, 2a35b28e), -688, -188},
     69  {UINT64_2PART_C(0x84c8d4df, d2c63f3b), -661, -180},
     70  {UINT64_2PART_C(0xc5dd4427, 1ad3cdba), -635, -172},
     71  {UINT64_2PART_C(0x936b9fce, bb25c996), -608, -164},
     72  {UINT64_2PART_C(0xdbac6c24, 7d62a584), -582, -156},
     73  {UINT64_2PART_C(0xa3ab6658, 0d5fdaf6), -555, -148},
     74  {UINT64_2PART_C(0xf3e2f893, dec3f126), -529, -140},
     75  {UINT64_2PART_C(0xb5b5ada8, aaff80b8), -502, -132},
     76  {UINT64_2PART_C(0x87625f05, 6c7c4a8b), -475, -124},
     77  {UINT64_2PART_C(0xc9bcff60, 34c13053), -449, -116},
     78  {UINT64_2PART_C(0x964e858c, 91ba2655), -422, -108},
     79  {UINT64_2PART_C(0xdff97724, 70297ebd), -396, -100},
     80  {UINT64_2PART_C(0xa6dfbd9f, b8e5b88f), -369, -92},
     81  {UINT64_2PART_C(0xf8a95fcf, 88747d94), -343, -84},
     82  {UINT64_2PART_C(0xb9447093, 8fa89bcf), -316, -76},
     83  {UINT64_2PART_C(0x8a08f0f8, bf0f156b), -289, -68},
     84  {UINT64_2PART_C(0xcdb02555, 653131b6), -263, -60},
     85  {UINT64_2PART_C(0x993fe2c6, d07b7fac), -236, -52},
     86  {UINT64_2PART_C(0xe45c10c4, 2a2b3b06), -210, -44},
     87  {UINT64_2PART_C(0xaa242499, 697392d3), -183, -36},
     88  {UINT64_2PART_C(0xfd87b5f2, 8300ca0e), -157, -28},
     89  {UINT64_2PART_C(0xbce50864, 92111aeb), -130, -20},
     90  {UINT64_2PART_C(0x8cbccc09, 6f5088cc), -103, -12},
     91  {UINT64_2PART_C(0xd1b71758, e219652c), -77, -4},
     92  {UINT64_2PART_C(0x9c400000, 00000000), -50, 4},
     93  {UINT64_2PART_C(0xe8d4a510, 00000000), -24, 12},
     94  {UINT64_2PART_C(0xad78ebc5, ac620000), 3, 20},
     95  {UINT64_2PART_C(0x813f3978, f8940984), 30, 28},
     96  {UINT64_2PART_C(0xc097ce7b, c90715b3), 56, 36},
     97  {UINT64_2PART_C(0x8f7e32ce, 7bea5c70), 83, 44},
     98  {UINT64_2PART_C(0xd5d238a4, abe98068), 109, 52},
     99  {UINT64_2PART_C(0x9f4f2726, 179a2245), 136, 60},
     100  {UINT64_2PART_C(0xed63a231, d4c4fb27), 162, 68},
     101  {UINT64_2PART_C(0xb0de6538, 8cc8ada8), 189, 76},
     102  {UINT64_2PART_C(0x83c7088e, 1aab65db), 216, 84},
     103  {UINT64_2PART_C(0xc45d1df9, 42711d9a), 242, 92},
     104  {UINT64_2PART_C(0x924d692c, a61be758), 269, 100},
     105  {UINT64_2PART_C(0xda01ee64, 1a708dea), 295, 108},
     106  {UINT64_2PART_C(0xa26da399, 9aef774a), 322, 116},
     107  {UINT64_2PART_C(0xf209787b, b47d6b85), 348, 124},
     108  {UINT64_2PART_C(0xb454e4a1, 79dd1877), 375, 132},
     109  {UINT64_2PART_C(0x865b8692, 5b9bc5c2), 402, 140},
     110  {UINT64_2PART_C(0xc83553c5, c8965d3d), 428, 148},
     111  {UINT64_2PART_C(0x952ab45c, fa97a0b3), 455, 156},
     112  {UINT64_2PART_C(0xde469fbd, 99a05fe3), 481, 164},
     113  {UINT64_2PART_C(0xa59bc234, db398c25), 508, 172},
     114  {UINT64_2PART_C(0xf6c69a72, a3989f5c), 534, 180},
     115  {UINT64_2PART_C(0xb7dcbf53, 54e9bece), 561, 188},
     116  {UINT64_2PART_C(0x88fcf317, f22241e2), 588, 196},
     117  {UINT64_2PART_C(0xcc20ce9b, d35c78a5), 614, 204},
     118  {UINT64_2PART_C(0x98165af3, 7b2153df), 641, 212},
     119  {UINT64_2PART_C(0xe2a0b5dc, 971f303a), 667, 220},
     120  {UINT64_2PART_C(0xa8d9d153, 5ce3b396), 694, 228},
     121  {UINT64_2PART_C(0xfb9b7cd9, a4a7443c), 720, 236},
     122  {UINT64_2PART_C(0xbb764c4c, a7a44410), 747, 244},
     123  {UINT64_2PART_C(0x8bab8eef, b6409c1a), 774, 252},
     124  {UINT64_2PART_C(0xd01fef10, a657842c), 800, 260},
     125  {UINT64_2PART_C(0x9b10a4e5, e9913129), 827, 268},
     126  {UINT64_2PART_C(0xe7109bfb, a19c0c9d), 853, 276},
     127  {UINT64_2PART_C(0xac2820d9, 623bf429), 880, 284},
     128  {UINT64_2PART_C(0x80444b5e, 7aa7cf85), 907, 292},
     129  {UINT64_2PART_C(0xbf21e440, 03acdd2d), 933, 300},
     130  {UINT64_2PART_C(0x8e679c2f, 5e44ff8f), 960, 308},
     131  {UINT64_2PART_C(0xd433179d, 9c8cb841), 986, 316},
     132  {UINT64_2PART_C(0x9e19db92, b4e31ba9), 1013, 324},
     133  {UINT64_2PART_C(0xeb96bf6e, badf77d9), 1039, 332},
     134  {UINT64_2PART_C(0xaf87023b, 9bf0ee6b), 1066, 340},
     135};
     136
     137constexpr static const int kCachedPowersOffset = 348;  // -1 * the first decimal_exponent.
     138constexpr static const double kD_1_LOG2_10 = 0.30102999566398114;  //  1 / lg(10)
     139// Difference between the decimal exponents in the table above.
     140const int PowersOfTenCache::kDecimalExponentDistance = 8;
     141const int PowersOfTenCache::kMinDecimalExponent = -348;
     142const int PowersOfTenCache::kMaxDecimalExponent = 340;
     143
     144void PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
     145    int min_exponent,
     146    int max_exponent,
     147    DiyFp* power,
     148    int* decimal_exponent) {
     149  int kQ = DiyFp::kSignificandSize;
     150  double k = ceil((min_exponent + kQ - 1) * kD_1_LOG2_10);
     151  int foo = kCachedPowersOffset;
     152  int index =
     153      (foo + static_cast<int>(k) - 1) / kDecimalExponentDistance + 1;
     154  ASSERT(0 <= index && index < static_cast<int>(ARRAY_SIZE(kCachedPowers)));
     155  CachedPower cached_power = kCachedPowers[index];
     156  ASSERT(min_exponent <= cached_power.binary_exponent);
     157  (void) max_exponent;  // Mark variable as used.
     158  ASSERT(cached_power.binary_exponent <= max_exponent);
     159  *decimal_exponent = cached_power.decimal_exponent;
     160  *power = DiyFp(cached_power.significand, cached_power.binary_exponent);
     161}
     162
     163
     164void PowersOfTenCache::GetCachedPowerForDecimalExponent(int requested_exponent,
     165                                                        DiyFp* power,
     166                                                        int* found_exponent) {
     167  ASSERT(kMinDecimalExponent <= requested_exponent);
     168  ASSERT(requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance);
     169  int index =
     170      (requested_exponent + kCachedPowersOffset) / kDecimalExponentDistance;
     171  CachedPower cached_power = kCachedPowers[index];
     172  *power = DiyFp(cached_power.significand, cached_power.binary_exponent);
     173  *found_exponent = cached_power.decimal_exponent;
     174  ASSERT(*found_exponent <= requested_exponent);
     175  ASSERT(requested_exponent < *found_exponent + kDecimalExponentDistance);
     176}
     177
    178178}  // namespace double_conversion
    179 
    180 } // namespace WTF
     179}  // namespace WTF
  • trunk/Source/WTF/wtf/dtoa/cached-powers.h

    r219124 r242048  
    2929#define DOUBLE_CONVERSION_CACHED_POWERS_H_
    3030
    31 #include "diy-fp.h"
     31#include <wtf/dtoa/diy-fp.h>
    3232
    3333namespace WTF {
     34namespace double_conversion {
    3435
    35 namespace double_conversion {
    36    
    37     class PowersOfTenCache {
    38     public:
    39        
    40         // Not all powers of ten are cached. The decimal exponent of two neighboring
    41         // cached numbers will differ by kDecimalExponentDistance.
    42         static const int kDecimalExponentDistance;
    43        
    44         static const int kMinDecimalExponent;
    45         static const int kMaxDecimalExponent;
    46        
    47         // Returns a cached power-of-ten with a binary exponent in the range
    48         // [min_exponent; max_exponent] (boundaries included).
    49         static void GetCachedPowerForBinaryExponentRange(int min_exponent,
    50                                                          int max_exponent,
    51                                                          DiyFp* power,
    52                                                          int* decimal_exponent);
    53        
    54         // Returns a cached power of ten x ~= 10^k such that
    55         //   k <= decimal_exponent < k + kCachedPowersDecimalDistance.
    56         // The given decimal_exponent must satisfy
    57         //   kMinDecimalExponent <= requested_exponent, and
    58         //   requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance.
    59         static void GetCachedPowerForDecimalExponent(int requested_exponent,
    60                                                      DiyFp* power,
    61                                                      int* found_exponent);
    62     };
    63    
     36class PowersOfTenCache {
     37 public:
     38
     39  // Not all powers of ten are cached. The decimal exponent of two neighboring
     40  // cached numbers will differ by kDecimalExponentDistance.
     41  static const int kDecimalExponentDistance;
     42
     43  static const int kMinDecimalExponent;
     44  static const int kMaxDecimalExponent;
     45
     46  // Returns a cached power-of-ten with a binary exponent in the range
     47  // [min_exponent; max_exponent] (boundaries included).
     48  static void GetCachedPowerForBinaryExponentRange(int min_exponent,
     49                                                   int max_exponent,
     50                                                   DiyFp* power,
     51                                                   int* decimal_exponent);
     52
     53  // Returns a cached power of ten x ~= 10^k such that
     54  //   k <= decimal_exponent < k + kCachedPowersDecimalDistance.
     55  // The given decimal_exponent must satisfy
     56  //   kMinDecimalExponent <= requested_exponent, and
     57  //   requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance.
     58  static void GetCachedPowerForDecimalExponent(int requested_exponent,
     59                                               DiyFp* power,
     60                                               int* found_exponent);
     61};
     62
    6463}  // namespace double_conversion
    65 
    66 } // namespace WTF
     64}  // namespace WTF
    6765
    6866#endif  // DOUBLE_CONVERSION_CACHED_POWERS_H_
  • trunk/Source/WTF/wtf/dtoa/diy-fp.cc

    r111778 r242048  
    2828#include "config.h"
    2929
    30 #include "diy-fp.h"
    31 #include "utils.h"
     30#include <wtf/dtoa/diy-fp.h>
     31#include <wtf/dtoa/utils.h>
    3232
    3333namespace WTF {
     34namespace double_conversion {
    3435
    35 namespace double_conversion {
    36    
    37     void DiyFp::Multiply(const DiyFp& other) {
    38         // Simply "emulates" a 128 bit multiplication.
    39         // However: the resulting number only contains 64 bits. The least
    40         // significant 64 bits are only used for rounding the most significant 64
    41         // bits.
    42         const uint64_t kM32 = 0xFFFFFFFFU;
    43         uint64_t a = f_ >> 32;
    44         uint64_t b = f_ & kM32;
    45         uint64_t c = other.f_ >> 32;
    46         uint64_t d = other.f_ & kM32;
    47         uint64_t ac = a * c;
    48         uint64_t bc = b * c;
    49         uint64_t ad = a * d;
    50         uint64_t bd = b * d;
    51         uint64_t tmp = (bd >> 32) + (ad & kM32) + (bc & kM32);
    52         // By adding 1U << 31 to tmp we round the final result.
    53         // Halfway cases will be round up.
    54         tmp += 1U << 31;
    55         uint64_t result_f = ac + (ad >> 32) + (bc >> 32) + (tmp >> 32);
    56         e_ += other.e_ + 64;
    57         f_ = result_f;
    58     }
    59    
     36void DiyFp::Multiply(const DiyFp& other) {
     37  // Simply "emulates" a 128 bit multiplication.
     38  // However: the resulting number only contains 64 bits. The least
     39  // significant 64 bits are only used for rounding the most significant 64
     40  // bits.
     41  const uint64_t kM32 = 0xFFFFFFFFU;
     42  uint64_t a = f_ >> 32;
     43  uint64_t b = f_ & kM32;
     44  uint64_t c = other.f_ >> 32;
     45  uint64_t d = other.f_ & kM32;
     46  uint64_t ac = a * c;
     47  uint64_t bc = b * c;
     48  uint64_t ad = a * d;
     49  uint64_t bd = b * d;
     50  uint64_t tmp = (bd >> 32) + (ad & kM32) + (bc & kM32);
     51  // By adding 1U << 31 to tmp we round the final result.
     52  // Halfway cases will be round up.
     53  tmp += 1U << 31;
     54  uint64_t result_f = ac + (ad >> 32) + (bc >> 32) + (tmp >> 32);
     55  e_ += other.e_ + 64;
     56  f_ = result_f;
     57}
     58
    6059}  // namespace double_conversion
    61 
    62 } // namespace WTF
     60}  // namespace WTF
  • trunk/Source/WTF/wtf/dtoa/diy-fp.h

    r111778 r242048  
    2929#define DOUBLE_CONVERSION_DIY_FP_H_
    3030
    31 #include "utils.h"
     31#include <wtf/dtoa/utils.h>
    3232
    3333namespace WTF {
     34namespace double_conversion {
    3435
    35 namespace double_conversion {
    36    
    37     // This "Do It Yourself Floating Point" class implements a floating-point number
    38     // with a uint64 significand and an int exponent. Normalized DiyFp numbers will
    39     // have the most significant bit of the significand set.
    40     // Multiplication and Subtraction do not normalize their results.
    41     // DiyFp are not designed to contain special doubles (NaN and Infinity).
    42     class DiyFp {
    43     public:
    44         static const int kSignificandSize = 64;
    45        
    46         DiyFp() : f_(0), e_(0) {}
    47         DiyFp(uint64_t f, int e) : f_(f), e_(e) {}
    48        
    49         // this = this - other.
    50         // The exponents of both numbers must be the same and the significand of this
    51         // must be bigger than the significand of other.
    52         // The result will not be normalized.
    53         void Subtract(const DiyFp& other) {
    54             ASSERT(e_ == other.e_);
    55             ASSERT(f_ >= other.f_);
    56             f_ -= other.f_;
    57         }
    58        
    59         // Returns a - b.
    60         // The exponents of both numbers must be the same and this must be bigger
    61         // than other. The result will not be normalized.
    62         static DiyFp Minus(const DiyFp& a, const DiyFp& b) {
    63             DiyFp result = a;
    64             result.Subtract(b);
    65             return result;
    66         }
    67        
    68        
    69         // this = this * other.
    70         void Multiply(const DiyFp& other);
    71        
    72         // returns a * b;
    73         static DiyFp Times(const DiyFp& a, const DiyFp& b) {
    74             DiyFp result = a;
    75             result.Multiply(b);
    76             return result;
    77         }
    78        
    79         void Normalize() {
    80             ASSERT(f_ != 0);
    81             uint64_t f = f_;
    82             int e = e_;
    83            
    84             // This method is mainly called for normalizing boundaries. In general
    85             // boundaries need to be shifted by 10 bits. We thus optimize for this case.
    86             const uint64_t k10MSBits = UINT64_2PART_C(0xFFC00000, 00000000);
    87             while ((f & k10MSBits) == 0) {
    88                 f <<= 10;
    89                 e -= 10;
    90             }
    91             while ((f & kUint64MSB) == 0) {
    92                 f <<= 1;
    93                 e--;
    94             }
    95             f_ = f;
    96             e_ = e;
    97         }
    98        
    99         static DiyFp Normalize(const DiyFp& a) {
    100             DiyFp result = a;
    101             result.Normalize();
    102             return result;
    103         }
    104        
    105         uint64_t f() const { return f_; }
    106         int e() const { return e_; }
    107        
    108         void set_f(uint64_t new_value) { f_ = new_value; }
    109         void set_e(int new_value) { e_ = new_value; }
    110        
    111     private:
    112         static const uint64_t kUint64MSB = UINT64_2PART_C(0x80000000, 00000000);
    113        
    114         uint64_t f_;
    115         int e_;
    116     };
    117    
     36// This "Do It Yourself Floating Point" class implements a floating-point number
     37// with a uint64 significand and an int exponent. Normalized DiyFp numbers will
     38// have the most significant bit of the significand set.
     39// Multiplication and Subtraction do not normalize their results.
     40// DiyFp are not designed to contain special doubles (NaN and Infinity).
     41class DiyFp {
     42 public:
     43  static const int kSignificandSize = 64;
     44
     45  DiyFp() : f_(0), e_(0) {}
     46  DiyFp(uint64_t significand, int exponent) : f_(significand), e_(exponent) {}
     47
     48  // this = this - other.
     49  // The exponents of both numbers must be the same and the significand of this
     50  // must be bigger than the significand of other.
     51  // The result will not be normalized.
     52  void Subtract(const DiyFp& other) {
     53    ASSERT(e_ == other.e_);
     54    ASSERT(f_ >= other.f_);
     55    f_ -= other.f_;
     56  }
     57
     58  // Returns a - b.
     59  // The exponents of both numbers must be the same and this must be bigger
     60  // than other. The result will not be normalized.
     61  static DiyFp Minus(const DiyFp& a, const DiyFp& b) {
     62    DiyFp result = a;
     63    result.Subtract(b);
     64    return result;
     65  }
     66
     67
     68  // this = this * other.
     69  void Multiply(const DiyFp& other);
     70
     71  // returns a * b;
     72  static DiyFp Times(const DiyFp& a, const DiyFp& b) {
     73    DiyFp result = a;
     74    result.Multiply(b);
     75    return result;
     76  }
     77
     78  void Normalize() {
     79    ASSERT(f_ != 0);
     80    uint64_t significand = f_;
     81    int exponent = e_;
     82
     83    // This method is mainly called for normalizing boundaries. In general
     84    // boundaries need to be shifted by 10 bits. We thus optimize for this case.
     85    const uint64_t k10MSBits = UINT64_2PART_C(0xFFC00000, 00000000);
     86    while ((significand & k10MSBits) == 0) {
     87      significand <<= 10;
     88      exponent -= 10;
     89    }
     90    while ((significand & kUint64MSB) == 0) {
     91      significand <<= 1;
     92      exponent--;
     93    }
     94    f_ = significand;
     95    e_ = exponent;
     96  }
     97
     98  static DiyFp Normalize(const DiyFp& a) {
     99    DiyFp result = a;
     100    result.Normalize();
     101    return result;
     102  }
     103
     104  uint64_t f() const { return f_; }
     105  int e() const { return e_; }
     106
     107  void set_f(uint64_t new_value) { f_ = new_value; }
     108  void set_e(int new_value) { e_ = new_value; }
     109
     110 private:
     111  static const uint64_t kUint64MSB = UINT64_2PART_C(0x80000000, 00000000);
     112
     113  uint64_t f_;
     114  int e_;
     115};
     116
    118117}  // namespace double_conversion
    119 
    120 } // namespace WTF
     118}  // namespace WTF
    121119
    122120#endif  // DOUBLE_CONVERSION_DIY_FP_H_
  • trunk/Source/WTF/wtf/dtoa/double-conversion.cc

    r209399 r242048  
    2727
    2828#include "config.h"
    29 #include "double-conversion.h"
    30 
    31 #include "bignum-dtoa.h"
    32 #include "double.h"
    33 #include "fast-dtoa.h"
    34 #include "fixed-dtoa.h"
    35 #include "strtod.h"
    36 #include "utils.h"
    37 #include <limits.h>
    38 #include <math.h>
     29
     30#include <climits>
     31#include <locale>
     32#include <cmath>
     33
     34#include <wtf/dtoa/double-conversion.h>
     35
     36#include <wtf/dtoa/bignum-dtoa.h>
     37#include <wtf/dtoa/fast-dtoa.h>
     38#include <wtf/dtoa/fixed-dtoa.h>
     39#include <wtf/dtoa/ieee.h>
     40#include <wtf/dtoa/strtod.h>
     41#include <wtf/dtoa/utils.h>
     42
    3943#include <wtf/ASCIICType.h>
    4044
    4145namespace WTF {
    42 
    4346namespace double_conversion {
    44    
    45     const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverter() {
    46         int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN;
    47         static DoubleToStringConverter converter(flags,
    48                                                  "Infinity",
    49                                                  "NaN",
    50                                                  'e',
    51                                                  -6, 21,
    52                                                  6, 0);
    53         return converter;
    54     }
    55    
    56    
    57     bool DoubleToStringConverter::HandleSpecialValues(
    58                                                       double value,
    59                                                       StringBuilder* result_builder) const {
    60         Double double_inspect(value);
    61         if (double_inspect.IsInfinite()) {
    62             if (infinity_symbol_ == NULL) return false;
    63             if (value < 0) {
    64                 result_builder->AddCharacter('-');
    65             }
    66             result_builder->AddString(infinity_symbol_);
    67             return true;
     47
     48const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverter() {
     49  int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN;
     50  static DoubleToStringConverter converter(flags,
     51                                           "Infinity",
     52                                           "NaN",
     53                                           'e',
     54                                           -6, 21,
     55                                           6, 0);
     56  return converter;
     57}
     58
     59
     60bool DoubleToStringConverter::HandleSpecialValues(
     61    double value,
     62    StringBuilder* result_builder) const {
     63  Double double_inspect(value);
     64  if (double_inspect.IsInfinite()) {
     65    if (infinity_symbol_ == NULL) return false;
     66    if (value < 0) {
     67      result_builder->AddCharacter('-');
     68    }
     69    result_builder->AddString(infinity_symbol_);
     70    return true;
     71  }
     72  if (double_inspect.IsNan()) {
     73    if (nan_symbol_ == NULL) return false;
     74    result_builder->AddString(nan_symbol_);
     75    return true;
     76  }
     77  return false;
     78}
     79
     80
     81void DoubleToStringConverter::CreateExponentialRepresentation(
     82    const char* decimal_digits,
     83    int length,
     84    int exponent,
     85    StringBuilder* result_builder) const {
     86  ASSERT(length != 0);
     87  result_builder->AddCharacter(decimal_digits[0]);
     88  if (length != 1) {
     89    result_builder->AddCharacter('.');
     90    result_builder->AddSubstring(&decimal_digits[1], length-1);
     91  }
     92  result_builder->AddCharacter(exponent_character_);
     93  if (exponent < 0) {
     94    result_builder->AddCharacter('-');
     95    exponent = -exponent;
     96  } else {
     97    if ((flags_ & EMIT_POSITIVE_EXPONENT_SIGN) != 0) {
     98      result_builder->AddCharacter('+');
     99    }
     100  }
     101  if (exponent == 0) {
     102    result_builder->AddCharacter('0');
     103    return;
     104  }
     105  ASSERT(exponent < 1e4);
     106  const int kMaxExponentLength = 5;
     107  char buffer[kMaxExponentLength + 1];
     108  buffer[kMaxExponentLength] = '\0';
     109  int first_char_pos = kMaxExponentLength;
     110  while (exponent > 0) {
     111    buffer[--first_char_pos] = '0' + (exponent % 10);
     112    exponent /= 10;
     113  }
     114  result_builder->AddSubstring(&buffer[first_char_pos],
     115                               kMaxExponentLength - first_char_pos);
     116}
     117
     118
     119void DoubleToStringConverter::CreateDecimalRepresentation(
     120    const char* decimal_digits,
     121    int length,
     122    int decimal_point,
     123    int digits_after_point,
     124    StringBuilder* result_builder) const {
     125  // Create a representation that is padded with zeros if needed.
     126  if (decimal_point <= 0) {
     127      // "0.00000decimal_rep" or "0.000decimal_rep00".
     128    result_builder->AddCharacter('0');
     129    if (digits_after_point > 0) {
     130      result_builder->AddCharacter('.');
     131      result_builder->AddPadding('0', -decimal_point);
     132      ASSERT(length <= digits_after_point - (-decimal_point));
     133      result_builder->AddSubstring(decimal_digits, length);
     134      int remaining_digits = digits_after_point - (-decimal_point) - length;
     135      result_builder->AddPadding('0', remaining_digits);
     136    }
     137  } else if (decimal_point >= length) {
     138    // "decimal_rep0000.00000" or "decimal_rep.0000".
     139    result_builder->AddSubstring(decimal_digits, length);
     140    result_builder->AddPadding('0', decimal_point - length);
     141    if (digits_after_point > 0) {
     142      result_builder->AddCharacter('.');
     143      result_builder->AddPadding('0', digits_after_point);
     144    }
     145  } else {
     146    // "decima.l_rep000".
     147    ASSERT(digits_after_point > 0);
     148    result_builder->AddSubstring(decimal_digits, decimal_point);
     149    result_builder->AddCharacter('.');
     150    ASSERT(length - decimal_point <= digits_after_point);
     151    result_builder->AddSubstring(&decimal_digits[decimal_point],
     152                                 length - decimal_point);
     153    int remaining_digits = digits_after_point - (length - decimal_point);
     154    result_builder->AddPadding('0', remaining_digits);
     155  }
     156  if (digits_after_point == 0) {
     157    if ((flags_ & EMIT_TRAILING_DECIMAL_POINT) != 0) {
     158      result_builder->AddCharacter('.');
     159    }
     160    if ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) {
     161      result_builder->AddCharacter('0');
     162    }
     163  }
     164}
     165
     166
     167bool DoubleToStringConverter::ToShortestIeeeNumber(
     168    double value,
     169    StringBuilder* result_builder,
     170    DoubleToStringConverter::DtoaMode mode) const {
     171  ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE);
     172  if (Double(value).IsSpecial()) {
     173    return HandleSpecialValues(value, result_builder);
     174  }
     175
     176  int decimal_point;
     177  bool sign;
     178  const int kDecimalRepCapacity = kBase10MaximalLength + 1;
     179  char decimal_rep[kDecimalRepCapacity];
     180  int decimal_rep_length;
     181
     182  DoubleToAscii(value, mode, 0, decimal_rep, kDecimalRepCapacity,
     183                &sign, &decimal_rep_length, &decimal_point);
     184
     185  bool unique_zero = (flags_ & UNIQUE_ZERO) != 0;
     186  if (sign && (value != 0.0 || !unique_zero)) {
     187    result_builder->AddCharacter('-');
     188  }
     189
     190  int exponent = decimal_point - 1;
     191  if ((decimal_in_shortest_low_ <= exponent) &&
     192      (exponent < decimal_in_shortest_high_)) {
     193    CreateDecimalRepresentation(decimal_rep, decimal_rep_length,
     194                                decimal_point,
     195                                Max(0, decimal_rep_length - decimal_point),
     196                                result_builder);
     197  } else {
     198    CreateExponentialRepresentation(decimal_rep, decimal_rep_length, exponent,
     199                                    result_builder);
     200  }
     201  return true;
     202}
     203
     204
     205bool DoubleToStringConverter::ToFixed(double value,
     206                                      int requested_digits,
     207                                      StringBuilder* result_builder) const {
     208  ASSERT(kMaxFixedDigitsBeforePoint == 60);
     209  const double kFirstNonFixed = 1e60;
     210
     211  if (Double(value).IsSpecial()) {
     212    return HandleSpecialValues(value, result_builder);
     213  }
     214
     215  if (requested_digits > kMaxFixedDigitsAfterPoint) return false;
     216  if (value >= kFirstNonFixed || value <= -kFirstNonFixed) return false;
     217
     218  // Find a sufficiently precise decimal representation of n.
     219  int decimal_point;
     220  bool sign;
     221  // Add space for the '\0' byte.
     222  const int kDecimalRepCapacity =
     223      kMaxFixedDigitsBeforePoint + kMaxFixedDigitsAfterPoint + 1;
     224  char decimal_rep[kDecimalRepCapacity];
     225  int decimal_rep_length;
     226  DoubleToAscii(value, FIXED, requested_digits,
     227                decimal_rep, kDecimalRepCapacity,
     228                &sign, &decimal_rep_length, &decimal_point);
     229
     230  bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
     231  if (sign && (value != 0.0 || !unique_zero)) {
     232    result_builder->AddCharacter('-');
     233  }
     234
     235  CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
     236                              requested_digits, result_builder);
     237  return true;
     238}
     239
     240
     241bool DoubleToStringConverter::ToExponential(
     242    double value,
     243    int requested_digits,
     244    StringBuilder* result_builder) const {
     245  if (Double(value).IsSpecial()) {
     246    return HandleSpecialValues(value, result_builder);
     247  }
     248
     249  if (requested_digits < -1) return false;
     250  if (requested_digits > kMaxExponentialDigits) return false;
     251
     252  int decimal_point;
     253  bool sign;
     254  // Add space for digit before the decimal point and the '\0' character.
     255  const int kDecimalRepCapacity = kMaxExponentialDigits + 2;
     256  ASSERT(kDecimalRepCapacity > kBase10MaximalLength);
     257  char decimal_rep[kDecimalRepCapacity];
     258  int decimal_rep_length;
     259
     260  if (requested_digits == -1) {
     261    DoubleToAscii(value, SHORTEST, 0,
     262                  decimal_rep, kDecimalRepCapacity,
     263                  &sign, &decimal_rep_length, &decimal_point);
     264  } else {
     265    DoubleToAscii(value, PRECISION, requested_digits + 1,
     266                  decimal_rep, kDecimalRepCapacity,
     267                  &sign, &decimal_rep_length, &decimal_point);
     268    ASSERT(decimal_rep_length <= requested_digits + 1);
     269
     270    for (int i = decimal_rep_length; i < requested_digits + 1; ++i) {
     271      decimal_rep[i] = '0';
     272    }
     273    decimal_rep_length = requested_digits + 1;
     274  }
     275
     276  bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
     277  if (sign && (value != 0.0 || !unique_zero)) {
     278    result_builder->AddCharacter('-');
     279  }
     280
     281  int exponent = decimal_point - 1;
     282  CreateExponentialRepresentation(decimal_rep,
     283                                  decimal_rep_length,
     284                                  exponent,
     285                                  result_builder);
     286  return true;
     287}
     288
     289
     290bool DoubleToStringConverter::ToPrecision(double value,
     291                                          int precision,
     292                                          StringBuilder* result_builder) const {
     293  if (Double(value).IsSpecial()) {
     294    return HandleSpecialValues(value, result_builder);
     295  }
     296
     297  if (precision < kMinPrecisionDigits || precision > kMaxPrecisionDigits) {
     298    return false;
     299  }
     300
     301  // Find a sufficiently precise decimal representation of n.
     302  int decimal_point;
     303  bool sign;
     304  // Add one for the terminating null character.
     305  const int kDecimalRepCapacity = kMaxPrecisionDigits + 1;
     306  char decimal_rep[kDecimalRepCapacity];
     307  int decimal_rep_length;
     308
     309  DoubleToAscii(value, PRECISION, precision,
     310                decimal_rep, kDecimalRepCapacity,
     311                &sign, &decimal_rep_length, &decimal_point);
     312  ASSERT(decimal_rep_length <= precision);
     313
     314  bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
     315  if (sign && (value != 0.0 || !unique_zero)) {
     316    result_builder->AddCharacter('-');
     317  }
     318
     319  // The exponent if we print the number as x.xxeyyy. That is with the
     320  // decimal point after the first digit.
     321  int exponent = decimal_point - 1;
     322
     323  int extra_zero = ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) ? 1 : 0;
     324  if ((-decimal_point + 1 > max_leading_padding_zeroes_in_precision_mode_) ||
     325      (decimal_point - precision + extra_zero >
     326       max_trailing_padding_zeroes_in_precision_mode_)) {
     327    // Fill buffer to contain 'precision' digits.
     328    // Usually the buffer is already at the correct length, but 'DoubleToAscii'
     329    // is allowed to return less characters.
     330    for (int i = decimal_rep_length; i < precision; ++i) {
     331      decimal_rep[i] = '0';
     332    }
     333
     334    CreateExponentialRepresentation(decimal_rep,
     335                                    precision,
     336                                    exponent,
     337                                    result_builder);
     338  } else {
     339    CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
     340                                Max(0, precision - decimal_point),
     341                                result_builder);
     342  }
     343  return true;
     344}
     345
     346
     347static BignumDtoaMode DtoaToBignumDtoaMode(
     348    DoubleToStringConverter::DtoaMode dtoa_mode) {
     349  switch (dtoa_mode) {
     350    case DoubleToStringConverter::SHORTEST:  return BIGNUM_DTOA_SHORTEST;
     351    case DoubleToStringConverter::SHORTEST_SINGLE:
     352        return BIGNUM_DTOA_SHORTEST_SINGLE;
     353    case DoubleToStringConverter::FIXED:     return BIGNUM_DTOA_FIXED;
     354    case DoubleToStringConverter::PRECISION: return BIGNUM_DTOA_PRECISION;
     355    default:
     356      UNREACHABLE();
     357  }
     358}
     359
     360
     361void DoubleToStringConverter::DoubleToAscii(double v,
     362                                            DtoaMode mode,
     363                                            int requested_digits,
     364                                            char* buffer,
     365                                            int buffer_length,
     366                                            bool* sign,
     367                                            int* length,
     368                                            int* point) {
     369  BufferReference<char> bufferReference(buffer, buffer_length);
     370  ASSERT(!Double(v).IsSpecial());
     371  ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE || requested_digits >= 0);
     372
     373  if (Double(v).Sign() < 0) {
     374    *sign = true;
     375    v = -v;
     376  } else {
     377    *sign = false;
     378  }
     379
     380  if (mode == PRECISION && requested_digits == 0) {
     381    bufferReference[0] = '\0';
     382    *length = 0;
     383    return;
     384  }
     385
     386  if (v == 0) {
     387    bufferReference[0] = '0';
     388    bufferReference[1] = '\0';
     389    *length = 1;
     390    *point = 1;
     391    return;
     392  }
     393
     394  bool fast_worked;
     395  switch (mode) {
     396    case SHORTEST:
     397      fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, bufferReference, length, point);
     398      break;
     399    case SHORTEST_SINGLE:
     400      fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST_SINGLE, 0,
     401                             bufferReference, length, point);
     402      break;
     403    case FIXED:
     404      fast_worked = FastFixedDtoa(v, requested_digits, bufferReference, length, point);
     405      break;
     406    case PRECISION:
     407      fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits,
     408                             bufferReference, length, point);
     409      break;
     410    default:
     411      fast_worked = false;
     412      UNREACHABLE();
     413  }
     414  if (fast_worked) return;
     415
     416  // If the fast dtoa didn't succeed use the slower bignum version.
     417  BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
     418  BignumDtoa(v, bignum_mode, requested_digits, bufferReference, length, point);
     419  bufferReference[*length] = '\0';
     420}
     421
     422// Maximum number of significant digits in decimal representation.
     423// The longest possible double in decimal representation is
     424// (2^53 - 1) * 2 ^ -1074 that is (2 ^ 53 - 1) * 5 ^ 1074 / 10 ^ 1074
     425// (768 digits). If we parse a number whose first digits are equal to a
     426// mean of 2 adjacent doubles (that could have up to 769 digits) the result
     427// must be rounded to the bigger one unless the tail consists of zeros, so
     428// we don't need to preserve all the digits.
     429const int kMaxSignificantDigits = 772;
     430
     431
     432static double SignedZero(bool sign) {
     433  return sign ? -0.0 : 0.0;
     434}
     435
     436
     437// Returns true, when the iterator is equal to end.
     438template<class Iterator>
     439static inline bool Advance(Iterator* it, Iterator& end) {
     440  ++(*it);
     441  return *it == end;
     442}
     443
     444template <typename FloatingPointType>
     445inline FloatingPointType StringToFloatingPointType(BufferReference<const char> buffer, int exponent);
     446
     447template <>
     448inline double StringToFloatingPointType<double>(BufferReference<const char> buffer, int exponent) {
     449  return Strtod(buffer, exponent);
     450}
     451
     452template <>
     453inline float StringToFloatingPointType<float>(BufferReference<const char> buffer, int exponent) {
     454  return Strtof(buffer, exponent);
     455}
     456
     457template <typename FloatingPointType, class Iterator>
     458static FloatingPointType StringToIeee(
     459    Iterator input,
     460    size_t length,
     461    size_t* processed_characters_count) {
     462  static_assert(std::is_floating_point<FloatingPointType>::value, "Only floating point types are allowed.");
     463
     464  Iterator current = input;
     465  Iterator end = input + length;
     466
     467  *processed_characters_count = 0;
     468
     469  // To make sure that iterator dereferencing is valid the following
     470  // convention is used:
     471  // 1. Each '++current' statement is followed by check for equality to 'end'.
     472  // 3. If 'current' becomes equal to 'end' the function returns or goes to
     473  // 'parsing_done'.
     474  // 4. 'current' is not dereferenced after the 'parsing_done' label.
     475  // 5. Code before 'parsing_done' may rely on 'current != end'.
     476
     477  if (current == end) return 0.0;
     478
     479  // The longest form of simplified number is: "-<significant digits>.1eXXX\0".
     480  const int kBufferSize = kMaxSignificantDigits + 10;
     481  char buffer[kBufferSize];  // NOLINT: size is known at compile time.
     482  int buffer_pos = 0;
     483
     484  // Exponent will be adjusted if insignificant digits of the integer part
     485  // or insignificant leading zeros of the fractional part are dropped.
     486  int exponent = 0;
     487  int significant_digits = 0;
     488  int insignificant_digits = 0;
     489  bool nonzero_digit_dropped = false;
     490
     491  bool sign = false;
     492
     493  if (*current == '+' || *current == '-') {
     494    sign = (*current == '-');
     495    ++current;
     496    if (current == end) return 0.0;
     497  }
     498
     499  bool leading_zero = false;
     500  if (*current == '0') {
     501    if (Advance(&current, end)) {
     502      *processed_characters_count = static_cast<size_t>(current - input);
     503      return SignedZero(sign);
     504    }
     505
     506    leading_zero = true;
     507
     508    // Ignore leading zeros in the integer part.
     509    while (*current == '0') {
     510      if (Advance(&current, end)) {
     511        *processed_characters_count = static_cast<size_t>(current - input);
     512        return SignedZero(sign);
     513      }
     514    }
     515  }
     516
     517  // Copy significant digits of the integer part (if any) to the buffer.
     518  while (isASCIIDigit(*current)) {
     519    if (significant_digits < kMaxSignificantDigits) {
     520      ASSERT(buffer_pos < kBufferSize);
     521      buffer[buffer_pos++] = static_cast<char>(*current);
     522      significant_digits++;
     523    } else {
     524      insignificant_digits++;  // Move the digit into the exponential part.
     525      nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
     526    }
     527    if (Advance(&current, end)) goto parsing_done;
     528  }
     529
     530  if (*current == '.') {
     531    if (Advance(&current, end)) {
     532      if (significant_digits == 0 && !leading_zero) {
     533        return 0.0;
     534      } else {
     535        goto parsing_done;
     536      }
     537    }
     538
     539    if (significant_digits == 0) {
     540      // Integer part consists of 0 or is absent. Significant digits start after
     541      // leading zeros (if any).
     542      while (*current == '0') {
     543        if (Advance(&current, end)) {
     544          *processed_characters_count = static_cast<size_t>(current - input);
     545          return SignedZero(sign);
    68546        }
    69         if (double_inspect.IsNan()) {
    70             if (nan_symbol_ == NULL) return false;
    71             result_builder->AddString(nan_symbol_);
    72             return true;
    73         }
    74         return false;
    75     }
    76    
    77    
    78     void DoubleToStringConverter::CreateExponentialRepresentation(
    79                                                                   const char* decimal_digits,
    80                                                                   int length,
    81                                                                   int exponent,
    82                                                                   StringBuilder* result_builder) const {
    83         ASSERT(length != 0);
    84         result_builder->AddCharacter(decimal_digits[0]);
    85         if (length != 1) {
    86             result_builder->AddCharacter('.');
    87             result_builder->AddSubstring(&decimal_digits[1], length-1);
    88         }
    89         result_builder->AddCharacter(exponent_character_);
    90         if (exponent < 0) {
    91             result_builder->AddCharacter('-');
    92             exponent = -exponent;
    93         } else {
    94             if ((flags_ & EMIT_POSITIVE_EXPONENT_SIGN) != 0) {
    95                 result_builder->AddCharacter('+');
    96             }
    97         }
    98         if (exponent == 0) {
    99             result_builder->AddCharacter('0');
    100             return;
    101         }
    102         ASSERT(exponent < 1e4);
    103         const int kMaxExponentLength = 5;
    104         char buffer[kMaxExponentLength + 1];
    105         int first_char_pos = kMaxExponentLength;
    106         buffer[first_char_pos] = '\0';
    107         while (exponent > 0) {
    108             buffer[--first_char_pos] = '0' + (exponent % 10);
    109             exponent /= 10;
    110         }
    111         result_builder->AddSubstring(&buffer[first_char_pos],
    112                                      kMaxExponentLength - first_char_pos);
    113     }
    114    
    115    
    116     void DoubleToStringConverter::CreateDecimalRepresentation(
    117                                                               const char* decimal_digits,
    118                                                               int length,
    119                                                               int decimal_point,
    120                                                               int digits_after_point,
    121                                                               StringBuilder* result_builder) const {
    122         // Create a representation that is padded with zeros if needed.
    123         if (decimal_point <= 0) {
    124             // "0.00000decimal_rep".
    125             result_builder->AddCharacter('0');
    126             if (digits_after_point > 0) {
    127                 result_builder->AddCharacter('.');
    128                 result_builder->AddPadding('0', -decimal_point);
    129                 ASSERT(length <= digits_after_point - (-decimal_point));
    130                 result_builder->AddSubstring(decimal_digits, length);
    131                 int remaining_digits = digits_after_point - (-decimal_point) - length;
    132                 result_builder->AddPadding('0', remaining_digits);
    133             }
    134         } else if (decimal_point >= length) {
    135             // "decimal_rep0000.00000" or "decimal_rep.0000"
    136             result_builder->AddSubstring(decimal_digits, length);
    137             result_builder->AddPadding('0', decimal_point - length);
    138             if (digits_after_point > 0) {
    139                 result_builder->AddCharacter('.');
    140                 result_builder->AddPadding('0', digits_after_point);
    141             }
    142         } else {
    143             // "decima.l_rep000"
    144             ASSERT(digits_after_point > 0);
    145             result_builder->AddSubstring(decimal_digits, decimal_point);
    146             result_builder->AddCharacter('.');
    147             ASSERT(length - decimal_point <= digits_after_point);
    148             result_builder->AddSubstring(&decimal_digits[decimal_point],
    149                                          length - decimal_point);
    150             int remaining_digits = digits_after_point - (length - decimal_point);
    151             result_builder->AddPadding('0', remaining_digits);
    152         }
    153         if (digits_after_point == 0) {
    154             if ((flags_ & EMIT_TRAILING_DECIMAL_POINT) != 0) {
    155                 result_builder->AddCharacter('.');
    156             }
    157             if ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) {
    158                 result_builder->AddCharacter('0');
    159             }
    160         }
    161     }
    162    
    163    
    164     bool DoubleToStringConverter::ToShortest(double value,
    165                                              StringBuilder* result_builder) const {
    166         if (Double(value).IsSpecial()) {
    167             return HandleSpecialValues(value, result_builder);
    168         }
    169        
    170         int decimal_point;
    171         bool sign;
    172         const int kDecimalRepCapacity = kBase10MaximalLength + 1;
    173         char decimal_rep[kDecimalRepCapacity];
    174         int decimal_rep_length;
    175        
    176         DoubleToAscii(value, SHORTEST, 0, decimal_rep, kDecimalRepCapacity,
    177                       &sign, &decimal_rep_length, &decimal_point);
    178        
    179         bool unique_zero = (flags_ & UNIQUE_ZERO) != 0;
    180         if (sign && (value != 0.0 || !unique_zero)) {
    181             result_builder->AddCharacter('-');
    182         }
    183        
    184         int exponent = decimal_point - 1;
    185         if ((decimal_in_shortest_low_ <= exponent) &&
    186             (exponent < decimal_in_shortest_high_)) {
    187             CreateDecimalRepresentation(decimal_rep, decimal_rep_length,
    188                                         decimal_point,
    189                                         Max(0, decimal_rep_length - decimal_point),
    190                                         result_builder);
    191         } else {
    192             CreateExponentialRepresentation(decimal_rep, decimal_rep_length, exponent,
    193                                             result_builder);
    194         }
    195         return true;
    196     }
    197    
    198    
    199     bool DoubleToStringConverter::ToFixed(double value,
    200                                           int requested_digits,
    201                                           StringBuilder* result_builder) const {
    202         ASSERT(kMaxFixedDigitsBeforePoint == 60);
    203         const double kFirstNonFixed = 1e60;
    204        
    205         if (Double(value).IsSpecial()) {
    206             return HandleSpecialValues(value, result_builder);
    207         }
    208        
    209         if (requested_digits > kMaxFixedDigitsAfterPoint) return false;
    210         if (value >= kFirstNonFixed || value <= -kFirstNonFixed) return false;
    211        
    212         // Find a sufficiently precise decimal representation of n.
    213         int decimal_point;
    214         bool sign;
    215         // Add space for the '\0' byte.
    216         const int kDecimalRepCapacity =
    217         kMaxFixedDigitsBeforePoint + kMaxFixedDigitsAfterPoint + 1;
    218         char decimal_rep[kDecimalRepCapacity];
    219         int decimal_rep_length;
    220         DoubleToAscii(value, FIXED, requested_digits,
    221                       decimal_rep, kDecimalRepCapacity,
    222                       &sign, &decimal_rep_length, &decimal_point);
    223        
    224         bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
    225         if (sign && (value != 0.0 || !unique_zero)) {
    226             result_builder->AddCharacter('-');
    227         }
    228        
    229         CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
    230                                     requested_digits, result_builder);
    231         return true;
    232     }
    233    
    234    
    235     bool DoubleToStringConverter::ToExponential(
    236                                                 double value,
    237                                                 int requested_digits,
    238                                                 StringBuilder* result_builder) const {
    239         if (Double(value).IsSpecial()) {
    240             return HandleSpecialValues(value, result_builder);
    241         }
    242        
    243         if (requested_digits < -1) return false;
    244         if (requested_digits > kMaxExponentialDigits) return false;
    245        
    246         int decimal_point;
    247         bool sign;
    248         // Add space for digit before the decimal point and the '\0' character.
    249         const int kDecimalRepCapacity = kMaxExponentialDigits + 2;
    250         ASSERT(kDecimalRepCapacity > kBase10MaximalLength);
    251         char decimal_rep[kDecimalRepCapacity];
    252         int decimal_rep_length;
    253        
    254         if (requested_digits == -1) {
    255             DoubleToAscii(value, SHORTEST, 0,
    256                           decimal_rep, kDecimalRepCapacity,
    257                           &sign, &decimal_rep_length, &decimal_point);
    258         } else {
    259             DoubleToAscii(value, PRECISION, requested_digits + 1,
    260                           decimal_rep, kDecimalRepCapacity,
    261                           &sign, &decimal_rep_length, &decimal_point);
    262             ASSERT(decimal_rep_length <= requested_digits + 1);
    263            
    264             for (int i = decimal_rep_length; i < requested_digits + 1; ++i) {
    265                 decimal_rep[i] = '0';
    266             }
    267             decimal_rep_length = requested_digits + 1;
    268         }
    269        
    270         bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
    271         if (sign && (value != 0.0 || !unique_zero)) {
    272             result_builder->AddCharacter('-');
    273         }
    274        
    275         int exponent = decimal_point - 1;
    276         CreateExponentialRepresentation(decimal_rep,
    277                                         decimal_rep_length,
    278                                         exponent,
    279                                         result_builder);
    280         return true;
    281     }
    282    
    283    
    284     bool DoubleToStringConverter::ToPrecision(double value,
    285                                               int precision,
    286                                               StringBuilder* result_builder) const {
    287         if (Double(value).IsSpecial()) {
    288             return HandleSpecialValues(value, result_builder);
    289         }
    290        
    291         if (precision < kMinPrecisionDigits || precision > kMaxPrecisionDigits) {
    292             return false;
    293         }
    294        
    295         // Find a sufficiently precise decimal representation of n.
    296         int decimal_point;
    297         bool sign;
    298         // Add one for the terminating null character.
    299         const int kDecimalRepCapacity = kMaxPrecisionDigits + 1;
    300         char decimal_rep[kDecimalRepCapacity];
    301         int decimal_rep_length;
    302        
    303         DoubleToAscii(value, PRECISION, precision,
    304                       decimal_rep, kDecimalRepCapacity,
    305                       &sign, &decimal_rep_length, &decimal_point);
    306         ASSERT(decimal_rep_length <= precision);
    307        
    308         bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
    309         if (sign && (value != 0.0 || !unique_zero)) {
    310             result_builder->AddCharacter('-');
    311         }
    312        
    313         // The exponent if we print the number as x.xxeyyy. That is with the
    314         // decimal point after the first digit.
    315         int exponent = decimal_point - 1;
    316        
    317         int extra_zero = ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) ? 1 : 0;
    318         if ((-decimal_point + 1 > max_leading_padding_zeroes_in_precision_mode_) ||
    319             (decimal_point - precision + extra_zero >
    320              max_trailing_padding_zeroes_in_precision_mode_)) {
    321                 // Fill buffer to contain 'precision' digits.
    322                 // Usually the buffer is already at the correct length, but 'DoubleToAscii'
    323                 // is allowed to return less characters.
    324                 for (int i = decimal_rep_length; i < precision; ++i) {
    325                     decimal_rep[i] = '0';
    326                 }
    327                
    328                 CreateExponentialRepresentation(decimal_rep,
    329                                                 precision,
    330                                                 exponent,
    331                                                 result_builder);
    332             } else {
    333                 CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
    334                                             Max(0, precision - decimal_point),
    335                                             result_builder);
    336             }
    337         return true;
    338     }
    339    
    340    
    341     static BignumDtoaMode DtoaToBignumDtoaMode(
    342                                                DoubleToStringConverter::DtoaMode dtoa_mode) {
    343         switch (dtoa_mode) {
    344             case DoubleToStringConverter::SHORTEST:  return BIGNUM_DTOA_SHORTEST;
    345             case DoubleToStringConverter::FIXED:     return BIGNUM_DTOA_FIXED;
    346             case DoubleToStringConverter::PRECISION: return BIGNUM_DTOA_PRECISION;
    347             default:
    348                 UNREACHABLE();
    349                 return BIGNUM_DTOA_SHORTEST;  // To silence compiler.
    350         }
    351     }
    352    
    353    
    354     void DoubleToStringConverter::DoubleToAscii(double v,
    355                                                 DtoaMode mode,
    356                                                 int requested_digits,
    357                                                 char* buffer,
    358                                                 int buffer_length,
    359                                                 bool* sign,
    360                                                 int* length,
    361                                                 int* point) {
    362         BufferReference<char> vector(buffer, buffer_length);
    363         ASSERT(!Double(v).IsSpecial());
    364         ASSERT(mode == SHORTEST || requested_digits >= 0);
    365        
    366         if (Double(v).Sign() < 0) {
    367             *sign = true;
    368             v = -v;
    369         } else {
    370             *sign = false;
    371         }
    372        
    373         if (mode == PRECISION && requested_digits == 0) {
    374             vector[0] = '\0';
    375             *length = 0;
    376             return;
    377         }
    378        
    379         if (v == 0) {
    380             vector[0] = '0';
    381             vector[1] = '\0';
    382             *length = 1;
    383             *point = 1;
    384             return;
    385         }
    386        
    387         bool fast_worked;
    388         switch (mode) {
    389             case SHORTEST:
    390                 fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, vector, length, point);
    391                 break;
    392             case FIXED:
    393                 fast_worked = FastFixedDtoa(v, requested_digits, vector, length, point);
    394                 break;
    395             case PRECISION:
    396                 fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits,
    397                                        vector, length, point);
    398                 break;
    399             default:
    400                 UNREACHABLE();
    401                 fast_worked = false;
    402         }
    403         if (fast_worked) return;
    404        
    405         // If the fast dtoa didn't succeed use the slower bignum version.
    406         BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
    407         BignumDtoa(v, bignum_mode, requested_digits, vector, length, point);
    408         vector[*length] = '\0';
    409     }
    410    
    411    
    412     // Maximum number of significant digits in decimal representation.
    413     // The longest possible double in decimal representation is
    414     // (2^53 - 1) * 2 ^ -1074 that is (2 ^ 53 - 1) * 5 ^ 1074 / 10 ^ 1074
    415     // (768 digits). If we parse a number whose first digits are equal to a
    416     // mean of 2 adjacent doubles (that could have up to 769 digits) the result
    417     // must be rounded to the bigger one unless the tail consists of zeros, so
    418     // we don't need to preserve all the digits.
    419     const int kMaxSignificantDigits = 772;
    420    
    421    
    422     static double SignedZero(bool sign) {
    423         return sign ? -0.0 : 0.0;
    424     }
    425    
    426    
    427     double StringToDoubleConverter::StringToDouble(
    428                                                    const char* input,
    429                                                    size_t length,
    430                                                    size_t* processed_characters_count) {
    431         const char* current = input;
    432         const char* end = input + length;
    433        
    434         *processed_characters_count = 0;
    435        
    436         // To make sure that iterator dereferencing is valid the following
    437         // convention is used:
    438         // 1. Each '++current' statement is followed by check for equality to 'end'.
    439         // 3. If 'current' becomes equal to 'end' the function returns or goes to
    440         // 'parsing_done'.
    441         // 4. 'current' is not dereferenced after the 'parsing_done' label.
    442         // 5. Code before 'parsing_done' may rely on 'current != end'.
    443         if (current == end) return 0.0;
    444        
    445         // The longest form of simplified number is: "-<significant digits>.1eXXX\0".
    446         const unsigned kBufferSize = kMaxSignificantDigits + 10;
    447         char buffer[kBufferSize];  // NOLINT: size is known at compile time.
    448         unsigned buffer_pos = 0;
    449        
    450         // Exponent will be adjusted if insignificant digits of the integer part
    451         // or insignificant leading zeros of the fractional part are dropped.
    452         int exponent = 0;
    453         int significant_digits = 0;
    454         int insignificant_digits = 0;
    455         bool nonzero_digit_dropped = false;
    456         bool sign = false;
    457        
    458         if (*current == '+' || *current == '-') {
    459             sign = (*current == '-');
    460             ++current;
    461             if (current == end) return 0.0;
    462         }
    463        
    464         bool leading_zero = false;
    465         if (*current == '0') {
    466             ++current;
    467             if (current == end) {
    468                 *processed_characters_count = current - input;
    469                 return SignedZero(sign);
    470             }
    471            
    472             leading_zero = true;
    473            
    474             // Ignore leading zeros in the integer part.
    475             while (*current == '0') {
    476                 ++current;
    477                 if (current == end) {
    478                     *processed_characters_count = current - input;
    479                     return SignedZero(sign);
    480                 }
    481             }
    482         }
    483        
    484         // Copy significant digits of the integer part (if any) to the buffer.
    485         while (isASCIIDigit(*current)) {
    486             if (significant_digits < kMaxSignificantDigits) {
    487                 ASSERT(buffer_pos < kBufferSize);
    488                 buffer[buffer_pos++] = static_cast<char>(*current);
    489                 significant_digits++;
    490             } else {
    491                 insignificant_digits++;  // Move the digit into the exponential part.
    492                 nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
    493             }
    494             ++current;
    495             if (current == end) goto parsing_done;
    496         }
    497        
    498         if (*current == '.') {
    499             ++current;
    500             if (current == end) {
    501                 if (significant_digits == 0 && !leading_zero) {
    502                     return 0.0;
    503                 } else {
    504                     goto parsing_done;
    505                 }
    506             }
    507            
    508             if (significant_digits == 0) {
    509                 // Integer part consists of 0 or is absent. Significant digits start after
    510                 // leading zeros (if any).
    511                 while (*current == '0') {
    512                     ++current;
    513                     if (current == end) {
    514                         *processed_characters_count = current - input;
    515                         return SignedZero(sign);
    516                     }
    517                     exponent--;  // Move this 0 into the exponent.
    518                 }
    519             }
    520 
    521             // There is a fractional part.
    522             while (isASCIIDigit(*current)) {
    523                 if (significant_digits < kMaxSignificantDigits) {
    524                     ASSERT(buffer_pos < kBufferSize);
    525                     buffer[buffer_pos++] = static_cast<char>(*current);
    526                     significant_digits++;
    527                     exponent--;
    528                 } else {
    529                     // Ignore insignificant digits in the fractional part.
    530                     nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
    531                 }
    532                 ++current;
    533                 if (current == end) goto parsing_done;
    534             }
    535         }
    536        
    537         if (!leading_zero && exponent == 0 && significant_digits == 0) {
    538             // If leading_zeros is true then the string contains zeros.
    539             // If exponent < 0 then string was [+-]\.0*...
    540             // If significant_digits != 0 the string is not equal to 0.
    541             // Otherwise there are no digits in the string.
    542             return 0.0;
    543         }
    544        
    545         // Parse exponential part.
    546         if (*current == 'e' || *current == 'E') {
    547             ++current;
    548             if (current == end) {
    549                 --current;
    550                 goto parsing_done;
    551             }
    552             char sign = 0;
    553             if (*current == '+' || *current == '-') {
    554                 sign = static_cast<char>(*current);
    555                 ++current;
    556                 if (current == end) {
    557                     current -= 2;
    558                     goto parsing_done;
    559                 }
    560             }
    561            
    562             if (*current < '0' || *current > '9') {
    563                 if (sign)
    564                     --current;
    565                 --current;
    566                 goto parsing_done;
    567             }
    568            
    569             const int max_exponent = INT_MAX / 2;
    570             ASSERT(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
    571             int num = 0;
    572             do {
    573                 // Check overflow.
    574                 int digit = *current - '0';
    575                 if (num >= max_exponent / 10
    576                     && !(num == max_exponent / 10 && digit <= max_exponent % 10)) {
    577                     num = max_exponent;
    578                 } else {
    579                     num = num * 10 + digit;
    580                 }
    581                 ++current;
    582             } while (current != end && isASCIIDigit(*current));
    583            
    584             exponent += (sign == '-' ? -num : num);
    585         }
    586        
    587     parsing_done:
    588         exponent += insignificant_digits;
    589        
    590         if (nonzero_digit_dropped) {
    591             buffer[buffer_pos++] = '1';
    592             exponent--;
    593         }
    594        
     547        exponent--;  // Move this 0 into the exponent.
     548      }
     549    }
     550
     551    // There is a fractional part.
     552    // We don't emit a '.', but adjust the exponent instead.
     553    while (isASCIIDigit(*current)) {
     554      if (significant_digits < kMaxSignificantDigits) {
    595555        ASSERT(buffer_pos < kBufferSize);
    596         buffer[buffer_pos] = '\0';
    597        
    598         double converted = Strtod(BufferReference<const char>(buffer, buffer_pos), exponent);
    599         *processed_characters_count = current - input;
    600         return sign? -converted: converted;
    601     }
    602    
     556        buffer[buffer_pos++] = static_cast<char>(*current);
     557        significant_digits++;
     558        exponent--;
     559      } else {
     560        // Ignore insignificant digits in the fractional part.
     561        nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
     562      }
     563      if (Advance(&current, end)) goto parsing_done;
     564    }
     565  }
     566
     567  if (!leading_zero && exponent == 0 && significant_digits == 0) {
     568    // If leading_zeros is true then the string contains zeros.
     569    // If exponent < 0 then string was [+-]\.0*...
     570    // If significant_digits != 0 the string is not equal to 0.
     571    // Otherwise there are no digits in the string.
     572    return 0.0;
     573  }
     574
     575  // Parse exponential part.
     576  if (*current == 'e' || *current == 'E') {
     577    ++current;
     578    if (current == end) {
     579      --current;
     580      goto parsing_done;
     581    }
     582    char exponen_sign = 0;
     583    if (*current == '+' || *current == '-') {
     584      exponen_sign = static_cast<char>(*current);
     585      ++current;
     586      if (current == end) {
     587        current -= 2;
     588        goto parsing_done;
     589      }
     590    }
     591
     592    if (*current < '0' || *current > '9') {
     593      if (exponen_sign)
     594        --current;
     595      --current;
     596      goto parsing_done;
     597    }
     598
     599    const int max_exponent = INT_MAX / 2;
     600    ASSERT(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
     601    int num = 0;
     602    do {
     603      // Check overflow.
     604      int digit = *current - '0';
     605      if (num >= max_exponent / 10
     606          && !(num == max_exponent / 10 && digit <= max_exponent % 10)) {
     607        num = max_exponent;
     608      } else {
     609        num = num * 10 + digit;
     610      }
     611      ++current;
     612    } while (current != end && isASCIIDigit(*current));
     613
     614    exponent += (exponen_sign == '-' ? -num : num);
     615  }
     616
     617  parsing_done:
     618  exponent += insignificant_digits;
     619
     620  if (nonzero_digit_dropped) {
     621    buffer[buffer_pos++] = '1';
     622    exponent--;
     623  }
     624
     625  ASSERT(buffer_pos < kBufferSize);
     626  buffer[buffer_pos] = '\0';
     627
     628  auto converted = StringToFloatingPointType<FloatingPointType>(BufferReference<const char>(buffer, buffer_pos), exponent);
     629  *processed_characters_count = static_cast<size_t>(current - input);
     630  return sign? -converted: converted;
     631}
     632
     633double StringToDoubleConverter::StringToDouble(
     634    const char* buffer,
     635    size_t length,
     636    size_t* processed_characters_count) {
     637  return StringToIeee<double>(buffer, length, processed_characters_count);
     638}
     639
     640
     641double StringToDoubleConverter::StringToDouble(
     642    const uc16* buffer,
     643    size_t length,
     644    size_t* processed_characters_count) {
     645  return StringToIeee<double>(buffer, length, processed_characters_count);
     646}
     647
     648
     649float StringToDoubleConverter::StringToFloat(
     650    const char* buffer,
     651    size_t length,
     652    size_t* processed_characters_count) {
     653  return StringToIeee<float>(buffer, length, processed_characters_count);
     654}
     655
     656
     657float StringToDoubleConverter::StringToFloat(
     658    const uc16* buffer,
     659    size_t length,
     660    size_t* processed_characters_count) {
     661  return StringToIeee<float>(buffer, length, processed_characters_count);
     662}
     663
    603664}  // namespace double_conversion
    604 
    605 } // namespace WTF
     665}  // namespace WTF
  • trunk/Source/WTF/wtf/dtoa/double-conversion.h

    r150995 r242048  
    1 // Copyright 2010 the V8 project authors. All rights reserved.
     1// Copyright 2012 the V8 project authors. All rights reserved.
    22// Redistribution and use in source and binary forms, with or without
    33// modification, are permitted provided that the following conditions are
     
    3232
    3333namespace WTF {
    34 
    3534namespace double_conversion {
    36    
    37     class DoubleToStringConverter {
    38     public:
    39         // When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint
    40         // or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the
    41         // function returns false.
    42         static const int kMaxFixedDigitsBeforePoint = 60;
    43         static const int kMaxFixedDigitsAfterPoint = 60;
    44        
    45         // When calling ToExponential with a requested_digits
    46         // parameter > kMaxExponentialDigits then the function returns false.
    47         static const int kMaxExponentialDigits = 120;
    48        
    49         // When calling ToPrecision with a requested_digits
    50         // parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits
    51         // then the function returns false.
    52         static const int kMinPrecisionDigits = 1;
    53         static const int kMaxPrecisionDigits = 120;
    54        
    55         enum Flags {
    56             NO_FLAGS = 0,
    57             EMIT_POSITIVE_EXPONENT_SIGN = 1,
    58             EMIT_TRAILING_DECIMAL_POINT = 2,
    59             EMIT_TRAILING_ZERO_AFTER_POINT = 4,
    60             UNIQUE_ZERO = 8
    61         };
    62        
    63         // Flags should be a bit-or combination of the possible Flags-enum.
    64         //  - NO_FLAGS: no special flags.
    65         //  - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent
    66         //    form, emits a '+' for positive exponents. Example: 1.2e+2.
    67         //  - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is
    68         //    converted into decimal format then a trailing decimal point is appended.
    69         //    Example: 2345.0 is converted to "2345.".
    70         //  - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point
    71         //    emits a trailing '0'-character. This flag requires the
    72         //    EXMIT_TRAILING_DECIMAL_POINT flag.
    73         //    Example: 2345.0 is converted to "2345.0".
    74         //  - UNIQUE_ZERO: "-0.0" is converted to "0.0".
    75         //
    76         // Infinity symbol and nan_symbol provide the string representation for these
    77         // special values. If the string is NULL and the special value is encountered
    78         // then the conversion functions return false.
    79         //
    80         // The exponent_character is used in exponential representations. It is
    81         // usually 'e' or 'E'.
    82         //
    83         // When converting to the shortest representation the converter will
    84         // represent input numbers in decimal format if they are in the interval
    85         // [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[
    86         //    (lower boundary included, greater boundary excluded).
    87         // Example: with decimal_in_shortest_low = -6 and
    88         //               decimal_in_shortest_high = 21:
    89         //   ToShortest(0.000001)  -> "0.000001"
    90         //   ToShortest(0.0000001) -> "1e-7"
    91         //   ToShortest(111111111111111111111.0)  -> "111111111111111110000"
    92         //   ToShortest(100000000000000000000.0)  -> "100000000000000000000"
    93         //   ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
    94         //
    95         // When converting to precision mode the converter may add
    96         // max_leading_padding_zeroes before returning the number in exponential
    97         // format.
    98         // Example with max_leading_padding_zeroes_in_precision_mode = 6.
    99         //   ToPrecision(0.0000012345, 2) -> "0.0000012"
    100         //   ToPrecision(0.00000012345, 2) -> "1.2e-7"
    101         // Similarily the converter may add up to
    102         // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
    103         // returning an exponential representation. A zero added by the
    104         // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
    105         // Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
    106         //   ToPrecision(230.0, 2) -> "230"
    107         //   ToPrecision(230.0, 2) -> "230."  with EMIT_TRAILING_DECIMAL_POINT.
    108         //   ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
    109         DoubleToStringConverter(int flags,
    110                                 const char* infinity_symbol,
    111                                 const char* nan_symbol,
    112                                 char exponent_character,
    113                                 int decimal_in_shortest_low,
    114                                 int decimal_in_shortest_high,
    115                                 int max_leading_padding_zeroes_in_precision_mode,
    116                                 int max_trailing_padding_zeroes_in_precision_mode)
    117         : flags_(flags),
     35
     36class DoubleToStringConverter {
     37 public:
     38  // When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint
     39  // or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the
     40  // function returns false.
     41  static const int kMaxFixedDigitsBeforePoint = 60;
     42  static const int kMaxFixedDigitsAfterPoint = 60;
     43
     44  // When calling ToExponential with a requested_digits
     45  // parameter > kMaxExponentialDigits then the function returns false.
     46  static const int kMaxExponentialDigits = 120;
     47
     48  // When calling ToPrecision with a requested_digits
     49  // parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits
     50  // then the function returns false.
     51  static const int kMinPrecisionDigits = 1;
     52  static const int kMaxPrecisionDigits = 120;
     53
     54  enum Flags {
     55    NO_FLAGS = 0,
     56    EMIT_POSITIVE_EXPONENT_SIGN = 1,
     57    EMIT_TRAILING_DECIMAL_POINT = 2,
     58    EMIT_TRAILING_ZERO_AFTER_POINT = 4,
     59    UNIQUE_ZERO = 8
     60  };
     61
     62  // Flags should be a bit-or combination of the possible Flags-enum.
     63  //  - NO_FLAGS: no special flags.
     64  //  - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent
     65  //    form, emits a '+' for positive exponents. Example: 1.2e+2.
     66  //  - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is
     67  //    converted into decimal format then a trailing decimal point is appended.
     68  //    Example: 2345.0 is converted to "2345.".
     69  //  - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point
     70  //    emits a trailing '0'-character. This flag requires the
     71  //    EXMIT_TRAILING_DECIMAL_POINT flag.
     72  //    Example: 2345.0 is converted to "2345.0".
     73  //  - UNIQUE_ZERO: "-0.0" is converted to "0.0".
     74  //
     75  // Infinity symbol and nan_symbol provide the string representation for these
     76  // special values. If the string is NULL and the special value is encountered
     77  // then the conversion functions return false.
     78  //
     79  // The exponent_character is used in exponential representations. It is
     80  // usually 'e' or 'E'.
     81  //
     82  // When converting to the shortest representation the converter will
     83  // represent input numbers in decimal format if they are in the interval
     84  // [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[
     85  //    (lower boundary included, greater boundary excluded).
     86  // Example: with decimal_in_shortest_low = -6 and
     87  //               decimal_in_shortest_high = 21:
     88  //   ToShortest(0.000001)  -> "0.000001"
     89  //   ToShortest(0.0000001) -> "1e-7"
     90  //   ToShortest(111111111111111111111.0)  -> "111111111111111110000"
     91  //   ToShortest(100000000000000000000.0)  -> "100000000000000000000"
     92  //   ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
     93  //
     94  // When converting to precision mode the converter may add
     95  // max_leading_padding_zeroes before returning the number in exponential
     96  // format.
     97  // Example with max_leading_padding_zeroes_in_precision_mode = 6.
     98  //   ToPrecision(0.0000012345, 2) -> "0.0000012"
     99  //   ToPrecision(0.00000012345, 2) -> "1.2e-7"
     100  // Similarily the converter may add up to
     101  // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
     102  // returning an exponential representation. A zero added by the
     103  // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
     104  // Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
     105  //   ToPrecision(230.0, 2) -> "230"
     106  //   ToPrecision(230.0, 2) -> "230."  with EMIT_TRAILING_DECIMAL_POINT.
     107  //   ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
     108  DoubleToStringConverter(int flags,
     109                          const char* infinity_symbol,
     110                          const char* nan_symbol,
     111                          char exponent_character,
     112                          int decimal_in_shortest_low,
     113                          int decimal_in_shortest_high,
     114                          int max_leading_padding_zeroes_in_precision_mode,
     115                          int max_trailing_padding_zeroes_in_precision_mode)
     116      : flags_(flags),
    118117        infinity_symbol_(infinity_symbol),
    119118        nan_symbol_(nan_symbol),
     
    122121        decimal_in_shortest_high_(decimal_in_shortest_high),
    123122        max_leading_padding_zeroes_in_precision_mode_(
    124                                                       max_leading_padding_zeroes_in_precision_mode),
     123            max_leading_padding_zeroes_in_precision_mode),
    125124        max_trailing_padding_zeroes_in_precision_mode_(
    126                                                        max_trailing_padding_zeroes_in_precision_mode) {
    127             // When 'trailing zero after the point' is set, then 'trailing point'
    128             // must be set too.
    129             ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) ||
    130                    !((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0));
    131         }
    132        
    133         // Returns a converter following the EcmaScript specification.
    134         WTF_EXPORT_PRIVATE static const DoubleToStringConverter& EcmaScriptConverter();
    135        
    136         // Computes the shortest string of digits that correctly represent the input
    137         // number. Depending on decimal_in_shortest_low and decimal_in_shortest_high
    138         // (see constructor) it then either returns a decimal representation, or an
    139         // exponential representation.
    140         // Example with decimal_in_shortest_low = -6,
    141         //              decimal_in_shortest_high = 21,
    142         //              EMIT_POSITIVE_EXPONENT_SIGN activated, and
    143         //              EMIT_TRAILING_DECIMAL_POINT deactived:
    144         //   ToShortest(0.000001)  -> "0.000001"
    145         //   ToShortest(0.0000001) -> "1e-7"
    146         //   ToShortest(111111111111111111111.0)  -> "111111111111111110000"
    147         //   ToShortest(100000000000000000000.0)  -> "100000000000000000000"
    148         //   ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
    149         //
    150         // Note: the conversion may round the output if the returned string
    151         // is accurate enough to uniquely identify the input-number.
    152         // For example the most precise representation of the double 9e59 equals
    153         // "899999999999999918767229449717619953810131273674690656206848", but
    154         // the converter will return the shorter (but still correct) "9e59".
    155         //
    156         // Returns true if the conversion succeeds. The conversion always succeeds
    157         // except when the input value is special and no infinity_symbol or
    158         // nan_symbol has been given to the constructor.
    159         bool ToShortest(double value, StringBuilder* result_builder) const;
    160        
    161        
    162         // Computes a decimal representation with a fixed number of digits after the
    163         // decimal point. The last emitted digit is rounded.
    164         //
    165         // Examples:
    166         //   ToFixed(3.12, 1) -> "3.1"
    167         //   ToFixed(3.1415, 3) -> "3.142"
    168         //   ToFixed(1234.56789, 4) -> "1234.5679"
    169         //   ToFixed(1.23, 5) -> "1.23000"
    170         //   ToFixed(0.1, 4) -> "0.1000"
    171         //   ToFixed(1e30, 2) -> "1000000000000000019884624838656.00"
    172         //   ToFixed(0.1, 30) -> "0.100000000000000005551115123126"
    173         //   ToFixed(0.1, 17) -> "0.10000000000000001"
    174         //
    175         // If requested_digits equals 0, then the tail of the result depends on
    176         // the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT.
    177         // Examples, for requested_digits == 0,
    178         //   let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be
    179         //    - false and false: then 123.45 -> 123
    180         //                             0.678 -> 1
    181         //    - true and false: then 123.45 -> 123.
    182         //                            0.678 -> 1.
    183         //    - true and true: then 123.45 -> 123.0
    184         //                           0.678 -> 1.0
    185         //
    186         // Returns true if the conversion succeeds. The conversion always succeeds
    187         // except for the following cases:
    188         //   - the input value is special and no infinity_symbol or nan_symbol has
    189         //     been provided to the constructor,
    190         //   - 'value' > 10^kMaxFixedDigitsBeforePoint, or
    191         //   - 'requested_digits' > kMaxFixedDigitsAfterPoint.
    192         // The last two conditions imply that the result will never contain more than
    193         // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters
    194         // (one additional character for the sign, and one for the decimal point).
    195         bool ToFixed(double value,
    196                      int requested_digits,
    197                      StringBuilder* result_builder) const;
    198        
    199         // Computes a representation in exponential format with requested_digits
    200         // after the decimal point. The last emitted digit is rounded.
    201         // If requested_digits equals -1, then the shortest exponential representation
    202         // is computed.
    203         //
    204         // Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and
    205         //               exponent_character set to 'e'.
    206         //   ToExponential(3.12, 1) -> "3.1e0"
    207         //   ToExponential(5.0, 3) -> "5.000e0"
    208         //   ToExponential(0.001, 2) -> "1.00e-3"
    209         //   ToExponential(3.1415, -1) -> "3.1415e0"
    210         //   ToExponential(3.1415, 4) -> "3.1415e0"
    211         //   ToExponential(3.1415, 3) -> "3.142e0"
    212         //   ToExponential(123456789000000, 3) -> "1.235e14"
    213         //   ToExponential(1000000000000000019884624838656.0, -1) -> "1e30"
    214         //   ToExponential(1000000000000000019884624838656.0, 32) ->
    215         //                     "1.00000000000000001988462483865600e30"
    216         //   ToExponential(1234, 0) -> "1e3"
    217         //
    218         // Returns true if the conversion succeeds. The conversion always succeeds
    219         // except for the following cases:
    220         //   - the input value is special and no infinity_symbol or nan_symbol has
    221         //     been provided to the constructor,
    222         //   - 'requested_digits' > kMaxExponentialDigits.
    223         // The last condition implies that the result will never contain more than
    224         // kMaxExponentialDigits + 8 characters (the sign, the digit before the
    225         // decimal point, the decimal point, the exponent character, the
    226         // exponent's sign, and at most 3 exponent digits).
    227         WTF_EXPORT_PRIVATE bool ToExponential(double value,
    228                            int requested_digits,
    229                            StringBuilder* result_builder) const;
    230        
    231         // Computes 'precision' leading digits of the given 'value' and returns them
    232         // either in exponential or decimal format, depending on
    233         // max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the
    234         // constructor).
    235         // The last computed digit is rounded.
    236         //
    237         // Example with max_leading_padding_zeroes_in_precision_mode = 6.
    238         //   ToPrecision(0.0000012345, 2) -> "0.0000012"
    239         //   ToPrecision(0.00000012345, 2) -> "1.2e-7"
    240         // Similarily the converter may add up to
    241         // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
    242         // returning an exponential representation. A zero added by the
    243         // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
    244         // Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
    245         //   ToPrecision(230.0, 2) -> "230"
    246         //   ToPrecision(230.0, 2) -> "230."  with EMIT_TRAILING_DECIMAL_POINT.
    247         //   ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
    248         // Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no
    249         //    EMIT_TRAILING_ZERO_AFTER_POINT:
    250         //   ToPrecision(123450.0, 6) -> "123450"
    251         //   ToPrecision(123450.0, 5) -> "123450"
    252         //   ToPrecision(123450.0, 4) -> "123500"
    253         //   ToPrecision(123450.0, 3) -> "123000"
    254         //   ToPrecision(123450.0, 2) -> "1.2e5"
    255         //
    256         // Returns true if the conversion succeeds. The conversion always succeeds
    257         // except for the following cases:
    258         //   - the input value is special and no infinity_symbol or nan_symbol has
    259         //     been provided to the constructor,
    260         //   - precision < kMinPericisionDigits
    261         //   - precision > kMaxPrecisionDigits
    262         // The last condition implies that the result will never contain more than
    263         // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the
    264         // exponent character, the exponent's sign, and at most 3 exponent digits).
    265         bool ToPrecision(double value,
    266                          int precision,
    267                          StringBuilder* result_builder) const;
    268        
    269         enum DtoaMode {
    270             // Produce the shortest correct representation.
    271             // For example the output of 0.299999999999999988897 is (the less accurate
    272             // but correct) 0.3.
    273             SHORTEST,
    274             // Produce a fixed number of digits after the decimal point.
    275             // For instance fixed(0.1, 4) becomes 0.1000
    276             // If the input number is big, the output will be big.
    277             FIXED,
    278             // Fixed number of digits (independent of the decimal point).
    279             PRECISION
    280         };
    281        
    282         // The maximal number of digits that are needed to emit a double in base 10.
    283         // A higher precision can be achieved by using more digits, but the shortest
    284         // accurate representation of any double will never use more digits than
    285         // kBase10MaximalLength.
    286         // Note that DoubleToAscii null-terminates its input. So the given buffer
    287         // should be at least kBase10MaximalLength + 1 characters long.
    288         static const int kBase10MaximalLength = 17;
    289        
    290         // Converts the given double 'v' to ascii.
    291         // The result should be interpreted as buffer * 10^(point-length).
    292         //
    293         // The output depends on the given mode:
    294         //  - SHORTEST: produce the least amount of digits for which the internal
    295         //   identity requirement is still satisfied. If the digits are printed
    296         //   (together with the correct exponent) then reading this number will give
    297         //   'v' again. The buffer will choose the representation that is closest to
    298         //   'v'. If there are two at the same distance, than the one farther away
    299         //   from 0 is chosen (halfway cases - ending with 5 - are rounded up).
    300         //   In this mode the 'requested_digits' parameter is ignored.
    301         //  - FIXED: produces digits necessary to print a given number with
    302         //   'requested_digits' digits after the decimal point. The produced digits
    303         //   might be too short in which case the caller has to fill the remainder
    304         //   with '0's.
    305         //   Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
    306         //   Halfway cases are rounded towards +/-Infinity (away from 0). The call
    307         //   toFixed(0.15, 2) thus returns buffer="2", point=0.
    308         //   The returned buffer may contain digits that would be truncated from the
    309         //   shortest representation of the input.
    310         //  - PRECISION: produces 'requested_digits' where the first digit is not '0'.
    311         //   Even though the length of produced digits usually equals
    312         //   'requested_digits', the function is allowed to return fewer digits, in
    313         //   which case the caller has to fill the missing digits with '0's.
    314         //   Halfway cases are again rounded away from 0.
    315         // DoubleToAscii expects the given buffer to be big enough to hold all
    316         // digits and a terminating null-character. In SHORTEST-mode it expects a
    317         // buffer of at least kBase10MaximalLength + 1. In all other modes the
    318         // requested_digits parameter (+ 1 for the null-character) limits the size of
    319         // the output. The given length is only used in debug mode to ensure the
    320         // buffer is big enough.
    321         static void DoubleToAscii(double v,
    322                                   DtoaMode mode,
    323                                   int requested_digits,
    324                                   char* buffer,
    325                                   int buffer_length,
    326                                   bool* sign,
    327                                   int* length,
    328                                   int* point);
    329        
    330     private:
    331         // If the value is a special value (NaN or Infinity) constructs the
    332         // corresponding string using the configured infinity/nan-symbol.
    333         // If either of them is NULL or the value is not special then the
    334         // function returns false.
    335         bool HandleSpecialValues(double value, StringBuilder* result_builder) const;
    336         // Constructs an exponential representation (i.e. 1.234e56).
    337         // The given exponent assumes a decimal point after the first decimal digit.
    338         void CreateExponentialRepresentation(const char* decimal_digits,
    339                                              int length,
    340                                              int exponent,
    341                                              StringBuilder* result_builder) const;
    342         // Creates a decimal representation (i.e 1234.5678).
    343         void CreateDecimalRepresentation(const char* decimal_digits,
    344                                          int length,
    345                                          int decimal_point,
    346                                          int digits_after_point,
    347                                          StringBuilder* result_builder) const;
    348        
    349         const int flags_;
    350         const char* const infinity_symbol_;
    351         const char* const nan_symbol_;
    352         const char exponent_character_;
    353         const int decimal_in_shortest_low_;
    354         const int decimal_in_shortest_high_;
    355         const int max_leading_padding_zeroes_in_precision_mode_;
    356         const int max_trailing_padding_zeroes_in_precision_mode_;
    357        
    358         DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter);
    359     };
    360    
    361    
    362     class StringToDoubleConverter {
    363     public:
    364         // Performs the conversion.
    365         // The output parameter 'processed_characters_count' is set to the number
    366         // of characters that have been processed to read the number.
    367         WTF_EXPORT_PRIVATE static double StringToDouble(const char* buffer, size_t length, size_t* processed_characters_count);
    368        
    369     private:
    370         DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter);
    371     };
    372    
     125            max_trailing_padding_zeroes_in_precision_mode) {
     126    // When 'trailing zero after the point' is set, then 'trailing point'
     127    // must be set too.
     128    ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) ||
     129        !((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0));
     130  }
     131
     132  // Returns a converter following the EcmaScript specification.
     133  WTF_EXPORT_PRIVATE static const DoubleToStringConverter& EcmaScriptConverter();
     134
     135  // Computes the shortest string of digits that correctly represent the input
     136  // number. Depending on decimal_in_shortest_low and decimal_in_shortest_high
     137  // (see constructor) it then either returns a decimal representation, or an
     138  // exponential representation.
     139  // Example with decimal_in_shortest_low = -6,
     140  //              decimal_in_shortest_high = 21,
     141  //              EMIT_POSITIVE_EXPONENT_SIGN activated, and
     142  //              EMIT_TRAILING_DECIMAL_POINT deactived:
     143  //   ToShortest(0.000001)  -> "0.000001"
     144  //   ToShortest(0.0000001) -> "1e-7"
     145  //   ToShortest(111111111111111111111.0)  -> "111111111111111110000"
     146  //   ToShortest(100000000000000000000.0)  -> "100000000000000000000"
     147  //   ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
     148  //
     149  // Note: the conversion may round the output if the returned string
     150  // is accurate enough to uniquely identify the input-number.
     151  // For example the most precise representation of the double 9e59 equals
     152  // "899999999999999918767229449717619953810131273674690656206848", but
     153  // the converter will return the shorter (but still correct) "9e59".
     154  //
     155  // Returns true if the conversion succeeds. The conversion always succeeds
     156  // except when the input value is special and no infinity_symbol or
     157  // nan_symbol has been given to the constructor.
     158  bool ToShortest(double value, StringBuilder* result_builder) const {
     159    return ToShortestIeeeNumber(value, result_builder, SHORTEST);
     160  }
     161
     162  // Same as ToShortest, but for single-precision floats.
     163  bool ToShortestSingle(float value, StringBuilder* result_builder) const {
     164    return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE);
     165  }
     166
     167
     168  // Computes a decimal representation with a fixed number of digits after the
     169  // decimal point. The last emitted digit is rounded.
     170  //
     171  // Examples:
     172  //   ToFixed(3.12, 1) -> "3.1"
     173  //   ToFixed(3.1415, 3) -> "3.142"
     174  //   ToFixed(1234.56789, 4) -> "1234.5679"
     175  //   ToFixed(1.23, 5) -> "1.23000"
     176  //   ToFixed(0.1, 4) -> "0.1000"
     177  //   ToFixed(1e30, 2) -> "1000000000000000019884624838656.00"
     178  //   ToFixed(0.1, 30) -> "0.100000000000000005551115123126"
     179  //   ToFixed(0.1, 17) -> "0.10000000000000001"
     180  //
     181  // If requested_digits equals 0, then the tail of the result depends on
     182  // the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT.
     183  // Examples, for requested_digits == 0,
     184  //   let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be
     185  //    - false and false: then 123.45 -> 123
     186  //                             0.678 -> 1
     187  //    - true and false: then 123.45 -> 123.
     188  //                            0.678 -> 1.
     189  //    - true and true: then 123.45 -> 123.0
     190  //                           0.678 -> 1.0
     191  //
     192  // Returns true if the conversion succeeds. The conversion always succeeds
     193  // except for the following cases:
     194  //   - the input value is special and no infinity_symbol or nan_symbol has
     195  //     been provided to the constructor,
     196  //   - 'value' > 10^kMaxFixedDigitsBeforePoint, or
     197  //   - 'requested_digits' > kMaxFixedDigitsAfterPoint.
     198  // The last two conditions imply that the result will never contain more than
     199  // 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters
     200  // (one additional character for the sign, and one for the decimal point).
     201  bool ToFixed(double value,
     202               int requested_digits,
     203               StringBuilder* result_builder) const;
     204
     205  // Computes a representation in exponential format with requested_digits
     206  // after the decimal point. The last emitted digit is rounded.
     207  // If requested_digits equals -1, then the shortest exponential representation
     208  // is computed.
     209  //
     210  // Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and
     211  //               exponent_character set to 'e'.
     212  //   ToExponential(3.12, 1) -> "3.1e0"
     213  //   ToExponential(5.0, 3) -> "5.000e0"
     214  //   ToExponential(0.001, 2) -> "1.00e-3"
     215  //   ToExponential(3.1415, -1) -> "3.1415e0"
     216  //   ToExponential(3.1415, 4) -> "3.1415e0"
     217  //   ToExponential(3.1415, 3) -> "3.142e0"
     218  //   ToExponential(123456789000000, 3) -> "1.235e14"
     219  //   ToExponential(1000000000000000019884624838656.0, -1) -> "1e30"
     220  //   ToExponential(1000000000000000019884624838656.0, 32) ->
     221  //                     "1.00000000000000001988462483865600e30"
     222  //   ToExponential(1234, 0) -> "1e3"
     223  //
     224  // Returns true if the conversion succeeds. The conversion always succeeds
     225  // except for the following cases:
     226  //   - the input value is special and no infinity_symbol or nan_symbol has
     227  //     been provided to the constructor,
     228  //   - 'requested_digits' > kMaxExponentialDigits.
     229  // The last condition implies that the result will never contain more than
     230  // kMaxExponentialDigits + 8 characters (the sign, the digit before the
     231  // decimal point, the decimal point, the exponent character, the
     232  // exponent's sign, and at most 3 exponent digits).
     233  WTF_EXPORT_PRIVATE bool ToExponential(double value,
     234                                        int requested_digits,
     235                                        StringBuilder* result_builder) const;
     236
     237  // Computes 'precision' leading digits of the given 'value' and returns them
     238  // either in exponential or decimal format, depending on
     239  // max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the
     240  // constructor).
     241  // The last computed digit is rounded.
     242  //
     243  // Example with max_leading_padding_zeroes_in_precision_mode = 6.
     244  //   ToPrecision(0.0000012345, 2) -> "0.0000012"
     245  //   ToPrecision(0.00000012345, 2) -> "1.2e-7"
     246  // Similarily the converter may add up to
     247  // max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
     248  // returning an exponential representation. A zero added by the
     249  // EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
     250  // Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
     251  //   ToPrecision(230.0, 2) -> "230"
     252  //   ToPrecision(230.0, 2) -> "230."  with EMIT_TRAILING_DECIMAL_POINT.
     253  //   ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
     254  // Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no
     255  //    EMIT_TRAILING_ZERO_AFTER_POINT:
     256  //   ToPrecision(123450.0, 6) -> "123450"
     257  //   ToPrecision(123450.0, 5) -> "123450"
     258  //   ToPrecision(123450.0, 4) -> "123500"
     259  //   ToPrecision(123450.0, 3) -> "123000"
     260  //   ToPrecision(123450.0, 2) -> "1.2e5"
     261  //
     262  // Returns true if the conversion succeeds. The conversion always succeeds
     263  // except for the following cases:
     264  //   - the input value is special and no infinity_symbol or nan_symbol has
     265  //     been provided to the constructor,
     266  //   - precision < kMinPericisionDigits
     267  //   - precision > kMaxPrecisionDigits
     268  // The last condition implies that the result will never contain more than
     269  // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the
     270  // exponent character, the exponent's sign, and at most 3 exponent digits).
     271  bool ToPrecision(double value,
     272                   int precision,
     273                   StringBuilder* result_builder) const;
     274
     275  enum DtoaMode {
     276    // Produce the shortest correct representation.
     277    // For example the output of 0.299999999999999988897 is (the less accurate
     278    // but correct) 0.3.
     279    SHORTEST,
     280    // Same as SHORTEST, but for single-precision floats.
     281    SHORTEST_SINGLE,
     282    // Produce a fixed number of digits after the decimal point.
     283    // For instance fixed(0.1, 4) becomes 0.1000
     284    // If the input number is big, the output will be big.
     285    FIXED,
     286    // Fixed number of digits (independent of the decimal point).
     287    PRECISION
     288  };
     289
     290  // The maximal number of digits that are needed to emit a double in base 10.
     291  // A higher precision can be achieved by using more digits, but the shortest
     292  // accurate representation of any double will never use more digits than
     293  // kBase10MaximalLength.
     294  // Note that DoubleToAscii null-terminates its input. So the given buffer
     295  // should be at least kBase10MaximalLength + 1 characters long.
     296  static const int kBase10MaximalLength = 17;
     297
     298  // Converts the given double 'v' to digit characters. 'v' must not be NaN,
     299  // +Infinity, or -Infinity. In SHORTEST_SINGLE-mode this restriction also
     300  // applies to 'v' after it has been casted to a single-precision float. That
     301  // is, in this mode static_cast<float>(v) must not be NaN, +Infinity or
     302  // -Infinity.
     303  //
     304  // The result should be interpreted as buffer * 10^(point-length).
     305  //
     306  // The digits are written to the buffer in the platform's charset, which is
     307  // often UTF-8 (with ASCII-range digits) but may be another charset, such
     308  // as EBCDIC.
     309  //
     310  // The output depends on the given mode:
     311  //  - SHORTEST: produce the least amount of digits for which the internal
     312  //   identity requirement is still satisfied. If the digits are printed
     313  //   (together with the correct exponent) then reading this number will give
     314  //   'v' again. The buffer will choose the representation that is closest to
     315  //   'v'. If there are two at the same distance, than the one farther away
     316  //   from 0 is chosen (halfway cases - ending with 5 - are rounded up).
     317  //   In this mode the 'requested_digits' parameter is ignored.
     318  //  - SHORTEST_SINGLE: same as SHORTEST but with single-precision.
     319  //  - FIXED: produces digits necessary to print a given number with
     320  //   'requested_digits' digits after the decimal point. The produced digits
     321  //   might be too short in which case the caller has to fill the remainder
     322  //   with '0's.
     323  //   Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
     324  //   Halfway cases are rounded towards +/-Infinity (away from 0). The call
     325  //   toFixed(0.15, 2) thus returns buffer="2", point=0.
     326  //   The returned buffer may contain digits that would be truncated from the
     327  //   shortest representation of the input.
     328  //  - PRECISION: produces 'requested_digits' where the first digit is not '0'.
     329  //   Even though the length of produced digits usually equals
     330  //   'requested_digits', the function is allowed to return fewer digits, in
     331  //   which case the caller has to fill the missing digits with '0's.
     332  //   Halfway cases are again rounded away from 0.
     333  // DoubleToAscii expects the given buffer to be big enough to hold all
     334  // digits and a terminating null-character. In SHORTEST-mode it expects a
     335  // buffer of at least kBase10MaximalLength + 1. In all other modes the
     336  // requested_digits parameter and the padding-zeroes limit the size of the
     337  // output. Don't forget the decimal point, the exponent character and the
     338  // terminating null-character when computing the maximal output size.
     339  // The given length is only used in debug mode to ensure the buffer is big
     340  // enough.
     341  static void DoubleToAscii(double v,
     342                            DtoaMode mode,
     343                            int requested_digits,
     344                            char* buffer,
     345                            int buffer_length,
     346                            bool* sign,
     347                            int* length,
     348                            int* point);
     349
     350 private:
     351  // Implementation for ToShortest and ToShortestSingle.
     352  bool ToShortestIeeeNumber(double value,
     353                            StringBuilder* result_builder,
     354                            DtoaMode mode) const;
     355
     356  // If the value is a special value (NaN or Infinity) constructs the
     357  // corresponding string using the configured infinity/nan-symbol.
     358  // If either of them is NULL or the value is not special then the
     359  // function returns false.
     360  bool HandleSpecialValues(double value, StringBuilder* result_builder) const;
     361  // Constructs an exponential representation (i.e. 1.234e56).
     362  // The given exponent assumes a decimal point after the first decimal digit.
     363  void CreateExponentialRepresentation(const char* decimal_digits,
     364                                       int length,
     365                                       int exponent,
     366                                       StringBuilder* result_builder) const;
     367  // Creates a decimal representation (i.e 1234.5678).
     368  void CreateDecimalRepresentation(const char* decimal_digits,
     369                                   int length,
     370                                   int decimal_point,
     371                                   int digits_after_point,
     372                                   StringBuilder* result_builder) const;
     373
     374  const int flags_;
     375  const char* const infinity_symbol_;
     376  const char* const nan_symbol_;
     377  const char exponent_character_;
     378  const int decimal_in_shortest_low_;
     379  const int decimal_in_shortest_high_;
     380  const int max_leading_padding_zeroes_in_precision_mode_;
     381  const int max_trailing_padding_zeroes_in_precision_mode_;
     382
     383  DC_DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter);
     384};
     385
     386
     387class StringToDoubleConverter {
     388 public:
     389  // Performs the conversion.
     390  // The output parameter 'processed_characters_count' is set to the number
     391  // of characters that have been processed to read the number.
     392  WTF_EXPORT_PRIVATE static double StringToDouble(const char* buffer,
     393                                                  size_t length,
     394                                                  size_t* processed_characters_count);
     395
     396  // Same as StringToDouble above but for 16 bit characters.
     397  WTF_EXPORT_PRIVATE static double StringToDouble(const uc16* buffer,
     398                                                  size_t length,
     399                                                  size_t* processed_characters_count);
     400
     401  // Same as StringToDouble but reads a float.
     402  // Note that this is not equivalent to static_cast<float>(StringToDouble(...))
     403  // due to potential double-rounding.
     404  WTF_EXPORT_PRIVATE static float StringToFloat(const char* buffer,
     405                                                size_t length,
     406                                                size_t* processed_characters_count);
     407
     408  // Same as StringToFloat above but for 16 bit characters.
     409  WTF_EXPORT_PRIVATE static float StringToFloat(const uc16* buffer,
     410                                                size_t length,
     411                                                size_t* processed_characters_count);
     412
     413 private:
     414  DC_DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter);
     415};
     416
    373417}  // namespace double_conversion
    374 
    375 } // namespace WTF
     418}  // namespace WTF
    376419
    377420#endif  // DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
  • trunk/Source/WTF/wtf/dtoa/fast-dtoa.cc

    r162793 r242048  
    1 // Copyright 2010 the V8 project authors. All rights reserved.
     1// Copyright 2012 the V8 project authors. All rights reserved.
    22// Redistribution and use in source and binary forms, with or without
    33// modification, are permitted provided that the following conditions are
     
    2828#include "config.h"
    2929
    30 #include "fast-dtoa.h"
    31 
    32 #include "cached-powers.h"
    33 #include "diy-fp.h"
    34 #include "double.h"
     30#include <wtf/dtoa/fast-dtoa.h>
     31
     32#include <wtf/dtoa/cached-powers.h>
     33#include <wtf/dtoa/diy-fp.h>
     34#include <wtf/dtoa/ieee.h>
    3535
    3636namespace WTF {
    37 
    3837namespace double_conversion {
    39    
    40     // The minimal and maximal target exponent define the range of w's binary
    41     // exponent, where 'w' is the result of multiplying the input by a cached power
    42     // of ten.
    43     //
    44     // A different range might be chosen on a different platform, to optimize digit
    45     // generation, but a smaller range requires more powers of ten to be cached.
    46     static const int kMinimalTargetExponent = -60;
    47     static const int kMaximalTargetExponent = -32;
    48    
    49    
    50     // Adjusts the last digit of the generated number, and screens out generated
    51     // solutions that may be inaccurate. A solution may be inaccurate if it is
    52     // outside the safe interval, or if we cannot prove that it is closer to the
    53     // input than a neighboring representation of the same length.
    54     //
    55     // Input: * buffer containing the digits of too_high / 10^kappa
    56     //        * the buffer's length
    57     //        * distance_too_high_w == (too_high - w).f() * unit
    58     //        * unsafe_interval == (too_high - too_low).f() * unit
    59     //        * rest = (too_high - buffer * 10^kappa).f() * unit
    60     //        * ten_kappa = 10^kappa * unit
    61     //        * unit = the common multiplier
    62     // Output: returns true if the buffer is guaranteed to contain the closest
    63     //    representable number to the input.
    64     //  Modifies the generated digits in the buffer to approach (round towards) w.
    65     static bool RoundWeed(BufferReference<char> buffer,
    66                           int length,
    67                           uint64_t distance_too_high_w,
    68                           uint64_t unsafe_interval,
    69                           uint64_t rest,
    70                           uint64_t ten_kappa,
    71                           uint64_t unit) {
    72         uint64_t small_distance = distance_too_high_w - unit;
    73         uint64_t big_distance = distance_too_high_w + unit;
    74         // Let w_low  = too_high - big_distance, and
    75         //     w_high = too_high - small_distance.
    76         // Note: w_low < w < w_high
    77         //
    78         // The real w (* unit) must lie somewhere inside the interval
    79         // ]w_low; w_high[ (often written as "(w_low; w_high)")
    80        
    81         // Basically the buffer currently contains a number in the unsafe interval
    82         // ]too_low; too_high[ with too_low < w < too_high
    83         //
    84         //  too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    85         //                     ^v 1 unit            ^      ^                 ^      ^
    86         //  boundary_high ---------------------     .      .                 .      .
    87         //                     ^v 1 unit            .      .                 .      .
    88         //   - - - - - - - - - - - - - - - - - - -  +  - - + - - - - - -     .      .
    89         //                                          .      .         ^       .      .
    90         //                                          .  big_distance  .       .      .
    91         //                                          .      .         .       .    rest
    92         //                              small_distance     .         .       .      .
    93         //                                          v      .         .       .      .
    94         //  w_high - - - - - - - - - - - - - - - - - -     .         .       .      .
    95         //                     ^v 1 unit                   .         .       .      .
    96         //  w ----------------------------------------     .         .       .      .
    97         //                     ^v 1 unit                   v         .       .      .
    98         //  w_low  - - - - - - - - - - - - - - - - - - - - -         .       .      .
    99         //                                                           .       .      v
    100         //  buffer --------------------------------------------------+-------+--------
    101         //                                                           .       .
    102         //                                                  safe_interval    .
    103         //                                                           v       .
    104         //   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -     .
    105         //                     ^v 1 unit                                     .
    106         //  boundary_low -------------------------                     unsafe_interval
    107         //                     ^v 1 unit                                     v
    108         //  too_low  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    109         //
    110         //
    111         // Note that the value of buffer could lie anywhere inside the range too_low
    112         // to too_high.
    113         //
    114         // boundary_low, boundary_high and w are approximations of the real boundaries
    115         // and v (the input number). They are guaranteed to be precise up to one unit.
    116         // In fact the error is guaranteed to be strictly less than one unit.
    117         //
    118         // Anything that lies outside the unsafe interval is guaranteed not to round
    119         // to v when read again.
    120         // Anything that lies inside the safe interval is guaranteed to round to v
    121         // when read again.
    122         // If the number inside the buffer lies inside the unsafe interval but not
    123         // inside the safe interval then we simply do not know and bail out (returning
    124         // false).
    125         //
    126         // Similarly we have to take into account the imprecision of 'w' when finding
    127         // the closest representation of 'w'. If we have two potential
    128         // representations, and one is closer to both w_low and w_high, then we know
    129         // it is closer to the actual value v.
    130         //
    131         // By generating the digits of too_high we got the largest (closest to
    132         // too_high) buffer that is still in the unsafe interval. In the case where
    133         // w_high < buffer < too_high we try to decrement the buffer.
    134         // This way the buffer approaches (rounds towards) w.
    135         // There are 3 conditions that stop the decrementation process:
    136         //   1) the buffer is already below w_high
    137         //   2) decrementing the buffer would make it leave the unsafe interval
    138         //   3) decrementing the buffer would yield a number below w_high and farther
    139         //      away than the current number. In other words:
    140         //              (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
    141         // Instead of using the buffer directly we use its distance to too_high.
    142         // Conceptually rest ~= too_high - buffer
    143         // We need to do the following tests in this order to avoid over- and
    144         // underflows.
    145         ASSERT(rest <= unsafe_interval);
    146         while (rest < small_distance &&  // Negated condition 1
    147                unsafe_interval - rest >= ten_kappa &&  // Negated condition 2
    148                (rest + ten_kappa < small_distance ||  // buffer{-1} > w_high
    149                 small_distance - rest >= rest + ten_kappa - small_distance)) {
    150                    buffer[length - 1]--;
    151                    rest += ten_kappa;
    152                }
    153        
    154         // We have approached w+ as much as possible. We now test if approaching w-
    155         // would require changing the buffer. If yes, then we have two possible
    156         // representations close to w, but we cannot decide which one is closer.
    157         if (rest < big_distance &&
    158             unsafe_interval - rest >= ten_kappa &&
    159             (rest + ten_kappa < big_distance ||
    160              big_distance - rest > rest + ten_kappa - big_distance)) {
    161                 return false;
    162             }
    163        
    164         // Weeding test.
    165         //   The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
    166         //   Since too_low = too_high - unsafe_interval this is equivalent to
    167         //      [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
    168         //   Conceptually we have: rest ~= too_high - buffer
    169         return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit);
     38
     39// The minimal and maximal target exponent define the range of w's binary
     40// exponent, where 'w' is the result of multiplying the input by a cached power
     41// of ten.
     42//
     43// A different range might be chosen on a different platform, to optimize digit
     44// generation, but a smaller range requires more powers of ten to be cached.
     45static const int kMinimalTargetExponent = -60;
     46static const int kMaximalTargetExponent = -32;
     47
     48
     49// Adjusts the last digit of the generated number, and screens out generated
     50// solutions that may be inaccurate. A solution may be inaccurate if it is
     51// outside the safe interval, or if we cannot prove that it is closer to the
     52// input than a neighboring representation of the same length.
     53//
     54// Input: * buffer containing the digits of too_high / 10^kappa
     55//        * the buffer's length
     56//        * distance_too_high_w == (too_high - w).f() * unit
     57//        * unsafe_interval == (too_high - too_low).f() * unit
     58//        * rest = (too_high - buffer * 10^kappa).f() * unit
     59//        * ten_kappa = 10^kappa * unit
     60//        * unit = the common multiplier
     61// Output: returns true if the buffer is guaranteed to contain the closest
     62//    representable number to the input.
     63//  Modifies the generated digits in the buffer to approach (round towards) w.
     64static bool RoundWeed(BufferReference<char> buffer,
     65                      int length,
     66                      uint64_t distance_too_high_w,
     67                      uint64_t unsafe_interval,
     68                      uint64_t rest,
     69                      uint64_t ten_kappa,
     70                      uint64_t unit) {
     71  uint64_t small_distance = distance_too_high_w - unit;
     72  uint64_t big_distance = distance_too_high_w + unit;
     73  // Let w_low  = too_high - big_distance, and
     74  //     w_high = too_high - small_distance.
     75  // Note: w_low < w < w_high
     76  //
     77  // The real w (* unit) must lie somewhere inside the interval
     78  // ]w_low; w_high[ (often written as "(w_low; w_high)")
     79
     80  // Basically the buffer currently contains a number in the unsafe interval
     81  // ]too_low; too_high[ with too_low < w < too_high
     82  //
     83  //  too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     84  //                     ^v 1 unit            ^      ^                 ^      ^
     85  //  boundary_high ---------------------     .      .                 .      .
     86  //                     ^v 1 unit            .      .                 .      .
     87  //   - - - - - - - - - - - - - - - - - - -  +  - - + - - - - - -     .      .
     88  //                                          .      .         ^       .      .
     89  //                                          .  big_distance  .       .      .
     90  //                                          .      .         .       .    rest
     91  //                              small_distance     .         .       .      .
     92  //                                          v      .         .       .      .
     93  //  w_high - - - - - - - - - - - - - - - - - -     .         .       .      .
     94  //                     ^v 1 unit                   .         .       .      .
     95  //  w ----------------------------------------     .         .       .      .
     96  //                     ^v 1 unit                   v         .       .      .
     97  //  w_low  - - - - - - - - - - - - - - - - - - - - -         .       .      .
     98  //                                                           .       .      v
     99  //  buffer --------------------------------------------------+-------+--------
     100  //                                                           .       .
     101  //                                                  safe_interval    .
     102  //                                                           v       .
     103  //   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -     .
     104  //                     ^v 1 unit                                     .
     105  //  boundary_low -------------------------                     unsafe_interval
     106  //                     ^v 1 unit                                     v
     107  //  too_low  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     108  //
     109  //
     110  // Note that the value of buffer could lie anywhere inside the range too_low
     111  // to too_high.
     112  //
     113  // boundary_low, boundary_high and w are approximations of the real boundaries
     114  // and v (the input number). They are guaranteed to be precise up to one unit.
     115  // In fact the error is guaranteed to be strictly less than one unit.
     116  //
     117  // Anything that lies outside the unsafe interval is guaranteed not to round
     118  // to v when read again.
     119  // Anything that lies inside the safe interval is guaranteed to round to v
     120  // when read again.
     121  // If the number inside the buffer lies inside the unsafe interval but not
     122  // inside the safe interval then we simply do not know and bail out (returning
     123  // false).
     124  //
     125  // Similarly we have to take into account the imprecision of 'w' when finding
     126  // the closest representation of 'w'. If we have two potential
     127  // representations, and one is closer to both w_low and w_high, then we know
     128  // it is closer to the actual value v.
     129  //
     130  // By generating the digits of too_high we got the largest (closest to
     131  // too_high) buffer that is still in the unsafe interval. In the case where
     132  // w_high < buffer < too_high we try to decrement the buffer.
     133  // This way the buffer approaches (rounds towards) w.
     134  // There are 3 conditions that stop the decrementation process:
     135  //   1) the buffer is already below w_high
     136  //   2) decrementing the buffer would make it leave the unsafe interval
     137  //   3) decrementing the buffer would yield a number below w_high and farther
     138  //      away than the current number. In other words:
     139  //              (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
     140  // Instead of using the buffer directly we use its distance to too_high.
     141  // Conceptually rest ~= too_high - buffer
     142  // We need to do the following tests in this order to avoid over- and
     143  // underflows.
     144  ASSERT(rest <= unsafe_interval);
     145  while (rest < small_distance &&  // Negated condition 1
     146         unsafe_interval - rest >= ten_kappa &&  // Negated condition 2
     147         (rest + ten_kappa < small_distance ||  // buffer{-1} > w_high
     148          small_distance - rest >= rest + ten_kappa - small_distance)) {
     149    buffer[length - 1]--;
     150    rest += ten_kappa;
     151  }
     152
     153  // We have approached w+ as much as possible. We now test if approaching w-
     154  // would require changing the buffer. If yes, then we have two possible
     155  // representations close to w, but we cannot decide which one is closer.
     156  if (rest < big_distance &&
     157      unsafe_interval - rest >= ten_kappa &&
     158      (rest + ten_kappa < big_distance ||
     159       big_distance - rest > rest + ten_kappa - big_distance)) {
     160    return false;
     161  }
     162
     163  // Weeding test.
     164  //   The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
     165  //   Since too_low = too_high - unsafe_interval this is equivalent to
     166  //      [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
     167  //   Conceptually we have: rest ~= too_high - buffer
     168  return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit);
     169}
     170
     171
     172// Rounds the buffer upwards if the result is closer to v by possibly adding
     173// 1 to the buffer. If the precision of the calculation is not sufficient to
     174// round correctly, return false.
     175// The rounding might shift the whole buffer in which case the kappa is
     176// adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
     177//
     178// If 2*rest > ten_kappa then the buffer needs to be round up.
     179// rest can have an error of +/- 1 unit. This function accounts for the
     180// imprecision and returns false, if the rounding direction cannot be
     181// unambiguously determined.
     182//
     183// Precondition: rest < ten_kappa.
     184static bool RoundWeedCounted(BufferReference<char> buffer,
     185                             int length,
     186                             uint64_t rest,
     187                             uint64_t ten_kappa,
     188                             uint64_t unit,
     189                             int* kappa) {
     190  ASSERT(rest < ten_kappa);
     191  // The following tests are done in a specific order to avoid overflows. They
     192  // will work correctly with any uint64 values of rest < ten_kappa and unit.
     193  //
     194  // If the unit is too big, then we don't know which way to round. For example
     195  // a unit of 50 means that the real number lies within rest +/- 50. If
     196  // 10^kappa == 40 then there is no way to tell which way to round.
     197  if (unit >= ten_kappa) return false;
     198  // Even if unit is just half the size of 10^kappa we are already completely
     199  // lost. (And after the previous test we know that the expression will not
     200  // over/underflow.)
     201  if (ten_kappa - unit <= unit) return false;
     202  // If 2 * (rest + unit) <= 10^kappa we can safely round down.
     203  if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit)) {
     204    return true;
     205  }
     206  // If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
     207  if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit))) {
     208    // Increment the last digit recursively until we find a non '9' digit.
     209    buffer[length - 1]++;
     210    for (int i = length - 1; i > 0; --i) {
     211      if (buffer[i] != '0' + 10) break;
     212      buffer[i] = '0';
     213      buffer[i - 1]++;
    170214    }
    171    
    172    
    173     // Rounds the buffer upwards if the result is closer to v by possibly adding
    174     // 1 to the buffer. If the precision of the calculation is not sufficient to
    175     // round correctly, return false.
    176     // The rounding might shift the whole buffer in which case the kappa is
    177     // adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
    178     //
    179     // If 2*rest > ten_kappa then the buffer needs to be round up.
    180     // rest can have an error of +/- 1 unit. This function accounts for the
    181     // imprecision and returns false, if the rounding direction cannot be
    182     // unambiguously determined.
    183     //
    184     // Precondition: rest < ten_kappa.
    185     static bool RoundWeedCounted(BufferReference<char> buffer,
    186                                  int length,
    187                                  uint64_t rest,
    188                                  uint64_t ten_kappa,
    189                                  uint64_t unit,
    190                                  int* kappa) {
    191         ASSERT(rest < ten_kappa);
    192         // The following tests are done in a specific order to avoid overflows. They
    193         // will work correctly with any uint64 values of rest < ten_kappa and unit.
    194         //
    195         // If the unit is too big, then we don't know which way to round. For example
    196         // a unit of 50 means that the real number lies within rest +/- 50. If
    197         // 10^kappa == 40 then there is no way to tell which way to round.
    198         if (unit >= ten_kappa) return false;
    199         // Even if unit is just half the size of 10^kappa we are already completely
    200         // lost. (And after the previous test we know that the expression will not
    201         // over/underflow.)
    202         if (ten_kappa - unit <= unit) return false;
    203         // If 2 * (rest + unit) <= 10^kappa we can safely round down.
    204         if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit)) {
    205             return true;
    206         }
    207         // If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
    208         if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit))) {
    209             // Increment the last digit recursively until we find a non '9' digit.
    210             buffer[length - 1]++;
    211             for (int i = length - 1; i > 0; --i) {
    212                 if (buffer[i] != '0' + 10) break;
    213                 buffer[i] = '0';
    214                 buffer[i - 1]++;
    215             }
    216             // If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
    217             // exception of the first digit all digits are now '0'. Simply switch the
    218             // first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
    219             // the power (the kappa) is increased.
    220             if (buffer[0] == '0' + 10) {
    221                 buffer[0] = '1';
    222                 (*kappa) += 1;
    223             }
    224             return true;
    225         }
    226         return false;
     215    // If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
     216    // exception of the first digit all digits are now '0'. Simply switch the
     217    // first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
     218    // the power (the kappa) is increased.
     219    if (buffer[0] == '0' + 10) {
     220      buffer[0] = '1';
     221      (*kappa) += 1;
    227222    }
    228    
    229    
    230     static const uint32_t kTen4 = 10000;
    231     static const uint32_t kTen5 = 100000;
    232     static const uint32_t kTen6 = 1000000;
    233     static const uint32_t kTen7 = 10000000;
    234     static const uint32_t kTen8 = 100000000;
    235     static const uint32_t kTen9 = 1000000000;
    236    
    237     // Returns the biggest power of ten that is less than or equal to the given
    238     // number. We furthermore receive the maximum number of bits 'number' has.
    239     // If number_bits == 0 then 0^-1 is returned
    240     // The number of bits must be <= 32.
    241     // Precondition: number < (1 << (number_bits + 1)).
    242     static void BiggestPowerTen(uint32_t number,
    243                                 int number_bits,
    244                                 uint32_t* power,
    245                                 int* exponent) {
    246         ASSERT(number < (uint32_t)(1 << (number_bits + 1)));
    247        
    248         switch (number_bits) {
    249             case 32:
    250             case 31:
    251             case 30:
    252                 if (kTen9 <= number) {
    253                     *power = kTen9;
    254                     *exponent = 9;
    255                     break;
    256                 }
    257                 FALLTHROUGH;
    258             case 29:
    259             case 28:
    260             case 27:
    261                 if (kTen8 <= number) {
    262                     *power = kTen8;
    263                     *exponent = 8;
    264                     break;
    265                 }
    266                 FALLTHROUGH;
    267             case 26:
    268             case 25:
    269             case 24:
    270                 if (kTen7 <= number) {
    271                     *power = kTen7;
    272                     *exponent = 7;
    273                     break;
    274                 }
    275                 FALLTHROUGH;
    276             case 23:
    277             case 22:
    278             case 21:
    279             case 20:
    280                 if (kTen6 <= number) {
    281                     *power = kTen6;
    282                     *exponent = 6;
    283                     break;
    284                 }
    285                 FALLTHROUGH;
    286             case 19:
    287             case 18:
    288             case 17:
    289                 if (kTen5 <= number) {
    290                     *power = kTen5;
    291                     *exponent = 5;
    292                     break;
    293                 }
    294                 FALLTHROUGH;
    295             case 16:
    296             case 15:
    297             case 14:
    298                 if (kTen4 <= number) {
    299                     *power = kTen4;
    300                     *exponent = 4;
    301                     break;
    302                 }
    303                 FALLTHROUGH;
    304             case 13:
    305             case 12:
    306             case 11:
    307             case 10:
    308                 if (1000 <= number) {
    309                     *power = 1000;
    310                     *exponent = 3;
    311                     break;
    312                 }
    313                 FALLTHROUGH;
    314             case 9:
    315             case 8:
    316             case 7:
    317                 if (100 <= number) {
    318                     *power = 100;
    319                     *exponent = 2;
    320                     break;
    321                 }
    322                 FALLTHROUGH;
    323             case 6:
    324             case 5:
    325             case 4:
    326                 if (10 <= number) {
    327                     *power = 10;
    328                     *exponent = 1;
    329                     break;
    330                 }
    331                 FALLTHROUGH;
    332             case 3:
    333             case 2:
    334             case 1:
    335                 if (1 <= number) {
    336                     *power = 1;
    337                     *exponent = 0;
    338                     break;
    339                 }
    340                 FALLTHROUGH;
    341             case 0:
    342                 *power = 0;
    343                 *exponent = -1;
    344                 break;
    345             default:
    346                 // Following assignments are here to silence compiler warnings.
    347                 *power = 0;
    348                 *exponent = 0;
    349                 UNREACHABLE();
    350         }
     223    return true;
     224  }
     225  return false;
     226}
     227
     228// Returns the biggest power of ten that is less than or equal to the given
     229// number. We furthermore receive the maximum number of bits 'number' has.
     230//
     231// Returns power == 10^(exponent_plus_one-1) such that
     232//    power <= number < power * 10.
     233// If number_bits == 0 then 0^(0-1) is returned.
     234// The number of bits must be <= 32.
     235// Precondition: number < (1 << (number_bits + 1)).
     236
     237// Inspired by the method for finding an integer log base 10 from here:
     238// http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
     239static unsigned int const kSmallPowersOfTen[] =
     240    {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
     241     1000000000};
     242
     243static void BiggestPowerTen(uint32_t number,
     244                            int number_bits,
     245                            uint32_t* power,
     246                            int* exponent_plus_one) {
     247  ASSERT(number < (1u << (number_bits + 1)));
     248  // 1233/4096 is approximately 1/lg(10).
     249  int exponent_plus_one_guess = ((number_bits + 1) * 1233 >> 12);
     250  // We increment to skip over the first entry in the kPowersOf10 table.
     251  // Note: kPowersOf10[i] == 10^(i-1).
     252  exponent_plus_one_guess++;
     253  // We don't have any guarantees that 2^number_bits <= number.
     254  if (number < kSmallPowersOfTen[exponent_plus_one_guess]) {
     255    exponent_plus_one_guess--;
     256  }
     257  *power = kSmallPowersOfTen[exponent_plus_one_guess];
     258  *exponent_plus_one = exponent_plus_one_guess;
     259}
     260
     261// Generates the digits of input number w.
     262// w is a floating-point number (DiyFp), consisting of a significand and an
     263// exponent. Its exponent is bounded by kMinimalTargetExponent and
     264// kMaximalTargetExponent.
     265//       Hence -60 <= w.e() <= -32.
     266//
     267// Returns false if it fails, in which case the generated digits in the buffer
     268// should not be used.
     269// Preconditions:
     270//  * low, w and high are correct up to 1 ulp (unit in the last place). That
     271//    is, their error must be less than a unit of their last digits.
     272//  * low.e() == w.e() == high.e()
     273//  * low < w < high, and taking into account their error: low~ <= high~
     274//  * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
     275// Postconditions: returns false if procedure fails.
     276//   otherwise:
     277//     * buffer is not null-terminated, but len contains the number of digits.
     278//     * buffer contains the shortest possible decimal digit-sequence
     279//       such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
     280//       correct values of low and high (without their error).
     281//     * if more than one decimal representation gives the minimal number of
     282//       decimal digits then the one closest to W (where W is the correct value
     283//       of w) is chosen.
     284// Remark: this procedure takes into account the imprecision of its input
     285//   numbers. If the precision is not enough to guarantee all the postconditions
     286//   then false is returned. This usually happens rarely (~0.5%).
     287//
     288// Say, for the sake of example, that
     289//   w.e() == -48, and w.f() == 0x1234567890abcdef
     290// w's value can be computed by w.f() * 2^w.e()
     291// We can obtain w's integral digits by simply shifting w.f() by -w.e().
     292//  -> w's integral part is 0x1234
     293//  w's fractional part is therefore 0x567890abcdef.
     294// Printing w's integral part is easy (simply print 0x1234 in decimal).
     295// In order to print its fraction we repeatedly multiply the fraction by 10 and
     296// get each digit. Example the first digit after the point would be computed by
     297//   (0x567890abcdef * 10) >> 48. -> 3
     298// The whole thing becomes slightly more complicated because we want to stop
     299// once we have enough digits. That is, once the digits inside the buffer
     300// represent 'w' we can stop. Everything inside the interval low - high
     301// represents w. However we have to pay attention to low, high and w's
     302// imprecision.
     303static bool DigitGen(DiyFp low,
     304                     DiyFp w,
     305                     DiyFp high,
     306                     BufferReference<char> buffer,
     307                     int* length,
     308                     int* kappa) {
     309  ASSERT(low.e() == w.e() && w.e() == high.e());
     310  ASSERT(low.f() + 1 <= high.f() - 1);
     311  ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
     312  // low, w and high are imprecise, but by less than one ulp (unit in the last
     313  // place).
     314  // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
     315  // the new numbers are outside of the interval we want the final
     316  // representation to lie in.
     317  // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
     318  // numbers that are certain to lie in the interval. We will use this fact
     319  // later on.
     320  // We will now start by generating the digits within the uncertain
     321  // interval. Later we will weed out representations that lie outside the safe
     322  // interval and thus _might_ lie outside the correct interval.
     323  uint64_t unit = 1;
     324  DiyFp too_low = DiyFp(low.f() - unit, low.e());
     325  DiyFp too_high = DiyFp(high.f() + unit, high.e());
     326  // too_low and too_high are guaranteed to lie outside the interval we want the
     327  // generated number in.
     328  DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low);
     329  // We now cut the input number into two parts: the integral digits and the
     330  // fractionals. We will not write any decimal separator though, but adapt
     331  // kappa instead.
     332  // Reminder: we are currently computing the digits (stored inside the buffer)
     333  // such that:   too_low < buffer * 10^kappa < too_high
     334  // We use too_high for the digit_generation and stop as soon as possible.
     335  // If we stop early we effectively round down.
     336  DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
     337  // Division by one is a shift.
     338  uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e());
     339  // Modulo by one is an and.
     340  uint64_t fractionals = too_high.f() & (one.f() - 1);
     341  uint32_t divisor;
     342  int divisor_exponent_plus_one;
     343  BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
     344                  &divisor, &divisor_exponent_plus_one);
     345  *kappa = divisor_exponent_plus_one;
     346  *length = 0;
     347  // Loop invariant: buffer = too_high / 10^kappa  (integer division)
     348  // The invariant holds for the first iteration: kappa has been initialized
     349  // with the divisor exponent + 1. And the divisor is the biggest power of ten
     350  // that is smaller than integrals.
     351  while (*kappa > 0) {
     352    int digit = integrals / divisor;
     353    ASSERT(digit <= 9);
     354    buffer[*length] = static_cast<char>('0' + digit);
     355    (*length)++;
     356    integrals %= divisor;
     357    (*kappa)--;
     358    // Note that kappa now equals the exponent of the divisor and that the
     359    // invariant thus holds again.
     360    uint64_t rest =
     361        (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
     362    // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
     363    // Reminder: unsafe_interval.e() == one.e()
     364    if (rest < unsafe_interval.f()) {
     365      // Rounding down (by not emitting the remaining digits) yields a number
     366      // that lies within the unsafe interval.
     367      return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(),
     368                       unsafe_interval.f(), rest,
     369                       static_cast<uint64_t>(divisor) << -one.e(), unit);
    351370    }
    352    
    353    
    354     // Generates the digits of input number w.
    355     // w is a floating-point number (DiyFp), consisting of a significand and an
    356     // exponent. Its exponent is bounded by kMinimalTargetExponent and
    357     // kMaximalTargetExponent.
    358     //       Hence -60 <= w.e() <= -32.
    359     //
    360     // Returns false if it fails, in which case the generated digits in the buffer
    361     // should not be used.
    362     // Preconditions:
    363     //  * low, w and high are correct up to 1 ulp (unit in the last place). That
    364     //    is, their error must be less than a unit of their last digits.
    365     //  * low.e() == w.e() == high.e()
    366     //  * low < w < high, and taking into account their error: low~ <= high~
    367     //  * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
    368     // Postconditions: returns false if procedure fails.
    369     //   otherwise:
    370     //     * buffer is not null-terminated, but len contains the number of digits.
    371     //     * buffer contains the shortest possible decimal digit-sequence
    372     //       such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
    373     //       correct values of low and high (without their error).
    374     //     * if more than one decimal representation gives the minimal number of
    375     //       decimal digits then the one closest to W (where W is the correct value
    376     //       of w) is chosen.
    377     // Remark: this procedure takes into account the imprecision of its input
    378     //   numbers. If the precision is not enough to guarantee all the postconditions
    379     //   then false is returned. This usually happens rarely (~0.5%).
    380     //
    381     // Say, for the sake of example, that
    382     //   w.e() == -48, and w.f() == 0x1234567890abcdef
    383     // w's value can be computed by w.f() * 2^w.e()
    384     // We can obtain w's integral digits by simply shifting w.f() by -w.e().
    385     //  -> w's integral part is 0x1234
    386     //  w's fractional part is therefore 0x567890abcdef.
    387     // Printing w's integral part is easy (simply print 0x1234 in decimal).
    388     // In order to print its fraction we repeatedly multiply the fraction by 10 and
    389     // get each digit. Example the first digit after the point would be computed by
    390     //   (0x567890abcdef * 10) >> 48. -> 3
    391     // The whole thing becomes slightly more complicated because we want to stop
    392     // once we have enough digits. That is, once the digits inside the buffer
    393     // represent 'w' we can stop. Everything inside the interval low - high
    394     // represents w. However we have to pay attention to low, high and w's
    395     // imprecision.
    396     static bool DigitGen(DiyFp low,
    397                          DiyFp w,
    398                          DiyFp high,
    399                          BufferReference<char> buffer,
    400                          int* length,
    401                          int* kappa) {
    402         ASSERT(low.e() == w.e() && w.e() == high.e());
    403         ASSERT(low.f() + 1 <= high.f() - 1);
    404         ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
    405         // low, w and high are imprecise, but by less than one ulp (unit in the last
    406         // place).
    407         // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
    408         // the new numbers are outside of the interval we want the final
    409         // representation to lie in.
    410         // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
    411         // numbers that are certain to lie in the interval. We will use this fact
    412         // later on.
    413         // We will now start by generating the digits within the uncertain
    414         // interval. Later we will weed out representations that lie outside the safe
    415         // interval and thus _might_ lie outside the correct interval.
    416         uint64_t unit = 1;
    417         DiyFp too_low = DiyFp(low.f() - unit, low.e());
    418         DiyFp too_high = DiyFp(high.f() + unit, high.e());
    419         // too_low and too_high are guaranteed to lie outside the interval we want the
    420         // generated number in.
    421         DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low);
    422         // We now cut the input number into two parts: the integral digits and the
    423         // fractionals. We will not write any decimal separator though, but adapt
    424         // kappa instead.
    425         // Reminder: we are currently computing the digits (stored inside the buffer)
    426         // such that:   too_low < buffer * 10^kappa < too_high
    427         // We use too_high for the digit_generation and stop as soon as possible.
    428         // If we stop early we effectively round down.
    429         DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
    430         // Division by one is a shift.
    431         uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e());
    432         // Modulo by one is an and.
    433         uint64_t fractionals = too_high.f() & (one.f() - 1);
    434         uint32_t divisor;
    435         int divisor_exponent;
    436         BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
    437                         &divisor, &divisor_exponent);
    438         *kappa = divisor_exponent + 1;
    439         *length = 0;
    440         // Loop invariant: buffer = too_high / 10^kappa  (integer division)
    441         // The invariant holds for the first iteration: kappa has been initialized
    442         // with the divisor exponent + 1. And the divisor is the biggest power of ten
    443         // that is smaller than integrals.
    444         while (*kappa > 0) {
    445             int digit = integrals / divisor;
    446             buffer[*length] = '0' + digit;
    447             (*length)++;
    448             integrals %= divisor;
    449             (*kappa)--;
    450             // Note that kappa now equals the exponent of the divisor and that the
    451             // invariant thus holds again.
    452             uint64_t rest =
    453             (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
    454             // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
    455             // Reminder: unsafe_interval.e() == one.e()
    456             if (rest < unsafe_interval.f()) {
    457                 // Rounding down (by not emitting the remaining digits) yields a number
    458                 // that lies within the unsafe interval.
    459                 return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(),
    460                                  unsafe_interval.f(), rest,
    461                                  static_cast<uint64_t>(divisor) << -one.e(), unit);
    462             }
    463             divisor /= 10;
    464         }
    465        
    466         // The integrals have been generated. We are at the point of the decimal
    467         // separator. In the following loop we simply multiply the remaining digits by
    468         // 10 and divide by one. We just need to pay attention to multiply associated
    469         // data (like the interval or 'unit'), too.
    470         // Note that the multiplication by 10 does not overflow, because w.e >= -60
    471         // and thus one.e >= -60.
    472         ASSERT(one.e() >= -60);
    473         ASSERT(fractionals < one.f());
    474         ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
    475         while (true) {
    476             fractionals *= 10;
    477             unit *= 10;
    478             unsafe_interval.set_f(unsafe_interval.f() * 10);
    479             // Integer division by one.
    480             int digit = static_cast<int>(fractionals >> -one.e());
    481             buffer[*length] = '0' + digit;
    482             (*length)++;
    483             fractionals &= one.f() - 1;  // Modulo by one.
    484             (*kappa)--;
    485             if (fractionals < unsafe_interval.f()) {
    486                 return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit,
    487                                  unsafe_interval.f(), fractionals, one.f(), unit);
    488             }
    489         }
     371    divisor /= 10;
     372  }
     373
     374  // The integrals have been generated. We are at the point of the decimal
     375  // separator. In the following loop we simply multiply the remaining digits by
     376  // 10 and divide by one. We just need to pay attention to multiply associated
     377  // data (like the interval or 'unit'), too.
     378  // Note that the multiplication by 10 does not overflow, because w.e >= -60
     379  // and thus one.e >= -60.
     380  ASSERT(one.e() >= -60);
     381  ASSERT(fractionals < one.f());
     382  ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
     383  for (;;) {
     384    fractionals *= 10;
     385    unit *= 10;
     386    unsafe_interval.set_f(unsafe_interval.f() * 10);
     387    // Integer division by one.
     388    int digit = static_cast<int>(fractionals >> -one.e());
     389    ASSERT(digit <= 9);
     390    buffer[*length] = static_cast<char>('0' + digit);
     391    (*length)++;
     392    fractionals &= one.f() - 1;  // Modulo by one.
     393    (*kappa)--;
     394    if (fractionals < unsafe_interval.f()) {
     395      return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit,
     396                       unsafe_interval.f(), fractionals, one.f(), unit);
    490397    }
    491    
    492    
    493    
    494     // Generates (at most) requested_digits digits of input number w.
    495     // w is a floating-point number (DiyFp), consisting of a significand and an
    496     // exponent. Its exponent is bounded by kMinimalTargetExponent and
    497     // kMaximalTargetExponent.
    498     //       Hence -60 <= w.e() <= -32.
    499     //
    500     // Returns false if it fails, in which case the generated digits in the buffer
    501     // should not be used.
    502     // Preconditions:
    503     //  * w is correct up to 1 ulp (unit in the last place). That
    504     //    is, its error must be strictly less than a unit of its last digit.
    505     //  * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
    506     //
    507     // Postconditions: returns false if procedure fails.
    508     //   otherwise:
    509     //     * buffer is not null-terminated, but length contains the number of
    510     //       digits.
    511     //     * the representation in buffer is the most precise representation of
    512     //       requested_digits digits.
    513     //     * buffer contains at most requested_digits digits of w. If there are less
    514     //       than requested_digits digits then some trailing '0's have been removed.
    515     //     * kappa is such that
    516     //            w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
    517     //
    518     // Remark: This procedure takes into account the imprecision of its input
    519     //   numbers. If the precision is not enough to guarantee all the postconditions
    520     //   then false is returned. This usually happens rarely, but the failure-rate
    521     //   increases with higher requested_digits.
    522     static bool DigitGenCounted(DiyFp w,
    523                                 int requested_digits,
    524                                 BufferReference<char> buffer,
    525                                 int* length,
    526                                 int* kappa) {
    527         ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
    528         ASSERT(kMinimalTargetExponent >= -60);
    529         ASSERT(kMaximalTargetExponent <= -32);
    530         // w is assumed to have an error less than 1 unit. Whenever w is scaled we
    531         // also scale its error.
    532         uint64_t w_error = 1;
    533         // We cut the input number into two parts: the integral digits and the
    534         // fractional digits. We don't emit any decimal separator, but adapt kappa
    535         // instead. Example: instead of writing "1.2" we put "12" into the buffer and
    536         // increase kappa by 1.
    537         DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
    538         // Division by one is a shift.
    539         uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e());
    540         // Modulo by one is an and.
    541         uint64_t fractionals = w.f() & (one.f() - 1);
    542         uint32_t divisor;
    543         int divisor_exponent;
    544         BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
    545                         &divisor, &divisor_exponent);
    546         *kappa = divisor_exponent + 1;
    547         *length = 0;
    548        
    549         // Loop invariant: buffer = w / 10^kappa  (integer division)
    550         // The invariant holds for the first iteration: kappa has been initialized
    551         // with the divisor exponent + 1. And the divisor is the biggest power of ten
    552         // that is smaller than 'integrals'.
    553         while (*kappa > 0) {
    554             int digit = integrals / divisor;
    555             buffer[*length] = '0' + digit;
    556             (*length)++;
    557             requested_digits--;
    558             integrals %= divisor;
    559             (*kappa)--;
    560             // Note that kappa now equals the exponent of the divisor and that the
    561             // invariant thus holds again.
    562             if (requested_digits == 0) break;
    563             divisor /= 10;
    564         }
    565        
    566         if (requested_digits == 0) {
    567             uint64_t rest =
    568             (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
    569             return RoundWeedCounted(buffer, *length, rest,
    570                                     static_cast<uint64_t>(divisor) << -one.e(), w_error,
    571                                     kappa);
    572         }
    573        
    574         // The integrals have been generated. We are at the point of the decimal
    575         // separator. In the following loop we simply multiply the remaining digits by
    576         // 10 and divide by one. We just need to pay attention to multiply associated
    577         // data (the 'unit'), too.
    578         // Note that the multiplication by 10 does not overflow, because w.e >= -60
    579         // and thus one.e >= -60.
    580         ASSERT(one.e() >= -60);
    581         ASSERT(fractionals < one.f());
    582         ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
    583         while (requested_digits > 0 && fractionals > w_error) {
    584             fractionals *= 10;
    585             w_error *= 10;
    586             // Integer division by one.
    587             int digit = static_cast<int>(fractionals >> -one.e());
    588             buffer[*length] = '0' + digit;
    589             (*length)++;
    590             requested_digits--;
    591             fractionals &= one.f() - 1;  // Modulo by one.
    592             (*kappa)--;
    593         }
    594         if (requested_digits != 0) return false;
    595         return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error,
    596                                 kappa);
    597     }
    598    
    599    
    600     // Provides a decimal representation of v.
    601     // Returns true if it succeeds, otherwise the result cannot be trusted.
    602     // There will be *length digits inside the buffer (not null-terminated).
    603     // If the function returns true then
    604     //        v == (double) (buffer * 10^decimal_exponent).
    605     // The digits in the buffer are the shortest representation possible: no
    606     // 0.09999999999999999 instead of 0.1. The shorter representation will even be
    607     // chosen even if the longer one would be closer to v.
    608     // The last digit will be closest to the actual v. That is, even if several
    609     // digits might correctly yield 'v' when read again, the closest will be
    610     // computed.
    611     static bool Grisu3(double v,
    612                        BufferReference<char> buffer,
    613                        int* length,
    614                        int* decimal_exponent) {
    615         DiyFp w = Double(v).AsNormalizedDiyFp();
    616         // boundary_minus and boundary_plus are the boundaries between v and its
    617         // closest floating-point neighbors. Any number strictly between
    618         // boundary_minus and boundary_plus will round to v when convert to a double.
    619         // Grisu3 will never output representations that lie exactly on a boundary.
    620         DiyFp boundary_minus, boundary_plus;
    621         Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
    622         ASSERT(boundary_plus.e() == w.e());
    623         DiyFp ten_mk;  // Cached power of ten: 10^-k
    624         int mk;        // -k
    625         int ten_mk_minimal_binary_exponent =
    626         kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
    627         int ten_mk_maximal_binary_exponent =
    628         kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
    629         PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
    630                                                                ten_mk_minimal_binary_exponent,
    631                                                                ten_mk_maximal_binary_exponent,
    632                                                                &ten_mk, &mk);
    633         ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
    634                 DiyFp::kSignificandSize) &&
    635                (kMaximalTargetExponent >= w.e() + ten_mk.e() +
    636                 DiyFp::kSignificandSize));
    637         // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
    638         // 64 bit significand and ten_mk is thus only precise up to 64 bits.
    639        
    640         // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
    641         // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
    642         // off by a small amount.
    643         // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
    644         // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
    645         //           (f-1) * 2^e < w*10^k < (f+1) * 2^e
    646         DiyFp scaled_w = DiyFp::Times(w, ten_mk);
    647         ASSERT(scaled_w.e() ==
    648                boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
    649         // In theory it would be possible to avoid some recomputations by computing
    650         // the difference between w and boundary_minus/plus (a power of 2) and to
    651         // compute scaled_boundary_minus/plus by subtracting/adding from
    652         // scaled_w. However the code becomes much less readable and the speed
    653         // enhancements are not terriffic.
    654         DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
    655         DiyFp scaled_boundary_plus  = DiyFp::Times(boundary_plus,  ten_mk);
    656        
    657         // DigitGen will generate the digits of scaled_w. Therefore we have
    658         // v == (double) (scaled_w * 10^-mk).
    659         // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
    660         // integer than it will be updated. For instance if scaled_w == 1.23 then
    661         // the buffer will be filled with "123" und the decimal_exponent will be
    662         // decreased by 2.
    663         int kappa;
    664         bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
    665                                buffer, length, &kappa);
    666         *decimal_exponent = -mk + kappa;
    667         return result;
    668     }
    669    
    670    
    671     // The "counted" version of grisu3 (see above) only generates requested_digits
    672     // number of digits. This version does not generate the shortest representation,
    673     // and with enough requested digits 0.1 will at some point print as 0.9999999...
    674     // Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
    675     // therefore the rounding strategy for halfway cases is irrelevant.
    676     static bool Grisu3Counted(double v,
    677                               int requested_digits,
    678                               BufferReference<char> buffer,
    679                               int* length,
    680                               int* decimal_exponent) {
    681         DiyFp w = Double(v).AsNormalizedDiyFp();
    682         DiyFp ten_mk;  // Cached power of ten: 10^-k
    683         int mk;        // -k
    684         int ten_mk_minimal_binary_exponent =
    685         kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
    686         int ten_mk_maximal_binary_exponent =
    687         kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
    688         PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
    689                                                                ten_mk_minimal_binary_exponent,
    690                                                                ten_mk_maximal_binary_exponent,
    691                                                                &ten_mk, &mk);
    692         ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
    693                 DiyFp::kSignificandSize) &&
    694                (kMaximalTargetExponent >= w.e() + ten_mk.e() +
    695                 DiyFp::kSignificandSize));
    696         // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
    697         // 64 bit significand and ten_mk is thus only precise up to 64 bits.
    698        
    699         // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
    700         // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
    701         // off by a small amount.
    702         // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
    703         // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
    704         //           (f-1) * 2^e < w*10^k < (f+1) * 2^e
    705         DiyFp scaled_w = DiyFp::Times(w, ten_mk);
    706        
    707         // We now have (double) (scaled_w * 10^-mk).
    708         // DigitGen will generate the first requested_digits digits of scaled_w and
    709         // return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
    710         // will not always be exactly the same since DigitGenCounted only produces a
    711         // limited number of digits.)
    712         int kappa;
    713         bool result = DigitGenCounted(scaled_w, requested_digits,
    714                                       buffer, length, &kappa);
    715         *decimal_exponent = -mk + kappa;
    716         return result;
    717     }
    718    
    719    
    720     bool FastDtoa(double v,
    721                   FastDtoaMode mode,
    722                   int requested_digits,
    723                   BufferReference<char> buffer,
    724                   int* length,
    725                   int* decimal_point) {
    726         ASSERT(v > 0);
    727         ASSERT(!Double(v).IsSpecial());
    728        
    729         bool result = false;
    730         int decimal_exponent = 0;
    731         switch (mode) {
    732             case FAST_DTOA_SHORTEST:
    733                 result = Grisu3(v, buffer, length, &decimal_exponent);
    734                 break;
    735             case FAST_DTOA_PRECISION:
    736                 result = Grisu3Counted(v, requested_digits,
    737                                        buffer, length, &decimal_exponent);
    738                 break;
    739             default:
    740                 UNREACHABLE();
    741         }
    742         if (result) {
    743             *decimal_point = *length + decimal_exponent;
    744             buffer[*length] = '\0';
    745         }
    746         return result;
    747     }
    748    
     398  }
     399}
     400
     401
     402
     403// Generates (at most) requested_digits digits of input number w.
     404// w is a floating-point number (DiyFp), consisting of a significand and an
     405// exponent. Its exponent is bounded by kMinimalTargetExponent and
     406// kMaximalTargetExponent.
     407//       Hence -60 <= w.e() <= -32.
     408//
     409// Returns false if it fails, in which case the generated digits in the buffer
     410// should not be used.
     411// Preconditions:
     412//  * w is correct up to 1 ulp (unit in the last place). That
     413//    is, its error must be strictly less than a unit of its last digit.
     414//  * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
     415//
     416// Postconditions: returns false if procedure fails.
     417//   otherwise:
     418//     * buffer is not null-terminated, but length contains the number of
     419//       digits.
     420//     * the representation in buffer is the most precise representation of
     421//       requested_digits digits.
     422//     * buffer contains at most requested_digits digits of w. If there are less
     423//       than requested_digits digits then some trailing '0's have been removed.
     424//     * kappa is such that
     425//            w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
     426//
     427// Remark: This procedure takes into account the imprecision of its input
     428//   numbers. If the precision is not enough to guarantee all the postconditions
     429//   then false is returned. This usually happens rarely, but the failure-rate
     430//   increases with higher requested_digits.
     431static bool DigitGenCounted(DiyFp w,
     432                            int requested_digits,
     433                            BufferReference<char> buffer,
     434                            int* length,
     435                            int* kappa) {
     436  ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
     437  ASSERT(kMinimalTargetExponent >= -60);
     438  ASSERT(kMaximalTargetExponent <= -32);
     439  // w is assumed to have an error less than 1 unit. Whenever w is scaled we
     440  // also scale its error.
     441  uint64_t w_error = 1;
     442  // We cut the input number into two parts: the integral digits and the
     443  // fractional digits. We don't emit any decimal separator, but adapt kappa
     444  // instead. Example: instead of writing "1.2" we put "12" into the buffer and
     445  // increase kappa by 1.
     446  DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
     447  // Division by one is a shift.
     448  uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e());
     449  // Modulo by one is an and.
     450  uint64_t fractionals = w.f() & (one.f() - 1);
     451  uint32_t divisor;
     452  int divisor_exponent_plus_one;
     453  BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
     454                  &divisor, &divisor_exponent_plus_one);
     455  *kappa = divisor_exponent_plus_one;
     456  *length = 0;
     457
     458  // Loop invariant: buffer = w / 10^kappa  (integer division)
     459  // The invariant holds for the first iteration: kappa has been initialized
     460  // with the divisor exponent + 1. And the divisor is the biggest power of ten
     461  // that is smaller than 'integrals'.
     462  while (*kappa > 0) {
     463    int digit = integrals / divisor;
     464    ASSERT(digit <= 9);
     465    buffer[*length] = static_cast<char>('0' + digit);
     466    (*length)++;
     467    requested_digits--;
     468    integrals %= divisor;
     469    (*kappa)--;
     470    // Note that kappa now equals the exponent of the divisor and that the
     471    // invariant thus holds again.
     472    if (requested_digits == 0) break;
     473    divisor /= 10;
     474  }
     475
     476  if (requested_digits == 0) {
     477    uint64_t rest =
     478        (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
     479    return RoundWeedCounted(buffer, *length, rest,
     480                            static_cast<uint64_t>(divisor) << -one.e(), w_error,
     481                            kappa);
     482  }
     483
     484  // The integrals have been generated. We are at the point of the decimal
     485  // separator. In the following loop we simply multiply the remaining digits by
     486  // 10 and divide by one. We just need to pay attention to multiply associated
     487  // data (the 'unit'), too.
     488  // Note that the multiplication by 10 does not overflow, because w.e >= -60
     489  // and thus one.e >= -60.
     490  ASSERT(one.e() >= -60);
     491  ASSERT(fractionals < one.f());
     492  ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
     493  while (requested_digits > 0 && fractionals > w_error) {
     494    fractionals *= 10;
     495    w_error *= 10;
     496    // Integer division by one.
     497    int digit = static_cast<int>(fractionals >> -one.e());
     498    ASSERT(digit <= 9);
     499    buffer[*length] = static_cast<char>('0' + digit);
     500    (*length)++;
     501    requested_digits--;
     502    fractionals &= one.f() - 1;  // Modulo by one.
     503    (*kappa)--;
     504  }
     505  if (requested_digits != 0) return false;
     506  return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error,
     507                          kappa);
     508}
     509
     510
     511// Provides a decimal representation of v.
     512// Returns true if it succeeds, otherwise the result cannot be trusted.
     513// There will be *length digits inside the buffer (not null-terminated).
     514// If the function returns true then
     515//        v == (double) (buffer * 10^decimal_exponent).
     516// The digits in the buffer are the shortest representation possible: no
     517// 0.09999999999999999 instead of 0.1. The shorter representation will even be
     518// chosen even if the longer one would be closer to v.
     519// The last digit will be closest to the actual v. That is, even if several
     520// digits might correctly yield 'v' when read again, the closest will be
     521// computed.
     522static bool Grisu3(double v,
     523                   FastDtoaMode mode,
     524                   BufferReference<char> buffer,
     525                   int* length,
     526                   int* decimal_exponent) {
     527  DiyFp w = Double(v).AsNormalizedDiyFp();
     528  // boundary_minus and boundary_plus are the boundaries between v and its
     529  // closest floating-point neighbors. Any number strictly between
     530  // boundary_minus and boundary_plus will round to v when convert to a double.
     531  // Grisu3 will never output representations that lie exactly on a boundary.
     532  DiyFp boundary_minus, boundary_plus;
     533  if (mode == FAST_DTOA_SHORTEST) {
     534    Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
     535  } else {
     536    ASSERT(mode == FAST_DTOA_SHORTEST_SINGLE);
     537    float single_v = static_cast<float>(v);
     538    Single(single_v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
     539  }
     540  ASSERT(boundary_plus.e() == w.e());
     541  DiyFp ten_mk;  // Cached power of ten: 10^-k
     542  int mk;        // -k
     543  int ten_mk_minimal_binary_exponent =
     544     kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
     545  int ten_mk_maximal_binary_exponent =
     546     kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
     547  PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
     548      ten_mk_minimal_binary_exponent,
     549      ten_mk_maximal_binary_exponent,
     550      &ten_mk, &mk);
     551  ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
     552          DiyFp::kSignificandSize) &&
     553         (kMaximalTargetExponent >= w.e() + ten_mk.e() +
     554          DiyFp::kSignificandSize));
     555  // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
     556  // 64 bit significand and ten_mk is thus only precise up to 64 bits.
     557
     558  // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
     559  // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
     560  // off by a small amount.
     561  // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
     562  // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
     563  //           (f-1) * 2^e < w*10^k < (f+1) * 2^e
     564  DiyFp scaled_w = DiyFp::Times(w, ten_mk);
     565  ASSERT(scaled_w.e() ==
     566         boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
     567  // In theory it would be possible to avoid some recomputations by computing
     568  // the difference between w and boundary_minus/plus (a power of 2) and to
     569  // compute scaled_boundary_minus/plus by subtracting/adding from
     570  // scaled_w. However the code becomes much less readable and the speed
     571  // enhancements are not terriffic.
     572  DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
     573  DiyFp scaled_boundary_plus  = DiyFp::Times(boundary_plus,  ten_mk);
     574
     575  // DigitGen will generate the digits of scaled_w. Therefore we have
     576  // v == (double) (scaled_w * 10^-mk).
     577  // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
     578  // integer than it will be updated. For instance if scaled_w == 1.23 then
     579  // the buffer will be filled with "123" und the decimal_exponent will be
     580  // decreased by 2.
     581  int kappa;
     582  bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
     583                         buffer, length, &kappa);
     584  *decimal_exponent = -mk + kappa;
     585  return result;
     586}
     587
     588
     589// The "counted" version of grisu3 (see above) only generates requested_digits
     590// number of digits. This version does not generate the shortest representation,
     591// and with enough requested digits 0.1 will at some point print as 0.9999999...
     592// Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
     593// therefore the rounding strategy for halfway cases is irrelevant.
     594static bool Grisu3Counted(double v,
     595                          int requested_digits,
     596                          BufferReference<char> buffer,
     597                          int* length,
     598                          int* decimal_exponent) {
     599  DiyFp w = Double(v).AsNormalizedDiyFp();
     600  DiyFp ten_mk;  // Cached power of ten: 10^-k
     601  int mk;        // -k
     602  int ten_mk_minimal_binary_exponent =
     603     kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
     604  int ten_mk_maximal_binary_exponent =
     605     kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
     606  PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
     607      ten_mk_minimal_binary_exponent,
     608      ten_mk_maximal_binary_exponent,
     609      &ten_mk, &mk);
     610  ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
     611          DiyFp::kSignificandSize) &&
     612         (kMaximalTargetExponent >= w.e() + ten_mk.e() +
     613          DiyFp::kSignificandSize));
     614  // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
     615  // 64 bit significand and ten_mk is thus only precise up to 64 bits.
     616
     617  // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
     618  // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
     619  // off by a small amount.
     620  // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
     621  // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
     622  //           (f-1) * 2^e < w*10^k < (f+1) * 2^e
     623  DiyFp scaled_w = DiyFp::Times(w, ten_mk);
     624
     625  // We now have (double) (scaled_w * 10^-mk).
     626  // DigitGen will generate the first requested_digits digits of scaled_w and
     627  // return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
     628  // will not always be exactly the same since DigitGenCounted only produces a
     629  // limited number of digits.)
     630  int kappa;
     631  bool result = DigitGenCounted(scaled_w, requested_digits,
     632                                buffer, length, &kappa);
     633  *decimal_exponent = -mk + kappa;
     634  return result;
     635}
     636
     637
     638bool FastDtoa(double v,
     639              FastDtoaMode mode,
     640              int requested_digits,
     641              BufferReference<char> buffer,
     642              int* length,
     643              int* decimal_point) {
     644  ASSERT(v > 0);
     645  ASSERT(!Double(v).IsSpecial());
     646
     647  bool result = false;
     648  int decimal_exponent = 0;
     649  switch (mode) {
     650    case FAST_DTOA_SHORTEST:
     651    case FAST_DTOA_SHORTEST_SINGLE:
     652      result = Grisu3(v, mode, buffer, length, &decimal_exponent);
     653      break;
     654    case FAST_DTOA_PRECISION:
     655      result = Grisu3Counted(v, requested_digits,
     656                             buffer, length, &decimal_exponent);
     657      break;
     658    default:
     659      UNREACHABLE();
     660  }
     661  if (result) {
     662    *decimal_point = *length + decimal_exponent;
     663    buffer[*length] = '\0';
     664  }
     665  return result;
     666}
     667
    749668}  // namespace double_conversion
    750 
    751 } // namespace WTF
     669}  // namespace WTF
  • trunk/Source/WTF/wtf/dtoa/fast-dtoa.h

    r147976 r242048  
    2929#define DOUBLE_CONVERSION_FAST_DTOA_H_
    3030
    31 #include "utils.h"
     31#include <wtf/dtoa/utils.h>
    3232
    3333namespace WTF {
     34namespace double_conversion {
    3435
    35 namespace double_conversion {
    36    
    37     enum FastDtoaMode {
    38         // Computes the shortest representation of the given input. The returned
    39         // result will be the most accurate number of this length. Longer
    40         // representations might be more accurate.
    41         FAST_DTOA_SHORTEST,
    42         // Computes a representation where the precision (number of digits) is
    43         // given as input. The precision is independent of the decimal point.
    44         FAST_DTOA_PRECISION
    45     };
    46    
    47     // FastDtoa will produce at most kFastDtoaMaximalLength digits. This does not
    48     // include the terminating '\0' character.
    49     static const int kFastDtoaMaximalLength = 17;
    50    
    51     // Provides a decimal representation of v.
    52     // The result should be interpreted as buffer * 10^(point - length).
    53     //
    54     // Precondition:
    55     //   * v must be a strictly positive finite double.
    56     //
    57     // Returns true if it succeeds, otherwise the result can not be trusted.
    58     // There will be *length digits inside the buffer followed by a null terminator.
    59     // If the function returns true and mode equals
    60     //   - FAST_DTOA_SHORTEST, then
    61     //     the parameter requested_digits is ignored.
    62     //     The result satisfies
    63     //         v == (double) (buffer * 10^(point - length)).
    64     //     The digits in the buffer are the shortest representation possible. E.g.
    65     //     if 0.099999999999 and 0.1 represent the same double then "1" is returned
    66     //     with point = 0.
    67     //     The last digit will be closest to the actual v. That is, even if several
    68     //     digits might correctly yield 'v' when read again, the buffer will contain
    69     //     the one closest to v.
    70     //   - FAST_DTOA_PRECISION, then
    71     //     the buffer contains requested_digits digits.
    72     //     the difference v - (buffer * 10^(point-length)) is closest to zero for
    73     //     all possible representations of requested_digits digits.
    74     //     If there are two values that are equally close, then FastDtoa returns
    75     //     false.
    76     // For both modes the buffer must be large enough to hold the result.
    77     bool FastDtoa(double d,
    78                   FastDtoaMode mode,
    79                   int requested_digits,
    80                   BufferReference<char> buffer,
    81                   int* length,
    82                   int* decimal_point);
    83    
     36enum FastDtoaMode {
     37  // Computes the shortest representation of the given input. The returned
     38  // result will be the most accurate number of this length. Longer
     39  // representations might be more accurate.
     40  FAST_DTOA_SHORTEST,
     41  // Same as FAST_DTOA_SHORTEST but for single-precision floats.
     42  FAST_DTOA_SHORTEST_SINGLE,
     43  // Computes a representation where the precision (number of digits) is
     44  // given as input. The precision is independent of the decimal point.
     45  FAST_DTOA_PRECISION
     46};
     47
     48// FastDtoa will produce at most kFastDtoaMaximalLength digits. This does not
     49// include the terminating '\0' character.
     50static const int kFastDtoaMaximalLength = 17;
     51// Same for single-precision numbers.
     52static const int kFastDtoaMaximalSingleLength = 9;
     53
     54// Provides a decimal representation of v.
     55// The result should be interpreted as buffer * 10^(point - length).
     56//
     57// Precondition:
     58//   * v must be a strictly positive finite double.
     59//
     60// Returns true if it succeeds, otherwise the result can not be trusted.
     61// There will be *length digits inside the buffer followed by a null terminator.
     62// If the function returns true and mode equals
     63//   - FAST_DTOA_SHORTEST, then
     64//     the parameter requested_digits is ignored.
     65//     The result satisfies
     66//         v == (double) (buffer * 10^(point - length)).
     67//     The digits in the buffer are the shortest representation possible. E.g.
     68//     if 0.099999999999 and 0.1 represent the same double then "1" is returned
     69//     with point = 0.
     70//     The last digit will be closest to the actual v. That is, even if several
     71//     digits might correctly yield 'v' when read again, the buffer will contain
     72//     the one closest to v.
     73//   - FAST_DTOA_PRECISION, then
     74//     the buffer contains requested_digits digits.
     75//     the difference v - (buffer * 10^(point-length)) is closest to zero for
     76//     all possible representations of requested_digits digits.
     77//     If there are two values that are equally close, then FastDtoa returns
     78//     false.
     79// For both modes the buffer must be large enough to hold the result.
     80bool FastDtoa(double d,
     81              FastDtoaMode mode,
     82              int requested_digits,
     83              BufferReference<char> buffer,
     84              int* length,
     85              int* decimal_point);
     86
    8487}  // namespace double_conversion
    85 
    86 } // namespace WTF
     88}  // namespace WTF
    8789
    8890#endif  // DOUBLE_CONVERSION_FAST_DTOA_H_
  • trunk/Source/WTF/wtf/dtoa/fixed-dtoa.cc

    r149980 r242048  
    2828#include "config.h"
    2929
    30 #include <math.h>
    31 
    32 #include "fixed-dtoa.h"
    33 #include "double.h"
     30#include <cmath>
     31
     32#include <wtf/dtoa/fixed-dtoa.h>
     33#include <wtf/dtoa/ieee.h>
    3434
    3535namespace WTF {
    36 
    3736namespace double_conversion {
    38    
    39     // Represents a 128bit type. This class should be replaced by a native type on
    40     // platforms that support 128bit integers.
    41     class UInt128 {
    42     public:
    43         UInt128() : high_bits_(0), low_bits_(0) { }
    44         UInt128(uint64_t high, uint64_t low) : high_bits_(high), low_bits_(low) { }
    45        
    46         void Multiply(uint32_t multiplicand) {
    47             uint64_t accumulator;
    48            
    49             accumulator = (low_bits_ & kMask32) * multiplicand;
    50             uint32_t part = static_cast<uint32_t>(accumulator & kMask32);
    51             accumulator >>= 32;
    52             accumulator = accumulator + (low_bits_ >> 32) * multiplicand;
    53             low_bits_ = (accumulator << 32) + part;
    54             accumulator >>= 32;
    55             accumulator = accumulator + (high_bits_ & kMask32) * multiplicand;
    56             part = static_cast<uint32_t>(accumulator & kMask32);
    57             accumulator >>= 32;
    58             accumulator = accumulator + (high_bits_ >> 32) * multiplicand;
    59             high_bits_ = (accumulator << 32) + part;
    60             ASSERT((accumulator >> 32) == 0);
    61         }
    62        
    63         void Shift(int shift_amount) {
    64             ASSERT(-64 <= shift_amount && shift_amount <= 64);
    65             if (shift_amount == 0) {
    66                 return;
    67             } else if (shift_amount == -64) {
    68                 high_bits_ = low_bits_;
    69                 low_bits_ = 0;
    70             } else if (shift_amount == 64) {
    71                 low_bits_ = high_bits_;
    72                 high_bits_ = 0;
    73             } else if (shift_amount <= 0) {
    74                 high_bits_ <<= -shift_amount;
    75                 high_bits_ += low_bits_ >> (64 + shift_amount);
    76                 low_bits_ <<= -shift_amount;
    77             } else {
    78                 low_bits_ >>= shift_amount;
    79                 low_bits_ += high_bits_ << (64 - shift_amount);
    80                 high_bits_ >>= shift_amount;
    81             }
    82         }
    83        
    84         // Modifies *this to *this MOD (2^power).
    85         // Returns *this DIV (2^power).
    86         int DivModPowerOf2(int power) {
    87             if (power >= 64) {
    88                 int result = static_cast<int>(high_bits_ >> (power - 64));
    89                 high_bits_ -= static_cast<uint64_t>(result) << (power - 64);
    90                 return result;
    91             } else {
    92                 uint64_t part_low = low_bits_ >> power;
    93                 uint64_t part_high = high_bits_ << (64 - power);
    94                 int result = static_cast<int>(part_low + part_high);
    95                 high_bits_ = 0;
    96                 low_bits_ -= part_low << power;
    97                 return result;
    98             }
    99         }
    100        
    101         bool IsZero() const {
    102             return high_bits_ == 0 && low_bits_ == 0;
    103         }
    104        
    105         int BitAt(int position) {
    106             if (position >= 64) {
    107                 return static_cast<int>(high_bits_ >> (position - 64)) & 1;
    108             } else {
    109                 return static_cast<int>(low_bits_ >> position) & 1;
    110             }
    111         }
    112        
    113     private:
    114         static const uint64_t kMask32 = 0xFFFFFFFF;
    115         // Value == (high_bits_ << 64) + low_bits_
    116         uint64_t high_bits_;
    117         uint64_t low_bits_;
    118     };
    119    
    120    
    121     static const int kDoubleSignificandSize = 53;  // Includes the hidden bit.
    122    
    123    
    124     static void FillDigits32FixedLength(uint32_t number, int requested_length,
    125                                         BufferReference<char> buffer, int* length) {
    126         for (int i = requested_length - 1; i >= 0; --i) {
    127             buffer[(*length) + i] = '0' + number % 10;
    128             number /= 10;
    129         }
    130         *length += requested_length;
    131     }
    132    
    133    
    134     static void FillDigits32(uint32_t number, BufferReference<char> buffer, int* length) {
    135         int number_length = 0;
    136         // We fill the digits in reverse order and exchange them afterwards.
    137         while (number != 0) {
    138             int digit = number % 10;
    139             number /= 10;
    140             buffer[(*length) + number_length] = '0' + digit;
    141             number_length++;
    142         }
    143         // Exchange the digits.
    144         int i = *length;
    145         int j = *length + number_length - 1;
    146         while (i < j) {
    147             char tmp = buffer[i];
    148             buffer[i] = buffer[j];
    149             buffer[j] = tmp;
    150             i++;
    151             j--;
    152         }
    153         *length += number_length;
    154     }
    155    
    156    
    157     static void FillDigits64FixedLength(uint64_t number, int requested_length,
    158                                         BufferReference<char> buffer, int* length) {
    159         UNUSED_PARAM(requested_length);
    160         const uint32_t kTen7 = 10000000;
    161         // For efficiency cut the number into 3 uint32_t parts, and print those.
    162         uint32_t part2 = static_cast<uint32_t>(number % kTen7);
    163         number /= kTen7;
    164         uint32_t part1 = static_cast<uint32_t>(number % kTen7);
    165         uint32_t part0 = static_cast<uint32_t>(number / kTen7);
    166        
    167         FillDigits32FixedLength(part0, 3, buffer, length);
    168         FillDigits32FixedLength(part1, 7, buffer, length);
    169         FillDigits32FixedLength(part2, 7, buffer, length);
    170     }
    171    
    172    
    173     static void FillDigits64(uint64_t number, BufferReference<char> buffer, int* length) {
    174         const uint32_t kTen7 = 10000000;
    175         // For efficiency cut the number into 3 uint32_t parts, and print those.
    176         uint32_t part2 = static_cast<uint32_t>(number % kTen7);
    177         number /= kTen7;
    178         uint32_t part1 = static_cast<uint32_t>(number % kTen7);
    179         uint32_t part0 = static_cast<uint32_t>(number / kTen7);
    180        
    181         if (part0 != 0) {
    182             FillDigits32(part0, buffer, length);
    183             FillDigits32FixedLength(part1, 7, buffer, length);
    184             FillDigits32FixedLength(part2, 7, buffer, length);
    185         } else if (part1 != 0) {
    186             FillDigits32(part1, buffer, length);
    187             FillDigits32FixedLength(part2, 7, buffer, length);
    188         } else {
    189             FillDigits32(part2, buffer, length);
    190         }
    191     }
    192    
    193    
    194     static void RoundUp(BufferReference<char> buffer, int* length, int* decimal_point) {
    195         // An empty buffer represents 0.
    196         if (*length == 0) {
    197             buffer[0] = '1';
    198             *decimal_point = 1;
    199             *length = 1;
    200             return;
    201         }
    202         // Round the last digit until we either have a digit that was not '9' or until
    203         // we reached the first digit.
    204         buffer[(*length) - 1]++;
    205         for (int i = (*length) - 1; i > 0; --i) {
    206             if (buffer[i] != '0' + 10) {
    207                 return;
    208             }
    209             buffer[i] = '0';
    210             buffer[i - 1]++;
    211         }
    212         // If the first digit is now '0' + 10, we would need to set it to '0' and add
    213         // a '1' in front. However we reach the first digit only if all following
    214         // digits had been '9' before rounding up. Now all trailing digits are '0' and
    215         // we simply switch the first digit to '1' and update the decimal-point
    216         // (indicating that the point is now one digit to the right).
    217         if (buffer[0] == '0' + 10) {
    218             buffer[0] = '1';
    219             (*decimal_point)++;
    220         }
    221     }
    222    
    223    
    224     // The given fractionals number represents a fixed-point number with binary
    225     // point at bit (-exponent).
    226     // Preconditions:
    227     //   -128 <= exponent <= 0.
    228     //   0 <= fractionals * 2^exponent < 1
    229     //   The buffer holds the result.
    230     // The function will round its result. During the rounding-process digits not
    231     // generated by this function might be updated, and the decimal-point variable
    232     // might be updated. If this function generates the digits 99 and the buffer
    233     // already contained "199" (thus yielding a buffer of "19999") then a
    234     // rounding-up will change the contents of the buffer to "20000".
    235     static void FillFractionals(uint64_t fractionals, int exponent,
    236                                 int fractional_count, BufferReference<char> buffer,
    237                                 int* length, int* decimal_point) {
    238         ASSERT(-128 <= exponent && exponent <= 0);
    239         // 'fractionals' is a fixed-point number, with binary point at bit
    240         // (-exponent). Inside the function the non-converted remainder of fractionals
    241         // is a fixed-point number, with binary point at bit 'point'.
    242         if (-exponent <= 64) {
    243             // One 64 bit number is sufficient.
    244             ASSERT(fractionals >> 56 == 0);
    245             int point = -exponent;
    246             for (int i = 0; i < fractional_count; ++i) {
    247                 if (fractionals == 0) break;
    248                 // Instead of multiplying by 10 we multiply by 5 and adjust the point
    249                 // location. This way the fractionals variable will not overflow.
    250                 // Invariant at the beginning of the loop: fractionals < 2^point.
    251                 // Initially we have: point <= 64 and fractionals < 2^56
    252                 // After each iteration the point is decremented by one.
    253                 // Note that 5^3 = 125 < 128 = 2^7.
    254                 // Therefore three iterations of this loop will not overflow fractionals
    255                 // (even without the subtraction at the end of the loop body). At this
    256                 // time point will satisfy point <= 61 and therefore fractionals < 2^point
    257                 // and any further multiplication of fractionals by 5 will not overflow.
    258                 fractionals *= 5;
    259                 point--;
    260                 int digit = static_cast<int>(fractionals >> point);
    261                 buffer[*length] = '0' + digit;
    262                 (*length)++;
    263                 fractionals -= static_cast<uint64_t>(digit) << point;
    264             }
    265             // If the first bit after the point is set we have to round up.
    266             if (((fractionals >> (point - 1)) & 1) == 1) {
    267                 RoundUp(buffer, length, decimal_point);
    268             }
    269         } else {  // We need 128 bits.
    270             ASSERT(64 < -exponent && -exponent <= 128);
    271             UInt128 fractionals128 = UInt128(fractionals, 0);
    272             fractionals128.Shift(-exponent - 64);
    273             int point = 128;
    274             for (int i = 0; i < fractional_count; ++i) {
    275                 if (fractionals128.IsZero()) break;
    276                 // As before: instead of multiplying by 10 we multiply by 5 and adjust the
    277                 // point location.
    278                 // This multiplication will not overflow for the same reasons as before.
    279                 fractionals128.Multiply(5);
    280                 point--;
    281                 int digit = fractionals128.DivModPowerOf2(point);
    282                 buffer[*length] = '0' + digit;
    283                 (*length)++;
    284             }
    285             if (fractionals128.BitAt(point - 1) == 1) {
    286                 RoundUp(buffer, length, decimal_point);
    287             }
    288         }
    289     }
    290    
    291    
    292     // Removes leading and trailing zeros.
    293     // If leading zeros are removed then the decimal point position is adjusted.
    294     static void TrimZeros(BufferReference<char> buffer, int* length, int* decimal_point) {
    295         while (*length > 0 && buffer[(*length) - 1] == '0') {
    296             (*length)--;
    297         }
    298         int first_non_zero = 0;
    299         while (first_non_zero < *length && buffer[first_non_zero] == '0') {
    300             first_non_zero++;
    301         }
    302         if (first_non_zero != 0) {
    303             for (int i = first_non_zero; i < *length; ++i) {
    304                 buffer[i - first_non_zero] = buffer[i];
    305             }
    306             *length -= first_non_zero;
    307             *decimal_point -= first_non_zero;
    308         }
    309     }
    310    
    311    
    312     bool FastFixedDtoa(double v,
    313                        int fractional_count,
    314                        BufferReference<char> buffer,
    315                        int* length,
    316                        int* decimal_point) {
    317         const uint32_t kMaxUInt32 = 0xFFFFFFFF;
    318         uint64_t significand = Double(v).Significand();
    319         int exponent = Double(v).Exponent();
    320         // v = significand * 2^exponent (with significand a 53bit integer).
    321         // If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
    322         // don't know how to compute the representation. 2^73 ~= 9.5*10^21.
    323         // If necessary this limit could probably be increased, but we don't need
    324         // more.
    325         if (exponent > 20) return false;
    326         if (fractional_count > 20) return false;
    327         *length = 0;
    328         // At most kDoubleSignificandSize bits of the significand are non-zero.
    329         // Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
    330         // bits:  0..11*..0xxx..53*..xx
    331         if (exponent + kDoubleSignificandSize > 64) {
    332             // The exponent must be > 11.
    333             //
    334             // We know that v = significand * 2^exponent.
    335             // And the exponent > 11.
    336             // We simplify the task by dividing v by 10^17.
    337             // The quotient delivers the first digits, and the remainder fits into a 64
    338             // bit number.
    339             // Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
    340             const uint64_t kFive17 = UINT64_2PART_C(0xB1, A2BC2EC5);  // 5^17
    341             uint64_t divisor = kFive17;
    342             int divisor_power = 17;
    343             uint64_t dividend = significand;
    344             uint32_t quotient;
    345             uint64_t remainder;
    346             // Let v = f * 2^e with f == significand and e == exponent.
    347             // Then need q (quotient) and r (remainder) as follows:
    348             //   v            = q * 10^17       + r
    349             //   f * 2^e      = q * 10^17       + r
    350             //   f * 2^e      = q * 5^17 * 2^17 + r
    351             // If e > 17 then
    352             //   f * 2^(e-17) = q * 5^17        + r/2^17
    353             // else
    354             //   f  = q * 5^17 * 2^(17-e) + r/2^e
    355             if (exponent > divisor_power) {
    356                 // We only allow exponents of up to 20 and therefore (17 - e) <= 3
    357                 dividend <<= exponent - divisor_power;
    358                 quotient = static_cast<uint32_t>(dividend / divisor);
    359                 remainder = (dividend % divisor) << divisor_power;
    360             } else {
    361                 divisor <<= divisor_power - exponent;
    362                 quotient = static_cast<uint32_t>(dividend / divisor);
    363                 remainder = (dividend % divisor) << exponent;
    364             }
    365             FillDigits32(quotient, buffer, length);
    366             FillDigits64FixedLength(remainder, divisor_power, buffer, length);
    367             *decimal_point = *length;
    368         } else if (exponent >= 0) {
    369             // 0 <= exponent <= 11
    370             significand <<= exponent;
    371             FillDigits64(significand, buffer, length);
    372             *decimal_point = *length;
    373         } else if (exponent > -kDoubleSignificandSize) {
    374             // We have to cut the number.
    375             uint64_t integrals = significand >> -exponent;
    376             uint64_t fractionals = significand - (integrals << -exponent);
    377             if (integrals > kMaxUInt32) {
    378                 FillDigits64(integrals, buffer, length);
    379             } else {
    380                 FillDigits32(static_cast<uint32_t>(integrals), buffer, length);
    381             }
    382             *decimal_point = *length;
    383             FillFractionals(fractionals, exponent, fractional_count,
    384                             buffer, length, decimal_point);
    385         } else if (exponent < -128) {
    386             // This configuration (with at most 20 digits) means that all digits must be
    387             // 0.
    388             ASSERT(fractional_count <= 20);
    389             buffer[0] = '\0';
    390             *length = 0;
    391             *decimal_point = -fractional_count;
    392         } else {
    393             *decimal_point = 0;
    394             FillFractionals(significand, exponent, fractional_count,
    395                             buffer, length, decimal_point);
    396         }
    397         TrimZeros(buffer, length, decimal_point);
    398         buffer[*length] = '\0';
    399         if ((*length) == 0) {
    400             // The string is empty and the decimal_point thus has no importance. Mimick
    401             // Gay's dtoa and and set it to -fractional_count.
    402             *decimal_point = -fractional_count;
    403         }
    404         return true;
    405     }
    406    
     37
     38// Represents a 128bit type. This class should be replaced by a native type on
     39// platforms that support 128bit integers.
     40class UInt128 {
     41 public:
     42  UInt128() : high_bits_(0), low_bits_(0) { }
     43  UInt128(uint64_t high, uint64_t low) : high_bits_(high), low_bits_(low) { }
     44
     45  void Multiply(uint32_t multiplicand) {
     46    uint64_t accumulator;
     47
     48    accumulator = (low_bits_ & kMask32) * multiplicand;
     49    uint32_t part = static_cast<uint32_t>(accumulator & kMask32);
     50    accumulator >>= 32;
     51    accumulator = accumulator + (low_bits_ >> 32) * multiplicand;
     52    low_bits_ = (accumulator << 32) + part;
     53    accumulator >>= 32;
     54    accumulator = accumulator + (high_bits_ & kMask32) * multiplicand;
     55    part = static_cast<uint32_t>(accumulator & kMask32);
     56    accumulator >>= 32;
     57    accumulator = accumulator + (high_bits_ >> 32) * multiplicand;
     58    high_bits_ = (accumulator << 32) + part;
     59    ASSERT((accumulator >> 32) == 0);
     60  }
     61
     62  void Shift(int shift_amount) {
     63    ASSERT(-64 <= shift_amount && shift_amount <= 64);
     64    if (shift_amount == 0) {
     65      return;
     66    } else if (shift_amount == -64) {
     67      high_bits_ = low_bits_;
     68      low_bits_ = 0;
     69    } else if (shift_amount == 64) {
     70      low_bits_ = high_bits_;
     71      high_bits_ = 0;
     72    } else if (shift_amount <= 0) {
     73      high_bits_ <<= -shift_amount;
     74      high_bits_ += low_bits_ >> (64 + shift_amount);
     75      low_bits_ <<= -shift_amount;
     76    } else {
     77      low_bits_ >>= shift_amount;
     78      low_bits_ += high_bits_ << (64 - shift_amount);
     79      high_bits_ >>= shift_amount;
     80    }
     81  }
     82
     83  // Modifies *this to *this MOD (2^power).
     84  // Returns *this DIV (2^power).
     85  int DivModPowerOf2(int power) {
     86    if (power >= 64) {
     87      int result = static_cast<int>(high_bits_ >> (power - 64));
     88      high_bits_ -= static_cast<uint64_t>(result) << (power - 64);
     89      return result;
     90    } else {
     91      uint64_t part_low = low_bits_ >> power;
     92      uint64_t part_high = high_bits_ << (64 - power);
     93      int result = static_cast<int>(part_low + part_high);
     94      high_bits_ = 0;
     95      low_bits_ -= part_low << power;
     96      return result;
     97    }
     98  }
     99
     100  bool IsZero() const {
     101    return high_bits_ == 0 && low_bits_ == 0;
     102  }
     103
     104  int BitAt(int position) const {
     105    if (position >= 64) {
     106      return static_cast<int>(high_bits_ >> (position - 64)) & 1;
     107    } else {
     108      return static_cast<int>(low_bits_ >> position) & 1;
     109    }
     110  }
     111
     112 private:
     113  static const uint64_t kMask32 = 0xFFFFFFFF;
     114  // Value == (high_bits_ << 64) + low_bits_
     115  uint64_t high_bits_;
     116  uint64_t low_bits_;
     117};
     118
     119
     120static const int kDoubleSignificandSize = 53;  // Includes the hidden bit.
     121
     122
     123static void FillDigits32FixedLength(uint32_t number, int requested_length,
     124                                    BufferReference<char> buffer, int* length) {
     125  for (int i = requested_length - 1; i >= 0; --i) {
     126    buffer[(*length) + i] = '0' + number % 10;
     127    number /= 10;
     128  }
     129  *length += requested_length;
     130}
     131
     132
     133static void FillDigits32(uint32_t number, BufferReference<char> buffer, int* length) {
     134  int number_length = 0;
     135  // We fill the digits in reverse order and exchange them afterwards.
     136  while (number != 0) {
     137    int digit = number % 10;
     138    number /= 10;
     139    buffer[(*length) + number_length] = static_cast<char>('0' + digit);
     140    number_length++;
     141  }
     142  // Exchange the digits.
     143  int i = *length;
     144  int j = *length + number_length - 1;
     145  while (i < j) {
     146    char tmp = buffer[i];
     147    buffer[i] = buffer[j];
     148    buffer[j] = tmp;
     149    i++;
     150    j--;
     151  }
     152  *length += number_length;
     153}
     154
     155
     156static void FillDigits64FixedLength(uint64_t number,
     157                                    BufferReference<char> buffer, int* length) {
     158  const uint32_t kTen7 = 10000000;
     159  // For efficiency cut the number into 3 uint32_t parts, and print those.
     160  uint32_t part2 = static_cast<uint32_t>(number % kTen7);
     161  number /= kTen7;
     162  uint32_t part1 = static_cast<uint32_t>(number % kTen7);
     163  uint32_t part0 = static_cast<uint32_t>(number / kTen7);
     164
     165  FillDigits32FixedLength(part0, 3, buffer, length);
     166  FillDigits32FixedLength(part1, 7, buffer, length);
     167  FillDigits32FixedLength(part2, 7, buffer, length);
     168}
     169
     170
     171static void FillDigits64(uint64_t number, BufferReference<char> buffer, int* length) {
     172  const uint32_t kTen7 = 10000000;
     173  // For efficiency cut the number into 3 uint32_t parts, and print those.
     174  uint32_t part2 = static_cast<uint32_t>(number % kTen7);
     175  number /= kTen7;
     176  uint32_t part1 = static_cast<uint32_t>(number % kTen7);
     177  uint32_t part0 = static_cast<uint32_t>(number / kTen7);
     178
     179  if (part0 != 0) {
     180    FillDigits32(part0, buffer, length);
     181    FillDigits32FixedLength(part1, 7, buffer, length);
     182    FillDigits32FixedLength(part2, 7, buffer, length);
     183  } else if (part1 != 0) {
     184    FillDigits32(part1, buffer, length);
     185    FillDigits32FixedLength(part2, 7, buffer, length);
     186  } else {
     187    FillDigits32(part2, buffer, length);
     188  }
     189}
     190
     191
     192static void RoundUp(BufferReference<char> buffer, int* length, int* decimal_point) {
     193  // An empty buffer represents 0.
     194  if (*length == 0) {
     195    buffer[0] = '1';
     196    *decimal_point = 1;
     197    *length = 1;
     198    return;
     199  }
     200  // Round the last digit until we either have a digit that was not '9' or until
     201  // we reached the first digit.
     202  buffer[(*length) - 1]++;
     203  for (int i = (*length) - 1; i > 0; --i) {
     204    if (buffer[i] != '0' + 10) {
     205      return;
     206    }
     207    buffer[i] = '0';
     208    buffer[i - 1]++;
     209  }
     210  // If the first digit is now '0' + 10, we would need to set it to '0' and add
     211  // a '1' in front. However we reach the first digit only if all following
     212  // digits had been '9' before rounding up. Now all trailing digits are '0' and
     213  // we simply switch the first digit to '1' and update the decimal-point
     214  // (indicating that the point is now one digit to the right).
     215  if (buffer[0] == '0' + 10) {
     216    buffer[0] = '1';
     217    (*decimal_point)++;
     218  }
     219}
     220
     221
     222// The given fractionals number represents a fixed-point number with binary
     223// point at bit (-exponent).
     224// Preconditions:
     225//   -128 <= exponent <= 0.
     226//   0 <= fractionals * 2^exponent < 1
     227//   The buffer holds the result.
     228// The function will round its result. During the rounding-process digits not
     229// generated by this function might be updated, and the decimal-point variable
     230// might be updated. If this function generates the digits 99 and the buffer
     231// already contained "199" (thus yielding a buffer of "19999") then a
     232// rounding-up will change the contents of the buffer to "20000".
     233static void FillFractionals(uint64_t fractionals, int exponent,
     234                            int fractional_count, BufferReference<char> buffer,
     235                            int* length, int* decimal_point) {
     236  ASSERT(-128 <= exponent && exponent <= 0);
     237  // 'fractionals' is a fixed-point number, with binary point at bit
     238  // (-exponent). Inside the function the non-converted remainder of fractionals
     239  // is a fixed-point number, with binary point at bit 'point'.
     240  if (-exponent <= 64) {
     241    // One 64 bit number is sufficient.
     242    ASSERT(fractionals >> 56 == 0);
     243    int point = -exponent;
     244    for (int i = 0; i < fractional_count; ++i) {
     245      if (fractionals == 0) break;
     246      // Instead of multiplying by 10 we multiply by 5 and adjust the point
     247      // location. This way the fractionals variable will not overflow.
     248      // Invariant at the beginning of the loop: fractionals < 2^point.
     249      // Initially we have: point <= 64 and fractionals < 2^56
     250      // After each iteration the point is decremented by one.
     251      // Note that 5^3 = 125 < 128 = 2^7.
     252      // Therefore three iterations of this loop will not overflow fractionals
     253      // (even without the subtraction at the end of the loop body). At this
     254      // time point will satisfy point <= 61 and therefore fractionals < 2^point
     255      // and any further multiplication of fractionals by 5 will not overflow.
     256      fractionals *= 5;
     257      point--;
     258      int digit = static_cast<int>(fractionals >> point);
     259      ASSERT(digit <= 9);
     260      buffer[*length] = static_cast<char>('0' + digit);
     261      (*length)++;
     262      fractionals -= static_cast<uint64_t>(digit) << point;
     263    }
     264    // If the first bit after the point is set we have to round up.
     265    ASSERT(fractionals == 0 || point - 1 >= 0);
     266    if ((fractionals != 0) && ((fractionals >> (point - 1)) & 1) == 1) {
     267      RoundUp(buffer, length, decimal_point);
     268    }
     269  } else {  // We need 128 bits.
     270    ASSERT(64 < -exponent && -exponent <= 128);
     271    UInt128 fractionals128 = UInt128(fractionals, 0);
     272    fractionals128.Shift(-exponent - 64);
     273    int point = 128;
     274    for (int i = 0; i < fractional_count; ++i) {
     275      if (fractionals128.IsZero()) break;
     276      // As before: instead of multiplying by 10 we multiply by 5 and adjust the
     277      // point location.
     278      // This multiplication will not overflow for the same reasons as before.
     279      fractionals128.Multiply(5);
     280      point--;
     281      int digit = fractionals128.DivModPowerOf2(point);
     282      ASSERT(digit <= 9);
     283      buffer[*length] = static_cast<char>('0' + digit);
     284      (*length)++;
     285    }
     286    if (fractionals128.BitAt(point - 1) == 1) {
     287      RoundUp(buffer, length, decimal_point);
     288    }
     289  }
     290}
     291
     292
     293// Removes leading and trailing zeros.
     294// If leading zeros are removed then the decimal point position is adjusted.
     295static void TrimZeros(BufferReference<char> buffer, int* length, int* decimal_point) {
     296  while (*length > 0 && buffer[(*length) - 1] == '0') {
     297    (*length)--;
     298  }
     299  int first_non_zero = 0;
     300  while (first_non_zero < *length && buffer[first_non_zero] == '0') {
     301    first_non_zero++;
     302  }
     303  if (first_non_zero != 0) {
     304    for (int i = first_non_zero; i < *length; ++i) {
     305      buffer[i - first_non_zero] = buffer[i];
     306    }
     307    *length -= first_non_zero;
     308    *decimal_point -= first_non_zero;
     309  }
     310}
     311
     312
     313bool FastFixedDtoa(double v,
     314                   int fractional_count,
     315                   BufferReference<char> buffer,
     316                   int* length,
     317                   int* decimal_point) {
     318  const uint32_t kMaxUInt32 = 0xFFFFFFFF;
     319  uint64_t significand = Double(v).Significand();
     320  int exponent = Double(v).Exponent();
     321  // v = significand * 2^exponent (with significand a 53bit integer).
     322  // If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
     323  // don't know how to compute the representation. 2^73 ~= 9.5*10^21.
     324  // If necessary this limit could probably be increased, but we don't need
     325  // more.
     326  if (exponent > 20) return false;
     327  if (fractional_count > 20) return false;
     328  *length = 0;
     329  // At most kDoubleSignificandSize bits of the significand are non-zero.
     330  // Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
     331  // bits:  0..11*..0xxx..53*..xx
     332  if (exponent + kDoubleSignificandSize > 64) {
     333    // The exponent must be > 11.
     334    //
     335    // We know that v = significand * 2^exponent.
     336    // And the exponent > 11.
     337    // We simplify the task by dividing v by 10^17.
     338    // The quotient delivers the first digits, and the remainder fits into a 64
     339    // bit number.
     340    // Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
     341    const uint64_t kFive17 = UINT64_2PART_C(0xB1, A2BC2EC5);  // 5^17
     342    uint64_t divisor = kFive17;
     343    int divisor_power = 17;
     344    uint64_t dividend = significand;
     345    uint32_t quotient;
     346    uint64_t remainder;
     347    // Let v = f * 2^e with f == significand and e == exponent.
     348    // Then need q (quotient) and r (remainder) as follows:
     349    //   v            = q * 10^17       + r
     350    //   f * 2^e      = q * 10^17       + r
     351    //   f * 2^e      = q * 5^17 * 2^17 + r
     352    // If e > 17 then
     353    //   f * 2^(e-17) = q * 5^17        + r/2^17
     354    // else
     355    //   f  = q * 5^17 * 2^(17-e) + r/2^e
     356    if (exponent > divisor_power) {
     357      // We only allow exponents of up to 20 and therefore (17 - e) <= 3
     358      dividend <<= exponent - divisor_power;
     359      quotient = static_cast<uint32_t>(dividend / divisor);
     360      remainder = (dividend % divisor) << divisor_power;
     361    } else {
     362      divisor <<= divisor_power - exponent;
     363      quotient = static_cast<uint32_t>(dividend / divisor);
     364      remainder = (dividend % divisor) << exponent;
     365    }
     366    FillDigits32(quotient, buffer, length);
     367    FillDigits64FixedLength(remainder, buffer, length);
     368    *decimal_point = *length;
     369  } else if (exponent >= 0) {
     370    // 0 <= exponent <= 11
     371    significand <<= exponent;
     372    FillDigits64(significand, buffer, length);
     373    *decimal_point = *length;
     374  } else if (exponent > -kDoubleSignificandSize) {
     375    // We have to cut the number.
     376    uint64_t integrals = significand >> -exponent;
     377    uint64_t fractionals = significand - (integrals << -exponent);
     378    if (integrals > kMaxUInt32) {
     379      FillDigits64(integrals, buffer, length);
     380    } else {
     381      FillDigits32(static_cast<uint32_t>(integrals), buffer, length);
     382    }
     383    *decimal_point = *length;
     384    FillFractionals(fractionals, exponent, fractional_count,
     385                    buffer, length, decimal_point);
     386  } else if (exponent < -128) {
     387    // This configuration (with at most 20 digits) means that all digits must be
     388    // 0.
     389    ASSERT(fractional_count <= 20);
     390    buffer[0] = '\0';
     391    *length = 0;
     392    *decimal_point = -fractional_count;
     393  } else {
     394    *decimal_point = 0;
     395    FillFractionals(significand, exponent, fractional_count,
     396                    buffer, length, decimal_point);
     397  }
     398  TrimZeros(buffer, length, decimal_point);
     399  buffer[*length] = '\0';
     400  if ((*length) == 0) {
     401    // The string is empty and the decimal_point thus has no importance. Mimick
     402    // Gay's dtoa and and set it to -fractional_count.
     403    *decimal_point = -fractional_count;
     404  }
     405  return true;
     406}
     407
    407408}  // namespace double_conversion
    408 
    409 } // namespace WTF
     409}  // namespace WTF
  • trunk/Source/WTF/wtf/dtoa/fixed-dtoa.h

    r147976 r242048  
    2929#define DOUBLE_CONVERSION_FIXED_DTOA_H_
    3030
    31 #include "utils.h"
     31#include <wtf/dtoa/utils.h>
    3232
    3333namespace WTF {
     34namespace double_conversion {
    3435
    35 namespace double_conversion {
    36    
    37     // Produces digits necessary to print a given number with
    38     // 'fractional_count' digits after the decimal point.
    39     // The buffer must be big enough to hold the result plus one terminating null
    40     // character.
    41     //
    42     // The produced digits might be too short in which case the caller has to fill
    43     // the gaps with '0's.
    44     // Example: FastFixedDtoa(0.001, 5, ...) is allowed to return buffer = "1", and
    45     // decimal_point = -2.
    46     // Halfway cases are rounded towards +/-Infinity (away from 0). The call
    47     // FastFixedDtoa(0.15, 2, ...) thus returns buffer = "2", decimal_point = 0.
    48     // The returned buffer may contain digits that would be truncated from the
    49     // shortest representation of the input.
    50     //
    51     // This method only works for some parameters. If it can't handle the input it
    52     // returns false. The output is null-terminated when the function succeeds.
    53     bool FastFixedDtoa(double v, int fractional_count,
    54                        BufferReference<char> buffer, int* length, int* decimal_point);
    55    
     36// Produces digits necessary to print a given number with
     37// 'fractional_count' digits after the decimal point.
     38// The buffer must be big enough to hold the result plus one terminating null
     39// character.
     40//
     41// The produced digits might be too short in which case the caller has to fill
     42// the gaps with '0's.
     43// Example: FastFixedDtoa(0.001, 5, ...) is allowed to return buffer = "1", and
     44// decimal_point = -2.
     45// Halfway cases are rounded towards +/-Infinity (away from 0). The call
     46// FastFixedDtoa(0.15, 2, ...) thus returns buffer = "2", decimal_point = 0.
     47// The returned buffer may contain digits that would be truncated from the
     48// shortest representation of the input.
     49//
     50// This method only works for some parameters. If it can't handle the input it
     51// returns false. The output is null-terminated when the function succeeds.
     52bool FastFixedDtoa(double v, int fractional_count,
     53                   BufferReference<char> buffer, int* length, int* decimal_point);
     54
    5655}  // namespace double_conversion
    57 
    58 } // namespace WTF
     56}  // namespace WTF
    5957
    6058#endif  // DOUBLE_CONVERSION_FIXED_DTOA_H_
  • trunk/Source/WTF/wtf/dtoa/strtod.cc

    r173376 r242048  
    2828#include "config.h"
    2929
    30 #include <stdarg.h>
    31 #include <limits.h>
    32 
    33 #include "strtod.h"
    34 #include "bignum.h"
    35 #include "cached-powers.h"
    36 #include "double.h"
     30#include <climits>
     31#include <cstdarg>
     32
     33#include <wtf/dtoa/bignum.h>
     34#include <wtf/dtoa/cached-powers.h>
     35#include <wtf/dtoa/ieee.h>
     36#include <wtf/dtoa/strtod.h>
    3737
    3838namespace WTF {
    39 
    4039namespace double_conversion {
    4140
    4241#if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
    43     // 2^53 = 9007199254740992.
    44     // Any integer with at most 15 decimal digits will hence fit into a double
    45     // (which has a 53bit significand) without loss of precision.
    46     static const int kMaxExactDoubleIntegerDecimalDigits = 15;
     42// 2^53 = 9007199254740992.
     43// Any integer with at most 15 decimal digits will hence fit into a double
     44// (which has a 53bit significand) without loss of precision.
     45static const int kMaxExactDoubleIntegerDecimalDigits = 15;
    4746#endif
    48     // 2^64 = 18446744073709551616 > 10^19
    49     static const int kMaxUint64DecimalDigits = 19;
    50    
    51     // Max double: 1.7976931348623157 x 10^308
    52     // Min non-zero double: 4.9406564584124654 x 10^-324
    53     // Any x >= 10^309 is interpreted as +infinity.
    54     // Any x <= 10^-324 is interpreted as 0.
    55     // Note that 2.5e-324 (despite being smaller than the min double) will be read
    56     // as non-zero (equal to the min non-zero double).
    57     static const int kMaxDecimalPower = 309;
    58     static const int kMinDecimalPower = -324;
    59    
    60     // 2^64 = 18446744073709551616
    61     static const uint64_t kMaxUint64 = UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF);
    62    
     47// 2^64 = 18446744073709551616 > 10^19
     48static const int kMaxUint64DecimalDigits = 19;
     49
     50// Max double: 1.7976931348623157 x 10^308
     51// Min non-zero double: 4.9406564584124654 x 10^-324
     52// Any x >= 10^309 is interpreted as +infinity.
     53// Any x <= 10^-324 is interpreted as 0.
     54// Note that 2.5e-324 (despite being smaller than the min double) will be read
     55// as non-zero (equal to the min non-zero double).
     56static const int kMaxDecimalPower = 309;
     57static const int kMinDecimalPower = -324;
     58
     59// 2^64 = 18446744073709551616
     60static const uint64_t kMaxUint64 = UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF);
     61
     62
    6363#if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
    64     static const double exact_powers_of_ten[] = {
    65         1.0,  // 10^0
    66         10.0,
    67         100.0,
    68         1000.0,
    69         10000.0,
    70         100000.0,
    71         1000000.0,
    72         10000000.0,
    73         100000000.0,
    74         1000000000.0,
    75         10000000000.0,  // 10^10
    76         100000000000.0,
    77         1000000000000.0,
    78         10000000000000.0,
    79         100000000000000.0,
    80         1000000000000000.0,
    81         10000000000000000.0,
    82         100000000000000000.0,
    83         1000000000000000000.0,
    84         10000000000000000000.0,
    85         100000000000000000000.0,  // 10^20
    86         1000000000000000000000.0,
    87         // 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
    88         10000000000000000000000.0
    89     };
    90     static const int kExactPowersOfTenSize = ARRAY_SIZE(exact_powers_of_ten);
     64static const double exact_powers_of_ten[] = {
     65  1.0,  // 10^0
     66  10.0,
     67  100.0,
     68  1000.0,
     69  10000.0,
     70  100000.0,
     71  1000000.0,
     72  10000000.0,
     73  100000000.0,
     74  1000000000.0,
     75  10000000000.0,  // 10^10
     76  100000000000.0,
     77  1000000000000.0,
     78  10000000000000.0,
     79  100000000000000.0,
     80  1000000000000000.0,
     81  10000000000000000.0,
     82  100000000000000000.0,
     83  1000000000000000000.0,
     84  10000000000000000000.0,
     85  100000000000000000000.0,  // 10^20
     86  1000000000000000000000.0,
     87  // 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
     88  10000000000000000000000.0
     89};
     90static const int kExactPowersOfTenSize = ARRAY_SIZE(exact_powers_of_ten);
    9191#endif
    92    
    93     // Maximum number of significant digits in the decimal representation.
    94     // In fact the value is 772 (see conversions.cc), but to give us some margin
    95     // we round up to 780.
    96     static const int kMaxSignificantDecimalDigits = 780;
    97    
    98     static BufferReference<const char> TrimLeadingZeros(BufferReference<const char> buffer) {
    99         for (int i = 0; i < buffer.length(); i++) {
    100             if (buffer[i] != '0') {
    101                 return buffer.SubBufferReference(i, buffer.length());
    102             }
    103         }
    104         return BufferReference<const char>(buffer.start(), 0);
    105     }
    106    
    107    
    108     static BufferReference<const char> TrimTrailingZeros(BufferReference<const char> buffer) {
    109         for (int i = buffer.length() - 1; i >= 0; --i) {
    110             if (buffer[i] != '0') {
    111                 return buffer.SubBufferReference(0, i + 1);
    112             }
    113         }
    114         return BufferReference<const char>(buffer.start(), 0);
    115     }
    116    
    117    
    118     static void TrimToMaxSignificantDigits(BufferReference<const char> buffer,
    119                                            int exponent,
    120                                            char* significant_buffer,
    121                                            int* significant_exponent) {
    122         for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) {
    123             significant_buffer[i] = buffer[i];
    124         }
    125         // The input buffer has been trimmed. Therefore the last digit must be
    126         // different from '0'.
    127         ASSERT(buffer[buffer.length() - 1] != '0');
    128         // Set the last digit to be non-zero. This is sufficient to guarantee
    129         // correct rounding.
    130         significant_buffer[kMaxSignificantDecimalDigits - 1] = '1';
    131         *significant_exponent =
    132         exponent + (buffer.length() - kMaxSignificantDecimalDigits);
    133     }
    134    
    135     // Reads digits from the buffer and converts them to a uint64.
    136     // Reads in as many digits as fit into a uint64.
    137     // When the string starts with "1844674407370955161" no further digit is read.
    138     // Since 2^64 = 18446744073709551616 it would still be possible read another
    139     // digit if it was less or equal than 6, but this would complicate the code.
    140     static uint64_t ReadUint64(BufferReference<const char> buffer,
    141                                int* number_of_read_digits) {
    142         uint64_t result = 0;
    143         int i = 0;
    144         while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
    145             int digit = buffer[i++] - '0';
    146             ASSERT(0 <= digit && digit <= 9);
    147             result = 10 * result + digit;
    148         }
    149         *number_of_read_digits = i;
    150         return result;
    151     }
    152    
    153    
    154     // Reads a DiyFp from the buffer.
    155     // The returned DiyFp is not necessarily normalized.
    156     // If remaining_decimals is zero then the returned DiyFp is accurate.
    157     // Otherwise it has been rounded and has error of at most 1/2 ulp.
    158     static void ReadDiyFp(BufferReference<const char> buffer,
    159                           DiyFp* result,
    160                           int* remaining_decimals) {
    161         int read_digits;
    162         uint64_t significand = ReadUint64(buffer, &read_digits);
    163         if (buffer.length() == read_digits) {
    164             *result = DiyFp(significand, 0);
    165             *remaining_decimals = 0;
    166         } else {
    167             // Round the significand.
    168             if (buffer[read_digits] >= '5') {
    169                 significand++;
    170             }
    171             // Compute the binary exponent.
    172             int exponent = 0;
    173             *result = DiyFp(significand, exponent);
    174             *remaining_decimals = buffer.length() - read_digits;
    175         }
    176     }
    177    
    178    
    179     static bool DoubleStrtod(BufferReference<const char> trimmed,
    180                              int exponent,
    181                              double* result) {
     92
     93// Maximum number of significant digits in the decimal representation.
     94// In fact the value is 772 (see conversions.cc), but to give us some margin
     95// we round up to 780.
     96static const int kMaxSignificantDecimalDigits = 780;
     97
     98static BufferReference<const char> TrimLeadingZeros(BufferReference<const char> buffer) {
     99  for (int i = 0; i < buffer.length(); i++) {
     100    if (buffer[i] != '0') {
     101      return buffer.SubBufferReference(i, buffer.length());
     102    }
     103  }
     104  return BufferReference<const char>(buffer.start(), 0);
     105}
     106
     107
     108static BufferReference<const char> TrimTrailingZeros(BufferReference<const char> buffer) {
     109  for (int i = buffer.length() - 1; i >= 0; --i) {
     110    if (buffer[i] != '0') {
     111      return buffer.SubBufferReference(0, i + 1);
     112    }
     113  }
     114  return BufferReference<const char>(buffer.start(), 0);
     115}
     116
     117
     118static void CutToMaxSignificantDigits(BufferReference<const char> buffer,
     119                                       int exponent,
     120                                       char* significant_buffer,
     121                                       int* significant_exponent) {
     122  for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) {
     123    significant_buffer[i] = buffer[i];
     124  }
     125  // The input buffer has been trimmed. Therefore the last digit must be
     126  // different from '0'.
     127  ASSERT(buffer[buffer.length() - 1] != '0');
     128  // Set the last digit to be non-zero. This is sufficient to guarantee
     129  // correct rounding.
     130  significant_buffer[kMaxSignificantDecimalDigits - 1] = '1';
     131  *significant_exponent =
     132      exponent + (buffer.length() - kMaxSignificantDecimalDigits);
     133}
     134
     135
     136// Trims the buffer and cuts it to at most kMaxSignificantDecimalDigits.
     137// If possible the input-buffer is reused, but if the buffer needs to be
     138// modified (due to cutting), then the input needs to be copied into the
     139// buffer_copy_space.
     140static void TrimAndCut(BufferReference<const char> buffer, int exponent,
     141                       char* buffer_copy_space, int space_size,
     142                       BufferReference<const char>* trimmed, int* updated_exponent) {
     143  BufferReference<const char> left_trimmed = TrimLeadingZeros(buffer);
     144  BufferReference<const char> right_trimmed = TrimTrailingZeros(left_trimmed);
     145  exponent += left_trimmed.length() - right_trimmed.length();
     146  if (right_trimmed.length() > kMaxSignificantDecimalDigits) {
     147    (void) space_size;  // Mark variable as used.
     148    ASSERT(space_size >= kMaxSignificantDecimalDigits);
     149    CutToMaxSignificantDigits(right_trimmed, exponent,
     150                              buffer_copy_space, updated_exponent);
     151    *trimmed = BufferReference<const char>(buffer_copy_space,
     152                                 kMaxSignificantDecimalDigits);
     153  } else {
     154    *trimmed = right_trimmed;
     155    *updated_exponent = exponent;
     156  }
     157}
     158
     159
     160// Reads digits from the buffer and converts them to a uint64.
     161// Reads in as many digits as fit into a uint64.
     162// When the string starts with "1844674407370955161" no further digit is read.
     163// Since 2^64 = 18446744073709551616 it would still be possible read another
     164// digit if it was less or equal than 6, but this would complicate the code.
     165static uint64_t ReadUint64(BufferReference<const char> buffer,
     166                           int* number_of_read_digits) {
     167  uint64_t result = 0;
     168  int i = 0;
     169  while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
     170    int digit = buffer[i++] - '0';
     171    ASSERT(0 <= digit && digit <= 9);
     172    result = 10 * result + digit;
     173  }
     174  *number_of_read_digits = i;
     175  return result;
     176}
     177
     178
     179// Reads a DiyFp from the buffer.
     180// The returned DiyFp is not necessarily normalized.
     181// If remaining_decimals is zero then the returned DiyFp is accurate.
     182// Otherwise it has been rounded and has error of at most 1/2 ulp.
     183static void ReadDiyFp(BufferReference<const char> buffer,
     184                      DiyFp* result,
     185                      int* remaining_decimals) {
     186  int read_digits;
     187  uint64_t significand = ReadUint64(buffer, &read_digits);
     188  if (buffer.length() == read_digits) {
     189    *result = DiyFp(significand, 0);
     190    *remaining_decimals = 0;
     191  } else {
     192    // Round the significand.
     193    if (buffer[read_digits] >= '5') {
     194      significand++;
     195    }
     196    // Compute the binary exponent.
     197    int exponent = 0;
     198    *result = DiyFp(significand, exponent);
     199    *remaining_decimals = buffer.length() - read_digits;
     200  }
     201}
     202
     203
     204static bool DoubleStrtod(BufferReference<const char> trimmed,
     205                         int exponent,
     206                         double* result) {
    182207#if !defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
    183         UNUSED_PARAM(trimmed);
    184         UNUSED_PARAM(exponent);
    185         UNUSED_PARAM(result);
    186         // On x86 the floating-point stack can be 64 or 80 bits wide. If it is
    187         // 80 bits wide (as is the case on Linux) then double-rounding occurs and the
    188         // result is not accurate.
    189         // We know that Windows32 uses 64 bits and is therefore accurate.
    190         // Note that the ARM simulator is compiled for 32bits. It therefore exhibits
    191         // the same problem.
    192         return false;
     208  UNUSED_PARAM(trimmed);
     209  UNUSED_PARAM(exponent);
     210  UNUSED_PARAM(result);
     211  // On x86 the floating-point stack can be 64 or 80 bits wide. If it is
     212  // 80 bits wide (as is the case on Linux) then double-rounding occurs and the
     213  // result is not accurate.
     214  // We know that Windows32 uses 64 bits and is therefore accurate.
     215  // Note that the ARM simulator is compiled for 32bits. It therefore exhibits
     216  // the same problem.
     217  return false;
    193218#else
    194         if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
    195             int read_digits;
    196             // The trimmed input fits into a double.
    197             // If the 10^exponent (resp. 10^-exponent) fits into a double too then we
    198             // can compute the result-double simply by multiplying (resp. dividing) the
    199             // two numbers.
    200             // This is possible because IEEE guarantees that floating-point operations
    201             // return the best possible approximation.
    202             if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
    203                 // 10^-exponent fits into a double.
    204                 *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
    205                 ASSERT(read_digits == trimmed.length());
    206                 *result /= exact_powers_of_ten[-exponent];
    207                 return true;
    208             }
    209             if (0 <= exponent && exponent < kExactPowersOfTenSize) {
    210                 // 10^exponent fits into a double.
    211                 *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
    212                 ASSERT(read_digits == trimmed.length());
    213                 *result *= exact_powers_of_ten[exponent];
    214                 return true;
    215             }
    216             int remaining_digits =
    217             kMaxExactDoubleIntegerDecimalDigits - trimmed.length();
    218             if ((0 <= exponent) &&
    219                 (exponent - remaining_digits < kExactPowersOfTenSize)) {
    220                 // The trimmed string was short and we can multiply it with
    221                 // 10^remaining_digits. As a result the remaining exponent now fits
    222                 // into a double too.
    223                 *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
    224                 ASSERT(read_digits == trimmed.length());
    225                 *result *= exact_powers_of_ten[remaining_digits];
    226                 *result *= exact_powers_of_ten[exponent - remaining_digits];
    227                 return true;
    228             }
    229         }
    230         return false;
     219  if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
     220    int read_digits;
     221    // The trimmed input fits into a double.
     222    // If the 10^exponent (resp. 10^-exponent) fits into a double too then we
     223    // can compute the result-double simply by multiplying (resp. dividing) the
     224    // two numbers.
     225    // This is possible because IEEE guarantees that floating-point operations
     226    // return the best possible approximation.
     227    if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
     228      // 10^-exponent fits into a double.
     229      *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
     230      ASSERT(read_digits == trimmed.length());
     231      *result /= exact_powers_of_ten[-exponent];
     232      return true;
     233    }
     234    if (0 <= exponent && exponent < kExactPowersOfTenSize) {
     235      // 10^exponent fits into a double.
     236      *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
     237      ASSERT(read_digits == trimmed.length());
     238      *result *= exact_powers_of_ten[exponent];
     239      return true;
     240    }
     241    int remaining_digits =
     242        kMaxExactDoubleIntegerDecimalDigits - trimmed.length();
     243    if ((0 <= exponent) &&
     244        (exponent - remaining_digits < kExactPowersOfTenSize)) {
     245      // The trimmed string was short and we can multiply it with
     246      // 10^remaining_digits. As a result the remaining exponent now fits
     247      // into a double too.
     248      *result = static_cast<double>(ReadUint64(trimmed, &read_digits));
     249      ASSERT(read_digits == trimmed.length());
     250      *result *= exact_powers_of_ten[remaining_digits];
     251      *result *= exact_powers_of_ten[exponent - remaining_digits];
     252      return true;
     253    }
     254  }
     255  return false;
    231256#endif
    232     }
    233    
    234    
    235     // Returns 10^exponent as an exact DiyFp.
    236     // The given exponent must be in the range [1; kDecimalExponentDistance[.
    237     static DiyFp AdjustmentPowerOfTen(int exponent) {
    238         ASSERT(0 < exponent);
    239         ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance);
    240         // Simply hardcode the remaining powers for the given decimal exponent
    241         // distance.
    242         ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8);
    243         switch (exponent) {
    244             case 1: return DiyFp(UINT64_2PART_C(0xa0000000, 00000000), -60);
    245             case 2: return DiyFp(UINT64_2PART_C(0xc8000000, 00000000), -57);
    246             case 3: return DiyFp(UINT64_2PART_C(0xfa000000, 00000000), -54);
    247             case 4: return DiyFp(UINT64_2PART_C(0x9c400000, 00000000), -50);
    248             case 5: return DiyFp(UINT64_2PART_C(0xc3500000, 00000000), -47);
    249             case 6: return DiyFp(UINT64_2PART_C(0xf4240000, 00000000), -44);
    250             case 7: return DiyFp(UINT64_2PART_C(0x98968000, 00000000), -40);
    251             default:
    252                 UNREACHABLE();
    253                 return DiyFp(0, 0);
    254         }
    255     }
    256    
    257    
    258     // If the function returns true then the result is the correct double.
    259     // Otherwise it is either the correct double or the double that is just below
    260     // the correct double.
    261     static bool DiyFpStrtod(BufferReference<const char> buffer,
    262                             int exponent,
    263                             double* result) {
    264         DiyFp input;
    265         int remaining_decimals;
    266         ReadDiyFp(buffer, &input, &remaining_decimals);
    267         // Since we may have dropped some digits the input is not accurate.
    268         // If remaining_decimals is different than 0 than the error is at most
    269         // .5 ulp (unit in the last place).
    270         // We don't want to deal with fractions and therefore keep a common
    271         // denominator.
    272         const int kDenominatorLog = 3;
    273         const int kDenominator = 1 << kDenominatorLog;
    274         // Move the remaining decimals into the exponent.
    275         exponent += remaining_decimals;
    276         int error = (remaining_decimals == 0 ? 0 : kDenominator / 2);
    277        
    278         int old_e = input.e();
    279         input.Normalize();
    280         error <<= old_e - input.e();
    281        
    282         ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent);
    283         if (exponent < PowersOfTenCache::kMinDecimalExponent) {
    284             *result = 0.0;
    285             return true;
    286         }
    287         DiyFp cached_power;
    288         int cached_decimal_exponent;
    289         PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent,
    290                                                            &cached_power,
    291                                                            &cached_decimal_exponent);
    292        
    293         if (cached_decimal_exponent != exponent) {
    294             int adjustment_exponent = exponent - cached_decimal_exponent;
    295             DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent);
    296             input.Multiply(adjustment_power);
    297             if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
    298                 // The product of input with the adjustment power fits into a 64 bit
    299                 // integer.
    300                 ASSERT(DiyFp::kSignificandSize == 64);
    301             } else {
    302                 // The adjustment power is exact. There is hence only an error of 0.5.
    303                 error += kDenominator / 2;
    304             }
    305         }
    306        
    307         input.Multiply(cached_power);
    308         // The error introduced by a multiplication of a*b equals
    309         //   error_a + error_b + error_a*error_b/2^64 + 0.5
    310         // Substituting a with 'input' and b with 'cached_power' we have
    311         //   error_b = 0.5  (all cached powers have an error of less than 0.5 ulp),
    312         //   error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64
    313         int error_b = kDenominator / 2;
    314         int error_ab = (error == 0 ? 0 : 1);  // We round up to 1.
    315         int fixed_error = kDenominator / 2;
    316         error += error_b + error_ab + fixed_error;
    317        
    318         old_e = input.e();
    319         input.Normalize();
    320         error <<= old_e - input.e();
    321        
    322         // See if the double's significand changes if we add/subtract the error.
    323         int order_of_magnitude = DiyFp::kSignificandSize + input.e();
    324         int effective_significand_size =
    325         Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude);
    326         int precision_digits_count =
    327         DiyFp::kSignificandSize - effective_significand_size;
    328         if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) {
    329             // This can only happen for very small denormals. In this case the
    330             // half-way multiplied by the denominator exceeds the range of an uint64.
    331             // Simply shift everything to the right.
    332             int shift_amount = (precision_digits_count + kDenominatorLog) -
    333             DiyFp::kSignificandSize + 1;
    334             input.set_f(input.f() >> shift_amount);
    335             input.set_e(input.e() + shift_amount);
    336             // We add 1 for the lost precision of error, and kDenominator for
    337             // the lost precision of input.f().
    338             error = (error >> shift_amount) + 1 + kDenominator;
    339             precision_digits_count -= shift_amount;
    340         }
    341         // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
    342         ASSERT(DiyFp::kSignificandSize == 64);
    343         ASSERT(precision_digits_count < 64);
    344         uint64_t one64 = 1;
    345         uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
    346         uint64_t precision_bits = input.f() & precision_bits_mask;
    347         uint64_t half_way = one64 << (precision_digits_count - 1);
    348         precision_bits *= kDenominator;
    349         half_way *= kDenominator;
    350         DiyFp rounded_input(input.f() >> precision_digits_count,
    351                             input.e() + precision_digits_count);
    352         if (precision_bits >= half_way + error) {
    353             rounded_input.set_f(rounded_input.f() + 1);
    354         }
    355         // If the last_bits are too close to the half-way case than we are too
    356         // inaccurate and round down. In this case we return false so that we can
    357         // fall back to a more precise algorithm.
    358        
    359         *result = Double(rounded_input).value();
    360         if (half_way - error < precision_bits && precision_bits < half_way + error) {
    361             // Too imprecise. The caller will have to fall back to a slower version.
    362             // However the returned number is guaranteed to be either the correct
    363             // double, or the next-lower double.
    364             return false;
    365         } else {
    366             return true;
    367         }
    368     }
    369    
    370    
    371     // Returns the correct double for the buffer*10^exponent.
    372     // The variable guess should be a close guess that is either the correct double
    373     // or its lower neighbor (the nearest double less than the correct one).
    374     // Preconditions:
    375     //   buffer.length() + exponent <= kMaxDecimalPower + 1
    376     //   buffer.length() + exponent > kMinDecimalPower
    377     //   buffer.length() <= kMaxDecimalSignificantDigits
    378     static double BignumStrtod(BufferReference<const char> buffer,
    379                                int exponent,
    380                                double guess) {
    381         if (guess == Double::Infinity()) {
    382             return guess;
    383         }
    384        
    385         DiyFp upper_boundary = Double(guess).UpperBoundary();
    386        
    387         ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1);
    388         ASSERT(buffer.length() + exponent > kMinDecimalPower);
    389         ASSERT(buffer.length() <= kMaxSignificantDecimalDigits);
    390         // Make sure that the Bignum will be able to hold all our numbers.
    391         // Our Bignum implementation has a separate field for exponents. Shifts will
    392         // consume at most one bigit (< 64 bits).
    393         // ln(10) == 3.3219...
    394         ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits);
    395         Bignum input;
    396         Bignum boundary;
    397         input.AssignDecimalString(buffer);
    398         boundary.AssignUInt64(upper_boundary.f());
    399         if (exponent >= 0) {
    400             input.MultiplyByPowerOfTen(exponent);
    401         } else {
    402             boundary.MultiplyByPowerOfTen(-exponent);
    403         }
    404         if (upper_boundary.e() > 0) {
    405             boundary.ShiftLeft(upper_boundary.e());
    406         } else {
    407             input.ShiftLeft(-upper_boundary.e());
    408         }
    409         int comparison = Bignum::Compare(input, boundary);
    410         if (comparison < 0) {
    411             return guess;
    412         } else if (comparison > 0) {
    413             return Double(guess).NextDouble();
    414         } else if ((Double(guess).Significand() & 1) == 0) {
    415             // Round towards even.
    416             return guess;
    417         } else {
    418             return Double(guess).NextDouble();
    419         }
    420     }
    421    
    422    
    423     double Strtod(BufferReference<const char> buffer, int exponent) {
    424         BufferReference<const char> left_trimmed = TrimLeadingZeros(buffer);
    425         BufferReference<const char> trimmed = TrimTrailingZeros(left_trimmed);
    426         exponent += left_trimmed.length() - trimmed.length();
    427         if (trimmed.length() == 0) return 0.0;
    428         if (trimmed.length() > kMaxSignificantDecimalDigits) {
    429             char significant_buffer[kMaxSignificantDecimalDigits];
    430             int significant_exponent;
    431             TrimToMaxSignificantDigits(trimmed, exponent,
    432                                        significant_buffer, &significant_exponent);
    433             return Strtod(BufferReference<const char>(significant_buffer,
    434                                              kMaxSignificantDecimalDigits),
    435                           significant_exponent);
    436         }
    437         if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) {
    438             return Double::Infinity();
    439         }
    440         if (exponent + trimmed.length() <= kMinDecimalPower) {
    441             return 0.0;
    442         }
    443        
    444         double guess;
    445         if (DoubleStrtod(trimmed, exponent, &guess) ||
    446             DiyFpStrtod(trimmed, exponent, &guess)) {
    447             return guess;
    448         }
    449         return BignumStrtod(trimmed, exponent, guess);
    450     }
    451    
     257}
     258
     259
     260// Returns 10^exponent as an exact DiyFp.
     261// The given exponent must be in the range [1; kDecimalExponentDistance[.
     262static DiyFp AdjustmentPowerOfTen(int exponent) {
     263  ASSERT(0 < exponent);
     264  ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance);
     265  // Simply hardcode the remaining powers for the given decimal exponent
     266  // distance.
     267  ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8);
     268  switch (exponent) {
     269    case 1: return DiyFp(UINT64_2PART_C(0xa0000000, 00000000), -60);
     270    case 2: return DiyFp(UINT64_2PART_C(0xc8000000, 00000000), -57);
     271    case 3: return DiyFp(UINT64_2PART_C(0xfa000000, 00000000), -54);
     272    case 4: return DiyFp(UINT64_2PART_C(0x9c400000, 00000000), -50);
     273    case 5: return DiyFp(UINT64_2PART_C(0xc3500000, 00000000), -47);
     274    case 6: return DiyFp(UINT64_2PART_C(0xf4240000, 00000000), -44);
     275    case 7: return DiyFp(UINT64_2PART_C(0x98968000, 00000000), -40);
     276    default:
     277      UNREACHABLE();
     278  }
     279}
     280
     281
     282// If the function returns true then the result is the correct double.
     283// Otherwise it is either the correct double or the double that is just below
     284// the correct double.
     285static bool DiyFpStrtod(BufferReference<const char> buffer,
     286                        int exponent,
     287                        double* result) {
     288  DiyFp input;
     289  int remaining_decimals;
     290  ReadDiyFp(buffer, &input, &remaining_decimals);
     291  // Since we may have dropped some digits the input is not accurate.
     292  // If remaining_decimals is different than 0 than the error is at most
     293  // .5 ulp (unit in the last place).
     294  // We don't want to deal with fractions and therefore keep a common
     295  // denominator.
     296  const int kDenominatorLog = 3;
     297  const int kDenominator = 1 << kDenominatorLog;
     298  // Move the remaining decimals into the exponent.
     299  exponent += remaining_decimals;
     300  uint64_t error = (remaining_decimals == 0 ? 0 : kDenominator / 2);
     301
     302  int old_e = input.e();
     303  input.Normalize();
     304  error <<= old_e - input.e();
     305
     306  ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent);
     307  if (exponent < PowersOfTenCache::kMinDecimalExponent) {
     308    *result = 0.0;
     309    return true;
     310  }
     311  DiyFp cached_power;
     312  int cached_decimal_exponent;
     313  PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent,
     314                                                     &cached_power,
     315                                                     &cached_decimal_exponent);
     316
     317  if (cached_decimal_exponent != exponent) {
     318    int adjustment_exponent = exponent - cached_decimal_exponent;
     319    DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent);
     320    input.Multiply(adjustment_power);
     321    if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
     322      // The product of input with the adjustment power fits into a 64 bit
     323      // integer.
     324      ASSERT(DiyFp::kSignificandSize == 64);
     325    } else {
     326      // The adjustment power is exact. There is hence only an error of 0.5.
     327      error += kDenominator / 2;
     328    }
     329  }
     330
     331  input.Multiply(cached_power);
     332  // The error introduced by a multiplication of a*b equals
     333  //   error_a + error_b + error_a*error_b/2^64 + 0.5
     334  // Substituting a with 'input' and b with 'cached_power' we have
     335  //   error_b = 0.5  (all cached powers have an error of less than 0.5 ulp),
     336  //   error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64
     337  int error_b = kDenominator / 2;
     338  int error_ab = (error == 0 ? 0 : 1);  // We round up to 1.
     339  int fixed_error = kDenominator / 2;
     340  error += error_b + error_ab + fixed_error;
     341
     342  old_e = input.e();
     343  input.Normalize();
     344  error <<= old_e - input.e();
     345
     346  // See if the double's significand changes if we add/subtract the error.
     347  int order_of_magnitude = DiyFp::kSignificandSize + input.e();
     348  int effective_significand_size =
     349      Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude);
     350  int precision_digits_count =
     351      DiyFp::kSignificandSize - effective_significand_size;
     352  if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) {
     353    // This can only happen for very small denormals. In this case the
     354    // half-way multiplied by the denominator exceeds the range of an uint64.
     355    // Simply shift everything to the right.
     356    int shift_amount = (precision_digits_count + kDenominatorLog) -
     357        DiyFp::kSignificandSize + 1;
     358    input.set_f(input.f() >> shift_amount);
     359    input.set_e(input.e() + shift_amount);
     360    // We add 1 for the lost precision of error, and kDenominator for
     361    // the lost precision of input.f().
     362    error = (error >> shift_amount) + 1 + kDenominator;
     363    precision_digits_count -= shift_amount;
     364  }
     365  // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
     366  ASSERT(DiyFp::kSignificandSize == 64);
     367  ASSERT(precision_digits_count < 64);
     368  uint64_t one64 = 1;
     369  uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
     370  uint64_t precision_bits = input.f() & precision_bits_mask;
     371  uint64_t half_way = one64 << (precision_digits_count - 1);
     372  precision_bits *= kDenominator;
     373  half_way *= kDenominator;
     374  DiyFp rounded_input(input.f() >> precision_digits_count,
     375                      input.e() + precision_digits_count);
     376  if (precision_bits >= half_way + error) {
     377    rounded_input.set_f(rounded_input.f() + 1);
     378  }
     379  // If the last_bits are too close to the half-way case than we are too
     380  // inaccurate and round down. In this case we return false so that we can
     381  // fall back to a more precise algorithm.
     382
     383  *result = Double(rounded_input).value();
     384  if (half_way - error < precision_bits && precision_bits < half_way + error) {
     385    // Too imprecise. The caller will have to fall back to a slower version.
     386    // However the returned number is guaranteed to be either the correct
     387    // double, or the next-lower double.
     388    return false;
     389  } else {
     390    return true;
     391  }
     392}
     393
     394
     395// Returns
     396//   - -1 if buffer*10^exponent < diy_fp.
     397//   -  0 if buffer*10^exponent == diy_fp.
     398//   - +1 if buffer*10^exponent > diy_fp.
     399// Preconditions:
     400//   buffer.length() + exponent <= kMaxDecimalPower + 1
     401//   buffer.length() + exponent > kMinDecimalPower
     402//   buffer.length() <= kMaxDecimalSignificantDigits
     403static int CompareBufferWithDiyFp(BufferReference<const char> buffer,
     404                                  int exponent,
     405                                  DiyFp diy_fp) {
     406  ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1);
     407  ASSERT(buffer.length() + exponent > kMinDecimalPower);
     408  ASSERT(buffer.length() <= kMaxSignificantDecimalDigits);
     409  // Make sure that the Bignum will be able to hold all our numbers.
     410  // Our Bignum implementation has a separate field for exponents. Shifts will
     411  // consume at most one bigit (< 64 bits).
     412  // ln(10) == 3.3219...
     413  ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits);
     414  Bignum buffer_bignum;
     415  Bignum diy_fp_bignum;
     416  buffer_bignum.AssignDecimalString(buffer);
     417  diy_fp_bignum.AssignUInt64(diy_fp.f());
     418  if (exponent >= 0) {
     419    buffer_bignum.MultiplyByPowerOfTen(exponent);
     420  } else {
     421    diy_fp_bignum.MultiplyByPowerOfTen(-exponent);
     422  }
     423  if (diy_fp.e() > 0) {
     424    diy_fp_bignum.ShiftLeft(diy_fp.e());
     425  } else {
     426    buffer_bignum.ShiftLeft(-diy_fp.e());
     427  }
     428  return Bignum::Compare(buffer_bignum, diy_fp_bignum);
     429}
     430
     431
     432// Returns true if the guess is the correct double.
     433// Returns false, when guess is either correct or the next-lower double.
     434static bool ComputeGuess(BufferReference<const char> trimmed, int exponent,
     435                         double* guess) {
     436  if (trimmed.length() == 0) {
     437    *guess = 0.0;
     438    return true;
     439  }
     440  if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) {
     441    *guess = Double::Infinity();
     442    return true;
     443  }
     444  if (exponent + trimmed.length() <= kMinDecimalPower) {
     445    *guess = 0.0;
     446    return true;
     447  }
     448
     449  if (DoubleStrtod(trimmed, exponent, guess) ||
     450      DiyFpStrtod(trimmed, exponent, guess)) {
     451    return true;
     452  }
     453  if (*guess == Double::Infinity()) {
     454    return true;
     455  }
     456  return false;
     457}
     458
     459double Strtod(BufferReference<const char> buffer, int exponent) {
     460  char copy_buffer[kMaxSignificantDecimalDigits];
     461  BufferReference<const char> trimmed;
     462  int updated_exponent;
     463  TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
     464             &trimmed, &updated_exponent);
     465  exponent = updated_exponent;
     466
     467  double guess;
     468  bool is_correct = ComputeGuess(trimmed, exponent, &guess);
     469  if (is_correct) return guess;
     470
     471  DiyFp upper_boundary = Double(guess).UpperBoundary();
     472  int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
     473  if (comparison < 0) {
     474    return guess;
     475  } else if (comparison > 0) {
     476    return Double(guess).NextDouble();
     477  } else if ((Double(guess).Significand() & 1) == 0) {
     478    // Round towards even.
     479    return guess;
     480  } else {
     481    return Double(guess).NextDouble();
     482  }
     483}
     484
     485static float SanitizedDoubletof(double d) {
     486  ASSERT(d >= 0.0);
     487  // ASAN has a sanitize check that disallows casting doubles to floats if
     488  // they are too big.
     489  // https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks
     490  // The behavior should be covered by IEEE 754, but some projects use this
     491  // flag, so work around it.
     492  float max_finite = 3.4028234663852885981170418348451692544e+38;
     493  // The half-way point between the max-finite and infinity value.
     494  // Since infinity has an even significand everything equal or greater than
     495  // this value should become infinity.
     496  double half_max_finite_infinity =
     497      3.40282356779733661637539395458142568448e+38;
     498  if (d >= max_finite) {
     499    if (d >= half_max_finite_infinity) {
     500      return Single::Infinity();
     501    } else {
     502      return max_finite;
     503    }
     504  } else {
     505    return static_cast<float>(d);
     506  }
     507}
     508
     509float Strtof(BufferReference<const char> buffer, int exponent) {
     510  char copy_buffer[kMaxSignificantDecimalDigits];
     511  BufferReference<const char> trimmed;
     512  int updated_exponent;
     513  TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
     514             &trimmed, &updated_exponent);
     515  exponent = updated_exponent;
     516
     517  double double_guess;
     518  bool is_correct = ComputeGuess(trimmed, exponent, &double_guess);
     519
     520  float float_guess = SanitizedDoubletof(double_guess);
     521  if (float_guess == double_guess) {
     522    // This shortcut triggers for integer values.
     523    return float_guess;
     524  }
     525
     526  // We must catch double-rounding. Say the double has been rounded up, and is
     527  // now a boundary of a float, and rounds up again. This is why we have to
     528  // look at previous too.
     529  // Example (in decimal numbers):
     530  //    input: 12349
     531  //    high-precision (4 digits): 1235
     532  //    low-precision (3 digits):
     533  //       when read from input: 123
     534  //       when rounded from high precision: 124.
     535  // To do this we simply look at the neigbors of the correct result and see
     536  // if they would round to the same float. If the guess is not correct we have
     537  // to look at four values (since two different doubles could be the correct
     538  // double).
     539
     540  double double_next = Double(double_guess).NextDouble();
     541  double double_previous = Double(double_guess).PreviousDouble();
     542
     543  float f1 = SanitizedDoubletof(double_previous);
     544  float f2 = float_guess;
     545  float f3 = SanitizedDoubletof(double_next);
     546  float f4;
     547  if (is_correct) {
     548    f4 = f3;
     549  } else {
     550    double double_next2 = Double(double_next).NextDouble();
     551    f4 = SanitizedDoubletof(double_next2);
     552  }
     553  (void) f2;  // Mark variable as used.
     554  ASSERT(f1 <= f2 && f2 <= f3 && f3 <= f4);
     555
     556  // If the guess doesn't lie near a single-precision boundary we can simply
     557  // return its float-value.
     558  if (f1 == f4) {
     559    return float_guess;
     560  }
     561
     562  ASSERT((f1 != f2 && f2 == f3 && f3 == f4) ||
     563         (f1 == f2 && f2 != f3 && f3 == f4) ||
     564         (f1 == f2 && f2 == f3 && f3 != f4));
     565
     566  // guess and next are the two possible candidates (in the same way that
     567  // double_guess was the lower candidate for a double-precision guess).
     568  float guess = f1;
     569  float next = f4;
     570  DiyFp upper_boundary;
     571  if (guess == 0.0f) {
     572    float min_float = 1e-45f;
     573    upper_boundary = Double(static_cast<double>(min_float) / 2).AsDiyFp();
     574  } else {
     575    upper_boundary = Single(guess).UpperBoundary();
     576  }
     577  int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
     578  if (comparison < 0) {
     579    return guess;
     580  } else if (comparison > 0) {
     581    return next;
     582  } else if ((Single(guess).Significand() & 1) == 0) {
     583    // Round towards even.
     584    return guess;
     585  } else {
     586    return next;
     587  }
     588}
     589
    452590}  // namespace double_conversion
    453 
    454 } // namespace WTF
     591}  // namespace WTF
  • trunk/Source/WTF/wtf/dtoa/strtod.h

    r147976 r242048  
    2929#define DOUBLE_CONVERSION_STRTOD_H_
    3030
    31 #include "utils.h"
     31#include <wtf/dtoa/utils.h>
    3232
    3333namespace WTF {
     34namespace double_conversion {
    3435
    35 namespace double_conversion {
    36    
    37     // The buffer must only contain digits in the range [0-9]. It must not
    38     // contain a dot or a sign. It must not start with '0', and must not be empty.
    39     double Strtod(BufferReference<const char> buffer, int exponent);
    40    
     36// The buffer must only contain digits in the range [0-9]. It must not
     37// contain a dot or a sign. It must not start with '0', and must not be empty.
     38double Strtod(BufferReference<const char> buffer, int exponent);
     39
     40// The buffer must only contain digits in the range [0-9]. It must not
     41// contain a dot or a sign. It must not start with '0', and must not be empty.
     42float Strtof(BufferReference<const char> buffer, int exponent);
     43
    4144}  // namespace double_conversion
    42 
    43 } // namespace WTF
     45}  // namespace WTF
    4446
    4547#endif  // DOUBLE_CONVERSION_STRTOD_H_
  • trunk/Source/WTF/wtf/dtoa/utils.h

    r225040 r242048  
    3030
    3131#include <wtf/Assertions.h>
    32 #include <stdlib.h>
    33 #include <string.h>
    34 
    35 #define UNIMPLEMENTED ASSERT_NOT_REACHED
    36 #define UNREACHABLE ASSERT_NOT_REACHED
     32#include <cstdlib>
     33#include <cstring>
     34
     35#ifndef UNIMPLEMENTED
     36#define UNIMPLEMENTED() ASSERT_NOT_REACHED()
     37#endif
     38#ifndef DOUBLE_CONVERSION_NO_RETURN
     39#ifdef _MSC_VER
     40#define DOUBLE_CONVERSION_NO_RETURN __declspec(noreturn)
     41#else
     42#define DOUBLE_CONVERSION_NO_RETURN __attribute__((noreturn))
     43#endif
     44#endif
     45#ifndef UNREACHABLE
     46#ifdef _MSC_VER
     47void DOUBLE_CONVERSION_NO_RETURN abort_noreturn();
     48inline void abort_noreturn() { abort(); }
     49#define UNREACHABLE()   (abort_noreturn())
     50#else
     51#define UNREACHABLE()   (abort())
     52#endif
     53#endif
     54
    3755
    3856// Double operations detection based on target architecture.
     
    4664// disabled.)
    4765// On Linux,x86 89255e-22 != Div_double(89255.0/1e22)
     66//
     67// For example:
     68/*
     69// -- in div.c
     70double Div_double(double x, double y) { return x / y; }
     71
     72// -- in main.c
     73double Div_double(double x, double y);  // Forward declaration.
     74
     75int main(int argc, char** argv) {
     76  return Div_double(89255.0, 1e22) == 89255e-22;
     77}
     78*/
     79// Run as follows ./main || echo "correct"
     80//
     81// If it prints "correct" then the architecture should be here, in the "correct" section.
    4882#if defined(_M_X64) || defined(__x86_64__) || \
    49 defined(__ARMEL__) || \
    50 defined(_MIPS_ARCH_MIPS32R2)
     83    defined(__ARMEL__) || defined(__avr32__) || defined(_M_ARM) || defined(_M_ARM64) || \
     84    defined(__hppa__) || defined(__ia64__) || \
     85    defined(__mips__) || \
     86    defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \
     87    defined(_POWER) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \
     88    defined(__sparc__) || defined(__sparc) || defined(__s390__) || \
     89    defined(__SH4__) || defined(__alpha__) || \
     90    defined(_MIPS_ARCH_MIPS32R2) || \
     91    defined(__AARCH64EL__) || defined(__aarch64__) || defined(__AARCH64EB__) || \
     92    defined(__riscv) || \
     93    defined(__or1k__) || defined(__arc__) || \
     94    defined(__EMSCRIPTEN__)
    5195#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
    52 #elif CPU(MIPS) || CPU(MIPS64) || CPU(PPC) || CPU(PPC64) || CPU(PPC64LE) || CPU(ARM64)
    53 #define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
    54 #elif defined(_M_IX86) || defined(__i386__)
     96#elif defined(__mc68000__) || \
     97    defined(__pnacl__) || defined(__native_client__)
     98#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
     99#elif defined(_M_IX86) || defined(__i386__) || defined(__i386)
    55100#if defined(_WIN32)
    56101// Windows uses a 64bit wide floating point stack.
     
    60105#endif  // _WIN32
    61106#else
    62 // Conservatively disable double conversion for unknown architectures.
    63 #undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
    64 #endif
    65 
     107#error Target architecture was not detected as supported by Double-Conversion.
     108#endif
    66109
    67110#if defined(_WIN32) && !defined(__MINGW32__)
     
    83126#endif
    84127
     128typedef uint16_t uc16;
     129
    85130// The following macro works on both 32 and 64-bit platforms.
    86131// Usage: instead of writing 0x1234567890123456
     
    93138// array. You should only use ARRAY_SIZE on statically allocated
    94139// arrays.
     140#ifndef ARRAY_SIZE
    95141#define ARRAY_SIZE(a)                                   \
    96 ((sizeof(a) / sizeof(*(a))) /                         \
    97 static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
     142  ((sizeof(a) / sizeof(*(a))) /                         \
     143  static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
     144#endif
    98145
    99146// A macro to disallow the evil copy constructor and operator= functions
    100147// This should be used in the private: declarations for a class
    101 #define DISALLOW_COPY_AND_ASSIGN(TypeName)      \
    102 TypeName(const TypeName&);                    \
    103 void operator=(const TypeName&)
     148#ifndef DC_DISALLOW_COPY_AND_ASSIGN
     149#define DC_DISALLOW_COPY_AND_ASSIGN(TypeName)      \
     150  TypeName(const TypeName&);                    \
     151  void operator=(const TypeName&)
     152#endif
    104153
    105154// A macro to disallow all the implicit constructors, namely the
     
    109158// that wants to prevent anyone from instantiating it. This is
    110159// especially useful for classes containing only static methods.
    111 #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
    112 TypeName();                                    \
    113 DISALLOW_COPY_AND_ASSIGN(TypeName)
     160#ifndef DC_DISALLOW_IMPLICIT_CONSTRUCTORS
     161#define DC_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
     162  TypeName();                                    \
     163  DC_DISALLOW_COPY_AND_ASSIGN(TypeName)
     164#endif
    114165
    115166namespace WTF {
    116 
    117167namespace double_conversion {
    118    
    119     static const int kCharSize = sizeof(char);
    120    
    121     // Returns the maximum of the two parameters.
    122     template <typename T>
    123     static T Max(T a, T b) {
    124         return a < b ? b : a;
     168
     169static const int kCharSize = sizeof(char);
     170
     171// Returns the maximum of the two parameters.
     172template <typename T>
     173static T Max(T a, T b) {
     174  return a < b ? b : a;
     175}
     176
     177
     178// Returns the minimum of the two parameters.
     179template <typename T>
     180static T Min(T a, T b) {
     181  return a < b ? a : b;
     182}
     183
     184
     185inline int StrLength(const char* string) {
     186  size_t length = strlen(string);
     187  ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
     188  return static_cast<int>(length);
     189}
     190
     191// This is a simplified version of V8's Vector class.
     192template <typename T>
     193class BufferReference {
     194 public:
     195  BufferReference() : start_(NULL), length_(0) {}
     196  BufferReference(T* data, int len) : start_(data), length_(len) {
     197    ASSERT(len == 0 || (len > 0 && data != NULL));
     198  }
     199
     200  // Returns a BufferReference using the same backing storage as this one,
     201  // spanning from and including 'from', to but not including 'to'.
     202  BufferReference<T> SubBufferReference(int from, int to) {
     203    ASSERT(to <= length_);
     204    ASSERT(from < to);
     205    ASSERT(0 <= from);
     206    return BufferReference<T>(start() + from, to - from);
     207  }
     208
     209  // Returns the length of the BufferReference.
     210  int length() const { return length_; }
     211
     212  // Returns whether or not the BufferReference is empty.
     213  bool is_empty() const { return length_ == 0; }
     214
     215  // Returns the pointer to the start of the data in the BufferReference.
     216  T* start() const { return start_; }
     217
     218  // Access individual BufferReference elements - checks bounds in debug mode.
     219  T& operator[](int index) const {
     220    ASSERT(0 <= index && index < length_);
     221    return start_[index];
     222  }
     223
     224  T& first() { return start_[0]; }
     225
     226  T& last() { return start_[length_ - 1]; }
     227
     228 private:
     229  T* start_;
     230  int length_;
     231};
     232
     233
     234// Helper class for building result strings in a character buffer. The
     235// purpose of the class is to use safe operations that checks the
     236// buffer bounds on all operations in debug mode.
     237class StringBuilder {
     238 public:
     239  StringBuilder(char* buffer, int buffer_size)
     240      : buffer_(buffer, buffer_size), position_(0) { }
     241
     242  ~StringBuilder() { if (!is_finalized()) Finalize(); }
     243
     244  int size() const { return buffer_.length(); }
     245
     246  // Get the current position in the builder.
     247  int position() const {
     248    ASSERT(!is_finalized());
     249    return position_;
     250  }
     251
     252  // Reset the position.
     253  void Reset() { position_ = 0; }
     254
     255  // Add a single character to the builder. It is not allowed to add
     256  // 0-characters; use the Finalize() method to terminate the string
     257  // instead.
     258  void AddCharacter(char c) {
     259    ASSERT(c != '\0');
     260    ASSERT(!is_finalized() && position_ < buffer_.length());
     261    buffer_[position_++] = c;
     262  }
     263
     264  // Add an entire string to the builder. Uses strlen() internally to
     265  // compute the length of the input string.
     266  void AddString(const char* s) {
     267    AddSubstring(s, StrLength(s));
     268  }
     269
     270  // Add the first 'n' characters of the given string 's' to the
     271  // builder. The input string must have enough characters.
     272  void AddSubstring(const char* s, int n) {
     273    ASSERT(!is_finalized() && position_ + n < buffer_.length());
     274    ASSERT_WITH_SECURITY_IMPLICATION(static_cast<size_t>(n) <= strlen(s));
     275    memmove(&buffer_[position_], s, n * kCharSize);
     276    position_ += n;
     277  }
     278
     279
     280  // Add character padding to the builder. If count is non-positive,
     281  // nothing is added to the builder.
     282  void AddPadding(char c, int count) {
     283    for (int i = 0; i < count; i++) {
     284      AddCharacter(c);
    125285    }
    126    
    127    
    128     // Returns the minimum of the two parameters.
    129     template <typename T>
    130     static T Min(T a, T b) {
    131         return a < b ? a : b;
    132     }
    133    
    134    
    135     inline int StrLength(const char* string) {
    136         size_t length = strlen(string);
    137         ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
    138         return static_cast<int>(length);
    139     }
    140 
    141     // BufferReference abstract a memory buffer. It provides a pointer
    142     // to the beginning of the buffer, and the available length.
    143     template <typename T>
    144     class BufferReference {
    145     public:
    146         BufferReference() : start_(NULL), length_(0) {}
    147         BufferReference(T* data, int length) : start_(data), length_(length) {
    148             ASSERT(length == 0 || (length > 0 && data != NULL));
    149         }
    150        
    151         // Returns a vector using the same backing storage as this one,
    152         // spanning from and including 'from', to but not including 'to'.
    153         BufferReference<T> SubBufferReference(int from, int to) {
    154             ASSERT(to <= length_);
    155             ASSERT_WITH_SECURITY_IMPLICATION(from < to);
    156             ASSERT(0 <= from);
    157             return BufferReference<T>(start() + from, to - from);
    158         }
    159        
    160         // Returns the length of the vector.
    161         int length() const { return length_; }
    162        
    163         // Returns whether or not the vector is empty.
    164         bool is_empty() const { return length_ == 0; }
    165        
    166         // Returns the pointer to the start of the data in the vector.
    167         T* start() const { return start_; }
    168        
    169         // Access individual vector elements - checks bounds in debug mode.
    170         T& operator[](int index) const {
    171             ASSERT(0 <= index && index < length_);
    172             return start_[index];
    173         }
    174        
    175         T& first() { return start_[0]; }
    176        
    177         T& last() { return start_[length_ - 1]; }
    178        
    179     private:
    180         T* start_;
    181         int length_;
    182     };
    183    
    184    
    185     // Helper class for building result strings in a character buffer. The
    186     // purpose of the class is to use safe operations that checks the
    187     // buffer bounds on all operations in debug mode.
    188     class StringBuilder {
    189     public:
    190         StringBuilder(char* buffer, int size)
    191         : buffer_(buffer, size), position_(0) { }
    192        
    193         ~StringBuilder() { if (!is_finalized()) Finalize(); }
    194        
    195         int size() const { return buffer_.length(); }
    196        
    197         // Get the current position in the builder.
    198         int position() const {
    199             ASSERT(!is_finalized());
    200             return position_;
    201         }
    202          
    203         // Set the current position in the builder.
    204         void SetPosition(int position)
    205         {
    206             ASSERT(!is_finalized());
    207             ASSERT_WITH_SECURITY_IMPLICATION(position < size());
    208             position_ = position;
    209         }
    210        
    211         // Reset the position.
    212         void Reset() { position_ = 0; }
    213        
    214         // Add a single character to the builder. It is not allowed to add
    215         // 0-characters; use the Finalize() method to terminate the string
    216         // instead.
    217         void AddCharacter(char c) {
    218             ASSERT(c != '\0');
    219             ASSERT(!is_finalized() && position_ < buffer_.length());
    220             buffer_[position_++] = c;
    221         }
    222        
    223         // Add an entire string to the builder. Uses strlen() internally to
    224         // compute the length of the input string.
    225         void AddString(const char* s) {
    226             AddSubstring(s, StrLength(s));
    227         }
    228        
    229         // Add the first 'n' characters of the given string 's' to the
    230         // builder. The input string must have enough characters.
    231         void AddSubstring(const char* s, int n) {
    232             ASSERT(!is_finalized() && position_ + n < buffer_.length());
    233             ASSERT_WITH_SECURITY_IMPLICATION(static_cast<size_t>(n) <= strlen(s));
    234             memcpy(&buffer_[position_], s, n * kCharSize);
    235             position_ += n;
    236         }
    237        
    238        
    239         // Add character padding to the builder. If count is non-positive,
    240         // nothing is added to the builder.
    241         void AddPadding(char c, int count) {
    242             for (int i = 0; i < count; i++) {
    243                 AddCharacter(c);
    244             }
    245         }
    246        
    247         void RemoveCharacters(int start, int end)
    248         {
    249             ASSERT(start >= 0);
    250             ASSERT(end >= 0);
    251             ASSERT(start <= end);
    252             ASSERT(end <= position_);
    253             std::memmove(&buffer_[start], &buffer_[end], position_ - end);
    254             position_ -= end - start;
    255         }
    256 
    257         // Finalize the string by 0-terminating it and returning the buffer.
    258         char* Finalize() {
    259             ASSERT(!is_finalized() && position_ < buffer_.length());
    260             buffer_[position_] = '\0';
    261             // Make sure nobody managed to add a 0-character to the
    262             // buffer while building the string.
    263             ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_));
    264             position_ = -1;
    265             ASSERT(is_finalized());
    266             return buffer_.start();
    267         }
    268        
    269     private:
    270         BufferReference<char> buffer_;
    271         int position_;
    272        
    273         bool is_finalized() const { return position_ < 0; }
    274        
    275         DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
    276     };
    277    
    278     // The type-based aliasing rule allows the compiler to assume that pointers of
    279     // different types (for some definition of different) never alias each other.
    280     // Thus the following code does not work:
    281     //
    282     // float f = foo();
    283     // int fbits = *(int*)(&f);
    284     //
    285     // The compiler 'knows' that the int pointer can't refer to f since the types
    286     // don't match, so the compiler may cache f in a register, leaving random data
    287     // in fbits.  Using C++ style casts makes no difference, however a pointer to
    288     // char data is assumed to alias any other pointer.  This is the 'memcpy
    289     // exception'.
    290     //
    291     // Bit_cast uses the memcpy exception to move the bits from a variable of one
    292     // type of a variable of another type.  Of course the end result is likely to
    293     // be implementation dependent.  Most compilers (gcc-4.2 and MSVC 2005)
    294     // will completely optimize BitCast away.
    295     //
    296     // There is an additional use for BitCast.
    297     // Recent gccs will warn when they see casts that may result in breakage due to
    298     // the type-based aliasing rule.  If you have checked that there is no breakage
    299     // you can use BitCast to cast one pointer type to another.  This confuses gcc
    300     // enough that it can no longer see that you have cast one pointer type to
    301     // another thus avoiding the warning.
    302     template <class Dest, class Source>
    303     inline Dest BitCast(const Source& source) {
    304         // Compile time assertion: sizeof(Dest) == sizeof(Source)
    305         // A compile error here means your Dest and Source have different sizes.
    306         static_assert(sizeof(Dest) == sizeof(Source), "Source and destination sizes must be equal");
    307        
    308         Dest dest;
    309         memcpy(&dest, &source, sizeof(dest));
    310         return dest;
    311     }
    312    
    313     template <class Dest, class Source>
    314     inline Dest BitCast(Source* source) {
    315         return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
    316     }
    317    
     286  }
     287
     288  void RemoveCharacters(int start, int end) {
     289    ASSERT(start >= 0);
     290    ASSERT(end >= 0);
     291    ASSERT(start <= end);
     292    ASSERT(end <= position_);
     293    std::memmove(&buffer_[start], &buffer_[end], position_ - end);
     294    position_ -= end - start;
     295  }
     296
     297  // Finalize the string by 0-terminating it and returning the buffer.
     298  char* Finalize() {
     299    ASSERT(!is_finalized() && position_ < buffer_.length());
     300    buffer_[position_] = '\0';
     301    // Make sure nobody managed to add a 0-character to the
     302    // buffer while building the string.
     303    ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_));
     304    position_ = -1;
     305    ASSERT(is_finalized());
     306    return buffer_.start();
     307  }
     308
     309 private:
     310  BufferReference<char> buffer_;
     311  int position_;
     312
     313  bool is_finalized() const { return position_ < 0; }
     314
     315  DC_DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
     316};
     317
     318// The type-based aliasing rule allows the compiler to assume that pointers of
     319// different types (for some definition of different) never alias each other.
     320// Thus the following code does not work:
     321//
     322// float f = foo();
     323// int fbits = *(int*)(&f);
     324//
     325// The compiler 'knows' that the int pointer can't refer to f since the types
     326// don't match, so the compiler may cache f in a register, leaving random data
     327// in fbits.  Using C++ style casts makes no difference, however a pointer to
     328// char data is assumed to alias any other pointer.  This is the 'memcpy
     329// exception'.
     330//
     331// Bit_cast uses the memcpy exception to move the bits from a variable of one
     332// type of a variable of another type.  Of course the end result is likely to
     333// be implementation dependent.  Most compilers (gcc-4.2 and MSVC 2005)
     334// will completely optimize BitCast away.
     335//
     336// There is an additional use for BitCast.
     337// Recent gccs will warn when they see casts that may result in breakage due to
     338// the type-based aliasing rule.  If you have checked that there is no breakage
     339// you can use BitCast to cast one pointer type to another.  This confuses gcc
     340// enough that it can no longer see that you have cast one pointer type to
     341// another thus avoiding the warning.
     342template <class Dest, class Source>
     343inline Dest BitCast(const Source& source) {
     344  // Compile time assertion: sizeof(Dest) == sizeof(Source)
     345  // A compile error here means your Dest and Source have different sizes.
     346#if __cplusplus >= 201103L
     347  static_assert(sizeof(Dest) == sizeof(Source),
     348                "source and destination size mismatch");
     349#else
     350  typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1];
     351#endif
     352
     353  Dest dest;
     354  memmove(&dest, &source, sizeof(dest));
     355  return dest;
     356}
     357
     358template <class Dest, class Source>
     359inline Dest BitCast(Source* source) {
     360  return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
     361}
     362
    318363}  // namespace double_conversion
    319 
    320 } // namespace WTF
     364}  // namespace WTF
    321365
    322366#endif  // DOUBLE_CONVERSION_UTILS_H_
Note: See TracChangeset for help on using the changeset viewer.