decimal128.js 28 KB

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