Example #1
0
static VALUE Node_init(int argc, VALUE *args, VALUE self)
{
    vx_graph graph = 0;
    vx_kernel kernel = 0;
    Check_Type(self, T_DATA);

    if (argc <= 1)
        rb_raise(rb_eArgError, "Not enough arguments");

    graph = (vx_graph)DATA_PTR(args[0]);

    if (argc == 2) // Kernel
    {
        Check_Type(args[1], T_DATA);
        kernel = (vx_kernel)DATA_PTR(args[1]);
        DATA_PTR(self) = (void *)vxCreateGenericNode(graph, kernel);
    }
    else if (argc == 3) // graph, [string|enum], array of hashes
    {
        vx_node node = 0;
        VALUE kern = args[1];
        VALUE array = args[2];
        long param = 0;

        if (TYPE(kern) == T_STRING)
            kernel = vxGetKernelByName(context, RSTRING_PTR(kern));
        else if (TYPE(kern) == T_FIXNUM)
            kernel = vxGetKernelByEnum(context, FIX2INT(kern));
        else if (TYPE(kern) == T_DATA) // a OpenVX::Kernel
            kernel = (vx_kernel)DATA_PTR(kern);
        else
            rb_raise(rb_eTypeError, "kernel must be a string, fixnum, or OpenVX::Kernel");

        if (kernel == 0)
            rb_raise(rb_eNameError, "kernel could not be found in OpenVX");

        Check_Type(array, T_ARRAY);

        node = vxCreateGenericNode(graph, kernel);
        if (node == 0)
            rb_raise(rb_eTypeError, "node could not be created!");

        REXT_PRINT("Array of parameters has len = %ld\n", RARRAY_LEN(array));
        for (param = 0; param < RARRAY_LEN(array) ; param++)
        {
            VALUE ref,hash;
            vx_reference ref2 = 0;
            vx_status status = 0;
            const char *name = NULL;

            hash = rb_ary_entry(array, param);
            Check_Type(hash, T_HASH);
            ref = rb_hash_aref(hash, ID2SYM(rb_intern("ref")));
            name = rb_obj_classname(ref);
            REXT_PRINT("ref class = %s\n", name);
            Check_Type(ref, T_DATA);
            ref2 = (vx_reference)DATA_PTR(ref);
            status = vxSetParameterByIndex(node, param, ref2);
            REXT_PRINT("status = %d\n", status);

        }
        DATA_PTR(self) = (void *)node;
    }
    else
    {
        rb_raise(rb_eArgError, "incorrect number of arguments");
    }
    return Qnil;
}
Example #2
0
File: rcsv.c Project: fiksu/rcsv
/* An rb_rescue()-compatible Ruby pseudo-method that handles the actual parsing */
VALUE rcsv_raw_parse(VALUE ensure_container) {
  /* Unpacking multiple variables from a single Ruby VALUE */
  VALUE options = rb_ary_entry(ensure_container, 0);
  VALUE csvio   = rb_ary_entry(ensure_container, 1);
  struct rcsv_metadata * meta = (struct rcsv_metadata *)NUM2LONG(rb_ary_entry(ensure_container, 2));
  struct csv_parser * cp = (struct csv_parser *)NUM2LONG(rb_ary_entry(ensure_container, 3));

  /* Helper temporary variables */
  VALUE option, csvstr, buffer_size;

  /* libcsv-related temporary variables */
  char * csv_string;
  size_t csv_string_len;
  int error;

  /* Generic iterator */
  size_t i = 0;

  /* IO buffer size can be controller via an option */
  buffer_size = rb_hash_aref(options, ID2SYM(rb_intern("buffer_size")));

  /* By default, parse as Array of Arrays */
  option = rb_hash_aref(options, ID2SYM(rb_intern("row_as_hash")));
  if (option && (option != Qnil)) {
    meta->row_as_hash = true;
  }

  /* :col_sep sets the column separator, default is comma (,) */
  option = rb_hash_aref(options, ID2SYM(rb_intern("col_sep")));
  if (option != Qnil) {
    csv_set_delim(cp, (unsigned char)*StringValuePtr(option));
  }

  /* :quote_char sets the character used for quoting data; default is double-quote (") */
  option = rb_hash_aref(options, ID2SYM(rb_intern("quote_char")));
  if (option != Qnil) {
    csv_set_quote(cp, (unsigned char)*StringValuePtr(option));
  }

  /* Specify how many rows to skip from the beginning of CSV */
  option = rb_hash_aref(options, ID2SYM(rb_intern("offset_rows")));
  if (option != Qnil) {
    meta->offset_rows = (size_t)NUM2INT(option);
  }

  /* Specify the character encoding of the input data */
  option = rb_hash_aref(options, ID2SYM(rb_intern("output_encoding")));
  if (option && (option != Qnil)) {
    meta->encoding_index = RB_ENC_FIND_INDEX(StringValueCStr(option));
  }

  /* :only_rows is a list of values where row is only parsed
     if its fields match those in the passed array.
     [nil, nil, ["ABC", nil, 1]] skips all rows where 3rd column isn't equal to "ABC", nil or 1 */
  option = rb_hash_aref(options, ID2SYM(rb_intern("only_rows")));
  if (option != Qnil) {
    meta->num_only_rows = (size_t)RARRAY_LEN(option);
    meta->only_rows = (VALUE *)malloc(meta->num_only_rows * sizeof(VALUE));

    for (i = 0; i < meta->num_only_rows; i++) {
      VALUE only_row = rb_ary_entry(option, i);
      meta->only_rows[i] = validate_filter_row("only_rows", only_row);
    }
  }

  /* :except_rows is a list of values where row is only parsed
     if its fields don't match those in the passed array.
     [nil, nil, ["ABC", nil, 1]] skips all rows where 3rd column is equal to "ABC", nil or 1 */
  option = rb_hash_aref(options, ID2SYM(rb_intern("except_rows")));
  if (option != Qnil) {
    meta->num_except_rows = (size_t)RARRAY_LEN(option);
    meta->except_rows = (VALUE *)malloc(meta->num_except_rows * sizeof(VALUE));

    for (i = 0; i < meta->num_except_rows; i++) {
      VALUE except_row = rb_ary_entry(option, i);
      meta->except_rows[i] = validate_filter_row("except_rows", except_row);
    }
  }

  /* :row_defaults is an array of default values that are assigned to fields containing empty strings
     according to matching field positions */
  option = rb_hash_aref(options, ID2SYM(rb_intern("row_defaults")));
  if (option != Qnil) {
    meta->num_row_defaults = RARRAY_LEN(option);
    meta->row_defaults = (VALUE*)malloc(meta->num_row_defaults * sizeof(VALUE*));

    for (i = 0; i < meta->num_row_defaults; i++) {
      VALUE row_default = rb_ary_entry(option, i);
      meta->row_defaults[i] = row_default;
    }
  }

  /* :row_conversions specifies Ruby types that CSV field values should be converted into.
     Each char of row_conversions string represents Ruby type for CSV field with matching position. */
  option = rb_hash_aref(options, ID2SYM(rb_intern("row_conversions")));
  if (option != Qnil) {
    meta->num_row_conversions = RSTRING_LEN(option);
    meta->row_conversions = StringValuePtr(option);
  }

 /* Column names should be declared explicitly when parsing fields as Hashes */
  if (meta->row_as_hash) { /* Only matters for hash results */
    option = rb_hash_aref(options, ID2SYM(rb_intern("column_names")));
    if (option == Qnil) {
      rb_raise(rcsv_parse_error, ":row_as_hash requires :column_names to be set.");
    } else {
      meta->last_entry = rb_hash_new();

      meta->num_columns = (size_t)RARRAY_LEN(option);
      meta->column_names = (VALUE*)malloc(meta->num_columns * sizeof(VALUE*));

      for (i = 0; i < meta->num_columns; i++) {
        meta->column_names[i] = rb_ary_entry(option, i);
      }
    }
  } else {
    meta->last_entry = rb_ary_new();
  }

  while(true) {
    csvstr = rb_funcall(csvio, rb_intern("read"), 1, buffer_size);
    if ((csvstr == Qnil) || (RSTRING_LEN(csvstr) == 0)) { break; }

    csv_string = StringValuePtr(csvstr);
    csv_string_len = strlen(csv_string);

    /* Actual parsing and error handling */
    if (csv_string_len != csv_parse(cp, csv_string, csv_string_len,
                                    &end_of_field_callback, &end_of_line_callback, meta)) {
      error = csv_error(cp);
      switch(error) {
        case CSV_EPARSE:
          rb_raise(rcsv_parse_error, "Error when parsing malformed data");
          break;
        case CSV_ENOMEM:
          rb_raise(rcsv_parse_error, "No memory");
          break;
        case CSV_ETOOBIG:
          rb_raise(rcsv_parse_error, "Field data is too large");
          break;
        case CSV_EINVALID:
          rb_raise(rcsv_parse_error, "%s", (const char *)csv_strerror(error));
        break;
        default:
          rb_raise(rcsv_parse_error, "Failed due to unknown reason");
      }
    }
  }

  /* Flushing libcsv's buffer */
  csv_fini(cp, &end_of_field_callback, &end_of_line_callback, meta);

  return Qnil;
}
Example #3
0
/*
 * R2D::Window#show
 */
