decimal128.js 28 KB

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