ensure_buffer.ts 889 B

123456789101112131415161718192021222324252627
  1. import { Buffer } from 'buffer';
  2. import { BSONTypeError } from './error';
  3. import { isAnyArrayBuffer } from './parser/utils';
  4. /**
  5. * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer.
  6. *
  7. * @param potentialBuffer - The potential buffer
  8. * @returns Buffer the input if potentialBuffer is a buffer, or a buffer that
  9. * wraps a passed in Uint8Array
  10. * @throws BSONTypeError If anything other than a Buffer or Uint8Array is passed in
  11. */
  12. export function ensureBuffer(potentialBuffer: Buffer | ArrayBufferView | ArrayBuffer): Buffer {
  13. if (ArrayBuffer.isView(potentialBuffer)) {
  14. return Buffer.from(
  15. potentialBuffer.buffer,
  16. potentialBuffer.byteOffset,
  17. potentialBuffer.byteLength
  18. );
  19. }
  20. if (isAnyArrayBuffer(potentialBuffer)) {
  21. return Buffer.from(potentialBuffer);
  22. }
  23. throw new BSONTypeError('Must use either Buffer or TypedArray');
  24. }