From 8adcc30e3abdcbec625c1c78e4e1320eac472c1a Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Thu, 17 May 2012 11:04:05 -0500 Subject: [PATCH] expose v8::Array --- ext/v8/array.cc | 16 ++++++++++++++++ ext/v8/convert.cc | 4 ++-- ext/v8/rr.h | 5 +++++ spec/c/array_spec.rb | 28 ++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 spec/c/array_spec.rb diff --git a/ext/v8/array.cc b/ext/v8/array.cc index 34fe379..ab4b9bb 100644 --- a/ext/v8/array.cc +++ b/ext/v8/array.cc @@ -4,7 +4,23 @@ namespace rr { void Array::Init() { ClassBuilder("Array", Object::Class). + defineSingletonMethod("New", &New). + defineMethod("Length", &Length). + defineMethod("CloneElementAt", &CloneElementAt). store(&Class); } +VALUE Array::New(int argc, VALUE argv[], VALUE self) { + VALUE length; rb_scan_args(argc, argv, "01", &length); + return Array(v8::Array::New(Int(length))); +} + +VALUE Array::Length(VALUE self) { + return UINT2NUM(Array(self)->Length()); +} + +VALUE Array::CloneElementAt(VALUE self, VALUE index) { + return Object(Array(self)->CloneElementAt(UInt32(index))); +} + } \ No newline at end of file diff --git a/ext/v8/convert.cc b/ext/v8/convert.cc index 343b32e..8548d25 100644 --- a/ext/v8/convert.cc +++ b/ext/v8/convert.cc @@ -6,8 +6,8 @@ VALUE Bool(bool b) { return b ? Qtrue : Qfalse; } -VALUE Int(int i) { - return INT2FIX(i); +int Int(VALUE v) { + return RTEST(v) ? NUM2INT(v) : 0; } uint32_t UInt32(VALUE num) { diff --git a/ext/v8/rr.h b/ext/v8/rr.h index 438f450..00120dd 100644 --- a/ext/v8/rr.h +++ b/ext/v8/rr.h @@ -315,7 +315,12 @@ public: class Array : public Ref { public: static void Init(); + static VALUE New(int argc, VALUE argv[], VALUE self); + static VALUE Length(VALUE self); + static VALUE CloneElementAt(VALUE self, VALUE index); + inline Array(v8::Handle array) : Ref(array) {} + inline Array(VALUE value) : Ref(value) {} }; class Template { diff --git a/spec/c/array_spec.rb b/spec/c/array_spec.rb new file mode 100644 index 0000000..06ef20c --- /dev/null +++ b/spec/c/array_spec.rb @@ -0,0 +1,28 @@ +require 'spec_helper' + +describe V8::C::Array do + before do + @cxt = V8::C::Context::New() + @cxt.Enter() + end + after do + @cxt.Exit() + end + it "can store and retrieve a value" do + V8::C::HandleScope() do + o = V8::C::Object::New() + a = V8::C::Array::New() + a.Length().should eql 0 + a.Set(0, o) + a.Length().should eql 1 + a.Get(0).Equals(o).should be_true + end + end + + it "can be initialized with a length" do + V8::C::HandleScope() do + a = V8::C::Array::New(5) + a.Length().should eql 5 + end + end +end \ No newline at end of file