Beispiel #1
0
static VALUE db_execute(int argc, VALUE *argv, VALUE self)
{
	sqlite3 * db = NULL;
	void **ppDB = NULL;		
	sqlite3_stmt *statement = NULL;
	const char* sql = NULL;
	VALUE arRes = rb_ary_new();
    VALUE* colNames = NULL;
	int nRes = 0;
    char * szErrMsg = 0;
    int is_batch = 0;

	if ((argc < 2) || (argc > 3))
		rb_raise(rb_eArgError, "wrong # of arguments(%d for 3)",argc);
	
	Data_Get_Struct(self, void *, ppDB);
	db = (sqlite3 *)rho_db_get_handle(*ppDB);
	sql = RSTRING_PTR(argv[0]);
    is_batch = argv[1] == Qtrue ? 1 : 0;

    RAWTRACE1("db_execute: %s", sql);

    if ( is_batch )
    {
        rho_db_lock(*ppDB);
        nRes = sqlite3_exec(db, sql,  NULL, NULL, &szErrMsg);
        rho_db_unlock(*ppDB);
    }
    else
    {
        rho_db_lock(*ppDB);

        nRes = rho_db_prepare_statement(*ppDB, sql, -1, &statement);
        //nRes = sqlite3_prepare_v2(db, sql, -1, &statement, NULL);
        if ( nRes != SQLITE_OK)
        {
            szErrMsg = (char *)sqlite3_errmsg(db);
            rho_db_unlock(*ppDB);

            rb_raise(rb_eArgError, "could not prepare statement: %d; Message: %s",nRes, (szErrMsg?szErrMsg:""));
        }

        if ( argc > 2 )
        {
            int i = 0;
            VALUE args = argv[2];
            if ( RARRAY_LEN(args) > 0 && TYPE(RARRAY_PTR(args)[0]) == T_ARRAY )
                args = RARRAY_PTR(args)[0];

            for( ; i < RARRAY_LEN(args); i++ )
            {
                VALUE arg = RARRAY_PTR(args)[i];
                if (NIL_P(arg))
                {
                    sqlite3_bind_null(statement, i+1);
                    continue;
                }

                switch( TYPE(arg) )
                {
                case T_STRING:
                    sqlite3_bind_text(statement, i+1, RSTRING_PTR(arg), RSTRING_LEN(arg), SQLITE_TRANSIENT);
                    break;
                case T_FLOAT:
                    sqlite3_bind_double(statement, i+1, NUM2DBL(arg));
                    break;
                case T_FIXNUM:
                case T_BIGNUM:
                    sqlite3_bind_int64(statement, i+1, NUM2LL(arg));
                    break;
                default:
					{
						VALUE strVal = rb_funcall(arg, rb_intern("to_s"), 0);	
	                    sqlite3_bind_text(statement, i+1, RSTRING_PTR(strVal), -1, SQLITE_TRANSIENT);	
					}
					break;
                }
            }
        }

	    while( (nRes=sqlite3_step(statement)) == SQLITE_ROW) {
		    int nCount = sqlite3_data_count(statement);
		    int nCol = 0;
		    VALUE hashRec = rb_hash_new();

            //if ( !colNames )
            //    colNames = getColNames(statement, nCount);

		    for(;nCol<nCount;nCol++){
			    int nColType = sqlite3_column_type(statement,nCol);
			    const char* szColName = sqlite3_column_name(statement,nCol);
			    VALUE colName = rb_str_new2(szColName);
			    VALUE colValue = Qnil;
    			
			    switch(nColType){
				    case SQLITE_NULL:
					    break;
                    case SQLITE_FLOAT:
                    {
                        double dVal = sqlite3_column_double(statement, nCol);
                        colValue = DBL2NUM(dVal);
                        break;
                    }
                    case SQLITE_INTEGER:
                    {
                        sqlite_int64 nVal = sqlite3_column_int64(statement, nCol);
                        colValue = LL2NUM(nVal);
                        break;
                    }
				    default:{
                        sqlite3_value * sqlValue = sqlite3_column_value(statement, nCol);
                        int nLen = sqlite3_value_bytes(sqlValue);
                        const char*  szValue = (const char *)sqlite3_value_text(sqlValue);
					    //char *text = (char *)sqlite3_column_text(statement, nCol);
					    colValue = rb_str_new(szValue, nLen);
					    break;
				    }
			    }
    			
			    rb_hash_aset(hashRec, colName/*colNames[nCol]*/, colValue);
		    }
    		
		    rb_ary_push(arRes, hashRec);
	    }

        rho_db_unlock(*ppDB);
    }

    if ( statement )
        //sqlite3_finalize(statement);
        sqlite3_reset(statement);

    if ( colNames )
        free(colNames);

    if ( nRes != SQLITE_OK && nRes != SQLITE_ROW && nRes != SQLITE_DONE )
    {
        if ( !szErrMsg )
            szErrMsg = (char*)sqlite3_errmsg(db);

        rb_raise(rb_eArgError, "could not execute statement: %d; Message: %s",nRes, (szErrMsg?szErrMsg:""));
    }

	return arRes;
}
Beispiel #2
0
static VALUE
nstruct_add_type(VALUE type, int argc, VALUE *argv, VALUE nst)
{
    VALUE ofs, size;
    ID id;
    int i;
    VALUE name=Qnil;
    size_t *shape=NULL;
    int ndim=0;
    ssize_t stride;
    narray_view_t *nt;
    int j;

    for (i=0; i<argc; i++) {
        switch(TYPE(argv[i])) {
        case T_STRING:
        case T_SYMBOL:
            if (NIL_P(name)) {
                name = argv[i];
                break;
            }
            rb_raise(rb_eArgError,"multiple name in struct definition");
        case T_ARRAY:
            if (shape) {
                rb_raise(rb_eArgError,"multiple shape in struct definition");
            }
            ndim = RARRAY_LEN(argv[i]);
            if (ndim > NA_MAX_DIMENSION) {
                rb_raise(rb_eArgError,"too large number of dimensions");
            }
            if (ndim == 0) {
                rb_raise(rb_eArgError,"array is empty");
            }
            shape = ALLOCA_N(size_t, ndim);
            na_array_to_internal_shape(Qnil, argv[i], shape);
            break;
        }
    }

    id = rb_to_id(name);
    name = ID2SYM(id);
    if (rb_obj_is_kind_of(type,cNArray)) {
        narray_t *na;
        GetNArray(type,na);
        type = CLASS_OF(type);
        ndim = na->ndim;
        shape = na->shape;
    }
    type = rb_narray_view_new(type,ndim,shape);
    GetNArrayView(type,nt);

    nt->stridx = ALLOC_N(stridx_t,ndim);
    stride = na_dtype_elmsz(CLASS_OF(type));
    for (j=ndim; j--; ) {
        SDX_SET_STRIDE(nt->stridx[j], stride);
        stride *= shape[j];
    }

    ofs  = rb_iv_get(nst, "__offset__");
    nt->offset = NUM2SIZE(ofs);

    size = rb_funcall(type, rb_intern("byte_size"), 0);
    rb_iv_set(nst, "__offset__", rb_funcall(ofs,'+',1,size));
    rb_ary_push(rb_iv_get(nst,"__members__"),
                rb_ary_new3(4,name,type,ofs,size));  // <- field definition
    return Qnil;
}
Beispiel #3
0
static VALUE rb_gsl_pow_int(VALUE obj, VALUE xx, VALUE nn)
{
  VALUE x, ary, argv[2];
  size_t i, j, size;
  int n;
  gsl_vector *v = NULL, *vnew = NULL;
  gsl_matrix *m = NULL, *mnew = NULL;
#ifdef HAVE_NARRAY_H
  struct NARRAY *na;
  double *ptr1, *ptr2;
#endif

  if (CLASS_OF(xx) == rb_cRange) xx = rb_gsl_range2ary(xx);
  switch (TYPE(xx)) {
  case T_FIXNUM:
  case T_BIGNUM:
  case T_FLOAT:
    return rb_float_new(gsl_pow_int(NUM2DBL(xx), FIX2INT(nn)));
    break;
  case T_ARRAY:
    CHECK_FIXNUM(nn);
    n = FIX2INT(nn);
    size = RARRAY_LEN(xx);
    ary = rb_ary_new2(size);
    for (i = 0; i < size; i++) {
      x = rb_ary_entry(xx, i);
      Need_Float(x);
      rb_ary_store(ary, i, rb_float_new(gsl_pow_int(RFLOAT_VALUE(x), n)));
    }
    return ary;
    break;
  default:
#ifdef HAVE_NARRAY_H
    if (NA_IsNArray(xx)) {
      CHECK_FIXNUM(nn);
      n = FIX2INT(nn);
      GetNArray(xx, na);
      ptr1 = (double*) na->ptr;
      size = na->total;
      ary = na_make_object(NA_DFLOAT, na->rank, na->shape, CLASS_OF(xx));
      ptr2 = NA_PTR_TYPE(ary, double*);
      for (i = 0; i < size; i++) ptr2[i] = gsl_pow_int(ptr1[i], n);
      return ary;
    }
#endif
    if (VECTOR_P(xx)) {
      CHECK_FIXNUM(nn);
      n = FIX2INT(nn);
      Data_Get_Struct(xx, gsl_vector, v);
      vnew = gsl_vector_alloc(v->size);
      for (i = 0; i < v->size; i++) {
	gsl_vector_set(vnew, i, gsl_pow_int(gsl_vector_get(v, i), n));
      }
      return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, vnew);
    } else if (MATRIX_P(xx)) {
      CHECK_FIXNUM(nn);
      n = FIX2INT(nn);
      Data_Get_Struct(xx, gsl_matrix, m);
      mnew = gsl_matrix_alloc(m->size1, m->size2);
      for (i = 0; i < m->size1; i++) {
	for (j = 0; j < m->size2; j++) {
	  gsl_matrix_set(mnew, i, j, gsl_pow_int(gsl_matrix_get(m, i, j), n));
	}
      }
      return Data_Wrap_Struct(cgsl_matrix, 0, gsl_matrix_free, mnew);
    } else if (COMPLEX_P(xx) || VECTOR_COMPLEX_P(xx) || MATRIX_COMPLEX_P(xx)) {
      argv[0] = xx;
      argv[1] = nn;
      return rb_gsl_complex_pow_real(2, argv, obj);
    } else {
      rb_raise(rb_eTypeError, "wrong argument type %s (Array or Vector or Matrix expected)", rb_class2name(CLASS_OF(xx)));
    }
    break;
  }
  /* never reach here */
  return Qnil;
}
Beispiel #4
0
/*
 * @overload read
 *
 *  
 *
 *  @param [Integer] length number of characters if +self+ is a {CLOB} or a {NCLOB}.
 *    number of bytes if +self+ is a {BLOB} or a {BFILE}.
 *  @return [String or nil] data read. <code>nil</code> means it
 *    met EOF at beginning. It returns an empty string '' as a special exception
 *    when <i>length</i> is <code>nil</code> and the lob is empty.
 *
 * @overload read(length)
 *
 *  Reads <i>length</i> characters for {CLOB} and {NCLOB} or <i>length</i>
 *  bytes for {BLOB} and {BFILE} from the current position.
 *  If <i>length</i> is <code>nil</code>, it reads data until EOF.
 *
 *  @param [Integer] length number of characters if +self+ is a {CLOB} or a {NCLOB}.
 *    number of bytes if +self+ is a {BLOB} or a {BFILE}.
 *  @return [String or nil] data read. <code>nil</code> means it
 *    met EOF at beginning. It returns an empty string '' as a special exception
 *    when <i>length</i> is <code>nil</code> and the lob is empty.
 */