static VALUE r2d_show(VALUE self) {
  
  // SDL Inits /////////////////////////////////////////////////////////////////
  
  SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
  TTF_Init();
  
  // Create SDL window and configure ///////////////////////////////////////////
  
  char* win_title = RSTRING_PTR(rb_iv_get(self, "@title"));
  int win_width   = NUM2INT(rb_iv_get(self, "@width"));
  int win_height  = NUM2INT(rb_iv_get(self, "@height"));
  int fps_cap     = NUM2INT(rb_iv_get(self, "@fps_cap"));
  bool vsync      = RTEST(rb_iv_get(self, "@vsync"));
  
  SDL_Window *window = SDL_CreateWindow(
    win_title,                                       // title
    SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,  // window position
    win_width, win_height,                           // window size
    SDL_WINDOW_OPENGL                                // flags
  );
  
  // Check if windows was successfully created
  if (!window) {
    printf("R2D Error: Could not create window: %s\n", SDL_GetError());
    return 1;
  }
  
  // Enable VSync
  if (vsync) {
    if (!SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1")) {
      printf("R2D Warning: VSync cannot be enabled!");
    }
  }
  
  // OpenGL Inits //////////////////////////////////////////////////////////////
  
  SDL_GLContext glcontext = SDL_GL_CreateContext(window);
  initGL(win_width, win_height);
  
  // Create SDL Renderer for Accelerated 2D ////////////////////////////////////
  
  SDL_Renderer *renderer = SDL_CreateRenderer(
    window, -1, SDL_RENDERER_ACCELERATED
  );
  
  // Setting up variables
  int cursor_x, cursor_y;  // Cursor positions
  const Uint8 *key_state;
  Uint32 frames = 0;       // Total frames since start
  Uint32 start_ms = SDL_GetTicks();  // Elapsed time since start
  Uint32 begin_ms = start_ms;  // TIme at beginning of loop
  Uint32 end_ms;    // Time at end of loop
  Uint32 total_ms;  // Total elapsed time
  Uint32 loop_ms;   // Elapsed time of loop
  int delay_ms;     // Amount of delay to achieve desired frame rate
  double fps;       // The actual frame rate
  
  // Main Event Loop ///////////////////////////////////////////////////////////
  
  bool quit = false;
  while (!quit) {
    
    // Set FPS /////////////////////////////////////////////////////////////////
    
    frames++;
    end_ms = SDL_GetTicks();
    
    total_ms = end_ms - start_ms;
    fps = frames / (total_ms / 1000.0);
    
    loop_ms = end_ms - begin_ms;
    delay_ms = (1000 / fps_cap) - loop_ms;
    
    if (delay_ms < 0) { delay_ms = 0; }
    
    // loop_ms + delay_ms => should equal (1000 / fps_cap)
    
    // Store FPS info
    rb_iv_set(self, "@frames", INT2NUM(frames));
    rb_iv_set(self, "@total_ms", INT2NUM(total_ms));
    rb_iv_set(self, "@loop_ms", INT2NUM(loop_ms));
    rb_iv_set(self, "@fps", DBL2NUM(fps));
    
    SDL_Delay(delay_ms);
    begin_ms = SDL_GetTicks();
    
    // Handle Input ////////////////////////////////////////////////////////////
    
    SDL_Event e;
    while (SDL_PollEvent(&e)) {
      switch(e.type) {
        case SDL_KEYDOWN:
          rb_funcall(self, rb_intern("on_key_callback"), 1,
            rb_str_new2(SDL_GetScancodeName(e.key.keysym.scancode))
          );
          break;
        case SDL_QUIT:
          quit = true;
          break;
      }
    }
    
    int num_keys;
    key_state = SDL_GetKeyboardState(&num_keys);
    
    for (int i = 0; i < num_keys; i++) {
      if (key_state[i] == 1) {
        rb_funcall(self, rb_intern("keys_down_callback"), 1,
          rb_str_new2(SDL_GetScancodeName(i))
        );
      }
    }
    
    // Store the cursor position
    SDL_GetMouseState(&cursor_x, &cursor_y);
    rb_iv_set(self, "@cursor_x", INT2NUM(cursor_x));
    rb_iv_set(self, "@cursor_y", INT2NUM(cursor_y));
    
    // Update Application State ////////////////////////////////////////////////
    
    // Call update proc, `window.update`
    rb_funcall(self, rb_intern("update_callback"), 0);
    
    // Draw Objects ////////////////////////////////////////////////////////////
    
    glClear(GL_COLOR_BUFFER_BIT);
    
    // Read window objects
    VALUE objects = rb_iv_get(self, "@objects");
    int num_objects = NUM2INT(rb_funcall(objects, rb_intern("count"), 0));
    
    // Switch on each object type
    for (int i = 0; i < num_objects; ++i) {
      
      VALUE el = rb_ary_entry(objects, i);
      int type_id = NUM2INT(rb_iv_get(el, "@type_id"));
      
      // Switch on the object's type_id
      switch(type_id) {
        
        case TRIANGLE: {
          VALUE c1 = rb_iv_get(el, "@c1");
          VALUE c2 = rb_iv_get(el, "@c2");
          VALUE c3 = rb_iv_get(el, "@c3");
          
          draw_triangle(
            NUM2DBL(rb_iv_get(el, "@x1")),
            NUM2DBL(rb_iv_get(el, "@y1")),
            NUM2DBL(rb_iv_get(c1, "@r")),
            NUM2DBL(rb_iv_get(c1, "@g")),
            NUM2DBL(rb_iv_get(c1, "@b")),
            NUM2DBL(rb_iv_get(c1, "@a")),
            
            NUM2DBL(rb_iv_get(el, "@x2")),
            NUM2DBL(rb_iv_get(el, "@y2")),
            NUM2DBL(rb_iv_get(c2, "@r")),
            NUM2DBL(rb_iv_get(c2, "@g")),
            NUM2DBL(rb_iv_get(c2, "@b")),
            NUM2DBL(rb_iv_get(c2, "@a")),
            
            NUM2DBL(rb_iv_get(el, "@x3")),
            NUM2DBL(rb_iv_get(el, "@y3")),
            NUM2DBL(rb_iv_get(c3, "@r")),
            NUM2DBL(rb_iv_get(c3, "@g")),
            NUM2DBL(rb_iv_get(c3, "@b")),
            NUM2DBL(rb_iv_get(c3, "@a"))
          );
        }
        break;
        
        case QUAD: {
          VALUE c1 = rb_iv_get(el, "@c1");
          VALUE c2 = rb_iv_get(el, "@c2");
          VALUE c3 = rb_iv_get(el, "@c3");
          VALUE c4 = rb_iv_get(el, "@c4");
          
          draw_triangle(
            NUM2DBL(rb_iv_get(el, "@x1")),
            NUM2DBL(rb_iv_get(el, "@y1")),
            NUM2DBL(rb_iv_get(c1, "@r")),
            NUM2DBL(rb_iv_get(c1, "@g")),
            NUM2DBL(rb_iv_get(c1, "@b")),
            NUM2DBL(rb_iv_get(c1, "@a")),
            
            NUM2DBL(rb_iv_get(el, "@x2")),
            NUM2DBL(rb_iv_get(el, "@y2")),
            NUM2DBL(rb_iv_get(c2, "@r")),
            NUM2DBL(rb_iv_get(c2, "@g")),
            NUM2DBL(rb_iv_get(c2, "@b")),
            NUM2DBL(rb_iv_get(c2, "@a")),
            
            NUM2DBL(rb_iv_get(el, "@x3")),
            NUM2DBL(rb_iv_get(el, "@y3")),
            NUM2DBL(rb_iv_get(c3, "@r")),
            NUM2DBL(rb_iv_get(c3, "@g")),
            NUM2DBL(rb_iv_get(c3, "@b")),
            NUM2DBL(rb_iv_get(c3, "@a"))
          );
          
          draw_triangle(
            NUM2DBL(rb_iv_get(el, "@x3")),
            NUM2DBL(rb_iv_get(el, "@y3")),
            NUM2DBL(rb_iv_get(c3, "@r")),
            NUM2DBL(rb_iv_get(c3, "@g")),
            NUM2DBL(rb_iv_get(c3, "@b")),
            NUM2DBL(rb_iv_get(c3, "@a")),
            
            NUM2DBL(rb_iv_get(el, "@x4")),
            NUM2DBL(rb_iv_get(el, "@y4")),
            NUM2DBL(rb_iv_get(c4, "@r")),
            NUM2DBL(rb_iv_get(c4, "@g")),
            NUM2DBL(rb_iv_get(c4, "@b")),
            NUM2DBL(rb_iv_get(c4, "@a")),
            
            NUM2DBL(rb_iv_get(el, "@x1")),
            NUM2DBL(rb_iv_get(el, "@y1")),
            NUM2DBL(rb_iv_get(c1, "@r")),
            NUM2DBL(rb_iv_get(c1, "@g")),
            NUM2DBL(rb_iv_get(c1, "@b")),
            NUM2DBL(rb_iv_get(c1, "@a"))
          );
        }
        break;
        
        case IMAGE: {
          if (rb_iv_get(el, "@data") == Qnil) {
            VALUE data = init_image(
              renderer,
              RSTRING_PTR(rb_iv_get(el, "@path"))
            );
            rb_iv_set(el, "@data", data);
          }
          
          draw_image(
            el,
            NUM2DBL(rb_iv_get(el, "@x")),
            NUM2DBL(rb_iv_get(el, "@y"))
          );
        }
        break;
        
        case TEXT: {
          if (rb_iv_get(el, "@data") == Qnil) {
            VALUE data = init_text(
              renderer,
              RSTRING_PTR(rb_iv_get(el, "@font")),
              RSTRING_PTR(rb_iv_get(el, "@text")),
              NUM2DBL(rb_iv_get(el, "@size"))
            );
            rb_iv_set(el, "@data", data);
          }
          
          // // TODO: Set color of text
          // VALUE c = rb_iv_get(el, "@c");
          // NUM2DBL(rb_iv_get(c, "@r")),
          // NUM2DBL(rb_iv_get(c, "@g")),
          // NUM2DBL(rb_iv_get(c, "@b")),
          
          draw_text(
            el,
            RSTRING_PTR(rb_iv_get(el, "@text")),
            NUM2DBL(rb_iv_get(el, "@x")),
            NUM2DBL(rb_iv_get(el, "@y"))
          );
        }
        break;
      }
    }
    
    // Draw frame
    SDL_GL_SwapWindow(window);
  }
  
  // Clean up
  IMG_Quit();
  Mix_Quit();
  SDL_GL_DeleteContext(glcontext);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();
  
  return 0;
}
Example #4
0
/*
 * call-seq:
 *    ctx.setup => Qtrue # first time
 *    ctx.setup => nil # thereafter
 *
 * This method is called automatically when a new SSLSocket is created.
 * Normally you do not need to call this method (unless you are writing an extension in C).
 */
