buffer.js 2.1 KB

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