array-buffer-transfer.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. var global = require('../internals/global');
  3. var uncurryThis = require('../internals/function-uncurry-this');
  4. var uncurryThisAccessor = require('../internals/function-uncurry-this-accessor');
  5. var toIndex = require('../internals/to-index');
  6. var isDetached = require('../internals/array-buffer-is-detached');
  7. var arrayBufferByteLength = require('../internals/array-buffer-byte-length');
  8. var detachTransferable = require('../internals/detach-transferable');
  9. var PROPER_STRUCTURED_CLONE_TRANSFER = require('../internals/structured-clone-proper-transfer');
  10. var structuredClone = global.structuredClone;
  11. var ArrayBuffer = global.ArrayBuffer;
  12. var DataView = global.DataView;
  13. var TypeError = global.TypeError;
  14. var min = Math.min;
  15. var ArrayBufferPrototype = ArrayBuffer.prototype;
  16. var DataViewPrototype = DataView.prototype;
  17. var slice = uncurryThis(ArrayBufferPrototype.slice);
  18. var isResizable = uncurryThisAccessor(ArrayBufferPrototype, 'resizable', 'get');
  19. var maxByteLength = uncurryThisAccessor(ArrayBufferPrototype, 'maxByteLength', 'get');
  20. var getInt8 = uncurryThis(DataViewPrototype.getInt8);
  21. var setInt8 = uncurryThis(DataViewPrototype.setInt8);
  22. module.exports = (PROPER_STRUCTURED_CLONE_TRANSFER || detachTransferable) && function (arrayBuffer, newLength, preserveResizability) {
  23. var byteLength = arrayBufferByteLength(arrayBuffer);
  24. var newByteLength = newLength === undefined ? byteLength : toIndex(newLength);
  25. var fixedLength = !isResizable || !isResizable(arrayBuffer);
  26. var newBuffer;
  27. if (isDetached(arrayBuffer)) throw new TypeError('ArrayBuffer is detached');
  28. if (PROPER_STRUCTURED_CLONE_TRANSFER) {
  29. arrayBuffer = structuredClone(arrayBuffer, { transfer: [arrayBuffer] });
  30. if (byteLength === newByteLength && (preserveResizability || fixedLength)) return arrayBuffer;
  31. }
  32. if (byteLength >= newByteLength && (!preserveResizability || fixedLength)) {
  33. newBuffer = slice(arrayBuffer, 0, newByteLength);
  34. } else {
  35. var options = preserveResizability && !fixedLength && maxByteLength ? { maxByteLength: maxByteLength(arrayBuffer) } : undefined;
  36. newBuffer = new ArrayBuffer(newByteLength, options);
  37. var a = new DataView(arrayBuffer);
  38. var b = new DataView(newBuffer);
  39. var copyLength = min(newByteLength, byteLength);
  40. for (var i = 0; i < copyLength; i++) setInt8(b, i, getInt8(a, i));
  41. }
  42. if (!PROPER_STRUCTURED_CLONE_TRANSFER) detachTransferable(arrayBuffer);
  43. return newBuffer;
  44. };