Macro ruru::unsafe_methods [] [src]

macro_rules! unsafe_methods {
    (
        $itself_class: ty,
        $itself_name: ident,
        $(
            fn $method_name: ident
            ($($arg_name: ident: $arg_type: ty),*) -> $return_type: ty $body: block
        )*
    ) => { ... };
}

Creates unsafe callbacks for Ruby methods

This macro is unsafe, because:

  • it uses automatic unsafe conversions for arguments (no guarantee that Ruby objects match the types which you expect);
  • no bound checks for the array of provided arguments (no guarantee that all the expected arguments are provided);

That is why creating callbacks in unsafe way may cause panics.

Due to the same reasons unsafe callbacks are faster.

Use it when:

  • you own the Ruby code which passes arguments to callback;
  • you are sure that all the object has correct type;
  • you are sure that all the required arguments are provided;
  • Ruby code has a good test coverage.

Examples

#[macro_use]
extern crate ruru;

use ruru::{Boolean, Class, Fixnum, Object, RString, VM};

// Creates `string_length_equals` functions
unsafe_methods!(
    RString, // type of `self` object
    itself, // name of `self` object which will be used in methods

    fn string_length_equals(expected_length: Fixnum) -> Boolean {
        let real_length = itself.to_string().len() as i64;

        Boolean::new(expected_length.to_i64() == real_length)
    }
);

fn main() {
    Class::from_existing("String").define(|itself| {
        itself.def("length_equals?", string_length_equals);
    });
}

Ruby:

class String
  def blank?
    # ...
  end

  def length_equals?(expected_length)
    # ...
  end
end