Skip to content

Commit

Permalink
Expose # bytes left in buffer after unpack.
Browse files Browse the repository at this point in the history
- If msgpack.unpack() does not consume the entire buffer, expose the
  number of bytes remaining as the 'msgpack.unpack.bytes_remaining'
  property.
  • Loading branch information
pgriess committed May 27, 2010
1 parent 28f071b commit 74002bb
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/msgpack.cc
Expand Up @@ -10,6 +10,9 @@ using namespace v8;
using namespace node;

static Persistent<String> msgpack_tag_symbol;
static Persistent<String> msgpack_bytes_remaining_symbol;

static Persistent<FunctionTemplate> msgpack_unpack_template;

// An exception class that wraps a textual message
class MsgpackException {
Expand Down Expand Up @@ -280,11 +283,12 @@ unpack(const Arguments &args) {

switch (msgpack_unpack(buf->data(), buf->length(), &off, &mz._mz, &mo)) {
case MSGPACK_UNPACK_EXTRA_BYTES:
fprintf(stderr, "msgpack::unpack() got %lu extra bytes\n", off);
/* fall through */

case MSGPACK_UNPACK_SUCCESS:
try {
msgpack_unpack_template->GetFunction()->Set(
msgpack_bytes_remaining_symbol,
Integer::New(buf->length() - off)
);
return scope.Close(msgpack_to_v8(&mo));
} catch (MsgpackException e) {
return e.getThrownException();
Expand All @@ -301,9 +305,19 @@ init(Handle<Object> target) {
HandleScope scope;

NODE_SET_METHOD(target, "pack", pack);
NODE_SET_METHOD(target, "unpack", unpack);

// Go through this mess rather than call NODE_SET_METHOD so that we can set
// a field on the function for 'bytes_remaining'.
msgpack_unpack_template = Persistent<FunctionTemplate>::New(
FunctionTemplate::New(unpack)
);
target->Set(
String::NewSymbol("unpack"),
msgpack_unpack_template->GetFunction()
);

msgpack_tag_symbol = NODE_PSYMBOL("msgpack::tag");
msgpack_bytes_remaining_symbol = NODE_PSYMBOL("bytes_remaining");
}

// vim:ts=4 sw=4 et
22 changes: 22 additions & 0 deletions test/test-unpack-extra.js
@@ -0,0 +1,22 @@
// Verify that unpacking a buffer with extra bytes doesn't lose the extra data

var assert = require('assert');
var msgpack = require('msgpack');
var buffer = require('buffer');

// Object to test with
var o = [1, 2, 3];

// Create two buffers full of packed data, 'b' and 'bb', with the latter
// containing 3 extra bytes
var b = msgpack.pack(o);
var bb = new buffer.Buffer(b.length + 3);
b.copy(bb, 0, 0, b.length);

// Expect no remaining bytes when unpacking 'b'
assert.deepEqual(msgpack.unpack(b), o);
assert.deepEqual(msgpack.unpack.bytes_remaining, 0);

// Expect 3 remaining bytes when unpacking 'bb'
assert.deepEqual(msgpack.unpack(bb), o);
assert.equal(msgpack.unpack.bytes_remaining, 3);
File renamed without changes.

0 comments on commit 74002bb

Please sign in to comment.