static VALUE
ossl_sslctx_setup(VALUE self)
{
  SSL_CTX *ctx;
  X509 *cert = NULL, *client_ca = NULL;
  X509_STORE *store;
  EVP_PKEY *key = NULL;
  char *ca_path = NULL, *ca_file = NULL;
  int i, verify_mode;
  VALUE val;

  Data_Get_Struct(self, SSL_CTX, ctx);

  if(SSL_CTX_get_ex_data(ctx, ossl_ssl_ex_ptr_idx) == (void*)self) return Qnil;
  SSL_CTX_set_ex_data(ctx, ossl_ssl_ex_ptr_idx, (void*)self);

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

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

  val = ossl_sslctx_get_extra_cert(self);
  if(!NIL_P(val)){
    size_t i;
    for(i = 0; i < rb_ary_size(val); i++) {
      ossl_sslctx_add_extra_chain_cert_i(rb_ary_entry(val, i), self);
    }
  }

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

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

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

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

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

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

  val = ossl_sslctx_get_options(self);
  if(!NIL_P(val)) SSL_CTX_set_options(ctx, NUM2LONG(val));

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

  if (RTEST(rb_iv_get(self, "@session_get_cb"))) {
    SSL_CTX_sess_set_get_cb(ctx, ossl_sslctx_session_get_cb);
    OSSL_Debug("SSL SESSION get callback added");
  }
  if (RTEST(rb_iv_get(self, "@session_new_cb"))) {
    SSL_CTX_sess_set_new_cb(ctx, ossl_sslctx_session_new_cb);
    OSSL_Debug("SSL SESSION new callback added");
  }
  if (RTEST(rb_iv_get(self, "@session_remove_cb"))) {
    SSL_CTX_sess_set_remove_cb(ctx, ossl_sslctx_session_remove_cb);
    OSSL_Debug("SSL SESSION remove callback added");
  }
  return Qtrue;
}
Example #5
0
/* grpc_rb_md_ary_fill_hash_cb is the hash iteration callback used
   to fill grpc_metadata_array.

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

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

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

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

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

  return ST_CONTINUE;
}
Example #6
0
static VALUE array_spec_rb_ary_entry(VALUE self, VALUE array, VALUE offset) {
  return rb_ary_entry(array, FIX2INT(offset));
}
Example #7
0
static GEOSCoordSequence* coord_seq_from_array(VALUE factory, VALUE array, char close)
{
  Check_Type(array, T_ARRAY);
  RGeo_FactoryData* factory_data = RGEO_FACTORY_DATA_PTR(factory);
  VALUE point_type = factory_data->globals->feature_point;
  unsigned int len = (unsigned int)RARRAY_LEN(array);
  char has_z = (char)(RGEO_FACTORY_DATA_PTR(factory)->flags & RGEO_FACTORYFLAGS_SUPPORTS_Z_OR_M);
  unsigned int dims = has_z ? 3 : 2;
  double* coords = ALLOC_N(double, len == 0 ? 1 : len * dims);
  if (!coords) {
    return NULL;
  }
  GEOSContextHandle_t context = factory_data->geos_context;
  unsigned int i;
  for (i=0; i<len; ++i) {
    char good = 0;
    const GEOSGeometry* entry_geom = rgeo_convert_to_geos_geometry(factory, rb_ary_entry(array, i), point_type);
    if (entry_geom) {
      const GEOSCoordSequence* entry_cs = GEOSGeom_getCoordSeq_r(context, entry_geom);
      if (entry_cs) {
        double x;
        if (GEOSCoordSeq_getX_r(context, entry_cs, 0, &x)) {
          coords[i*dims] = x;
          if (GEOSCoordSeq_getY_r(context, entry_cs, 0, &x)) {
            coords[i*dims+1] = x;
            good = 1;
            if (has_z) {
              if (GEOSCoordSeq_getZ_r(context, entry_cs, 0, &x)) {
                coords[i*dims+2] = x;
              }
              else {
                good = 0;
              }
            }
          }
        }
      }
    }
    if (!good) {
      free(coords);
      return NULL;
    }
  }
  if (len > 0 && close) {
    if (coords[0] == coords[(len-1)*dims] && coords[1] == coords[(len-1)*dims+1]) {
      close = 0;
    }
  }
  else {
    close = 0;
  }
  GEOSCoordSequence* coord_seq = GEOSCoordSeq_create_r(context, len + close, 3);
  if (coord_seq) {
    for (i=0; i<len; ++i) {
      GEOSCoordSeq_setX_r(context, coord_seq, i, coords[i*dims]);
      GEOSCoordSeq_setY_r(context, coord_seq, i, coords[i*dims+1]);
      GEOSCoordSeq_setZ_r(context, coord_seq, i, has_z ? coords[i*dims+2] : 0);
    }
    if (close) {
      GEOSCoordSeq_setX_r(context, coord_seq, len, coords[0]);
      GEOSCoordSeq_setY_r(context, coord_seq, len, coords[1]);
      GEOSCoordSeq_setZ_r(context, coord_seq, len, has_z ? coords[2] : 0);
    }
  }
  free(coords);
  return coord_seq;
}
Example #8
0
static VALUE rb_mysql_result_each_(VALUE self,
                                   VALUE(*fetch_row_func)(VALUE, MYSQL_FIELD *fields, const result_each_args *args),
                                   const result_each_args *args)
{
  unsigned long i;
  const char *errstr;
  MYSQL_FIELD *fields = NULL;

  GET_RESULT(self);

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

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

      fields = mysql_fetch_fields(wrapper->result);

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

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

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

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

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

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

  // FIXME return Enumerator instead?
  // return rb_ary_each(wrapper->rows);
  return wrapper->rows;
}
Example #9
0
static int write_element(VALUE key, VALUE value, VALUE extra, int allow_id) {
    buffer_t buffer = (buffer_t)NUM2LL(rb_ary_entry(extra, 0));
    VALUE check_keys = rb_ary_entry(extra, 1);

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

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

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

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

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

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

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

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

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

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

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

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

                start_position = buffer_get_position(buffer);

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

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

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

            write_name_and_type(buffer, key, 0x0B);

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

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

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

            break;
        }
    default:
        {
            const char* cls = rb_obj_classname(value);
            buffer_free(buffer);
            rb_raise(InvalidDocument, "Cannot serialize an object of class %s (type %d) into BSON.", cls, TYPE(value));
            break;
        }
    }
    return ST_CONTINUE;
}
Example #10
0
static void* get_parameter(const ool_conmin_minimizer_type *T, ool_conmin_pgrad_parameters *Pp,
	ool_conmin_spg_parameters *Ps, ool_conmin_gencan_parameters *Pg, VALUE ary)
{
	if (T == ool_conmin_minimizer_pgrad) {
		if (ary == Qnil) {
			ool_conmin_parameters_default(T, (void*) Pp);
		} else {
			Pp->fmin = NUM2DBL(rb_ary_entry(ary, 0));
			Pp->tol = NUM2DBL(rb_ary_entry(ary, 1));		
			Pp->alpha = NUM2DBL(rb_ary_entry(ary, 2));
			Pp->sigma1 = NUM2DBL(rb_ary_entry(ary, 3));
			Pp->sigma2 = NUM2DBL(rb_ary_entry(ary, 4));						
		}
		return (void*) Pp;
	} else if (T == ool_conmin_minimizer_spg) {
		if (ary == Qnil) {
			ool_conmin_parameters_default(T, (void*) Ps);
		} else {
			Ps->fmin = NUM2DBL(rb_ary_entry(ary, 0));
			Ps->tol = NUM2DBL(rb_ary_entry(ary, 1));		
			Ps->M = NUM2DBL(rb_ary_entry(ary, 2));
			Ps->alphamin = NUM2DBL(rb_ary_entry(ary, 3));
			Ps->alphamax = NUM2DBL(rb_ary_entry(ary, 4));								
			Ps->gamma = NUM2DBL(rb_ary_entry(ary, 5));								
			Ps->sigma2 = NUM2DBL(rb_ary_entry(ary, 6));										
			Ps->sigma2 = NUM2DBL(rb_ary_entry(ary, 7));												
		}
		return (void*) Ps;
	} else {
		if (ary == Qnil) {
			ool_conmin_parameters_default(T, (void*) Pg);
		} else {
			Pg->epsgpen = NUM2DBL(rb_ary_entry(ary, 0));
			Pg->epsgpsn = NUM2DBL(rb_ary_entry(ary, 1));		
			Pg->fmin = NUM2DBL(rb_ary_entry(ary, 2));
			Pg->udelta0 = NUM2DBL(rb_ary_entry(ary, 3));
			Pg->ucgmia = NUM2DBL(rb_ary_entry(ary, 4));								
			Pg->ucgmib = NUM2DBL(rb_ary_entry(ary, 5));								
			Pg->cg_scre = FIX2INT(rb_ary_entry(ary, 6));										
			Pg->cg_gpnf = NUM2DBL(rb_ary_entry(ary, 7));				
			Pg->cg_epsi = NUM2DBL(rb_ary_entry(ary, 8));				
			Pg->cg_epsf = NUM2DBL(rb_ary_entry(ary, 9));													
			Pg->cg_epsnqmp = NUM2DBL(rb_ary_entry(ary, 10));
			Pg->cg_maxitnqmp = (size_t) FIX2INT(rb_ary_entry(ary, 11));
			Pg->nearlyq = FIX2INT(rb_ary_entry(ary, 12));			
			Pg->nint = NUM2DBL(rb_ary_entry(ary, 13));						
			Pg->next = NUM2DBL(rb_ary_entry(ary, 14));						
			Pg->mininterp = (size_t) FIX2INT(rb_ary_entry(ary, 15));
			Pg->maxextrap = (size_t) FIX2INT(rb_ary_entry(ary, 16));						
			Pg->trtype = FIX2INT(rb_ary_entry(ary, 17));						
			Pg->eta = NUM2DBL(rb_ary_entry(ary, 18));																
			Pg->delmin = NUM2DBL(rb_ary_entry(ary, 19));			
			Pg->lspgmi = NUM2DBL(rb_ary_entry(ary, 20));			
			Pg->lspgma = NUM2DBL(rb_ary_entry(ary, 21));			
			Pg->theta = NUM2DBL(rb_ary_entry(ary, 22));			
			Pg->gamma = NUM2DBL(rb_ary_entry(ary, 23));
			Pg->beta = NUM2DBL(rb_ary_entry(ary, 24));			
			Pg->sigma1 = NUM2DBL(rb_ary_entry(ary, 25));			
			Pg->sigma2 = NUM2DBL(rb_ary_entry(ary, 26));			
			Pg->epsrel = NUM2DBL(rb_ary_entry(ary, 27));			
			Pg->epsabs = NUM2DBL(rb_ary_entry(ary, 28));			
			Pg->infrel = NUM2DBL(rb_ary_entry(ary, 29));			
			Pg->infabs = NUM2DBL(rb_ary_entry(ary, 30));															
		}		
		return (void*) Pg;		
	}
}
Example #11
0
static VALUE rb_ool_conmin_function_params(VALUE obj)
{
	ool_conmin_function *F;
	Data_Get_Struct(obj, ool_conmin_function, F);
	return rb_ary_entry((VALUE) F->params, 4);;
}
Example #12
0
File: cparse.c Project: hsbt/racc
static VALUE
reduce0(VALUE val, VALUE data, VALUE self)
{
    struct cparse_params *v;
    VALUE reduce_to, reduce_len, method_id;
    long len;
    ID mid;
    VALUE tmp, tmp_t = Qundef, tmp_v = Qundef;
    long i, k1, k2;
    VALUE goto_state;

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

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

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

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

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

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

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

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

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

  notfound:
    D_puts("(goto) not found: use default");
    /* overwrite `goto-state' by default value */
    goto_state = AREF(v->goto_default, k1);
    goto transit;
}
Example #13
0
File: cparse.c Project: hsbt/racc
static void
parse_main(struct cparse_params *v, VALUE tok, VALUE val, int resume)
{
    long i;              /* table index */
    long act;            /* action type */
    VALUE act_value;     /* action type, VALUE version */
    int read_next = 1;   /* true if we need to read next token */
    VALUE tmp;

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

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

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

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

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

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

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


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

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


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


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

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

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

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

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

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

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

    /* shift/reduce error token */
    if (act > 0 && act < v->shift_n) {
        D_puts("e shift");
        SHIFT(v, act, ERROR_TOKEN, val);
    }
    else if (act < 0 && act > -(v->reduce_n)) {
        D_puts("e reduce");
        REDUCE(v, act);
    }
    else if (act == v->shift_n) {
        D_puts("e accept");
        goto accept;
    }
    else {
        rb_raise(RaccBug, "[Racc Bug] unknown act value %ld", act);
    }
    goto error_recovered;
}
Example #14
0
File: cparse.c Project: hsbt/racc
static VALUE
initialize_params(VALUE vparams, VALUE parser, VALUE lexer, VALUE lexmid)
{
    struct cparse_params *v;

    Data_Get_Struct(vparams, struct cparse_params, v);
    v->value_v = vparams;
    v->parser = parser;
    v->lexer = lexer;
    if (! NIL_P(lexmid))
        v->lexmid = value_to_id(lexmid);
    v->debug = RTEST(rb_ivar_get(parser, id_yydebug));

    Check_Type(arg, T_ARRAY);
    if (!(13 <= RARRAY_LEN(arg) && RARRAY_LEN(arg) <= 14))
        rb_raise(RaccBug, "[Racc Bug] wrong arg.size %ld", RARRAY_LEN(arg));
    v->action_table   = assert_array  (rb_ary_entry(arg,  0));
    v->action_check   = assert_array  (rb_ary_entry(arg,  1));
    v->action_default = assert_array  (rb_ary_entry(arg,  2));
    v->action_pointer = assert_array  (rb_ary_entry(arg,  3));
    v->goto_table     = assert_array  (rb_ary_entry(arg,  4));
    v->goto_check     = assert_array  (rb_ary_entry(arg,  5));
    v->goto_default   = assert_array  (rb_ary_entry(arg,  6));
    v->goto_pointer   = assert_array  (rb_ary_entry(arg,  7));
    v->nt_base        = assert_integer(rb_ary_entry(arg,  8));
    v->reduce_table   = assert_array  (rb_ary_entry(arg,  9));
    v->token_table    = assert_hash   (rb_ary_entry(arg, 10));
    v->shift_n        = assert_integer(rb_ary_entry(arg, 11));
    v->reduce_n       = assert_integer(rb_ary_entry(arg, 12));
    if (RARRAY_LEN(arg) > 13) {
        v->use_result_var = RTEST(rb_ary_entry(arg, 13));
    }
    else {
        v->use_result_var = Qtrue;
    }

    v->use_result_var  = NUM2INT(rb_ivar_get(parser, id_use_result));

    /* if (RARRAY_LEN(arg) > 13) { */
    /*     v->use_result_var = RTEST(RARRAY_PTR(arg)[13]); */
    /* } */
    /* else { */
    /*     v->use_result_var = Qtrue; */
    /* } */

    PUSH(v->state, INT2FIX(0));

    rb_ivar_set(parser, id_errstatus, LONG2NUM(v->errstatus));

    rb_iv_set(parser, "@vstack", v->vstack);

    if (v->debug) {
        rb_iv_set(parser, "@tstack", v->tstack);
    }
    else {
        rb_iv_set(parser, "@tstack", Qnil);
    }

    return vparams;
}
Example #15
0
VALUE rho_ruby_array_get(VALUE ar, int nIndex)
{
    return rb_ary_entry( ar, nIndex);
}
Example #16
0
bp::Object *
rubyToBPObject(VALUE v)
{
    bp::Object * obj = NULL;
    
    switch (TYPE(v)) {
        case T_FLOAT:
            obj = new bp::Double(rb_num2dbl(v));
            break;
        case T_STRING:
            obj = new bp::String(RSTRING_PTR(v));
            break;
        case T_FIXNUM:
            obj = new bp::Integer(rb_num2ull(v));
            break;
        case T_TRUE:
            obj = new bp::Bool(true);
            break;
        case T_FALSE:
            obj = new bp::Bool(false);
            break;
        case T_HASH:
            obj = new bp::Map;
            rb_hash_foreach(v,
                            (int (*)(ANYARGS)) hashPopulator,
                            (VALUE) obj);
            break;
        case T_ARRAY:
        {
            long i;
            bp::List * l = new bp::List;
            for (i=0; i < RARRAY_LEN(v); i++) {
                l->append(rubyToBPObject(rb_ary_entry(v, i)));
            }
            obj = l;
        }
        break;
        case T_OBJECT: {
            // map Pathname objects into BPTPath types
            VALUE id = rb_intern("Pathname");
            VALUE klass = 0;
            if (rb_const_defined(rb_cObject, id) &&
                (klass = rb_const_get(rb_cObject, id)) &&
                TYPE(klass) == T_CLASS)
            {
                VALUE r = rb_obj_is_kind_of(v, klass);
                if (RTEST(r)) {
                    // convert to abs path
                    int error = 0;
                    VALUE absPath =
                        ruby::invokeFunction(v, "realpath", &error, 0);
                    VALUE pathString =
                        ruby::invokeFunction(absPath, "to_s", &error, 0);
                    if (!error && TYPE(pathString) == T_STRING) {
						obj = new bp::Path((const BPPath) convert::fromUTF8(RSTRING_PTR(pathString)).c_str());
                    }
                    break;
                }
            }
        }
        case T_NIL:
        default:
            obj = new bp::Null();
            break;
    }
    
    return obj;
}
Example #17
0
static VALUE Node_init(int argc, VALUE *args, VALUE self)
{
    vx_graph graph = 0;
    vx_kernel kernel = 0;
    VALUE w,h,f;
    Check_Type(self, T_DATA);

    if (argc <= 1)
        rb_raise(rb_eArgError, "Not enough arguments");

    graph = (vx_graph)DATA_PTR(args[0]);

    if (argc == 2) // Kernel
    {
        Check_Type(args[1], T_DATA);
        kernel = (vx_kernel)DATA_PTR(args[1]);
        DATA_PTR(self) = (void *)vxCreateNode(graph, kernel);
    }
    else if (argc == 3) // graph, [string|enum], array of hashes
    {
        vx_node node = 0;
        vx_uint32 p = 0;
        VALUE kern = args[1];
        VALUE array = args[2];
        long param = 0;

        if (TYPE(kern) == T_STRING)
            kernel = vxGetKernelByName(context, RSTRING(kern)->ptr);
        else if (TYPE(kern) == T_FIXNUM)
            kernel = vxGetKernelByEnum(context, FIX2INT(kern));
        else if (TYPE(kern) == T_DATA) // a OpenVX::Kernel
            kernel = (vx_kernel)DATA_PTR(kern);
        else
            rb_raise(rb_eTypeError, "kernel must be a string, fixnum, or OpenVX::Kernel");

        if (kernel == 0)
            rb_raise(rb_eNameError, "kernel could not be found in OpenVX");

        Check_Type(array, T_ARRAY);

        node = vxCreateNode(graph, kernel);
        if (node == 0)
            rb_raise(rb_eTypeError, "node could not be created!");

        REXT_PRINT("Array of parameters has len = %ld\n", RARRAY(array)->len);
        for (param = 0; param < RARRAY(array)->len ; param++)
        {
            VALUE dir,ref,hash;
            vx_reference ref2 = 0;
            vx_status status = 0;
            vx_enum type = VX_TYPE_INVALID;
            const char *name;

            hash = rb_ary_entry(array, param);
            Check_Type(hash, T_HASH);
            dir = rb_hash_aref(hash, ID2SYM(rb_intern("dir")));
            ref = rb_hash_aref(hash, ID2SYM(rb_intern("ref")));
            name = rb_obj_classname(ref);

            REXT_PRINT("rb_type(dir)=0x%x\n", TYPE(dir));
            REXT_PRINT("ref class = %s\n", name);

            Check_Type(dir, T_FIXNUM);
            Check_Type(ref, T_DATA);

            REXT_PRINT("dir=%ld\n", FIX2UINT(dir));

            ref2 = (vx_reference)DATA_PTR(ref);
            if (strcmp("OpenVX::Image", name) == 0)
                type = VX_TYPE_IMAGE;
            else if (strcmp("OpenVX::Buffer", name) == 0)
                type = VX_TYPE_BUFFER;
            else if (strcmp("OpenVX::Scalar", name) == 0)
                type = VX_TYPE_MAX;

            REXT_PRINT("vx type = %d (0x%08x)\n", type, type);
            if (type == VX_TYPE_IMAGE) // replace with format
                status = vxQueryImage(ref2, VX_QUERY_IMAGE_FORMAT, &type, sizeof(vx_fourcc));
            else if (type == VX_TYPE_MAX)
                status = vxQueryReference(ref2, VX_QUERY_REF_TYPE, &type, sizeof(type));
            REXT_PRINT("status = %d vx type = %d (0x%08x)\n", status, type, type);

            status = vxSetParameterByIndex(node, param, FIX2UINT(dir), type, ref2);
            REXT_PRINT("status = %d\n", status);

        }
        DATA_PTR(self) = (void *)node;
    }
    else
    {
        rb_raise(rb_eArgError, "incorrect number of arguments");
    }
    return Qnil;
}
Example #18
0
/* call-seq: emitter.start_document(version, tags, implicit)
 *
 * Start a document emission with YAML +version+, +tags+, and an +implicit+
 * start.
 *
 * See Psych::Handler#start_document
 */
