CloneArrayBuffer.js 1.8 KB

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