fixed-dtoa.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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 <cmath>
  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. DOUBLE_CONVERSION_ASSERT((accumulator >> 32) == 0);
  51. }
  52. void Shift(int shift_amount) {
  53. DOUBLE_CONVERSION_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) const {
  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. DOUBLE_CONVERSION_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. DOUBLE_CONVERSION_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. DOUBLE_CONVERSION_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. DOUBLE_CONVERSION_ASSERT(fractionals == 0 || point - 1 >= 0);
  236. if ((fractionals != 0) && ((fractionals >> (point - 1)) & 1) == 1) {
  237. RoundUp(buffer, length, decimal_point);
  238. }
  239. } else { // We need 128 bits.
  240. DOUBLE_CONVERSION_ASSERT(64 < -exponent && -exponent <= 128);
  241. UInt128 fractionals128 = UInt128(fractionals, 0);
  242. fractionals128.Shift(-exponent - 64);
  243. int point = 128;
  244. for (int i = 0; i < fractional_count; ++i) {
  245. if (fractionals128.IsZero()) break;
  246. // As before: instead of multiplying by 10 we multiply by 5 and adjust the
  247. // point location.
  248. // This multiplication will not overflow for the same reasons as before.
  249. fractionals128.Multiply(5);
  250. point--;
  251. int digit = fractionals128.DivModPowerOf2(point);
  252. DOUBLE_CONVERSION_ASSERT(digit <= 9);
  253. buffer[*length] = static_cast<char>('0' + digit);
  254. (*length)++;
  255. }
  256. if (fractionals128.BitAt(point - 1) == 1) {
  257. RoundUp(buffer, length, decimal_point);
  258. }
  259. }
  260. }
  261. // Removes leading and trailing zeros.
  262. // If leading zeros are removed then the decimal point position is adjusted.
  263. static void TrimZeros(Vector<char> buffer, int* length, int* decimal_point) {
  264. while (*length > 0 && buffer[(*length) - 1] == '0') {
  265. (*length)--;
  266. }
  267. int first_non_zero = 0;
  268. while (first_non_zero < *length && buffer[first_non_zero] == '0') {
  269. first_non_zero++;
  270. }
  271. if (first_non_zero != 0) {
  272. for (int i = first_non_zero; i < *length; ++i) {
  273. buffer[i - first_non_zero] = buffer[i];
  274. }
  275. *length -= first_non_zero;
  276. *decimal_point -= first_non_zero;
  277. }
  278. }
  279. bool FastFixedDtoa(double v,
  280. int fractional_count,
  281. Vector<char> buffer,
  282. int* length,
  283. int* decimal_point) {
  284. const uint32_t kMaxUInt32 = 0xFFFFFFFF;
  285. uint64_t significand = Double(v).Significand();
  286. int exponent = Double(v).Exponent();
  287. // v = significand * 2^exponent (with significand a 53bit integer).
  288. // If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
  289. // don't know how to compute the representation. 2^73 ~= 9.5*10^21.
  290. // If necessary this limit could probably be increased, but we don't need
  291. // more.
  292. if (exponent > 20) return false;
  293. if (fractional_count > 20) return false;
  294. *length = 0;
  295. // At most kDoubleSignificandSize bits of the significand are non-zero.
  296. // Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
  297. // bits: 0..11*..0xxx..53*..xx
  298. if (exponent + kDoubleSignificandSize > 64) {
  299. // The exponent must be > 11.
  300. //
  301. // We know that v = significand * 2^exponent.
  302. // And the exponent > 11.
  303. // We simplify the task by dividing v by 10^17.
  304. // The quotient delivers the first digits, and the remainder fits into a 64
  305. // bit number.
  306. // Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
  307. const uint64_t kFive17 = DOUBLE_CONVERSION_UINT64_2PART_C(0xB1, A2BC2EC5); // 5^17
  308. uint64_t divisor = kFive17;
  309. int divisor_power = 17;
  310. uint64_t dividend = significand;
  311. uint32_t quotient;
  312. uint64_t remainder;
  313. // Let v = f * 2^e with f == significand and e == exponent.
  314. // Then need q (quotient) and r (remainder) as follows:
  315. // v = q * 10^17 + r
  316. // f * 2^e = q * 10^17 + r
  317. // f * 2^e = q * 5^17 * 2^17 + r
  318. // If e > 17 then
  319. // f * 2^(e-17) = q * 5^17 + r/2^17
  320. // else
  321. // f = q * 5^17 * 2^(17-e) + r/2^e
  322. if (exponent > divisor_power) {
  323. // We only allow exponents of up to 20 and therefore (17 - e) <= 3
  324. dividend <<= exponent - divisor_power;
  325. quotient = static_cast<uint32_t>(dividend / divisor);
  326. remainder = (dividend % divisor) << divisor_power;
  327. } else {
  328. divisor <<= divisor_power - exponent;
  329. quotient = static_cast<uint32_t>(dividend / divisor);
  330. remainder = (dividend % divisor) << exponent;
  331. }
  332. FillDigits32(quotient, buffer, length);
  333. FillDigits64FixedLength(remainder, buffer, length);
  334. *decimal_point = *length;
  335. } else if (exponent >= 0) {
  336. // 0 <= exponent <= 11
  337. significand <<= exponent;
  338. FillDigits64(significand, buffer, length);
  339. *decimal_point = *length;
  340. } else if (exponent > -kDoubleSignificandSize) {
  341. // We have to cut the number.
  342. uint64_t integrals = significand >> -exponent;
  343. uint64_t fractionals = significand - (integrals << -exponent);
  344. if (integrals > kMaxUInt32) {
  345. FillDigits64(integrals, buffer, length);
  346. } else {
  347. FillDigits32(static_cast<uint32_t>(integrals), buffer, length);
  348. }
  349. *decimal_point = *length;
  350. FillFractionals(fractionals, exponent, fractional_count,
  351. buffer, length, decimal_point);
  352. } else if (exponent < -128) {
  353. // This configuration (with at most 20 digits) means that all digits must be
  354. // 0.
  355. DOUBLE_CONVERSION_ASSERT(fractional_count <= 20);
  356. buffer[0] = '\0';
  357. *length = 0;
  358. *decimal_point = -fractional_count;
  359. } else {
  360. *decimal_point = 0;
  361. FillFractionals(significand, exponent, fractional_count,
  362. buffer, length, decimal_point);
  363. }
  364. TrimZeros(buffer, length, decimal_point);
  365. buffer[*length] = '\0';
  366. if ((*length) == 0) {
  367. // The string is empty and the decimal_point thus has no importance. Mimic
  368. // Gay's dtoa and set it to -fractional_count.
  369. *decimal_point = -fractional_count;
  370. }
  371. return true;
  372. }
  373. } // namespace double_conversion