decimal128.ts 24 KB

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