static VALUE start_document(VALUE self, VALUE version, VALUE tags, VALUE imp)
{
    yaml_emitter_t * emitter;
    yaml_tag_directive_t * head = NULL;
    yaml_tag_directive_t * tail = NULL;
    yaml_event_t event;
    yaml_version_directive_t version_directive;
    Data_Get_Struct(self, yaml_emitter_t, emitter);


    Check_Type(version, T_ARRAY);

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

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

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

        Check_Type(tags, T_ARRAY);

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

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

            Check_Type(tuple, T_ARRAY);

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

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

            tail++;
        }
    }

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

    emit(emitter, &event);

    if(head) xfree(head);

    return self;
}
Example #19
0
static VALUE sub_pair(VALUE el, VALUE holder) {
  return rb_ary_push(holder, rb_ary_entry(el, 1));
}
Example #20
0
static VALUE
fntype_initialize(int argc, VALUE* argv, VALUE self)
{
    FunctionType *fnInfo;
    ffi_status status;
    VALUE rbReturnType = Qnil, rbParamTypes = Qnil, rbOptions = Qnil;
    VALUE rbEnums = Qnil, rbConvention = Qnil, rbBlocking = Qnil;
#if defined(_WIN32) || defined(__WIN32__)
    VALUE rbConventionStr;
#endif
    int i, nargs;

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

    Check_Type(rbParamTypes, T_ARRAY);

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

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

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

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

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

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

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

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


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

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

    fnInfo->invoke = rbffi_GetInvoker(fnInfo);

    return self;
}
/*
  call-seq:
    creds = ServerCredentials.new(nil,
                                  [{private_key: <pem_private_key1>,
                                   {cert_chain: <pem_cert_chain1>}],
                                  force_client_auth)
    creds = ServerCredentials.new(pem_root_certs,
                                  [{private_key: <pem_private_key1>,
                                   {cert_chain: <pem_cert_chain1>}],
                                  force_client_auth)

    pem_root_certs: (optional) PEM encoding of the server root certificate
    pem_private_key: (required) PEM encoding of the server's private keys
    force_client_auth: indicatees

    Initializes ServerCredential instances. */
