number.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.NumberCoder = void 0;
  4. const index_js_1 = require("../../utils/index.js");
  5. const typed_js_1 = require("../typed.js");
  6. const abstract_coder_js_1 = require("./abstract-coder.js");
  7. const BN_0 = BigInt(0);
  8. const BN_1 = BigInt(1);
  9. const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  10. /**
  11. * @_ignore
  12. */
  13. class NumberCoder extends abstract_coder_js_1.Coder {
  14. size;
  15. signed;
  16. constructor(size, signed, localName) {
  17. const name = ((signed ? "int" : "uint") + (size * 8));
  18. super(name, name, localName, false);
  19. (0, index_js_1.defineProperties)(this, { size, signed }, { size: "number", signed: "boolean" });
  20. }
  21. defaultValue() {
  22. return 0;
  23. }
  24. encode(writer, _value) {
  25. let value = (0, index_js_1.getBigInt)(typed_js_1.Typed.dereference(_value, this.type));
  26. // Check bounds are safe for encoding
  27. let maxUintValue = (0, index_js_1.mask)(BN_MAX_UINT256, abstract_coder_js_1.WordSize * 8);
  28. if (this.signed) {
  29. let bounds = (0, index_js_1.mask)(maxUintValue, (this.size * 8) - 1);
  30. if (value > bounds || value < -(bounds + BN_1)) {
  31. this._throwError("value out-of-bounds", _value);
  32. }
  33. value = (0, index_js_1.toTwos)(value, 8 * abstract_coder_js_1.WordSize);
  34. }
  35. else if (value < BN_0 || value > (0, index_js_1.mask)(maxUintValue, this.size * 8)) {
  36. this._throwError("value out-of-bounds", _value);
  37. }
  38. return writer.writeValue(value);
  39. }
  40. decode(reader) {
  41. let value = (0, index_js_1.mask)(reader.readValue(), this.size * 8);
  42. if (this.signed) {
  43. value = (0, index_js_1.fromTwos)(value, this.size * 8);
  44. }
  45. return value;
  46. }
  47. }
  48. exports.NumberCoder = NumberCoder;
  49. //# sourceMappingURL=number.js.map