Debian Codegraph @

rhino/src/org/mozilla/javascript/v8dtoa/FastDtoaBuilder.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript.v8dtoa;
8
9 import java.util.Arrays;
10
11 public class FastDtoaBuilder {
12
13 // allocate buffer for generated digits + extra notation + padding zeroes
14 final char[] chars = new char[FastDtoa.kFastDtoaMaximalLength + 8];
15 int end = 0;
16 int point;
17 boolean formatted = false;
18
19 void append(char c) {
20 chars[end++] = c;
21 }
22
23 void decreaseLast() {
24 chars[end - 1]--;
25 }
26
27 public void reset() {
28 end = 0;
29 formatted = false;
30 }
31
32 @Override
33 public String toString() {
34 return "[chars:" + new String(chars, 0, end) + ", point:" + point + "]";
35 }
36
37 public String format() {
38 if (!formatted) {
39 // check for minus sign
40 int firstDigit = chars[0] == '-' ? 1 : 0;
41 int decPoint = point - firstDigit;
42 if (decPoint < -5 || decPoint > 21) {
43 toExponentialFormat(firstDigit, decPoint);
44 } else {
45 toFixedFormat(firstDigit, decPoint);
46 }
47 formatted = true;
48 }
49 return new String(chars, 0, end);
50
51 }
52
53 private void toFixedFormat(int firstDigit, int decPoint) {
54 if (point < end) {
55 // insert decimal point
56 if (decPoint > 0) {
57 // >= 1, split decimals and insert point
58 System.arraycopy(chars, point, chars, point + 1, end - point);
59 chars[point] = '.';
60 end++;
61 } else {
62 // < 1,
63 int target = firstDigit + 2 - decPoint;
64 System.arraycopy(chars, firstDigit, chars, target, end - firstDigit);
65 chars[firstDigit] = '0';
66 chars[firstDigit + 1] = '.';
67 if (decPoint < 0) {
68 Arrays.fill(chars, firstDigit + 2, target, '0');
69 }
70 end += 2 - decPoint;
71 }
72 } else if (point > end) {
73 // large integer, add trailing zeroes
74 Arrays.fill(chars, end, point, '0');
75 end += point - end;
76 }
77 }
78
79 private void toExponentialFormat(int firstDigit, int decPoint) {
80 if (end - firstDigit > 1) {
81 // insert decimal point if more than one digit was produced
82 int dot = firstDigit + 1;
83 System.arraycopy(chars, dot, chars, dot + 1, end - dot);
84 chars[dot] = '.';
85 end++;
86 }
87 chars[end++] = 'e';
88 char sign = '+';
89 int exp = decPoint - 1;
90 if (exp < 0) {
91 sign = '-';
92 exp = -exp;
93 }
94 chars[end++] = sign;
95
96 int charPos = exp > 99 ? end + 2 : exp > 9 ? end + 1 : end;
97 end = charPos + 1;
98
99 // code below is needed because Integer.getChars() is not public
100 for (;;) {
101 int r = exp % 10;
102 chars[charPos--] = digits[r];
103 exp = exp / 10;
104 if (exp == 0) break;
105 }
106 }
107
108 final static char[] digits = {
109 '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9'
110 };
111 }