static VALUE grpc_rb_server_credentials_init(VALUE self, VALUE pem_root_certs,
                                             VALUE pem_key_certs,
                                             VALUE force_client_auth) {
  grpc_rb_server_credentials *wrapper = NULL;
  grpc_server_credentials *creds = NULL;
  grpc_ssl_pem_key_cert_pair *key_cert_pairs = NULL;
  VALUE cert = Qnil;
  VALUE key = Qnil;
  VALUE key_cert = Qnil;
  int auth_client = 0;
  long num_key_certs = 0;
  int i;

  if (NIL_P(force_client_auth) ||
      !(force_client_auth == Qfalse || force_client_auth == Qtrue)) {
    rb_raise(rb_eTypeError,
             "bad force_client_auth: got:<%s> want: <True|False|nil>",
             rb_obj_classname(force_client_auth));
    return Qnil;
  }
  if (NIL_P(pem_key_certs) || TYPE(pem_key_certs) != T_ARRAY) {
    rb_raise(rb_eTypeError, "bad pem_key_certs: got:<%s> want: <Array>",
             rb_obj_classname(pem_key_certs));
    return Qnil;
  }
  num_key_certs = RARRAY_LEN(pem_key_certs);
  if (num_key_certs == 0) {
    rb_raise(rb_eTypeError, "bad pem_key_certs: it had no elements");
    return Qnil;
  }
  for (i = 0; i < num_key_certs; i++) {
    key_cert = rb_ary_entry(pem_key_certs, i);
    if (key_cert == Qnil) {
      rb_raise(rb_eTypeError,
               "could not create a server credential: nil key_cert");
      return Qnil;
    } else if (TYPE(key_cert) != T_HASH) {
      rb_raise(rb_eTypeError,
               "could not create a server credential: want <Hash>, got <%s>",
               rb_obj_classname(key_cert));
      return Qnil;
    } else if (rb_hash_aref(key_cert, sym_private_key) == Qnil) {
      rb_raise(rb_eTypeError,
               "could not create a server credential: want nil private key");
      return Qnil;
    } else if (rb_hash_aref(key_cert, sym_cert_chain) == Qnil) {
      rb_raise(rb_eTypeError,
               "could not create a server credential: want nil cert chain");
      return Qnil;
    }
  }

  auth_client = TYPE(force_client_auth) == T_TRUE
                    ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY
                    : GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE;
  key_cert_pairs = ALLOC_N(grpc_ssl_pem_key_cert_pair, num_key_certs);
  for (i = 0; i < num_key_certs; i++) {
    key_cert = rb_ary_entry(pem_key_certs, i);
    key = rb_hash_aref(key_cert, sym_private_key);
    cert = rb_hash_aref(key_cert, sym_cert_chain);
    key_cert_pairs[i].private_key = RSTRING_PTR(key);
    key_cert_pairs[i].cert_chain = RSTRING_PTR(cert);
  }

  TypedData_Get_Struct(self, grpc_rb_server_credentials,
                       &grpc_rb_server_credentials_data_type, wrapper);

  if (pem_root_certs == Qnil) {
    creds = grpc_ssl_server_credentials_create_ex(
        NULL, key_cert_pairs, num_key_certs, auth_client, NULL);
  } else {
    creds = grpc_ssl_server_credentials_create_ex(RSTRING_PTR(pem_root_certs),
                                                  key_cert_pairs, num_key_certs,
                                                  auth_client, NULL);
  }
  xfree(key_cert_pairs);
  if (creds == NULL) {
    rb_raise(rb_eRuntimeError, "could not create a credentials, not sure why");
    return Qnil;
  }
  wrapper->wrapped = creds;

  /* Add the input objects as hidden fields to preserve them. */
  rb_ivar_set(self, id_pem_key_certs, pem_key_certs);
  rb_ivar_set(self, id_pem_root_certs, pem_root_certs);

  return self;
}
Example #22
0
/* call-seq: calc_coherent_sums(cuts,ic,a,file) -> self
 *
 *
 *
 */
