Esempio n. 1
0
static VALUE rb_fastadd_add_one(int argc, VALUE *argv, VALUE self)
{
  int n = NUM2INT(rb_funcall(self, rb_intern("n"), 0));
  return INT2NUM(n + 1);
}
Esempio n. 2
0
File: ossl.c Progetto: 2220142/ruby
VALUE
ossl_call_verify_cb_proc(struct ossl_verify_cb_args *args)
{
    return rb_funcall(args->proc, rb_intern("call"), 2,
                      args->preverify_ok, args->store_ctx);
}
Esempio n. 3
0
/*
 * call-seq:
 *   Kernel.backtrace_includes?( method_or_object, ... ) -> true or false
 *   Kernel.backtrace_includes?( number_of_frames, method_or_object, ... ) -> true or false
 *
 * Returns whether specified methods or objects or classes are in the current backtrace context.
 * Kernel.backtrace_includes? begins with the prior frame, so asking if the backtrace includes the current method
 * will only report true if the current method is part of the earlier call chain.
 */
VALUE rb_RPRuby_Sender_Kernel_backtrace_includes(  int    argc,
                          VALUE*  args,
                          VALUE  rb_self )  {
  
  //  this function is also used for 
  //  * backtrace_includes_one_of?
  //  * backtrace_includes_frame?
  //  * backtrace_includes_one_of_frames?
  
  //  create tracking array
  VALUE  rb_tracking_array  =  rb_ary_new();
  
  //  populate tracking array with methods/objects
  //  optional - if first arg is Qtrue, we are looking for one of the args instead of all of the args
  int    c_which_arg        =  0;
  BOOL  c_requires_all_items  = TRUE;
  if (  args[ 0 ] == Qnil
    ||  (  argc > 1
       &&  args[ 1 ] == Qnil ) )  {
    c_which_arg++;
    c_requires_all_items = FALSE;
  }
  BOOL  c_return_frame  =  FALSE;
  if (  args[ 0 ] == Qfalse
    ||  (  argc > 1
       &&  args[ 1 ] == Qfalse ) )  {
    c_which_arg++;
    c_return_frame = TRUE;
  }
  BOOL  c_return_all_frames  =  FALSE;
  if (  args[ 0 ] == Qtrue
    ||  (  argc > 1
       &&  args[ 1 ] == Qtrue ) )  {
    c_which_arg++;
    c_return_all_frames = TRUE;
  }
  int  c_args_offset  =  c_which_arg;
  for ( ; c_which_arg < argc ; c_which_arg++ )  {
    rb_ary_push(  rb_tracking_array,
            args[ c_which_arg ] );
  }
    
  rb_thread_t*      c_thread          = (rb_thread_t *)RTYPEDDATA_DATA(rb_thread_current());
  //  Get the current frame - we're doing a backtrace, so our current working frame to start is the first previous thread
  rb_control_frame_t*    c_current_context_frame    = RUBY_VM_PREVIOUS_CONTROL_FRAME( RUBY_VM_PREVIOUS_CONTROL_FRAME( c_thread->cfp ) );
  
  //  c_top_of_control_frame describes the top edge of the stack trace
  //  set c_top_of_control_frame to the first frame in <main>
    rb_control_frame_t*    c_top_of_control_frame  =  RUBY_VM_NEXT_CONTROL_FRAME( RUBY_VM_NEXT_CONTROL_FRAME( (void *)( c_thread->stack + c_thread->stack_size ) ) );
  
  VALUE  rb_test_index_array  =  rb_ary_new();
  //  :object
  //  instance or class
  rb_ary_push(  rb_test_index_array,
          ID2SYM( rb_intern( "object" ) ) );
  //  :method        
  rb_ary_push(  rb_test_index_array,
          ID2SYM( rb_intern( "method" ) ) );
  //  :file
  rb_ary_push(  rb_test_index_array,
          ID2SYM( rb_intern( "file" ) ) );
  //  :line
  rb_ary_push(  rb_test_index_array,
          ID2SYM( rb_intern( "line" ) ) );
  
  //  only used if c_return_all_frames == TRUE
  VALUE  rb_frame_hashes_array  =  Qnil;
  if ( c_return_all_frames == TRUE )  {
    rb_frame_hashes_array    =  rb_ary_new();
  }
  
  VALUE  rb_frame_hash  =  Qnil;
  
  //  for each control frame:
    while ( c_current_context_frame < c_top_of_control_frame ) {
     
    //  iterate each array member 
    int  c_which_member;
    for ( c_which_member = 0 ; c_which_member < RARRAY_LEN( rb_tracking_array ) ; c_which_member++ )  {
       
      VALUE  rb_this_arg  =  args[ c_which_member + c_args_offset ];
       
      BOOL    matched  =  FALSE;
       
      rb_frame_hash  =  rb_RPRuby_Sender_Kernel_internal_backtraceHashForControlFrame(  & c_current_context_frame );
      
      //  if we have a hash we are testing multiple items in a frame
      if ( TYPE( rb_this_arg ) == T_HASH )  {

        VALUE  rb_frame_test_array  =  rb_obj_clone( rb_test_index_array );
      
        //  for each element that we could test for
        int  c_which_index;
        int  c_skipped_index_count  =  0;
        for ( c_which_index = 0 ; c_which_index < RARRAY_LEN( rb_frame_test_array ) ; c_which_index++ )  {
          
          VALUE  rb_this_index  =  RARRAY_PTR( rb_frame_test_array )[ c_which_index ];
          
          //  see if our requested test hash includes the potential test element
          if ( rb_hash_lookup(  rb_this_arg,
                      rb_this_index ) != Qnil )  {
            
            VALUE  rb_required_element  =  rb_hash_aref(  rb_this_arg,
                                    rb_this_index );
            VALUE  rb_frame_element  =  rb_hash_aref(  rb_frame_hash,
                                    rb_this_index  );
                               
            //  if it does, we need to see if the current frame's element matches this element
            VALUE  rb_required_element_klass;
            if ( rb_required_element == rb_frame_element
              //  if we have a string, which is a filename
              ||  (  TYPE( rb_required_element ) == T_STRING
                 &&  rb_funcall( rb_frame_element, rb_intern( "==" ), 1, rb_required_element ) == Qtrue )
              //  if we have a class, which is a special case for :object
              ||  (  rb_this_index == ID2SYM( rb_intern( "class" ) ) 
                 &&  ( rb_required_element_klass = ( ( TYPE( rb_required_element ) == T_CLASS ) ? rb_required_element : rb_funcall( rb_required_element, rb_intern( "class" ), 0 ) ) )
                 &&  rb_required_element_klass == rb_required_element ) )  {

              rb_ary_delete_at(  rb_frame_test_array,
                        c_which_index );
              c_which_index--;
            }
          }
          else {
            c_skipped_index_count++;
          }

          if ( RARRAY_LEN( rb_frame_test_array ) == c_skipped_index_count )  {
            if ( c_return_frame == TRUE )  {
              return rb_frame_hash;
            }
            else if ( c_return_all_frames == TRUE )  {
              rb_ary_push(  rb_frame_hashes_array,
                      rb_frame_hash );
            }
            else {
              return Qtrue;              
            }
          }          
        }
      }
      else {

        //  :object => <class:instance>
        if  (  TYPE( rb_this_arg ) == T_OBJECT )  {

          if ( rb_hash_aref(  rb_frame_hash,
                    ID2SYM( rb_intern( "object" ) ) ) == rb_this_arg )  {
            matched = TRUE;
          }
        }
        //  :object => <class>
        else if  ( TYPE( rb_this_arg ) == T_CLASS )  {
          
          VALUE  rb_frame_object      =  rb_hash_aref(  rb_frame_hash,
                                    ID2SYM( rb_intern( "object" ) ) );
          VALUE  rb_frame_object_klass  =  TYPE( rb_frame_object ) == T_CLASS ? rb_frame_object : rb_funcall( rb_frame_object, rb_intern( "class" ), 0 );
          if ( rb_frame_object_klass == rb_this_arg )  {
            matched = TRUE;
          }
        }
        //  :method => :method
        else if  ( TYPE( rb_this_arg ) == T_SYMBOL )  {
           
          if ( rb_hash_aref(  rb_frame_hash,
                    ID2SYM( rb_intern( "method" ) ) ) == rb_this_arg )  {
            matched = TRUE;
          }
        }
        //  :file => "filename"
        else if ( TYPE( rb_this_arg ) == T_STRING )  {
          VALUE  rb_filename  =  rb_hash_aref(  rb_frame_hash,
                              ID2SYM( rb_intern( "file" ) ) );
          VALUE  rb_comparison  =  rb_funcall( rb_filename, rb_intern( "==" ), 1, rb_this_arg );
          if ( rb_comparison == Qtrue )  {
            matched = TRUE;
          }
        }
        //  :line => number
        else if ( TYPE( rb_this_arg ) == T_FIXNUM )  {
          if ( rb_hash_aref(  rb_frame_hash,
                    ID2SYM( rb_intern( "line" ) ) ) == rb_this_arg )  {
            matched = TRUE;
          }
        }
         
        //  if array member exists in frame, remove from array
        if ( matched )  {
          if ( c_requires_all_items == FALSE )  {
            if ( c_return_frame == TRUE )  {
              return rb_frame_hash;
            }
            else {
              return Qtrue;              
            }

          }
          else {
            
            //  delete this index
            rb_ary_delete_at(  rb_tracking_array,
                      c_which_member );
            
            //  decrement the loop iterator so that the increase is offset
            //  this is necessary since we just removed an index and are iterating vs. the length of the array
            c_which_member--;
          }
        }
      }
    }
     
    //  if array is empty, return true
    //  we check here as well as at the end so we can stop iterating the backtrace if we find all our items
    if ( RARRAY_LEN( rb_tracking_array ) == 0 )  {
      if ( c_return_frame == TRUE )  {
        return rb_frame_hash;
      }
      else if ( c_return_all_frames == TRUE )  {
        rb_ary_push(  rb_frame_hashes_array,
                rb_frame_hash );
        return rb_frame_hashes_array;
      }
      else {
        return Qtrue;              
      }
    }
    c_current_context_frame = RUBY_VM_PREVIOUS_CONTROL_FRAME( c_current_context_frame );    
  }
  
  if (  c_return_all_frames == TRUE
    &&  RARRAY_LEN( rb_frame_hashes_array ) > 0 ) {
    return rb_frame_hashes_array;
  }
  //  if we finish iterating frames and still have items in the array, return false
  else if ( RARRAY_LEN( rb_tracking_array ) > 0 )  {
    if ( c_return_frame == TRUE )  {
      return Qnil;
    }
    else {
      return Qfalse;
    }
  }
  //  otherwise, return true
  else if ( c_return_frame == TRUE )  {
    return rb_frame_hash;
  }
  else {
    return Qtrue;              
  }
  //  we don't get here
  return Qnil;
}
Esempio n. 4
0
static VALUE get_value(const char* buffer, int* position, int type) {
    VALUE value;
    switch (type) {
    case 1:
        {
            double d;
            memcpy(&d, buffer + *position, 8);
            value = rb_float_new(d);
            *position += 8;
            break;
        }
    case 2:
    case 13:
        {
            int value_length;
            *position += 4;
            value_length = strlen(buffer + *position);
            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 + 14;
                VALUE argv[2];
                int collection_length = strlen(buffer + offset);
                char id_type;

                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, rb_intern("unpack"), 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;
            VALUE seconds, microseconds;
            memcpy(&millis, buffer + *position, 8);
            seconds = LL2NUM(millis / 1000);
            microseconds = INT2NUM((millis % 1000) * 1000);

            value = rb_funcall(Time, rb_intern("at"), 2, seconds, microseconds);
            value = rb_funcall(value, rb_intern("utc"), 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;
            char extra[10];
            VALUE argv[3];
            *position += pattern_length + 1;

            flags_length = strlen(buffer + *position);
            extra[0] = 0;
            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;
                }
                else if (strlen(extra) < 9) {
                    strncat(extra, &flag, 1);
                }
            }
            argv[0] = pattern;
            argv[1] = INT2FIX(flags);
            argv[2] = rb_str_new2(extra);
            value = rb_class_new_instance(3, argv, RegexpOfHolding);
            *position += flags_length + 1;
            break;
        }
    case 12:
        {
            int collection_length;
            VALUE collection, str, oid, id, argv[2];
            *position += 4;
            collection_length = strlen(buffer + *position);
            collection = STR_NEW(buffer + *position, collection_length);
            *position += collection_length + 1;

            str = rb_str_new(buffer + *position, 12);
            oid = rb_funcall(str, rb_intern("unpack"), 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 += 8;
            code_length = strlen(buffer + *position);
            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;
        }
    default:
        {
            rb_raise(rb_eTypeError, "no c decoder for this type yet (%d)", type);
            break;
        }
    }
    return value;
}
Esempio n. 5
0
VALUE
rbgutil_def_setters(VALUE klass)
{
    return rb_funcall(mGLib, id_add_one_arg_setter, 1, klass);
}
Esempio n. 6
0
File: gsl.c Progetto: masaomi/rb-gsl
static VALUE rb_gsl_call_name(VALUE obj)
{
  return rb_funcall(obj, rb_gsl_id_name, 0);
}
Esempio n. 7
0
void klassify(VALUE obj, char * name) {
  VALUE klassname;
  klassname = rb_funcall(rb_funcall(obj, rb_intern("class"), 0), rb_intern("name"), 0);
  printf("obj %s was a: %s\n", name, StringValuePtr(klassname));

}
Esempio n. 8
0
void init_mpcrnd()
{
  ID new_id = rb_intern ("new");
  cMPC = rb_define_class ("MPC", rb_cNumeric);

  cMPC_Rnd = rb_define_class_under (cMPC, "Rnd", rb_cObject);

  rb_define_singleton_method (cMPC_Rnd, "new", r_mpcrndsg_new, -1);
  rb_define_method (cMPC_Rnd, "initialize", r_mpcrnd_initialize, -1);
  rb_define_method (cMPC_Rnd, "inspect", r_mpcrnd_inspect, 0);

  rb_define_attr (cMPC_Rnd, "mode",    1, 0);
  rb_define_attr (cMPC_Rnd, "name",    1, 0);
  rb_define_attr (cMPC_Rnd, "ieee754", 1, 0);

  rb_define_const(cMPC, "MPC_RNDNN", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(0)));
  rb_define_const(cMPC, "MPC_RNDNZ", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(16)));
  rb_define_const(cMPC, "MPC_RNDNU", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(32)));
  rb_define_const(cMPC, "MPC_RNDND", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(48)));
  rb_define_const(cMPC, "MPC_RNDZN", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(1)));
  rb_define_const(cMPC, "MPC_RNDZZ", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(17)));
  rb_define_const(cMPC, "MPC_RNDZU", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(33)));
  rb_define_const(cMPC, "MPC_RNDZD", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(49)));
  rb_define_const(cMPC, "MPC_RNDUN", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(2)));
  rb_define_const(cMPC, "MPC_RNDUZ", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(18)));
  rb_define_const(cMPC, "MPC_RNDUU", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(34)));
  rb_define_const(cMPC, "MPC_RNDUD", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(50)));
  rb_define_const(cMPC, "MPC_RNDDN", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(3)));
  rb_define_const(cMPC, "MPC_RNDDZ", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(19)));
  rb_define_const(cMPC, "MPC_RNDDU", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(35)));
  rb_define_const(cMPC, "MPC_RNDDD", rb_funcall (cMPC_Rnd, new_id, 1, INT2FIX(51)));
}
Esempio n. 9
0
jobject event_cast<jobject, VALUE>(VALUE rEvent)
{
    if (NIL_P(rEvent))
        return NULL;

    RHO_TRACE("eventFromRuby (1)");
    JNIEnv *env = jnienv();
    if (!init_event_stuff(env))
        return NULL;

    RHO_TRACE("eventFromRuby (2)");
    VALUE rId = rb_hash_aref(rEvent, rb_str_new2(RUBY_EV_ID));
    if (NIL_P(rId))
        rId = rb_str_new2("");
    Check_Type(rId, T_STRING);

    RHO_TRACE("eventFromRuby (3)");
    jmethodID mid = getJNIClassMethod(env, clsEvent, "<init>", "(Ljava/lang/String;)V");
    if (!mid) return NULL;

    jhstring jhId = rho_cast<jstring>(env, rId);
    jobject jEvent = env->NewObject(clsEvent, mid, jhId.get());
    if (!jEvent) return NULL;

    RHO_TRACE("eventFromRuby (4)");
    VALUE rTitle = rb_hash_aref(rEvent, rb_str_new2(RUBY_EV_TITLE));
    if (!NIL_P(rTitle))
    {
        Check_Type(rTitle, T_STRING);
        jhstring jhTitle = rho_cast<jstring>(env, rTitle);
        env->SetObjectField(jEvent, fidTitle, jhTitle.get());
    }

    RHO_TRACE("eventFromRuby (5)");
    VALUE rStartDate = rb_hash_aref(rEvent, rb_str_new2(RUBY_EV_START_DATE));
    if (!NIL_P(rStartDate))
        env->SetObjectField(jEvent, fidStartDate, date_cast<jobject>(rStartDate));

    RHO_TRACE("eventFromRuby (6)");
    VALUE rEndDate = rb_hash_aref(rEvent, rb_str_new2(RUBY_EV_END_DATE));
    if (!NIL_P(rEndDate))
        env->SetObjectField(jEvent, fidEndDate, date_cast<jobject>(rEndDate));

    RHO_TRACE("eventFromRuby (7)");
    VALUE rLastModified = rb_hash_aref(rEvent, rb_str_new2(RUBY_EV_LAST_MODIFIED));
    if (!NIL_P(rLastModified))
        env->SetObjectField(jEvent, fidLastModified, date_cast<jobject>(rLastModified));

    RHO_TRACE("eventFromRuby (8)");
    VALUE rLocation = rb_hash_aref(rEvent, rb_str_new2(RUBY_EV_LOCATION));
    if (!NIL_P(rLocation))
    {
        Check_Type(rLocation, T_STRING);
        jhstring jhLocation = rho_cast<jstring>(env, rLocation);
        env->SetObjectField(jEvent, fidLocation, jhLocation.get());
    }

    RHO_TRACE("eventFromRuby (9)");
    VALUE rNotes = rb_hash_aref(rEvent, rb_str_new2(RUBY_EV_NOTES));
    if (!NIL_P(rNotes))
    {
        Check_Type(rNotes, T_STRING);
        jhstring jhNotes = rho_cast<jstring>(env, rNotes);
        env->SetObjectField(jEvent, fidNotes, jhNotes.get());
    }

    RHO_TRACE("eventFromRuby privacy");
    VALUE rPrivacy = rb_hash_aref(rEvent, rb_str_new2(RUBY_EV_PRIVACY));
    if (!NIL_P(rPrivacy))
    {
        Check_Type(rPrivacy, T_STRING);
        jhstring jhPrivacy = rho_cast<jstring>(env, rPrivacy);
        env->SetObjectField(jEvent, fidPrivacy, jhPrivacy.get());
    }

    RHO_TRACE("eventFromRuby recurrence");
    VALUE rRecurrence = rb_hash_aref(rEvent, rb_str_new2(RUBY_EV_RECURRENCE));
    if (!NIL_P(rRecurrence)) {
        Check_Type(rRecurrence, T_HASH);

        VALUE rFrequency = rb_hash_aref(rRecurrence, rb_str_new2(RUBY_EV_RECURRENCE_FREQUENCY));
        Check_Type(rFrequency, T_STRING);
        const char *frequency = RSTRING_PTR(rFrequency);
        if (   strcasecmp(frequency, RUBY_EV_RECURRENCE_FREQUENCY_DAILY) != 0
        	&& strcasecmp(frequency, RUBY_EV_RECURRENCE_FREQUENCY_WEEKLY) != 0
        	&& strcasecmp(frequency, RUBY_EV_RECURRENCE_FREQUENCY_MONTHLY) != 0
        	&& strcasecmp(frequency, RUBY_EV_RECURRENCE_FREQUENCY_YEARLY) != 0)
        {
        	rb_raise(rb_eArgError, "Wrong recurrence frequency: %s", frequency);
        }
        jhstring jhFreq = rho_cast<jstring>(env, rFrequency);
        env->SetObjectField(jEvent, fidFrequency, jhFreq.get());

        VALUE rInterval = rb_hash_aref(rRecurrence, rb_str_new2(RUBY_EV_RECURRENCE_INTERVAL));
        rInterval = rb_funcall(rInterval, rb_intern("to_i"), 0);
        int interval = NUM2INT(rInterval);
        env->SetIntField(jEvent, fidInterval, interval);
        RAWTRACE1("eventFromRuby recurrence interval: %d", interval);

        VALUE rUntilDate = rb_hash_aref(rRecurrence, rb_str_new2(RUBY_EV_RECURRENCE_END));
        if (!NIL_P(rUntilDate))
        {
            env->SetObjectField(jEvent, fidRecurrenceEnd, date_cast<jobject>(rUntilDate));
            RAWTRACE("eventFromRuby recurrence until date");
        }

        VALUE rTimes = rb_funcall(rb_hash_aref(rRecurrence, rb_str_new2(RUBY_EV_RECURRENCE_COUNT)), rb_intern("to_i"), 0);;
        int times = NUM2INT(rTimes);
        env->SetIntField(jEvent, fidRecurrenceTimes, times);
        RAWTRACE1("eventFromRuby recurrence count: %d", times);
    }

    RHO_TRACE("eventFromRuby: return");
    return jEvent;
}
Esempio n. 10
0
static VALUE
rg_s_type_register(int argc, VALUE* argv, VALUE self)
{
    VALUE type_name, flags;
    volatile VALUE class_init_proc = Qnil;
    GType parent_type;
    GTypeInfo* info;

    rb_scan_args(argc, argv, "03", &type_name, &info, &flags);

    {
        const RGObjClassInfo* cinfo = rbgobj_lookup_class(self);
        if (cinfo->klass == self)
            rb_raise(rb_eTypeError, "already registered");
    }

    {
        VALUE superclass = rb_funcall(self, rb_intern("superclass"), 0);
        const RGObjClassInfo* cinfo = rbgobj_lookup_class(superclass);
        if (cinfo->klass != superclass)
            rb_raise(rb_eTypeError, "super class must be registered to GLib");
        parent_type = cinfo->gtype;
    }

    if (NIL_P(type_name)) {
        VALUE s = rb_funcall(self, rb_intern("name"), 0);

        if (strlen(StringValuePtr(s)) == 0)
            rb_raise(rb_eTypeError, "can't determine type name");

        type_name = rb_funcall(
                        rb_eval_string("lambda{|x| x.gsub(/::/,'') }"),
                        rb_intern("call"), 1, s);
    }

    {
        GTypeQuery query;
        g_type_query(parent_type, &query);

        /* TODO: Why new?  g_type_register_static() doesn’t retain a copy, so
         * this should be allocated on the stack. */
        info = g_new0(GTypeInfo, 1);
        info->class_size     = query.class_size;
        info->base_init      = NULL;
        info->base_finalize  = NULL;
        info->class_init     = class_init_func;
        info->class_finalize = NULL;
        info->class_data     = (gpointer)class_init_proc;
        info->instance_size  = query.instance_size;
        info->n_preallocs    = 0;
        info->instance_init  = NULL;
        info->value_table    = NULL;
    }

    {
        GType type = g_type_register_static(parent_type,
                                            StringValuePtr(type_name),
                                            info,
                                            NIL_P(flags) ? 0 : NUM2INT(flags));
        G_RELATIVE(self, class_init_proc);

        rbgobj_register_class(self, type, TRUE, TRUE);

        {
            RGObjClassInfo* cinfo = (RGObjClassInfo*)rbgobj_lookup_class(self);
            cinfo->flags |= RBGOBJ_DEFINED_BY_RUBY;
        }

        {
            GType parent = g_type_parent(type);
            const RGObjClassInfo* cinfo =  GTYPE2CINFO(parent);
            VALUE m = rb_define_module_under(self, RubyGObjectHookModule);

            if (! (cinfo->flags & RBGOBJ_DEFINED_BY_RUBY)) {
                rbg_define_method(m, "initialize", rg_initialize, -1);
            }

            rb_include_module(self, m);
        }

        return Qnil;
    }
}
Esempio n. 11
0
/* 
 * Returns the record in this DtraceBufdata. Records are returned as
 * either DtraceRecords or DtraceStackRecords as appropriate for the
 * type of action.
 */
