browserHashUtils.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var Buffer = require('buffer/').Buffer;
  2. /**
  3. * This is a polyfill for the static method `isView` of `ArrayBuffer`, which is
  4. * e.g. missing in IE 10.
  5. *
  6. * @api private
  7. */
  8. if (
  9. typeof ArrayBuffer !== 'undefined' &&
  10. typeof ArrayBuffer.isView === 'undefined'
  11. ) {
  12. ArrayBuffer.isView = function(arg) {
  13. return viewStrings.indexOf(Object.prototype.toString.call(arg)) > -1;
  14. };
  15. }
  16. /**
  17. * @api private
  18. */
  19. var viewStrings = [
  20. '[object Int8Array]',
  21. '[object Uint8Array]',
  22. '[object Uint8ClampedArray]',
  23. '[object Int16Array]',
  24. '[object Uint16Array]',
  25. '[object Int32Array]',
  26. '[object Uint32Array]',
  27. '[object Float32Array]',
  28. '[object Float64Array]',
  29. '[object DataView]',
  30. ];
  31. /**
  32. * @api private
  33. */
  34. function isEmptyData(data) {
  35. if (typeof data === 'string') {
  36. return data.length === 0;
  37. }
  38. return data.byteLength === 0;
  39. }
  40. /**
  41. * @api private
  42. */
  43. function convertToBuffer(data) {
  44. if (typeof data === 'string') {
  45. data = new Buffer(data, 'utf8');
  46. }
  47. if (ArrayBuffer.isView(data)) {
  48. return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
  49. }
  50. return new Uint8Array(data);
  51. }
  52. /**
  53. * @api private
  54. */
  55. module.exports = exports = {
  56. isEmptyData: isEmptyData,
  57. convertToBuffer: convertToBuffer,
  58. };