VALUE calc_coherent_sums(VALUE __self, VALUE __num_files, VALUE __cuts_on,
			 VALUE __cuts_ary, VALUE __num_evts){

  VectorFlt2D *cross_term_ints 
    = get_cpp_ptr(rb_iv_get(__self,"@cross_term_ints"),__VectorFlt2D__);
  int cuts_on = NUM2INT(__cuts_on);
  int num_amps = NUM2INT(__num_files);
  int num_evts = NUM2INT(__num_evts);
  double cut_check;
  int good_events = 0;
  ifstream in_file[num_amps];
  char *amp_names[num_amps];

  // array to hold the sums
  complex<float> cross_terms[num_amps][num_amps];
  // Naming and opening files...
  for(int iter = 0;iter<num_amps;iter++){
    amp_names[iter] = STR2CSTR(rb_ary_entry(rb_iv_get(__self,
						      "@coh_amps"),iter));
    in_file[iter].open(amp_names[iter]);
  }
  bool take_event;
  complex<float> amp[num_amps];
  int event = 0;
  int read_tag = 0;
  while(event<num_evts && read_tag<1){
    for(int j = 1;j<num_amps;j++){
      if(in_file[j].eof())  read_tag++;
    }
    if(cuts_on){
      cut_check = NUM2DBL(rb_ary_entry(__cuts_ary,event));
      if(cut_check >= 0.0){
	take_event = true;
      }
      else take_event = false;
    }
    else if(!cuts_on){
      take_event = true;
    }
    // read the amp vals...
    for(int amp_num = 0;amp_num<num_amps;amp_num++){
      in_file[amp_num].read((char*)&amp[amp_num],sizeof(amp[amp_num]));
    }

    if(take_event){
      good_events++;
      for(int row = 0;row<num_amps;row++){
	for(int col = row;col<num_amps;col++){
	  cross_terms[row][col] = cross_terms[row][col]
	    + amp[row] * conj(amp[col]);
	}
      }
    }
    event++;
  }
  cout << "Events used: " << good_events << "\n";
  // impose symmetry...
  for(int row = 0;row<num_amps;row++){
    for(int col = 0;col<=row;col++){
      cross_terms[row][col] = conj(cross_terms[col][row]);
    }
  }
  // assign values to VectorFlt2D...
  for(int i = 0;i<num_amps;i++){
    for(int j = 0;j<num_amps;j++){
      (*cross_term_ints)[i][j] = cross_terms[i][j];
    }
  }
  return rb_int_new(event);
}
Example #23
0
static VALUE
obj_func_obj(VALUE self, VALUE argv, const char *field, int type)
{
  VALUE arg, rstr, val;
  int i, n;
  struct ngraph_instance *inst;
  ngraph_arg carg;
  int argc;
  ngraph_returned_value rval;
  const char *str;

  inst = check_id(self);
  if (inst == NULL) {
    return Qnil;
  }

  argc = RARRAY_LEN(argv);
  if (argc < 1) {
    str = NULL;
  } else {
    arg = rb_ary_entry(argv, 0);
    if (RB_TYPE_P(arg, T_ARRAY)) {
      if (argc > 1) {
	return Qnil;
      }
      n = RARRAY_LEN(arg);
      if (n < 1) {
	str = NULL;
      } else {
	rstr = create_obj_arg(arg);
	if (NIL_P(rstr)) {
	  return Qnil;
	}
	str = StringValueCStr(rstr);
      }
    } else {
      rstr = create_obj_arg(argv);
      if (NIL_P(rstr)) {
	return Qnil;
      }
      str = StringValueCStr(rstr);
    }
  }

  carg.num = 1;
  carg.ary[0].str = str;
  if (type == NVFUNC) {
    inst->rcode = ngraph_object_exe(inst->obj, field, inst->id, &carg);
  } else {
    inst->rcode = ngraph_object_get(inst->obj, field, inst->id, &carg, &rval);
  }
  if (inst->rcode < 0) {
    return Qnil;
  }

  switch (type) {
  case NVFUNC:
    val = self;
    break;
  case NBFUNC:
    val = (rval.i) ? Qtrue : Qfalse;
    break;
#if USE_NCHAR
  case NCFUNC:
#endif
  case NIFUNC:
    val = INT2NUM(rval.i);
    break;
  case NDFUNC:
    val = rb_float_new(rval.d);
    break;
  case NSFUNC:
    val = tainted_utf8_str_new(rval.str);
    break;
  case NIAFUNC:
    val = rb_ary_new2(rval.ary.num);
    for (i = 0; i < rval.ary.num; i++) {
      rb_ary_store(val, i, INT2NUM(rval.ary.data.ia[i]));
    }
    break;
  case NDAFUNC:
    val = rb_ary_new2(rval.ary.num);
    for (i = 0; i < rval.ary.num; i++) {
      rb_ary_store(val, i, rb_float_new(rval.ary.data.da[i]));
    }
    break;
  case NSAFUNC:
    val = rb_ary_new2(rval.ary.num);
    for (i = 0; i < rval.ary.num; i++) {
      rb_ary_store(val, i, tainted_utf8_str_new(rval.ary.data.sa[i]));
    }
    break;
  default:
    val = Qnil;
  }

  return val;
}
Example #24
0
File: math.c Project: Fudge/rb-gsl
static VALUE rb_gsl_math_eval2(double (*func)(const double, const double), VALUE xx,
			       VALUE yy)
{
  VALUE x, y, ary;
  size_t i, j, size;
  gsl_vector *v = NULL, *v2 = NULL, *vnew = NULL;
  gsl_matrix *m = NULL, *m2 = NULL, *mnew = NULL;
#ifdef HAVE_NARRAY_H
  struct NARRAY *nax, *nay;
  double *ptr1, *ptr2, *ptr3;
#endif
  if (CLASS_OF(xx) == rb_cRange) xx = rb_gsl_range2ary(xx);
  switch (TYPE(xx)) {
  case T_FIXNUM:
  case T_BIGNUM:
  case T_FLOAT:
    Need_Float(yy);
    return rb_float_new((*func)(NUM2DBL(xx), NUM2DBL(yy)));
    break;
  case T_ARRAY:
    Check_Type(yy, T_ARRAY);
    size = RARRAY_LEN(xx);
    if (size != RARRAY_LEN(yy)) rb_raise(rb_eRuntimeError, "array sizes are different.");
    ary = rb_ary_new2(size);
    for (i = 0; i < size; i++) {
      x = rb_ary_entry(xx, i);
      y = rb_ary_entry(yy, i);
      Need_Float(x); Need_Float(y);
      rb_ary_store(ary, i, rb_float_new((*func)(RFLOAT_VALUE(x), RFLOAT_VALUE(y))));
    }
    return ary;
    break;
  default:
#ifdef HAVE_NARRAY_H
    if (NA_IsNArray(xx)) {
      GetNArray(xx, nax);
      GetNArray(yy, nay);
      ptr1 = (double*) nax->ptr;
      ptr2 = (double*) nay->ptr;
      size = nax->total;
      ary = na_make_object(NA_DFLOAT, nax->rank, nax->shape, CLASS_OF(xx));
      ptr3 = NA_PTR_TYPE(ary, double*);
      for (i = 0; i < size; i++) ptr3[i] = (*func)(ptr1[i], ptr2[i]);
      return ary;
    }
#endif
    if (VECTOR_P(xx)) {
      CHECK_VECTOR(yy);
      Data_Get_Struct(xx, gsl_vector, v);
      Data_Get_Struct(yy, gsl_vector, v2);
      vnew = gsl_vector_alloc(v->size);
      for (i = 0; i < v->size; i++) {
	gsl_vector_set(vnew, i, (*func)(gsl_vector_get(v, i), gsl_vector_get(v2, i)));
      }
      return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, vnew);
    } else if (MATRIX_P(xx)) {
      CHECK_MATRIX(yy);
      Data_Get_Struct(xx, gsl_matrix, m);
      Data_Get_Struct(yy, gsl_matrix, m2);
      mnew = gsl_matrix_alloc(m->size1, m->size2);
      for (i = 0; i < m->size1; i++) {
	for (j = 0; j < m->size2; j++) {
	  gsl_matrix_set(mnew, i, j, (*func)(gsl_matrix_get(m, i, j), gsl_matrix_get(m2, i, j)));
	}
      }
      return Data_Wrap_Struct(cgsl_matrix, 0, gsl_matrix_free, mnew);
    } else {
      rb_raise(rb_eTypeError, 
	       "wrong argument type %s "
	       "(Array or Vector or Matrix expected)", rb_class2name(CLASS_OF(xx)));
    }
    break;
  }
  /* never reach here */
  return Qnil;
}
Example #25
0
/* grpc_run_batch_stack_fill_ops fills the run_batch_stack ops array from
 * ops_hash */
