decimal128.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. 'use strict';
  2. let Long = require('./long');
  3. const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  4. const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  5. const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  6. const EXPONENT_MAX = 6111;
  7. const EXPONENT_MIN = -6176;
  8. const EXPONENT_BIAS = 6176;
  9. const MAX_DIGITS = 34;
  10. // Nan value bits as 32 bit values (due to lack of longs)
  11. const NAN_BUFFER = [
  12. 0x7c,
  13. 0x00,
  14. 0x00,
  15. 0x00,
  16. 0x00,
  17. 0x00,
  18. 0x00,
  19. 0x00,
  20. 0x00,
  21. 0x00,
  22. 0x00,
  23. 0x00,
  24. 0x00,
  25. 0x00,
  26. 0x00,
  27. 0x00
  28. ].reverse();
  29. // Infinity value bits 32 bit values (due to lack of longs)
  30. const INF_NEGATIVE_BUFFER = [
  31. 0xf8,
  32. 0x00,
  33. 0x00,
  34. 0x00,
  35. 0x00,
  36. 0x00,
  37. 0x00,
  38. 0x00,
  39. 0x00,
  40. 0x00,
  41. 0x00,
  42. 0x00,
  43. 0x00,
  44. 0x00,
  45. 0x00,
  46. 0x00
  47. ].reverse();
  48. const INF_POSITIVE_BUFFER = [
  49. 0x78,
  50. 0x00,
  51. 0x00,
  52. 0x00,
  53. 0x00,
  54. 0x00,
  55. 0x00,
  56. 0x00,
  57. 0x00,
  58. 0x00,
  59. 0x00,
  60. 0x00,
  61. 0x00,
  62. 0x00,
  63. 0x00,
  64. 0x00
  65. ].reverse();
  66. const EXPONENT_REGEX = /^([-+])?(\d+)?$/;
  67. // Detect if the value is a digit
  68. function isDigit(value) {
  69. return !isNaN(parseInt(value, 10));
  70. }
  71. // Divide two uint128 values
  72. function divideu128(value) {
  73. const DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
  74. let _rem = Long.fromNumber(0);
  75. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  76. return { quotient: value, rem: _rem };
  77. }
  78. for (let i = 0; i <= 3; i++) {
  79. // Adjust remainder to match value of next dividend
  80. _rem = _rem.shiftLeft(32);
  81. // Add the divided to _rem
  82. _rem = _rem.add(new Long(value.parts[i], 0));
  83. value.parts[i] = _rem.div(DIVISOR).low;
  84. _rem = _rem.modulo(DIVISOR);
  85. }
  86. return { quotient: value, rem: _rem };
  87. }
  88. // Multiply two Long values and return the 128 bit value
  89. function multiply64x2(left, right) {
  90. if (!left && !right) {
  91. return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
  92. }
  93. const leftHigh = left.shiftRightUnsigned(32);
  94. const leftLow = new Long(left.getLowBits(), 0);
  95. const rightHigh = right.shiftRightUnsigned(32);
  96. const rightLow = new Long(right.getLowBits(), 0);
  97. let productHigh = leftHigh.multiply(rightHigh);
  98. let productMid = leftHigh.multiply(rightLow);
  99. let productMid2 = leftLow.multiply(rightHigh);
  100. let productLow = leftLow.multiply(rightLow);
  101. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  102. productMid = new Long(productMid.getLowBits(), 0)
  103. .add(productMid2)
  104. .add(productLow.shiftRightUnsigned(32));
  105. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  106. productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
  107. // Return the 128 bit result
  108. return { high: productHigh, low: productLow };
  109. }
  110. function lessThan(left, right) {
  111. // Make values unsigned
  112. const uhleft = left.high >>> 0;
  113. const uhright = right.high >>> 0;
  114. // Compare high bits first
  115. if (uhleft < uhright) {
  116. return true;
  117. } else if (uhleft === uhright) {
  118. const ulleft = left.low >>> 0;
  119. const ulright = right.low >>> 0;
  120. if (ulleft < ulright) return true;
  121. }
  122. return false;
  123. }
  124. function invalidErr(string, message) {
  125. throw new TypeError(`"${string}" is not a valid Decimal128 string - ${message}`);
  126. }
  127. /**
  128. * A class representation of the BSON Decimal128 type.
  129. *
  130. * @class
  131. * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes.
  132. * @return {Double}
  133. */
  134. function Decimal128(bytes) {
  135. this.bytes = bytes;
  136. }
  137. /**
  138. * Create a Decimal128 instance from a string representation
  139. *
  140. * @method
  141. * @param {string} string a numeric string representation.
  142. * @return {Decimal128} returns a Decimal128 instance.
  143. */
  144. Decimal128.fromString = function(string) {
  145. // Parse state tracking
  146. let isNegative = false;
  147. let sawRadix = false;
  148. let foundNonZero = false;
  149. // Total number of significant digits (no leading or trailing zero)
  150. let significantDigits = 0;
  151. // Total number of significand digits read
  152. let nDigitsRead = 0;
  153. // Total number of digits (no leading zeros)
  154. let nDigits = 0;
  155. // The number of the digits after radix
  156. let radixPosition = 0;
  157. // The index of the first non-zero in *str*
  158. let firstNonZero = 0;
  159. // Digits Array
  160. const digits = [0];
  161. // The number of digits in digits
  162. let nDigitsStored = 0;
  163. // Insertion pointer for digits
  164. let digitsInsert = 0;
  165. // The index of the first non-zero digit
  166. let firstDigit = 0;
  167. // The index of the last digit
  168. let lastDigit = 0;
  169. // Exponent
  170. let exponent = 0;
  171. // loop index over array
  172. let i = 0;
  173. // The high 17 digits of the significand
  174. let significandHigh = [0, 0];
  175. // The low 17 digits of the significand
  176. let significandLow = [0, 0];
  177. // The biased exponent
  178. let biasedExponent = 0;
  179. // Read index
  180. let index = 0;
  181. // Naively prevent against REDOS attacks.
  182. // TODO: implementing a custom parsing for this, or refactoring the regex would yield
  183. // further gains.
  184. if (string.length >= 7000) {
  185. throw new TypeError('' + string + ' not a valid Decimal128 string');
  186. }
  187. // Results
  188. const stringMatch = string.match(PARSE_STRING_REGEXP);
  189. const infMatch = string.match(PARSE_INF_REGEXP);
  190. const nanMatch = string.match(PARSE_NAN_REGEXP);
  191. // Validate the string
  192. if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) {
  193. throw new TypeError('' + string + ' not a valid Decimal128 string');
  194. }
  195. if (stringMatch) {
  196. // full_match = stringMatch[0]
  197. // sign = stringMatch[1]
  198. let unsignedNumber = stringMatch[2];
  199. // stringMatch[3] is undefined if a whole number (ex "1", 12")
  200. // but defined if a number w/ decimal in it (ex "1.0, 12.2")
  201. let e = stringMatch[4];
  202. let expSign = stringMatch[5];
  203. let expNumber = stringMatch[6];
  204. // they provided e, but didn't give an exponent number. for ex "1e"
  205. if (e && expNumber === undefined) invalidErr(string, 'missing exponent power');
  206. // they provided e, but didn't give a number before it. for ex "e1"
  207. if (e && unsignedNumber === undefined) invalidErr(string, 'missing exponent base');
  208. if (e === undefined && (expSign || expNumber)) {
  209. invalidErr(string, 'missing e before exponent');
  210. }
  211. }
  212. // Get the negative or positive sign
  213. if (string[index] === '+' || string[index] === '-') {
  214. isNegative = string[index++] === '-';
  215. }
  216. // Check if user passed Infinity or NaN
  217. if (!isDigit(string[index]) && string[index] !== '.') {
  218. if (string[index] === 'i' || string[index] === 'I') {
  219. return new Decimal128(Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  220. } else if (string[index] === 'N') {
  221. return new Decimal128(Buffer.from(NAN_BUFFER));
  222. }
  223. }
  224. // Read all the digits
  225. while (isDigit(string[index]) || string[index] === '.') {
  226. if (string[index] === '.') {
  227. if (sawRadix) invalidErr(string, 'contains multiple periods');
  228. sawRadix = true;
  229. index = index + 1;
  230. continue;
  231. }
  232. if (nDigitsStored < 34) {
  233. if (string[index] !== '0' || foundNonZero) {
  234. if (!foundNonZero) {
  235. firstNonZero = nDigitsRead;
  236. }
  237. foundNonZero = true;
  238. // Only store 34 digits
  239. digits[digitsInsert++] = parseInt(string[index], 10);
  240. nDigitsStored = nDigitsStored + 1;
  241. }
  242. }
  243. if (foundNonZero) nDigits = nDigits + 1;
  244. if (sawRadix) radixPosition = radixPosition + 1;
  245. nDigitsRead = nDigitsRead + 1;
  246. index = index + 1;
  247. }
  248. if (sawRadix && !nDigitsRead) throw new TypeError('' + string + ' not a valid Decimal128 string');
  249. // Read exponent if exists
  250. if (string[index] === 'e' || string[index] === 'E') {
  251. // Read exponent digits
  252. const match = string.substr(++index).match(EXPONENT_REGEX);
  253. // No digits read
  254. if (!match || !match[2]) return new Decimal128(Buffer.from(NAN_BUFFER));
  255. // Get exponent
  256. exponent = parseInt(match[0], 10);
  257. // Adjust the index
  258. index = index + match[0].length;
  259. }
  260. // Return not a number
  261. if (string[index]) return new Decimal128(Buffer.from(NAN_BUFFER));
  262. // Done reading input
  263. // Find first non-zero digit in digits
  264. firstDigit = 0;
  265. if (!nDigitsStored) {
  266. firstDigit = 0;
  267. lastDigit = 0;
  268. digits[0] = 0;
  269. nDigits = 1;
  270. nDigitsStored = 1;
  271. significantDigits = 0;
  272. } else {
  273. lastDigit = nDigitsStored - 1;
  274. significantDigits = nDigits;
  275. if (significantDigits !== 1) {
  276. while (string[firstNonZero + significantDigits - 1] === '0') {
  277. significantDigits = significantDigits - 1;
  278. }
  279. }
  280. }
  281. // Normalization of exponent
  282. // Correct exponent based on radix position, and shift significand as needed
  283. // to represent user input
  284. // Overflow prevention
  285. if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) {
  286. exponent = EXPONENT_MIN;
  287. } else {
  288. exponent = exponent - radixPosition;
  289. }
  290. // Attempt to normalize the exponent
  291. while (exponent > EXPONENT_MAX) {
  292. // Shift exponent to significand and decrease
  293. lastDigit = lastDigit + 1;
  294. if (lastDigit - firstDigit > MAX_DIGITS) {
  295. // Check if we have a zero then just hard clamp, otherwise fail
  296. const digitsString = digits.join('');
  297. if (digitsString.match(/^0+$/)) {
  298. exponent = EXPONENT_MAX;
  299. break;
  300. }
  301. invalidErr(string, 'overflow');
  302. }
  303. exponent = exponent - 1;
  304. }
  305. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  306. // Shift last digit. can only do this if < significant digits than # stored.
  307. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  308. exponent = EXPONENT_MIN;
  309. significantDigits = 0;
  310. break;
  311. }
  312. if (nDigitsStored < nDigits) {
  313. // adjust to match digits not stored
  314. nDigits = nDigits - 1;
  315. } else {
  316. // adjust to round
  317. lastDigit = lastDigit - 1;
  318. }
  319. if (exponent < EXPONENT_MAX) {
  320. exponent = exponent + 1;
  321. } else {
  322. // Check if we have a zero then just hard clamp, otherwise fail
  323. const digitsString = digits.join('');
  324. if (digitsString.match(/^0+$/)) {
  325. exponent = EXPONENT_MAX;
  326. break;
  327. }
  328. invalidErr(string, 'overflow');
  329. }
  330. }
  331. // Round
  332. // We've normalized the exponent, but might still need to round.
  333. if (lastDigit - firstDigit + 1 < significantDigits) {
  334. let endOfString = nDigitsRead;
  335. // If we have seen a radix point, 'string' is 1 longer than we have
  336. // documented with ndigits_read, so inc the position of the first nonzero
  337. // digit and the position that digits are read to.
  338. if (sawRadix) {
  339. firstNonZero = firstNonZero + 1;
  340. endOfString = endOfString + 1;
  341. }
  342. // if negative, we need to increment again to account for - sign at start.
  343. if (isNegative) {
  344. firstNonZero = firstNonZero + 1;
  345. endOfString = endOfString + 1;
  346. }
  347. const roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10);
  348. let roundBit = 0;
  349. if (roundDigit >= 5) {
  350. roundBit = 1;
  351. if (roundDigit === 5) {
  352. roundBit = digits[lastDigit] % 2 === 1;
  353. for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  354. if (parseInt(string[i], 10)) {
  355. roundBit = 1;
  356. break;
  357. }
  358. }
  359. }
  360. }
  361. if (roundBit) {
  362. let dIdx = lastDigit;
  363. for (; dIdx >= 0; dIdx--) {
  364. if (++digits[dIdx] > 9) {
  365. digits[dIdx] = 0;
  366. // overflowed most significant digit
  367. if (dIdx === 0) {
  368. if (exponent < EXPONENT_MAX) {
  369. exponent = exponent + 1;
  370. digits[dIdx] = 1;
  371. } else {
  372. return new Decimal128(
  373. Buffer.from(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)
  374. );
  375. }
  376. }
  377. }
  378. }
  379. }
  380. }
  381. // Encode significand
  382. // The high 17 digits of the significand
  383. significandHigh = Long.fromNumber(0);
  384. // The low 17 digits of the significand
  385. significandLow = Long.fromNumber(0);
  386. // read a zero
  387. if (significantDigits === 0) {
  388. significandHigh = Long.fromNumber(0);
  389. significandLow = Long.fromNumber(0);
  390. } else if (lastDigit - firstDigit < 17) {
  391. let dIdx = firstDigit;
  392. significandLow = Long.fromNumber(digits[dIdx++]);
  393. significandHigh = new Long(0, 0);
  394. for (; dIdx <= lastDigit; dIdx++) {
  395. significandLow = significandLow.multiply(Long.fromNumber(10));
  396. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  397. }
  398. } else {
  399. let dIdx = firstDigit;
  400. significandHigh = Long.fromNumber(digits[dIdx++]);
  401. for (; dIdx <= lastDigit - 17; dIdx++) {
  402. significandHigh = significandHigh.multiply(Long.fromNumber(10));
  403. significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
  404. }
  405. significandLow = Long.fromNumber(digits[dIdx++]);
  406. for (; dIdx <= lastDigit; dIdx++) {
  407. significandLow = significandLow.multiply(Long.fromNumber(10));
  408. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  409. }
  410. }
  411. const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
  412. significand.low = significand.low.add(significandLow);
  413. if (lessThan(significand.low, significandLow)) {
  414. significand.high = significand.high.add(Long.fromNumber(1));
  415. }
  416. // Biased exponent
  417. biasedExponent = exponent + EXPONENT_BIAS;
  418. const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
  419. // Encode combination, exponent, and significand.
  420. if (
  421. significand.high
  422. .shiftRightUnsigned(49)
  423. .and(Long.fromNumber(1))
  424. .equals(Long.fromNumber(1))
  425. ) {
  426. // Encode '11' into bits 1 to 3
  427. dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
  428. dec.high = dec.high.or(
  429. Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))
  430. );
  431. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
  432. } else {
  433. dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
  434. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
  435. }
  436. dec.low = significand.low;
  437. // Encode sign
  438. if (isNegative) {
  439. dec.high = dec.high.or(Long.fromString('9223372036854775808'));
  440. }
  441. // Encode into a buffer
  442. const buffer = Buffer.alloc(16);
  443. index = 0;
  444. // Encode the low 64 bits of the decimal
  445. // Encode low bits
  446. buffer[index++] = dec.low.low & 0xff;
  447. buffer[index++] = (dec.low.low >> 8) & 0xff;
  448. buffer[index++] = (dec.low.low >> 16) & 0xff;
  449. buffer[index++] = (dec.low.low >> 24) & 0xff;
  450. // Encode high bits
  451. buffer[index++] = dec.low.high & 0xff;
  452. buffer[index++] = (dec.low.high >> 8) & 0xff;
  453. buffer[index++] = (dec.low.high >> 16) & 0xff;
  454. buffer[index++] = (dec.low.high >> 24) & 0xff;
  455. // Encode the high 64 bits of the decimal
  456. // Encode low bits
  457. buffer[index++] = dec.high.low & 0xff;
  458. buffer[index++] = (dec.high.low >> 8) & 0xff;
  459. buffer[index++] = (dec.high.low >> 16) & 0xff;
  460. buffer[index++] = (dec.high.low >> 24) & 0xff;
  461. // Encode high bits
  462. buffer[index++] = dec.high.high & 0xff;
  463. buffer[index++] = (dec.high.high >> 8) & 0xff;
  464. buffer[index++] = (dec.high.high >> 16) & 0xff;
  465. buffer[index++] = (dec.high.high >> 24) & 0xff;
  466. // Return the new Decimal128
  467. return new Decimal128(buffer);
  468. };
  469. // Extract least significant 5 bits
  470. const COMBINATION_MASK = 0x1f;
  471. // Extract least significant 14 bits
  472. const EXPONENT_MASK = 0x3fff;
  473. // Value of combination field for Inf
  474. const COMBINATION_INFINITY = 30;
  475. // Value of combination field for NaN
  476. const COMBINATION_NAN = 31;
  477. /**
  478. * Create a string representation of the raw Decimal128 value
  479. *
  480. * @method
  481. * @return {string} returns a Decimal128 string representation.
  482. */
  483. Decimal128.prototype.toString = function() {
  484. // Note: bits in this routine are referred to starting at 0,
  485. // from the sign bit, towards the coefficient.
  486. // bits 0 - 31
  487. let high;
  488. // bits 32 - 63
  489. let midh;
  490. // bits 64 - 95
  491. let midl;
  492. // bits 96 - 127
  493. let low;
  494. // bits 1 - 5
  495. let combination;
  496. // decoded biased exponent (14 bits)
  497. let biased_exponent;
  498. // the number of significand digits
  499. let significand_digits = 0;
  500. // the base-10 digits in the significand
  501. const significand = new Array(36);
  502. for (let i = 0; i < significand.length; i++) significand[i] = 0;
  503. // read pointer into significand
  504. let index = 0;
  505. // unbiased exponent
  506. let exponent;
  507. // the exponent if scientific notation is used
  508. let scientific_exponent;
  509. // true if the number is zero
  510. let is_zero = false;
  511. // the most signifcant significand bits (50-46)
  512. let significand_msb;
  513. // temporary storage for significand decoding
  514. let significand128 = { parts: new Array(4) };
  515. // indexing variables
  516. let j, k;
  517. // Output string
  518. const string = [];
  519. // Unpack index
  520. index = 0;
  521. // Buffer reference
  522. const buffer = this.bytes;
  523. // Unpack the low 64bits into a long
  524. low =
  525. buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  526. midl =
  527. buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  528. // Unpack the high 64bits into a long
  529. midh =
  530. buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  531. high =
  532. buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  533. // Unpack index
  534. index = 0;
  535. // Create the state of the decimal
  536. const dec = {
  537. low: new Long(low, midl),
  538. high: new Long(midh, high)
  539. };
  540. if (dec.high.lessThan(Long.ZERO)) {
  541. string.push('-');
  542. }
  543. // Decode combination field and exponent
  544. combination = (high >> 26) & COMBINATION_MASK;
  545. if (combination >> 3 === 3) {
  546. // Check for 'special' values
  547. if (combination === COMBINATION_INFINITY) {
  548. return string.join('') + 'Infinity';
  549. } else if (combination === COMBINATION_NAN) {
  550. return 'NaN';
  551. } else {
  552. biased_exponent = (high >> 15) & EXPONENT_MASK;
  553. significand_msb = 0x08 + ((high >> 14) & 0x01);
  554. }
  555. } else {
  556. significand_msb = (high >> 14) & 0x07;
  557. biased_exponent = (high >> 17) & EXPONENT_MASK;
  558. }
  559. exponent = biased_exponent - EXPONENT_BIAS;
  560. // Create string of significand digits
  561. // Convert the 114-bit binary number represented by
  562. // (significand_high, significand_low) to at most 34 decimal
  563. // digits through modulo and division.
  564. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
  565. significand128.parts[1] = midh;
  566. significand128.parts[2] = midl;
  567. significand128.parts[3] = low;
  568. if (
  569. significand128.parts[0] === 0 &&
  570. significand128.parts[1] === 0 &&
  571. significand128.parts[2] === 0 &&
  572. significand128.parts[3] === 0
  573. ) {
  574. is_zero = true;
  575. } else {
  576. for (k = 3; k >= 0; k--) {
  577. let least_digits = 0;
  578. // Peform the divide
  579. let result = divideu128(significand128);
  580. significand128 = result.quotient;
  581. least_digits = result.rem.low;
  582. // We now have the 9 least significant digits (in base 2).
  583. // Convert and output to string.
  584. if (!least_digits) continue;
  585. for (j = 8; j >= 0; j--) {
  586. // significand[k * 9 + j] = Math.round(least_digits % 10);
  587. significand[k * 9 + j] = least_digits % 10;
  588. // least_digits = Math.round(least_digits / 10);
  589. least_digits = Math.floor(least_digits / 10);
  590. }
  591. }
  592. }
  593. // Output format options:
  594. // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
  595. // Regular - ddd.ddd
  596. if (is_zero) {
  597. significand_digits = 1;
  598. significand[index] = 0;
  599. } else {
  600. significand_digits = 36;
  601. while (!significand[index]) {
  602. significand_digits = significand_digits - 1;
  603. index = index + 1;
  604. }
  605. }
  606. scientific_exponent = significand_digits - 1 + exponent;
  607. // The scientific exponent checks are dictated by the string conversion
  608. // specification and are somewhat arbitrary cutoffs.
  609. //
  610. // We must check exponent > 0, because if this is the case, the number
  611. // has trailing zeros. However, we *cannot* output these trailing zeros,
  612. // because doing so would change the precision of the value, and would
  613. // change stored data if the string converted number is round tripped.
  614. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  615. // Scientific format
  616. // if there are too many significant digits, we should just be treating numbers
  617. // as + or - 0 and using the non-scientific exponent (this is for the "invalid
  618. // representation should be treated as 0/-0" spec cases in decimal128-1.json)
  619. if (significand_digits > 34) {
  620. string.push(0);
  621. if (exponent > 0) string.push('E+' + exponent);
  622. else if (exponent < 0) string.push('E' + exponent);
  623. return string.join('');
  624. }
  625. string.push(significand[index++]);
  626. significand_digits = significand_digits - 1;
  627. if (significand_digits) {
  628. string.push('.');
  629. }
  630. for (let i = 0; i < significand_digits; i++) {
  631. string.push(significand[index++]);
  632. }
  633. // Exponent
  634. string.push('E');
  635. if (scientific_exponent > 0) {
  636. string.push('+' + scientific_exponent);
  637. } else {
  638. string.push(scientific_exponent);
  639. }
  640. } else {
  641. // Regular format with no decimal place
  642. if (exponent >= 0) {
  643. for (let i = 0; i < significand_digits; i++) {
  644. string.push(significand[index++]);
  645. }
  646. } else {
  647. let radix_position = significand_digits + exponent;
  648. // non-zero digits before radix
  649. if (radix_position > 0) {
  650. for (let i = 0; i < radix_position; i++) {
  651. string.push(significand[index++]);
  652. }
  653. } else {
  654. string.push('0');
  655. }
  656. string.push('.');
  657. // add leading zeros after radix
  658. while (radix_position++ < 0) {
  659. string.push('0');
  660. }
  661. for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
  662. string.push(significand[index++]);
  663. }
  664. }
  665. }
  666. return string.join('');
  667. };
  668. Decimal128.prototype.toJSON = function() {
  669. return { $numberDecimal: this.toString() };
  670. };
  671. /**
  672. * @ignore
  673. */
  674. Decimal128.prototype.toExtendedJSON = function() {
  675. return { $numberDecimal: this.toString() };
  676. };
  677. /**
  678. * @ignore
  679. */
  680. Decimal128.fromExtendedJSON = function(doc) {
  681. return Decimal128.fromString(doc.$numberDecimal);
  682. };
  683. Object.defineProperty(Decimal128.prototype, '_bsontype', { value: 'Decimal128' });
  684. module.exports = Decimal128;