diff options
author | James M Snell <jasnell@gmail.com> | 2016-03-15 11:08:32 -0700 |
---|---|---|
committer | James M Snell <jasnell@gmail.com> | 2016-03-23 08:52:44 -0700 |
commit | 7d73e60f60e2161457ca4c923008c9064a36bced (patch) | |
tree | 3fca1081a347bdc49ec710b971225d8f6a0c295b /lib | |
parent | 443c2d5442edf78a5b91ed13e756e21ea30a5bb1 (diff) | |
download | android-node-v8-7d73e60f60e2161457ca4c923008c9064a36bced.tar.gz android-node-v8-7d73e60f60e2161457ca4c923008c9064a36bced.tar.bz2 android-node-v8-7d73e60f60e2161457ca4c923008c9064a36bced.zip |
buffer: add swap16() and swap32() methods
Adds Buffer.prototype.swap16() and Buffer.prototype.swap32()
methods that mutate the Buffer instance in-place by swapping the
16-bit and 32-bit byte-order.
Example:
```js
const buf = Buffer([0x1, 0x2, 0x3, 0x4]);
buf.swap16();
console.log(buf);
// prints Buffer(0x2, 0x1, 0x4, 0x3);
buf.swap32();
console.log(buf);
// prints Buffer(0x3, 0x4, 0x1, 0x2);
```
PR-URL: https://github.com/nodejs/node/pull/5724
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/buffer.js | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/lib/buffer.js b/lib/buffer.js index b138552ef9..2fe13303f6 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -17,6 +17,48 @@ var poolSize, poolOffset, allocPool; binding.setupBufferJS(Buffer.prototype, bindingObj); + +const swap16n = binding.swap16; +const swap32n = binding.swap32; + +function swap(b, n, m) { + const i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16() { + // For Buffer.length < 512, it's generally faster to + // do the swap in javascript. For larger buffers, + // dropping down to the native code is faster. + const len = this.length; + if (len % 2 !== 0) + throw new RangeError('Buffer size must be a multiple of 16-bits'); + if (len < 512) { + for (var i = 0; i < len; i += 2) + swap(this, i, i + 1); + return this; + } + return swap16n.apply(this); +}; + +Buffer.prototype.swap32 = function swap32() { + // For Buffer.length < 1024, it's generally faster to + // do the swap in javascript. For larger buffers, + // dropping down to the native code is faster. + const len = this.length; + if (len % 4 !== 0) + throw new RangeError('Buffer size must be a multiple of 32-bits'); + if (len < 1024) { + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; + } + return swap32n.apply(this); +}; + const flags = bindingObj.flags; const kNoZeroFill = 0; |