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

114 lines
2.5 KiB
C
Raw Normal View History

#ifndef __convert_v8_h__
#define __convert_v8_h__
#include <v8.h>
#include <stdint.h>
#include <stdio.h>
#include <string>
template<class T, class R> class V8HandleSource {
T dest;
public:
V8HandleSource() {}
~V8HandleSource() {}
R operator() (v8::Handle<v8::Value>& value) {
2009-12-18 02:48:06 -05:00
if (value.IsEmpty()) {
return dest.pushNull();
}
2009-10-16 16:27:39 -04:00
if (value->IsUndefined()) {
2009-12-13 11:07:34 -05:00
return dest.pushNull();
}
2009-10-16 16:27:39 -04:00
if(value->IsNull()) {
2009-12-13 11:07:34 -05:00
return dest.pushNull();
2009-10-16 16:27:39 -04:00
}
if(value->IsTrue()) {
2009-12-13 11:07:34 -05:00
return dest.pushBool(true);
}
if(value->IsFalse()) {
2009-12-13 11:07:34 -05:00
return dest.pushBool(false);
}
if(value->IsString()) {
v8::Local<v8::String> str = value->ToString();
char buffer[1024];
int strlen = str->Length();
std::string output(strlen, 0);
for (int total = 0; total < strlen;) {
int written = str->WriteAscii(buffer, total, 1024);
output.replace(total, written, buffer);
total += written;
}
2009-12-13 11:07:34 -05:00
return dest.pushString(output);
}
if(value->IsInt32()) {
2009-12-13 11:07:34 -05:00
return dest.pushInt(value->Int32Value());
}
if(value->IsNumber()) {
2009-12-13 11:07:34 -05:00
return dest.pushDouble(value->NumberValue());
}
if (value->IsObject()) {
2009-10-23 00:27:41 -04:00
v8::Local<v8::Object> object(v8::Object::Cast(*value));
2009-12-13 11:07:34 -05:00
return dest.pushObject(object);
}
2009-12-13 11:07:34 -05:00
return dest.pushNull();
}
};
/**
* StringDest is a data type conversion destination that converts
* any argument into a string. It should have all methods listed
* in data_conversion.txt so it can be used as a template argument
* for a conversion source class.
*/
class V8LocalDest {
public:
V8LocalDest();
~V8LocalDest();
2009-12-13 11:07:34 -05:00
v8::Local<v8::Value> pushString(const std::string& value) {
return v8::Local<v8::Value>::New(v8::String::New(value.c_str()));
}
2009-12-13 11:07:34 -05:00
v8::Local<v8::Value> pushInt(int64_t value) {
return v8::Local<v8::Value>::New(v8::Integer::New(value));
}
2009-12-13 11:07:34 -05:00
v8::Local<v8::Value> pushDouble(double value) {
return v8::Local<v8::Value>::New(v8::Number::New(value));
}
2009-12-13 11:07:34 -05:00
v8::Local<v8::Value> pushBool(bool value) {
return v8::Local<v8::Value>::New(v8::Boolean::New(value));
}
2009-12-13 11:07:34 -05:00
v8::Local<v8::Value> pushNull() {
return v8::Local<v8::Value>::New(v8::Null());
}
2009-12-13 11:07:34 -05:00
v8::Local<v8::Value> pushUndefined() {
return v8::Local<v8::Value>::New(v8::Undefined());
}
// v8:Local<v8:Value> pushFunction(Function) {
//
// }
};
#endif