2011-04-13 17:20:48 -04:00
|
|
|
#include "v8.h"
|
|
|
|
#include "v8_weakref.h"
|
|
|
|
|
|
|
|
using namespace v8;
|
|
|
|
|
|
|
|
v8_weakref::v8_weakref(VALUE object) {
|
|
|
|
this->external = Persistent<External>::New(External::New((void *)this));
|
2011-04-15 09:43:06 -04:00
|
|
|
this->external.MakeWeak(this, v8_weakref_dispose);
|
2011-04-13 17:20:48 -04:00
|
|
|
this->set(object);
|
|
|
|
}
|
|
|
|
|
|
|
|
void v8_weakref::set(VALUE value) {
|
|
|
|
this->object_id = rb_obj_id(value);
|
2011-05-02 11:29:34 -04:00
|
|
|
VALUE data = Data_Wrap_Struct(rb_cObject, 0, 0, this);
|
|
|
|
VALUE finalizer = rb_proc_new((VALUE (*)(...))v8_weakref_finalize, data);
|
2011-04-15 09:43:06 -04:00
|
|
|
rb_funcall(v8_weakref_objectspace(), rb_intern("define_finalizer"), 2, value, finalizer);
|
2011-04-13 17:20:48 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
VALUE v8_weakref::get() {
|
2011-04-15 09:43:06 -04:00
|
|
|
if (this->object_id) {
|
|
|
|
return rb_rescue((VALUE (*)(...))v8_weakref_id2ref, this->object_id, (VALUE (*)(...))v8_weakref_nil, Qnil);
|
|
|
|
} else {
|
|
|
|
return Qnil;
|
|
|
|
}
|
2011-04-13 17:20:48 -04:00
|
|
|
}
|
|
|
|
|
2011-05-02 11:29:34 -04:00
|
|
|
VALUE v8_weakref_finalize(VALUE object_id, VALUE data) {
|
2011-04-15 09:43:06 -04:00
|
|
|
v8_weakref* weakref = 0;
|
2011-05-02 11:29:34 -04:00
|
|
|
Data_Get_Struct(data, struct v8_weakref, weakref);
|
2011-04-15 09:43:06 -04:00
|
|
|
weakref->object_id = Qnil;
|
|
|
|
return Qnil;
|
|
|
|
}
|
|
|
|
|
|
|
|
void v8_weakref_dispose(Persistent<Value> value, void* weakref) {
|
2011-04-13 17:20:48 -04:00
|
|
|
value.Dispose();
|
|
|
|
value.Clear();
|
|
|
|
delete (v8_weakref*)weakref;
|
|
|
|
}
|
|
|
|
|
|
|
|
VALUE v8_weakref_nil(VALUE nil, VALUE exception) {
|
|
|
|
return nil;
|
|
|
|
}
|
|
|
|
|
2011-04-15 09:43:06 -04:00
|
|
|
VALUE v8_weakref_objectspace() {
|
|
|
|
return rb_const_get(rb_cObject, rb_intern("ObjectSpace"));
|
|
|
|
}
|
|
|
|
|
2011-04-13 17:20:48 -04:00
|
|
|
VALUE v8_weakref_id2ref(VALUE id) {
|
2011-04-15 09:43:06 -04:00
|
|
|
return rb_funcall(v8_weakref_objectspace(), rb_intern("_id2ref"), 1, id);
|
2011-04-13 17:20:48 -04:00
|
|
|
}
|
|
|
|
|