Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 487
zneak Avatar asked Apr 11 '12 06:04

zneak


People also ask

Is ArrayBuffer same as buffer?

1. A Buffer is just a view for looking into an ArrayBuffer . A Buffer , in fact, is a FastBuffer , which extends (inherits from) Uint8Array , which is an octet-unit view (“partial accessor”) of the actual memory, an ArrayBuffer .

Is ArrayBuffer a binary?

The ArrayBuffer is a data type that is used to represent a generic, fixed-length binary data buffer.

What is a ArrayBuffer?

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".

What is Uint8Array used for?

Uint8Array – treats each byte in ArrayBuffer as a separate number, with possible values from 0 to 255 (a byte is 8-bit, so it can hold only that much). Such value is called a “8-bit unsigned integer”.


1 Answers

I prefer the following method

function copy(src)  {     var dst = new ArrayBuffer(src.byteLength);     new Uint8Array(dst).set(new Uint8Array(src));     return dst; } 
like image 155
Gleno Avatar answered Sep 29 '22 13:09

Gleno