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_immediatly, 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_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
.rb_protect
: Called internally by Magnus when required. Available as [rb_sys::protect
] withrb-sys-interop
feature for calling raw Ruby api.
rb_r
rb_raise
: ReturnError
.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
: See [embed::init
] and [embed::Cleanup
].ruby_script
: Similar to [embed::ruby_script
].ruby_setup
: See [embed::init
].ruby_set_script_name
: [embed::ruby_script
].
S-Z
Re-exports
pub use value::Fixnum;
pub use value::Flonum;
pub use value::StaticSymbol;
pub use value::Value;
pub use value::QFALSE;
pub use value::QNIL;
pub use value::QTRUE;
pub use class::RClass;
pub use error::Error;
pub use exception::Exception;
pub use exception::ExceptionClass;
pub use module::Attr;
pub use module::Module;
pub use module::RModule;
pub use r_hash::RHash;
pub use r_string::RString;
pub use r_struct::RStruct;
pub use r_typed_data::DataType;
pub use r_typed_data::DataTypeFunctions;
pub use r_typed_data::RTypedData;
pub use r_typed_data::TypedData;
Modules
Types and functions for working with Ruby blocks and Procs.
Types and functions for working with Ruby classes.
Types and functions for working with encodings.
Rust types for working with Ruby Exceptions and other interrupts.
Types and functions for working with Ruby exceptions.
Functions for working with Ruby’s Garbage Collector.
Types and Traits for exposing Rust functions as Ruby methods.
Types and functions for working with Ruby modules.
Traits that commonly should be in scope.
Types and functions for working with Ruby’s Hash class.
Types for working with Ruby’s String class.
Types and functions for working with Ruby’s Struct class.
Types and Traits for wrapping Rust types as Ruby objects.
Types and functions for complex method arguments.
Types for working with Ruby’s VALUE type, representing all objects, and ‘immediate’ values such as Fixnum.
Macros
Evaluate a literal string of Ruby code with the given local variables.
Wrap a Rust function item with Ruby type conversion and error handling,
ignoring Ruby’s self
argument.
Utility to simplify initialising a static with std::sync::Once
.
Wrap a Rust function item with Ruby type conversion and error handling.
Structs
A Value known to be an instance of Binding.
Wrapper type for a Value known to be an instance of Ruby’s Enumerator class.
A Value pointer to a RArray struct, Ruby’s internal representation of an Array.
A Value pointer to a RBignum struct, Ruby’s internal representation of large integers.
A Value pointer to a RComplex struct, Ruby’s internal representation of complex numbers.
A Value pointer to a RFile struct, Ruby’s internal representation of files.
A Value pointer to a RFloat struct, Ruby’s internal representation of high precision floating point numbers.
A Value pointer to a RMatch struct, Ruby’s internal representation of the MatchData returned from a regex match.
A Value pointer to a RObject struct, Ruby’s internal representation of generic objects, not covered by the other R* types.
A Value pointer to a RRational struct, Ruby’s internal representation of rational numbers.
A Value pointer to a RRegexp struct, Ruby’s internal representation of regular expressions.
Wrapper type for a Value known to be an instance of Ruby’s Range class.
A type wrapping either a StaticSymbol
or a Value pointer to a RSymbol
struct.
Traits
Trait for types that can be used as an arguments list when calling Ruby methods.
Functions available all non-immediate values.
Conversions from Value
to Rust types.
Functions
Call the super method of the current method context.
Return the Ruby self
of the current method context.
Define a class in the root scope.
Define a global constant.
Define a method in the root scope.
Define a global variable.
Define a module in the root scope.
Define a global variable.
Evaluate a string of Ruby code, converting the result to a T
.
Finds and loads the given feature if not already loaded.
Attribute Macros
Mark a function as the ‘init’ function to be run for a library when it is
require
d by Ruby code.
Allow a Rust type to be passed to Ruby, automatically wrapped as a Ruby object.
Derive Macros
Derives DataTypeFunctions
with default implementations, for simple uses
of TypedData
.
Derives TypedData
, allowing the type to be passed to Ruby automatically
wrapped as a Ruby object.