Skip to content

Instantly share code, notes, and snippets.

@renesugar
Forked from nphyx/arraybuffer.transfer.js
Created May 11, 2021 03:16
Show Gist options
  • Save renesugar/ae894ece95cb5544ab611c10224fefcb to your computer and use it in GitHub Desktop.
Save renesugar/ae894ece95cb5544ab611c10224fefcb to your computer and use it in GitHub Desktop.
A polyfill for ArrayBuffer.prototype.transfer that is substantially faster than a naive byte-by-byte transfer implementation.
if(typeof(ArrayBuffer.prototype.transfer) === "undefined") {
ArrayBuffer.prototype.transfer = function transfer(old) {
var dva, dvb, i, mod;
dva = new DataView(this);
dvb = new DataView(old);
mod = this.byteLength%8+1;
for(i = 0; i <= old.byteLength-mod; i+=8) dva.setFloat64(i, dvb.getFloat64(i));
mod = this.byteLength%4+1;
if(i < old.byteLength-mod) {
dva.setUint32(i, dvb.getUint32(i));
i += 4;
}
mod = this.byteLength%2+1;
if(i < old.byteLength-mod) {
dva.setUint16(i, dvb.getUint16(i));
i += 2;
}
if(i < old.byteLength) dva.setUint8(i, dvb.getUint8(i));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment