| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package org.mozilla.javascript.v8dtoa; |
| 8 |
|
| 9 |
import java.util.Arrays; |
| 10 |
|
| 11 |
public class FastDtoaBuilder { |
| 12 |
|
| 13 |
|
| 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 |
|
| 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 |
|
| 56 |
if (decPoint > 0) { |
| 57 |
|
| 58 |
System.arraycopy(chars, point, chars, point + 1, end - point); |
| 59 |
chars[point] = '.'; |
| 60 |
end++; |
| 61 |
} else { |
| 62 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
} |