NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
crates.io
crates.io, #4441 most downloaded on crates.io
High level Ruby bindings. Write Ruby extension gems in Rust, or call Ruby code from a Rust binary.
Latest stable
0.9.3
Last release 1 months ago
16 Oct 2026
Ships unpredictably
gaps range from 1 weeks to 1.2 years
Nearly every release is documented
notes for 33 of 33 stable releases
Nothing withdrawn
no release was ever pulled
5 years old
33 releases · first in 2022
Drag across the ruler to compare, or tap a release to open it.
Magnus 0.9.3 is a patch release, with 1 bug fix.
Magnus 0.9.3 is a patch release, with 1 bug fix.
Fixes a potential crash if an exception is raised and converted to a magnus::Error while handling another exception.
Magnus' handling of the new exception would clear the current exception, rather than restoring the original exception, leaving Ruby with an unexpected nil when wrapping up the handling of the outer exception. See https://bugs.ruby-lang.org/issues/22240 for more details.
Thanks to @rwstauner finding and fixing this.
Ruby::eval, or any API that may raise)
no longer clears $!. It is now restored to the exception Ruby was already
handling, matching the semantics of a Ruby rescue. Clearing it corrupted
the interpreter's unwind state when Rust was called while an exception was
propagating, crashing Ruby with ec->errinfo == nil
(https://bugs.ruby-lang.org/issues/22240).Magnus 0.9.2 is a patch release, with 2 bug fixes.
Magnus 0.9.2 is a patch release, with 2 bug fixes.
Removes Ruby::waitpid on non-unix/non-windows platforms to resolve a compilation error on non-unix/non-windows platforms.
Fixes Fixnum::to_u32 on 32-bit platforms so that it doesn't always return RangeError.
Thanks to @buvinghausen for reporting these.
Your coding agent can read these notes before it upgrades. Set up the MCP server →
Ruby::waitpid is now only available on Unix (this includes Linux and macOS)
and Windows platforms so that Magnus may compile on non-unix/non-windows
platforms, e.g wasi.Fixnum::to_u32 on 32-bit platforms would always return RangeError.Magnus 0.9.1 is a patch release, with 1 bug fix.
Magnus 0.9.1 is a patch release, with 1 bug fix.
Bumps the dependency for the quote crate in magnus-macros to 1.0.37 or later, as magnus-macros depends on CString support that was added in 1.0.37. Thanks to @y-yagi for this fix.
See the 0.9.0 release for what's new in 0.9.
quote dependency to 1.0.37 in magnus-macros for CString support.The 'old-api' feature, which previously disabled deprecation warnings for the old api (largely the ability to create Ruby objects with associated func…
Magnus 0.9.0 adds a handful of features and fixes, otherwise it is largely compatible with 0.8.
Magnus is a Rust library providing a high-level easy-to-use interface to the C API of the Ruby programming language. Magnus lets you write Ruby extension libraries (or 'gems') in Rust, or embed Ruby in your Rust program.
The debug module implements functions from Ruby's debug.h header, including Ruby::profile_frames, Ruby::debug_inspector_open, Ruby::tracepoint_new, and Ruby::postponed_job_preregister.
Conversions for C strings with Ruby::str_from_c_str, RString::to_c_string, and implementations of IntoRString for &CStr, IntoValue for &CStr, and TryConvert for CString.
RString::modify_expand to grow the capacity of a Ruby string.
RTypedData::as_ptr/typed_data::Obj::as_ptr to get the raw pointer to Rust data that has been wrapped as a Ruby object.
Minimum supported Rust version is now 1.85.
The supported Ruby versions are now 4.0, 3.4, 3.3, and 3.2. Magnus will compile with Ruby 3.1, but tests are no longer run for Ruby 3.1. Small patches will be accepted for Ruby 3.1 compatibility. Magnus will no longer compile with Ruby 2.7 and 3.0. As of the time of this release Magnus works with the unreleased Ruby 4.1. It is possible that changes in this unreleased version of Ruby may break compatibility before the release of 4.1.
Magnus is no longer tested on macOS Intel, though it should still compile and patches will be accepted for macOS Intel compatibility.
The 'old-api' feature, which previously disabled deprecation warnings for the old api (largely the ability to create Ruby objects with associated functions, like RArray::new) now enables/disables the old api, with deprecation warnings no longer optional. The old api will be removed entirely in the next (0.10.0) version of Magnus.
Ruby::define_global_function now returns Result<(), Error> rather than ().
RArray::each, has been removed, use ary.into_iter() or ary.enumeratorize(\"each\", ()) instead.
RStruct::get and RStruct::set have been removed. While they had a small performance benefit they posed a compatibility hazard with future versions of Ruby. They should be easily swapped for the directly compatible RStruct::aref and RStruct::aset.
The data_type_builder! and r_string! macros have been deprecated in favour of functions taking &'static CStr now that C-string literals are available in Rust. See the changelog for more details and other deprecations.
See the changelog for all the changes.
@ankane for support for conversions to/from CString and &CStr
@gjtorikian for a fix for compiling with the musl C standard library on 32-bit systems
@pboling for a fix for the future Ruby 4.1 release
Ruby::profile_frames to collect a lightweight backtrace for profiling.Thread::profile_frames to collect a lightweight backtrace for profiling a
specific thread.Ruby::debug_inspector_open to acquire a DebugInspector struct that gives
access to the current frame's self, class, binding, and instruction sequence.Ruby::tracepoint_new and TracePoint to access Ruby's TracePoint api.Ruby::postponed_job_preregister and PostponedJobHandle::trigger to
register and trigger postponed jobs that can be triggered from non-Ruby
threads/without the GVL to be run later from a Ruby thread with the GVL.Ruby::str_from_c_str, RString::to_c_string,
and implementations of IntoRString for &CStr, IntoValue for &CStr, and
TryConvert for CString.RString::modify_expand to grow the capacity of a Ruby string.RTypedData::as_ptr/typed_data::Obj::as_ptr to get the raw pointer to Rust
data wrapped as a Ruby object.Ruby::define_global_function now returns Result<(), Error> rather than ().Ruby::get no longer caches the GVL state of the current thread.data_type_builder! macro. Please use
DataTypeBuilder::<Example>::new(c\"example\") instead.r_string! macro. Please use Ruby::utf8_str_new_static(c\"example\")
instead.gc::register_mark_object. Please use Ruby::gc_register_mark_object instead.gc::register_address. Please use Ruby::gc_register_address instead.gc::unregister_address. Please use Ruby::gc_unregister_address instead.IntoValue::into_value_unchecked, IntoRString::into_r_string_unchecked,
IntoSymbol::into_symbol_unchecked, and IntoId::into_id_unchecked. Please
use the _with variant passing &Ruby::get_unchecked(), e.g.
"example".into_r_string_with(&Ruby::get_unchecked()).RArray::each, use ary.into_iter() or ary.enumeratorize(\"each\", ())
instead.RStruct::get/RStruct::set, use RStruct::aref/RStruct::aset instead.arm-linux-musl).Magnus 0.8.4 is a patch release, with 1 bug fix.
Magnus 0.8.4 is a patch release, with 1 bug fix.
Fixes a potential crash if an exception is raised and converted to a magnus::Error while handling another exception.
Magnus' handling of the new exception would clear the current exception, rather than restoring the original exception, leaving Ruby with an unexpected nil when wrapping up the handling of the outer exception. See https://bugs.ruby-lang.org/issues/22240 for more details.
Thanks to @rwstauner finding and fixing this.
Ruby::eval, or any API that may raise)
no longer clears $!. It is now restored to the exception Ruby was already
handling, matching the semantics of a Ruby rescue. Clearing it corrupted
the interpreter's unwind state when Rust was called while an exception was
propagating, crashing Ruby with ec->errinfo == nil
(https://bugs.ruby-lang.org/issues/22240).Magnus 0.8.3 is a patch release, with 2 bug fixes.
Magnus 0.8.3 is a patch release, with 2 bug fixes.
Removes Ruby::waitpid on non-unix/non-windows platforms to resolve a compilation error on non-unix/non-windows platforms.
Fixes Fixnum::to_u32 on 32-bit platforms so that it doesn't always return RangeError.
Thanks to @buvinghausen for reporting these.
Ruby::waitpid is now only available on Unix (this includes Linux and macOS)
and Windows platforms so that Magnus may compile on non-unix/non-windows
platforms, e.g wasi.Fixnum::to_u32 on 32-bit platforms would always return RangeError.Magnus 0.8.2 is a patch release, with 1 bug fix.
Magnus 0.8.2 is a patch release, with 1 bug fix.
Fixes an incorrect error message when converting a Ruby string to a Rust string fails. Thanks to @jeffcharles for this fix.
See the 0.8.0 release for what's new in 0.8.
Magnus 0.8.1 is a patch release, with 1 bug fix.
Magnus 0.8.1 is a patch release, with 1 bug fix.
Fixes a compilation error on 32-bit platforms. Thanks to @jonian for reporting this issue.
See the 0.8.0 release for what's new in 0.8.
…functions marked as part of the old API will be deprecated by default. Otherwise it is largely compatible with 0.7.
Magnus 0.8.0 adds a handful of features and fixes. The old-api feature introduced in 0.7.0 is no longer a default feature, so functions marked as part of the old API will be deprecated by default. Otherwise it is largely compatible with 0.7.
Magnus is a Rust library providing a high-level easy-to-use interface to the C API of the Ruby programming language. Magnus lets you write Ruby extension libraries (or 'gems') in Rust, or embed Ruby in your Rust program.
fatal exception raised when a Rust function bound to Ruby panics can no longer be caught with rescue Exception.TryConvertOwned for (T, ...) so that T must be TryConvertOwned.The minimum supported Rust version in now 1.65.
Magnus 0.5 and earlier would allow you to create Ruby objects with associated functions, like RArray::new. In Magnus 0.6 a new set of APIs for creating Ruby objects was added, as methods on a Ruby handle that can only be obtained on a Ruby thread. The older associated functions API is now marked as deprecated by default. The old-api feature can be enabled to disable deprecation warnings for the old API. In a future version of Magnus will remove this feature.
The FString type has been removed as it can not safely uphold the promise it was making. Either due to Ruby's apis changing or a misinterpretation of old documentation it had been designed assuming interned strings (aka 'fstrings') would not be garbage collected, which is not the case.
Conversions between Ruby's Time and Rust's SystemTime now preserve nanosecond precision.
RString::to_string will now use a Ruby utf-8 validation api that caches the results of the validity check. This will greatly improve performance in the case a string is already known to be utf-8, but may slightly reduce performance when not known.
Ruby::time_nano_new, Ruby::time_timespec_new, and Time::timespec.chrono feature can be enabled to allow automatic conversions between chrono::DateTime<Utc> and chrono::DateTime<FixedOffset> and Ruby Time objects.typed_data::Writebarrier::writebarrier and writebarrier_unprotect.NonZero types, i128/u128, and BTreeMap.Ruby::io_extract_modeenc.Upgrading from Magnus 0.6 or 0.7 should be straightforward. If upgrading from 0.5 or earlier, it's recommended to upgrade to 0.6 first.
FromIterator for RArray and RHash are hidden behind the old-api feature (which will be removed in a future version of Magnus). Use Ruby::ary_from_iter and Ruby::hash_from_iter rather than RArray/Rhash::from_iter or collect::<RArray>()/collect::<RHash>().
See the changelog for all the changes.
@ankane for implementing TryConvert for NonZero types, i128/u128 support, and some additional improvements.
@emwalker for the chrono feature.
@erickguan for improvements to docs, some fixes, and IO features including Ruby::io_extract_modeenc.
@ianks and @sandbergja for other fixes.
@yaroslav for a detailed issue report that lead to an improvement.
Ruby::time_nano_new, Ruby::time_timespec_new, and Time::timespec.chrono feature can be enabled to allow automatic conversions
between chrono::DateTime<Utc> and chrono::DateTime<FixedOffset> and Ruby
Time objects.typed_data::Writebarrier::writebarrier and writebarrier_unprotect.TryConvert for NonZero types.io module available with io feature, supporting io_extract_modeenc,
OpenFlags, FMode, and IoEncoding.Ruby::io_extract_modeenc, a safe wrapper around rb_io_extract_modeenc,
allowing structured extraction of open flags, mode flags, and IO encoding
metadata.OpenFlags struct, which wraps Ruby's O_ open flags
(e.g. O_RDONLY, O_CREAT) in a convenient bitflag-like interface.FMode struct, representing FMODE_ flags used internally by Ruby to
represent IO modes (READ, WRITE, BINARY_MODE, etc.).IoEncoding, a safe Rust struct for temporarily owning and
inspecting rb_io_encoding, including safe accessors for
internal/external encoding and encoding options.i128/u128.to_i128/to_u128 for Fixnum/Bignum/Integer.Ruby::integer_from_i128 & Ruby::integer_from_u128.RHash::to_btree_map and automatic conversion from Hash to BTreeMap.Time and Rust's SystemTime now preserve
nanosecond precision.RString::to_string will now use a Ruby utf-8 validation api that caches the
results of the validity check. This will greatly improve performance in the
case a string is already known to be utf-8, but may slightly reduce
performance when not known.RString::to_interned_str now returns an RString rather than an FString.thread_fd_close as it will be a no-op as of Ruby 3.5FString as it can not safely uphold the promise it was making. Either due
to Ruby's apis changing or a misinterpretation of old documentation it had
been designed assuming interned strings (aka fstrings) would not be garbage
collected, which is not the case.RString::as_interned_str as its only purpose was to return an FString.fatal exception raised when a Rust function bound to Ruby panics can no
longer be caught with rescue Exception.TryConvertOwned for (T, ...) so that T must be
TryConvertOwned.Magnus 0.7.1 is a patch release, with 1 documentation fix.
Magnus 0.7.1 is a patch release, with 1 documentation fix.
Fixes building docs against Ruby 3.0. This should resolve building docs for docs.rs.
See the 0.7.0 release for what's new in 0.7.
…be obtained on a Ruby thread. 0.7 begins the deprecation of the associated functions with the old-api feature. This feature is enabled by default, but…
Magnus 0.7.0 adds many features, but should be largely compatible with 0.6.
Magnus is a Rust library providing a high-level easy-to-use interface to the C API of the Ruby programming language. Magnus lets you write Ruby extension libraries (or 'gems') in Rust, or embed Ruby in your Rust program.
Magnus 0.5 and earlier would allow you to create Ruby objects with associated functions, like RArray::new. In Magnus 0.6 a new set of APIs for creating Ruby objects was added, as methods on a Ruby handle that can only be obtained on a Ruby thread. 0.7 begins the deprecation of the associated functions with the old-api feature. This feature is enabled by default, but if disabled the old-api functions will issue deprecation warnings. Disable this feature to get an early start on migrating these functions to the new API.
As part of the same effort, closures and functions used as Ruby blocks or procs now take an additional first argument of &Ruby.
The ruby-static feature has been removed. Instead enable the feature for rb-sys in your Cargo.toml like so:
rb-sys = { version = "*", features = ["ruby-static"] }
Thread api via methods to create threads on the Ruby type and the Thread type.Mutex api via methods to create a mutex on the Ruby type and the Mutex type.Fiber api via methods to create fibers on the Ruby type and the Fiber type (on Ruby versions 3.1 and up).Time type representing instances of Ruby's Time class that will convert to/from std::time::SystemTime.r_array::TypedArray, a Ruby Array that may only contain elements of type T. On creation the Array is hidden from Ruby, and must be consumed to pass it to Ruby (where it reverts to a regular untyped Array). It is then inaccessible to Rust.magnus::Integer now implements PartialEq, PartialOrd, Add, Sub, Mul, and Div so it can be used with mathematical operators like + and -.Ruby::define_data for working with Ruby's Data class (Ruby 3.3 and up only).RArray implements IntoIterator.IntoError is a new trait for converting types to magnus::Error. Functions returning to Ruby can now return Result where the error type is any type that implements IntoError.Upgrading from Magnus 0.6 should be straightforward. If upgrading from 0.5 or earlier, it's recommended to upgrade to 0.6 first.
See the changelog for all the changes.
@Maaarcocr for implementing the Add et al traits for Integer.
@adampetro for contributions to the implementation of IntoIterator for RArray.
@macournoyer for fixes to Error.
@y-yagi and @gjtorikian for fixing typos.
Thread, Ruby::thread_create/thread_create_from_fn and other thread APIs.Mutex, Ruby::mutex_new and other mutex APIs.Fiber, Ruby::fiber_new/fiber_new_from_fn and other fiber APIs
(requires Ruby >= 3.1).Ruby::ary_try_from_iter is an efficient way to create a Ruby array from a
fallible Rust iterator.Ruby::hash_from_iter and Ruby::hash_try_from_iter.RFile implements AsRawFd.TypedArray<T>, a Ruby Array that may only contain elements of type T.
On creation the Array is hidden from Ruby, and must be consumed to pass it
to Ruby (where it reverts to a regular untyped Array). It is then
inaccessible to Rust.IntoIterator for RArray.PartialEq, PartialOrd, Add, Sub, Mul, and Div for
Integer.Time with automatic conversion to/from std::time::SystemTime.Ruby::alias_variable.Ruby::waitpid.RHash::lookup2.Ruby::define_data new for Ruby 3.3.IntoError trait for conversion to Error, plus impl ReturnValue for Result<T, E> where E: IntoError to allow returning custom error types to
Ruby.&Ruby.RArray::each. Please use ary.into_iter() or
ary.enumeratorize("each", ()) instead.deprecated-send-sync-value feature.ruby-static feature. Instead enable the feature for rb-sys in your
Cargo.toml like so: rb-sys = { version = "*", features = ["ruby-static"] }typed_data::Obj::get.QTRUE, QFALSE, and QNIL constants.Class::undef_alloc_func.Value::try_convert.Binding.gc::{mark, mark_slice, mark_movable, location}.RStruct::as_slice.Exception::backtrace.Magnus 0.6.4 is a patch release, with 1 fix.
Magnus 0.6.4 is a patch release, with 1 fix.
Lazy could deadlock when called for the first time from multiple threads simultaneously.
The fix for results in a slight change in expected behaviour. If multiple threads attempt first access at the same time the func given to Lazy::new may be called more than once, but all threads will receive the same value.
Thanks to @choubacha for reporting this issue, along with an excellent repro.
Lazy when accessed for the first time from
multiple threads simultaneously.Magnus 0.6.3 is a patch release, with 1 fix.
Magnus 0.6.3 is a patch release, with 1 fix.
Adds missing IntoValueFromNative implementations for Vec and HashMap. This was preventing converting nested Vecs to Ruby Arrays. See issue #105.
Thanks to @Vagab for reporting this issue.
Magnus 0.6.2 is a patch release, with 1 fix.
Magnus 0.6.2 is a patch release, with 1 fix.
Fixes a compile error using the bytes feature. See issue #90.
Thanks to @jwilm for reporting this issue.
Magnus 0.6.1 is a patch release, with 1 change.
Magnus 0.6.1 is a patch release, with 1 change.
This release adds support for rb-sys' stable-api feature.
Thanks to @gmalette for this change.
If you encounter a lot of deprecation warnings when upgrading it may be easier to ignore warnings to concentrate on fixing errors, assuming your proje…
Magnus 0.6.0 makes some breaking API changes to improve thread safety. A handful of fixes and new features are also included.
Magnus is a Rust library providing a high-level easy-to-use interface to the C API of the Ruby programming language. Magnus lets you write Ruby extension libraries (or 'gems') in Rust, or embed Ruby in your Rust program.
Previous versions of Magnus have ignored thread safety in aid of getting something working, but support for threads and running Rust code outside of the Global VM Lock via rb_thread_call_without_gvl have been common feature requests. This release prepares for the introduction of those features with some breaking API changes.
To this end all APIs that create Ruby objects have been moved to a new Ruby handle which can only be obtained on a Ruby thread. For example RArray::new() becomes Ruby::ary_new(&self) (currently RArray::new() still exists as a wrapper around Ruby::get().unwrap().ary_new()). Default implementations have been removed. Additionally Ruby types are no longer Send & Sync. An Opaque wrapper type can be used to pass Ruby types between threads where they can only be unwrapped on a Ruby thread.
To make getting ahold of the Ruby handle simple, functions bound as Ruby methods with method!() and function!(), along with the function marked with #[magnus::init] optionally take &Ruby as a first argument.
The minimum supported Rust version is now 1.61.
The bytes-crate and rb-sys-interop features have been renamed to bytes and rb-sys respectively.
Previously all Ruby types, such as RString, RArray, etc Deref'd to Value, allowing Value methods to be called on all Ruby types. This is no longer the case. All Value methods have been moved to the ReprValue trait, which is implemented by Value and all other Ruby types.
This allows typed_data::Obj<T> to Deref to T, turning typed_data::Obj into a 'smart pointer' type that makes advanced use of wrapped data much more pleasant.
rb_assert!() macrovalue::Lazy lazily initialises a Ruby value so it can be assigned to a staticClass::define_alloc_func and Ruby::obj_wrap_askwargs!() macro and KwArgs type can be used to pass keyword arguments to ReprValue::funcall, et al.If you encounter a lot of deprecation warnings when upgrading it may be easier to ignore warnings to concentrate on fixing errors, assuming your project is setup with a Rake and a 'compile' task this can be done with:
RUSTFLAGS=-Awarnings rake compile
It is also possible to ignore errors due to Value no longer being Send + Sync by activating the deprecated-send-sync-value feature:
magnus = { version = "0.6", features = ["deprecated-send-sync-value"] }
This feature is intended purely as a convenience when upgrading and will be removed with the next release.
To make a Ruby type Send + Sync wrap it with Opaque::from. To get the Ruby type back use Ruby::get_inner().
Functions on Value have moved to the ReprValue trait, It is recommended to import this with use magnus::prelude::*. Magnus' prelude module only imports traits, and does so anonymously, so there is minimal chance of it causing problems.
There are no longer From<T>/Into implementations for Value. In a lot of cases this can be replaced with .as_value(). For 'wrapped' structs you will need to wrap them with Ruby::obj_wrap first. Internally Magnus uses the IntoValue trait, which is available publicly with use magnus::IntoValue.
See the changelog for all the changes.
@wfchandler for reporting issues with subclassing wrapped types.
@adampetro for implementing keyword support in funcall, et al.
value::Opaque can be used to wrap a Ruby type to make it Send + Sync.value::Lazy lazily initialises a Ruby value so it can be assigned to a
static.value::OpaqueId is a Send + Sync version of value::Id.value::LazyId is an Id with a const constructor so can be assigned to a
static and derefs to OpaqueId.error::OpaqueError is a Send + Sync version of Error.#[magnus(opaque_attr_reader)] attribute can be set on Opaque wrapped
fields of a struct when deriving TypedData to generate a method to return
the inner value.Ruby::init function to initialise Ruby when embedding Ruby in Rust that
runs a function with Ruby initialised, passing &Ruby.rb_assert!() macro to assert a Ruby expression evaluates to a truthy value.Class::undef_default_alloc_func to remove a class' allocator function only
if it is Ruby's default allocator function.Class::obj_alloc and Class::define_alloc_func for allocating an object
without calling initialize, and for defining an allocator function.RTypedData::wrap_as & typed_data::Obj<T>::wrap_as can be used to
dynamically set the class when wrapping Rust data in a Ruby object. This can
be used to allow wrapped data to be subclassed in Ruby.Exception::exception_class returns the class of an exception as an
ExceptionClass.kwargs!() macro and KwArgs type can be used to pass keyword arguments
to ReprValue::funcall, et al.bytes-crate feature has been renamed to bytes.rb-sys-interop feature has been renamed to rb-sys.Send or Sync. These types can be made Send &
Sync with the deprecated-send-sync-value feature. This feature is meant
to ease upgrading and will be removed with the next release.Value's methods moved to the ReprValue trait.typed_data::Obj<T> derefs to T so now T's methods can be called
directly on typed_data::Obj<T>.ReprValue and TryConvert added to magnus::prelude.typed_data::Cmp, typed_data::Dup and typed_data::Inspect traits to help
with implementing #<=>, #dup & #clone, and #inspect methods for
wrapped structs.Sync to enable frozen_shareable flag.TypedData::class and TypedData::class_for now take a &Ruby argument.DataTypeFunctions::mark and DataTypeFunctions::compact now take
&gc::Marker and &gc::Compactor arguments respectively.#[magnus::init] optionally takes a &Ruby
argument.method!() and function!() optionally
take &Ruby as a first argument.embed::init derefs to Ruby.DataTypeBuilder::new/DataType::builder now take their name argument
as a 'static CStr (see the magnus::data_type_builder! macro to construct
a DataTypeBuilder with a 'static CStr name).DataTypeBuilder are now const, so DataType can be
constructed in a const context and be assigned to a static.#[wrap] and #[derive(TypedData)] macros now support setting the
#[magnus(unsafe_generics)] attribute to allow deriving TypedData for
types with generics. The derived implementation is not guaranteed to be
correct.typed_data::Obj::get as it is made redundant by the Deref implementation
for typed_data::Obj.QTRUE, QFALSE, and QNIL constants. Please use value::qtrue(),
value::qfalse(), and value::qnil().Class::undef_alloc_func. Please use Class::undef_default_alloc_func.Value::try_convert, prefer TryConvert::try_convert or T::try_convert.Binding. To call methods on Ruby's binding, use ReprValue::funcall on a
Value know to be an instance of Ruby's Binding class.gc::{mark, mark_slice, mark_movable, location}, instead use
gc::Marker::{mark, mark_slice, mark_movable} and Compactor::location.RStruct::as_slice.RClass, import magnus::Class trait or
magnus::prelude::*.Into<Value>/From<T> for Value implementations, use IntoValue.Default implementations for Value, RClass, and ExceptionClass.Error can no longer be directly constructed, must use Error::new or
Error::from/Exception::into.RString::append (use RString::buf_append).Error::runtime_error (use Error::new(exception::runtime_error(), msg)).RFloat::from_value now returns None when value is a Flonum.Magnus 0.5.5 is a patch release, with 1 change.
Magnus 0.5.5 is a patch release, with 1 change.
This release adds support for rb-sys' stable-api feature. This necessitates upping the minimum supported Rust version to 1.60.
Additionally, Ruby 2.6 support requires enabling rb-sys' stable-api-compiled-fallback feature in your Cargo.toml like so:
rb-sys = { version = "*", default-features = false, features = ["stable-api-compiled-fallback"] }
Thanks to @gmalette and @ianks for this change.
rb-sys' stable-api feature.rb-sys' stable-api-compiled-fallback
feature in your Cargo.toml like so:
rb-sys = { version = "*", default-features = false, features = ["stable-api-compiled-fallback"] }Magnus 0.5.3 is a patch release, with 1 change.
Magnus 0.5.3 is a patch release, with 1 change.
The try_convert module is now public so that TryConvertOwned trait can be named and implemented. Thanks to @Qqwy for reporting this issue.
Magnus 0.5.3 is a patch release, with 1 addition.
Magnus 0.5.3 is a patch release, with 1 addition.
Added Value::as_value method that can be called on any Ruby type (as all Ruby types deref to Value) as a forward-compatible way to convert a Ruby type to Value.
This method should be prefered over dereferencing (e.g. *example), and the From/Into traits (e.g. Value::from(example) and let v: Value = example.into()) as in future versions of Magnus Ruby types will not dereference to Value (Value's methods will move to a trait) and From/Into will not be implemented.
Magnus 0.5.2 is a patch release, with 1 bug fix.
Magnus 0.5.2 is a patch release, with 1 bug fix.
Fixed compilation issue in RBignum on 32 bit platforms. Thanks to @yammine for reporting this.
Magnus 0.5.1 is a patch release that improves documentation. Thanks to @y-yagi and @dylanahsmith.
Magnus 0.5.1 is a patch release that improves documentation. Thanks to @y-yagi and @dylanahsmith.
Magnus 0.5.0 adds many features, a handful of fixes, and some API changes.
Magnus 0.5.0 adds many features, a handful of fixes, and some API changes.
Magnus is a Rust library providing a high-level easy-to-use interface to the C API of the Ruby programming language. Magnus lets you write Ruby extension libraries (or 'gems') in Rust, or embed Ruby in your Rust program.
RStruct was missing an implementation of the ReprValue trait that would allow it to be passed to functions that require a value that is already a Ruby object. This trait implementation has now been added.
When converting Ruby values to RArray (or Vec<T>, [T; 1], or (T,)), an error will now be returned if given a non-Array (or non to_ary-able) value, rather than wrapping it in an array (see RArray::to_ary for the old behaviour).
There have been some internal changes to start making Magnus safe to use with multithreaded code. Many functions are now documented as panicking when called from a non-Ruby thread. This check is currently only performed in debug builds, as there is no api to avoid the performance hit of this check (calling these functions from a non-Ruby thread in a release build is undefined behaviour).
The IntoValue trait is now used instead of Into<Value> for converting to Ruby types. The Into<Value> implementations will be removed in the next release.
use magnus::prelude::* will now import traits anonymously.
The bytes-crate feature can be enabled to allow automatic conversions between bytes::Bytes and Ruby strings.
typed_data::Obj<T>, is a Ruby object wrapping a Rust type known to be T. Previously you could declare a function accepting &T to receive a reference to the Rust data wrapped in a Ruby object, but you wouldn't have access to the wrapping object. Or if you declared the argument as Value you could get the wrapping object, but it was awkward to get the inner Rust data. typed_data::Obj<T> gets you the best of both worlds. See the typed_data_obj.rs test for an example.
TypedData::class_for can be implemented to customise the class on a case by case basis when wrapping Rust data in a Ruby object. See the docs for details. A simple interface to this is enabled with the #[wrap] macro now allowing #[magnus(class = "...")] attributes on enum variants.
The typed_data::Hash and typed_data::IsEql traits are automatically implemented for compatible types, providing Ruby compatible #hash and #eql? methods ready to be bound to your object.
error::Result<T> as a shorthand for std::result::Result<T, Error>.
The following Ruby API functions are now implemented in Magnus:
Value
RArray
RHash
with_capacity new for Ruby 3.2.bulk_insertRString
capacitycmpcomparabledrop_bytesdumpellipsizeoffsetplustimesreplacescrubshared_replacesplitupdateto_bytes (with the bytes-crate feature)RRegexp
backref_get returning RMatchRMatch
RBignum
RRational
Float
RComplex
Numeric trait implemented for Integer, Float, RRational, RComplex, etc.
coerce_bin for calling binary operators such as +.coerce_cmp for calling comparison operators such as <=>.coerce_relop for calling relationship operators such as <=.coerce_bit for calling bitwise operators such as |.See the changelog for more details.
rb-sys crate, the idea for the typed_data::Obj<T> feature, some CI improvements for Magnus, and the auto wb_protected flag feature.funcall_public and error::Result<T>.Vec<Value> could be passed as an argument to Ruby (Value should never be stored in a heap allocated struct like Vec) that inspired the design of the IntoValue trait.TypedData::class_for and #[magnus(class = "...")] on enum variants.embed::init and the ruby-static feature that resulted in a change that gives better error messages from embed::init.bytes-crate feature.typed_data::Obj<T>, a Ruby object wrapping a Rust type known to be T.RArray::to_ary, RArray::assoc, RArray::rassoc, and RArray::cmp.RHash::with_capacity new for Ruby 3.2.RHash::bulk_insert.Value::hash to generate a hash key for a Ruby object.typed_data::Hash and typed_data::IsEql traits to help with implementing
#hash and #eql? methods for wrapped structs.RString methods: capacity, cmp, comparable, drop_bytes,
dump, ellipsize, offset, plus, times, replace, scrub,
shared_replace, split, update.RRegexp::new/new_str, RRegexp::reg_match, and RRegexp::options.backref_get function to get the RMatch for the last regexp match.RMatch::nth_defined, RMatch::nth_match, RMatch::backref_number,
RMatch::matched, RMatch::pre, RMatch::post, and RMatch::lastRBignum::is_positive/is_negative.new, num, and den for RRational, plus rationalize and
rationalize_with_prec for Float.RComplex::new, polar, real, imag, conjugate, abs & arg.Numeric trait implemented for Integer, Float, RRational,
RComplex, etc. Exposes functions for applying operators to numeric types
following Ruby's coercion protocol.value::Id::new added to replace value::Id::from.TypedData::class_for can be implemented to customise the class on a case by
case basis when wrapping Rust data in a Ruby object.#[wrap] and #[derive(TypedData)] macros now allow setting
#[magnus(class = "...")] on enum variants to customise the class per
variant when wrapping enums in a Ruby object.Value::funcall_public calls a public method, returning an error for a
private or protected method.error::Result<T> is shorthand for std::result::Result<T, Error>.embed::setup to perform minimal initialisation of Ruby for environments
where embed::init doesn't work.bytes-crate feature can be enabled to allow automatic conversions
between bytes::Bytes and Ruby strings.RArray (or Vec<T>, [T; 1], or (T,)),
an error will be returned if given a non-Array (or non-to_ary-able) value,
rather than wrapping it in an array (see RArray::to_ary for the old
behaviour).r_typed_data::{DataType, DataTypeFunctions, DataTypeBuilder, TypedData} all
moved to typed_data module, r_typed_data module removed. This should only
affect DataTypeBuilder as it was the only one not exported at the crate
root.gc::adjust_memory_usage's argument changed to isize, rather than i32 or
i64 depending on pointer width.IntoValue trait is now used instead of Into<Value> for converting to
Ruby types.IntoId, IntoRString, and IntoSymbol are used instead of Into<Id>,
Into<RString>, and Into<Symbol>.use magnus::prelude::* will now import traits anonymously.EncodingCapable, Module, Class, and Object traits can no longer be
implemented by user code.wb_protected flag is automatically set for data wrapped in a Ruby
object when mark is not set.RString::append (use RString::buf_append).Error::runtime_error (use Error::new(exception::runtime_error(), msg)).Into<Value> (use IntoValue).DataTypeBuilder::free_immediatly (use free_immediately).From<&str> for RString / Into<RString> for &str.From<String> for RString / Into<RString> for String.From<&str> for Symbol / Into<Symbol> for &str.From<String> for Symbol / Into<Symbol> for String.From<&str> for StaticSymbol / Into<StaticSymbol> for &str.From<String> for StaticSymbol / Into<StaticSymbol> for String.From<&str> for Id / Into<Id> for &str.From<String> for Id / Into<Id> for String.debug_assert_value!() macro no longer public.ReprValue implementation for RStruct.Magnus 0.4.4 is a patch release, with 1 addition and 1 bug fix.
Magnus 0.4.4 is a patch release, with 1 addition and 1 bug fix.
Added is Class::undef_alloc_func, a function to remove a class' allocator function.
Fixed 'wrapped' structs from #[wrap] and #[derive(TypedData)] macros generating warning: undefining the allocator of T_DATA class under Ruby 3.2.
Thanks to @jbourassa for these changes.
Class::undef_alloc_func, a function to remove a class' allocator function.#[wrap] and #[derive(TypedData)] macros will not
generate warning: undefining the allocator of T_DATA class under Ruby 3.2Magnus 0.4.3 is a patch release, with 1 bug fix.
Magnus 0.4.3 is a patch release, with 1 bug fix.
Fixed a bug where gc::mark_slice was failing to mark the last element of the slice. Thanks to @jbourassa for the fix.
Magnus 0.4.2 is a patch release that removes an errant dbg!() call.
Magnus 0.4.2 is a patch release that removes an errant dbg!() call.
Magnus 0.4.1 is a patch release, with 1 bug fix.
Magnus 0.4.1 is a patch release, with 1 bug fix.
Fixed bug where scan_args::get_kwargs could error/segfault when leading optional args were not provided, due to trying to convert the type of the missing value. Thanks to @gjtorikian for reporting this.
scan_args::get_kwargs error/segfault when leading optional args were not
provided, due to trying to convert the type of the missing value.Magnus 0.4.0 adds a handful of new features and fixes. Support for different platforms has been greatly improved.
Magnus 0.4.0 adds a handful of new features and fixes. Support for different platforms has been greatly improved.
Magnus is a Rust library binding to the C API of the Ruby programming language. Magnus lets you write Ruby extension libraries (or 'gems') in Rust, or embed Ruby in your Rust program.
Magnus has switched from our own built in bindings to Ruby to using the rb-sys crate. This, along with the rb-sys gem, greatly improves the compatibility and reliability across different platforms and Ruby versions. Notable improvements include:
Thanks to @ianks for all his hard work on this.
Additions around exceptions make for easier defining of custom exceptions. See examples/custom_exception_ruby and examples/custom_exception_rust.
Notable fixes include:
Error to raise an exception.Flonum support disabled on platforms where it is not supported. This allows compiling Magnus on 32 bit systems (though full 32 bit support is not yet guaranteed).See CHANGELOG.md for full details.
Value::funcall_with_block.TryConvert for Exception and ExceptionClass.Class trait (implemented for RClass and ExceptionClass).define_error and Module::define_error helpers for defining an Exception
Class.RTypedData::wrap and RTypedData::get inherent methods for wrapping Rust
types in Ruby objects.Send.Value::block_call. Use Proc::from_fn + Value::funcall_with_block
for closures that capture variables.Proc::new only accepts a function pointer, use Proc::from_fn for closures
that capture variables.ExceptionClass::default() now returns StandardError rather than
RuntimeError.TryConvert now takes Value by value (rather than a reference).DataTypeBuilder::free_immediatly (use free_immediately).free_immediatly attribute in wrap macro (use free_immediately).free_immediatly in magnus attribute of derive(TypedData) macro
(use free_immediately).String::encode_utf8, use r_string.conv_enc(RbEncoding::utf8()) instead.Value::leak, use gc::register_mark_object instead.define_global_variable (use define_variable).Error to raise an exception.Flonum support disabled for Ruby built with USE_FLONUM=0 (e.g. 32 bit
systems).free_immediatly (to free_immediately) in the
DataTypeBuilder struct, and wrap and derive(TypedData) macros.printf-style format strings no longer interpreted in error messages when
automatically raised as Ruby exceptions.Magnus 0.3.2 is a patch release, with 2 bug fixes.
Magnus 0.3.2 is a patch release, with 2 bug fixes.
Better error output from the build script when ruby can't be found or errors. Thanks to @ms-jpq for this fix.
Fixed crash in Proc::new and Value::block_call when the proc was stored and called later.
ruby can't be found or errors.Proc::new and Value::block_call when the proc was stored
and called later.Magnus 0.3.1 is a patch release, with 1 bug fix.
Magnus 0.3.1 is a patch release, with 1 bug fix.
Fixed Integer overflow in Ruby Float to f64 conversion.
Magnus 0.3.0 adds many new features and includes a number of fixes.
Magnus 0.3.0 adds many new features and includes a number of fixes.
Magnus is a Rust library binding to the C API of the Ruby programming language. Magnus lets you write Ruby extension libraries (or 'gems') in Rust, or embed Ruby in your Rust program.
A large portion of Ruby encoding API has been added, this includes creating Ruby strings in any encoding, converting between encodings, iterating a Ruby string's codepoints, testing a character's type, and an optimisation to RString::as_str that can avoid utf8 validity checks when that information is already known by Ruby.
Conversions between Ruby's integer and float format and the native types used by Rust has seen dramatic performance improvements, and is now on-par with C performance.
Ruby Proc objects can now be created from a Rust closure.
Many functions, plus BoxValue, that were previously stuck using the base Ruby Value type can now accept any Ruby type. Along the same lines, arguments to the closure of RHash::foreach are not longer forced to Value and can now participate in automatic type conversion.
For anyone already familiar with Ruby's C API, or taking advantage of documentation or guides assuming use of C an index has been added to the documentation mapping C functions to Rust functions in Magnus. This currently only lists the parts of Ruby's API implemented in Magnus, and is missing some cases where Magnus has equivalent behaviour, but it isn't directly implemented in terms of the C API. This will be expanded in future releases.
Many additional methods for the core Ruby classes String, Array, and Hash:
RString::new_sharedRString::new_frozenRString::enc_newRString::enc_coderangeRString::codepointsRString::char_bytesRString::lenRString::lengthRString::is_emptyRArray::dupRArray::concatRArray::plusRArray::deleteRArray::delete_atRArray::resizeRArray::reverseRArray::rotateRArray::sortRHash::deleteRHash::clearThe rb-sys-interop feature swaps out the built in low-level bindings to Ruby for rb-sys and enables a module with functionality for interoperability. Future versions of Magnus will switch to rb-sys, and this feature should be considered a preview. Please give it a try and feedback is welcomed.
A handful of bugs have been fixed, including:
StaticSymbol from a &str with characters outside the ASCII range.define_*_method functions now return an error, as they are in fact fallible.And many more changes, see CHANGELOG.md for more details.
RString::new_shared and RString::new_frozen.encoding module, including encoding::Index and RbEncoding types.RString::enc_coderange and related methods.RString::codepoints and RString::char_bytes iterators over string
contents.RArray: dup, concat, plus, delete,
delete_at, resize, reverse, rotate, and sort.RString: enc_new, len, length, and is_empty.RHash gains the methods delete and clear.require, current_receiver, call_super, and define_global_const
functions.Object::singleton_class and Object::extend_object.Proc::new, Proc::arity, and Proc::is_lambda.superclass and name methods for RClass.scan_args::check_arity.Module: include_module, prepend_module, const_set,
ancestors, define_attr, and define_alias.rb-sys-interop feature to use low level bindings from rb-sys, and rb_sys
module to expose functions for working with rb-sys.gc::register_mark_object, gc::register_address,
gc::unregister_address, gc::count, gc::stat, and gc::all_stats.Error::iter_break.StaticSymbol::check and Id::check to check if a symbol exists.RArray::cat, RArray::from_slice, and gc::mark_slice will accept a
slice of any Ruby type as an argument, rather than only a slice of Value.
This may change type inference rules such that things like
RArray::from_slice(&[1.into()]) will no longer work. Use
RArray::from_slice(&[Value::from(1)]) instead.gc::location will accept any Ruby type as an argument.BoxValue can hold any Ruby type, not just Value.RHash::foreach will now be
automatically converted from Value to Rust types.Module::define_method, Module::define_private_method,
Module::define_protected_method, RModule::define_singleton_method, and
Object::define_singleton_method all return Result<(), Error> rather than
() as they may fail in the unusual case that the receiver is frozen.String::encode_utf8, use r_string.conv_enc(RbEncoding::utf8()) instead.Value::leak, use gc::register_mark_object instead.define_global_variable (use define_variable) to better match Ruby C API
naming.Exception::backtrace, use ex.funcall("backtrace", ()) instead.error::protect removed as it should not be needed when using Magnus. For
use with rb-sys enable the rb-sys-interop feature and use
magnus::rb_sys::protect.Qfalse::new, Qnil::new, Qtrue::new, Qundef::new (use
QFALSE/QNIL/QTRUE/QUNDEF).Error with a specific Ruby type. E.g.
Error::type_error("..."), use Error::new(exception::type_error(), "...").StaticSymbol from a &str with characters outside the ASCII
range.DataTypeFunctions will abort the
process to avoid undefined behaviour.RHash::foreach won't result in undefined
behaviour.Magnus 0.2.1 is a patch release, with 1 bug fix.
Magnus 0.2.1 is a patch release, with 1 bug fix.
Fixed compilation error in method! and function! macros with arity argument of 5.
Magnus 0.2.0 brings a number of new features and fixes to Magnus.
Magnus 0.2.0 brings a number of new features and fixes to Magnus.
Magnus is a Rust library binding to the C API of the Ruby programming language. Magnus lets you write Ruby extension libraries in Rust, or embed Ruby in your Rust program.
This release brings improvements to the documentation, adding doc examples to large parts of the API. As the doc examples are run as part of the tests, this also improves the test coverage in Magnus.
scan_args and get_kwargs functions have been implemented for complex argument handing. These functions are driven by the type parameters in their return type, adding a compile-time checked layer atop the base API exposed by Ruby.
Value::block_call allows for calling Ruby methods, passing a Rust closure as a 'block' parameter.
See CHANGELOG.md for more details.
class, module, and error modules to access built-in
classes/modules.RArray::len, RArray::includes, RArray::join, RArray::is_shared,
RArray::replace, and RArray::subseq.From<&str> and From<String> for RString.Range.Class::new and Module::new for creating anonymous classes/modules.r_string! macro to create Ruby string from a str literal.Value::equal and Value::eql for object equality.Value::respond_to and Value::check_funcall for conditionally calling Ruby
methods only when they are defined.scan_args and get_kwargs for complex argument parsing.Qundef::to_value now marked unsafe.RArray::cat, RArray::push, RArray::unshift, and RArray::store now
return Result<(), Error>.eval! macro uses anonymous (rather than caller's) binding.Qfalse::new, Qnil::new, Qtrue::new, Qundef::new (use
QFALSE/QNIL/QTRUE/QUNDEF).Error with a specific Ruby type. E.g.
Error::type_error("...") is now Error::new(exception::type_error(), "...")Binding::new. This will be removed in the future as the underlying
rb_binding_new will not function as of Ruby 3.2.isize/i64/usize/u64 on Windows.RArray methods now correctly protect from exceptions (instead
returning Result<_, Error> when an exception occurs).Magnus 0.1.0 is the first release of Magnus, Rust bindings to the C API of the Ruby programming language. Magnus lets you write Ruby extension librari
Magnus 0.1.0 is the first release of Magnus, Rust bindings to the C API of the Ruby programming language. Magnus lets you write Ruby extension libraries in Rust, or embed Ruby in your Rust program.
This first release includes, support for most core Ruby classes, String, Symbol, Integer, Float, Array, Hash and more.
Rust functions can be bound as Ruby methods, with automatic conversion between Ruby objects and Rust types for arguments and return values. This includes returning Rust's Result to raise a Ruby Exception.
Ruby methods can be called from Rust, again with automatic type conversions, including Ruby Exceptions converted to Rust's Result.
See CHANGELOG.md for more details.
String, Symbol, Integer, Float,
Array, Hash and more.Enumerator as a iterator.yield to Ruby blocks.#[init] macro to mark init function to load extension with require.One column per quarter.