decimal128.ts 27 KB

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