What's the most straightforward way to copy an ArrayBuffer object? What's the most straightforward way to copy an ArrayBuffer object? javascript javascript

What's the most straightforward way to copy an ArrayBuffer object?


I prefer the following method

function copy(src)  {    var dst = new ArrayBuffer(src.byteLength);    new Uint8Array(dst).set(new Uint8Array(src));    return dst;}


ArrayBuffer is supposed to support slice (http://www.khronos.org/registry/typedarray/specs/latest/) so you can try,

buffer.slice(0);

which works in Chrome 18 but not Firefox 10 or 11. As for Firefox, you need to copy it manually. You can monkey patch the slice() in Firefox because the Chrome slice() will outperform a manual copy. This would look something like,

if (!ArrayBuffer.prototype.slice)    ArrayBuffer.prototype.slice = function (start, end) {        var that = new Uint8Array(this);        if (end == undefined) end = that.length;        var result = new ArrayBuffer(end - start);        var resultArray = new Uint8Array(result);        for (var i = 0; i < resultArray.length; i++)           resultArray[i] = that[i + start];        return result;    }

Then you can call,

buffer.slice(0);

to copy the array in both Chrome and Firefox.


It appears that simply passing in the source dataview performs a copy:

var a = new Uint8Array([2,3,4,5]);var b = new Uint8Array(a);a[0] = 6;console.log(a); // [6, 3, 4, 5]console.log(b); // [2, 3, 4, 5]

Tested in FF 33 and Chrome 36.