Пример #1
0
static VALUE read_anything(VALUE protocol, int ttype, VALUE field_info) {
  VALUE result = Qnil;

  if (ttype == TTYPE_BOOL) {
    result = mt->read_bool(protocol);
  } else if (ttype == TTYPE_BYTE) {
    result = mt->read_byte(protocol);
  } else if (ttype == TTYPE_I16) {
    result = mt->read_i16(protocol);
  } else if (ttype == TTYPE_I32) {
    result = mt->read_i32(protocol);
  } else if (ttype == TTYPE_I64) {
    result = mt->read_i64(protocol);
  } else if (ttype == TTYPE_STRING) {
    result = mt->read_string(protocol);
  } else if (ttype == TTYPE_DOUBLE) {
    result = mt->read_double(protocol);
  } else if (ttype == TTYPE_STRUCT) {
    VALUE klass = rb_hash_aref(field_info, class_sym);
    result = rb_class_new_instance(0, NULL, klass);

    if (rb_obj_is_kind_of(result, thrift_union_class)) {
      rb_thrift_union_read(result, protocol);
    } else {
      rb_thrift_struct_read(result, protocol);
    }
  } else if (ttype == TTYPE_MAP) {
    int i;

    VALUE map_header = mt->read_map_begin(protocol);
    int key_ttype = FIX2INT(rb_ary_entry(map_header, 0));
    int value_ttype = FIX2INT(rb_ary_entry(map_header, 1));
    int num_entries = FIX2INT(rb_ary_entry(map_header, 2));

    VALUE key_info = rb_hash_aref(field_info, key_sym);
    VALUE value_info = rb_hash_aref(field_info, value_sym);

    result = rb_hash_new();

    for (i = 0; i < num_entries; ++i) {
      VALUE key, val;

      key = read_anything(protocol, key_ttype, key_info);
      val = read_anything(protocol, value_ttype, value_info);

      rb_hash_aset(result, key, val);
    }

    mt->read_map_end(protocol);
  } else if (ttype == TTYPE_LIST) {
    int i;

    VALUE list_header = mt->read_list_begin(protocol);
    int element_ttype = FIX2INT(rb_ary_entry(list_header, 0));
    int num_elements = FIX2INT(rb_ary_entry(list_header, 1));
    result = rb_ary_new2(num_elements);

    for (i = 0; i < num_elements; ++i) {
      rb_ary_push(result, read_anything(protocol, element_ttype, rb_hash_aref(field_info, element_sym)));
    }

    mt->read_list_end(protocol);
  } else if (ttype == TTYPE_SET) {
    VALUE items;
    int i;

    VALUE set_header = mt->read_set_begin(protocol);
    int element_ttype = FIX2INT(rb_ary_entry(set_header, 0));
    int num_elements = FIX2INT(rb_ary_entry(set_header, 1));
    items = rb_ary_new2(num_elements);

    for (i = 0; i < num_elements; ++i) {
      rb_ary_push(items, read_anything(protocol, element_ttype, rb_hash_aref(field_info, element_sym)));
    }

    mt->read_set_end(protocol);

    result = rb_class_new_instance(1, &items, rb_cSet);
  } else {
    rb_raise(rb_eNotImpError, "read_anything not implemented for type %d!", ttype);
  }

  return result;
}
Пример #2
0
/*
 * This is a shortcut for Daemon.new + Daemon#mainloop.
 */
static VALUE daemon_c_mainloop(VALUE klass){
   VALUE v_args[1];
   VALUE v_daemon = rb_class_new_instance(0, v_args, klass);
   return rb_funcall(v_daemon, rb_intern("mainloop"), 0, 0);
}
Пример #3
0
///////////////////////////////////////////////////////////
// ARGSS Color create new instance
///////////////////////////////////////////////////////////
VALUE ARGSS::AColor::New() {
	VALUE args[4] = {rb_float_new(0), rb_float_new(0), rb_float_new(0), rb_float_new(255)};
	return rb_class_new_instance(4, args, id);
}
Пример #4
0
/*
 * call-seq:
 *     RbPod(mount_point) -> RbPod::Database
 *
 * A shortcut for creating an RbPod::Database instance from a mount point.
 *
 */
static VALUE rbpod_load_database(VALUE self, VALUE mount_point)
{
    return rb_class_new_instance(1, &mount_point, cRbPodDatabase);
}
Пример #5
0
VALUE rb_define_module_under(VALUE outer, const char *name) {
  VALUE mod = rb_class_new_instance(0, NULL, rb_cModule);
  rb_const_set(outer, rb_intern(name), mod);
  return mod;
}
Пример #6
0
VALUE
rb_dl_dlopen(int argc, VALUE argv[], VALUE self)
{
    return rb_class_new_instance(argc, argv, rb_cDLHandle);
}
Пример #7
0
VALUE
rb_struct_alloc(VALUE klass, VALUE values)
{
    return rb_class_new_instance(RARRAY_LENINT(values), RARRAY_PTR(values), klass);
}
Пример #8
0
	ruby_value 
	rb_tone_new(ruby_value tone) {
		return rb_class_new_instance(1, &tone, rb_cTone);
	}
Пример #9
0
	ruby_value
	rb_tone_new() {
		return rb_class_new_instance(0, NULL, rb_cTone);
	}
Пример #10
0
		VALUE FileWrapper::new_ruby_class_instance(void)
		{
			return rb_class_new_instance(0, nullptr, rb_rageFileClass);
		}
Пример #11
0
VALUE
rbffi_NativeValue_ToRuby(Type* type, VALUE rbType, const void* ptr, VALUE enums)
{
    switch (type->nativeType) {
        case NATIVE_VOID:
            return Qnil;
        case NATIVE_INT8:
          return INT2NUM((signed char) *(ffi_sarg *) ptr);
        case NATIVE_INT16:
          return INT2NUM((signed short) *(ffi_sarg *) ptr);
        case NATIVE_INT32:
          return INT2NUM((signed int) *(ffi_sarg *) ptr);
        case NATIVE_LONG:
            return LONG2NUM((signed long) *(ffi_sarg *) ptr);
        case NATIVE_INT64:
            return LL2NUM(*(signed long long *) ptr);

        case NATIVE_UINT8:
          return UINT2NUM((unsigned char) *(ffi_arg *) ptr);
        case NATIVE_UINT16:
          return UINT2NUM((unsigned short) *(ffi_arg *) ptr);
        case NATIVE_UINT32:
          return UINT2NUM((unsigned int) *(ffi_arg *) ptr);
        case NATIVE_ULONG:
            return ULONG2NUM((unsigned long) *(ffi_arg *) ptr);
        case NATIVE_UINT64:
            return ULL2NUM(*(unsigned long long *) ptr);

        case NATIVE_FLOAT32:
            return rb_float_new(*(float *) ptr);
        case NATIVE_FLOAT64:
            return rb_float_new(*(double *) ptr);
        case NATIVE_STRING:
            return (*(void **) ptr != NULL) ? rb_tainted_str_new2(*(char **) ptr) : Qnil;
        case NATIVE_POINTER:
            return rbffi_Pointer_NewInstance(*(void **) ptr);
        case NATIVE_BOOL:
            return ((unsigned char) *(ffi_arg *) ptr) ? Qtrue : Qfalse;
        
        case NATIVE_FUNCTION:
        case NATIVE_CALLBACK: {
            return *(void **) ptr != NULL 
                    ? rbffi_Function_NewInstance(rbType, rbffi_Pointer_NewInstance(*(void **) ptr))
                    : Qnil;
        }

        case NATIVE_STRUCT: {
            StructByValue* sbv = (StructByValue *)type;
            AbstractMemory* mem;
            VALUE rbMemory = rbffi_MemoryPointer_NewInstance(1, sbv->base.ffiType->size, false);

            Data_Get_Struct(rbMemory, AbstractMemory, mem);
            memcpy(mem->address, ptr, sbv->base.ffiType->size);

            return rb_class_new_instance(1, &rbMemory, sbv->rbStructClass);
        }

        case NATIVE_MAPPED: {
            // For mapped types, first convert to the real native type, then upcall to
            // ruby to convert to the expected return type
            MappedType* m;
            VALUE values[2];

            Data_Get_Struct(rbType, MappedType, m);
            values[0] = rbffi_NativeValue_ToRuby(m->type, m->rbType, ptr, enums);
            values[1] = Qnil;

            return rb_funcall2(m->rbConverter, id_from_native, 2, values);
        }
    
        default:
            rb_raise(rb_eRuntimeError, "Unknown type: %d", type->nativeType);
            return Qnil;
    }
}
Пример #12
0
VALUE
rb_syserr_new_str(int n, VALUE arg)
{
    return rb_class_new_instance(1, &arg, get_syserr(n));
}
Пример #13
0
static VALUE
Font_s_new(int argc, VALUE* argv, VALUE self)
{
  volatile VALUE rbPath, rbSize, rbOptions;
  rb_scan_args(argc, argv, "21", &rbPath, &rbSize, &rbOptions);
  if (NIL_P(rbOptions)) {
    rbOptions = rb_hash_new();
  }
  volatile VALUE rbRealFilePath;
  int preTtcIndex = -1;
  SearchFont(rbPath, (VALUE*)&rbRealFilePath, &preTtcIndex);
  if (NIL_P(rbRealFilePath)) {
    char* path = StringValueCStr(rbPath);
    rb_raise(rb_path2class("Errno::ENOENT"), "%s", path);
    return Qnil;
  }
  int size = NUM2INT(rbSize);
  bool bold = false;
  bool italic = false;
  int ttcIndex = 0;
  volatile VALUE val;
  Check_Type(rbOptions, T_HASH);
  if (!NIL_P(val = rb_hash_aref(rbOptions, symbol_bold))) {
    bold = RTEST(val);
  }
  if (!NIL_P(val = rb_hash_aref(rbOptions, symbol_italic))) {
    italic = RTEST(val);
  }
  if (preTtcIndex != -1) {
    ttcIndex = preTtcIndex;
  } else if (!NIL_P(val = rb_hash_aref(rbOptions, symbol_ttc_index))) {
    ttcIndex = NUM2INT(val);
  }
  volatile VALUE rbHashKey = rb_str_dup(rbRealFilePath);  
  char temp[256];
  // TODO: change the delimiter or the way to name a hash key
  rb_str_cat2(rbHashKey, ";size=");
  snprintf(temp, sizeof(temp), "%d", size);
  rb_str_cat2(rbHashKey, temp);
  if (bold) {
    rb_str_cat2(rbHashKey, ";bold=true");
  } else {
    rb_str_cat2(rbHashKey, ";bold=false");
  }
  if (italic) {
    rb_str_cat2(rbHashKey, ";italic=true");
  } else {
    rb_str_cat2(rbHashKey, ";italic=false");
  }
  rb_str_cat2(rbHashKey, ";ttc_index=");
  snprintf(temp, sizeof(temp), "%d", ttcIndex);
  rb_str_cat2(rbHashKey, temp);

  if (!NIL_P(val = rb_hash_aref(rbFontCache, rbHashKey))) {
    return val;
  } else {
    VALUE args[] = {
      rbRealFilePath,
      rbSize,
      bold ? Qtrue : Qfalse,
      italic ? Qtrue : Qfalse,
      INT2NUM(ttcIndex),
    };
    volatile VALUE rbNewFont =
      rb_class_new_instance(sizeof(args) / sizeof(VALUE), args, self);
    rb_hash_aset(rbFontCache, rbHashKey, rbNewFont);
    return rbNewFont;
  }
}
Пример #14
0
static VALUE dh_new(VALUE device)
{
  return rb_class_new_instance(1, &device, cDeviceHandle);
}
Пример #15
0
static VALUE rd_attr_loc_list(VALUE self)
{
    rd_attr_t *attr = GetAttr(self);
    Dwarf_Error err;
    Dwarf_Loc_Head_c loc_head;
    Dwarf_Unsigned count;
    VALUE lhead;
    Dwarf_Unsigned idx;

    chkerr1(dwarf_get_loclist_c(attr->attr, &loc_head, &count, &err), &err, self);
    lhead = rb_ary_new_capa(count);
    for (idx = 0; idx < count; idx++) {
        Dwarf_Small lle;
        Dwarf_Addr lowpc;
        Dwarf_Addr hipc;
        Dwarf_Unsigned loclist_count;
        Dwarf_Locdesc_c locentry;
        Dwarf_Small source;
        Dwarf_Unsigned expression_offset;
        Dwarf_Unsigned locdesc_offset;
        ID id_lle;
        ID id_lowpc;
        ID id_hipc;
        ID id_source;
        ID id_expression_offset;
        ID id_locdesc_offset;
        VALUE llist;
        int idx2;

        CONST_ID(id_lle, "@lle");
        CONST_ID(id_lowpc, "@lowpc");
        CONST_ID(id_hipc, "@hipc");
        CONST_ID(id_source, "@source");
        CONST_ID(id_expression_offset, "@expression_offset");
        CONST_ID(id_locdesc_offset, "@locdesc_offset");

        chkerr1(dwarf_get_locdesc_entry_c(loc_head, idx, &lle, &lowpc, &hipc,
                                          &loclist_count, &locentry, &source,
                                          &expression_offset, &locdesc_offset, &err),
                &err, self);
        llist = rb_class_new_instance(0, NULL, rd_cLocList);
        rb_ivar_set(llist, id_lle, rb_hash_aref(rdwarf_lle2name, INT2FIX(lle)));
        rb_ivar_set(llist, id_lowpc, ULL2NUM(lowpc));
        rb_ivar_set(llist, id_hipc, ULL2NUM(hipc));
        rb_ivar_set(llist, id_source, INT2FIX(source));
        rb_ivar_set(llist, id_expression_offset, ULL2NUM(expression_offset));
        rb_ivar_set(llist, id_locdesc_offset, ULL2NUM(locdesc_offset));
        for (idx2 = 0; idx2 < loclist_count; idx2++) {
            Dwarf_Small atom;
            Dwarf_Unsigned operand1;
            Dwarf_Unsigned operand2;
            Dwarf_Unsigned operand3;
            Dwarf_Unsigned offset_for_branch;
            ID id_atom;
            ID id_operand1;
            ID id_operand2;
            ID id_operand3;
            ID id_offset_for_branch;
            VALUE ldesc;

            CONST_ID(id_atom, "@atom");
            CONST_ID(id_operand1, "@operand1");
            CONST_ID(id_operand2, "@operand2");
            CONST_ID(id_operand3, "@operand3");
            CONST_ID(id_offset_for_branch, "@offset_for_branch");

            chkerr1(dwarf_get_location_op_value_c(locentry, idx2, &atom, &operand1, &operand2, &operand3, &offset_for_branch, &err),
                    &err, self);
            ldesc = rb_class_new_instance(0, NULL, rd_cLocDesc);
            rb_ivar_set(ldesc, id_atom, rb_hash_aref(rdwarf_op2name, INT2FIX(atom)));
            rb_ivar_set(ldesc, id_operand1, ULL2NUM(operand1));
            rb_ivar_set(ldesc, id_operand2, ULL2NUM(operand2));
            rb_ivar_set(ldesc, id_operand3, ULL2NUM(operand3));
            rb_ivar_set(ldesc, id_offset_for_branch, ULL2NUM(offset_for_branch));
            rb_ary_store(llist, idx2, ldesc);
        }
        rb_ary_store(lhead, idx, llist);
    }
    dwarf_loc_head_c_dealloc(loc_head);
    return lhead;
}
Пример #16
0
static VALUE zkrb_new_instance(VALUE args) {
    return rb_class_new_instance(2, (VALUE*)args+1, *(VALUE*)args);
}
Пример #17
0
VALUE
bpObjectToRuby(const bp::Object * obj,
               unsigned int tid)
{
    if (obj == NULL) return Qnil;

    VALUE v = Qnil;

    switch (obj->type()) {
        case BPTNull:
            v = Qnil;
            break;
        case BPTBoolean:
        {
            if (((bp::Bool *) obj)->value()) v = Qtrue;
            else v = Qfalse;
            break;
        }
        case BPTInteger:
            v = rb_ull2inum(((bp::Integer *) obj)->value());
            break;
        case BPTCallBack: {
            VALUE args[2];
            args[0] = rb_uint2inum(tid);
            args[1] = rb_ull2inum(((bp::Integer *) obj)->value());
            v = rb_class_new_instance(2, args, bp_rb_cCallback);
            break;
        }           
        case BPTDouble:
            v = rb_float_new(((bp::Double *) obj)->value());
            break;
        case BPTString:
            v = rb_str_new2(((bp::String *) obj)->value());
            break;
        case BPTNativePath: {
            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)
            {
				std::string path = convert::toUTF8(((bp::Path *) obj)->value());
                VALUE p = rb_str_new2(path.c_str());
                v = rb_class_new_instance(1, &p, klass);
            }
            break;
        }
        case BPTMap: 
        {
            bp::Map * m = (bp::Map *) obj;
            v = rb_hash_new();
            bp::Map::Iterator i(*m);
            const char * key;
            while (NULL != (key = i.nextKey())) {
                rb_hash_aset(v,ID2SYM(rb_intern(key)), 
                             bpObjectToRuby(m->value(key), tid));
            }
            
            break;
        }
        
        case BPTList: 
        {
            bp::List * l = (bp::List *) obj;

            v = rb_ary_new();
            
            unsigned int i;
            for (i=0; i < l->size(); i++) {
                rb_ary_push(v, bpObjectToRuby(l->value(i), tid));
            }
            
            break;
        }
        case BPTAny: 
            // invalid
            break;
    }
    
    return v;
}
Пример #18
0
static VALUE read_anything(VALUE protocol, int ttype, VALUE field_info) {
  VALUE result = Qnil;

  if (ttype == TTYPE_BOOL) {
    result = default_read_bool(protocol);
  } else if (ttype == TTYPE_BYTE) {
    result = default_read_byte(protocol);
  } else if (ttype == TTYPE_I16) {
    result = default_read_i16(protocol);
  } else if (ttype == TTYPE_I32) {
    result = default_read_i32(protocol);
  } else if (ttype == TTYPE_I64) {
    result = default_read_i64(protocol);
  } else if (ttype == TTYPE_STRING) {
    result = default_read_string(protocol);
  } else if (ttype == TTYPE_DOUBLE) {
    result = default_read_double(protocol);
  } else if (ttype == TTYPE_STRUCT) {
    VALUE klass = rb_hash_aref(field_info, class_sym);
    result = rb_class_new_instance(0, NULL, klass);

    if (rb_obj_is_kind_of(result, thrift_union_class)) {
      rb_thrift_union_read(result, protocol);
    } else {
      rb_thrift_struct_read(result, protocol);
    }
  } else if (ttype == TTYPE_MAP) {
    int i;

    VALUE map_header = default_read_map_begin(protocol);
    int key_ttype = FIX2INT(rb_ary_entry(map_header, 0));
    int value_ttype = FIX2INT(rb_ary_entry(map_header, 1));
    int num_entries = FIX2INT(rb_ary_entry(map_header, 2));

    // Check the declared key and value types against the expected ones and skip the map contents
    // if the types don't match.
    VALUE key_info = rb_hash_aref(field_info, key_sym);
    VALUE value_info = rb_hash_aref(field_info, value_sym);

    if (!NIL_P(key_info) && !NIL_P(value_info)) {
      int specified_key_type = FIX2INT(rb_hash_aref(key_info, type_sym));
      int specified_value_type = FIX2INT(rb_hash_aref(value_info, type_sym));
      if (num_entries == 0 || (specified_key_type == key_ttype && specified_value_type == value_ttype)) {
        result = rb_hash_new();

        for (i = 0; i < num_entries; ++i) {
          VALUE key, val;

          key = read_anything(protocol, key_ttype, key_info);
          val = read_anything(protocol, value_ttype, value_info);

          rb_hash_aset(result, key, val);
        }
      } else {
        skip_map_contents(protocol, INT2FIX(key_ttype), INT2FIX(value_ttype), num_entries);
      }
    } else {
      skip_map_contents(protocol, INT2FIX(key_ttype), INT2FIX(value_ttype), num_entries);
    }

    default_read_map_end(protocol);
  } else if (ttype == TTYPE_LIST) {
    int i;

    VALUE list_header = default_read_list_begin(protocol);
    int element_ttype = FIX2INT(rb_ary_entry(list_header, 0));
    int num_elements = FIX2INT(rb_ary_entry(list_header, 1));

    // Check the declared element type against the expected one and skip the list contents
    // if the types don't match.
    VALUE element_info = rb_hash_aref(field_info, element_sym);
    if (!NIL_P(element_info)) {
      int specified_element_type = FIX2INT(rb_hash_aref(element_info, type_sym));
      if (specified_element_type == element_ttype) {
        result = rb_ary_new2(num_elements);

        for (i = 0; i < num_elements; ++i) {
          rb_ary_push(result, read_anything(protocol, element_ttype, rb_hash_aref(field_info, element_sym)));
        }
      } else {
        skip_list_or_set_contents(protocol, INT2FIX(element_ttype), num_elements);
      }
    } else {
      skip_list_or_set_contents(protocol, INT2FIX(element_ttype), num_elements);
    }

    default_read_list_end(protocol);
  } else if (ttype == TTYPE_SET) {
    VALUE items;
    int i;

    VALUE set_header = default_read_set_begin(protocol);
    int element_ttype = FIX2INT(rb_ary_entry(set_header, 0));
    int num_elements = FIX2INT(rb_ary_entry(set_header, 1));

    // Check the declared element type against the expected one and skip the set contents
    // if the types don't match.
    VALUE element_info = rb_hash_aref(field_info, element_sym);
    if (!NIL_P(element_info)) {
      int specified_element_type = FIX2INT(rb_hash_aref(element_info, type_sym));
      if (specified_element_type == element_ttype) {
        items = rb_ary_new2(num_elements);

        for (i = 0; i < num_elements; ++i) {
          rb_ary_push(items, read_anything(protocol, element_ttype, rb_hash_aref(field_info, element_sym)));
        }

        result = rb_class_new_instance(1, &items, rb_cSet);
      } else {
        skip_list_or_set_contents(protocol, INT2FIX(element_ttype), num_elements);
      }
    } else {
      skip_list_or_set_contents(protocol, INT2FIX(element_ttype), num_elements);
    }

    default_read_set_end(protocol);
  } else {
    rb_raise(rb_eNotImpError, "read_anything not implemented for type %d!", ttype);
  }

  return result;
}
Пример #19
0
static VALUE rrrd_rrd_fetch(int argc, VALUE *argv, VALUE self) {
  VALUE function, options;
  VALUE resolution, starts_at, ends_at;

  rb_scan_args(argc, argv, "11", &function, &options);

  list arguments = rrrd_list_new();
  rrrd_add_filename_arg(self, &arguments);

  // consolidation function
  function = rb_str_new2(rb_id2name(rb_to_id(function)));
  function = rb_funcall(function, rb_intern("upcase"), 0);
  rrrd_add_arg(&arguments, STR2CSTR(function));

  if (RTEST(options)) {
    // extract options from hash
    resolution = rb_hash_aref(options, ID2SYM(rb_intern("resolution")));
    starts_at = rb_hash_aref(options, ID2SYM(rb_intern("starts_at")));
    ends_at = rb_hash_aref(options, ID2SYM(rb_intern("ends_at")));

    // resolution
    if (RTEST(resolution)) {
      resolution = rb_fix2str(resolution, 10);

      rrrd_add_arg(&arguments, "--resolution");
      rrrd_add_arg(&arguments, STR2CSTR(resolution));
    }

    // start time
    if (RTEST(starts_at)) {
      starts_at = rb_funcall(starts_at, rb_intern("to_i"), 0);
      starts_at = rb_fix2str(starts_at, 10);

      rrrd_add_arg(&arguments, "--start");
      rrrd_add_arg(&arguments, STR2CSTR(starts_at));
    }

    // end time
    if (RTEST(ends_at)) {
      ends_at = rb_funcall(ends_at, rb_intern("to_i"), 0);
      ends_at = rb_fix2str(ends_at, 10);

      rrrd_add_arg(&arguments, "--end");
      rrrd_add_arg(&arguments, STR2CSTR(ends_at));
    }
  }

  time_t start, end;
  unsigned long step, ds_count;
  char **raw_names;
  rrd_value_t *raw_data;

  rrd_fetch(arguments.length, arguments.strings, &start, &end, &step, &ds_count, &raw_names, &raw_data);
  rrrd_free_arguments(arguments);
  rrrd_check_for_errors();

  int i;
  int index = 0;
  VALUE data = rb_ary_new();

  for (i = start + step; i <= end; i+= step) {
    int j;
    VALUE timestamp = rb_time_new(i, 0);
    VALUE values = rb_hash_new();

    for (j = 0; j < ds_count; j++) {
      VALUE key = ID2SYM(rb_intern(raw_names[j]));
      rb_hash_aset(values, key, rb_float_new(raw_data[index++]));
    }

    VALUE args[] = { timestamp, values };
    VALUE tuple = rb_class_new_instance(2, args, Tuple);

    rb_ary_push(data, tuple);
  }

  free(raw_data);

  return data;
}
Пример #20
0
VALUE
rb_struct_alloc(VALUE klass, VALUE values)
{
    return rb_class_new_instance(RARRAY(values)->len, RARRAY(values)->ptr, klass);
}
Пример #21
0
Файл: ruby.c Проект: ayumin/ruby
static void
process_sflag(int *sflag)
{
    if (*sflag > 0) {
	long n;
	VALUE *args;
	VALUE argv = rb_argv;

	n = RARRAY_LEN(argv);
	args = RARRAY_PTR(argv);
	while (n > 0) {
	    VALUE v = *args++;
	    char *s = StringValuePtr(v);
	    char *p;
	    int hyphen = FALSE;

	    if (s[0] != '-')
		break;
	    n--;
	    if (s[1] == '-' && s[2] == '\0')
		break;

	    v = Qtrue;
	    /* check if valid name before replacing - with _ */
	    for (p = s + 1; *p; p++) {
		if (*p == '=') {
		    *p++ = '\0';
		    v = rb_str_new2(p);
		    break;
		}
		if (*p == '-') {
		    hyphen = TRUE;
		}
		else if (*p != '_' && !ISALNUM(*p)) {
		    VALUE name_error[2];
		    name_error[0] =
			rb_str_new2("invalid name for global variable - ");
		    if (!(p = strchr(p, '='))) {
			rb_str_cat2(name_error[0], s);
		    }
		    else {
			rb_str_cat(name_error[0], s, p - s);
		    }
		    name_error[1] = args[-1];
		    rb_exc_raise(rb_class_new_instance(2, name_error, rb_eNameError));
		}
	    }
	    s[0] = '$';
	    if (hyphen) {
		for (p = s + 1; *p; ++p) {
		    if (*p == '-')
			*p = '_';
		}
	    }
	    rb_gv_set(s, v);
	}
	n = RARRAY_LEN(argv) - n;
	while (n--) {
	    rb_ary_shift(argv);
	}
	*sflag = -1;
    }
}
Пример #22
0
static VALUE ov_http_client_submit(VALUE self, VALUE request) {
    CURL* handle;
    VALUE response;
    VALUE transfer;
    ov_http_client_object* ptr;
    ov_http_request_object* request_ptr;
    ov_http_transfer_object* transfer_ptr;
    struct curl_slist* headers;

    /* Get the pointer to the native object and check that it isn't closed: */
    ov_http_client_ptr(self, ptr);
    ov_http_client_check_closed(ptr);

    /* Check the type of request and get the pointer to the native object: */
    if (NIL_P(request)) {
        rb_raise(ov_error_class, "The 'request' parameter can't be nil");
    }
    if (!rb_obj_is_instance_of(request, ov_http_request_class)) {
        rb_raise(ov_error_class, "The 'request' parameter isn't an instance of class 'HttpRequest'");
    }
    ov_http_request_ptr(request, request_ptr);

    /* Create the libcurl easy handle: */
    handle = curl_easy_init();
    if (ptr->handle == NULL) {
        rb_raise(ov_error_class, "Can't create libcurl object");
    }

    /* The headers used by the libcurl easy handle can't be released till the handle is released itself, so we need
       to initialize here, and add it to the context so that we can release it later: */
    headers = NULL;

    /* Configure the libcurl easy handle with the data from the client and from the request: */
    ov_http_client_prepare_handle(ptr, request_ptr, &headers, handle);

    /* Allocate a ne empty response: */
    response = rb_class_new_instance(0, NULL, ov_http_response_class);

    /* Allocate a new empty transfer: */
    transfer = rb_class_new_instance(0, NULL, ov_http_transfer_class);
    ov_http_transfer_ptr(transfer, transfer_ptr);
    transfer_ptr->client = self;
    transfer_ptr->request = request;
    transfer_ptr->response = response;
    transfer_ptr->headers = headers;
    transfer_ptr->cancel = false;
    if (NIL_P(request_ptr->body)) {
        transfer_ptr->in = rb_class_new_instance(0, NULL, STRING_IO_CLASS);
    }
    else {
        transfer_ptr->in = rb_class_new_instance(1, &request_ptr->body, STRING_IO_CLASS);
    }
    transfer_ptr->out = rb_class_new_instance(0, NULL, STRING_IO_CLASS);

    /* Put the request and the transfer in the hash of pending transfers: */
    rb_hash_aset(ptr->pending, request, transfer);

    /* Set the transfer as the data for all the callbacks, so we can access it from any place where it is needed: */
    curl_easy_setopt(handle, CURLOPT_PRIVATE, transfer);
    curl_easy_setopt(handle, CURLOPT_READDATA, transfer);
    curl_easy_setopt(handle, CURLOPT_WRITEDATA, transfer);
    curl_easy_setopt(handle, CURLOPT_HEADERDATA, transfer);
    curl_easy_setopt(handle, CURLOPT_DEBUGDATA, transfer);

    /* Add the easy handle to the multi handle: */
    curl_multi_add_handle(ptr->handle, handle);

    return Qnil;
}
Пример #23
0
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super) {
  VALUE mod = rb_class_new_instance(1, &super, rb_cClass);
  rb_const_set(outer, rb_intern(name), mod);
  return mod;
}
Пример #24
0
static void* ov_http_client_complete_task(void* data) {
    CURLM* handle;
    CURLMsg* message;
    VALUE error_class;
    VALUE error_instance;
    VALUE transfer;
    long code;
    ov_http_client_object* client_ptr;
    ov_http_request_object* request_ptr;
    ov_http_response_object* response_ptr;
    ov_http_transfer_object* transfer_ptr;

    /* The passed pointer is the libcurl message describing the completed transfer: */
    message = (CURLMsg*) data;
    handle = message->easy_handle;

    /* The transfer is stored as the private data of the libcurl easy handle: */
    curl_easy_getinfo(handle, CURLINFO_PRIVATE, &transfer);

    /* Get the pointers to the transfer, client and response: */
    ov_http_transfer_ptr(transfer, transfer_ptr);
    ov_http_client_ptr(transfer_ptr->client, client_ptr);
    ov_http_request_ptr(transfer_ptr->request, request_ptr);
    ov_http_response_ptr(transfer_ptr->response, response_ptr);

    /* Remove the transfer from the pending hash: */
    rb_hash_delete(client_ptr->pending, transfer_ptr->request);

    if (message->data.result == CURLE_OK) {
        /* Copy the response code and the response body to the response object: */
        curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &code);
        response_ptr->code = LONG2NUM(code);
        response_ptr->body = rb_funcall(transfer_ptr->out, STRING_ID, 0);

        /* Put the request and the response in the completed transfers hash: */
        rb_hash_aset(client_ptr->completed, transfer_ptr->request, transfer_ptr->response);

        /* Send a summary of the response to the log: */
        ov_http_client_log_info(
            client_ptr->log,
            "Received response code %"PRIsVALUE" for %"PRIsVALUE" request to URL '%"PRIsVALUE"'.",
            response_ptr->code,
            request_ptr->method,
            request_ptr->url
        );
    }
    else {
        /* Select the error class according to the kind of error returned by libcurl: */
        switch (message->data.result) {
        case CURLE_COULDNT_CONNECT:
        case CURLE_COULDNT_RESOLVE_HOST:
        case CURLE_COULDNT_RESOLVE_PROXY:
            error_class = ov_connection_error_class;
            break;
        case CURLE_OPERATION_TIMEDOUT:
            error_class = ov_timeout_error_class;
            break;
        default:
            error_class = ov_error_class;
        }

        /* Put the request and error in the completed transfers hash: */
        error_instance = rb_sprintf("Can't send request: %s", curl_easy_strerror(message->data.result));
        error_instance = rb_class_new_instance(1, &error_instance, error_class);
        rb_hash_aset(client_ptr->completed, transfer_ptr->request, error_instance);
    }

    /* Now that the libcurl easy handle is released, we can release the headers as well: */
    curl_slist_free_all(transfer_ptr->headers);

    return NULL;
}
Пример #25
0
void Nokogiri_marshal_xpath_funcall_and_return_values(xmlXPathParserContextPtr ctx, int nargs, VALUE handler, const char* function_name)
{
  int i;
  VALUE result, doc;
  VALUE *argv;
  VALUE node_set = Qnil;
  xmlNodeSetPtr xml_node_set = NULL;
  xmlXPathObjectPtr obj;

  assert(ctx->context->doc);
  assert(DOC_RUBY_OBJECT_TEST(ctx->context->doc));

  argv = (VALUE *)calloc((size_t)nargs, sizeof(VALUE));
  for (i = 0 ; i < nargs ; ++i) {
    rb_gc_register_address(&argv[i]);
  }

  doc = DOC_RUBY_OBJECT(ctx->context->doc);

  if (nargs > 0) {
    i = nargs - 1;
    do {
      obj = valuePop(ctx);
      switch(obj->type) {
        case XPATH_STRING:
          argv[i] = NOKOGIRI_STR_NEW2(obj->stringval);
          break;
        case XPATH_BOOLEAN:
          argv[i] = obj->boolval == 1 ? Qtrue : Qfalse;
          break;
        case XPATH_NUMBER:
          argv[i] = rb_float_new(obj->floatval);
          break;
        case XPATH_NODESET:
          argv[i] = Nokogiri_wrap_xml_node_set(obj->nodesetval, doc);
          break;
        default:
          argv[i] = NOKOGIRI_STR_NEW2(xmlXPathCastToString(obj));
      }
      xmlXPathFreeNodeSetList(obj);
    } while(i-- > 0);
  }

  result = rb_funcall2(handler, rb_intern((const char*)function_name), nargs, argv);

  for (i = 0 ; i < nargs ; ++i) {
    rb_gc_unregister_address(&argv[i]);
  }
  free(argv);

  switch(TYPE(result)) {
    case T_FLOAT:
    case T_BIGNUM:
    case T_FIXNUM:
      xmlXPathReturnNumber(ctx, NUM2DBL(result));
      break;
    case T_STRING:
      xmlXPathReturnString(
          ctx,
          xmlCharStrdup(StringValuePtr(result))
      );
      break;
    case T_TRUE:
      xmlXPathReturnTrue(ctx);
      break;
    case T_FALSE:
      xmlXPathReturnFalse(ctx);
      break;
    case T_NIL:
      break;
    case T_ARRAY:
      {
        VALUE args[2];
        args[0] = doc;
        args[1] = result;
        node_set = rb_class_new_instance(2, args, cNokogiriXmlNodeSet);
        Data_Get_Struct(node_set, xmlNodeSet, xml_node_set);
        xmlXPathReturnNodeSet(ctx, xmlXPathNodeSetMerge(NULL, xml_node_set));
      }
    break;
    case T_DATA:
      if(rb_obj_is_kind_of(result, cNokogiriXmlNodeSet)) {
        Data_Get_Struct(result, xmlNodeSet, xml_node_set);
        /* Copy the node set, otherwise it will get GC'd. */
        xmlXPathReturnNodeSet(ctx, xmlXPathNodeSetMerge(NULL, xml_node_set));
        break;
      }
    default:
      rb_raise(rb_eRuntimeError, "Invalid return type");
    }
}
Пример #26
0
/*
 * call-seq:
 *   list_cache([cache_name]) -> array
 *
 * Call krb5_cc_next_cred to fetch credentials from a cachefile.  With no parameters, it fetches the credentials in the default cachefile.  With one parameter, it fetches the credentials in the named cachefile.  Returns a list of Krb5Auth::Krb5::Cred objects on success, raises Krb5Auth::Krb5::Exception on failure.
 */