static void grpc_run_batch_stack_fill_ops(run_batch_stack *st, VALUE ops_hash) {
  VALUE this_op = Qnil;
  VALUE this_value = Qnil;
  VALUE ops_ary = rb_ary_new();
  size_t i = 0;

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

  /* Fill the ops array */
  for (i = 0; i < (size_t)RARRAY_LEN(ops_ary); i++) {
    this_op = rb_ary_entry(ops_ary, i);
    this_value = rb_hash_aref(ops_hash, this_op);
    st->ops[st->op_num].flags = 0;
    switch (NUM2INT(this_op)) {
      case GRPC_OP_SEND_INITIAL_METADATA:
        /* N.B. later there is no need to explicitly delete the metadata keys
         * and values, they are references to data in ruby objects. */
        grpc_rb_md_ary_convert(this_value, &st->send_metadata);
        st->ops[st->op_num].data.send_initial_metadata.count =
            st->send_metadata.count;
        st->ops[st->op_num].data.send_initial_metadata.metadata =
            st->send_metadata.metadata;
        break;
      case GRPC_OP_SEND_MESSAGE:
        st->ops[st->op_num].data.send_message = grpc_rb_s_to_byte_buffer(
            RSTRING_PTR(this_value), RSTRING_LEN(this_value));
        st->ops[st->op_num].flags = st->write_flag;
        break;
      case GRPC_OP_SEND_CLOSE_FROM_CLIENT:
        break;
      case GRPC_OP_SEND_STATUS_FROM_SERVER:
        /* N.B. later there is no need to explicitly delete the metadata keys
         * and values, they are references to data in ruby objects. */
        grpc_rb_op_update_status_from_server(
            &st->ops[st->op_num], &st->send_trailing_metadata, this_value);
        break;
      case GRPC_OP_RECV_INITIAL_METADATA:
        st->ops[st->op_num].data.recv_initial_metadata = &st->recv_metadata;
        break;
      case GRPC_OP_RECV_MESSAGE:
        st->ops[st->op_num].data.recv_message = &st->recv_message;
        break;
      case GRPC_OP_RECV_STATUS_ON_CLIENT:
        st->ops[st->op_num].data.recv_status_on_client.trailing_metadata =
            &st->recv_trailing_metadata;
        st->ops[st->op_num].data.recv_status_on_client.status =
            &st->recv_status;
        st->ops[st->op_num].data.recv_status_on_client.status_details =
            &st->recv_status_details;
        st->ops[st->op_num].data.recv_status_on_client.status_details_capacity =
            &st->recv_status_details_capacity;
        break;
      case GRPC_OP_RECV_CLOSE_ON_SERVER:
        st->ops[st->op_num].data.recv_close_on_server.cancelled =
            &st->recv_cancelled;
        break;
      default:
        grpc_run_batch_stack_cleanup(st);
        rb_raise(rb_eTypeError, "invalid operation : bad value %d",
                 NUM2INT(this_op));
    };
    st->ops[st->op_num].op = (grpc_op_type)NUM2INT(this_op);
    st->ops[st->op_num].reserved = NULL;
    st->op_num++;
  }
}
Example #26
0
File: math.c Project: Fudge/rb-gsl
static VALUE rb_gsl_pow_int(VALUE obj, VALUE xx, VALUE nn)
{
  VALUE x, ary, argv[2];
  size_t i, j, size;
  int n;
  gsl_vector *v = NULL, *vnew = NULL;
  gsl_matrix *m = NULL, *mnew = NULL;
#ifdef HAVE_NARRAY_H
  struct NARRAY *na;
  double *ptr1, *ptr2;
#endif

  if (CLASS_OF(xx) == rb_cRange) xx = rb_gsl_range2ary(xx);
  switch (TYPE(xx)) {
  case T_FIXNUM:
  case T_BIGNUM:
  case T_FLOAT:
    return rb_float_new(gsl_pow_int(NUM2DBL(xx), FIX2INT(nn)));
    break;
  case T_ARRAY:
    CHECK_FIXNUM(nn);
    n = FIX2INT(nn);
    size = RARRAY_LEN(xx);
    ary = rb_ary_new2(size);
    for (i = 0; i < size; i++) {
      x = rb_ary_entry(xx, i);
      Need_Float(x);
      rb_ary_store(ary, i, rb_float_new(gsl_pow_int(RFLOAT_VALUE(x), n)));
    }
    return ary;
    break;
  default:
#ifdef HAVE_NARRAY_H
    if (NA_IsNArray(xx)) {
      CHECK_FIXNUM(nn);
      n = FIX2INT(nn);
      GetNArray(xx, na);
      ptr1 = (double*) na->ptr;
      size = na->total;
      ary = na_make_object(NA_DFLOAT, na->rank, na->shape, CLASS_OF(xx));
      ptr2 = NA_PTR_TYPE(ary, double*);
      for (i = 0; i < size; i++) ptr2[i] = gsl_pow_int(ptr1[i], n);
      return ary;
    }
#endif
    if (VECTOR_P(xx)) {
      CHECK_FIXNUM(nn);
      n = FIX2INT(nn);
      Data_Get_Struct(xx, gsl_vector, v);
      vnew = gsl_vector_alloc(v->size);
      for (i = 0; i < v->size; i++) {
	gsl_vector_set(vnew, i, gsl_pow_int(gsl_vector_get(v, i), n));
      }
      return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, vnew);
    } else if (MATRIX_P(xx)) {
      CHECK_FIXNUM(nn);
      n = FIX2INT(nn);
      Data_Get_Struct(xx, gsl_matrix, m);
      mnew = gsl_matrix_alloc(m->size1, m->size2);
      for (i = 0; i < m->size1; i++) {
	for (j = 0; j < m->size2; j++) {
	  gsl_matrix_set(mnew, i, j, gsl_pow_int(gsl_matrix_get(m, i, j), n));
	}
      }
      return Data_Wrap_Struct(cgsl_matrix, 0, gsl_matrix_free, mnew);
    } else if (COMPLEX_P(xx) || VECTOR_COMPLEX_P(xx) || MATRIX_COMPLEX_P(xx)) {
      argv[0] = xx;
      argv[1] = nn;
      return rb_gsl_complex_pow_real(2, argv, obj);
    } else {
      rb_raise(rb_eTypeError, "wrong argument type %s (Array or Vector or Matrix expected)", rb_class2name(CLASS_OF(xx)));
    }
    break;
  }
  /* never reach here */
  return Qnil;
}
Example #27
0
File: rcsv.c Project: fiksu/rcsv
/* The main method that handles parsing */
static VALUE rb_rcsv_raw_parse(int argc, VALUE * argv, VALUE self) {
  struct rcsv_metadata meta;
  VALUE csvio, options, option;
  VALUE ensure_container = rb_ary_new(); /* [] */

  struct csv_parser cp;
  unsigned char csv_options = CSV_STRICT_FINI | CSV_APPEND_NULL;

  /* Setting up some sane defaults */
  meta.row_as_hash = false;
  meta.empty_field_is_nil = false;
  meta.skip_current_row = false;
  meta.encoding_index = -1;
  meta.num_columns = 0;
  meta.current_col = 0;
  meta.current_row = 0;
  meta.offset_rows = 0;
  meta.num_only_rows = 0;
  meta.num_except_rows = 0;
  meta.num_row_defaults = 0;
  meta.num_row_conversions = 0;
  meta.only_rows = NULL;
  meta.except_rows = NULL;
  meta.row_defaults = NULL;
  meta.row_conversions = NULL;
  meta.column_names = NULL;
  meta.result = (VALUE[]){rb_ary_new()}; /* [] */

  /* csvio is required, options is optional (pun intended) */
  rb_scan_args(argc, argv, "11", &csvio, &options);

  /* options ||= {} */
  if (NIL_P(options)) {
    options = rb_hash_new();
  }

  /* First of all, we parse libcsv-related params so that it fails early if something is wrong with them */

  /* By default, parsing is strict */
  option = rb_hash_aref(options, ID2SYM(rb_intern("nostrict")));
  if (!option || (option == Qnil)) {
    csv_options |= CSV_STRICT;
  }

  /* By default, empty strings are treated as Nils and quoted empty strings are treated as empty Ruby strings */
  option = rb_hash_aref(options, ID2SYM(rb_intern("parse_empty_fields_as")));
  if ((option == Qnil) || (option == ID2SYM(rb_intern("nil_or_string")))) {
    csv_options |= CSV_EMPTY_IS_NULL;
  } else if (option == ID2SYM(rb_intern("nil"))) {
    meta.empty_field_is_nil = true;
  } else if (option == ID2SYM(rb_intern("string"))) {
    meta.empty_field_is_nil = false;
  } else {
    rb_raise(rcsv_parse_error, "The only valid options for :parse_empty_fields_as are :nil, :string and :nil_or_string, but %s was supplied.", RSTRING_PTR(rb_inspect(option)));
  }

  /* rb_ensure() only expects callback functions to accept and return VALUEs */
  /* This ugly hack converts C pointers into Ruby Fixnums in order to pass them in Array */
  rb_ary_push(ensure_container, options);               /* [options] */
  rb_ary_push(ensure_container, csvio);                 /* [options, csvio] */
  rb_ary_push(ensure_container, LONG2NUM((long)&meta)); /* [options, csvio, &meta] */
  rb_ary_push(ensure_container, LONG2NUM((long)&cp));   /* [options, csvio, &meta, &cp] */

  /* Try to initialize libcsv */
  if (csv_init(&cp, csv_options) == -1) {
    rb_raise(rcsv_parse_error, "Couldn't initialize libcsv");
  }

  /* From now on, cp handles allocated data and should be free'd on exit or exception */
  rb_ensure(rcsv_raw_parse, ensure_container, rcsv_free_memory, ensure_container);

  /* Remove the last row if it's empty. That happens if CSV file ends with a newline. */
  if (RARRAY_LEN(*(meta.result)) && /* meta.result.size != 0 */
      RARRAY_LEN(rb_ary_entry(*(meta.result), -1)) == 0) {
    rb_ary_pop(*(meta.result));
  }

  if (rb_block_given_p()) {
    return Qnil; /* STREAMING */
  } else {
    return *(meta.result); /* Return accumulated result */
  }
}
Example #28
0
static VALUE tokenize_string(VALUE self, 
    VALUE string,
    VALUE tokens_to_find_indexes,
    VALUE tokens_to_find_strings,
    VALUE tokens_to_extract_indexes,
    VALUE tokens_to_extract_names)
{
  const char* input_string = StringValueCStr(string);
  VALUE extracted_tokens = rb_hash_new();
  VALUE curr_token;
  unsigned int curr_token_ix;
  long n_tokens_to_find = RARRAY_LEN(tokens_to_find_indexes);
  size_t str_len = strlen(input_string);
  size_t ix;
  char c;
  char looking_for;
  size_t looking_for_len;
  size_t looking_for_ix = 0;
  long find_ix = 0;
  const char*  looking_for_token;
  unsigned int n_tokens = (unsigned int)RARRAY_LEN(rb_iv_get(self, "@tokens"));

  size_t startpoint = 0;

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

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

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

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


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

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

  ix = str_len;
  curr_token_ix = n_tokens - 1;

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

  return extracted_tokens;
}
Example #29
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);
}
Example #30
0
File: result.c Project: ab/mysql2
static VALUE rb_mysql_result_each(int argc, VALUE * argv, VALUE self) {
  VALUE defaults, opts, block;
  ID db_timezone, app_timezone, dbTz, appTz;
  mysql2_result_wrapper * wrapper;
  unsigned long i;
  int symbolizeKeys = 0, asArray = 0, castBool = 0, cacheRows = 1, cast = 1, streaming = 0;
  MYSQL_FIELD * fields = NULL;

  GetMysql2Result(self, wrapper);

  defaults = rb_iv_get(self, "@query_options");
  if (rb_scan_args(argc, argv, "01&", &opts, &block) == 1) {
    opts = rb_funcall(defaults, intern_merge, 1, opts);
  } else {
    opts = defaults;
  }

  if (rb_hash_aref(opts, sym_symbolize_keys) == Qtrue) {
    symbolizeKeys = 1;
  }

  if (rb_hash_aref(opts, sym_as) == sym_array) {
    asArray = 1;
  }

  if (rb_hash_aref(opts, sym_cast_booleans) == Qtrue) {
    castBool = 1;
  }

  if (rb_hash_aref(opts, sym_cache_rows) == Qfalse) {
    cacheRows = 0;
  }

  if (rb_hash_aref(opts, sym_cast) == Qfalse) {
    cast = 0;
  }

  if(rb_hash_aref(opts, sym_stream) == Qtrue) {
    streaming = 1;
  }

  if(streaming && cacheRows) {
    rb_warn("cacheRows is ignored if streaming is true");
  }

  dbTz = rb_hash_aref(opts, sym_database_timezone);
  if (dbTz == sym_local) {
    db_timezone = intern_local;
  } else if (dbTz == sym_utc) {
    db_timezone = intern_utc;
  } else {
    if (!NIL_P(dbTz)) {
      rb_warn(":database_timezone option must be :utc or :local - defaulting to :local");
    }
    db_timezone = intern_local;
  }

  appTz = rb_hash_aref(opts, sym_application_timezone);
  if (appTz == sym_local) {
    app_timezone = intern_local;
  } else if (appTz == sym_utc) {
    app_timezone = intern_utc;
  } else {
    app_timezone = Qnil;
  }

  if (wrapper->lastRowProcessed == 0) {
    if(streaming) {
      // We can't get number of rows if we're streaming,
      // until we've finished fetching all rows
      wrapper->numberOfRows = 0;
      wrapper->rows = rb_ary_new();
    } else {
      wrapper->numberOfRows = mysql_num_rows(wrapper->result);
      if (wrapper->numberOfRows == 0) {
        wrapper->rows = rb_ary_new();
        return wrapper->rows;
      }
      wrapper->rows = rb_ary_new2(wrapper->numberOfRows);
    }
  }

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

      fields = mysql_fetch_fields(wrapper->result);

      do {
        row = rb_mysql_result_fetch_row(self, db_timezone, app_timezone, symbolizeKeys, asArray, castBool, cast, fields);

        if (block != Qnil) {
          rb_yield(row);
          wrapper->lastRowProcessed++;
        }
      } while(row != Qnil);

      rb_mysql_result_free_result(wrapper);

      wrapper->numberOfRows = wrapper->lastRowProcessed;
      wrapper->streamingComplete = 1;
    } else {
      rb_raise(cMysql2Error, "You have already fetched all the rows for this query and streaming is true. (to reiterate you must requery).");
    }
  } else {
    if (cacheRows && wrapper->lastRowProcessed == wrapper->numberOfRows) {
      // we've already read the entire dataset from the C result into our
      // internal array. Lets hand that over to the user since it's ready to go
      for (i = 0; i < wrapper->numberOfRows; i++) {
        rb_yield(rb_ary_entry(wrapper->rows, i));
      }
    } else {
      unsigned long rowsProcessed = 0;
      rowsProcessed = RARRAY_LEN(wrapper->rows);
      fields = mysql_fetch_fields(wrapper->result);

      for (i = 0; i < wrapper->numberOfRows; i++) {
        VALUE row;
        if (cacheRows && i < rowsProcessed) {
          row = rb_ary_entry(wrapper->rows, i);
        } else {
          row = rb_mysql_result_fetch_row(self, db_timezone, app_timezone, symbolizeKeys, asArray, castBool, cast, fields);
          if (cacheRows) {
            rb_ary_store(wrapper->rows, i, row);
          }
          wrapper->lastRowProcessed++;
        }

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

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

  return wrapper->rows;
}