1
0
Fork 0
mirror of https://github.com/rubyjs/therubyracer synced 2023-03-27 23:21:42 -04:00
therubyracer/ruby_data.h

105 lines
2.3 KiB
C
Raw Normal View History

#ifndef __ruby_data_h__
#define __ruby_data_h__
#include <ruby.h>
#include <v8.h>
2009-10-23 00:27:41 -04:00
#include <v8_object.h>
#include <stdio.h>
#include <string>
/**
* A RubyValueSource takes a Destination class and a return
* type as a template argument, it converts a Ruby Value to
* the appropriate intermediate type and feed it to an
* instance Destination type.
*
* The destination type should have a default constructor,
* and provide the methods detailed in data_conversion.txt
* \tparam DEST destination type for the converted data
* \tparam RET is the return type of T's methods
*/
template<class DEST, class RET> class RubyValueSource {
/**
* An instance of the destination class
*/
DEST dest;
public:
RubyValueSource() {}
~RubyValueSource() {}
2009-12-13 11:07:34 -05:00
RET push(VALUE& value) {
switch (TYPE(value)) {
case T_FIXNUM:
2009-12-13 11:07:34 -05:00
return dest.pushInt(FIX2INT(value));
case T_FLOAT:
2009-12-13 11:07:34 -05:00
return dest.pushDouble(NUM2DBL(value));
case T_STRING:
2009-12-13 11:07:34 -05:00
return convertString(value);
case T_NIL:
2009-12-13 11:07:34 -05:00
return dest.pushNull();
case T_TRUE:
2009-12-13 11:07:34 -05:00
return dest.pushBool(true);
case T_FALSE:
2009-12-13 11:07:34 -05:00
return dest.pushBool(false);
// case T_DATA:
// if (rb_is_function(value)) {
// return dest.pushCode(new Code<RubyCaller>)
// }
}
2009-12-13 11:07:34 -05:00
return dest.pushUndefined();
}
private:
2009-12-13 11:07:34 -05:00
RET convertString(VALUE& value) {
std::string stringValue(RSTRING(value)->ptr);
2009-12-13 11:07:34 -05:00
return dest.pushString(stringValue);
}
};
/**
* A RubyDest class receives on of the types defined in
* data_conversion.txt, and converts it to the appropriate
* Ruby VALUE.
*/
class RubyDest {
public:
RubyDest();
~RubyDest();
2009-12-13 11:07:34 -05:00
VALUE pushString(const std::string& value) {
return rb_str_new2(value.c_str());
}
2009-12-13 11:07:34 -05:00
VALUE pushInt(int64_t value) {
return INT2FIX(value);
}
2009-12-13 11:07:34 -05:00
VALUE pushDouble(double value) {
return rb_float_new(value);
}
2009-12-13 11:07:34 -05:00
VALUE pushBool(bool value) {
return value ? Qtrue : Qfalse;
}
2009-12-13 11:07:34 -05:00
VALUE pushNull() {
return Qnil;
}
2009-12-13 11:07:34 -05:00
VALUE pushUndefined() {
return Qnil;
}
2009-12-13 11:07:34 -05:00
VALUE pushObject(v8::Handle<v8::Object>& value) {
v8_object* wrapper = new v8_object(value);
return wrapper->ruby_value;
}
};
#endif