static VALUE oci8_lob_read(int argc, VALUE *argv, VALUE self)
{
    oci8_lob_t *lob = TO_LOB(self);
    oci8_svcctx_t *svcctx = check_svcctx(lob);
    ub8 lob_length;
    ub8 read_len;
    ub8 pos = lob->pos;
    long strbufsiz;
    ub8 byte_amt;
    ub8 char_amt;
    sword rv;
    VALUE size;
    VALUE v = rb_ary_new();
    OCIError *errhp = oci8_errhp;
    ub1 piece = OCI_FIRST_PIECE;

    rb_scan_args(argc, argv, "01", &size);
    lob_length = oci8_lob_get_length(lob);
    if (lob_length == 0 && NIL_P(size)) {
        return rb_usascii_str_new("", 0);
    }
    if (lob_length <= pos) /* EOF */
        return Qnil;
    if (NIL_P(size)) {
        read_len = lob_length - pos;
    } else {
        ub8 sz = NUM2ULL(size);
        read_len = MIN(sz, lob_length - pos);
    }
    if (lob->lobtype == OCI_TEMP_CLOB) {
        byte_amt = 0;
        char_amt = read_len;
        if (oci8_nls_ratio == 1) {
            strbufsiz = MIN(read_len, ULONG_MAX);
        } else {
            strbufsiz = MIN(read_len + read_len / 8, ULONG_MAX);
        }
        if (strbufsiz <= 10) {
            strbufsiz = 10;
        }
    } else {
        byte_amt = read_len;
        char_amt = 0;
        strbufsiz = MIN(read_len, ULONG_MAX);
    }
    if (lob->state == S_BFILE_CLOSE) {
        open_bfile(svcctx, lob, errhp);
    }
    do {
        VALUE strbuf = rb_str_buf_new(strbufsiz);
        char *buf = RSTRING_PTR(strbuf);

        rv = OCILobRead2_nb(svcctx, svcctx->base.hp.svc, errhp, lob->base.hp.lob, &byte_amt, &char_amt, pos + 1, buf, strbufsiz, piece, NULL, NULL, 0, lob->csfrm);
        svcctx->suppress_free_temp_lobs = 0;
        switch (rv) {
        case OCI_SUCCESS:
            break;
        case OCI_NEED_DATA:
            /* prevent OCILobFreeTemporary() from being called.
             * See: https://github.com/kubo/ruby-oci8/issues/20
             */
            svcctx->suppress_free_temp_lobs = 1;
            piece = OCI_NEXT_PIECE;
            break;
        default:
            chker2(rv, &svcctx->base);
        }
        if (byte_amt == 0)
            break;
        if (lob->lobtype == OCI_TEMP_CLOB) {
            pos += char_amt;
        } else {
            pos += byte_amt;
        }
        rb_str_set_len(strbuf, byte_amt);
        rb_ary_push(v, strbuf);
    } while (rv == OCI_NEED_DATA);

    if (pos >= lob_length) {
        lob_close(lob);
        bfile_close(lob);
    }
    lob->pos = pos;
    switch (RARRAY_LEN(v)) {
    case 0:
        return Qnil;
    case 1:
        v = RARRAY_AREF(v, 0);
        break;
    default:
        v = rb_ary_join(v, Qnil);
    }
    OBJ_TAINT(v);
    if (lob->lobtype == OCI_TEMP_CLOB) {
        /* set encoding */
        rb_enc_associate(v, oci8_encoding);
        return rb_str_conv_enc(v, oci8_encoding, rb_default_internal_encoding());
    } else {
        /* ASCII-8BIT */
        return v;
    }
}
Beispiel #5
0
static VALUE mc_get(int argc, VALUE *argv, VALUE self) {
  memcached_st *mc;
  VALUE cas, keys, results, key, result;
  VALUE scalar_key = Qnil;
  memcached_return status;

  Data_Get_Struct(self, memcached_st, mc);
  rb_scan_args(argc, argv, "11", &keys, &cas);
  memcached_behavior_set(mc, MEMCACHED_BEHAVIOR_SUPPORT_CAS, RTEST(cas) ? 1 : 0);

  if (RTEST(cas) && TYPE(keys) != T_ARRAY) {
    scalar_key = keys;
    keys = rb_ary_new4(1, &keys);
  }

  if (TYPE(keys) != T_ARRAY) {
    char*    str;
    size_t   len;
    uint32_t flags;

    key = use_binary(mc) ? keys : escape_key(keys, NULL);
    str = memcached_get(mc, RSTRING_PTR(key), RSTRING_LEN(key), &len, &flags, &status);
    if (str == NULL) return Qnil;

    if (status == MEMCACHED_SUCCESS) {
      result = rb_hash_new();
      rb_hash_aset(result, sym_value, rb_str_new(str, len));
      rb_hash_aset(result, sym_flags, INT2NUM(flags));
      free(str);
      return result;
    } else {
      printf("Memcache read error: %s %u\n", memcached_strerror(mc, status), status);
      return Qnil;
    }
  } else {
    memcached_result_st* mc_result;
    size_t       num_keys, i;
    const char** key_strings;
    size_t*      key_lengths;
    bool         escaped;

    results = rb_hash_new();
    num_keys = RARRAY_LEN(keys);
    if (num_keys == 0) return results;

    key_strings = (const char**) malloc(num_keys * sizeof(char *));
    key_lengths = (size_t *) malloc(num_keys * sizeof(size_t));
    for (i = 0; i < RARRAY_LEN(keys); i++) {
      key = RARRAY_PTR(keys)[i];
      if (!use_binary(mc)) key = escape_key(key, &escaped);

      key_lengths[i] = RSTRING_LEN(key);
      key_strings[i] = RSTRING_PTR(key);
    }

    memcached_mget(mc, key_strings, key_lengths, num_keys);

    while ((mc_result = memcached_fetch_result(mc, NULL, &status))) {
      if (escaped) {
        key = unescape_key(memcached_result_key_value(mc_result), memcached_result_key_length(mc_result));
      } else {
        key = rb_str_new(memcached_result_key_value(mc_result), memcached_result_key_length(mc_result));
      }

      if (status == MEMCACHED_SUCCESS) {
        result = rb_hash_new();
        rb_hash_aset(result, sym_value, rb_str_new(memcached_result_value(mc_result),
                                                   memcached_result_length(mc_result)));
        rb_hash_aset(result, sym_flags, INT2NUM(memcached_result_flags(mc_result)));
        if (RTEST(cas)) rb_hash_aset(result, sym_cas, ULL2NUM(memcached_result_cas(mc_result)));
        memcached_result_free(mc_result);
        rb_hash_aset(results, key, result);
      } else {
        printf("Memcache read error: %s %u\n", memcached_strerror(mc, status), status);
      }
    }
    free(key_strings);
    free(key_lengths);
    if (!NIL_P(scalar_key)) return rb_hash_aref(results, scalar_key);
    return results;
  }
}
Beispiel #6
0
static VALUE
fntype_initialize(int argc, VALUE* argv, VALUE self)
{
    FunctionType *fnInfo;
    ffi_status status;
    VALUE rbReturnType = Qnil, rbParamTypes = Qnil, rbOptions = Qnil;
    VALUE rbEnums = Qnil, rbConvention = Qnil, rbBlocking = Qnil;
#if defined(_WIN32) || defined(__WIN32__)
    VALUE rbConventionStr;
#endif
    int i, nargs;

    nargs = rb_scan_args(argc, argv, "21", &rbReturnType, &rbParamTypes, &rbOptions);
    if (nargs >= 3 && rbOptions != Qnil) {
        rbConvention = rb_hash_aref(rbOptions, ID2SYM(rb_intern("convention")));
        rbEnums = rb_hash_aref(rbOptions, ID2SYM(rb_intern("enums")));
        rbBlocking = rb_hash_aref(rbOptions, ID2SYM(rb_intern("blocking")));
    }

    Check_Type(rbParamTypes, T_ARRAY);

    Data_Get_Struct(self, FunctionType, fnInfo);
    fnInfo->parameterCount = (int) RARRAY_LEN(rbParamTypes);
    fnInfo->parameterTypes = xcalloc(fnInfo->parameterCount, sizeof(*fnInfo->parameterTypes));
    fnInfo->ffiParameterTypes = xcalloc(fnInfo->parameterCount, sizeof(ffi_type *));
    fnInfo->nativeParameterTypes = xcalloc(fnInfo->parameterCount, sizeof(*fnInfo->nativeParameterTypes));
    fnInfo->rbParameterTypes = rb_ary_new2(fnInfo->parameterCount);
    fnInfo->rbEnums = rbEnums;
    fnInfo->blocking = RTEST(rbBlocking);
    fnInfo->hasStruct = false;

    for (i = 0; i < fnInfo->parameterCount; ++i) {
        VALUE entry = rb_ary_entry(rbParamTypes, i);
        VALUE type = rbffi_Type_Lookup(entry);

        if (!RTEST(type)) {
            VALUE typeName = rb_funcall2(entry, rb_intern("inspect"), 0, NULL);
            rb_raise(rb_eTypeError, "Invalid parameter type (%s)", RSTRING_PTR(typeName));
        }

        if (rb_obj_is_kind_of(type, rbffi_FunctionTypeClass)) {
            REALLOC_N(fnInfo->callbackParameters, VALUE, fnInfo->callbackCount + 1);
            fnInfo->callbackParameters[fnInfo->callbackCount++] = type;
        }

        if (rb_obj_is_kind_of(type, rbffi_StructByValueClass)) {
            fnInfo->hasStruct = true;
        }

        rb_ary_push(fnInfo->rbParameterTypes, type);
        Data_Get_Struct(type, Type, fnInfo->parameterTypes[i]);
        fnInfo->ffiParameterTypes[i] = fnInfo->parameterTypes[i]->ffiType;
        fnInfo->nativeParameterTypes[i] = fnInfo->parameterTypes[i]->nativeType;
    }

    fnInfo->rbReturnType = rbffi_Type_Lookup(rbReturnType);
    if (!RTEST(fnInfo->rbReturnType)) {
        VALUE typeName = rb_funcall2(rbReturnType, rb_intern("inspect"), 0, NULL);
        rb_raise(rb_eTypeError, "Invalid return type (%s)", RSTRING_PTR(typeName));
    }
    
    if (rb_obj_is_kind_of(fnInfo->rbReturnType, rbffi_StructByValueClass)) {
        fnInfo->hasStruct = true;
    }

    Data_Get_Struct(fnInfo->rbReturnType, Type, fnInfo->returnType);
    fnInfo->ffiReturnType = fnInfo->returnType->ffiType;


#if defined(_WIN32) || defined(__WIN32__)
    rbConventionStr = (rbConvention != Qnil) ? rb_funcall2(rbConvention, rb_intern("to_s"), 0, NULL) : Qnil;
    fnInfo->abi = (rbConventionStr != Qnil && strcmp(StringValueCStr(rbConventionStr), "stdcall") == 0)
            ? FFI_STDCALL : FFI_DEFAULT_ABI;
#else
    fnInfo->abi = FFI_DEFAULT_ABI;
#endif

    status = ffi_prep_cif(&fnInfo->ffi_cif, fnInfo->abi, fnInfo->parameterCount,
            fnInfo->ffiReturnType, fnInfo->ffiParameterTypes);
    switch (status) {
        case FFI_BAD_ABI:
            rb_raise(rb_eArgError, "Invalid ABI specified");
        case FFI_BAD_TYPEDEF:
            rb_raise(rb_eArgError, "Invalid argument type specified");
        case FFI_OK:
            break;
        default:
            rb_raise(rb_eArgError, "Unknown FFI error");
    }

    fnInfo->invoke = rbffi_GetInvoker(fnInfo);

    return self;
}
Beispiel #7
0
VALUE
rb_struct_initialize(VALUE self, VALUE values)
{
    return rb_struct_initialize_m(RARRAY_LEN(values), RARRAY_PTR(values), self);
}
Beispiel #8
0
static int write_element(VALUE key, VALUE value, VALUE extra, int allow_id) {
    buffer_t buffer = (buffer_t)NUM2LL(rb_ary_entry(extra, 0));
    VALUE check_keys = rb_ary_entry(extra, 1);

    if (TYPE(key) == T_SYMBOL) {
        // TODO better way to do this... ?
        key = rb_str_new2(rb_id2name(SYM2ID(key)));
    }

    if (TYPE(key) != T_STRING) {
        buffer_free(buffer);
        rb_raise(rb_eTypeError, "keys must be strings or symbols");
    }

    if (allow_id == 0 && strcmp("_id", RSTRING_PTR(key)) == 0) {
        return ST_CONTINUE;
    }

    if (check_keys == Qtrue) {
        int i;
        if (RSTRING_LEN(key) > 0 && RSTRING_PTR(key)[0] == '$') {
            buffer_free(buffer);
            rb_raise(InvalidKeyName, "key must not start with '$'");
        }
        for (i = 0; i < RSTRING_LEN(key); i++) {
            if (RSTRING_PTR(key)[i] == '.') {
                buffer_free(buffer);
                rb_raise(InvalidKeyName, "key must not contain '.'");
            }
        }
    }

    switch(TYPE(value)) {
    case T_BIGNUM:
    case T_FIXNUM:
        {
            if (rb_funcall(value, gt_operator, 1, LL2NUM(9223372036854775807LL)) == Qtrue ||
                rb_funcall(value, lt_operator, 1, LL2NUM(-9223372036854775808ULL)) == Qtrue) {
                buffer_free(buffer);
                rb_raise(rb_eRangeError, "MongoDB can only handle 8-byte ints");
            }
            if (rb_funcall(value, gt_operator, 1, INT2NUM(2147483647L)) == Qtrue ||
                rb_funcall(value, lt_operator, 1, INT2NUM(-2147483648L)) == Qtrue) {
                long long ll_value;
                write_name_and_type(buffer, key, 0x12);
                ll_value = NUM2LL(value);
                SAFE_WRITE(buffer, (char*)&ll_value, 8);
            } else {
                int int_value;
                write_name_and_type(buffer, key, 0x10);
                int_value = NUM2LL(value);
                SAFE_WRITE(buffer, (char*)&int_value, 4);
            }
            break;
        }
    case T_TRUE:
        {
            write_name_and_type(buffer, key, 0x08);
            SAFE_WRITE(buffer, &one, 1);
            break;
        }
    case T_FALSE:
        {
            write_name_and_type(buffer, key, 0x08);
            SAFE_WRITE(buffer, &zero, 1);
            break;
        }
    case T_FLOAT:
        {
            double d = NUM2DBL(value);
            write_name_and_type(buffer, key, 0x01);
            SAFE_WRITE(buffer, (char*)&d, 8);
            break;
        }
    case T_NIL:
        {
            write_name_and_type(buffer, key, 0x0A);
            break;
        }
    case T_HASH:
        {
            write_name_and_type(buffer, key, 0x03);
            write_doc(buffer, value, check_keys, Qfalse);
            break;
        }
    case T_ARRAY:
        {
            buffer_position length_location, start_position, obj_length;
            int items, i;
            VALUE* values;

            write_name_and_type(buffer, key, 0x04);
            start_position = buffer_get_position(buffer);

            // save space for length
            length_location = buffer_save_space(buffer, 4);
            if (length_location == -1) {
                rb_raise(rb_eNoMemError, "failed to allocate memory in buffer.c");
            }

            items = RARRAY_LEN(value);
            values = RARRAY_PTR(value);
            for(i = 0; i < items; i++) {
                char* name;
                VALUE key;
                INT2STRING(&name, i);
                key = rb_str_new2(name);
                write_element_with_id(key, values[i], pack_extra(buffer, check_keys));
                free(name);
            }

            // write null byte and fill in length
            SAFE_WRITE(buffer, &zero, 1);
            obj_length = buffer_get_position(buffer) - start_position;
            SAFE_WRITE_AT_POS(buffer, length_location, (const char*)&obj_length, 4);
            break;
        }
    case T_STRING:
        {
            if (strcmp(rb_obj_classname(value),
                  "BSON::Code") == 0) {
                buffer_position length_location, start_position, total_length;
                int length;
                write_name_and_type(buffer, key, 0x0F);

                start_position = buffer_get_position(buffer);
                length_location = buffer_save_space(buffer, 4);
                if (length_location == -1) {
                    rb_raise(rb_eNoMemError, "failed to allocate memory in buffer.c");
                }

                length = RSTRING_LEN(value) + 1;
                SAFE_WRITE(buffer, (char*)&length, 4);
                SAFE_WRITE(buffer, RSTRING_PTR(value), length - 1);
                SAFE_WRITE(buffer, &zero, 1);
                write_doc(buffer, rb_funcall(value, rb_intern("scope"), 0), Qfalse, Qfalse);

                total_length = buffer_get_position(buffer) - start_position;
                SAFE_WRITE_AT_POS(buffer, length_location, (const char*)&total_length, 4);
                break;
            } else {
                int length;
                write_name_and_type(buffer, key, 0x02);
                value = TO_UTF8(value);
                length = RSTRING_LEN(value) + 1;
                SAFE_WRITE(buffer, (char*)&length, 4);
                write_utf8(buffer, value, 0);
                SAFE_WRITE(buffer, &zero, 1);
                break;
            }
        }
    case T_SYMBOL:
        {
            const char* str_value = rb_id2name(SYM2ID(value));
            int length = strlen(str_value) + 1;
            write_name_and_type(buffer, key, 0x0E);
            SAFE_WRITE(buffer, (char*)&length, 4);
            SAFE_WRITE(buffer, str_value, length);
            break;
        }
    case T_OBJECT:
        {
            // TODO there has to be a better way to do these checks...
            const char* cls = rb_obj_classname(value);
            if (strcmp(cls, "BSON::Binary") == 0 ||
                strcmp(cls, "ByteBuffer") == 0) {
                const char subtype = strcmp(cls, "ByteBuffer") ?
                    (const char)FIX2INT(rb_funcall(value, rb_intern("subtype"), 0)) : 2;
                VALUE string_data = rb_funcall(value, rb_intern("to_s"), 0);
                int length = RSTRING_LEN(string_data);
                write_name_and_type(buffer, key, 0x05);
                if (subtype == 2) {
                    const int other_length = length + 4;
                    SAFE_WRITE(buffer, (const char*)&other_length, 4);
                    SAFE_WRITE(buffer, &subtype, 1);
                }
                SAFE_WRITE(buffer, (const char*)&length, 4);
                if (subtype != 2) {
                    SAFE_WRITE(buffer, &subtype, 1);
                }
                SAFE_WRITE(buffer, RSTRING_PTR(string_data), length);
                break;
            }
            if ((strcmp(cls, "BSON::ObjectId") == 0) || (strcmp(cls, "BSON::ObjectID") == 0)) {
                VALUE as_array = rb_funcall(value, rb_intern("to_a"), 0);
                int i;
                write_name_and_type(buffer, key, 0x07);
                for (i = 0; i < 12; i++) {
                    char byte = (char)FIX2INT(RARRAY_PTR(as_array)[i]);
                    SAFE_WRITE(buffer, &byte, 1);
                }
                break;
            }
            if (strcmp(cls, "BSON::DBRef") == 0) {
                buffer_position length_location, start_position, obj_length;
                VALUE ns, oid;
                write_name_and_type(buffer, key, 0x03);

                start_position = buffer_get_position(buffer);

                // save space for length
                length_location = buffer_save_space(buffer, 4);
                if (length_location == -1) {
                    rb_raise(rb_eNoMemError, "failed to allocate memory in buffer.c");
                }

                ns = rb_funcall(value, rb_intern("namespace"), 0);
                write_element_with_id(rb_str_new2("$ref"), ns, pack_extra(buffer, Qfalse));
                oid = rb_funcall(value, rb_intern("object_id"), 0);
                write_element_with_id(rb_str_new2("$id"), oid, pack_extra(buffer, Qfalse));

                // write null byte and fill in length
                SAFE_WRITE(buffer, &zero, 1);
                obj_length = buffer_get_position(buffer) - start_position;
                SAFE_WRITE_AT_POS(buffer, length_location, (const char*)&obj_length, 4);
                break;
            }
            if (strcmp(cls, "BSON::MaxKey") == 0) {
                write_name_and_type(buffer, key, 0x7f);
                break;
            }
            if (strcmp(cls, "BSON::MinKey") == 0) {
                write_name_and_type(buffer, key, 0xff);
                break;
            }
            if (strcmp(cls, "DateTime") == 0 || strcmp(cls, "Date") == 0 || strcmp(cls, "ActiveSupport::TimeWithZone") == 0) {
                buffer_free(buffer);
                rb_raise(InvalidDocument, "%s is not currently supported; use a UTC Time instance instead.", cls);
                break;
            }
            if(strcmp(cls, "Complex") == 0 || strcmp(cls, "Rational") == 0 || strcmp(cls, "BigDecimal") == 0) {
                buffer_free(buffer);
                rb_raise(InvalidDocument, "Cannot serialize the Numeric type %s as BSON; only Bignum, Fixnum, and Float are supported.", cls);
                break;
            }
            buffer_free(buffer);
            rb_raise(InvalidDocument, "Cannot serialize an object of class %s into BSON.", cls);
            break;
        }
    case T_DATA:
        {
            const char* cls = rb_obj_classname(value);
            if (strcmp(cls, "Time") == 0) {
                double t = NUM2DBL(rb_funcall(value, rb_intern("to_f"), 0));
                long long time_since_epoch = (long long)round(t * 1000);
                write_name_and_type(buffer, key, 0x09);
                SAFE_WRITE(buffer, (const char*)&time_since_epoch, 8);
                break;
            }
            if(strcmp(cls, "BigDecimal") == 0) {
                buffer_free(buffer);
                rb_raise(InvalidDocument, "Cannot serialize the Numeric type %s as BSON; only Bignum, Fixnum, and Float are supported.", cls);
                break;
            }
            buffer_free(buffer);
            rb_raise(InvalidDocument, "Cannot serialize an object of class %s into BSON.", cls);
            break;
        }
    case T_REGEXP:
        {
            VALUE pattern = RREGEXP_SRC(value);
            long flags = RREGEXP_OPTIONS(value);
            VALUE has_extra;

            write_name_and_type(buffer, key, 0x0B);

            pattern = TO_UTF8(pattern);
            write_utf8(buffer, pattern, 1);
            SAFE_WRITE(buffer, &zero, 1);

            if (flags & IGNORECASE) {
                char ignorecase = 'i';
                SAFE_WRITE(buffer, &ignorecase, 1);
            }
            if (flags & MULTILINE) {
                char multiline = 'm';
                SAFE_WRITE(buffer, &multiline, 1);
            }
            if (flags & EXTENDED) {
                char extended = 'x';
                SAFE_WRITE(buffer, &extended, 1);
            }

            has_extra = rb_funcall(value, rb_intern("respond_to?"), 1, rb_str_new2("extra_options_str"));
            if (TYPE(has_extra) == T_TRUE) {
                VALUE extra = rb_funcall(value, rb_intern("extra_options_str"), 0);
                buffer_position old_position = buffer_get_position(buffer);
                SAFE_WRITE(buffer, RSTRING_PTR(extra), RSTRING_LEN(extra));
                qsort(buffer_get_buffer(buffer) + old_position, RSTRING_LEN(extra), sizeof(char), cmp_char);
            }
            SAFE_WRITE(buffer, &zero, 1);

            break;
        }
    default:
        {
            const char* cls = rb_obj_classname(value);
            buffer_free(buffer);
            rb_raise(InvalidDocument, "Cannot serialize an object of class %s (type %d) into BSON.", cls, TYPE(value));
            break;
        }
    }
    return ST_CONTINUE;
}
Beispiel #9
0
static void write_doc(buffer_t buffer, VALUE hash, VALUE check_keys, VALUE move_id) {
    buffer_position start_position = buffer_get_position(buffer);
    buffer_position length_location = buffer_save_space(buffer, 4);
    buffer_position length;
    int allow_id;
    int (*write_function)(VALUE, VALUE, VALUE) = NULL;
    VALUE id_str = rb_str_new2("_id");
    VALUE id_sym = ID2SYM(rb_intern("_id"));

    if (length_location == -1) {
        rb_raise(rb_eNoMemError, "failed to allocate memory in buffer.c");
    }

    // write '_id' first if move_id is true. then don't allow an id to be written.
    if(move_id == Qtrue) {
        allow_id = 0;
        if (rb_funcall(hash, rb_intern("has_key?"), 1, id_str) == Qtrue) {
            VALUE id = rb_hash_aref(hash, id_str);
            write_element_with_id(id_str, id, pack_extra(buffer, check_keys));
        } else if (rb_funcall(hash, rb_intern("has_key?"), 1, id_sym) == Qtrue) {
            VALUE id = rb_hash_aref(hash, id_sym);
            write_element_with_id(id_sym, id, pack_extra(buffer, check_keys));
        }
    }
    else {
        allow_id = 1;
        // Ensure that hash doesn't contain both '_id' and :_id
        if ((rb_obj_classname(hash), "Hash") == 0) {
            if ((rb_funcall(hash, rb_intern("has_key?"), 1, id_str) == Qtrue) &&
                   (rb_funcall(hash, rb_intern("has_key?"), 1, id_sym) == Qtrue)) {
                      VALUE oid_sym = rb_hash_delete(hash, id_sym);
                      rb_funcall(hash, rb_intern("[]="), 2, id_str, oid_sym);
            }
        }
    }

    if(allow_id == 1) {
        write_function = write_element_with_id;
    }
    else {
        write_function = write_element_without_id;
    }

    // we have to check for an OrderedHash and handle that specially
    if (strcmp(rb_obj_classname(hash), "BSON::OrderedHash") == 0) {
        VALUE keys = rb_funcall(hash, rb_intern("keys"), 0);
        int i;
                for(i = 0; i < RARRAY_LEN(keys); i++) {
            VALUE key = RARRAY_PTR(keys)[i];
            VALUE value = rb_hash_aref(hash, key);

            write_function(key, value, pack_extra(buffer, check_keys));
        }
    } else if (rb_obj_is_kind_of(hash, RB_HASH) == Qtrue) {
        rb_hash_foreach(hash, write_function, pack_extra(buffer, check_keys));
    } else {
        buffer_free(buffer);
        char* cls = rb_obj_classname(hash);
        rb_raise(InvalidDocument, "BSON.serialize takes a Hash but got a %s", cls);
    }

    // write null byte and fill in length
    SAFE_WRITE(buffer, &zero, 1);
    length = buffer_get_position(buffer) - start_position;

    // make sure that length doesn't exceed 4MB
    if (length > 4 * 1024 * 1024) {
      buffer_free(buffer);
      rb_raise(InvalidDocument, "Document too large: BSON documents are limited to 4MB.");
      return;
    }
    SAFE_WRITE_AT_POS(buffer, length_location, (const char*)&length, 4);
}
Beispiel #10
0
static VALUE
reduce0(VALUE val, VALUE data, VALUE self)
{
    struct cparse_params *v;
    VALUE reduce_to, reduce_len, method_id;
    long len;
    ID mid;
    VALUE tmp, tmp_t = Qundef, tmp_v = Qundef;
    long i, k1, k2;
    VALUE goto_state;

    Data_Get_Struct(data, struct cparse_params, v);
    reduce_len = RARRAY_PTR(v->reduce_table)[v->ruleno];
    reduce_to  = RARRAY_PTR(v->reduce_table)[v->ruleno+1];
    method_id  = RARRAY_PTR(v->reduce_table)[v->ruleno+2];
    len = NUM2LONG(reduce_len);
    mid = value_to_id(method_id);

    /* call action */
    if (len == 0) {
        tmp = Qnil;
        if (mid != id_noreduce)
            tmp_v = rb_ary_new();
        if (v->debug)
            tmp_t = rb_ary_new();
    }
    else {
        if (mid != id_noreduce) {
            tmp_v = GET_TAIL(v->vstack, len);
            tmp = RARRAY_PTR(tmp_v)[0];
        }
        else {
            tmp = RARRAY_PTR(v->vstack)[ RARRAY_LEN(v->vstack) - len ];
        }
        CUT_TAIL(v->vstack, len);
        if (v->debug) {
            tmp_t = GET_TAIL(v->tstack, len);
            CUT_TAIL(v->tstack, len);
        }
        CUT_TAIL(v->state, len);
    }
    if (mid != id_noreduce) {
        if (v->use_result_var) {
            tmp = rb_funcall(v->parser, mid,
                             3, tmp_v, v->vstack, tmp);
        }
        else {
            tmp = rb_funcall(v->parser, mid,
                             2, tmp_v, v->vstack);
        }
    }

    /* then push result */
    PUSH(v->vstack, tmp);
    if (v->debug) {
        PUSH(v->tstack, reduce_to);
        rb_funcall(v->parser, id_d_reduce,
                   4, tmp_t, reduce_to, v->tstack, v->vstack);
    }

    /* calculate transition state */
    if (RARRAY_LEN(v->state) == 0)
        rb_raise(RaccBug, "state stack unexpectedly empty");
    k2 = num_to_long(LAST_I(v->state));
    k1 = num_to_long(reduce_to) - v->nt_base;
    D_printf("(goto) k1=%ld\n", k1);
    D_printf("(goto) k2=%ld\n", k2);

    tmp = AREF(v->goto_pointer, k1);
    if (NIL_P(tmp)) goto notfound;

    i = NUM2LONG(tmp) + k2;
    D_printf("(goto) i=%ld\n", i);
    if (i < 0) goto notfound;

    goto_state = AREF(v->goto_table, i);
    if (NIL_P(goto_state)) {
        D_puts("(goto) table[i] == nil");
        goto notfound;
    }
    D_printf("(goto) table[i]=%ld (goto_state)\n", NUM2LONG(goto_state));

    tmp = AREF(v->goto_check, i);
    if (NIL_P(tmp)) {
        D_puts("(goto) check[i] == nil");
        goto notfound;
    }
    if (tmp != LONG2NUM(k1)) {
        D_puts("(goto) check[i] != table[i]");
        goto notfound;
    }
    D_printf("(goto) check[i]=%ld\n", NUM2LONG(tmp));

    D_puts("(goto) found");
  transit:
    PUSH(v->state, goto_state);
    v->curstate = NUM2LONG(goto_state);
    return INT2FIX(0);

  notfound:
    D_puts("(goto) not found: use default");
    /* overwrite `goto-state' by default value */
    goto_state = AREF(v->goto_default, k1);
    goto transit;
}
Beispiel #11
0
static VALUE rb_mysql_result_each_(VALUE self,
                                   VALUE(*fetch_row_func)(VALUE, MYSQL_FIELD *fields, const result_each_args *args),
                                   const result_each_args *args)
{
  unsigned long i;
  const char *errstr;
  MYSQL_FIELD *fields = NULL;

  GET_RESULT(self);

  if (wrapper->is_streaming) {
    /* When streaming, we will only yield rows, not return them. */
    if (wrapper->rows == Qnil) {
      wrapper->rows = rb_ary_new();
    }

    if (!wrapper->streamingComplete) {
      VALUE row;

      fields = mysql_fetch_fields(wrapper->result);

      do {
        row = fetch_row_func(self, fields, args);
        if (row != Qnil) {
          wrapper->numberOfRows++;
          if (args->block_given != Qnil) {
            rb_yield(row);
          }
        }
      } while(row != Qnil);

      rb_mysql_result_free_result(wrapper);
      wrapper->streamingComplete = 1;

      // Check for errors, the connection might have gone out from under us
      // mysql_error returns an empty string if there is no error
      errstr = mysql_error(wrapper->client_wrapper->client);
      if (errstr[0]) {
        rb_raise(cMysql2Error, "%s", errstr);
      }
    } else {
      rb_raise(cMysql2Error, "You have already fetched all the rows for this query and streaming is true. (to reiterate you must requery).");
    }
  } else {
    if (args->cacheRows && wrapper->lastRowProcessed == wrapper->numberOfRows) {
      /* we've already read the entire dataset from the C result into our */
      /* internal array. Lets hand that over to the user since it's ready to go */
      for (i = 0; i < wrapper->numberOfRows; i++) {
        rb_yield(rb_ary_entry(wrapper->rows, i));
      }
    } else {
      unsigned long rowsProcessed = 0;
      rowsProcessed = RARRAY_LEN(wrapper->rows);
      fields = mysql_fetch_fields(wrapper->result);

      for (i = 0; i < wrapper->numberOfRows; i++) {
        VALUE row;
        if (args->cacheRows && i < rowsProcessed) {
          row = rb_ary_entry(wrapper->rows, i);
        } else {
          row = fetch_row_func(self, fields, args);
          if (args->cacheRows) {
            rb_ary_store(wrapper->rows, i, row);
          }
          wrapper->lastRowProcessed++;
        }

        if (row == Qnil) {
          /* we don't need the mysql C dataset around anymore, peace it */
          if (args->cacheRows) {
            rb_mysql_result_free_result(wrapper);
          }
          return Qnil;
        }

        if (args->block_given != Qnil) {
          rb_yield(row);
        }
      }
      if (wrapper->lastRowProcessed == wrapper->numberOfRows && args->cacheRows) {
        /* we don't need the mysql C dataset around anymore, peace it */
        rb_mysql_result_free_result(wrapper);
      }
    }
  }

  // FIXME return Enumerator instead?
  // return rb_ary_each(wrapper->rows);
  return wrapper->rows;
}
Beispiel #12
0
static void
parse_main(struct cparse_params *v, VALUE tok, VALUE val, int resume)
{
    long i;              /* table index */
    long act;            /* action type */
    VALUE act_value;     /* action type, VALUE version */
    int read_next = 1;   /* true if we need to read next token */
    VALUE tmp;

    if (resume)
        goto resume;
    
    while (1) {
        D_puts("");
        D_puts("---- enter new loop ----");
        D_puts("");

        D_printf("(act) k1=%ld\n", v->curstate);
        tmp = AREF(v->action_pointer, v->curstate);
        if (NIL_P(tmp)) goto notfound;
        D_puts("(act) pointer[k1] ok");
        i = NUM2LONG(tmp);

        D_printf("read_next=%d\n", read_next);
        if (read_next && (v->t != vFINAL_TOKEN)) {
            if (v->lex_is_iterator) {
                D_puts("resuming...");
                if (v->fin) rb_raise(rb_eArgError, "token given after EOF");
                v->i = i;  /* save i */
                return;
              resume:
                D_puts("resumed");
                i = v->i;  /* load i */
            }
            else {
                D_puts("next_token");
                tmp = rb_funcall(v->parser, id_nexttoken, 0);
                extract_user_token(v, tmp, &tok, &val);
            }
            /* convert token */
            v->t = rb_hash_aref(v->token_table, tok);
            if (NIL_P(v->t)) {
                v->t = vERROR_TOKEN;
            }
            D_printf("(act) t(k2)=%ld\n", NUM2LONG(v->t));
            if (v->debug) {
                rb_funcall(v->parser, id_d_read_token,
                           3, v->t, tok, val);
            }
        }
        read_next = 0;

        i += NUM2LONG(v->t);
        D_printf("(act) i=%ld\n", i);
        if (i < 0) goto notfound;

        act_value = AREF(v->action_table, i);
        if (NIL_P(act_value)) goto notfound;
        act = NUM2LONG(act_value);
        D_printf("(act) table[i]=%ld\n", act);

        tmp = AREF(v->action_check, i);
        if (NIL_P(tmp)) goto notfound;
        if (NUM2LONG(tmp) != v->curstate) goto notfound;
        D_printf("(act) check[i]=%ld\n", NUM2LONG(tmp));

        D_puts("(act) found");
      act_fixed:
        D_printf("act=%ld\n", act);
        goto handle_act;
    
      notfound:
        D_puts("(act) not found: use default");
        act_value = AREF(v->action_default, v->curstate);
        act = NUM2LONG(act_value);
        goto act_fixed;


      handle_act:
        if (act > 0 && act < v->shift_n) {
            D_puts("shift");
            if (v->errstatus > 0) {
                v->errstatus--;
                rb_ivar_set(v->parser, id_errstatus, LONG2NUM(v->errstatus));
            }
            SHIFT(v, act, v->t, val);
            read_next = 1;
        }
        else if (act < 0 && act > -(v->reduce_n)) {
            D_puts("reduce");
            REDUCE(v, act);
        }
        else if (act == -(v->reduce_n)) {
            goto error;
          error_recovered:
            ;   /* goto label requires stmt */
        }
        else if (act == v->shift_n) {
            D_puts("accept");
            goto accept;
        }
        else {
            rb_raise(RaccBug, "[Racc Bug] unknown act value %ld", act);
        }

        if (v->debug) {
            rb_funcall(v->parser, id_d_next_state,
                       2, LONG2NUM(v->curstate), v->state);
        }
    }
    /* not reach */


  accept:
    if (v->debug) rb_funcall(v->parser, id_d_accept, 0);
    v->retval = RARRAY_PTR(v->vstack)[0];
    v->fin = CP_FIN_ACCEPT;
    return;


  error:
    D_printf("error detected, status=%ld\n", v->errstatus);
    if (v->errstatus == 0) {
        v->nerr++;
        rb_funcall(v->parser, id_onerror,
                   3, v->t, val, v->vstack);
    }
  user_yyerror:
    if (v->errstatus == 3) {
        if (v->t == vFINAL_TOKEN) {
            v->retval = Qfalse;
            v->fin = CP_FIN_EOT;
            return;
        }
        read_next = 1;
    }
    v->errstatus = 3;
    rb_ivar_set(v->parser, id_errstatus, LONG2NUM(v->errstatus));

    /* check if we can shift/reduce error token */
    D_printf("(err) k1=%ld\n", v->curstate);
    D_printf("(err) k2=%d (error)\n", ERROR_TOKEN);
    while (1) {
        tmp = AREF(v->action_pointer, v->curstate);
        if (NIL_P(tmp)) goto error_pop;
        D_puts("(err) pointer[k1] ok");

        i = NUM2LONG(tmp) + ERROR_TOKEN;
        D_printf("(err) i=%ld\n", i);
        if (i < 0) goto error_pop;

        act_value = AREF(v->action_table, i);
        if (NIL_P(act_value)) {
            D_puts("(err) table[i] == nil");
            goto error_pop;
        }
        act = NUM2LONG(act_value);
        D_printf("(err) table[i]=%ld\n", act);

        tmp = AREF(v->action_check, i);
        if (NIL_P(tmp)) {
            D_puts("(err) check[i] == nil");
            goto error_pop;
        }
        if (NUM2LONG(tmp) != v->curstate) {
            D_puts("(err) check[i] != k1");
            goto error_pop;
        }

        D_puts("(err) found: can handle error token");
        break;
          
      error_pop:
        D_puts("(err) act not found: can't handle error token; pop");

        if (RARRAY_LEN(v->state) <= 1) {
            v->retval = Qnil;
            v->fin = CP_FIN_CANTPOP;
            return;
        }
        POP(v->state);
        POP(v->vstack);
        v->curstate = num_to_long(LAST_I(v->state));
        if (v->debug) {
            POP(v->tstack);
            rb_funcall(v->parser, id_d_e_pop,
                       3, v->state, v->tstack, v->vstack);
        }
    }

    /* shift/reduce error token */
    if (act > 0 && act < v->shift_n) {
        D_puts("e shift");
        SHIFT(v, act, ERROR_TOKEN, val);
    }
    else if (act < 0 && act > -(v->reduce_n)) {
        D_puts("e reduce");
        REDUCE(v, act);
    }
    else if (act == v->shift_n) {
        D_puts("e accept");
        goto accept;
    }
    else {
        rb_raise(RaccBug, "[Racc Bug] unknown act value %ld", act);
    }
    goto error_recovered;
}
Beispiel #13
0
/* grpc_run_batch_stack_fill_ops fills the run_batch_stack ops array from
 * ops_hash */
