common.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. // **Github:** https://github.com/fidm/x509
  4. //
  5. // **License:** MIT
  6. /**
  7. * BufferVisitor is a visit tool to manipulate buffer.
  8. */
  9. class BufferVisitor {
  10. constructor(buf, start = 0, end = 0) {
  11. this.start = start;
  12. this.end = end > start ? end : start;
  13. this.buf = buf;
  14. }
  15. /**
  16. * return the underlying buffer length
  17. */
  18. get length() {
  19. return this.buf.length;
  20. }
  21. /**
  22. * Reset visitor' start and end value.
  23. * @param start
  24. * @param end
  25. */
  26. reset(start = 0, end = 0) {
  27. this.start = start;
  28. if (end >= this.start) {
  29. this.end = end;
  30. }
  31. else if (this.end < this.start) {
  32. this.end = this.start;
  33. }
  34. return this;
  35. }
  36. /**
  37. * consume some bytes.
  38. * @param steps steps to walk
  39. */
  40. walk(steps) {
  41. this.start = this.end;
  42. this.end += steps;
  43. return this;
  44. }
  45. /**
  46. * The buffer should have remaining the "steps" of bytes to consume,
  47. * otherwise it will throw an error with given message.
  48. * @param steps steps to consume.
  49. * @param message message to throw.
  50. */
  51. mustHas(steps, message = 'Too few bytes to parse.') {
  52. const requested = this.end + steps;
  53. if (requested > this.buf.length) {
  54. const error = new Error(message);
  55. error.available = this.buf.length;
  56. error.requested = requested;
  57. throw error;
  58. }
  59. this.walk(0);
  60. return this;
  61. }
  62. /**
  63. * Check the remaining bytes with bufferVisitor.mustHas method and then walk.
  64. * @param steps steps to consume.
  65. * @param message message to throw.
  66. */
  67. mustWalk(steps, message) {
  68. this.mustHas(steps, message);
  69. this.walk(steps);
  70. return this;
  71. }
  72. }
  73. exports.BufferVisitor = BufferVisitor;
  74. //# sourceMappingURL=common.js.map