number.js 1.6 KB

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