static void grpc_run_batch_stack_fill_ops(run_batch_stack *st, VALUE ops_hash) {
  VALUE this_op = Qnil;
  VALUE this_value = Qnil;
  VALUE ops_ary = rb_ary_new();
  size_t i = 0;

  /* Create a ruby array with just the operation keys */
  rb_hash_foreach(ops_hash, grpc_rb_call_check_op_keys_hash_cb, ops_ary);

  /* Fill the ops array */
  for (i = 0; i < (size_t)RARRAY_LEN(ops_ary); i++) {
    this_op = rb_ary_entry(ops_ary, i);
    this_value = rb_hash_aref(ops_hash, this_op);
    st->ops[st->op_num].flags = 0;
    switch (NUM2INT(this_op)) {
      case GRPC_OP_SEND_INITIAL_METADATA:
        /* N.B. later there is no need to explicitly delete the metadata keys
         * and values, they are references to data in ruby objects. */
        grpc_rb_md_ary_convert(this_value, &st->send_metadata);
        st->ops[st->op_num].data.send_initial_metadata.count =
            st->send_metadata.count;
        st->ops[st->op_num].data.send_initial_metadata.metadata =
            st->send_metadata.metadata;
        break;
      case GRPC_OP_SEND_MESSAGE:
        st->ops[st->op_num].data.send_message = grpc_rb_s_to_byte_buffer(
            RSTRING_PTR(this_value), RSTRING_LEN(this_value));
        st->ops[st->op_num].flags = st->write_flag;
        break;
      case GRPC_OP_SEND_CLOSE_FROM_CLIENT:
        break;
      case GRPC_OP_SEND_STATUS_FROM_SERVER:
        /* N.B. later there is no need to explicitly delete the metadata keys
         * and values, they are references to data in ruby objects. */
        grpc_rb_op_update_status_from_server(
            &st->ops[st->op_num], &st->send_trailing_metadata, this_value);
        break;
      case GRPC_OP_RECV_INITIAL_METADATA:
        st->ops[st->op_num].data.recv_initial_metadata = &st->recv_metadata;
        break;
      case GRPC_OP_RECV_MESSAGE:
        st->ops[st->op_num].data.recv_message = &st->recv_message;
        break;
      case GRPC_OP_RECV_STATUS_ON_CLIENT:
        st->ops[st->op_num].data.recv_status_on_client.trailing_metadata =
            &st->recv_trailing_metadata;
        st->ops[st->op_num].data.recv_status_on_client.status =
            &st->recv_status;
        st->ops[st->op_num].data.recv_status_on_client.status_details =
            &st->recv_status_details;
        st->ops[st->op_num].data.recv_status_on_client.status_details_capacity =
            &st->recv_status_details_capacity;
        break;
      case GRPC_OP_RECV_CLOSE_ON_SERVER:
        st->ops[st->op_num].data.recv_close_on_server.cancelled =
            &st->recv_cancelled;
        break;
      default:
        grpc_run_batch_stack_cleanup(st);
        rb_raise(rb_eTypeError, "invalid operation : bad value %d",
                 NUM2INT(this_op));
    };
    st->ops[st->op_num].op = (grpc_op_type)NUM2INT(this_op);
    st->ops[st->op_num].reserved = NULL;
    st->op_num++;
  }
}
Beispiel #14
0
/* grpc_rb_md_ary_fill_hash_cb is the hash iteration callback used
   to fill grpc_metadata_array.

   it's capacity should have been computed via a prior call to
   grpc_rb_md_ary_fill_hash_cb
*/
static int grpc_rb_md_ary_fill_hash_cb(VALUE key, VALUE val, VALUE md_ary_obj) {
  grpc_metadata_array *md_ary = NULL;
  long array_length;
  long i;
  char *key_str;
  size_t key_len;
  char *value_str;
  size_t value_len;

  if (TYPE(key) == T_SYMBOL) {
    key_str = (char *)rb_id2name(SYM2ID(key));
    key_len = strlen(key_str);
  } else { /* StringValueCStr does all other type exclusions for us */
    key_str = StringValueCStr(key);
    key_len = RSTRING_LEN(key);
  }

  if (!grpc_header_key_is_legal(key_str, key_len)) {
    rb_raise(rb_eArgError,
             "'%s' is an invalid header key, must match [a-z0-9-_.]+",
             key_str);
    return ST_STOP;
  }

  /* Construct a metadata object from key and value and add it */
  TypedData_Get_Struct(md_ary_obj, grpc_metadata_array,
                       &grpc_rb_md_ary_data_type, md_ary);

  if (TYPE(val) == T_ARRAY) {
    array_length = RARRAY_LEN(val);
    /* If the value is an array, add capacity for each value in the array */
    for (i = 0; i < array_length; i++) {
      value_str = RSTRING_PTR(rb_ary_entry(val, i));
      value_len = RSTRING_LEN(rb_ary_entry(val, i));
      if (!grpc_is_binary_header(key_str, key_len) &&
          !grpc_header_nonbin_value_is_legal(value_str, value_len)) {
        // The value has invalid characters
        rb_raise(rb_eArgError,
                 "Header value '%s' has invalid characters", value_str);
        return ST_STOP;
      }
      md_ary->metadata[md_ary->count].key = key_str;
      md_ary->metadata[md_ary->count].value = value_str;
      md_ary->metadata[md_ary->count].value_length = value_len;
      md_ary->count += 1;
    }
  } else if (TYPE(val) == T_STRING) {
    value_str = RSTRING_PTR(val);
    value_len = RSTRING_LEN(val);
    if (!grpc_is_binary_header(key_str, key_len) &&
        !grpc_header_nonbin_value_is_legal(value_str, value_len)) {
      // The value has invalid characters
      rb_raise(rb_eArgError,
               "Header value '%s' has invalid characters", value_str);
      return ST_STOP;
    }
    md_ary->metadata[md_ary->count].key = key_str;
    md_ary->metadata[md_ary->count].value = value_str;
    md_ary->metadata[md_ary->count].value_length = value_len;
    md_ary->count += 1;
  } else {
    rb_raise(rb_eArgError,
               "Header values must be of type string or array");
    return ST_STOP;
  }

  return ST_CONTINUE;
}
Beispiel #15
0
/* call-seq: emitter.start_document(version, tags, implicit)
 *
 * Start a document emission with YAML +version+, +tags+, and an +implicit+
 * start.
 *
 * See Psych::Handler#start_document
 */
