• 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 "include/v8stdint.h"
8 #include "src/checks.h"
9 #include "src/utils.h"
10 
11 #include "src/dtoa.h"
12 
13 #include "src/bignum-dtoa.h"
14 #include "src/double.h"
15 #include "src/fast-dtoa.h"
16 #include "src/fixed-dtoa.h"
17 
18 namespace v8 {
19 namespace internal {
20 
DtoaToBignumDtoaMode(DtoaMode dtoa_mode)21 static BignumDtoaMode DtoaToBignumDtoaMode(DtoaMode dtoa_mode) {
22   switch (dtoa_mode) {
23     case DTOA_SHORTEST:  return BIGNUM_DTOA_SHORTEST;
24     case DTOA_FIXED:     return BIGNUM_DTOA_FIXED;
25     case DTOA_PRECISION: return BIGNUM_DTOA_PRECISION;
26     default:
27       UNREACHABLE();
28       return BIGNUM_DTOA_SHORTEST;  // To silence compiler.
29   }
30 }
31 
32 
DoubleToAscii(double v,DtoaMode mode,int requested_digits,Vector<char> buffer,int * sign,int * length,int * point)33 void DoubleToAscii(double v, DtoaMode mode, int requested_digits,
34                    Vector<char> buffer, int* sign, int* length, int* point) {
35   ASSERT(!Double(v).IsSpecial());
36   ASSERT(mode == DTOA_SHORTEST || requested_digits >= 0);
37 
38   if (Double(v).Sign() < 0) {
39     *sign = 1;
40     v = -v;
41   } else {
42     *sign = 0;
43   }
44 
45   if (v == 0) {
46     buffer[0] = '0';
47     buffer[1] = '\0';
48     *length = 1;
49     *point = 1;
50     return;
51   }
52 
53   if (mode == DTOA_PRECISION && requested_digits == 0) {
54     buffer[0] = '\0';
55     *length = 0;
56     return;
57   }
58 
59   bool fast_worked;
60   switch (mode) {
61     case DTOA_SHORTEST:
62       fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, buffer, length, point);
63       break;
64     case DTOA_FIXED:
65       fast_worked = FastFixedDtoa(v, requested_digits, buffer, length, point);
66       break;
67     case DTOA_PRECISION:
68       fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits,
69                              buffer, length, point);
70       break;
71     default:
72       UNREACHABLE();
73       fast_worked = false;
74   }
75   if (fast_worked) return;
76 
77   // If the fast dtoa didn't succeed use the slower bignum version.
78   BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
79   BignumDtoa(v, bignum_mode, requested_digits, buffer, length, point);
80   buffer[*length] = '\0';
81 }
82 
83 } }  // namespace v8::internal
84