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

zneak picture zneak · Apr 11, 2012 · Viewed 36k times · Source

I'm working with ArrayBuffer objects, and I would like to duplicate them. While this is rather easy with actual pointers and memcpy, I couldn't find any straightforward way to do it in Javascript.

Right now, this is how I copy my ArrayBuffers:

function copy(buffer)
{
    var bytes = new Uint8Array(buffer);
    var output = new ArrayBuffer(buffer.byteLength);
    var outputBytes = new Uint8Array(output);
    for (var i = 0; i < bytes.length; i++)
        outputBytes[i] = bytes[i];
    return output;
}

Is there a prettier way?

Answer

Gleno picture Gleno · Mar 1, 2014

I prefer the following method

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