CloneArrayBuffer.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var GetPrototypeFromConstructor = require('./GetPrototypeFromConstructor');
  5. var IsConstructor = require('./IsConstructor');
  6. var IsDetachedBuffer = require('./IsDetachedBuffer');
  7. var OrdinarySetPrototypeOf = require('./OrdinarySetPrototypeOf');
  8. var isInteger = require('../helpers/isInteger');
  9. var isArrayBuffer = require('is-array-buffer');
  10. var arrayBufferSlice = require('arraybuffer.prototype.slice');
  11. // https://262.ecma-international.org/12.0/#sec-clonearraybuffer
  12. module.exports = function CloneArrayBuffer(srcBuffer, srcByteOffset, srcLength, cloneConstructor) {
  13. if (!isArrayBuffer(srcBuffer)) {
  14. throw new $TypeError('Assertion failed: `srcBuffer` must be an ArrayBuffer instance');
  15. }
  16. if (!isInteger(srcByteOffset) || srcByteOffset < 0) {
  17. throw new $TypeError('Assertion failed: `srcByteOffset` must be a non-negative integer');
  18. }
  19. if (!isInteger(srcLength) || srcLength < 0) {
  20. throw new $TypeError('Assertion failed: `srcLength` must be a non-negative integer');
  21. }
  22. if (!IsConstructor(cloneConstructor)) {
  23. throw new $TypeError('Assertion failed: `cloneConstructor` must be a constructor');
  24. }
  25. // 3. Let targetBuffer be ? AllocateArrayBuffer(cloneConstructor, srcLength).
  26. var proto = GetPrototypeFromConstructor(cloneConstructor, '%ArrayBufferPrototype%'); // step 3, kinda
  27. if (IsDetachedBuffer(srcBuffer)) {
  28. throw new $TypeError('`srcBuffer` must not be a detached ArrayBuffer'); // step 4
  29. }
  30. /*
  31. 5. Let srcBlock be srcBuffer.[[ArrayBufferData]].
  32. 6. Let targetBlock be targetBuffer.[[ArrayBufferData]].
  33. 7. Perform CopyDataBlockBytes(targetBlock, 0, srcBlock, srcByteOffset, srcLength).
  34. */
  35. var targetBuffer = arrayBufferSlice(srcBuffer, srcByteOffset, srcByteOffset + srcLength); // steps 5-7
  36. OrdinarySetPrototypeOf(targetBuffer, proto); // step 3
  37. return targetBuffer; // step 8
  38. };