VALUE dtracebufdata_record(VALUE self)
{
  dtrace_bufdata_t *bufdata;
  const dtrace_recdesc_t *rec;
  dtrace_actkind_t act = DTRACEACT_NONE;
  const char *s;
  VALUE v = Qnil;
  VALUE dtracerecord;
  VALUE dtraceaggdata;
  VALUE dtracerecdesc;

  Data_Get_Struct(self, dtrace_bufdata_t, bufdata);
  
  if (bufdata->dtbda_aggdata) {
    dtraceaggdata = Data_Wrap_Struct(cDtraceAggData, 0, NULL, (dtrace_bufdata_t *)bufdata);
    return dtraceaggdata;
  }

  s = bufdata->dtbda_buffered;
  if (s == NULL) {
    return Qnil;
  }
  
  rec = bufdata->dtbda_recdesc;
  if (rec) {
    act = rec->dtrd_action;
  }
  
  switch (act) {
  case DTRACEACT_DIFEXPR:
    /* trace() action */
    break;
  case DTRACEACT_PRINTF:
    /* printf action, not available in probedata */
    v = rb_str_new2(s);
    dtracerecord = rb_class_new_instance(0, NULL, rb_path2class("Dtrace::PrintfRecord"));
    rb_iv_set(dtracerecord, "@from", rb_str_new2("bufdata"));
    rb_iv_set(dtracerecord, "@value", v);
    return (dtracerecord);
    break;
  case DTRACEACT_STACK:
  case DTRACEACT_USTACK:
  case DTRACEACT_JSTACK:
    /* stand-alone stack(), ustack(), or jstack() action */
    v = rb_str_new2(s);
    dtracerecord = rb_class_new_instance(0, NULL, rb_path2class("Dtrace::StackRecord"));
    rb_iv_set(dtracerecord, "@from", rb_str_new2("bufdata"));
    rb_funcall(dtracerecord, rb_intern("parse"), 1, v);
    return (dtracerecord);
    break;
  case DTRACEACT_USYM:
  case DTRACEACT_UADDR:
  case DTRACEACT_UMOD:
  case DTRACEACT_SYM:
  case DTRACEACT_MOD:
    v = rb_str_new2(s);
    break;
  case DTRACEACT_PRINTA:
    v = rb_str_new2(s);
    break;
  default:
    /*
     * The record handle defers nothing else to this
     * bufhandler.
     */
    break;
  }

  if (!NIL_P(v)) {
    dtracerecord = rb_class_new_instance(0, NULL, rb_path2class("Dtrace::Record"));
    rb_iv_set(dtracerecord, "@value", v);
    rb_iv_set(dtracerecord, "@action", INT2FIX(act));
    rb_iv_set(dtracerecord, "@from", rb_str_new2("bufdata"));
    return (dtracerecord);
  }
  else {
    return Qnil;
  }
}
Esempio n. 12
0
static VALUE
ossl_asn1_decode0(unsigned char **pp, long length, long *offset, long depth,
		  int once, int yield)
{
    unsigned char *start, *p;
    const unsigned char *p0;
    long len, off = *offset;
    int hlen, tag, tc, j;
    VALUE ary, asn1data, value, tag_class;

    ary = rb_ary_new();
    p = *pp;
    while(length > 0){
	start = p;
	p0 = p;
	j = ASN1_get_object(&p0, &len, &tag, &tc, length);
	p = (unsigned char *)p0;
	if(j & 0x80) ossl_raise(eASN1Error, NULL);
	hlen = p - start;
	if(yield){
	    VALUE arg = rb_ary_new();
	    rb_ary_push(arg, LONG2NUM(depth));
	    rb_ary_push(arg, LONG2NUM(off));
	    rb_ary_push(arg, LONG2NUM(hlen));
	    rb_ary_push(arg, LONG2NUM(len));
	    rb_ary_push(arg, (j & V_ASN1_CONSTRUCTED) ? Qtrue : Qfalse);
	    rb_ary_push(arg, ossl_asn1_class2sym(tc));
	    rb_ary_push(arg, INT2NUM(tag));
	    rb_yield(arg);
	}
	length -= hlen;
	off += hlen; 
	if(len > length) ossl_raise(eASN1Error, "value is too short");
	if((tc & V_ASN1_PRIVATE) == V_ASN1_PRIVATE)
	    tag_class = sPRIVATE;
	else if((tc & V_ASN1_CONTEXT_SPECIFIC) == V_ASN1_CONTEXT_SPECIFIC)
	    tag_class = sCONTEXT_SPECIFIC;
	else if((tc & V_ASN1_APPLICATION) == V_ASN1_APPLICATION)
	    tag_class = sAPPLICATION;
	else
	    tag_class = sUNIVERSAL;
	if(j & V_ASN1_CONSTRUCTED){
	    /* TODO: if j == 0x21 it is indefinite length object. */
	    if((j == 0x21) && (len == 0)){
		long lastoff = off;
		value = ossl_asn1_decode0(&p, length, &off, depth+1, 0, yield);
		len = off - lastoff;
	    }
	    else value = ossl_asn1_decode0(&p, len, &off, depth+1, 0, yield);
	}
	else{
	    value = rb_str_new((const char *)p, len);
	    p += len;
	    off += len;
	}
	if(tag_class == sUNIVERSAL &&
	   tag < ossl_asn1_info_size && ossl_asn1_info[tag].klass){
	    VALUE klass = *ossl_asn1_info[tag].klass;
	    long flag = 0;
	    if(!rb_obj_is_kind_of(value, rb_cArray)){
		switch(tag){
		case V_ASN1_BOOLEAN:
		    value = decode_bool(start, hlen+len);
		    break;
		case V_ASN1_INTEGER:
		    value = decode_int(start, hlen+len);
		    break;
		case V_ASN1_BIT_STRING:
		    value = decode_bstr(start, hlen+len, &flag);
		    break;
		case V_ASN1_NULL:
		    value = decode_null(start, hlen+len);
		    break;
		case V_ASN1_ENUMERATED:
		    value = decode_enum(start, hlen+len);
		    break;
		case V_ASN1_OBJECT:
		    value = decode_obj(start, hlen+len);
		    break;
		case V_ASN1_UTCTIME:           /* FALLTHROUGH */
		case V_ASN1_GENERALIZEDTIME:
		    value = decode_time(start, hlen+len);
		    break;
		default:
		    /* use original value */
		    break;
		}
	    }
	    asn1data = rb_funcall(klass, rb_intern("new"), 1, value);
	    if(tag == V_ASN1_BIT_STRING){
		rb_iv_set(asn1data, "@unused_bits", LONG2NUM(flag));
	    }
	}
	else{
	    asn1data = rb_funcall(cASN1Data, rb_intern("new"), 3,
				  value, INT2NUM(tag), ID2SYM(tag_class));
	}
	rb_ary_push(ary, asn1data);
	length -= len;
        if(once) break;
    }
    *pp = p;
    *offset = off;

    return ary;
}
Esempio n. 13
0
/*
 * call-seq:
 *      Raindrops::Linux.tcp_listener_stats([addrs[, sock]]) => hash
 *
 * If specified, +addr+ may be a string or array of strings representing
 * listen addresses to filter for. Returns a hash with given addresses as
 * keys and ListenStats objects as the values or a hash of all addresses.
 *
 *      addrs = %w(0.0.0.0:80 127.0.0.1:8080)
 *
 * If +addr+ is nil or not specified, all (IPv4) addresses are returned.
 * If +sock+ is specified, it should be a Raindrops::InetDiagSock object.
 */
