You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

404 line
15 KiB

  1. // Copyright 2010 the V8 project authors. All rights reserved.
  2. // Redistribution and use in source and binary forms, with or without
  3. // modification, are permitted provided that the following conditions are
  4. // met:
  5. //
  6. // * Redistributions of source code must retain the above copyright
  7. // notice, this list of conditions and the following disclaimer.
  8. // * Redistributions in binary form must reproduce the above
  9. // copyright notice, this list of conditions and the following
  10. // disclaimer in the documentation and/or other materials provided
  11. // with the distribution.
  12. // * Neither the name of Google Inc. nor the names of its
  13. // contributors may be used to endorse or promote products derived
  14. // from this software without specific prior written permission.
  15. //
  16. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  17. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  18. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  19. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  20. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  21. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  22. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  26. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. #include <math.h>
  28. #include "fixed-dtoa.h"
  29. #include "ieee.h"
  30. namespace double_conversion {
  31. // Represents a 128bit type. This class should be replaced by a native type on
  32. // platforms that support 128bit integers.
  33. class UInt128 {
  34. public:
  35. UInt128() : high_bits_(0), low_bits_(0) { }
  36. UInt128(uint64_t high, uint64_t low) : high_bits_(high), low_bits_(low) { }
  37. void Multiply(uint32_t multiplicand) {
  38. uint64_t accumulator;
  39. accumulator = (low_bits_ & kMask32) * multiplicand;
  40. uint32_t part = static_cast<uint32_t>(accumulator & kMask32);
  41. accumulator >>= 32;
  42. accumulator = accumulator + (low_bits_ >> 32) * multiplicand;
  43. low_bits_ = (accumulator << 32) + part;
  44. accumulator >>= 32;
  45. accumulator = accumulator + (high_bits_ & kMask32) * multiplicand;
  46. part = static_cast<uint32_t>(accumulator & kMask32);
  47. accumulator >>= 32;
  48. accumulator = accumulator + (high_bits_ >> 32) * multiplicand;
  49. high_bits_ = (accumulator << 32) + part;
  50. ASSERT((accumulator >> 32) == 0);
  51. }
  52. void Shift(int shift_amount) {
  53. ASSERT(-64 <= shift_amount && shift_amount <= 64);
  54. if (shift_amount == 0) {
  55. return;
  56. } else if (shift_amount == -64) {
  57. high_bits_ = low_bits_;
  58. low_bits_ = 0;
  59. } else if (shift_amount == 64) {
  60. low_bits_ = high_bits_;
  61. high_bits_ = 0;
  62. } else if (shift_amount <= 0) {
  63. high_bits_ <<= -shift_amount;
  64. high_bits_ += low_bits_ >> (64 + shift_amount);
  65. low_bits_ <<= -shift_amount;
  66. } else {
  67. low_bits_ >>= shift_amount;
  68. low_bits_ += high_bits_ << (64 - shift_amount);
  69. high_bits_ >>= shift_amount;
  70. }
  71. }
  72. // Modifies *this to *this MOD (2^power).
  73. // Returns *this DIV (2^power).
  74. int DivModPowerOf2(int power) {
  75. if (power >= 64) {
  76. int result = static_cast<int>(high_bits_ >> (power - 64));
  77. high_bits_ -= static_cast<uint64_t>(result) << (power - 64);
  78. return result;
  79. } else {
  80. uint64_t part_low = low_bits_ >> power;
  81. uint64_t part_high = high_bits_ << (64 - power);
  82. int result = static_cast<int>(part_low + part_high);
  83. high_bits_ = 0;
  84. low_bits_ -= part_low << power;
  85. return result;
  86. }
  87. }
  88. bool IsZero() const {
  89. return high_bits_ == 0 && low_bits_ == 0;
  90. }
  91. int BitAt(int position) {
  92. if (position >= 64) {
  93. return static_cast<int>(high_bits_ >> (position - 64)) & 1;
  94. } else {
  95. return static_cast<int>(low_bits_ >> position) & 1;
  96. }
  97. }
  98. private:
  99. static const uint64_t kMask32 = 0xFFFFFFFF;
  100. // Value == (high_bits_ << 64) + low_bits_
  101. uint64_t high_bits_;
  102. uint64_t low_bits_;
  103. };
  104. static const int kDoubleSignificandSize = 53; // Includes the hidden bit.
  105. static void FillDigits32FixedLength(uint32_t number, int requested_length,
  106. Vector<char> buffer, int* length) {
  107. for (int i = requested_length - 1; i >= 0; --i) {
  108. buffer[(*length) + i] = '0' + number % 10;
  109. number /= 10;
  110. }
  111. *length += requested_length;
  112. }
  113. static void FillDigits32(uint32_t number, Vector<char> buffer, int* length) {
  114. int number_length = 0;
  115. // We fill the digits in reverse order and exchange them afterwards.
  116. while (number != 0) {
  117. int digit = number % 10;
  118. number /= 10;
  119. buffer[(*length) + number_length] = static_cast<char>('0' + digit);
  120. number_length++;
  121. }
  122. // Exchange the digits.
  123. int i = *length;
  124. int j = *length + number_length - 1;
  125. while (i < j) {
  126. char tmp = buffer[i];
  127. buffer[i] = buffer[j];
  128. buffer[j] = tmp;
  129. i++;
  130. j--;
  131. }
  132. *length += number_length;
  133. }
  134. static void FillDigits64FixedLength(uint64_t number,
  135. Vector<char> buffer, int* length) {
  136. const uint32_t kTen7 = 10000000;
  137. // For efficiency cut the number into 3 uint32_t parts, and print those.
  138. uint32_t part2 = static_cast<uint32_t>(number % kTen7);
  139. number /= kTen7;
  140. uint32_t part1 = static_cast<uint32_t>(number % kTen7);
  141. uint32_t part0 = static_cast<uint32_t>(number / kTen7);
  142. FillDigits32FixedLength(part0, 3, buffer, length);
  143. FillDigits32FixedLength(part1, 7, buffer, length);
  144. FillDigits32FixedLength(part2, 7, buffer, length);
  145. }
  146. static void FillDigits64(uint64_t number, Vector<char> buffer, int* length) {
  147. const uint32_t kTen7 = 10000000;
  148. // For efficiency cut the number into 3 uint32_t parts, and print those.
  149. uint32_t part2 = static_cast<uint32_t>(number % kTen7);
  150. number /= kTen7;
  151. uint32_t part1 = static_cast<uint32_t>(number % kTen7);
  152. uint32_t part0 = static_cast<uint32_t>(number / kTen7);
  153. if (part0 != 0) {
  154. FillDigits32(part0, buffer, length);
  155. FillDigits32FixedLength(part1, 7, buffer, length);
  156. FillDigits32FixedLength(part2, 7, buffer, length);
  157. } else if (part1 != 0) {
  158. FillDigits32(part1, buffer, length);
  159. FillDigits32FixedLength(part2, 7, buffer, length);
  160. } else {
  161. FillDigits32(part2, buffer, length);
  162. }
  163. }
  164. static void RoundUp(Vector<char> buffer, int* length, int* decimal_point) {
  165. // An empty buffer represents 0.
  166. if (*length == 0) {
  167. buffer[0] = '1';
  168. *decimal_point = 1;
  169. *length = 1;
  170. return;
  171. }
  172. // Round the last digit until we either have a digit that was not '9' or until
  173. // we reached the first digit.
  174. buffer[(*length) - 1]++;
  175. for (int i = (*length) - 1; i > 0; --i) {
  176. if (buffer[i] != '0' + 10) {
  177. return;
  178. }
  179. buffer[i] = '0';
  180. buffer[i - 1]++;
  181. }
  182. // If the first digit is now '0' + 10, we would need to set it to '0' and add
  183. // a '1' in front. However we reach the first digit only if all following
  184. // digits had been '9' before rounding up. Now all trailing digits are '0' and
  185. // we simply switch the first digit to '1' and update the decimal-point
  186. // (indicating that the point is now one digit to the right).
  187. if (buffer[0] == '0' + 10) {
  188. buffer[0] = '1';
  189. (*decimal_point)++;
  190. }
  191. }
  192. // The given fractionals number represents a fixed-point number with binary
  193. // point at bit (-exponent).
  194. // Preconditions:
  195. // -128 <= exponent <= 0.
  196. // 0 <= fractionals * 2^exponent < 1
  197. // The buffer holds the result.
  198. // The function will round its result. During the rounding-process digits not
  199. // generated by this function might be updated, and the decimal-point variable
  200. // might be updated. If this function generates the digits 99 and the buffer
  201. // already contained "199" (thus yielding a buffer of "19999") then a
  202. // rounding-up will change the contents of the buffer to "20000".
  203. static void FillFractionals(uint64_t fractionals, int exponent,
  204. int fractional_count, Vector<char> buffer,
  205. int* length, int* decimal_point) {
  206. ASSERT(-128 <= exponent && exponent <= 0);
  207. // 'fractionals' is a fixed-point number, with binary point at bit
  208. // (-exponent). Inside the function the non-converted remainder of fractionals
  209. // is a fixed-point number, with binary point at bit 'point'.
  210. if (-exponent <= 64) {
  211. // One 64 bit number is sufficient.
  212. ASSERT(fractionals >> 56 == 0);
  213. int point = -exponent;
  214. for (int i = 0; i < fractional_count; ++i) {
  215. if (fractionals == 0) break;
  216. // Instead of multiplying by 10 we multiply by 5 and adjust the point
  217. // location. This way the fractionals variable will not overflow.
  218. // Invariant at the beginning of the loop: fractionals < 2^point.
  219. // Initially we have: point <= 64 and fractionals < 2^56
  220. // After each iteration the point is decremented by one.
  221. // Note that 5^3 = 125 < 128 = 2^7.
  222. // Therefore three iterations of this loop will not overflow fractionals
  223. // (even without the subtraction at the end of the loop body). At this
  224. // time point will satisfy point <= 61 and therefore fractionals < 2^point
  225. // and any further multiplication of fractionals by 5 will not overflow.
  226. fractionals *= 5;
  227. point--;
  228. int digit = static_cast<int>(fractionals >> point);
  229. ASSERT(digit <= 9);
  230. buffer[*length] = static_cast<char>('0' + digit);
  231. (*length)++;
  232. fractionals -= static_cast<uint64_t>(digit) << point;
  233. }
  234. // If the first bit after the point is set we have to round up.
  235. if (((fractionals >> (point - 1)) & 1) == 1) {
  236. RoundUp(buffer, length, decimal_point);
  237. }
  238. } else { // We need 128 bits.
  239. ASSERT(64 < -exponent && -exponent <= 128);
  240. UInt128 fractionals128 = UInt128(fractionals, 0);
  241. fractionals128.Shift(-exponent - 64);
  242. int point = 128;
  243. for (int i = 0; i < fractional_count; ++i) {
  244. if (fractionals128.IsZero()) break;
  245. // As before: instead of multiplying by 10 we multiply by 5 and adjust the
  246. // point location.
  247. // This multiplication will not overflow for the same reasons as before.
  248. fractionals128.Multiply(5);
  249. point--;
  250. int digit = fractionals128.DivModPowerOf2(point);
  251. ASSERT(digit <= 9);
  252. buffer[*length] = static_cast<char>('0' + digit);
  253. (*length)++;
  254. }
  255. if (fractionals128.BitAt(point - 1) == 1) {
  256. RoundUp(buffer, length, decimal_point);
  257. }
  258. }
  259. }
  260. // Removes leading and trailing zeros.
  261. // If leading zeros are removed then the decimal point position is adjusted.
  262. static void TrimZeros(Vector<char> buffer, int* length, int* decimal_point) {
  263. while (*length > 0 && buffer[(*length) - 1] == '0') {
  264. (*length)--;
  265. }
  266. int first_non_zero = 0;
  267. while (first_non_zero < *length && buffer[first_non_zero] == '0') {
  268. first_non_zero++;
  269. }
  270. if (first_non_zero != 0) {
  271. for (int i = first_non_zero; i < *length; ++i) {
  272. buffer[i - first_non_zero] = buffer[i];
  273. }
  274. *length -= first_non_zero;
  275. *decimal_point -= first_non_zero;
  276. }
  277. }
  278. bool FastFixedDtoa(double v,
  279. int fractional_count,
  280. Vector<char> buffer,
  281. int* length,
  282. int* decimal_point) {
  283. const uint32_t kMaxUInt32 = 0xFFFFFFFF;
  284. uint64_t significand = Double(v).Significand();
  285. int exponent = Double(v).Exponent();
  286. // v = significand * 2^exponent (with significand a 53bit integer).
  287. // If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
  288. // don't know how to compute the representation. 2^73 ~= 9.5*10^21.
  289. // If necessary this limit could probably be increased, but we don't need
  290. // more.
  291. if (exponent > 20) return false;
  292. if (fractional_count > 20) return false;
  293. *length = 0;
  294. // At most kDoubleSignificandSize bits of the significand are non-zero.
  295. // Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
  296. // bits: 0..11*..0xxx..53*..xx
  297. if (exponent + kDoubleSignificandSize > 64) {
  298. // The exponent must be > 11.
  299. //
  300. // We know that v = significand * 2^exponent.
  301. // And the exponent > 11.
  302. // We simplify the task by dividing v by 10^17.
  303. // The quotient delivers the first digits, and the remainder fits into a 64
  304. // bit number.
  305. // Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
  306. const uint64_t kFive17 = UINT64_2PART_C(0xB1, A2BC2EC5); // 5^17
  307. uint64_t divisor = kFive17;
  308. int divisor_power = 17;
  309. uint64_t dividend = significand;
  310. uint32_t quotient;
  311. uint64_t remainder;
  312. // Let v = f * 2^e with f == significand and e == exponent.
  313. // Then need q (quotient) and r (remainder) as follows:
  314. // v = q * 10^17 + r
  315. // f * 2^e = q * 10^17 + r
  316. // f * 2^e = q * 5^17 * 2^17 + r
  317. // If e > 17 then
  318. // f * 2^(e-17) = q * 5^17 + r/2^17
  319. // else
  320. // f = q * 5^17 * 2^(17-e) + r/2^e
  321. if (exponent > divisor_power) {
  322. // We only allow exponents of up to 20 and therefore (17 - e) <= 3
  323. dividend <<= exponent - divisor_power;
  324. quotient = static_cast<uint32_t>(dividend / divisor);
  325. remainder = (dividend % divisor) << divisor_power;
  326. } else {
  327. divisor <<= divisor_power - exponent;
  328. quotient = static_cast<uint32_t>(dividend / divisor);
  329. remainder = (dividend % divisor) << exponent;
  330. }
  331. FillDigits32(quotient, buffer, length);
  332. FillDigits64FixedLength(remainder, buffer, length);
  333. *decimal_point = *length;
  334. } else if (exponent >= 0) {
  335. // 0 <= exponent <= 11
  336. significand <<= exponent;
  337. FillDigits64(significand, buffer, length);
  338. *decimal_point = *length;
  339. } else if (exponent > -kDoubleSignificandSize) {
  340. // We have to cut the number.
  341. uint64_t integrals = significand >> -exponent;
  342. uint64_t fractionals = significand - (integrals << -exponent);
  343. if (integrals > kMaxUInt32) {
  344. FillDigits64(integrals, buffer, length);
  345. } else {
  346. FillDigits32(static_cast<uint32_t>(integrals), buffer, length);
  347. }
  348. *decimal_point = *length;
  349. FillFractionals(fractionals, exponent, fractional_count,
  350. buffer, length, decimal_point);
  351. } else if (exponent < -128) {
  352. // This configuration (with at most 20 digits) means that all digits must be
  353. // 0.
  354. ASSERT(fractional_count <= 20);
  355. buffer[0] = '\0';
  356. *length = 0;
  357. *decimal_point = -fractional_count;
  358. } else {
  359. *decimal_point = 0;
  360. FillFractionals(significand, exponent, fractional_count,
  361. buffer, length, decimal_point);
  362. }
  363. TrimZeros(buffer, length, decimal_point);
  364. buffer[*length] = '\0';
  365. if ((*length) == 0) {
  366. // The string is empty and the decimal_point thus has no importance. Mimick
  367. // Gay's dtoa and and set it to -fractional_count.
  368. *decimal_point = -fractional_count;
  369. }
  370. return true;
  371. }
  372. } // namespace double_conversion