hash-reader.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. /**
  4. * The maximum number of bytes that can be read from the hash.
  5. *
  6. * Calculated out 2^64-1, since `Xn` syntax (for `Xn ** Yn`) requires TS
  7. * targeting esnext/es2020 which includes features that Node 10 doesn't
  8. * yet supported.
  9. */
  10. exports.maxHashBytes = BigInt('18446744073709551615');
  11. /**
  12. * Base hash reader implementation.
  13. */
  14. class BaseHashReader {
  15. constructor(reader) {
  16. this.pos = BigInt(0);
  17. this.reader = reader;
  18. }
  19. get position() {
  20. return this.pos;
  21. }
  22. set position(value) {
  23. var _a;
  24. // to avoid footguns of people using numbers:
  25. if (typeof value !== 'bigint') {
  26. throw new Error(`Got a ${typeof value} set in to reader.position, expected a bigint`);
  27. }
  28. this.boundsCheck(value);
  29. this.pos = value;
  30. (_a = this.reader) === null || _a === void 0 ? void 0 : _a.set_position(value);
  31. }
  32. /**
  33. * @inheritdoc
  34. */
  35. readInto(target) {
  36. if (!this.reader) {
  37. throw new Error(`Cannot read from a hash after it was disposed`);
  38. }
  39. const next = this.pos + BigInt(target.length);
  40. this.boundsCheck(next);
  41. this.reader.fill(target);
  42. this.position = next;
  43. }
  44. /**
  45. * @inheritdoc
  46. */
  47. read(bytes) {
  48. const data = this.alloc(bytes);
  49. this.readInto(data);
  50. return data;
  51. }
  52. /**
  53. * @inheritdoc
  54. */
  55. dispose() {
  56. var _a, _b;
  57. (_b = (_a = this.reader) === null || _a === void 0 ? void 0 : _a.free) === null || _b === void 0 ? void 0 : _b.call(_a);
  58. this.reader = undefined;
  59. }
  60. boundsCheck(position) {
  61. if (position > exports.maxHashBytes) {
  62. throw new RangeError(`Cannot read past ${exports.maxHashBytes} bytes in BLAKE3 hashes`);
  63. }
  64. if (position < BigInt(0)) {
  65. throw new RangeError(`Cannot read to a negative position`);
  66. }
  67. }
  68. }
  69. exports.BaseHashReader = BaseHashReader;
  70. //# sourceMappingURL=hash-reader.js.map