fixednumber.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.FixedNumber = void 0;
  4. /**
  5. * The **FixedNumber** class permits using values with decimal places,
  6. * using fixed-pont math.
  7. *
  8. * Fixed-point math is still based on integers under-the-hood, but uses an
  9. * internal offset to store fractional components below, and each operation
  10. * corrects for this after each operation.
  11. *
  12. * @_section: api/utils/fixed-point-math:Fixed-Point Maths [about-fixed-point-math]
  13. */
  14. const data_js_1 = require("./data.js");
  15. const errors_js_1 = require("./errors.js");
  16. const maths_js_1 = require("./maths.js");
  17. const properties_js_1 = require("./properties.js");
  18. const BN_N1 = BigInt(-1);
  19. const BN_0 = BigInt(0);
  20. const BN_1 = BigInt(1);
  21. const BN_5 = BigInt(5);
  22. const _guard = {};
  23. // Constant to pull zeros from for multipliers
  24. let Zeros = "0000";
  25. while (Zeros.length < 80) {
  26. Zeros += Zeros;
  27. }
  28. // Returns a string "1" followed by decimal "0"s
  29. function getTens(decimals) {
  30. let result = Zeros;
  31. while (result.length < decimals) {
  32. result += result;
  33. }
  34. return BigInt("1" + result.substring(0, decimals));
  35. }
  36. function checkValue(val, format, safeOp) {
  37. const width = BigInt(format.width);
  38. if (format.signed) {
  39. const limit = (BN_1 << (width - BN_1));
  40. (0, errors_js_1.assert)(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
  41. operation: safeOp, fault: "overflow", value: val
  42. });
  43. if (val > BN_0) {
  44. val = (0, maths_js_1.fromTwos)((0, maths_js_1.mask)(val, width), width);
  45. }
  46. else {
  47. val = -(0, maths_js_1.fromTwos)((0, maths_js_1.mask)(-val, width), width);
  48. }
  49. }
  50. else {
  51. const limit = (BN_1 << width);
  52. (0, errors_js_1.assert)(safeOp == null || (val >= 0 && val < limit), "overflow", "NUMERIC_FAULT", {
  53. operation: safeOp, fault: "overflow", value: val
  54. });
  55. val = (((val % limit) + limit) % limit) & (limit - BN_1);
  56. }
  57. return val;
  58. }
  59. function getFormat(value) {
  60. if (typeof (value) === "number") {
  61. value = `fixed128x${value}`;
  62. }
  63. let signed = true;
  64. let width = 128;
  65. let decimals = 18;
  66. if (typeof (value) === "string") {
  67. // Parse the format string
  68. if (value === "fixed") {
  69. // defaults...
  70. }
  71. else if (value === "ufixed") {
  72. signed = false;
  73. }
  74. else {
  75. const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
  76. (0, errors_js_1.assertArgument)(match, "invalid fixed format", "format", value);
  77. signed = (match[1] !== "u");
  78. width = parseInt(match[2]);
  79. decimals = parseInt(match[3]);
  80. }
  81. }
  82. else if (value) {
  83. // Extract the values from the object
  84. const v = value;
  85. const check = (key, type, defaultValue) => {
  86. if (v[key] == null) {
  87. return defaultValue;
  88. }
  89. (0, errors_js_1.assertArgument)(typeof (v[key]) === type, "invalid fixed format (" + key + " not " + type + ")", "format." + key, v[key]);
  90. return v[key];
  91. };
  92. signed = check("signed", "boolean", signed);
  93. width = check("width", "number", width);
  94. decimals = check("decimals", "number", decimals);
  95. }
  96. (0, errors_js_1.assertArgument)((width % 8) === 0, "invalid FixedNumber width (not byte aligned)", "format.width", width);
  97. (0, errors_js_1.assertArgument)(decimals <= 80, "invalid FixedNumber decimals (too large)", "format.decimals", decimals);
  98. const name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals);
  99. return { signed, width, decimals, name };
  100. }
  101. function toString(val, decimals) {
  102. let negative = "";
  103. if (val < BN_0) {
  104. negative = "-";
  105. val *= BN_N1;
  106. }
  107. let str = val.toString();
  108. // No decimal point for whole values
  109. if (decimals === 0) {
  110. return (negative + str);
  111. }
  112. // Pad out to the whole component (including a whole digit)
  113. while (str.length <= decimals) {
  114. str = Zeros + str;
  115. }
  116. // Insert the decimal point
  117. const index = str.length - decimals;
  118. str = str.substring(0, index) + "." + str.substring(index);
  119. // Trim the whole component (leaving at least one 0)
  120. while (str[0] === "0" && str[1] !== ".") {
  121. str = str.substring(1);
  122. }
  123. // Trim the decimal component (leaving at least one 0)
  124. while (str[str.length - 1] === "0" && str[str.length - 2] !== ".") {
  125. str = str.substring(0, str.length - 1);
  126. }
  127. return (negative + str);
  128. }
  129. /**
  130. * A FixedNumber represents a value over its [[FixedFormat]]
  131. * arithmetic field.
  132. *
  133. * A FixedNumber can be used to perform math, losslessly, on
  134. * values which have decmial places.
  135. *
  136. * A FixedNumber has a fixed bit-width to store values in, and stores all
  137. * values internally by multiplying the value by 10 raised to the power of
  138. * %%decimals%%.
  139. *
  140. * If operations are performed that cause a value to grow too high (close to
  141. * positive infinity) or too low (close to negative infinity), the value
  142. * is said to //overflow//.
  143. *
  144. * For example, an 8-bit signed value, with 0 decimals may only be within
  145. * the range ``-128`` to ``127``; so ``-128 - 1`` will overflow and become
  146. * ``127``. Likewise, ``127 + 1`` will overflow and become ``-127``.
  147. *
  148. * Many operation have a normal and //unsafe// variant. The normal variant
  149. * will throw a [[NumericFaultError]] on any overflow, while the //unsafe//
  150. * variant will silently allow overflow, corrupting its value value.
  151. *
  152. * If operations are performed that cause a value to become too small
  153. * (close to zero), the value loses precison and is said to //underflow//.
  154. *
  155. * For example, an value with 1 decimal place may store a number as small
  156. * as ``0.1``, but the value of ``0.1 / 2`` is ``0.05``, which cannot fit
  157. * into 1 decimal place, so underflow occurs which means precision is lost
  158. * and the value becomes ``0``.
  159. *
  160. * Some operations have a normal and //signalling// variant. The normal
  161. * variant will silently ignore underflow, while the //signalling// variant
  162. * will thow a [[NumericFaultError]] on underflow.
  163. */
  164. class FixedNumber {
  165. /**
  166. * The specific fixed-point arithmetic field for this value.
  167. */
  168. format;
  169. #format;
  170. // The actual value (accounting for decimals)
  171. #val;
  172. // A base-10 value to multiple values by to maintain the magnitude
  173. #tens;
  174. /**
  175. * This is a property so console.log shows a human-meaningful value.
  176. *
  177. * @private
  178. */
  179. _value;
  180. // Use this when changing this file to get some typing info,
  181. // but then switch to any to mask the internal type
  182. //constructor(guard: any, value: bigint, format: _FixedFormat) {
  183. /**
  184. * @private
  185. */
  186. constructor(guard, value, format) {
  187. (0, errors_js_1.assertPrivate)(guard, _guard, "FixedNumber");
  188. this.#val = value;
  189. this.#format = format;
  190. const _value = toString(value, format.decimals);
  191. (0, properties_js_1.defineProperties)(this, { format: format.name, _value });
  192. this.#tens = getTens(format.decimals);
  193. }
  194. /**
  195. * If true, negative values are permitted, otherwise only
  196. * positive values and zero are allowed.
  197. */
  198. get signed() { return this.#format.signed; }
  199. /**
  200. * The number of bits available to store the value.
  201. */
  202. get width() { return this.#format.width; }
  203. /**
  204. * The number of decimal places in the fixed-point arithment field.
  205. */
  206. get decimals() { return this.#format.decimals; }
  207. /**
  208. * The value as an integer, based on the smallest unit the
  209. * [[decimals]] allow.
  210. */
  211. get value() { return this.#val; }
  212. #checkFormat(other) {
  213. (0, errors_js_1.assertArgument)(this.format === other.format, "incompatible format; use fixedNumber.toFormat", "other", other);
  214. }
  215. #checkValue(val, safeOp) {
  216. /*
  217. const width = BigInt(this.width);
  218. if (this.signed) {
  219. const limit = (BN_1 << (width - BN_1));
  220. assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
  221. operation: <string>safeOp, fault: "overflow", value: val
  222. });
  223. if (val > BN_0) {
  224. val = fromTwos(mask(val, width), width);
  225. } else {
  226. val = -fromTwos(mask(-val, width), width);
  227. }
  228. } else {
  229. const masked = mask(val, width);
  230. assert(safeOp == null || (val >= 0 && val === masked), "overflow", "NUMERIC_FAULT", {
  231. operation: <string>safeOp, fault: "overflow", value: val
  232. });
  233. val = masked;
  234. }
  235. */
  236. val = checkValue(val, this.#format, safeOp);
  237. return new FixedNumber(_guard, val, this.#format);
  238. }
  239. #add(o, safeOp) {
  240. this.#checkFormat(o);
  241. return this.#checkValue(this.#val + o.#val, safeOp);
  242. }
  243. /**
  244. * Returns a new [[FixedNumber]] with the result of %%this%% added
  245. * to %%other%%, ignoring overflow.
  246. */
  247. addUnsafe(other) { return this.#add(other); }
  248. /**
  249. * Returns a new [[FixedNumber]] with the result of %%this%% added
  250. * to %%other%%. A [[NumericFaultError]] is thrown if overflow
  251. * occurs.
  252. */
  253. add(other) { return this.#add(other, "add"); }
  254. #sub(o, safeOp) {
  255. this.#checkFormat(o);
  256. return this.#checkValue(this.#val - o.#val, safeOp);
  257. }
  258. /**
  259. * Returns a new [[FixedNumber]] with the result of %%other%% subtracted
  260. * from %%this%%, ignoring overflow.
  261. */
  262. subUnsafe(other) { return this.#sub(other); }
  263. /**
  264. * Returns a new [[FixedNumber]] with the result of %%other%% subtracted
  265. * from %%this%%. A [[NumericFaultError]] is thrown if overflow
  266. * occurs.
  267. */
  268. sub(other) { return this.#sub(other, "sub"); }
  269. #mul(o, safeOp) {
  270. this.#checkFormat(o);
  271. return this.#checkValue((this.#val * o.#val) / this.#tens, safeOp);
  272. }
  273. /**
  274. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  275. * by %%other%%, ignoring overflow and underflow (precision loss).
  276. */
  277. mulUnsafe(other) { return this.#mul(other); }
  278. /**
  279. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  280. * by %%other%%. A [[NumericFaultError]] is thrown if overflow
  281. * occurs.
  282. */
  283. mul(other) { return this.#mul(other, "mul"); }
  284. /**
  285. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  286. * by %%other%%. A [[NumericFaultError]] is thrown if overflow
  287. * occurs or if underflow (precision loss) occurs.
  288. */
  289. mulSignal(other) {
  290. this.#checkFormat(other);
  291. const value = this.#val * other.#val;
  292. (0, errors_js_1.assert)((value % this.#tens) === BN_0, "precision lost during signalling mul", "NUMERIC_FAULT", {
  293. operation: "mulSignal", fault: "underflow", value: this
  294. });
  295. return this.#checkValue(value / this.#tens, "mulSignal");
  296. }
  297. #div(o, safeOp) {
  298. (0, errors_js_1.assert)(o.#val !== BN_0, "division by zero", "NUMERIC_FAULT", {
  299. operation: "div", fault: "divide-by-zero", value: this
  300. });
  301. this.#checkFormat(o);
  302. return this.#checkValue((this.#val * this.#tens) / o.#val, safeOp);
  303. }
  304. /**
  305. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  306. * by %%other%%, ignoring underflow (precision loss). A
  307. * [[NumericFaultError]] is thrown if overflow occurs.
  308. */
  309. divUnsafe(other) { return this.#div(other); }
  310. /**
  311. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  312. * by %%other%%, ignoring underflow (precision loss). A
  313. * [[NumericFaultError]] is thrown if overflow occurs.
  314. */
  315. div(other) { return this.#div(other, "div"); }
  316. /**
  317. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  318. * by %%other%%. A [[NumericFaultError]] is thrown if underflow
  319. * (precision loss) occurs.
  320. */
  321. divSignal(other) {
  322. (0, errors_js_1.assert)(other.#val !== BN_0, "division by zero", "NUMERIC_FAULT", {
  323. operation: "div", fault: "divide-by-zero", value: this
  324. });
  325. this.#checkFormat(other);
  326. const value = (this.#val * this.#tens);
  327. (0, errors_js_1.assert)((value % other.#val) === BN_0, "precision lost during signalling div", "NUMERIC_FAULT", {
  328. operation: "divSignal", fault: "underflow", value: this
  329. });
  330. return this.#checkValue(value / other.#val, "divSignal");
  331. }
  332. /**
  333. * Returns a comparison result between %%this%% and %%other%%.
  334. *
  335. * This is suitable for use in sorting, where ``-1`` implies %%this%%
  336. * is smaller, ``1`` implies %%this%% is larger and ``0`` implies
  337. * both are equal.
  338. */
  339. cmp(other) {
  340. let a = this.value, b = other.value;
  341. // Coerce a and b to the same magnitude
  342. const delta = this.decimals - other.decimals;
  343. if (delta > 0) {
  344. b *= getTens(delta);
  345. }
  346. else if (delta < 0) {
  347. a *= getTens(-delta);
  348. }
  349. // Comnpare
  350. if (a < b) {
  351. return -1;
  352. }
  353. if (a > b) {
  354. return 1;
  355. }
  356. return 0;
  357. }
  358. /**
  359. * Returns true if %%other%% is equal to %%this%%.
  360. */
  361. eq(other) { return this.cmp(other) === 0; }
  362. /**
  363. * Returns true if %%other%% is less than to %%this%%.
  364. */
  365. lt(other) { return this.cmp(other) < 0; }
  366. /**
  367. * Returns true if %%other%% is less than or equal to %%this%%.
  368. */
  369. lte(other) { return this.cmp(other) <= 0; }
  370. /**
  371. * Returns true if %%other%% is greater than to %%this%%.
  372. */
  373. gt(other) { return this.cmp(other) > 0; }
  374. /**
  375. * Returns true if %%other%% is greater than or equal to %%this%%.
  376. */
  377. gte(other) { return this.cmp(other) >= 0; }
  378. /**
  379. * Returns a new [[FixedNumber]] which is the largest **integer**
  380. * that is less than or equal to %%this%%.
  381. *
  382. * The decimal component of the result will always be ``0``.
  383. */
  384. floor() {
  385. let val = this.#val;
  386. if (this.#val < BN_0) {
  387. val -= this.#tens - BN_1;
  388. }
  389. val = (this.#val / this.#tens) * this.#tens;
  390. return this.#checkValue(val, "floor");
  391. }
  392. /**
  393. * Returns a new [[FixedNumber]] which is the smallest **integer**
  394. * that is greater than or equal to %%this%%.
  395. *
  396. * The decimal component of the result will always be ``0``.
  397. */
  398. ceiling() {
  399. let val = this.#val;
  400. if (this.#val > BN_0) {
  401. val += this.#tens - BN_1;
  402. }
  403. val = (this.#val / this.#tens) * this.#tens;
  404. return this.#checkValue(val, "ceiling");
  405. }
  406. /**
  407. * Returns a new [[FixedNumber]] with the decimal component
  408. * rounded up on ties at %%decimals%% places.
  409. */
  410. round(decimals) {
  411. if (decimals == null) {
  412. decimals = 0;
  413. }
  414. // Not enough precision to not already be rounded
  415. if (decimals >= this.decimals) {
  416. return this;
  417. }
  418. const delta = this.decimals - decimals;
  419. const bump = BN_5 * getTens(delta - 1);
  420. let value = this.value + bump;
  421. const tens = getTens(delta);
  422. value = (value / tens) * tens;
  423. checkValue(value, this.#format, "round");
  424. return new FixedNumber(_guard, value, this.#format);
  425. }
  426. /**
  427. * Returns true if %%this%% is equal to ``0``.
  428. */
  429. isZero() { return (this.#val === BN_0); }
  430. /**
  431. * Returns true if %%this%% is less than ``0``.
  432. */
  433. isNegative() { return (this.#val < BN_0); }
  434. /**
  435. * Returns the string representation of %%this%%.
  436. */
  437. toString() { return this._value; }
  438. /**
  439. * Returns a float approximation.
  440. *
  441. * Due to IEEE 754 precission (or lack thereof), this function
  442. * can only return an approximation and most values will contain
  443. * rounding errors.
  444. */
  445. toUnsafeFloat() { return parseFloat(this.toString()); }
  446. /**
  447. * Return a new [[FixedNumber]] with the same value but has had
  448. * its field set to %%format%%.
  449. *
  450. * This will throw if the value cannot fit into %%format%%.
  451. */
  452. toFormat(format) {
  453. return FixedNumber.fromString(this.toString(), format);
  454. }
  455. /**
  456. * Creates a new [[FixedNumber]] for %%value%% divided by
  457. * %%decimal%% places with %%format%%.
  458. *
  459. * This will throw a [[NumericFaultError]] if %%value%% (once adjusted
  460. * for %%decimals%%) cannot fit in %%format%%, either due to overflow
  461. * or underflow (precision loss).
  462. */
  463. static fromValue(_value, _decimals, _format) {
  464. const decimals = (_decimals == null) ? 0 : (0, maths_js_1.getNumber)(_decimals);
  465. const format = getFormat(_format);
  466. let value = (0, maths_js_1.getBigInt)(_value, "value");
  467. const delta = decimals - format.decimals;
  468. if (delta > 0) {
  469. const tens = getTens(delta);
  470. (0, errors_js_1.assert)((value % tens) === BN_0, "value loses precision for format", "NUMERIC_FAULT", {
  471. operation: "fromValue", fault: "underflow", value: _value
  472. });
  473. value /= tens;
  474. }
  475. else if (delta < 0) {
  476. value *= getTens(-delta);
  477. }
  478. checkValue(value, format, "fromValue");
  479. return new FixedNumber(_guard, value, format);
  480. }
  481. /**
  482. * Creates a new [[FixedNumber]] for %%value%% with %%format%%.
  483. *
  484. * This will throw a [[NumericFaultError]] if %%value%% cannot fit
  485. * in %%format%%, either due to overflow or underflow (precision loss).
  486. */
  487. static fromString(_value, _format) {
  488. const match = _value.match(/^(-?)([0-9]*)\.?([0-9]*)$/);
  489. (0, errors_js_1.assertArgument)(match && (match[2].length + match[3].length) > 0, "invalid FixedNumber string value", "value", _value);
  490. const format = getFormat(_format);
  491. let whole = (match[2] || "0"), decimal = (match[3] || "");
  492. // Pad out the decimals
  493. while (decimal.length < format.decimals) {
  494. decimal += Zeros;
  495. }
  496. // Check precision is safe
  497. (0, errors_js_1.assert)(decimal.substring(format.decimals).match(/^0*$/), "too many decimals for format", "NUMERIC_FAULT", {
  498. operation: "fromString", fault: "underflow", value: _value
  499. });
  500. // Remove extra padding
  501. decimal = decimal.substring(0, format.decimals);
  502. const value = BigInt(match[1] + whole + decimal);
  503. checkValue(value, format, "fromString");
  504. return new FixedNumber(_guard, value, format);
  505. }
  506. /**
  507. * Creates a new [[FixedNumber]] with the big-endian representation
  508. * %%value%% with %%format%%.
  509. *
  510. * This will throw a [[NumericFaultError]] if %%value%% cannot fit
  511. * in %%format%% due to overflow.
  512. */
  513. static fromBytes(_value, _format) {
  514. let value = (0, maths_js_1.toBigInt)((0, data_js_1.getBytes)(_value, "value"));
  515. const format = getFormat(_format);
  516. if (format.signed) {
  517. value = (0, maths_js_1.fromTwos)(value, format.width);
  518. }
  519. checkValue(value, format, "fromBytes");
  520. return new FixedNumber(_guard, value, format);
  521. }
  522. }
  523. exports.FixedNumber = FixedNumber;
  524. //const f1 = FixedNumber.fromString("12.56", "fixed16x2");
  525. //const f2 = FixedNumber.fromString("0.3", "fixed16x2");
  526. //console.log(f1.divSignal(f2));
  527. //const BUMP = FixedNumber.from("0.5");
  528. //# sourceMappingURL=fixednumber.js.map