Expand description
Magnus is a library for writing Ruby extentions in Rust, or running Ruby code from Rust.
Overview
All Ruby objects are represented by Value
. To make it easier to work
with values that are instances of specific classes a number of wrapper
types are available. These wrappers will Deref
to
Value
, so you can still use Value
’s methods on them.
Ruby Class | Magnus Type |
---|---|
String | RString |
Integer | Integer |
Float | Float |
Array | RArray |
Hash | RHash |
Symbol | Symbol |
Class | RClass |
Module | RModule |
When writing Rust code to be called from Ruby the init
attribute can
be used to mark your init function that Ruby will call when your library
is require
d.
When embedding Ruby in a Rust program, see embed::init
for initialising
the Ruby VM.
The method
macro can be used to wrap a Rust function
with automatic type conversion and error handing so it can be exposed to
Ruby. The TryConvert
trait handles conversions from Ruby to Rust, and
anything implementing Into<Value>
can be returned to Ruby. See the
Module
and Object
traits for defining methods.
Value::funcall
can be used to call Ruby methods from Rust.
See the wrap
attribute macro for wrapping Rust types as Ruby objects.
Safety
When using Magnus, in Rust code, Ruby objects must be kept on the stack. If objects are moved to the heap the Ruby GC can not reach them, and they may be garbage collected. This could lead to memory safety issues.
It is not possible to enforce this rule in Rust’s type system or via the borrow checker, users of Magnus must maintain this rule manually.
While it would be possible to mark any functions that could expose this
unsafty as unsafe
, that would mean that almost every interaction with
Ruby would be unsafe
. This would leave no way to differentiate the
really unsafe functions that need much more care to use.
Examples
use magnus::{define_module, function, method, prelude::*, Error};
#[magnus::wrap(class = "Euclid::Point", free_immediately, size)]
struct Point {
x: isize,
y: isize,
}
impl Point {
fn new(x: isize, y: isize) -> Self {
Self { x, y }
}
fn x(&self) -> isize {
self.x
}
fn y(&self) -> isize {
self.y
}
}
fn distance(a: &Point, b: &Point) -> f64 {
(((b.x - a.x).pow(2) + (b.y - a.y).pow(2)) as f64).sqrt()
}
#[magnus::init]
fn init() -> Result<(), Error> {
let module = define_module("Euclid")?;
let class = module.define_class("Point", Default::default())?;
class.define_singleton_method("new", function!(Point::new, 2))?;
class.define_method("x", method!(Point::x, 0))?;
class.define_method("y", method!(Point::y, 0))?;
module.define_module_function("distance", function!(distance, 2))?;
Ok(())
}
C Function Index
Click to show
This lists all the Ruby C API functions currently implemented, and how they map to Rust functions and methods in Magnus.
A-N
Data_Get_Struct
: Seewrap
andTypedData
.Data_Make_Struct
: Seewrap
andTypedData
.Data_Wrap_Struct
: Seewrap
andTypedData
.
RARRAY
RARRAY
: Similar toRArray::from_value
.RARRAY_ASET
: Similar toRArray::store
.RARRAY_CONST_PTR
: Similar toRArray::as_slice
.RARRAY_EMBED_LEN
: SeeRArray::len
.RARRAY_LEN
:RArray::len
.RARRAY_LENINT
:RArray::len
.RARRAY_PTR
: Similar toRArray::as_slice
.
RB
rb_a
-rb_arx
rb_alias
:Module::define_alias
.rb_any_to_s
:std::fmt::Display
.
rb_ary
rb_ary_cat
:RArray::cat
.rb_ary_clear
:RArray::clear
.rb_ary_concat
:RArray::concat
.rb_ary_delete
:RArray::delete
.rb_ary_delete_at
:RArray::delete_at
.rb_ary_each
: SeeRArray::each
.rb_ary_entry
:RArray::entry
.rb_ary_includes
:RArray::includes
.rb_ary_new
:RArray::new
.rb_ary_new_capa
:RArray::with_capacity
.rb_ary_new_from_values
:RArray::from_slice
.rb_ary_plus
:RArray::plus
.rb_ary_pop
:RArray::pop
.rb_ary_push
:RArray::push
.rb_ary_replace
:RArray::replace
.rb_ary_resize
:RArray::resize
.rb_ary_reverse
:RArray::reverse
.rb_ary_rotate
:RArray::rotate
.rb_ary_shared_with_p
:RArray::is_shared
.rb_ary_shift
:RArray::shift
.rb_ary_sort
: Not implemented, seeRArray::sort
.rb_ary_sort_bang
:RArray::sort
.rb_ary_store
:RArray::store
.rb_ary_subseq
:RArray::subseq
.rb_ary_to_ary
: SeeTryConvert
andValue::try_convert
.rb_ary_to_s
: Not implemented directly, seeValue::to_r_string
.rb_ary_unshift
:RArray::unshift
.
rb_as
-rb_az
rb_ascii8bit_encindex
:encoding::Index::ascii8bit
.rb_ascii8bit_encoding
:RbEncoding::ascii8bit
.rb_attr
:Module::define_attr
.
rb_b
rb_binding_new
:Binding::new
. Unimplemented >= Ruby 3.2.rb_block_call
:Value::block_call
.rb_block_given_p
:block::block_given
.rb_block_proc
:block::block_proc
.rb_bug
:error::bug
.
rb_c
rb_call_super
:call_super
.rb_check_arity
:scan_args::check_arity
.rb_check_funcall
:Value::check_funcall
.rb_check_hash_type
: SeeTryConvert
andValue::try_convert
.rb_check_id
: Similar toId::check
.rb_check_id_cstr
:Id::check
.rb_check_symbol
: Similar toStaticSymbol::check
.rb_check_symbol_cstr
:StaticSymbol::check
.rb_check_typeddata
: SeeTryConvert
andValue::try_convert
.rb_class2name
:RClass::name
.rb_class_name
: Simmilar toValue::classname
.rb_class_new
:RClass::new
.rb_class_new_instance
:RClass::new_instance
.rb_class_superclass
:RClass::superclass
.rb_const_get
:Module::const_get
.rb_const_set
:Module::const_set
.rb_current_receiver
:current_receiver
.
rb_d
rb_data_object_make
: Seewrap
andTypedData
.rb_data_object_wrap
: Seewrap
andTypedData
.rb_data_object_zalloc
: Seewrap
andTypedData
.rb_data_typed_object_make
: Seewrap
andTypedData
.rb_data_typed_object_wrap
: Seewrap
andTypedData
.rb_data_typed_object_zalloc
: Seewrap
andTypedData
.rb_default_external_encoding
:RbEncoding::default_external
.rb_default_internal_encoding
:RbEncoding::default_internal
.rb_define_alias
:Module::define_alias
.rb_define_attr
: SeeModule::define_attr
.rb_define_class
:define_class
.rb_define_class_id
: Simmilar todefine_class
.rb_define_class_id_under
:Module::define_class
.rb_define_class_under
: SeeModule::define_class
.rb_define_global_function
:define_global_function
.rb_define_method
: SeeModule::define_method
.rb_define_method_id
:Module::define_method
.rb_define_module
:define_module
.rb_define_module_function
:RModule::define_module_function
.rb_define_module_id
: Seedefine_module
.rb_define_module_id_under
:Module::define_module
.rb_define_module_under
: SeeModule::define_module
.rb_define_private_method
:Module::define_private_method
.rb_define_protected_method
:Module::define_protected_method
.rb_define_singleton_method
:Object::define_singleton_method
.rb_define_variable
:define_variable
.
rb_e
-rb_enb
rb_enc
rb_enc_ascget
:RbEncoding::ascget
.rb_enc_associate
: SeeEncodingCapable::enc_associate
.rb_enc_associate_index
:EncodingCapable::enc_associate
.rb_enc_check
:encoding::check
.rb_enc_codelen
:RbEncoding::codelen
.rb_enc_codepoint_len
:RbEncoding::codepoint_len
.RB_ENC_CODERANGE
:RString::enc_coderange
.RB_ENC_CODERANGE_CLEAR
:RString::enc_coderange_clear
.RB_ENC_CODERANGE_SET
:RString::enc_coderange_set
.rb_enc_compatible
:encoding::compatible
.rb_enc_copy
:encoding::copy
.rb_enc_default_external
:Encoding::default_external
.Encoding::default_internal
.rb_enc_fast_mbclen
:RbEncoding::fast_mbclen
.rb_enc_find
:RbEncoding::find
.rb_enc_find_index
:encoding::Index::find
.rb_enc_from_encoding
:std::convert::From
.rb_enc_from_index
:std::convert::From
.rb_enc_get
: UseEncodingCapable::enc_get
plusstd::convert::From
.rb_enc_get_index
:EncodingCapable::enc_get
.rb_enc_mbclen
:RbEncoding::mbclen
.rb_enc_precise_mbclen
:RbEncoding::precise_mbclen
.rb_enc_set_index
:EncodingCapable::enc_set
.rb_enc_str_coderange
:RString::enc_coderange_scan
.rb_enc_str_new
:RString::enc_new
.rb_enc_to_index
:std::convert::From
.rb_enc_uint_chr
:RbEncoding::chr
.
rb_en
-rb_ez
rb_enumeratorize
: SeeValue::enumeratorize
.rb_enumeratorize_with_size
: Simmilar toValue::enumeratorize
.rb_eql
:Value::eql
.rb_equal
:Value::equal
.rb_error_arity
:scan_args::check_arity
.rb_eval_string
: Seeeval()
oreval!
.rb_eval_string_protect
:eval()
oreval!
.rb_exc_raise
: ReturnError
.rb_extend_object
:Object::extend_object
.
rb_f
rb_filesystem_encindex
:encoding::Index::filesystem
.rb_filesystem_encoding
:RbEncoding::filesystem
.rb_find_encoding
:std::convert::From
.rb_float_new
:RFloat::from_f64
orFloat::from_f64
.rb_float_new_in_heap
: SeeFloat::from_f64
.rb_funcall
: SeeValue::funcall
.rb_funcallv
:Value::funcall
.rb_funcall_with_block
:Value::funcall_with_block
.
rb_g
rb_gc
:gc::start
.rb_gc_adjust_memory_usage
:gc::adjust_memory_usage
.rb_gc_count
:gc::count
.rb_gc_disable
:gc::disable
.rb_gc_enable
:gc::enable
.rb_gc_location
:gc::location
.rb_gc_mark
:gc::mark
.rb_gc_mark_locations
:gc::mark_slice
.rb_gc_mark_movable
:gc::mark_movable
.rb_gc_register_address
:gc::register_address
orBoxValue
.rb_gc_register_mark_object
:gc::register_mark_object
.rb_gc_start
:gc::start
.rb_gc_stat
:gc::stat
orgc::all_stats
.rb_gc_unregister_address
:gc::unregister_address
.rb_get_kwargs
:scan_args::get_kwargs
.rb_get_path
:TryConvert
/Value::try_convert
tostd::path::PathBuf
.
rb_h
rb_hash_aref
:RHash::aref
.rb_hash_aset
:RHash::aset
.rb_hash_clear
:RHash::clear
.rb_hash_delete
:RHash::delete
.rb_hash_fetch
:RHash::fetch
.rb_hash_foreach
:RHash::foreach
.rb_hash_lookup
:RHash::lookup
.rb_hash_lookup2
:RHash::get
.rb_hash_new
:RHash::new
.rb_hash_size
:RHash::size
.
rb_i
-rb_in
rb_id2name
:Id::name
.rb_id2sym
:std::convert::From
.rb_include_module
:Module::include_module
.rb_inspect
:Value::inspect
orstd::fmt::Debug
.rb_intern
:std::convert::From
.rb_intern2
:std::convert::From
.rb_intern3
:std::convert::From
.rb_intern_str
:std::convert::From
.
rb_io
rb_is
-rb_iz
rb_ivar_get
:Object::ivar_get
.rb_ivar_set
:Object::ivar_set
.
rb_j
-rb_k
rb_jump_tag
: ReturnError
.
rb_l
rb_locale_encindex
:encoding::Index::locale
.rb_locale_encoding
:RbEncoding::locale
.
rb_m
rb_module_new
:RModule::new
.rb_mod_ancestors
:Module::ancestors
.
rb_n
rb_o
rb_obj_as_string
:Value::to_r_string
.rb_obj_classname
:Value::classname
.rb_obj_freeze
:Value::freeze
.rb_obj_is_kind_of
:Value::is_kind_of
.rb_obj_is_proc
:Proc::from_value
.rb_obj_respond_to
:Value::respond_to
.
rb_p
rb_proc_arity
:Proc::arity
.rb_proc_call
:Proc::call
.rb_proc_lambda_p
:Proc::is_lambda
.rb_proc_new
:Proc::new
&Proc::from_fn
.rb_protect
: Called internally by Magnus when required. Available asrb_sys::protect
withrb-sys-interop
feature for calling raw Ruby api.
rb_r
rb_raise
: Simmilar to returningError
.rb_range_beg_len
:Range::beg_len
.rb_require
:require
.rb_require_string
:require
.
rb_s
-rb_strl
rb_scan_args
:scan_args::scan_args
.rb_singleton_class
:Object::singleton_class
.
rb_struct
rb_struct_aref
:RStruct::aref
.rb_struct_aset
:RStruct::aset
.rb_struct_define
:r_struct::define_struct
.rb_struct_getmember
:RStruct::getmember
.rb_struct_members
:RStruct::members
.rb_struct_new
: SeeRClass::new_instance
.rb_struct_size
:RStruct::size
.
rb_str
rb_str_buf_append
:RString::append
.rb_str_buf_new
:RString::buf_new
.rb_str_cat
:RString::cat
.rb_str_conv_enc
:RString::conv_enc
.rb_str_new
:RString::from_slice
.rb_str_new_frozen
:RString::new_frozen
.rb_str_new_lit
: Simmilar tor_string!
.rb_str_new_literal
: Simmilar tor_string!
.rb_str_new_shared
:RString::new_shared
.rb_str_strlen
:RString::length
.rb_str_to_interned_str
:RString::to_interned_str
.rb_str_to_str
:TryConvert
orValue::try_convert
.
rb_st_
rb_sy
-rb_sz
rb_sym2id
:std::convert::From
.rb_sym2str
:Symbol::name
.
rb_t
RB_TEST
:Value::to_bool
/TryConvert
/Value::try_convert
.rb_to_encoding
:TryConvert
orValue::try_convert
.rb_to_encoding_index
:TryConvert
orValue::try_convert
.rb_to_float
:TryConvert
orValue::try_convert
.rb_to_int
:TryConvert
orValue::try_convert
.rb_to_symbol
:std::convert::From
.
rb_u
rb_usascii_encindex
:encoding::Index::usascii
.rb_usascii_encoding
:RbEncoding::usascii
.rb_utf8_encindex
:encoding::Index::utf8
.rb_utf8_encoding
:RbEncoding::utf8
.rb_utf8_str_new
:RString::new
.rb_utf8_str_new_cstr
: SeeRString::new
.rb_utf8_str_new_lit
: Simmilar tor_string!
.rb_utf8_str_new_literal
: Simmilar tor_string!
.rb_utf8_str_new_static
:r_string!
.
rb_v
-rb_z
rb_warning
:error::warning
.rb_yield
:block::yield_value
/ returnblock::Yield
.rb_yield_splat
:block::yield_splat
/ returnblock::YieldSplat
.rb_yield_values
: Seeblock::yield_values
/ returnblock::YieldValues
.rb_yield_values2
:block::yield_values
/ returnblock::YieldValues
.
rc
-rt
RSTRING
: Similar toRString::from_value
.RSTRING_EMBED_LEN
: Similar toRString::len
.RSTRING_LEN
:RString::len
.RSTRING_LENINT
:RString::len
.RSTRING_PTR
: Similar toRString::as_str
andRString::as_slice
.RTEST
:Value::to_bool
/TryConvert
/Value::try_convert
.
ruby_
ruby_cleanup
: Seeembed::init
andembed::Cleanup
.ruby_script
: Similar toembed::ruby_script
.ruby_setup
: Seeembed::init
.ruby_set_script_name
:embed::ruby_script
.
S-Z
Re-exports
pub use crate::class::Class;
pub use crate::class::RClass;
pub use crate::error::Error;
pub use crate::exception::Exception;
pub use crate::exception::ExceptionClass;
pub use crate::module::Attr;
pub use crate::module::Module;
pub use crate::module::RModule;
pub use crate::r_hash::RHash;
pub use crate::r_string::RString;
pub use crate::r_struct::RStruct;
pub use crate::r_typed_data::DataType;
pub use crate::r_typed_data::DataTypeFunctions;
pub use crate::r_typed_data::RTypedData;
pub use crate::r_typed_data::TypedData;
pub use crate::value::Fixnum;
pub use crate::value::StaticSymbol;
pub use crate::value::Value;
pub use crate::value::QFALSE;
pub use crate::value::QNIL;
pub use crate::value::QTRUE;
Modules
embed
rb-sys-interop
Macros
self
argument.std::sync::Once
.Structs
StaticSymbol
or a Value pointer to a RSymbol
struct.Traits
Value
to Rust types.Functions
self
of the current method context.T
.Attribute Macros
require
d by Ruby code.Derive Macros
DataTypeFunctions
with default implementations, for simple uses
of TypedData
.TypedData
, allowing the type to be passed to Ruby automatically
wrapped as a Ruby object.