static VALUE start_document(VALUE self, VALUE version, VALUE tags, VALUE imp)
{
    yaml_emitter_t * emitter;
    yaml_tag_directive_t * head = NULL;
    yaml_tag_directive_t * tail = NULL;
    yaml_event_t event;
    yaml_version_directive_t version_directive;
    Data_Get_Struct(self, yaml_emitter_t, emitter);


    Check_Type(version, T_ARRAY);

    if(RARRAY_LEN(version) > 0) {
        VALUE major = rb_ary_entry(version, (long)0);
        VALUE minor = rb_ary_entry(version, (long)1);

        version_directive.major = NUM2INT(major);
        version_directive.minor = NUM2INT(minor);
    }

    if(RTEST(tags)) {
        int i = 0;
#ifdef HAVE_RUBY_ENCODING_H
        rb_encoding * encoding = rb_utf8_encoding();
#endif

        Check_Type(tags, T_ARRAY);

        head  = xcalloc((size_t)RARRAY_LEN(tags), sizeof(yaml_tag_directive_t));
        tail  = head;

        for(i = 0; i < RARRAY_LEN(tags); i++) {
            VALUE tuple = rb_ary_entry(tags, i);
            VALUE name;
            VALUE value;

            Check_Type(tuple, T_ARRAY);

            if(RARRAY_LEN(tuple) < 2) {
                xfree(head);
                rb_raise(rb_eRuntimeError, "tag tuple must be of length 2");
            }
            name  = rb_ary_entry(tuple, 0);
            value = rb_ary_entry(tuple, 1);
#ifdef HAVE_RUBY_ENCODING_H
            name = rb_str_export_to_enc(name, encoding);
            value = rb_str_export_to_enc(value, encoding);
#endif

            tail->handle = (yaml_char_t *)StringValuePtr(name);
            tail->prefix = (yaml_char_t *)StringValuePtr(value);

            tail++;
        }
    }

    yaml_document_start_event_initialize(
        &event,
        (RARRAY_LEN(version) > 0) ? &version_directive : NULL,
        head,
        tail,
        imp ? 1 : 0
    );

    emit(emitter, &event);

    if(head) xfree(head);

    return self;
}
Beispiel #16
0
inline static VALUE mArray_json_transfrom(VALUE self, VALUE Vstate, VALUE Vdepth) {
    long i, len = RARRAY_LEN(self);
    VALUE shift, result;
    long depth = NIL_P(Vdepth) ? 0 : FIX2LONG(Vdepth);
    VALUE delim = rb_str_new2(",");
    GET_STATE(Vstate);

    check_max_nesting(state, depth);
    if (state->check_circular) {
        VALUE self_id = rb_obj_id(self);
        rb_hash_aset(state->seen, self_id, Qtrue);
        result = rb_str_buf_new(len);
        if (RSTRING_LEN(state->array_nl)) rb_str_append(delim, state->array_nl);
        shift = rb_str_times(state->indent, LONG2FIX(depth + 1));

        rb_str_buf_cat2(result, "[");
        OBJ_INFECT(result, self);
        rb_str_buf_append(result, state->array_nl);
        for (i = 0;  i < len; i++) {
            VALUE element = RARRAY_PTR(self)[i];
            if (RTEST(rb_hash_aref(state->seen, rb_obj_id(element)))) {
                rb_raise(eCircularDatastructure,
                        "circular data structures not supported!");
            }
            OBJ_INFECT(result, element);
            if (i > 0) rb_str_buf_append(result, delim);
            rb_str_buf_append(result, shift);
            element = rb_funcall(element, i_to_json, 2, Vstate, LONG2FIX(depth + 1));
            Check_Type(element, T_STRING);
            rb_str_buf_append(result, element);
        }
        if (RSTRING_LEN(state->array_nl)) {
            rb_str_buf_append(result, state->array_nl);
            rb_str_buf_append(result, rb_str_times(state->indent, LONG2FIX(depth)));
        }
        rb_str_buf_cat2(result, "]");
        rb_hash_delete(state->seen, self_id);
    } else {
        result = rb_str_buf_new(len);
        OBJ_INFECT(result, self);
        if (RSTRING_LEN(state->array_nl)) rb_str_append(delim, state->array_nl);
        shift = rb_str_times(state->indent, LONG2FIX(depth + 1));

        rb_str_buf_cat2(result, "[");
        rb_str_buf_append(result, state->array_nl);
        for (i = 0;  i < len; i++) {
            VALUE element = RARRAY_PTR(self)[i];
            OBJ_INFECT(result, element);
            if (i > 0) rb_str_buf_append(result, delim);
            rb_str_buf_append(result, shift);
            element = rb_funcall(element, i_to_json, 2, Vstate, LONG2FIX(depth + 1));
            Check_Type(element, T_STRING);
            rb_str_buf_append(result, element);
        }
        rb_str_buf_append(result, state->array_nl);
        if (RSTRING_LEN(state->array_nl)) {
            rb_str_buf_append(result, rb_str_times(state->indent, LONG2FIX(depth)));
        }
        rb_str_buf_cat2(result, "]");
    }
    return result;
}
VALUE
rb_gi_function_info_invoke_raw(GIFunctionInfo *info, VALUE rb_options,
                               GIArgument *return_value)
{
    GICallableInfo *callable_info;
    GIArgument receiver;
    GArray *in_args, *out_args;
    GPtrArray *args_metadata;
    VALUE rb_out_args = Qnil;
    gboolean succeeded;
    GError *error = NULL;
    gboolean unlock_gvl = FALSE;
    VALUE rb_receiver, rb_arguments, rb_unlock_gvl;

    if (RB_TYPE_P(rb_options, RUBY_T_ARRAY)) {
        rb_receiver = Qnil;
        rb_arguments = rb_options;
        rb_unlock_gvl = Qnil;
    } else if (NIL_P(rb_options)) {
        rb_receiver = Qnil;
        rb_arguments = rb_ary_new();
        rb_unlock_gvl = Qnil;
    } else {
        rb_options = rbg_check_hash_type(rb_options);
        rbg_scan_options(rb_options,
                         "receiver", &rb_receiver,
                         "arguments", &rb_arguments,
                         "unlock_gvl", &rb_unlock_gvl,
                         NULL);
    }

    if (NIL_P(rb_receiver)) {
        receiver.v_pointer = NULL;
    } else {
        if (gobject_based_p((GIBaseInfo *)info)) {
            receiver.v_pointer = RVAL2GOBJ(rb_receiver);
        } else {
            receiver.v_pointer = DATA_PTR(rb_receiver);
        }
    }
    rb_arguments = rbg_to_array(rb_arguments);
    if (!NIL_P(rb_unlock_gvl) && RVAL2CBOOL(rb_unlock_gvl)) {
        unlock_gvl = TRUE;
    }

    callable_info = (GICallableInfo *)info;
    arguments_init(&in_args, &out_args, &args_metadata);
    if (receiver.v_pointer) {
        g_array_append_val(in_args, receiver);
    }
    arguments_from_ruby(callable_info, rb_arguments,
                        in_args, out_args, args_metadata);
    {
        InvokeData data;
        data.info = info;
        data.in_args = in_args;
        data.out_args = out_args;
        data.return_value = return_value;
        data.error = &error;
        if (unlock_gvl) {
            rb_thread_call_without_gvl(
                rb_gi_function_info_invoke_raw_call_without_gvl_body, &data,
                NULL, NULL);
        } else {
            rb_gi_function_info_invoke_raw_call(&data);
        }
        succeeded = data.succeeded;
    }

    if (succeeded) {
        rb_out_args = out_arguments_to_ruby(callable_info,
                                            in_args, out_args,
                                            args_metadata);
    }
    arguments_free(in_args, out_args, args_metadata);
    if (!succeeded) {
        RG_RAISE_ERROR(error);
    }

    if (!NIL_P(rb_out_args) && RARRAY_LEN(rb_out_args) == 1) {
        VALUE rb_out_arg;
        rb_out_arg = RARRAY_PTR(rb_out_args)[0];
        if (rb_obj_is_kind_of(rb_out_arg, rb_cGLibError)) {
            rb_exc_raise(rb_out_arg);
        }
    }

    return rb_out_args;
}
Beispiel #18
0
bp::Object *
rubyToBPObject(VALUE v)
{
    bp::Object * obj = NULL;
    
    switch (TYPE(v)) {
        case T_FLOAT:
            obj = new bp::Double(rb_num2dbl(v));
            break;
        case T_STRING:
            obj = new bp::String(RSTRING_PTR(v));
            break;
        case T_FIXNUM:
            obj = new bp::Integer(rb_num2ull(v));
            break;
        case T_TRUE:
            obj = new bp::Bool(true);
            break;
        case T_FALSE:
            obj = new bp::Bool(false);
            break;
        case T_HASH:
            obj = new bp::Map;
            rb_hash_foreach(v,
                            (int (*)(ANYARGS)) hashPopulator,
                            (VALUE) obj);
            break;
        case T_ARRAY:
        {
            long i;
            bp::List * l = new bp::List;
            for (i=0; i < RARRAY_LEN(v); i++) {
                l->append(rubyToBPObject(rb_ary_entry(v, i)));
            }
            obj = l;
        }
        break;
        case T_OBJECT: {
            // map Pathname objects into BPTPath types
            VALUE id = rb_intern("Pathname");
            VALUE klass = 0;
            if (rb_const_defined(rb_cObject, id) &&
                (klass = rb_const_get(rb_cObject, id)) &&
                TYPE(klass) == T_CLASS)
            {
                VALUE r = rb_obj_is_kind_of(v, klass);
                if (RTEST(r)) {
                    // convert to abs path
                    int error = 0;
                    VALUE absPath =
                        ruby::invokeFunction(v, "realpath", &error, 0);
                    VALUE pathString =
                        ruby::invokeFunction(absPath, "to_s", &error, 0);
                    if (!error && TYPE(pathString) == T_STRING) {
						obj = new bp::Path((const BPPath) convert::fromUTF8(RSTRING_PTR(pathString)).c_str());
                    }
                    break;
                }
            }
        }
        case T_NIL:
        default:
            obj = new bp::Null();
            break;
    }
    
    return obj;
}
Beispiel #19
0
static int
rb_feature_p(const char *feature, const char *ext, int rb, int expanded, const char **fn)
{
    VALUE features, this_feature_index = Qnil, v, p, load_path = 0;
    const char *f, *e;
    long i, len, elen, n;
    st_table *loading_tbl, *features_index;
    st_data_t data;
    int type;

    if (fn) *fn = 0;
    if (ext) {
	elen = strlen(ext);
	len = strlen(feature) - elen;
	type = rb ? 'r' : 's';
    }
    else {
	len = strlen(feature);
	elen = 0;
	type = 0;
    }
    features = get_loaded_features();
    features_index = get_loaded_features_index();

    st_lookup(features_index, (st_data_t)feature, (st_data_t *)&this_feature_index);
    /* We search `features` for an entry such that either
         "#{features[i]}" == "#{load_path[j]}/#{feature}#{e}"
       for some j, or
         "#{features[i]}" == "#{feature}#{e}"
       Here `e` is an "allowed" extension -- either empty or one
       of the extensions accepted by IS_RBEXT, IS_SOEXT, or
       IS_DLEXT.  Further, if `ext && rb` then `IS_RBEXT(e)`,
       and if `ext && !rb` then `IS_SOEXT(e) || IS_DLEXT(e)`.

       If `expanded`, then only the latter form (without load_path[j])
       is accepted.  Otherwise either form is accepted, *unless* `ext`
       is false and an otherwise-matching entry of the first form is
       preceded by an entry of the form
         "#{features[i2]}" == "#{load_path[j2]}/#{feature}#{e2}"
       where `e2` matches %r{^\.[^./]*$} but is not an allowed extension.
       After a "distractor" entry of this form, only entries of the
       form "#{feature}#{e}" are accepted.

       In `rb_provide_feature()` and `get_loaded_features_index()` we
       maintain an invariant that the array `this_feature_index` will
       point to every entry in `features` which has the form
         "#{prefix}#{feature}#{e}"
       where `e` is empty or matches %r{^\.[^./]*$}, and `prefix` is empty
       or ends in '/'.  This includes both match forms above, as well
       as any distractors, so we may ignore all other entries in `features`.
     */
    if (!NIL_P(this_feature_index)) {
	for (i = 0; ; i++) {
	    VALUE entry;
	    long index;
	    if (RB_TYPE_P(this_feature_index, T_ARRAY)) {
		if (i >= RARRAY_LEN(this_feature_index)) break;
		entry = RARRAY_AREF(this_feature_index, i);
	    }
	    else {
		if (i > 0) break;
		entry = this_feature_index;
	    }
	    index = FIX2LONG(entry);

	    v = RARRAY_AREF(features, index);
	    f = StringValuePtr(v);
	    if ((n = RSTRING_LEN(v)) < len) continue;
	    if (strncmp(f, feature, len) != 0) {
		if (expanded) continue;
		if (!load_path) load_path = rb_get_expanded_load_path();
		if (!(p = loaded_feature_path(f, n, feature, len, type, load_path)))
		    continue;
		expanded = 1;
		f += RSTRING_LEN(p) + 1;
	    }
	    if (!*(e = f + len)) {
		if (ext) continue;
		return 'u';
	    }
	    if (*e != '.') continue;
	    if ((!rb || !ext) && (IS_SOEXT(e) || IS_DLEXT(e))) {
		return 's';
	    }
	    if ((rb || !ext) && (IS_RBEXT(e))) {
		return 'r';
	    }
	}
    }

    loading_tbl = get_loading_table();
    if (loading_tbl) {
	f = 0;
	if (!expanded) {
	    struct loaded_feature_searching fs;
	    fs.name = feature;
	    fs.len = len;
	    fs.type = type;
	    fs.load_path = load_path ? load_path : rb_get_expanded_load_path();
	    fs.result = 0;
	    st_foreach(loading_tbl, loaded_feature_path_i, (st_data_t)&fs);
	    if ((f = fs.result) != 0) {
		if (fn) *fn = f;
		goto loading;
	    }
	}
	if (st_get_key(loading_tbl, (st_data_t)feature, &data)) {
	    if (fn) *fn = (const char*)data;
	  loading:
	    if (!ext) return 'u';
	    return !IS_RBEXT(ext) ? 's' : 'r';
	}
	else {
	    VALUE bufstr;
	    char *buf;
	    static const char so_ext[][4] = {
		".so", ".o",
	    };

	    if (ext && *ext) return 0;
	    bufstr = rb_str_tmp_new(len + DLEXT_MAXLEN);
	    buf = RSTRING_PTR(bufstr);
	    MEMCPY(buf, feature, char, len);
	    for (i = 0; (e = loadable_ext[i]) != 0; i++) {
		strlcpy(buf + len, e, DLEXT_MAXLEN + 1);
		if (st_get_key(loading_tbl, (st_data_t)buf, &data)) {
		    rb_str_resize(bufstr, 0);
		    if (fn) *fn = (const char*)data;
		    return i ? 's' : 'r';
		}
	    }
	    for (i = 0; i < numberof(so_ext); i++) {
		strlcpy(buf + len, so_ext[i], DLEXT_MAXLEN + 1);
		if (st_get_key(loading_tbl, (st_data_t)buf, &data)) {
		    rb_str_resize(bufstr, 0);
		    if (fn) *fn = (const char*)data;
		    return 's';
		}
	    }
	    rb_str_resize(bufstr, 0);
	}
    }
    return 0;
}
Beispiel #20
0
unsigned int rb_ary_len(VALUE x) {
  return RARRAY_LEN(x);
}
Beispiel #21
0
VALUE
rb_struct_alloc(VALUE klass, VALUE values)
{
    return rb_class_new_instance(RARRAY_LEN(values), RARRAY_PTR(values), klass);
}
Beispiel #22
0
Datei: rdo.c Projekt: d11wtq/rdo
/**
 * Takes String stmt, which contains ? markers and interpolates the values in Array params.
 *
 * Each value in Array params that is not NilClass, Fixnum or Float is passed
 * to #quote on the Driver.
 *
 * Non-numeric values are surrounded by String quote.
 *
 * @param VALUE (String) stmt
 *   SQL, possibly containining '?' markers.
 *
 * @param VALUE (Array) params
 *   arguments to interpolate in place of the ? markers
 *
 * @return VALUE (String)
 *   the same SQL with the parameters interpolated.
 */
