From 8a295cd520bf7fb0e4bf44b7451e1f1fe2456706 Mon Sep 17 00:00:00 2001 From: Trevor Norris Date: Fri, 11 Oct 2013 11:44:56 -0700 Subject: [PATCH] buffer: add buf.toArrayBuffer() API --- doc/api/buffer.markdown | 4 ++++ src/node_buffer.cc | 22 ++++++++++++++++++++++ test/simple/test-buffer.js | 12 ++++++++++++ 3 files changed, 38 insertions(+) diff --git a/doc/api/buffer.markdown b/doc/api/buffer.markdown index a753aaadbe..4951567589 100644 --- a/doc/api/buffer.markdown +++ b/doc/api/buffer.markdown @@ -671,6 +671,10 @@ buffer. var b = new Buffer(50); b.fill("h"); +### buf.toArrayBuffer() + +Creates a new `ArrayBuffer` with the copied memory of the buffer instance. + ## buffer.INSPECT_MAX_BYTES * Number, Default: 50 diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 61980cb095..733684d11c 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -59,6 +59,7 @@ namespace node { namespace Buffer { +using v8::ArrayBuffer; using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; @@ -550,6 +551,25 @@ void WriteDoubleBE(const FunctionCallbackInfo& args) { } +void ToArrayBuffer(const FunctionCallbackInfo& args) { + HandleScope scope(node_isolate); + + ARGS_THIS(args.This()); + void* adata = malloc(obj_length); + + if (adata == NULL) { + FatalError("node::Buffer::ToArrayBuffer(" + "const FunctionCallbackInfo&)", + "Out Of Memory"); + } + + memcpy(adata, obj_data, obj_length); + + Local abuf = ArrayBuffer::New(adata, obj_length); + args.GetReturnValue().Set(abuf); +} + + void ByteLength(const FunctionCallbackInfo &args) { HandleScope scope(node_isolate); @@ -604,6 +624,8 @@ void SetupBufferJS(const FunctionCallbackInfo& args) { NODE_SET_METHOD(proto, "writeFloatBE", WriteFloatBE); NODE_SET_METHOD(proto, "writeFloatLE", WriteFloatLE); + NODE_SET_METHOD(proto, "toArrayBuffer", ToArrayBuffer); + NODE_SET_METHOD(proto, "copy", Copy); NODE_SET_METHOD(proto, "fill", Fill); diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index 45eb28761a..55a5ca7806 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -981,3 +981,15 @@ assert.throws(function() { assert.equal(c[i], i); } })(); + +// Test Buffers to ArrayBuffers +var b = new Buffer(5).fill('abcdf'); +var c = b.toArrayBuffer(); +assert.equal(c.byteLength, 5); +assert.equal(Object.prototype.toString.call(c), '[object ArrayBuffer]'); +var d = new Uint8Array(c); +for (var i = 0; i < 5; i++) + assert.equal(d[i], b[i]); +b.fill('ghijk'); +for (var i = 0; i < 5; i++) + assert.notEqual(d[i], b[i]);