@@ -96,6 +96,7 @@ _free_sbuf(char *data, void *hint) {
9696// If a circular reference is detected, an exception is thrown.
9797static void
9898v8_to_msgpack (Handle<Value> v8obj, msgpack_object *mo, msgpack_zone *mz, size_t depth) {
99+ static const Persistent<String> TOJSON = NODE_PSYMBOL (" toJSON" );
99100
100101 if (512 < ++depth) {
101102 throw MsgpackException (" Cowardly refusing to pack object with circular reference" );
@@ -158,6 +159,14 @@ v8_to_msgpack(Handle<Value> v8obj, msgpack_object *mo, msgpack_zone *mz, size_t
158159 mo->via .raw .ptr = Buffer::Data (buf);
159160 } else {
160161 Local<Object> o = v8obj->ToObject ();
162+
163+ // for o.toJSON()
164+ if (o->Has (TOJSON ) && o->Get (TOJSON )->IsFunction ()) {
165+ Local<Function> fn = Local<Function>::Cast (o->Get (TOJSON ));
166+ v8_to_msgpack (fn->Call (o, 0 , NULL ), mo, mz, depth);
167+ return ;
168+ }
169+
161170 Local<Array> a = o->GetPropertyNames ();
162171
163172 mo->type = MSGPACK_OBJECT_MAP ;
@@ -277,16 +286,16 @@ pack(const Arguments &args) {
277286 }
278287
279288 v8::Local<Buffer> slowBuffer = node::Buffer::New (
280- sb->data , sb->alloc , _free_sbuf, (void *)sb
289+ sb->data , sb->alloc , _free_sbuf, (void *)sb
281290 );
282291
283292 // godsflaw: this part makes msgpack.pack() 1x slower than JSON.stringify()
284293 // reaching back into JS appears to be expensive.
285294 v8::Local<Object> global = v8::Context::GetCurrent ()->Global ();
286295 v8::Local<Value> bv = global->Get (String::NewSymbol (" Buffer" ));
287-
296+
288297 assert (bv->IsFunction ());
289-
298+
290299 Local<Function> bc = v8::Local<Function>::Cast (bv);
291300 Handle<Value> cArgs[3 ] = {
292301 slowBuffer->handle_ ,
0 commit comments