static VALUE rdo_driver_interpolate(VALUE self, VALUE stmt, VALUE params) {
  Check_Type(stmt,   T_STRING);
  Check_Type(params, T_ARRAY);

  int  argc   = RARRAY_LEN(params);
  long buflen = 0;
  char ** quoted_params = rdo_driver_quote_params(
      self,
      RARRAY_PTR(params), argc,
      &buflen);
  char buffer[buflen + RSTRING_LEN(stmt) + 1];

  char * b = buffer;
  char * s = RSTRING_PTR(stmt);
  int    n = 0;

  int insquote = 0;
  int indquote = 0;
  int inmlcmt  = 0;
  int inslcmt  = 0;

  // this loop is intentionally kept procedural (for performance)
  for (; *s; ++s, ++b) {
    switch (*s) {
      case '\\':
        if (!insquote && !indquote && !inmlcmt && !inslcmt && *(s + 1) == '?')
          ++s;

        *b = *s;
        break;

      case '?':
        if (insquote || indquote || inmlcmt || inslcmt) {
          *b = *s;
        } else {
          if (n < argc) {
            strcpy(b, quoted_params[n]);
            b += strlen(quoted_params[n]) - 1;
          } else {
            *b = *s;
          }
          ++n;
        }
        break;

      case '-':
        if (!insquote && !indquote && !inmlcmt && *(s + 1) == '-') {
          inslcmt = 1;
          *(b++) = *(s++);
        }
        *b = *s;
        break;

      case '\r':
      case '\n':
        inslcmt = 0;
        *b = *s;
        break;

      case '/':
        if (!insquote && !indquote && !inslcmt && *(s + 1) == '*') {
          ++inmlcmt;
          *(b++) = *(s++);
        }
        *b = *s;
        break;

      case '*':
        if (inmlcmt && *(s + 1) == '/') {
          --inmlcmt;
          *(b++) = *(s++);
        }
        *b = *s;
        break;

      case '\'':
        if (!indquote && !inmlcmt && !inslcmt) insquote = !insquote;
        *b = *s;
        break;

      case '"':
        if (!insquote && !inmlcmt && !inslcmt) indquote = !indquote;
        *b = *s;
        break;

      default:
        *b = *s;
    }
  }

  *b = '\0';

  rdo_driver_free_params(quoted_params, argc);

  if (n != argc) {
    rb_raise(rb_eArgError,
        "Bind parameter mismatch (%i for %i) in query %s",
        argc, n, RSTRING_PTR(stmt));
  }

  return rb_str_new2(buffer);
}
Beispiel #23
0
VALUE method_empty(VALUE self) {
	return RARRAY_LEN(get_object_handle(self)->points) == 0 ? Qtrue : Qfalse;
}
Beispiel #24
0
/*
 * call-seq:
 *    ctx.setup => Qtrue # first time
 *    ctx.setup => nil # thereafter
 *
 * This method is called automatically when a new SSLSocket is created.
 * Normally you do not need to call this method (unless you are writing an extension in C).
 */
