buffer.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const hasBuffer = (typeof Buffer !== 'undefined');
  2. let textDecoder;
  3. export class VSBuffer {
  4. constructor(buffer) {
  5. this.buffer = buffer;
  6. this.byteLength = this.buffer.byteLength;
  7. }
  8. static wrap(actual) {
  9. if (hasBuffer && !(Buffer.isBuffer(actual))) {
  10. // https://nodejs.org/dist/latest-v10.x/docs/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
  11. // Create a zero-copy Buffer wrapper around the ArrayBuffer pointed to by the Uint8Array
  12. actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength);
  13. }
  14. return new VSBuffer(actual);
  15. }
  16. toString() {
  17. if (hasBuffer) {
  18. return this.buffer.toString();
  19. }
  20. else {
  21. if (!textDecoder) {
  22. textDecoder = new TextDecoder();
  23. }
  24. return textDecoder.decode(this.buffer);
  25. }
  26. }
  27. }
  28. export function readUInt16LE(source, offset) {
  29. return (((source[offset + 0] << 0) >>> 0) |
  30. ((source[offset + 1] << 8) >>> 0));
  31. }
  32. export function writeUInt16LE(destination, value, offset) {
  33. destination[offset + 0] = (value & 0b11111111);
  34. value = value >>> 8;
  35. destination[offset + 1] = (value & 0b11111111);
  36. }
  37. export function readUInt32BE(source, offset) {
  38. return (source[offset] * Math.pow(2, 24)
  39. + source[offset + 1] * Math.pow(2, 16)
  40. + source[offset + 2] * Math.pow(2, 8)
  41. + source[offset + 3]);
  42. }
  43. export function writeUInt32BE(destination, value, offset) {
  44. destination[offset + 3] = value;
  45. value = value >>> 8;
  46. destination[offset + 2] = value;
  47. value = value >>> 8;
  48. destination[offset + 1] = value;
  49. value = value >>> 8;
  50. destination[offset] = value;
  51. }
  52. export function readUInt8(source, offset) {
  53. return source[offset];
  54. }
  55. export function writeUInt8(destination, value, offset) {
  56. destination[offset] = value;
  57. }