Skip to content

Instantly share code, notes, and snippets.

@nodejsbot
Created July 26, 2010 20:50
Show Gist options
  • Select an option

  • Save nodejsbot/491221 to your computer and use it in GitHub Desktop.

Select an option

Save nodejsbot/491221 to your computer and use it in GitHub Desktop.
// http://wiki.ecmascript.org/doku.php?id=harmony:ephemeron_tables
// node-overload
// @exports
// EphemeronTable()
// get(key)
// set(key,value)
//
#include <v8.h>
#include <stdio.h>
using namespace v8;
using namespace std;
void Noop(
Persistent<Value> object
, void* parameter
) {
object.Dispose();
}
void OurWeakReferenceCallback(
Persistent<Value> object
, void* parameter
) {
HandleScope scope;
Handle<Function> callback = Handle<Function>((Function*)parameter);
Handle<Value> values[0];
//ERROR: SegFault / Bus Error
printf("obj : %d : invoking collector\n",(int)&object);
callback->Call(Context::GetCurrent()->Global(),0,values);
object.Dispose();
scope.Close(Undefined());
}
void KeepingWeakReferenceCallback(
Persistent<Value> callback
, void* parameter
) {
HandleScope scope;
Handle<Object> object = Handle<Object>((Object*)parameter);
//ERROR points to different space?
printf("obj : %d : testing revival need\n",(int)&object);
if(object.IsEmpty()) {
callback.Dispose();
}
else {
//Revive this object so long as there is a dependant weak reference
Persistent<Value>::New(callback).MakeWeak(parameter,OurWeakReferenceCallback);
}
scope.Close(Undefined());
}
Handle<Value> Weak(
const Arguments& args
) {
HandleScope scope;
Handle<Value> obj = args[0];
if(!obj->IsObject() || obj->IsNull() || obj->IsUndefined()) {
return scope.Close(ThrowException(Exception::Error(String::New("First argument must be an object"))));
}
Handle<Value> onCollect = args[1];
if(onCollect->IsFunction()) {
Persistent<Object> persistent_obj = Persistent<Object>::New(Handle<Object>::Cast(obj));
Persistent<Function> persistent_cb = Persistent<Function>::New(Handle<Function>::Cast(onCollect));
printf("obj : %d : making weak\n",(int)&persistent_obj);
persistent_obj.MakeWeak(
&persistent_cb
, OurWeakReferenceCallback
);
//bind a weak ref of cb to the obj
persistent_cb.MakeWeak(
&persistent_obj
, KeepingWeakReferenceCallback
);
return scope.Close(persistent_obj);
}
else {
return scope.Close(ThrowException(Exception::Error(String::New("Collect callback must be a function"))));
}
}
extern "C" void init (Handle<Object> target)
{
HandleScope scope;
Local<FunctionTemplate> weak_template = FunctionTemplate::New(Weak);
Local<Function> weak = weak_template->GetFunction();
//Export
target->Set(String::New("Weak"),weak);
}
var Weak = require("../lib/ephemeron_table").Weak
, gc = require("../node-gc/gc")
, GC = new gc.GC();
var a={toString:function(){return "not deleted"}}
Weak(a,function a(){
//console.log("Weak Callback Invoked")
//a="deleted"
})
setInterval(function(){GC.collect()},500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment