コード例 #1
0
IOBasicTypes::LongBufferSizeType ObjectByteReaderWithPosition::Read(IOBasicTypes::Byte* inBuffer,IOBasicTypes::LongBufferSizeType inBufferSize)
{
	CREATE_ISOLATE_CONTEXT;
	CREATE_ESCAPABLE_SCOPE;

	Handle<Value> value = OBJECT_FROM_PERSISTENT(mObject)->Get(NEW_STRING("read"));
    if(value->IsUndefined())
        return 0;
    Handle<Function> func = Handle<Function>::Cast(value);
    
    Handle<Value> args[1];
    args[0] = NEW_NUMBER(inBufferSize);
    
	Handle<Value> result = func->Call(OBJECT_FROM_PERSISTENT(mObject), 1, args);
    
    if(!result->IsArray())
        return 0;
    
    IOBasicTypes::LongBufferSizeType bufferLength = result->ToObject()->Get(NEW_STRING("length"))->ToObject()->Uint32Value();
    for(IOBasicTypes::LongBufferSizeType i=0;i < bufferLength;++i)
        inBuffer[i] = (IOBasicTypes::Byte)(result->ToObject()->Get((uint32_t)i)->ToNumber()->Uint32Value());
    
    return bufferLength;
    
}
コード例 #2
0
ファイル: engine_v8.cpp プロジェクト: IlyaM/mongo
    int V8Scope::type( const char *field ){
        V8_SIMPLE_HEADER
        Handle<Value> v = get( field );
        if ( v->IsNull() )
            return jstNULL;
        if ( v->IsUndefined() )
            return Undefined;
        if ( v->IsString() )
            return String;
        if ( v->IsFunction() )
            return Code;
        if ( v->IsArray() )
            return Array;
        if ( v->IsBoolean() )
            return Bool;
        if ( v->IsInt32() )
            return NumberInt;
        if ( v->IsNumber() )
            return NumberDouble;
        if ( v->IsExternal() ){
            uassert( 10230 ,  "can't handle external yet" , 0 );
            return -1;
        }
        if ( v->IsDate() )
            return Date;
        if ( v->IsObject() )
            return Object;

        throw UserException( 12509, (string)"don't know what this is: " + field );
    }
コード例 #3
0
ファイル: AudioEngine.cpp プロジェクト: MrZunz/AVA-Home
/*! Queues up an array to be sent to the sound card */
void Audio::AudioEngine::queueOutputBuffer( Handle<Array> result ) {
	// Reset our record of the number of cached output samples
	m_uNumCachedOutputSamples[m_uCurrentWriteBuffer] = 0;

	if( m_bInterleaved ) {
		for( int iSample=0; iSample<m_uSamplesPerBuffer*m_uOutputChannels; ++iSample )
			setSample( iSample, result->Get(iSample) );

		m_uNumCachedOutputSamples[m_uCurrentWriteBuffer] = result->Length()/m_uOutputChannels;

	} else {
		// Validate the structure of the output buffer array
		if( !result->Get(0)->IsArray() ) {
			NanThrowTypeError("Output buffer not properly setup, 0th channel is not an array");
			return;
		}

		Handle<Array> item;

		for( int iChannel=0; iChannel<m_uOutputChannels; ++iChannel ) {
			for( int iSample=0; iSample<m_uSamplesPerBuffer; ++iSample ) {

				item = Handle<Array>::Cast( result->Get(iChannel) );
				if( item->IsArray() ) {
					if( item->Length() > m_uNumCachedOutputSamples[m_uCurrentWriteBuffer] )
						m_uNumCachedOutputSamples[m_uCurrentWriteBuffer] = item->Length();

					setSample( iSample, item->Get(iSample) );
				}
			} // end for each sample
		} // end for each channel
	}
	m_uCurrentWriteBuffer = (m_uCurrentWriteBuffer + 1)%m_uNumBuffers;
} // end AudioEngine::queueOutputBuffer()
コード例 #4
0
ファイル: Conv.cpp プロジェクト: Armen138/anode
int Conv::GetNaturalType(Handle<Object> val) {
  if(val.IsEmpty()) return TYPE_INVALID;
  if(val->IsDate()) return TYPE_DATE;
  if(val->IsFunction()) return TYPE_FUNCTION;
  if(val->IsArray()) return TYPE_ARRAY;
  if(val->IsObject()) return TYPE_OBJECT;
  return TYPE_INVALID;
}
コード例 #5
0
ファイル: serialize.cpp プロジェクト: dkarpman/node-protobuf
int SerializePart(google::protobuf::Message *message, Handle<Object> subj) {
  Nan::HandleScope scope;
  // get a reflection
  const Reflection *r = message->GetReflection();
  const Descriptor *d = message->GetDescriptor();

  // build a list of required properties
  vector<string> required;
  for (int i = 0; i < d->field_count(); i++) {
    const FieldDescriptor *field = d->field(i);
    if (field->is_required())
      required.push_back(field->name());
  }

  // build a reflection
  // get properties of passed object
  Handle<Array> properties = subj->GetPropertyNames();
  uint32_t len = properties->Length();

  // check that all required properties are present
  for (uint32_t i = 0; i < required.size(); i++) {
    Handle<String> key = Nan::New<String>(required.at(i).c_str()).ToLocalChecked();
    if (!subj->Has(key))
      return -1;
  }

  for (uint32_t i = 0; i < len; i++) {
    Handle<Value> property = properties->Get(i);
    Handle<String> property_s = property->ToString();

    if (*property_s == NULL)
      continue;

    String::Utf8Value temp(property);
    std::string propertyName = std::string(*temp);

    const FieldDescriptor *field = d->FindFieldByName(propertyName);
    if (field == NULL) continue;

    Handle<Value> val = subj->Get(property);

    if (field->is_repeated()) {
      if (!val->IsArray())
        continue;

      Handle<Array> array = val.As<Array>();
      int len = array->Length();

      for (int i = 0; i < len; i++)
        SerializeField(message, r, field, array->Get(i));

    } else {
      SerializeField(message, r, field, val);
    }
  }

  return 0;
}
コード例 #6
0
QByteArray TiObject::getByteArrayFromValue(Handle<Value> value)
{
	if (value->IsArray()) {
		Handle<Array> array = Handle<Array>::Cast(value);
		int length = array->Length();
		QByteArray result = QByteArray(length, 0);
		char *data = result.data();
		for (int index = 0; index < length; ++index) {
			data[index] = Handle<Number>::Cast(array->Get(index))->Value();
		}
		return result;
	}
	return QByteArray();
}
コード例 #7
0
ファイル: ModuleManager.cpp プロジェクト: Floby/Purple
static vector<string> get_paths(Handle<Function> require) {
    HandleScope hs;
    Handle<Object> paths = Handle<Object>::Cast(require->Get(String::New("paths")));
    if(!paths->IsArray()) return vector<string>();
    vector<string> res;
    unsigned int length = paths->Get(String::New("length"))->Uint32Value();
    cerr << "paths.length = " << length << endl;
    for(unsigned int i=0; i<length ; ++i) {
	String::Utf8Value v(paths->Get(i));
	cerr << "found " << *v << " in paths[" << i << "]\n";
	res.push_back(string(*v));
    }
    return res;
}
コード例 #8
0
ファイル: JSEngine.cpp プロジェクト: Spacefish/susi
Susi::Util::Any Susi::JS::Engine::convertFromJS(Handle<Value> jsVal){
	if(jsVal->IsArray()){
		Susi::Util::Any::Array result;
		auto obj = jsVal->ToObject();
		const Local<Array> props = obj->GetPropertyNames();
		const uint32_t length = props->Length();
		for (uint32_t i=0 ; i<length ; ++i){
			const Local<Value> key = props->Get(i);
			const Local<Value> value = obj->Get(key);
			result.push_back(Susi::JS::Engine::convertFromJS(value));
		}
		return result;
	}
	if(jsVal->IsObject()){
		Susi::Util::Any result = Susi::Util::Any::Object{};
		auto obj = jsVal->ToObject();
		const Local<Array> props = obj->GetPropertyNames();
		const uint32_t length = props->Length();
		for (uint32_t i=0 ; i<length ; ++i){
			const Local<Value> key = props->Get(i);
			const Local<Value> value = obj->Get(key);
			String::Utf8Value keyStr(key);
			result[std::string(*keyStr)] = Susi::JS::Engine::convertFromJS(value);
		}
		return result;
	}
	if(jsVal->IsString()){
		String::Utf8Value val(jsVal);
		Susi::Util::Any result{std::string(*val)};
		return result;
	}
	if(jsVal->IsNumber()){
		Susi::Util::Any result{jsVal->ToNumber()->Value()};
		return result;
	}
	if(jsVal->IsBoolean()){
		Susi::Util::Any result{jsVal->ToBoolean()->Value()};
		return result;
	}
	if(jsVal->IsNativeError()){
		String::Utf8Value val(jsVal);
		Susi::Util::Any result{std::string(*val)};
		return result;
	}
	if(jsVal->IsUndefined()){
		Susi::Util::Any result;
		return result;
	}
	return Susi::Util::Any{"type not known"};
}
コード例 #9
0
ファイル: node.cpp プロジェクト: ngocdaothanh/jsg
// Returns number of bytes written.
ssize_t DecodeWrite(char *buf,
                    size_t buflen,
                    Handle<Value> val,
                    enum encoding encoding) {
  HandleScope scope;

  // XXX
  // A lot of improvement can be made here. See:
  // http://code.google.com/p/v8/issues/detail?id=270
  // http://groups.google.com/group/v8-dev/browse_thread/thread/dba28a81d9215291/ece2b50a3b4022c
  // http://groups.google.com/group/v8-users/browse_thread/thread/1f83b0ba1f0a611

  if (val->IsArray()) {
    fprintf(stderr, "'raw' encoding (array of integers) has been removed. "
                    "Use 'binary'.\n");
    assert(0);
    return -1;
  }

  Local<String> str = val->ToString();

  if (encoding == UTF8) {
    str->WriteUtf8(buf, buflen, NULL, String::HINT_MANY_WRITES_EXPECTED);
    return buflen;
  }

  if (encoding == ASCII) {
    str->WriteAscii(buf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);
    return buflen;
  }

  // THIS IS AWFUL!!! FIXME

  assert(encoding == BINARY);

  uint16_t * twobytebuf = new uint16_t[buflen];

  str->Write(twobytebuf, 0, buflen, String::HINT_MANY_WRITES_EXPECTED);

  for (size_t i = 0; i < buflen; i++) {
    unsigned char *b = reinterpret_cast<unsigned char*>(&twobytebuf[i]);
    buf[i] = b[0];
  }

  delete [] twobytebuf;

  return buflen;
}
コード例 #10
0
ファイル: converters.cpp プロジェクト: brainshave/v8cl
  void NullTerminatedList (const Wrapper* wrapper, Handle<Value> value, vector<void*>& natives) {
    if (!value->IsArray()) {
      natives.push_back(NULL);
      return;
    }
    Handle<Array> array = Handle<Array>::Cast<Value>(value);
    const size_t size = array->Length() + 1;
    intptr_t *nativeArray = (intptr_t*) malloc(sizeof(intptr_t) * size);

    for (size_t i = 0; i < size - 1; ++i) {
      nativeArray[i] = array->Get(i)->IntegerValue();
    }
    nativeArray[size - 1] = 0;

    natives.push_back(nativeArray);
  }