static VALUE Krb5_list_cache_creds(int argc, VALUE *argv, VALUE self)
{
  VALUE cache_val;
  struct ruby_krb5 *kerb;
  krb5_error_code krbret;
  char *cache_name;
  krb5_ccache cc;
  krb5_cc_cursor cur;
  krb5_creds creds;
  char *name;
  char *sname;
  krb5_ticket *tkt;
  VALUE result;
  VALUE line;

  rb_scan_args(argc, argv, "01", &cache_val);

  cache_name = get_string_or_nil(cache_val);

  Data_Get_Struct(self, struct ruby_krb5, kerb);
  if (!kerb) {
    NOSTRUCT_EXCEPT();
    return Qfalse;
  }

  if (cache_name == NULL) {
    krbret = krb5_cc_default(kerb->ctx, &cc);
  }
  else {
    krbret = krb5_cc_resolve(kerb->ctx, cache_name, &cc);
  }

  if (krbret) {
    goto cache_fail_raise;
  }

  krbret = krb5_cc_start_seq_get(kerb->ctx, cc, &cur);
  if (krbret) {
    goto cache_fail_close;
  }

  result = rb_ary_new();
  while (!(krbret = krb5_cc_next_cred(kerb->ctx, cc, &cur, &creds))) {
    krbret = krb5_unparse_name(kerb->ctx, creds.client, &name);
    if (krbret) {
      krb5_free_cred_contents(kerb->ctx, &creds);
      break;
    }
    krbret = krb5_unparse_name(kerb->ctx, creds.server, &sname);
    if (krbret) {
      free(name);
      krb5_free_cred_contents(kerb->ctx, &creds);
      break;
    }
    krbret = krb5_decode_ticket(&creds.ticket, &tkt);
    if (krbret) {
      free(sname);
      free(name);
      krb5_free_cred_contents(kerb->ctx, &creds);
      break;
    }
    line = rb_class_new_instance(0, NULL, cCred);
    rb_iv_set(line, "@client", rb_str_new2(name));
    rb_iv_set(line, "@server", rb_str_new2(sname));
    rb_iv_set(line, "@starttime", INT2NUM(creds.times.starttime));
    rb_iv_set(line, "@authtime", INT2NUM(creds.times.authtime));
    rb_iv_set(line, "@endtime", INT2NUM(creds.times.endtime));
    rb_iv_set(line, "@ticket_flags", INT2NUM(creds.ticket_flags));
    rb_iv_set(line, "@cred_enctype", INT2NUM(creds.keyblock.enctype));
    rb_iv_set(line, "@ticket_enctype", INT2NUM(tkt->enc_part.enctype));
    rb_ary_push(result, line);
    krb5_free_ticket(kerb->ctx, tkt);
    free(sname);
    free(name);
    krb5_free_cred_contents(kerb->ctx, &creds);
  }

  if (krbret != KRB5_CC_END) {
    // FIXME: do we need to free up "result" here?  There will be no
    // references to it, so I think the garbage collector will pick it up,
    // but I'm not sure.

    goto cache_fail_close;
  }

  krbret = krb5_cc_end_seq_get(kerb->ctx, cc, &cur);

  krb5_cc_close(kerb->ctx, cc);

  return result;

 cache_fail_close:
  krb5_cc_close(kerb->ctx, cc);

 cache_fail_raise:
  Krb5_register_error(krbret);

  return Qfalse;
}
Пример #27
0
///////////////////////////////////////////////////////////
// ARGSS Color class methods
///////////////////////////////////////////////////////////
VALUE ARGSS::AColor::rload(VALUE self, VALUE str) {
	VALUE arr = rb_funcall(str, rb_intern("unpack"), 1, rb_str_new2("d4"));
	VALUE args[4] = {rb_ary_entry(arr, 0), rb_ary_entry(arr, 1), rb_ary_entry(arr, 2), rb_ary_entry(arr, 3)};
	return rb_class_new_instance(4, args, ARGSS::AColor::id);
}
Пример #28
0
static VALUE get_value(const char* buffer, int* position, int type) {
    VALUE value;
    switch (type) {
    case -1:
        {
            value = rb_class_new_instance(0, NULL, MinKey);
            break;
        }
    case 1:
        {
            double d;
            memcpy(&d, buffer + *position, 8);
            value = rb_float_new(d);
            *position += 8;
            break;
        }
    case 2:
    case 13:
        {
            int value_length;
            value_length = *(int*)(buffer + *position) - 1;
            *position += 4;
            value = STR_NEW(buffer + *position, value_length);
            *position += value_length + 1;
            break;
        }
    case 3:
        {
            int size;
            memcpy(&size, buffer + *position, 4);
            if (strcmp(buffer + *position + 5, "$ref") == 0) { // DBRef
                int offset = *position + 10;
                VALUE argv[2];
                int collection_length = *(int*)(buffer + offset) - 1;
                char id_type;
                offset += 4;

                argv[0] = STR_NEW(buffer + offset, collection_length);
                offset += collection_length + 1;
                id_type = buffer[offset];
                offset += 5;
                argv[1] = get_value(buffer, &offset, (int)id_type);
                value = rb_class_new_instance(2, argv, DBRef);
            } else {
                value = elements_to_hash(buffer + *position + 4, size - 5);
            }
            *position += size;
            break;
        }
    case 4:
        {
            int size, end;
            memcpy(&size, buffer + *position, 4);
            end = *position + size - 1;
            *position += 4;

            value = rb_ary_new();
            while (*position < end) {
                int type = (int)buffer[(*position)++];
                int key_size = strlen(buffer + *position);
                VALUE to_append;

                *position += key_size + 1; // just skip the key, they're in order.
                to_append = get_value(buffer, position, type);
                rb_ary_push(value, to_append);
            }
            (*position)++;
            break;
        }
    case 5:
        {
            int length, subtype;
            VALUE data, st;
            VALUE argv[2];
            memcpy(&length, buffer + *position, 4);
            subtype = (unsigned char)buffer[*position + 4];
            if (subtype == 2) {
                data = rb_str_new(buffer + *position + 9, length - 4);
            } else {
                data = rb_str_new(buffer + *position + 5, length);
            }
            st = INT2FIX(subtype);
            argv[0] = data;
            argv[1] = st;
            value = rb_class_new_instance(2, argv, Binary);
            *position += length + 5;
            break;
        }
    case 6:
        {
            value = Qnil;
            break;
        }
    case 7:
        {
            VALUE str = rb_str_new(buffer + *position, 12);
            VALUE oid = rb_funcall(str, unpack_method, 1, rb_str_new2("C*"));
            value = rb_class_new_instance(1, &oid, ObjectId);
            *position += 12;
            break;
        }
    case 8:
        {
            value = buffer[(*position)++] ? Qtrue : Qfalse;
            break;
        }
    case 9:
        {
            long long millis;
            memcpy(&millis, buffer + *position, 8);

            value = rb_time_new(millis / 1000, (millis % 1000) * 1000);
            value = rb_funcall(value, utc_method, 0);
            *position += 8;
            break;
        }
    case 10:
        {
            value = Qnil;
            break;
        }
    case 11:
        {
            int pattern_length = strlen(buffer + *position);
            VALUE pattern = STR_NEW(buffer + *position, pattern_length);
            int flags_length, flags = 0, i = 0;
            VALUE argv[3];
            *position += pattern_length + 1;

            flags_length = strlen(buffer + *position);
            for (i = 0; i < flags_length; i++) {
                char flag = buffer[*position + i];
                if (flag == 'i') {
                    flags |= IGNORECASE;
                }
                else if (flag == 'm') {
                    flags |= MULTILINE;
                }
                else if (flag == 'x') {
                    flags |= EXTENDED;
                }
            }
            argv[0] = pattern;
            argv[1] = INT2FIX(flags);
            value = rb_class_new_instance(2, argv, Regexp);
            *position += flags_length + 1;
            break;
        }
    case 12:
        {
            int collection_length;
            VALUE collection, str, oid, id, argv[2];
            collection_length = *(int*)(buffer + *position) - 1;
            *position += 4;
            collection = STR_NEW(buffer + *position, collection_length);
            *position += collection_length + 1;

            str = rb_str_new(buffer + *position, 12);
            oid = rb_funcall(str, unpack_method, 1, rb_str_new2("C*"));
            id = rb_class_new_instance(1, &oid, ObjectId);
            *position += 12;

            argv[0] = collection;
            argv[1] = id;
            value = rb_class_new_instance(2, argv, DBRef);
            break;
        }
    case 14:
        {
            int value_length;
            memcpy(&value_length, buffer + *position, 4);
            value = ID2SYM(rb_intern(buffer + *position + 4));
            *position += value_length + 4;
            break;
        }
    case 15:
        {
            int code_length, scope_size;
            VALUE code, scope, argv[2];
            *position += 4;
            code_length = *(int*)(buffer + *position) - 1;
            *position += 4;
            code = STR_NEW(buffer + *position, code_length);
            *position += code_length + 1;

            memcpy(&scope_size, buffer + *position, 4);
            scope = elements_to_hash(buffer + *position + 4, scope_size - 5);
            *position += scope_size;

            argv[0] = code;
            argv[1] = scope;
            value = rb_class_new_instance(2, argv, Code);
            break;
        }
    case 16:
        {
            int i;
            memcpy(&i, buffer + *position, 4);
            value = LL2NUM(i);
            *position += 4;
            break;
        }
    case 17:
        {
            int i;
            int j;
            memcpy(&i, buffer + *position, 4);
            memcpy(&j, buffer + *position + 4, 4);
            value = rb_ary_new3(2, LL2NUM(i), LL2NUM(j));
            *position += 8;
            break;
        }
    case 18:
        {
            long long ll;
            memcpy(&ll, buffer + *position, 8);
            value = LL2NUM(ll);
            *position += 8;
            break;
        }
    case 127:
        {
            value = rb_class_new_instance(0, NULL, MaxKey);
            break;
        }
    default:
        {
            rb_raise(rb_eTypeError, "no c decoder for this type yet (%d)", type);
            break;
        }
    }
    return value;
}
Пример #29
0
VALUE ARGSS::AColor::New(VALUE color) {
	VALUE args[4] = {rb_iv_get(color, "@red"), rb_iv_get(color, "@green"), rb_iv_get(color, "@blue"), rb_iv_get(color, "@alpha")};
	return rb_class_new_instance(4, args, id);
}
Пример #30
0
/*
 * call-seq:
 *    sax_parser.initialize -> sax_parser
 * 
 * Initiliazes instance of parser.
 */
static VALUE
rxml_sax_parser_initialize(VALUE self) {
  VALUE input = rb_class_new_instance(0, NULL, cXMLInput);
  rb_iv_set(self, "@input", input);
  return self;
}