static VALUE tcp_listener_stats(int argc, VALUE *argv, VALUE self)
{
	VALUE rv = rb_hash_new();
	struct nogvl_args args;
	VALUE addrs, sock;

	rb_scan_args(argc, argv, "02", &addrs, &sock);

	/*
	 * allocating page_size instead of OP_LEN since we'll reuse the
	 * buffer for recvmsg() later, we already checked for
	 * OPLEN <= page_size at initialization
	 */
	args.iov[2].iov_len = OPLEN;
	args.iov[2].iov_base = alloca(page_size);
	args.table = NULL;
	if (NIL_P(sock))
		sock = rb_funcall(cIDSock, id_new, 0);
	args.fd = my_fileno(sock);

	switch (TYPE(addrs)) {
	case T_STRING:
		rb_hash_aset(rv, addrs, tcp_stats(&args, addrs));
		return rv;
	case T_ARRAY: {
		long i;
		long len = RARRAY_LEN(addrs);
		VALUE cur;

		if (len == 1) {
			cur = rb_ary_entry(addrs, 0);

			rb_hash_aset(rv, cur, tcp_stats(&args, cur));
			return rv;
		}
		for (i = 0; i < len; i++) {
			union any_addr check;
			VALUE cur = rb_ary_entry(addrs, i);

			parse_addr(&check, cur);
			rb_hash_aset(rv, cur, Qtrue);
		}
		/* fall through */
	}
	case T_NIL:
		args.table = st_init_strtable();
		gen_bytecode_all(&args.iov[2]);
		break;
	default:
		rb_raise(rb_eArgError,
		         "addr must be an array of strings, a string, or nil");
	}

	nl_errcheck(rb_thread_io_blocking_region(diag, &args, args.fd));

	st_foreach(args.table, NIL_P(addrs) ? st_to_hash : st_AND_hash, rv);
	st_free_table(args.table);

	/* let GC deal with corner cases */
	if (argc < 2) rb_io_close(sock);
	return rv;
}
Esempio n. 14
0
/* True if there are monitors on the loop */
static VALUE NIO_Selector_is_empty(VALUE self)
{
    VALUE selectables = rb_ivar_get(self, rb_intern("selectables"));

    return rb_funcall(selectables, rb_intern("empty?"), 0) == Qtrue ? Qtrue : Qfalse;
}
Esempio n. 15
0
VALUE
rb_exc_new_str(VALUE etype, VALUE str)
{
    StringValue(str);
    return rb_funcall(etype, rb_intern("new"), 1, str);
}
Esempio n. 16
0
static VALUE
range_check(VALUE *args)
{
    return rb_funcall(args[0], id_cmp, 1, args[1]);
}
Esempio n. 17
0
static VALUE
exc_message(VALUE exc)
{
    return rb_funcall(exc, rb_intern("to_s"), 0, 0);
}
Esempio n. 18
0
static VALUE
range_step(int argc, VALUE *argv, VALUE range)
{
    VALUE b, e, step, tmp;

    RETURN_ENUMERATOR(range, argc, argv);

    b = RANGE_BEG(range);
    e = RANGE_END(range);
    if (argc == 0) {
	step = INT2FIX(1);
    }
    else {
	rb_scan_args(argc, argv, "01", &step);
	if (!rb_obj_is_kind_of(step, rb_cNumeric)) {
	    step = rb_to_int(step);
	}
	if (rb_funcall(step, '<', 1, INT2FIX(0))) {
	    rb_raise(rb_eArgError, "step can't be negative");
	}
	else if (!rb_funcall(step, '>', 1, INT2FIX(0))) {
	    rb_raise(rb_eArgError, "step can't be 0");
	}
    }

    if (FIXNUM_P(b) && FIXNUM_P(e) && FIXNUM_P(step)) { /* fixnums are special */
	long end = FIX2LONG(e);
	long i, unit = FIX2LONG(step);

	if (!EXCL(range))
	    end += 1;
	i = FIX2LONG(b);
	while (i < end) {
	    rb_yield(LONG2NUM(i));
	    if (i + unit < i) break;
	    i += unit;
	}

    }
    else if (SYMBOL_P(b) && SYMBOL_P(e)) { /* symbols are special */
	VALUE args[2], iter[2];

	args[0] = rb_sym_to_s(e);
	args[1] = EXCL(range) ? Qtrue : Qfalse;
	iter[0] = INT2FIX(1);
	iter[1] = step;
	rb_block_call(rb_sym_to_s(b), rb_intern("upto"), 2, args, sym_step_i, (VALUE)iter);
    }
    else if (ruby_float_step(b, e, step, EXCL(range))) {
	/* done */
    }
    else if (rb_obj_is_kind_of(b, rb_cNumeric) ||
	     !NIL_P(rb_check_to_integer(b, "to_int")) ||
	     !NIL_P(rb_check_to_integer(e, "to_int"))) {
	ID op = EXCL(range) ? '<' : rb_intern("<=");
	VALUE v = b;
	int i = 0;

	while (RTEST(rb_funcall(v, op, 1, e))) {
	    rb_yield(v);
	    i++;
	    v = rb_funcall(b, '+', 1, rb_funcall(INT2NUM(i), '*', 1, step));
	}
    }
    else {
	tmp = rb_check_string_type(b);

	if (!NIL_P(tmp)) {
	    VALUE args[2], iter[2];

	    b = tmp;
	    args[0] = e;
	    args[1] = EXCL(range) ? Qtrue : Qfalse;
	    iter[0] = INT2FIX(1);
	    iter[1] = step;
	    rb_block_call(b, rb_intern("upto"), 2, args, step_i, (VALUE)iter);
	}
	else {
	    VALUE args[2];

	    if (!rb_respond_to(b, id_succ)) {
		rb_raise(rb_eTypeError, "can't iterate from %s",
			 rb_obj_classname(b));
	    }
	    args[0] = INT2FIX(1);
	    args[1] = step;
	    range_each_func(range, step_i, args);
	}
    }
    return range;
}
Esempio n. 19
0
File: gsl.c Progetto: masaomi/rb-gsl
static VALUE rb_gsl_call_size(VALUE obj)
{
  return rb_funcall(obj, rb_gsl_id_size, 0);
}
Esempio n. 20
0
static VALUE
range_eqq(VALUE range, VALUE val)
{
    return rb_funcall(range, rb_intern("include?"), 1, val);
}
Esempio n. 21
0
static int write_element_allow_id(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 && 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(InvalidName, "key must not start with '$'");
        }
        for (i = 0; i < RSTRING_LEN(key); i++) {
            if (RSTRING_PTR(key)[i] == '.') {
                buffer_free(buffer);
                rb_raise(InvalidName, "key must not contain '.'");
            }
        }
    }

    switch(TYPE(value)) {
    case T_BIGNUM:
    case T_FIXNUM:
        {
            if (rb_funcall(value, rb_intern(">"), 1, LL2NUM(9223372036854775807LL)) == Qtrue ||
                rb_funcall(value, rb_intern("<"), 1, LL2NUM(-9223372036854775808LL)) == Qtrue) {
                buffer_free(buffer);
                rb_raise(rb_eRangeError, "MongoDB can only handle 8-byte ints");
            }
            if (rb_funcall(value, rb_intern(">"), 1, INT2NUM(2147483647L)) == Qtrue ||
                rb_funcall(value, rb_intern("<"), 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);
            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(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_class2name(RBASIC(value)->klass),
                       "Mongo::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);

                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);
                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_class2name(RBASIC(value)->klass);
            if (strcmp(cls, "Mongo::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, "Mongo::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, "Mongo::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(rb_str_new2("$ref"), ns, pack_extra(buffer, Qfalse));
                oid = rb_funcall(value, rb_intern("object_id"), 0);
                write_element(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;
            }
        }
    case T_DATA:
        {
            // TODO again, is this really the only way to do this?
            const char* cls = rb_class2name(RBASIC(value)->klass);
            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;
            }
        }
    case T_REGEXP:
        {
            int length = RREGEXP_SRC_LEN(value);
            char* pattern = (char*)RREGEXP_SRC_PTR(value);
            long flags = RREGEXP(value)->ptr->options;
            VALUE has_extra;

            write_name_and_type(buffer, key, 0x0B);

            SAFE_WRITE(buffer, pattern, length);
            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:
        {
            buffer_free(buffer);
            rb_raise(rb_eTypeError, "no c encoder for this type yet (%d)", TYPE(value));
            break;
        }
    }
    return ST_CONTINUE;
}
Esempio n. 22
0
/*  call-seq:
 *     OpenSSL::PKey::EC.new()
 *     OpenSSL::PKey::EC.new(ec_key)
 *     OpenSSL::PKey::EC.new(ec_group)
 *     OpenSSL::PKey::EC.new("secp112r1")
 *     OpenSSL::PKey::EC.new(pem_string)
 *     OpenSSL::PKey::EC.new(pem_string [, pwd])
 *     OpenSSL::PKey::EC.new(der_string)
 *
 *  See the OpenSSL documentation for:
 *     EC_KEY_*
 */
static VALUE ossl_ec_key_initialize(int argc, VALUE *argv, VALUE self)
{
    EVP_PKEY *pkey;
    EC_KEY *ec = NULL;
    VALUE arg, pass;
    VALUE group = Qnil;
    char *passwd = NULL;

    GetPKey(self, pkey);
    if (pkey->pkey.ec)
        ossl_raise(eECError, "EC_KEY already initialized");

    rb_scan_args(argc, argv, "02", &arg, &pass);

    if (NIL_P(arg)) {
        ec = EC_KEY_new();
    } else {
        if (rb_obj_is_kind_of(arg, cEC)) {
            EC_KEY *other_ec = NULL;

            SafeRequire_EC_KEY(arg, other_ec);
            ec = EC_KEY_dup(other_ec);
        } else if (rb_obj_is_kind_of(arg, cEC_GROUP)) {
        	ec = EC_KEY_new();
        	group = arg;
        } else {
            BIO *in = ossl_obj2bio(arg);

            if (!NIL_P(pass)) {
		passwd = StringValuePtr(pass);
	    }
	    ec = PEM_read_bio_ECPrivateKey(in, NULL, ossl_pem_passwd_cb, passwd);
            if (!ec) {
		OSSL_BIO_reset(in);
		ec = PEM_read_bio_EC_PUBKEY(in, NULL, ossl_pem_passwd_cb, passwd);
            }
            if (!ec) {
		OSSL_BIO_reset(in);
                ec = d2i_ECPrivateKey_bio(in, NULL);
            }
            if (!ec) {
		OSSL_BIO_reset(in);
                ec = d2i_EC_PUBKEY_bio(in, NULL);
            }

            BIO_free(in);

            if (ec == NULL) {
                const char *name = StringValueCStr(arg);
                int nid = OBJ_sn2nid(name);

                (void)ERR_get_error();
                if (nid == NID_undef)
                    ossl_raise(eECError, "unknown curve name (%s)\n", name);

                if ((ec = EC_KEY_new_by_curve_name(nid)) == NULL)
                    ossl_raise(eECError, "unable to create curve (%s)\n", name);

                EC_KEY_set_asn1_flag(ec, OPENSSL_EC_NAMED_CURVE);
                EC_KEY_set_conv_form(ec, POINT_CONVERSION_UNCOMPRESSED);
            }
        }
    }

    if (ec == NULL)
        ossl_raise(eECError, NULL);

    if (!EVP_PKEY_assign_EC_KEY(pkey, ec)) {
	EC_KEY_free(ec);
	ossl_raise(eECError, "EVP_PKEY_assign_EC_KEY");
    }

    rb_iv_set(self, "@group", Qnil);

    if (!NIL_P(group))
        rb_funcall(self, rb_intern("group="), 1, arg);

    return self;
}
Esempio n. 23
0
/*
 * A Ruby interface for gathering process table information.
 */
void Init_proctable(){
  VALUE mSys, cProcTable;

  /* The Sys module serves as a namespace only */
  mSys = rb_define_module("Sys");

  /* The ProcTable class encapsulates process table information */
  cProcTable = rb_define_class_under(mSys, "ProcTable", rb_cObject);

  /* The Error class typically raised if any of the ProcTable methods fail */
  cProcTableError = rb_define_class_under(cProcTable, "Error", rb_eStandardError);

  /* Singleton methods */

  rb_define_singleton_method(cProcTable, "ps", pt_ps, -1);
  rb_define_singleton_method(cProcTable, "fields", pt_fields, 0);

  /* There is no constructor */
  rb_funcall(cProcTable, rb_intern("private_class_method"), 1, ID2SYM(rb_intern("new")));

  /* Constants */

  /* 0.9.3: The version of the sys-proctable library */
  rb_define_const(cProcTable, "VERSION", rb_str_new2(SYS_PROCTABLE_VERSION));

  /* Structs */

  sProcStruct = rb_struct_define("ProcTableStruct",
    "pid",         /* Process identifier */
    "ppid",        /* Parent process id */
    "pgid",        /* Process group id */
    "ruid",        /* Real user id */
    "rgid",        /* Real group id */
    "euid",        /* Effective user id */
    "egid",        /* Effective group id */
    "groups",      /* All effective group ids */
    "svuid",       /* Saved effective user id */
    "svgid",       /* Saved effective group id */
    "comm",        /* Command name (15 chars) */
    "state",       /* Process status */
    "pctcpu",      /* %cpu for this process during p_swtime */
    "oncpu",       /* nil */
    "tnum",        /* Controlling tty dev */
    "tdev",        /* Controlling tty name */
    "wmesg",       /* Wchan message */
    "rtime",       /* Real time */
    "priority",    /* Process priority */
    "usrpri",      /* User-priority */
    "nice",        /* Process "nice" value */
    "cmdline",     /* Complete command line */
    "exe",         /* Saved pathname of the executed command */
    "environ",     /* Hash with process environment variables */
    "starttime",   /* Process start time */
    "maxrss",      /* Max resident set size (PL) */
    "ixrss",       /* Integral shared memory size (NU) */
    "idrss",       /* Integral unshared data (NU) */
    "isrss",       /* Integral unshared stack (NU) */
    "minflt",      /* Page reclaims (NU) */
    "majflt",      /* Page faults (NU) */
    "nswap",       /* Swaps (NU) */
    "inblock",     /* Block input operations (atomic) */
    "oublock",     /* Block output operations (atomic) */
    "msgsnd",      /* Messages sent (atomic) */
    "msgrcv",      /* Messages received (atomic) */
    "nsignals",    /* Signals received (atomic) */
    "nvcsw",       /* Voluntary context switches (atomic) */
    "nivcsw",      /* Involuntary context switches (atomic) */
    "utime",       /* User time used (PL) */
    "stime",       /* System time used (PL) */
    NULL
  );
}
Esempio n. 24
0
static VALUE
invoke_callback(VALUE arg_)
{
    struct callback_arg *arg = (struct callback_arg *)arg_;
    return rb_funcall(arg->callback, id_call, 1, arg->page_setup);
}
Esempio n. 25
0
VALUE regexp_spec_match(VALUE self, VALUE regexp, VALUE str) {
  return rb_funcall(regexp, rb_intern("match"), 1, str);
}
Esempio n. 26
0
static VALUE rldap_msg_keys(VALUE obj)
{
	return rb_funcall(rb_iv_get(obj, "@attrs"), rb_intern("keys"), 0);
}
Esempio n. 27
0
File: oj.c Progetto: MSNexploder/oj
/* call-seq: default_options=(opts)
 *
 * Sets the default options for load and dump.
 * @param [Hash] opts options to change
 * @param [Fixnum] :indent number of spaces to indent each element in an JSON document
 * @param [String] :encoding character encoding for the JSON file
 * @param [true|false|nil] :circular support circular references while dumping
 * @param [true|false|nil] :auto_define automatically define classes if they do not exist
 * @param [true|false|nil] :symbol_keys convert hash keys to symbols
 * @param [true|false|nil] :ascii_only encode all high-bit characters as escaped sequences if true
 * @param [:object|:strict|:compat|:null] load and dump mode to use for JSON
 *        :strict raises an exception when a non-supported Object is
 *        encountered. :compat attempts to extract variable values from an
 *        Object using to_json() or to_hash() then it walks the Object's
 *        variables if neither is found. The :object mode ignores to_hash()
 *        and to_json() methods and encodes variables using code internal to
 *        the Oj gem. The :null mode ignores non-supported Objects and
 *        replaces them with a null.  @return [nil]
 */
static VALUE
set_def_opts(VALUE self, VALUE opts) {
    struct _YesNoOpt    ynos[] = {
        { circular_sym, &oj_default_options.circular },
        { auto_define_sym, &oj_default_options.auto_define },
        { symbol_keys_sym, &oj_default_options.sym_key },
        { ascii_only_sym, &oj_default_options.ascii_only },
        { Qnil, 0 }
    };
    YesNoOpt    o;
    VALUE       v;
    
    Check_Type(opts, T_HASH);

#ifdef HAVE_RUBY_ENCODING_H
    if (Qtrue == rb_funcall(opts, rb_intern("has_key?"), 1, encoding_sym)) {
	v = rb_hash_lookup(opts, encoding_sym);
	if (Qnil == v) {
	    oj_default_options.encoding = 0;
	} else if (T_STRING == rb_type(v)) {
	    oj_default_options.encoding = rb_enc_find(StringValuePtr(v));
	} else if (rb_cEncoding == rb_obj_class(v)) {
	    oj_default_options.encoding = rb_to_encoding(v);
	} else {
	    rb_raise(rb_eArgError, ":encoding must be nil, a String, or an Encoding.\n");
	}
    }
#endif
    v = rb_hash_aref(opts, indent_sym);
    if (Qnil != v) {
        Check_Type(v, T_FIXNUM);
        oj_default_options.indent = FIX2INT(v);
    }

    v = rb_hash_lookup(opts, mode_sym);
    if (Qnil == v) {
	// ignore
    } else if (object_sym == v) {
        oj_default_options.mode = ObjectMode;
    } else if (strict_sym == v) {
        oj_default_options.mode = StrictMode;
    } else if (compat_sym == v) {
        oj_default_options.mode = CompatMode;
    } else if (null_sym == v) {
        oj_default_options.mode = NullMode;
    } else {
        rb_raise(rb_eArgError, ":mode must be :object, :strict, :compat, or :null.\n");
    }

    for (o = ynos; 0 != o->attr; o++) {
	if (Qtrue != rb_funcall(opts, rb_intern("has_key?"), 1, o->sym)) {
	    continue;
	}
        if (Qnil != (v = rb_hash_lookup(opts, o->sym))) {
	    if (Qtrue == v) {
		*o->attr = Yes;
	    } else if (Qfalse == v) {
		*o->attr = No;
	    } else {
		rb_raise(rb_eArgError, "%s must be true, false, or nil.\n", rb_id2name(SYM2ID(o->sym)));
	    }
	}
    }
    return Qnil;
}
Esempio n. 28
0
VALUE
rb_exc_new(VALUE etype, const char *ptr, long len)
{
    return rb_funcall(etype, rb_intern("new"), 1, rb_str_new(ptr, len));
}
Esempio n. 29
0
VALUE rb_RPRuby_Sender_Kernel_internal_backtraceHashForControlFrame(  rb_control_frame_t**    c_current_frame )  {

  const char*    c_method_name    =  NULL;
  int        c_sourcefile_line  =  0;
  
  //  create new hash for this frame
  VALUE  rb_frame_hash      =  rb_hash_new();
    
  VALUE  rb_sourcefile_name    =  Qnil;
  VALUE  rb_sourcefile_line    =  Qnil;
  VALUE  rb_method_name      =  Qnil;
  VALUE  rb_object_for_frame    =  Qnil;
  
  if ( ( *c_current_frame )->iseq != 0 ) {
    
    if ( ( *c_current_frame )->pc != 0 ) {
      
      rb_iseq_t *iseq      = ( *c_current_frame )->iseq;
      
      //  get sourcefile name and set in hash
      rb_sourcefile_name    =  iseq->filename;
      
      //  get sourcefile line and set in hash
      c_sourcefile_line    =  rb_vm_get_sourceline( *c_current_frame );
      rb_sourcefile_line    =  INT2FIX( c_sourcefile_line );
      
      //  get name of instruction sequence
      rb_method_name      =  ID2SYM( rb_intern( StringValuePtr( iseq->name ) ) );        
      rb_object_for_frame  =  ( *c_current_frame )->self;
    }
  }
  else if ( RUBYVM_CFUNC_FRAME_P( *c_current_frame ) ) {
    
    //  get name of method

    #if RUBY_PATCHLEVEL >= -1
    //  For 1.9.2:
    const rb_method_entry_t*  c_method_for_frame  =  ( *c_current_frame )->me;
    c_method_name        =  rb_id2name( c_method_for_frame->called_id );
    #else
    //  For 1.9.1:
    c_method_name        =  rb_id2name( ( *c_current_frame )->method_id );
    #endif
    
    rb_method_name        =  ( c_method_name == NULL ? Qnil : ID2SYM( rb_intern( c_method_name ) ) );
    rb_object_for_frame  =  ( *c_current_frame )->self;    
  }
  //  we have to test this case - it works for blocks but there may be other cases too
  else if (  ( *c_current_frame )->block_iseq != 0
       &&  ( *c_current_frame )->pc == 0)  {
  
    //  If we got here we have a fiber
    //  There doesn't seem to be much that we can tell about a fiber's context
      
    VALUE      rb_current_fiber  =  rb_fiber_current();
    rb_fiber_t*    c_current_fiber    =  NULL;

    GetFiberPtr(  rb_current_fiber, 
            c_current_fiber);
            
    rb_context_t*  c_context      =  & c_current_fiber->cont;
    
//    rb_block_t*  c_blockptr = RUBY_VM_GET_BLOCK_PTR_IN_CFP( *c_current_frame );
     
    rb_object_for_frame  =  ( *c_current_frame )->self;
    
    //  get sourcefile name and set in hash
    rb_sourcefile_name    =  Qnil;

    //  get sourcefile line and set in hash
    rb_sourcefile_line    =  Qnil;
    
    //  get name of instruction sequence
    rb_method_name      =  rb_str_new2( "<Fiber>" );    
    
    //  if we have a fiber we also include its ruby reference since we have so little other context
    rb_hash_aset(  rb_frame_hash,
            ID2SYM( rb_intern( "fiber" ) ),
            c_context->self );
    
    //  The one time that we know a fiber is in use in the Ruby base is with Enumerators
    //  For now we will handle that with a special case
    
    VALUE  rb_enumerator_class  =  rb_const_get(  rb_cObject,
                            rb_intern( "Enumerator" ) );
    
    VALUE  rb_object_for_frame_klass  =  ( ( TYPE( rb_object_for_frame ) == T_CLASS ) ? rb_object_for_frame : rb_funcall( rb_object_for_frame, rb_intern( "class" ), 0 ) );

    VALUE  rb_ancestors  =  rb_funcall(  rb_object_for_frame_klass,
                        rb_intern( "ancestors" ),
                        0 );
    
    if ( rb_ary_includes(  rb_ancestors,
                rb_enumerator_class ) )  {
      
      struct enumerator* c_enumerator    =  enumerator_ptr( rb_object_for_frame );
      
      rb_object_for_frame  =  c_enumerator->obj;
      rb_method_name    =  ID2SYM( c_enumerator->meth );      
    }
    
  }
  else if (  ( *c_current_frame )->block_iseq == 0
       &&  ( *c_current_frame )->pc == 0)  {
    //  this happens after we had a fiber and we try to go up - which doesn't make sense with a fiber
    //  not sure what we want to do here, if anything
    return Qnil;
  }
  else {
    //  The third possibility is that we have an iseq frame with nil params for what we want
    //  In that case we can simply return the next frame
    *c_current_frame  =  RUBY_VM_PREVIOUS_CONTROL_FRAME( *c_current_frame );
    
    //  in theory this could crash because we are going forward a frame when we don't know what's there
    //  in practice I think we are ok, since we are only jumping forward from nil frames which should never be at the end
    //  at least - I don't think they should... we shall see.
    //  
    //  a fix would be to check the next frame, but that requires access to the thread or the limit cfp, 
    //  which requires passing more context; so for now, I'm leaving it there
    
    return rb_RPRuby_Sender_Kernel_internal_backtraceHashForControlFrame( c_current_frame );
  }

  //  Push values to return hash

  rb_hash_aset(  rb_frame_hash,
          ID2SYM( rb_intern( "object" ) ),
          rb_object_for_frame );
          
  rb_hash_aset(  rb_frame_hash,
          ID2SYM( rb_intern( "file" ) ),
          rb_sourcefile_name );

  rb_hash_aset(  rb_frame_hash,
          ID2SYM( rb_intern( "line" ) ),
          rb_sourcefile_line );

  rb_hash_aset(  rb_frame_hash,
          ID2SYM( rb_intern( "method" ) ),
          rb_method_name );
  
  return rb_frame_hash;
}
Esempio n. 30
0
static VALUE
call_next(VALUE obj)
{
    return rb_funcall(obj, id_next, 0);
}