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