コード例 #11
0
ファイル: blpapijs.cpp プロジェクト: ZJONSSON/node-blpapi
void
Session::formOptions(std::string* str, Handle<Value> value)
{
    // Use the HandleScope of the calling function for speed.

    if (value->IsUndefined() || value->IsNull())
        return;

    assert(value->IsObject());

    std::stringstream ss;

    if (value->IsArray()) {
        // Format each array value into the options string "V[&V]"
        Local<Object> object = value->ToObject();
        for (std::size_t i = 0; i < Array::Cast(*object)->Length(); ++i) {
            Local<String> key = object->Get(i)->ToString();
            String::Utf8Value valv(key);
            if (valv.length()) {
                if (i > 0)
                    ss << "&";
                ss << *valv;
            }
        }
    } else {
        // Format each KV pair into the options string "K=V[&K=V]"
        Local<Object> object = value->ToObject();
        Local<Array> keys = object->GetPropertyNames();
        for (std::size_t i = 0; i < keys->Length(); ++i) {
            Local<String> key = keys->Get(i)->ToString();
            String::Utf8Value keyv(key);
            if (keyv.length()) {
                if (i > 0)
                    ss << "&";
                ss << *keyv << "=";
            }

            Local<String> val = object->Get(key)->ToString();
            String::Utf8Value valv(val);
            if (valv.length())
                ss << *valv;
        }
    }

    *str = ss.str();
}
コード例 #12
0
ファイル: geojsonreader.cpp プロジェクト: kashif/node-geos
Handle<Array> GeoJSONReader::getGeomsArray(Handle<Object> geojson) {
    Isolate* isolate = Isolate::GetCurrent();

    Handle<String> geomsKey = String::NewFromUtf8(isolate, "geometries");
    if (!geojson->HasOwnProperty(geomsKey))
        throw "Property \"geometries\" is missing";


    Handle<Value> geoms = geojson->Get(geomsKey);
    if (
        !geoms->IsArray()
    )
        throw "Property \"geometries\" must be an instance of Array";


    return Handle<Array>::Cast(geoms);
}
コード例 #13
0
ファイル: geojsonreader.cpp プロジェクト: kashif/node-geos
Handle<Value> GeoJSONReader::getCoordsArray(Handle<Object> geojson) {
    Isolate* isolate = Isolate::GetCurrent();

    Handle<String> coordsKey = String::NewFromUtf8(isolate, "coordinates");
    if (!geojson->HasOwnProperty(coordsKey))
        throw "Property \"coordinates\" is missing";


    Handle<Value> coords = geojson->Get(coordsKey);
    if (
        !coords->IsArray()
        && !coords->IsNull()
        && !coords->IsUndefined()
    )
        throw "Property \"coordinates\" must be an instance of Array or null";


    return coords;
}
コード例 #14
0
ファイル: converters.cpp プロジェクト: brainshave/v8cl
  void Many (const Wrapper* wrapper, Handle<Value> value, vector<void*>& natives) {
    if (!value->IsArray()) {
      natives.push_back(NULL);
      // set size = 0;
      PushBackWrapped<size_t>(natives, 0);
      return;
    }

    Handle<Array> array = Handle<Array>::Cast<Value>(value);
    const size_t size = array->Length();
    T *nativeArray = (T*) malloc(sizeof(T) * size);

    for (size_t i = 0; i < size; ++i) {
      nativeArray[i] = Get<T>(array->Get(i));
    }

    natives.push_back(nativeArray);
    PushBackWrapped(natives, size);
  }
コード例 #15
0
int NativeWindowObject::setOrientationModes(TiObject* obj) {
    Handle<Value> val = obj->getValue();
    if (!val->IsArray()) {
        return NATIVE_ERROR_INVALID_ARG;
    }

    // Convert the array of modes into a bitwise flags value.
    Handle<Array> modes = Handle<Array>::Cast(val);
    uint32_t modeCount = modes->Length();
    int flags = 0;
    for (uint32_t i = 0; i < modeCount; i++) {
        int32_t flag = modes->Get(i)->Int32Value();
        flags |= Orientation::toSceneMode(static_cast<Orientation::Type>(flag));
    }

    scene_.setOrientationModes(flags);

    return NATIVE_ERROR_OK;
}
コード例 #16
0
ファイル: geojsonreader.cpp プロジェクト: kashif/node-geos
geos::geom::Coordinate GeoJSONReader::getCoordinate(Handle<Value> value, bool acceptArrayOnly) {

    bool isArray = value->IsArray();

    if (acceptArrayOnly) {
        if (!isArray)
            throw "A coordinate must be an instance of Array";


    }
    else {
        if (
            !isArray
            && !value->IsNull()
            && !value->IsUndefined()
        )
            throw "A coordinate must be an instance of Array or null";


        if (!isArray)
            return geos::geom::Coordinate::getNull();
    }


    Handle<Array> array = Handle<Array>::Cast(value);
    uint32_t length = array->Length();
    if (length < 2)
        throw "A coordinate's length must be >= 2";


    geos::geom::Coordinate coord;

    coord.x = valueToDouble(array->Get(0));
    coord.y = valueToDouble(array->Get(1));
    if (length > 2) {
        coord.z = valueToDouble(array->Get(2));
    }
    precisionModel->makePrecise(&coord);

    return coord;
}
コード例 #17
0
ファイル: GNContext.cpp プロジェクト: gmadkat/getdns-node
static void setUpstreams(getdns_context* context, Handle<Value> opt) {
    if (opt->IsArray()) {
        getdns_list* upstreams = getdns_list_create();
        Handle<Array> values = Handle<Array>::Cast(opt);
        for (uint32_t i = 0; i < values->Length(); ++i) {
            Local<Value> ipOrTuple = values->Get(i);
            getdns_dict* ipDict = NULL;
            if (ipOrTuple->IsArray()) {
                // two tuple - first is IP, 2nd is port
                Handle<Array> tuple = Handle<Array>::Cast(ipOrTuple);
                if (tuple->Length() > 0) {
                    String::AsciiValue asciiStr(tuple->Get(0)->ToString());
                    ipDict = getdns_util_create_ip(*asciiStr);
                    if (ipDict && tuple->Length() > 1 &&
                        tuple->Get(1)->IsNumber()) {
                        // port
                        uint32_t port = tuple->Get(1)->Uint32Value();
                        getdns_dict_set_int(ipDict, "port", port);
                    }
                }
            } else {
                String::AsciiValue asciiStr(ipOrTuple->ToString());
                ipDict = getdns_util_create_ip(*asciiStr);
            }
            if (ipDict) {
                size_t len = 0;
                getdns_list_get_length(upstreams, &len);
                getdns_list_set_dict(upstreams, len, ipDict);
                getdns_dict_destroy(ipDict);
            } else {
                Local<String> msg = String::Concat(String::New("Upstream value is invalid: "), ipOrTuple->ToString());
                ThrowException(Exception::TypeError(msg));
            }
        }
        getdns_return_t r = getdns_context_set_upstream_recursive_servers(context, upstreams);
        getdns_list_destroy(upstreams);
        if (r != GETDNS_RETURN_GOOD) {
            ThrowException(Exception::TypeError(String::New("Failed to set upstreams.")));
        }
    }
}
コード例 #18
0
ファイル: blpapijs.cpp プロジェクト: ZJONSSON/node-blpapi
void
Session::formFields(std::string* str, Handle<Object> object)
{
    // Use the HandleScope of the calling function for speed.

    assert(object->IsArray());

    std::stringstream ss;

    // Format each array value into the options string "V[&V]"
    for (std::size_t i = 0; i < Array::Cast(*object)->Length(); ++i) {
        Local<String> s = object->Get(i)->ToString();
        String::Utf8Value v(s);
        if (v.length()) {
            if (i > 0)
                ss << ",";
            ss << *v;
        }
    }

    *str = ss.str();
}
コード例 #19
0
ファイル: rr.cpp プロジェクト: Cythnk/territory_mapper
VALUE rr_v82rb(Handle<Value> value) {
  if (value.IsEmpty()) {
    return rr_v8_value_empty();
  }
  if (value->IsUndefined() || value->IsNull()) {
    return Qnil;
  }
  if (value->IsExternal()) {
    return rr_reflect_v8_external(value);
  }
  if (value->IsUint32()) {
    return UINT2NUM(value->Uint32Value());
  }
  if (value->IsInt32()) {
    return INT2FIX(value->Int32Value());
  }
  if (value->IsBoolean()) {
    return value->BooleanValue() ? Qtrue : Qfalse;
  }
  if (value->IsNumber()) {
    return rb_float_new(value->NumberValue());
  }  
  if (value->IsString()) {
    return rr_reflect_v8_string(value);
  }
  if (value->IsFunction()) {
    return rr_reflect_v8_function(value);
  }
  if (value->IsArray()) {
    return rr_reflect_v8_array(value);
  }
  if (value->IsDate()) {
    return rr_reflect_v8_date(value);
  }
  if (value->IsObject()) {
    return rr_reflect_v8_object(value);
  }
  return rr_wrap_v8_value(value);  
}
コード例 #20
0
ファイル: ObjectByteReader.cpp プロジェクト: abyr/HummusJS
IOBasicTypes::LongBufferSizeType ObjectByteReader::Read(IOBasicTypes::Byte* inBuffer,IOBasicTypes::LongBufferSizeType inBufferSize)
{
    HandleScope handle;
    
    Handle<Value> value = mObject->Get(String::New("read"));
    if(value->IsUndefined())
        return 0;
    Handle<Function> func = Handle<Function>::Cast(value);
    
    Handle<Value> args[1];
    args[0] = Number::New(inBufferSize);
    
    Handle<Value> result = func->Call(mObject, 1, args);
    
    if(!result->IsArray())
        return 0;
    
    IOBasicTypes::LongBufferSizeType bufferLength = result->ToObject()->Get(v8::String::New("length"))->ToObject()->Uint32Value();
    for(IOBasicTypes::LongBufferSizeType i=0;i < bufferLength;++i)
        inBuffer[i] = (IOBasicTypes::Byte)(value->ToObject()->Get((uint32_t)i)->ToNumber()->Uint32Value());
    
    return bufferLength;
}
コード例 #21
0
void SerializeField(google::protobuf::Message *message, const Reflection *r, const FieldDescriptor *field, Handle<Value> val) {
	const EnumValueDescriptor *enumValue = NULL;
	bool repeated = field->is_repeated();

	if (*val != NULL) {
		if (field->is_optional() && (val->IsNull() || val->IsUndefined()))
			return;
		
		switch (field->cpp_type()) {
			case FieldDescriptor::CPPTYPE_INT32: {
				if (repeated)
					r->AddInt32(message, field, val->Int32Value());
				else
					r->SetInt32(message, field, val->Int32Value());
				break;
			}
			case FieldDescriptor::CPPTYPE_INT64:
				if (repeated)
					if (preserve_int64 && val->IsArray()) {
						Local<Object> n64_array = val->ToObject();
						uint64 n64;
						uint32 hi = n64_array->Get(0)->Uint32Value(), lo = n64_array->Get(1)->Uint32Value();
						n64 = ((uint64)hi << 32) + (uint64)lo;
						r->AddInt64(message, field, n64);
					} else
						r->AddInt64(message, field, val->NumberValue());
				else
					if (preserve_int64 && val->IsArray()) {
						Local<Object> n64_array = val->ToObject();
						uint64 n64;
						uint32 hi = n64_array->Get(0)->Uint32Value(), lo = n64_array->Get(1)->Uint32Value();
						n64 = ((uint64)hi << 32) + (uint64)lo;
						r->SetInt64(message, field, n64);
					} else
						r->SetInt64(message, field, val->NumberValue());
				break;
			case FieldDescriptor::CPPTYPE_UINT32:
				if (repeated)
					r->AddUInt32(message, field, val->Uint32Value());
				else
					r->SetUInt32(message, field, val->Uint32Value());
				break;
			case FieldDescriptor::CPPTYPE_UINT64:
				if (repeated)
					if (preserve_int64 && val->IsArray()) {
						Local<Object> n64_array = val->ToObject();
						uint64 n64;
						uint32 hi = n64_array->Get(0)->Uint32Value(), lo = n64_array->Get(1)->Uint32Value();
						n64 = ((uint64)hi << 32) + (uint64)lo;
						r->AddUInt64(message, field, n64);
					} else
						r->AddUInt64(message, field, val->NumberValue());
				else
					if (preserve_int64 && val->IsArray()) {
						Local<Object> n64_array = val->ToObject();
						uint64 n64;
						uint32 hi = n64_array->Get(0)->Uint32Value(), lo = n64_array->Get(1)->Uint32Value();
						n64 = ((uint64)hi << 32) + (uint64)lo;
						r->SetUInt64(message, field, n64);
					} else
						r->SetUInt64(message, field, val->NumberValue());
				break;
			case FieldDescriptor::CPPTYPE_DOUBLE:
				if (repeated)
					r->AddDouble(message, field, val->NumberValue());
				else
					r->SetDouble(message, field, val->NumberValue());
				break;
			case FieldDescriptor::CPPTYPE_FLOAT:
				if (repeated)
					r->AddFloat(message, field, val->NumberValue());
				else
					r->SetFloat(message, field, val->NumberValue());
				break;
			case FieldDescriptor::CPPTYPE_BOOL:
				if (repeated)
					r->AddBool(message, field, val->BooleanValue());
				else
					r->SetBool(message, field, val->BooleanValue());
				break;
			case FieldDescriptor::CPPTYPE_ENUM:
				// TODO: possible memory leak?
				enumValue =
					val->IsNumber() ?
						field->enum_type()->FindValueByNumber(val->Int32Value()) :
						field->enum_type()->FindValueByName(*NanAsciiString(val));

				if (enumValue != NULL) {
					if (repeated)
						r->AddEnum(message, field, enumValue);
					else
						r->SetEnum(message, field, enumValue);
				}
				break;
			case FieldDescriptor::CPPTYPE_MESSAGE:
				if (val->IsObject()) {
					if (repeated)
						SerializePart(r->AddMessage(message, field), val.As<Object>());
					else
						SerializePart(r->MutableMessage(message, field), val.As<Object>());
				}
				break;
			case FieldDescriptor::CPPTYPE_STRING:
				if (Buffer::HasInstance(val)) {
					Local<Object> buf = val->ToObject();
					if (repeated)
						r->AddString(message, field, std::string(Buffer::Data(buf), Buffer::Length(buf)));
					else
						r->SetString(message, field, std::string(Buffer::Data(buf), Buffer::Length(buf)));
					break;
				}

				if (val->IsObject()) {
					Local<Object> val2 = val->ToObject();
					Local<Value> converter = val2->Get(NanNew<String>("toProtobuf"));
					if (converter->IsFunction()) {
						Local<Function> toProtobuf = Local<Function>::Cast(converter);
						Local<Value> ret = toProtobuf->Call(val2,0,NULL);
						if (Buffer::HasInstance(ret)) {
							Local<Object> buf = ret->ToObject();
							if (repeated)
								r->AddString(message, field, std::string(Buffer::Data(buf), Buffer::Length(buf)));
							else
								r->SetString(message, field, std::string(Buffer::Data(buf), Buffer::Length(buf)));
							break;
						}
					}
				}
				String::Utf8Value temp(val->ToString());
				std::string value = std::string(*temp);
				if (repeated)
					r->AddString(message, field, value);
				else
					r->SetString(message, field, value);
				break;
		}
	}
}
コード例 #22
0
ファイル: v8_helper.cpp プロジェクト: edumunoz/MiXture
extern "C" bool isArray(Handle<Value> arr) {
    return arr->IsArray();
}
コード例 #23
0
int main(int argc, const char * argv[])
{
    using namespace v8::bridge;
    
    /* Create a scripting engine */
    ScriptingEngine *engine = new ScriptingEngine();
    
    /* Execute simple script which contains some variable declarations in the global scope */
    std::stringstream io;
    io << "var intVar          = 10;" << std::endl;
    io << "var numberVar       = 10.5;" << std::endl;
    io << "var stringVar       = 'Hello, World!';" << std::endl;
    io << "var boolVar         = false;" << std::endl;
    io << "var nullVar         = null;" << std::endl;
    io << "var undefinedVar    = undefined;" << std::endl;
    io << "var arrayVar        = [1, 2, 3];" << std::endl;
    io << "var objectVar       = { 'foo': 1, 'bar': 2 };" << std::endl;
    io << "var callbackVar     = function() { };" << std::endl;
    
    engine->execute(io.str());
    
    /*
     * Access each variable. Since the variables was defined
     * in the global scope, we can easly access them using
     * ScriptingEngine::getFromGlobalScope and ScriptingEngine::getValueFromGlobalScope<TType>.
     *
     * Note that you should may use getFromGlobalScope<TType> only when you're sure that the given variable
     * is in your desired type, otherwsie an runtime_error will raise.
     */
    
    /* Lets start by retriving variables using the Conversion API: */
    
    // Int:
    int intVar = engine->getValueFromGlobalScope<int>("intVar");
    std::cout << "intVal: " << intVar << std::endl;
    
    // Number (double/float):
    double numberVar = engine->getValueFromGlobalScope<double>("numberVar");
    std::cout << "numberVar: " << numberVar << std::endl;
    
    // String:
    std::string stringVar = engine->getValueFromGlobalScope<std::string>("stringVar");
    std::cout << "stringVar: " << stringVar << std::endl;
    
    // Bool:
    bool boolVar = engine->getValueFromGlobalScope<bool>("boolVar");
    std::cout << "boolVar: " << boolVar << std::endl;
    
    /* To retrive null and undefined, we must retrive the Handle<Value> */
    
    // Note: since we're going to interact with raw handles,
    // and we're in main, we must create a new handle scope.
    //
    // Note 2: We don't need to open a scope when interacting with raw values
    // in functions and methods that was exposed to JS since v8bridge
    // opens one for us before triggering our function.
    HandleScope handle_scope(engine->getActiveIsolationScope());
    
    // Null:
    Handle<Value> nullVar = engine->getFromGlobalScope("nullVar");
    std::cout << "nullVar (is null?): " << (nullVar->IsNull()) << std::endl;
    
    // Undefined:
    Handle<Value> undefinedVar = engine->getFromGlobalScope("undefinedVar");
    std::cout << "undefinedVar (is undefined?): " << (undefinedVar->IsUndefined()) << std::endl;
    
    /*
     * Array:
     * There're two ways to interact with arrays:
     *  1. JS arrays are been converted automaticly to list. So we can use the
     *  conversion API to convert the Handle<Array> to a native list type. The con
     *  of this action is that the array must contain a specific type (e.g. strings only, ints only). 
     *  2. We can receive the array as raw Handle<Array>. To make things simpler
     *  we can avoid the type-verification by requesting from the Conversion API to get Handle<Array>.
     *  this will make sure that we're dealing with an array (and not with string or undefined variable, for instance).
     */
#if 0 // std::list<T> approch:
    std::list<int> arrayVar = engine->getValueFromGlobalScope<std::list<int> >("arrayVar");
    std::cout << "arrayVar (size: " << arrayVar.size() << "): [";
    for (int i = 0; i < arrayVar.size(); i++)
    {
        if (i < arrayVar.size() - 1)
            std::cout << i << ", ";
        else
            std::cout << i;
    }
    std::cout << "]" << std::endl;
#elif 1 // Handle<Array>
    Handle<Array> arrayVar = engine->getHandleFromGlobalScope<Handle<Array> >("arrayVar");
    String::Utf8Value arrayVarStringRep(arrayVar); // We're using v8::String::Utf8Value to evaluate the array contents into a string
    std::cout << "arrayVar (size: " << arrayVar->Length() << "):"
    << "[" << *arrayVarStringRep << "]" << std::endl;
#else // Handle<Value> raw parsing
    Handle<Value> arrayVar = engine->getFromGlobalScope("arrayVar");
    assert(arrayVar->IsArray());
    String::Utf8Value arrayVarStringRep(arrayVar);
    std::cout << "arrayVar (size: " << Handle<Array>::Cast(arrayVar)->Length() << "):"
   
    << "[" << *arrayVarStringRep << "]" << std::endl;
#endif
    
    /* Free */
    delete engine;
    
    /* Done. */
    return 0;
}
コード例 #24
0
ファイル: jsengine.cpp プロジェクト: Daniel15/vroomjs
jsvalue JsEngine::AnyFromV8(Handle<Value> value, Handle<Object> thisArg)
{
    jsvalue v;
    
    // Initialize to a generic error.
    v.type = JSVALUE_TYPE_UNKNOWN_ERROR;
    v.length = 0;
    v.value.str = 0;
    
    if (value->IsNull() || value->IsUndefined()) {
        v.type = JSVALUE_TYPE_NULL;
    }                
    else if (value->IsBoolean()) {
        v.type = JSVALUE_TYPE_BOOLEAN;
        v.value.i32 = value->BooleanValue() ? 1 : 0;
    }
    else if (value->IsInt32()) {
        v.type = JSVALUE_TYPE_INTEGER;
        v.value.i32 = value->Int32Value();            
    }
    else if (value->IsUint32()) {
        v.type = JSVALUE_TYPE_INDEX;
        v.value.i64 = value->Uint32Value();            
    }
    else if (value->IsNumber()) {
        v.type = JSVALUE_TYPE_NUMBER;
        v.value.num = value->NumberValue();
    }
    else if (value->IsString()) {
        v = StringFromV8(value);
    }
    else if (value->IsDate()) {
        v.type = JSVALUE_TYPE_DATE;
        v.value.num = value->NumberValue();
    }
    else if (value->IsArray()) {
        Handle<Array> object = Handle<Array>::Cast(value->ToObject());
        v.length = object->Length();
        jsvalue* array = new jsvalue[v.length];
        if (array != NULL) {
            for(int i = 0; i < v.length; i++) {
                array[i] = AnyFromV8(object->Get(i));
            }
            v.type = JSVALUE_TYPE_ARRAY;
            v.value.arr = array;
        }
    }
    else if (value->IsFunction()) {
		Handle<Function> function = Handle<Function>::Cast(value);
		jsvalue* array = new jsvalue[2];
        if (array != NULL) { 
			array[0].value.ptr = new Persistent<Object>(Persistent<Function>::New(function));
			array[0].length = 0;
			array[0].type = JSVALUE_TYPE_WRAPPED;
			if (!thisArg.IsEmpty()) {
				array[1].value.ptr = new Persistent<Object>(Persistent<Object>::New(thisArg));
				array[1].length = 0;
				array[1].type = JSVALUE_TYPE_WRAPPED;
			} else {
				array[1].value.ptr = NULL;
				array[1].length = 0;
				array[1].type = JSVALUE_TYPE_NULL;
			}
	        v.type = JSVALUE_TYPE_FUNCTION;
            v.value.arr = array;
        }
    }
    else if (value->IsObject()) {
        Handle<Object> obj = Handle<Object>::Cast(value);
        if (obj->InternalFieldCount() == 1)
            v = ManagedFromV8(obj);
        else
            v = WrappedFromV8(obj);
    }

    return v;
}