Skip to content

Commit 8a295cd

Browse files
committed
buffer: add buf.toArrayBuffer() API
1 parent fe0bf6b commit 8a295cd

3 files changed

Lines changed: 38 additions & 0 deletions

File tree

doc/api/buffer.markdown

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -671,6 +671,10 @@ buffer.
671671
var b = new Buffer(50);
672672
b.fill("h");
673673

674+
### buf.toArrayBuffer()
675+
676+
Creates a new `ArrayBuffer` with the copied memory of the buffer instance.
677+
674678
## buffer.INSPECT_MAX_BYTES
675679

676680
* Number, Default: 50

src/node_buffer.cc

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
namespace node {
6060
namespace Buffer {
6161

62+
using v8::ArrayBuffer;
6263
using v8::Context;
6364
using v8::Function;
6465
using v8::FunctionCallbackInfo;
@@ -550,6 +551,25 @@ void WriteDoubleBE(const FunctionCallbackInfo<Value>& args) {
550551
}
551552

552553

554+
void ToArrayBuffer(const FunctionCallbackInfo<Value>& args) {
555+
HandleScope scope(node_isolate);
556+
557+
ARGS_THIS(args.This());
558+
void* adata = malloc(obj_length);
559+
560+
if (adata == NULL) {
561+
FatalError("node::Buffer::ToArrayBuffer("
562+
"const FunctionCallbackInfo<v8::Value>&)",
563+
"Out Of Memory");
564+
}
565+
566+
memcpy(adata, obj_data, obj_length);
567+
568+
Local<ArrayBuffer> abuf = ArrayBuffer::New(adata, obj_length);
569+
args.GetReturnValue().Set(abuf);
570+
}
571+
572+
553573
void ByteLength(const FunctionCallbackInfo<Value> &args) {
554574
HandleScope scope(node_isolate);
555575

@@ -604,6 +624,8 @@ void SetupBufferJS(const FunctionCallbackInfo<Value>& args) {
604624
NODE_SET_METHOD(proto, "writeFloatBE", WriteFloatBE);
605625
NODE_SET_METHOD(proto, "writeFloatLE", WriteFloatLE);
606626

627+
NODE_SET_METHOD(proto, "toArrayBuffer", ToArrayBuffer);
628+
607629
NODE_SET_METHOD(proto, "copy", Copy);
608630
NODE_SET_METHOD(proto, "fill", Fill);
609631

test/simple/test-buffer.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -981,3 +981,15 @@ assert.throws(function() {
981981
assert.equal(c[i], i);
982982
}
983983
})();
984+
985+
// Test Buffers to ArrayBuffers
986+
var b = new Buffer(5).fill('abcdf');
987+
var c = b.toArrayBuffer();
988+
assert.equal(c.byteLength, 5);
989+
assert.equal(Object.prototype.toString.call(c), '[object ArrayBuffer]');
990+
var d = new Uint8Array(c);
991+
for (var i = 0; i < 5; i++)
992+
assert.equal(d[i], b[i]);
993+
b.fill('ghijk');
994+
for (var i = 0; i < 5; i++)
995+
assert.notEqual(d[i], b[i]);

0 commit comments

Comments
 (0)