ensure_buffer.js 706 B

1234567891011121314151617181920212223
  1. 'use strict';
  2. const Buffer = require('buffer').Buffer;
  3. /**
  4. * Makes sure that, if a Uint8Array is passed in, it is wrapped in a Buffer.
  5. *
  6. * @param {Buffer|Uint8Array} potentialBuffer The potential buffer
  7. * @returns {Buffer} the input if potentialBuffer is a buffer, or a buffer that
  8. * wraps a passed in Uint8Array
  9. * @throws {TypeError} If anything other than a Buffer or Uint8Array is passed in
  10. */
  11. module.exports = function ensureBuffer(potentialBuffer) {
  12. if (potentialBuffer instanceof Buffer) {
  13. return potentialBuffer;
  14. }
  15. if (potentialBuffer instanceof Uint8Array) {
  16. return Buffer.from(potentialBuffer.buffer);
  17. }
  18. throw new TypeError('Must use either Buffer or Uint8Array');
  19. };