dataReader.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { Decode } from "./stringTools.js";
  2. /**
  3. * Utility class for reading from a data buffer
  4. */
  5. export class DataReader {
  6. /**
  7. * Constructor
  8. * @param buffer The buffer to read
  9. */
  10. constructor(buffer) {
  11. /**
  12. * The current byte offset from the beginning of the data buffer.
  13. */
  14. this.byteOffset = 0;
  15. this.buffer = buffer;
  16. }
  17. /**
  18. * Loads the given byte length.
  19. * @param byteLength The byte length to load
  20. * @returns A promise that resolves when the load is complete
  21. */
  22. loadAsync(byteLength) {
  23. return this.buffer.readAsync(this.byteOffset, byteLength).then((data) => {
  24. this._dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
  25. this._dataByteOffset = 0;
  26. });
  27. }
  28. /**
  29. * Read a unsigned 32-bit integer from the currently loaded data range.
  30. * @returns The 32-bit integer read
  31. */
  32. readUint32() {
  33. const value = this._dataView.getUint32(this._dataByteOffset, true);
  34. this._dataByteOffset += 4;
  35. this.byteOffset += 4;
  36. return value;
  37. }
  38. /**
  39. * Read a byte array from the currently loaded data range.
  40. * @param byteLength The byte length to read
  41. * @returns The byte array read
  42. */
  43. readUint8Array(byteLength) {
  44. const value = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._dataByteOffset, byteLength);
  45. this._dataByteOffset += byteLength;
  46. this.byteOffset += byteLength;
  47. return value;
  48. }
  49. /**
  50. * Read a string from the currently loaded data range.
  51. * @param byteLength The byte length to read
  52. * @returns The string read
  53. */
  54. readString(byteLength) {
  55. return Decode(this.readUint8Array(byteLength));
  56. }
  57. /**
  58. * Skips the given byte length the currently loaded data range.
  59. * @param byteLength The byte length to skip
  60. */
  61. skipBytes(byteLength) {
  62. this._dataByteOffset += byteLength;
  63. this.byteOffset += byteLength;
  64. }
  65. }
  66. //# sourceMappingURL=dataReader.js.map