static VALUE
ossl_sslctx_setup(VALUE self)
{
    SSL_CTX *ctx;
    X509 *cert = NULL, *client_ca = NULL;
    X509_STORE *store;
    EVP_PKEY *key = NULL;
    char *ca_path = NULL, *ca_file = NULL;
    int i, verify_mode;
    VALUE val;

    if(OBJ_FROZEN(self)) return Qnil;
    Data_Get_Struct(self, SSL_CTX, ctx);

#if !defined(OPENSSL_NO_DH)
    if (RTEST(ossl_sslctx_get_tmp_dh_cb(self))){
	SSL_CTX_set_tmp_dh_callback(ctx, ossl_tmp_dh_callback);
    }
    else{
	SSL_CTX_set_tmp_dh_callback(ctx, ossl_default_tmp_dh_callback);
    }
#endif
    SSL_CTX_set_ex_data(ctx, ossl_ssl_ex_ptr_idx, (void*)self);

    val = ossl_sslctx_get_cert_store(self);
    if(!NIL_P(val)){
	/*
         * WORKAROUND:
	 *   X509_STORE can count references, but
	 *   X509_STORE_free() doesn't care it.
	 *   So we won't increment it but mark it by ex_data.
	 */
        store = GetX509StorePtr(val); /* NO NEED TO DUP */
        SSL_CTX_set_cert_store(ctx, store);
        SSL_CTX_set_ex_data(ctx, ossl_ssl_ex_store_p, (void*)1);
    }

    val = ossl_sslctx_get_extra_cert(self);
    if(!NIL_P(val)){
	rb_block_call(val, rb_intern("each"), 0, 0, ossl_sslctx_add_extra_chain_cert_i, self);
    }

    /* private key may be bundled in certificate file. */
    val = ossl_sslctx_get_cert(self);
    cert = NIL_P(val) ? NULL : GetX509CertPtr(val); /* NO DUP NEEDED */
    val = ossl_sslctx_get_key(self);
    key = NIL_P(val) ? NULL : GetPKeyPtr(val); /* NO DUP NEEDED */
    if (cert && key) {
        if (!SSL_CTX_use_certificate(ctx, cert)) {
            /* Adds a ref => Safe to FREE */
            ossl_raise(eSSLError, "SSL_CTX_use_certificate:");
        }
        if (!SSL_CTX_use_PrivateKey(ctx, key)) {
            /* Adds a ref => Safe to FREE */
            ossl_raise(eSSLError, "SSL_CTX_use_PrivateKey:");
        }
        if (!SSL_CTX_check_private_key(ctx)) {
            ossl_raise(eSSLError, "SSL_CTX_check_private_key:");
        }
    }

    val = ossl_sslctx_get_client_ca(self);
    if(!NIL_P(val)){
	if(TYPE(val) == T_ARRAY){
	    for(i = 0; i < RARRAY_LEN(val); i++){
		client_ca = GetX509CertPtr(RARRAY_PTR(val)[i]);
        	if (!SSL_CTX_add_client_CA(ctx, client_ca)){
		    /* Copies X509_NAME => FREE it. */
        	    ossl_raise(eSSLError, "SSL_CTX_add_client_CA");
        	}
	    }
        }
	else{
	    client_ca = GetX509CertPtr(val); /* NO DUP NEEDED. */
            if (!SSL_CTX_add_client_CA(ctx, client_ca)){
		/* Copies X509_NAME => FREE it. */
        	ossl_raise(eSSLError, "SSL_CTX_add_client_CA");
            }
	}
    }

    val = ossl_sslctx_get_ca_file(self);
    ca_file = NIL_P(val) ? NULL : StringValuePtr(val);
    val = ossl_sslctx_get_ca_path(self);
    ca_path = NIL_P(val) ? NULL : StringValuePtr(val);
    if(ca_file || ca_path){
	if (!SSL_CTX_load_verify_locations(ctx, ca_file, ca_path))
	    rb_warning("can't set verify locations");
    }

    val = ossl_sslctx_get_verify_mode(self);
    verify_mode = NIL_P(val) ? SSL_VERIFY_NONE : NUM2INT(val);
    SSL_CTX_set_verify(ctx, verify_mode, ossl_ssl_verify_callback);
    if (RTEST(ossl_sslctx_get_client_cert_cb(self)))
	SSL_CTX_set_client_cert_cb(ctx, ossl_client_cert_cb);

    val = ossl_sslctx_get_timeout(self);
    if(!NIL_P(val)) SSL_CTX_set_timeout(ctx, NUM2LONG(val));

    val = ossl_sslctx_get_verify_dep(self);
    if(!NIL_P(val)) SSL_CTX_set_verify_depth(ctx, NUM2LONG(val));

    val = ossl_sslctx_get_options(self);
    if(!NIL_P(val)) {
	SSL_CTX_set_options(ctx, NUM2LONG(val));
    } else {
	SSL_CTX_set_options(ctx, SSL_OP_ALL);
    }
    rb_obj_freeze(self);

    val = ossl_sslctx_get_sess_id_ctx(self);
    if (!NIL_P(val)){
	StringValue(val);
	if (!SSL_CTX_set_session_id_context(ctx, (unsigned char *)RSTRING_PTR(val),
					    RSTRING_LEN(val))){
	    ossl_raise(eSSLError, "SSL_CTX_set_session_id_context:");
	}
    }

    if (RTEST(rb_iv_get(self, "@session_get_cb"))) {
	SSL_CTX_sess_set_get_cb(ctx, ossl_sslctx_session_get_cb);
	OSSL_Debug("SSL SESSION get callback added");
    }
    if (RTEST(rb_iv_get(self, "@session_new_cb"))) {
	SSL_CTX_sess_set_new_cb(ctx, ossl_sslctx_session_new_cb);
	OSSL_Debug("SSL SESSION new callback added");
    }
    if (RTEST(rb_iv_get(self, "@session_remove_cb"))) {
	SSL_CTX_sess_set_remove_cb(ctx, ossl_sslctx_session_remove_cb);
	OSSL_Debug("SSL SESSION remove callback added");
    }

#ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
    val = rb_iv_get(self, "@servername_cb");
    if (!NIL_P(val)) {
        SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb);
	OSSL_Debug("SSL TLSEXT servername callback added");
    }
