Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tjfontaine
Last active December 16, 2015 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjfontaine/aac4a2226c9f15d12ab5 to your computer and use it in GitHub Desktop.
Save tjfontaine/aac4a2226c9f15d12ab5 to your computer and use it in GitHub Desktop.
#define PERSIST_POOL_SIZE 1024
static Persistent<Array> persist_pool;
static Persistent<Object> buffer_proto;
static Persistent<FunctionTemplate> one_t;
static Persistent<Function> one_int;
static int persist_last_idx = 0;
static Handle<Value> OneInt(const Arguments &args) {
return args.This();
}
Handle<Value> Buffer::New(const Arguments &args) {
if (!args.IsConstructCall()) {
return FromConstructorTemplate(constructor_template, args);
}
HandleScope scope(node_isolate);
if (!args[0]->IsUint32()) return ThrowTypeError("Bad argument");
size_t length = args[0]->Uint32Value();
if (length > Buffer::kMaxLength) {
return ThrowRangeError("length > kMaxLength");
}
if (persist_last_idx == 0) {
if (persist_pool.IsEmpty())
persist_pool = Persistent<Array>::New(node_isolate, Array::New(PERSIST_POOL_SIZE));
if (one_int.IsEmpty()) {
Local<FunctionTemplate> t = FunctionTemplate::New(OneInt);
one_t = Persistent<FunctionTemplate>::New(node_isolate, t);
one_t->InstanceTemplate()->SetInternalFieldCount(1);
one_t->SetClassName(String::New("SlowBufferTJ"));
one_int = Persistent<Function>::New(node_isolate, one_t->GetFunction());
// TODO cache buffer proto
}
for (; persist_last_idx < PERSIST_POOL_SIZE; persist_last_idx++) {
Persistent<Object> obj = Persistent<Object>::New(node_isolate, one_int->NewInstance());
obj->SetPrototype(buffer_proto);
obj.MakeWeak(node_isolate, NULL, ObjectWrap::WeakCallback);
obj.MarkIndependent(node_isolate);
obj.SetWrapperClassId(node_isolate, BUFFER_CLASS_ID);
persist_pool->Set(persist_last_idx, obj);
}
}
Handle<Value> v = Handle<Value>(persist_pool->Get(--persist_last_idx));
persist_pool->Set(persist_last_idx, Undefined());
Persistent<Object> obj(v.As<Object>());
new Buffer(obj, length);
return scope.Close(v);
}
Buffer::Buffer(Persistent<Object> wrapper, size_t length) : ObjectWrap() {
handle_ = wrapper;
handle_->SetAlignedPointerInInternalField(0, this);
length_ = 0;
callback_ = NULL;
Replace(NULL, length, NULL, NULL);
}
Buffer::Buffer(Handle<Object> wrapper, size_t length) : ObjectWrap() {
Wrap(wrapper);
length_ = 0;
callback_ = NULL;
handle_.SetWrapperClassId(node_isolate, BUFFER_CLASS_ID);
Replace(NULL, length, NULL, NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment