JsonPackMpint.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.JsonPackMpint = void 0;
  4. class JsonPackMpint {
  5. constructor(data) {
  6. this.data = data;
  7. }
  8. static fromBigInt(value) {
  9. if (value === BigInt(0)) {
  10. return new JsonPackMpint(new Uint8Array(0));
  11. }
  12. const negative = value < BigInt(0);
  13. const bytes = [];
  14. if (negative) {
  15. const absValue = -value;
  16. const bitLength = absValue.toString(2).length;
  17. const byteLength = Math.ceil((bitLength + 1) / 8);
  18. const twoComplement = (BigInt(1) << BigInt(byteLength * 8)) + value;
  19. for (let i = byteLength - 1; i >= 0; i--) {
  20. bytes.push(Number((twoComplement >> BigInt(i * 8)) & BigInt(0xff)));
  21. }
  22. while (bytes.length > 0 && bytes[0] === 0xff && bytes.length > 1 && (bytes[1] & 0x80) !== 0) {
  23. bytes.shift();
  24. }
  25. }
  26. else {
  27. let tempValue = value;
  28. while (tempValue > BigInt(0)) {
  29. bytes.unshift(Number(tempValue & BigInt(0xff)));
  30. tempValue >>= BigInt(8);
  31. }
  32. if (bytes[0] & 0x80) {
  33. bytes.unshift(0);
  34. }
  35. }
  36. return new JsonPackMpint(new Uint8Array(bytes));
  37. }
  38. toBigInt() {
  39. if (this.data.length === 0) {
  40. return BigInt(0);
  41. }
  42. const negative = (this.data[0] & 0x80) !== 0;
  43. if (negative) {
  44. let value = BigInt(0);
  45. for (let i = 0; i < this.data.length; i++) {
  46. value = (value << BigInt(8)) | BigInt(this.data[i]);
  47. }
  48. const bitLength = this.data.length * 8;
  49. return value - (BigInt(1) << BigInt(bitLength));
  50. }
  51. else {
  52. let value = BigInt(0);
  53. for (let i = 0; i < this.data.length; i++) {
  54. value = (value << BigInt(8)) | BigInt(this.data[i]);
  55. }
  56. return value;
  57. }
  58. }
  59. static fromNumber(value) {
  60. if (!Number.isInteger(value)) {
  61. throw new Error('Value must be an integer');
  62. }
  63. return JsonPackMpint.fromBigInt(BigInt(value));
  64. }
  65. toNumber() {
  66. const bigIntValue = this.toBigInt();
  67. if (bigIntValue > BigInt(Number.MAX_SAFE_INTEGER) || bigIntValue < BigInt(Number.MIN_SAFE_INTEGER)) {
  68. throw new Error('Value is outside safe integer range');
  69. }
  70. return Number(bigIntValue);
  71. }
  72. }
  73. exports.JsonPackMpint = JsonPackMpint;
  74. //# sourceMappingURL=JsonPackMpint.js.map