#endif

    return Qtrue;
}
Beispiel #25
0
/*
  Foo = NArray::Struct.new {
    int8     :byte
    float64  :float, [2,2]
    dcomplex :compl
  }
 */
static VALUE
nst_s_new(int argc, VALUE *argv, VALUE klass)
{
    VALUE name=Qnil, rest, size;
    VALUE st, members;
    ID id;

    rb_scan_args(argc, argv, "0*", &rest);
    if (RARRAY_LEN(rest)>0) {
        name = RARRAY_PTR(rest)[0];
        if (!NIL_P(name)) {
            VALUE tmp = rb_check_string_type(name);
            if (!NIL_P(tmp)) {
                rb_ary_shift(rest);
            } else {
                name = Qnil;
            }
        }
    }

    if (NIL_P(name)) {
        st = rb_class_new(klass);
        rb_make_metaclass(st, RBASIC(klass)->klass);
        rb_class_inherited(klass, st);
    }
    else {
        char *cname = StringValuePtr(name);
        id = rb_intern(cname);
        if (!rb_is_const_id(id)) {
            rb_name_error(id, "identifier %s needs to be constant", cname);
        }
        if (rb_const_defined_at(klass, id)) {
            rb_warn("redefining constant Struct::%s", cname);
            rb_mod_remove_const(klass, ID2SYM(id));
        }
        st = rb_define_class_under(klass, rb_id2name(id), klass);
    }

    rb_iv_set(st, "__members__", rb_ary_new());
    rb_iv_set(st, "__offset__", INT2FIX(0));

    if (rb_block_given_p()) {
        rb_mod_module_eval(0, 0, st);
    }

    size = rb_iv_get(st, "__offset__");
    members = rb_iv_get(st, "__members__");
    //printf("size=%d\n",NUM2INT(size));
    rb_define_const(st, CONTIGUOUS_STRIDE, size);
    rb_define_const(st, ELEMENT_BYTE_SIZE, size);
    rb_define_const(st, ELEMENT_BIT_SIZE,  rb_funcall(size,'*',1,INT2FIX(8)));

    OBJ_FREEZE(members);
    rb_define_const(st, "DEFINITIONS", members);

    rb_define_singleton_method(st, "new", rb_class_new_instance, -1);
    //rb_define_singleton_method(st, "[]", rb_class_new_instance, -1);
    rb_define_method(st, "allocate", nst_allocate, 0);

    return st;
}
Beispiel #26
0
void
rb_vm_bugreport(void)
{
    rb_vm_t *vm = GET_VM();
    if (vm) {
	int i = 0;
	SDR();

	if (rb_backtrace_each(bugreport_backtrace, &i)) {
	    fputs("\n", stderr);
	}
    }

#if HAVE_BACKTRACE || defined(_WIN32)
    fprintf(stderr, "-- C level backtrace information "
	    "-------------------------------------------\n");

    {
#if defined __MACH__ && defined __APPLE__
	fprintf(stderr, "\n");
	fprintf(stderr, "   See Crash Report log file under "
		"~/Library/Logs/CrashReporter or\n");
	fprintf(stderr, "   /Library/Logs/CrashReporter, for "
		"the more detail of.\n");
#elif HAVE_BACKTRACE
#define MAX_NATIVE_TRACE 1024
	static void *trace[MAX_NATIVE_TRACE];
	int n = backtrace(trace, MAX_NATIVE_TRACE);
	char **syms = backtrace_symbols(trace, n);

	if (syms) {
#ifdef USE_ELF
	    rb_dump_backtrace_with_lines(n, trace, syms);
#else
	    int i;
	    for (i=0; i<n; i++) {
		fprintf(stderr, "%s\n", syms[i]);
	    }
#endif
	    free(syms);
	}
#elif defined(_WIN32)
	DWORD tid = GetCurrentThreadId();
	HANDLE th = (HANDLE)_beginthread(dump_thread, 0, &tid);
	if (th != (HANDLE)-1)
	    WaitForSingleObject(th, INFINITE);
#endif
    }

    fprintf(stderr, "\n");
#endif /* HAVE_BACKTRACE */

    fprintf(stderr, "-- Other runtime information "
	    "-----------------------------------------------\n\n");
    {
	int i;

	fprintf(stderr, "* Loaded script: %s\n", StringValueCStr(vm->progname));
	fprintf(stderr, "\n");
	fprintf(stderr, "* Loaded features:\n\n");
	for (i=0; i<RARRAY_LEN(vm->loaded_features); i++) {
	    fprintf(stderr, " %4d %s\n", i, StringValueCStr(RARRAY_PTR(vm->loaded_features)[i]));
	}
	fprintf(stderr, "\n");

#if __linux__
	{
	    FILE *fp = fopen("/proc/self/maps", "r");
	    if (fp) {
		fprintf(stderr, "* Process memory map:\n\n");

		while (!feof(fp)) {
		    char buff[0x100];
		    size_t rn = fread(buff, 1, 0x100, fp);
		    fwrite(buff, 1, rn, stderr);
		}

		fclose(fp);
		fprintf(stderr, "\n\n");
	    }
	}
#endif /* __linux__ */
    }
}
Beispiel #27
0
static VALUE rb_gsl_math_eval2(double (*func)(const double, const double), VALUE xx,
			       VALUE yy)
{
  VALUE x, y, ary;
  size_t i, j, size;
  gsl_vector *v = NULL, *v2 = NULL, *vnew = NULL;
  gsl_matrix *m = NULL, *m2 = NULL, *mnew = NULL;
#ifdef HAVE_NARRAY_H
  struct NARRAY *nax, *nay;
  double *ptr1, *ptr2, *ptr3;
#endif
  if (CLASS_OF(xx) == rb_cRange) xx = rb_gsl_range2ary(xx);
  switch (TYPE(xx)) {
  case T_FIXNUM:
  case T_BIGNUM:
  case T_FLOAT:
    Need_Float(yy);
    return rb_float_new((*func)(NUM2DBL(xx), NUM2DBL(yy)));
    break;
  case T_ARRAY:
    Check_Type(yy, T_ARRAY);
    size = RARRAY_LEN(xx);
    if (size != RARRAY_LEN(yy)) rb_raise(rb_eRuntimeError, "array sizes are different.");
    ary = rb_ary_new2(size);
    for (i = 0; i < size; i++) {
      x = rb_ary_entry(xx, i);
      y = rb_ary_entry(yy, i);
      Need_Float(x); Need_Float(y);
      rb_ary_store(ary, i, rb_float_new((*func)(RFLOAT_VALUE(x), RFLOAT_VALUE(y))));
    }
    return ary;
    break;
  default:
#ifdef HAVE_NARRAY_H
    if (NA_IsNArray(xx)) {
      GetNArray(xx, nax);
      GetNArray(yy, nay);
      ptr1 = (double*) nax->ptr;
      ptr2 = (double*) nay->ptr;
      size = nax->total;
      ary = na_make_object(NA_DFLOAT, nax->rank, nax->shape, CLASS_OF(xx));
      ptr3 = NA_PTR_TYPE(ary, double*);
      for (i = 0; i < size; i++) ptr3[i] = (*func)(ptr1[i], ptr2[i]);
      return ary;
    }
#endif
    if (VECTOR_P(xx)) {
      CHECK_VECTOR(yy);
      Data_Get_Struct(xx, gsl_vector, v);
      Data_Get_Struct(yy, gsl_vector, v2);
      vnew = gsl_vector_alloc(v->size);
      for (i = 0; i < v->size; i++) {
	gsl_vector_set(vnew, i, (*func)(gsl_vector_get(v, i), gsl_vector_get(v2, i)));
      }
      return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, vnew);
    } else if (MATRIX_P(xx)) {
      CHECK_MATRIX(yy);
      Data_Get_Struct(xx, gsl_matrix, m);
      Data_Get_Struct(yy, gsl_matrix, m2);
      mnew = gsl_matrix_alloc(m->size1, m->size2);
      for (i = 0; i < m->size1; i++) {
	for (j = 0; j < m->size2; j++) {
	  gsl_matrix_set(mnew, i, j, (*func)(gsl_matrix_get(m, i, j), gsl_matrix_get(m2, i, j)));
	}
      }
      return Data_Wrap_Struct(cgsl_matrix, 0, gsl_matrix_free, mnew);
    } else {
      rb_raise(rb_eTypeError, 
	       "wrong argument type %s "
	       "(Array or Vector or Matrix expected)", rb_class2name(CLASS_OF(xx)));
    }
    break;
  }
  /* never reach here */
  return Qnil;
}
Beispiel #28
0
mrb_value
mrb_struct_initialize(mrb_state *mrb, mrb_value self, mrb_value values)
{
  return mrb_struct_initialize_withArg(mrb, RARRAY_LEN(values), RARRAY_PTR(values), self);
}
Beispiel #29
0
static VALUE tokenize_string(VALUE self, 
    VALUE string,
    VALUE tokens_to_find_indexes,
    VALUE tokens_to_find_strings,
    VALUE tokens_to_extract_indexes,
    VALUE tokens_to_extract_names)
{
  const char* input_string = StringValueCStr(string);
  VALUE extracted_tokens = rb_hash_new();
  VALUE curr_token;
  unsigned int curr_token_ix;
  long n_tokens_to_find = RARRAY_LEN(tokens_to_find_indexes);
  size_t str_len = strlen(input_string);
  size_t ix;
  char c;
  char looking_for;
  size_t looking_for_len;
  size_t looking_for_ix = 0;
  long find_ix = 0;
  const char*  looking_for_token;
  unsigned int n_tokens = (unsigned int)RARRAY_LEN(rb_iv_get(self, "@tokens"));

  size_t startpoint = 0;

  long n_tokens_to_extract = RARRAY_LEN(tokens_to_extract_indexes);
  long last_token_extracted_ix = 0;

  long next_token_to_extract_ix = NUM2UINT(rb_ary_entry(tokens_to_extract_indexes, last_token_extracted_ix));

  curr_token = rb_ary_entry(tokens_to_find_strings, find_ix);
  curr_token_ix = NUM2UINT(rb_ary_entry(tokens_to_find_indexes, find_ix));
  looking_for_token = StringValueCStr(curr_token);
  looking_for_len = strlen(looking_for_token);
  looking_for = looking_for_token[looking_for_ix];

  for(ix = 0; ix < str_len; ix++)
  {
    c = input_string[ix];
    if(c == looking_for)
    {
      if(looking_for_ix == 0)
      {
        /* entering new token */
        if(curr_token_ix > 0)
        {
          /* extract, if necessary */
          if((curr_token_ix - 1) == next_token_to_extract_ix)
          {
            last_token_extracted_ix++;
            if(last_token_extracted_ix < n_tokens_to_extract)
            {
              next_token_to_extract_ix = NUM2UINT(rb_ary_entry(tokens_to_extract_indexes, last_token_extracted_ix));
            }
            else
            {
              next_token_to_extract_ix = -1;
            }
            rb_hash_aset(extracted_tokens,
                rb_ary_entry(tokens_to_extract_names, curr_token_ix - 1),
                rb_usascii_str_new(input_string + startpoint,
                  ix - startpoint));
          }
        }
        startpoint = ix;
      }
      if(looking_for_ix >= looking_for_len - 1)
      {
        /* leaving token */
        if(curr_token_ix >= n_tokens-1)
        {
          break;
        }
        else
        {
          startpoint = ix + 1;
        }


        /* next token */
        find_ix++;
        if(find_ix >= n_tokens_to_find)
        {
          /* done! */
          break;
        }

        curr_token = rb_ary_entry(tokens_to_find_strings, find_ix);
        curr_token_ix = NUM2UINT(rb_ary_entry(tokens_to_find_indexes, find_ix));
        looking_for_token = StringValueCStr(curr_token);
        looking_for_len = strlen(looking_for_token);
        looking_for_ix = 0;
      }
      else
      {
        looking_for_ix++;
      }
      looking_for = looking_for_token[looking_for_ix];
    }
  }

  ix = str_len;
  curr_token_ix = n_tokens - 1;

  if(curr_token_ix == next_token_to_extract_ix)
  {
    rb_hash_aset(extracted_tokens,
        rb_ary_entry(tokens_to_extract_names, curr_token_ix),
        rb_usascii_str_new(input_string + startpoint,
          ix - startpoint));
  }

  return extracted_tokens;
}
Beispiel #30
0
VALUE
rb_ary_notempty_p( VALUE ary)
{
    return RARRAY_LEN( ary) == 0 ? Qnil : ary;
}