123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. 'use strict';
  2. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  3. (typeof Uint16Array !== 'undefined') &&
  4. (typeof Int32Array !== 'undefined');
  5. function _has(obj, key) {
  6. return Object.prototype.hasOwnProperty.call(obj, key);
  7. }
  8. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  9. var sources = Array.prototype.slice.call(arguments, 1);
  10. while (sources.length) {
  11. var source = sources.shift();
  12. if (!source) { continue; }
  13. if (typeof source !== 'object') {
  14. throw new TypeError(source + 'must be non-object');
  15. }
  16. for (var p in source) {
  17. if (_has(source, p)) {
  18. obj[p] = source[p];
  19. }
  20. }
  21. }
  22. return obj;
  23. };
  24. // reduce buffer size, avoiding mem copy
  25. exports.shrinkBuf = function (buf, size) {
  26. if (buf.length === size) { return buf; }
  27. if (buf.subarray) { return buf.subarray(0, size); }
  28. buf.length = size;
  29. return buf;
  30. };
  31. var fnTyped = {
  32. arraySet: function (dest, src, src_offs, len, dest_offs) {
  33. if (src.subarray && dest.subarray) {
  34. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  35. return;
  36. }
  37. // Fallback to ordinary array
  38. for (var i = 0; i < len; i++) {
  39. dest[dest_offs + i] = src[src_offs + i];
  40. }
  41. },
  42. // Join array of chunks to single array.
  43. flattenChunks: function (chunks) {
  44. var i, l, len, pos, chunk, result;
  45. // calculate data length
  46. len = 0;
  47. for (i = 0, l = chunks.length; i < l; i++) {
  48. len += chunks[i].length;
  49. }
  50. // join chunks
  51. result = new Uint8Array(len);
  52. pos = 0;
  53. for (i = 0, l = chunks.length; i < l; i++) {
  54. chunk = chunks[i];
  55. result.set(chunk, pos);
  56. pos += chunk.length;
  57. }
  58. return result;
  59. }
  60. };
  61. var fnUntyped = {
  62. arraySet: function (dest, src, src_offs, len, dest_offs) {
  63. for (var i = 0; i < len; i++) {
  64. dest[dest_offs + i] = src[src_offs + i];
  65. }
  66. },
  67. // Join array of chunks to single array.
  68. flattenChunks: function (chunks) {
  69. return [].concat.apply([], chunks);
  70. }
  71. };
  72. // Enable/Disable typed arrays use, for testing
  73. //
  74. exports.setTyped = function (on) {
  75. if (on) {
  76. exports.Buf8 = Uint8Array;
  77. exports.Buf16 = Uint16Array;
  78. exports.Buf32 = Int32Array;
  79. exports.assign(exports, fnTyped);
  80. } else {
  81. exports.Buf8 = Array;
  82. exports.Buf16 = Array;
  83. exports.Buf32 = Array;
  84. exports.assign(exports, fnUntyped);
  85. }
  86. };
  87. exports.setTyped(TYPED_OK);