• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <cmath>
6 
7 #include "src/base/logging.h"
8 #include "src/utils.h"
9 
10 #include "src/dtoa.h"
11 
12 #include "src/bignum-dtoa.h"
13 #include "src/double.h"
14 #include "src/fast-dtoa.h"
15 #include "src/fixed-dtoa.h"
16 
17 namespace v8 {
18 namespace internal {
19 
DtoaToBignumDtoaMode(DtoaMode dtoa_mode)20 static BignumDtoaMode DtoaToBignumDtoaMode(DtoaMode dtoa_mode) {
21   switch (dtoa_mode) {
22     case DTOA_SHORTEST:  return BIGNUM_DTOA_SHORTEST;
23     case DTOA_FIXED:     return BIGNUM_DTOA_FIXED;
24     case DTOA_PRECISION: return BIGNUM_DTOA_PRECISION;
25     default:
26       UNREACHABLE();
27       return BIGNUM_DTOA_SHORTEST;  // To silence compiler.
28   }
29 }
30 
31 
DoubleToAscii(double v,DtoaMode mode,int requested_digits,Vector<char> buffer,int * sign,int * length,int * point)32 void DoubleToAscii(double v, DtoaMode mode, int requested_digits,
33                    Vector<char> buffer, int* sign, int* length, int* point) {
34   DCHECK(!Double(v).IsSpecial());
35   DCHECK(mode == DTOA_SHORTEST || requested_digits >= 0);
36 
37   if (Double(v).Sign() < 0) {
38     *sign = 1;
39     v = -v;
40   } else {
41     *sign = 0;
42   }
43 
44   if (v == 0) {
45     buffer[0] = '0';
46     buffer[1] = '\0';
47     *length = 1;
48     *point = 1;
49     return;
50   }
51 
52   if (mode == DTOA_PRECISION && requested_digits == 0) {
53     buffer[0] = '\0';
54     *length = 0;
55     return;
56   }
57 
58   bool fast_worked;
59   switch (mode) {
60     case DTOA_SHORTEST:
61       fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, buffer, length, point);
62       break;
63     case DTOA_FIXED:
64       fast_worked = FastFixedDtoa(v, requested_digits, buffer, length, point);
65       break;
66     case DTOA_PRECISION:
67       fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits,
68                              buffer, length, point);
69       break;
70     default:
71       UNREACHABLE();
72       fast_worked = false;
73   }
74   if (fast_worked) return;
75 
76   // If the fast dtoa didn't succeed use the slower bignum version.
77   BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
78   BignumDtoa(v, bignum_mode, requested_digits, buffer, length, point);
79   buffer[*length] = '\0';
80 }
81 
82 }  // namespace internal
83 }  // namespace v8
84