utils.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  3. (typeof Uint16Array !== 'undefined') &&
  4. (typeof Int32Array !== 'undefined');
  5. export function assign(obj /*from1, from2, from3, ...*/) {
  6. var sources = Array.prototype.slice.call(arguments, 1);
  7. while (sources.length) {
  8. var source = sources.shift();
  9. if (!source) { continue; }
  10. if (typeof source !== 'object') {
  11. throw new TypeError(source + 'must be non-object');
  12. }
  13. for (var p in source) {
  14. if (source.hasOwnProperty(p)) {
  15. obj[p] = source[p];
  16. }
  17. }
  18. }
  19. return obj;
  20. }
  21. // reduce buffer size, avoiding mem copy
  22. export function shrinkBuf(buf, size) {
  23. if (buf.length === size) { return buf; }
  24. if (buf.subarray) { return buf.subarray(0, size); }
  25. buf.length = size;
  26. return buf;
  27. }
  28. export function arraySet(dest, src, src_offs, len, dest_offs) {
  29. if (src.subarray && dest.subarray) {
  30. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  31. return;
  32. }
  33. // Fallback to ordinary array
  34. for (var i = 0; i < len; i++) {
  35. dest[dest_offs + i] = src[src_offs + i];
  36. }
  37. }
  38. export function flattenChunks(chunks) {
  39. var i, l, len, pos, chunk, result;
  40. // calculate data length
  41. len = 0;
  42. for (i = 0, l = chunks.length; i < l; i++) {
  43. len += chunks[i].length;
  44. }
  45. // join chunks
  46. result = new Uint8Array(len);
  47. pos = 0;
  48. for (i = 0, l = chunks.length; i < l; i++) {
  49. chunk = chunks[i];
  50. result.set(chunk, pos);
  51. pos += chunk.length;
  52. }
  53. return result;
  54. }
  55. export var Buf8 = Uint8Array;
  56. export var Buf16 = Uint16Array;
  57. export var Buf32 = Int32Array;
  58. // Enable/Disable typed arrays use, for testing
  59. //