index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. var forEach = require('for-each');
  3. var callBind = require('call-bind');
  4. var typedArrays = require('available-typed-arrays')();
  5. var getters = {};
  6. var hasProto = require('has-proto')();
  7. var gOPD = Object.getOwnPropertyDescriptor;
  8. var oDP = Object.defineProperty;
  9. if (gOPD) {
  10. var getByteLength = function (x) {
  11. return x.byteLength;
  12. };
  13. forEach(typedArrays, function (typedArray) {
  14. // In Safari 7, Typed Array constructors are typeof object
  15. if (typeof global[typedArray] === 'function' || typeof global[typedArray] === 'object') {
  16. var Proto = global[typedArray].prototype;
  17. var descriptor = gOPD(Proto, 'byteLength');
  18. if (!descriptor && hasProto) {
  19. var superProto = Proto.__proto__; // eslint-disable-line no-proto
  20. descriptor = gOPD(superProto, 'byteLength');
  21. }
  22. // Opera 12.16 has a magic byteLength data property on instances AND on Proto
  23. if (descriptor && descriptor.get) {
  24. getters[typedArray] = callBind(descriptor.get);
  25. } else if (oDP) {
  26. // this is likely an engine where instances have a magic byteLength data property
  27. var arr = new global[typedArray](2);
  28. descriptor = gOPD(arr, 'byteLength');
  29. if (descriptor && descriptor.configurable) {
  30. oDP(arr, 'length', { value: 3 });
  31. }
  32. if (arr.length === 2) {
  33. getters[typedArray] = getByteLength;
  34. }
  35. }
  36. }
  37. });
  38. }
  39. var tryTypedArrays = function tryAllTypedArrays(value) {
  40. var foundByteLength;
  41. forEach(getters, function (getter) {
  42. if (typeof foundByteLength !== 'number') {
  43. try {
  44. var byteLength = getter(value);
  45. if (typeof byteLength === 'number') {
  46. foundByteLength = byteLength;
  47. }
  48. } catch (e) {}
  49. }
  50. });
  51. return foundByteLength;
  52. };
  53. var isTypedArray = require('is-typed-array');
  54. module.exports = function typedArrayByteLength(value) {
  55. if (!isTypedArray(value)) {
  56. return false;
  57. }
  58. return tryTypedArrays(value);
  59. };