hash-reader.js 1.9 KB

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