### setup Source: https://docs.rs/magnus/latest/magnus/embed/index.html?search= Performs basic initialisation of the Ruby VM. ```APIDOC ## setup ### Description Performs basic initialisation of the Ruby VM. ### Signature `pub fn setup()` ``` -------------------------------- ### Define a module example Source: https://docs.rs/magnus/latest/magnus/fn.define_module.html?search= Demonstrates defining a module named 'Example' and verifying its type using rb_assert. ```rust use magnus::{define_module, rb_assert}; define_module("Example").unwrap(); rb_assert!("Example.is_a?(Module)"); rb_assert!("!Example.is_a?(Class)"); ``` -------------------------------- ### Function signature for start Source: https://docs.rs/magnus/latest/magnus/gc/fn.start.html?search=u32+-%3E+bool The signature for the start function. ```rust pub fn start() ``` -------------------------------- ### Instantiate a class Source: https://docs.rs/magnus/latest/magnus/class/trait.Class.html?search=u32+-%3E+bool Examples of creating new instances of classes with various argument configurations. ```rust use magnus::{prelude::*, Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let s = ruby.class_string().new_instance(())?; assert!(s.is_kind_of(ruby.class_string())); assert_eq!(s.to_string(), ""); Ok(()) } ``` ```rust use magnus::{eval, kwargs, prelude::*, Error, RClass, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let cls: RClass = eval!( ruby, r#" class Foo def initialize(bar, baz:) @bar = bar @baz = baz end attr_reader(:bar, :baz) end Object.const_get(:Foo) "# )?; let instance = cls.new_instance((1, kwargs!("baz" => 2)))?; assert!(instance.is_kind_of(cls)); let bar: i32 = instance.funcall("bar", ())?; assert_eq!(bar, 1); let baz: i32 = instance.funcall("baz", ())?; assert_eq!(baz, 2); Ok(()) } ``` ```rust use magnus::{prelude::*, Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let s = ruby.exception_standard_error().new_instance(("bang!",))?; assert!(s.is_kind_of(ruby.exception_standard_error())); Ok(()) } ``` ```rust use magnus::{eval, ExceptionClass, kwargs, prelude::*, Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let exc: ExceptionClass = eval!( ruby, r#" class MyError < StandardError def initialize(message:) super(message) end end Object.const_get(:MyError) "# )?; let s = exc.new_instance((kwargs!("message" => "bang!"),))?; assert!(s.is_kind_of(exc)); let message: String = s.funcall("message", ())?; assert_eq!(message, "bang!"); Ok(()) } ``` -------------------------------- ### Function Signature Source: https://docs.rs/magnus/latest/magnus/embed/fn.setup.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E The signature for the setup function, which is available only when the embed feature is enabled. ```rust pub unsafe fn setup() -> Cleanup ``` -------------------------------- ### Example Search Queries Source: https://docs.rs/magnus/latest/magnus/module/struct.RModule.html?search= Common search patterns for finding types and functions within the documentation. ```text std::vec ``` ```text u32 -> bool ``` ```text Option, (T -> U) -> Option ``` -------------------------------- ### rb_assert Failure Example Source: https://docs.rs/magnus/latest/magnus/macro.rb_assert.html?search= Example of a failing assertion and its resulting panic output. ```rust magnus::rb_assert!("1 + 2 == 4"); ``` ```text thread 'main' panicked at ' 1 + 2 == 4 | | | false 3', src/lib.rs:5:1 ``` -------------------------------- ### Access Fiber-local Storage Source: https://docs.rs/magnus/latest/magnus/struct.Thread.html Demonstrates setting and getting values in fiber-local storage for a thread. ```rust use magnus::{Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let current = ruby.thread_current(); let val: Option = current.local_aref("example")?; assert!(val.is_none()); let other = ruby.thread_create(|ruby| { ruby.thread_stop()?; let val: String = ruby.thread_current().local_aref("example")?; assert_eq!(val, "test"); Ok(()) }); current.local_aset("example", "foo")?; other.local_aset("example", "test")?; let val: String = current.local_aref("example")?; assert_eq!(val, "foo"); other.run()?; Ok(()) } ``` ```rust use magnus::{Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let current = ruby.thread_current(); let val: Option = current.local_aref("example")?; assert!(val.is_none()); let other = ruby.thread_create(|ruby| { ruby.thread_stop()?; let val: String = ruby.thread_current().local_aref("example")?; assert_eq!(val, "test"); Ok(()) }); current.local_aset("example", "foo")?; other.local_aset("example", "test")?; let val: String = current.local_aref("example")?; assert_eq!(val, "foo"); other.run()?; Ok(()) } ``` -------------------------------- ### Create a new class Source: https://docs.rs/magnus/latest/magnus/class/trait.Class.html?search=u32+-%3E+bool Examples of creating new anonymous classes or exception classes. ```rust use magnus::{prelude::*, Error, RClass, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let class = RClass::new(ruby.class_object())?; assert!(class.is_kind_of(ruby.class_class())); Ok(()) } ``` ```rust use magnus::{prelude::*, Error, ExceptionClass, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { assert!(ExceptionClass::new(ruby.exception_standard_error()).is_ok()); Ok(()) } ``` -------------------------------- ### Load a Ruby feature Source: https://docs.rs/magnus/latest/magnus/fn.require.html?search= Example of using the require function to load the net/http Ruby library. ```rust use magnus::require; assert!(require("net/http").unwrap()); ``` -------------------------------- ### Adjusting memory usage example Source: https://docs.rs/magnus/latest/magnus/gc/fn.adjust_memory_usage.html?search= Demonstrates notifying Ruby of external memory allocation and subsequent deallocation. ```rust use magnus::gc; let buf = Vec::::with_capacity(1024 * 1024); let mem_size = buf.capacity() * std::mem::size_of::(); gc::adjust_memory_usage(mem_size as isize); // ... drop(buf); gc::adjust_memory_usage(-(mem_size as isize)); ``` -------------------------------- ### Implement TCPServer::new with explicit type parameters Source: https://docs.rs/magnus/latest/magnus/scan_args/fn.scan_args.html An alternative approach to the previous example, specifying types directly in the scan_args call. ```rust use magnus::{function, prelude::*, scan_args::scan_args, Error, Ruby, Value}; fn tcp_svr_init(args: &[Value]) -> Result { let args = scan_args::<(), (Option,), (), (u16,), (), ()>(args)?; let (hostname,) = args.optional; let (port,) = args.trailing; // ... } fn example(ruby: &Ruby) -> Result<(), Error> { let class = ruby.define_class("TCPServer", ruby.class_object())?; class.define_singleton_method("new", function!(tcp_svr_init, -1))?; Ok(()) } ``` -------------------------------- ### Define a Ruby method using method! Source: https://docs.rs/magnus/latest/magnus/macro.method.html Example of wrapping a Rust function with the method macro to define a Ruby method on a class. ```rust use magnus::{method, prelude::*, Error, Ruby}; fn rb_is_blank(rb_self: String) -> bool { rb_self.contains(|c: char| !c.is_whitespace()) } #[magnus::init] fn init(ruby: &Ruby) -> Result<(), Error> { let class = ruby.define_class("String", ruby.class_object())?; class.define_method("blank?", method!(rb_is_blank, 0))?; Ok(()) } ``` -------------------------------- ### Get Garbage Collection Count Source: https://docs.rs/magnus/latest/magnus/embed/struct.Cleanup.html?search=u32+-%3E+bool Returns the total number of GC runs since process start. ```rust use magnus::{Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let before = ruby.gc_count(); ruby.gc_start(); assert!(ruby.gc_count() > before); Ok(()) } ``` -------------------------------- ### Get Garbage Collection Count Source: https://docs.rs/magnus/latest/magnus/gc/fn.count.html?search= Returns the number of garbage collections run since process start. Requires the 'old-api' feature flag and must be called from a Ruby thread. ```rust pub fn count() -> usize ``` ```rust use magnus::gc; let before = gc::count(); gc::start(); assert!(gc::count() > before); ``` -------------------------------- ### init Source: https://docs.rs/magnus/latest/magnus/embed/index.html?search= Initialises the Ruby VM. ```APIDOC ## init ### Description Initialises the Ruby VM. ### Signature `pub fn init()` ``` -------------------------------- ### Implementing Cmp for a TypedData Struct Source: https://docs.rs/magnus/latest/magnus/typed_data/trait.Cmp.html Example demonstrating how to implement Cmp for a custom struct by leveraging PartialOrd and defining the <=> method. ```rust use std::cmp::Ordering; use magnus::{ function, gc, method, prelude::*, rb_assert, typed_data, value::Opaque, DataTypeFunctions, Error, Module, Ruby, TypedData, Value, }; #[derive(TypedData)] #[magnus(class = "Pair", free_immediately, mark)] struct Pair { #[magnus(opaque_attr_reader)] a: Opaque, #[magnus(opaque_attr_reader)] b: Opaque, } impl Pair { fn new(a: Value, b: Value) -> Self { Self { a: a.into(), b: b.into(), } } } impl DataTypeFunctions for Pair { fn mark(&self, marker: &gc::Marker) { marker.mark(self.a); marker.mark(self.b); } } impl PartialEq for Pair { fn eq(&self, other: &Self) -> bool { self.a().eql(other.a()).unwrap_or(false) && self.b().eql(other.b()).unwrap_or(false) } } impl PartialOrd for Pair { fn partial_cmp(&self, other: &Self) -> Option { let a = self .a() .funcall("<=>", (other.a(),)) .ok() .map(|o: i64| o.cmp(&0))?; match a { Ordering::Less | Ordering::Greater => Some(a), Ordering::Equal => self .b() .funcall("<=>", (other.b(),)) .ok() .map(|o: i64| o.cmp(&0)), } } } fn example(ruby: &Ruby) -> Result<(), Error> { let class = ruby.define_class("Pair", ruby.class_object())?; class.define_singleton_method("new", function!(Pair::new, 2))?; class.define_method("<=>", method!(::cmp, 1))?; class.include_module(ruby.module_comparable())?; let a = Pair::new( ruby.str_new("foo").as_value(), ruby.integer_from_i64(1).as_value(), ); let b = Pair::new( ruby.str_new("foo").as_value(), ruby.integer_from_i64(2).as_value(), ); rb_assert!(ruby, "a < b", a, b); let b = Pair::new( ruby.str_new("foo").as_value(), ruby.integer_from_i64(2).as_value(), ); let c = Pair::new( ruby.str_new("bar").as_value(), ruby.integer_from_i64(1).as_value(), ); rb_assert!(ruby, "b > c", b, c); let a = Pair::new( ruby.str_new("foo").as_value(), ruby.integer_from_i64(1).as_value(), ); let b = Pair::new( ruby.str_new("foo").as_value(), ruby.integer_from_i64(2).as_value(), ); rb_assert!(ruby, "(a <=> b) == -1", a, b); Ok(()) } ``` -------------------------------- ### Register a Rust function with Ruby Source: https://docs.rs/magnus/latest/magnus/macro.function.html Example of defining a Rust function and registering it as a global Ruby function using the function macro. ```rust fn distance(a: (f64, f64), b: (f64, f64)) -> f64 { ((b.0 - a.0).powi(2) + (b.0 - a.0).powi(2)).sqrt() } #[magnus::init] fn init(ruby: &magnus::Ruby) { ruby.define_global_function("distance", magnus::function!(distance, 2)); } ``` -------------------------------- ### Use Opaque for thread safety Source: https://docs.rs/magnus/latest/magnus/value/struct.Opaque.html Example showing how to wrap a Ruby value in Opaque and later retrieve it on a Ruby thread. ```rust use magnus::{rb_assert, value::Opaque, Ruby}; let ruby = Ruby::get().unwrap(); let opaque_str = Opaque::from(ruby.str_new("example")); // send to another Ruby thread let ruby = Ruby::get().unwrap(); // errors on non-Ruby thread let str = ruby.get_inner(opaque_str); rb_assert!(ruby, r#"str == "example""#, str); ``` -------------------------------- ### Implementing Writebarrier with TypedData Source: https://docs.rs/magnus/latest/magnus/typed_data/trait.Writebarrier.html Example demonstrating how to use writebarrier when pushing values into a protected TypedData structure. ```rust use std::cell::RefCell; use magnus::{ function, gc, method, prelude::*, typed_data::{Obj, Writebarrier}, value::Opaque, DataTypeFunctions, Error, Ruby, TypedData, Value, }; #[derive(TypedData)] #[magnus(class = "MyVec", free_immediately, mark, wb_protected)] struct MyVec { values: RefCell>>, } impl DataTypeFunctions for MyVec { fn mark(&self, marker: &gc::Marker) { marker.mark_slice(self.values.borrow().as_slice()); } } impl MyVec { fn new() -> Self { Self { values: RefCell::new(Vec::new()), } } fn push(ruby: &Ruby, rb_self: Obj, val: Value) -> Obj { rb_self.values.borrow_mut().push(val.into()); rb_self.writebarrier(rb_self); rb_self } } fn example(ruby: &Ruby) -> Result<(), Error> { let class = ruby.define_class("MyVec", ruby.class_object())?; class.define_singleton_method("new", function!(MyVec::new, 0))?; class.define_method("push", method!(MyVec::push, 1))?; let _: Value = ruby.eval( r#" vec = MyVec.new vec.push("test") vec.push("example") "#, )?; Ok(()) } ``` -------------------------------- ### magnus::embed::setup() Source: https://docs.rs/magnus/latest/magnus/embed/fn.setup.html?search= Initializes the Ruby VM core functionality. This function is only required when embedding Ruby in Rust and must be called in main or a high-level function. ```APIDOC ## magnus::embed::setup ### Description Performs basic initialization of the Ruby VM. This initializes the core of Ruby's functionality and is required when embedding Ruby in Rust. ### Signature `pub unsafe fn setup() -> Cleanup` ### Safety Must be called in `main()`, or at least a function higher up the stack than any code calling Ruby. The returned `Cleanup` object must not be dropped until the very end of the process, after all Ruby execution has finished. ### Panics Panics if this, `init`, or `Ruby::init` are collectively called more than once. ### Example ```rust let ruby = unsafe { magnus::embed::setup() }; let result: i64 = ruby.eval("2 + 2").unwrap(); assert_eq!(result, 4); ``` ``` -------------------------------- ### Usage of data_type_builder Source: https://docs.rs/magnus/latest/magnus/macro.data_type_builder.html Example usage of the data_type_builder macro. ```rust data_type_builder!(Example, "example") ``` -------------------------------- ### ascget Source: https://docs.rs/magnus/latest/magnus/encoding/struct.RbEncoding.html Attempts to retrieve an ASCII character from the start of the slice. ```APIDOC ## pub fn ascget(&self, slice: &[u8]) -> Option<(u8, usize)> ### Description If the first character in `slice` is included in ASCII return it and its encoded length in `slice`, otherwise returns None. ``` -------------------------------- ### magnus::embed::setup() Source: https://docs.rs/magnus/latest/magnus/embed/fn.setup.html?search=std%3A%3Avec Initializes the Ruby VM core functionality. This function is required when embedding Ruby in Rust and must be called in main() or a high-level stack frame. ```APIDOC ## pub unsafe fn setup() -> Cleanup ### Description Performs basic initialization of the Ruby VM. This function initializes the core of Ruby's functionality and is required when embedding Ruby in Rust. ### Safety Must be called in `main()`, or at least a function higher up the stack than any code calling Ruby. The returned `Cleanup` object must not be dropped until the very end of the process, after all Ruby execution has finished. ### Panics Panics if this function, `init`, or `Ruby::init` are collectively called more than once. ### Example ```rust let ruby = unsafe { magnus::embed::setup() }; let result: i64 = ruby.eval("2 + 2").unwrap(); assert_eq!(result, 4); ``` ``` -------------------------------- ### RMatch::backref_number Source: https://docs.rs/magnus/latest/magnus/struct.RMatch.html Gets the index of a named capture group. ```APIDOC ## pub fn backref_number(self, name: T) -> Result ### Description Returns the index for the named capture group. Returns an `Err` if no named capture group with the given name exists. ``` -------------------------------- ### magnus::embed::setup Source: https://docs.rs/magnus/latest/magnus/embed/fn.setup.html?search=u32+-%3E+bool Initializes the Ruby VM core functionality. This function is unsafe and must be called in main() or a high-level stack frame. ```APIDOC ## Function: magnus::embed::setup ### Description Performs basic initialization of the Ruby VM. This function is only required when embedding Ruby in Rust and should be called in `main()`. ### Signature `pub unsafe fn setup() -> Cleanup` ### Safety - Must be called in `main()` or a function higher up the stack than any code calling Ruby. - The returned `Cleanup` object must not be dropped until the end of the process. - Do not use Ruby values after `Cleanup` has been dropped. ### Panics Panics if this function, `init`, or `Ruby::init` are called more than once. ### Example ```rust let ruby = unsafe { magnus::embed::setup() }; let result: i64 = ruby.eval("2 + 2").unwrap(); assert_eq!(result, 4); ``` ``` -------------------------------- ### Implement TCPServer::new argument handling Source: https://docs.rs/magnus/latest/magnus/scan_args/fn.scan_args.html Demonstrates parsing arguments for a method equivalent to def new(hostname=nil, port). ```rust use magnus::{function, prelude::*, scan_args::scan_args, Error, Ruby, Value}; fn tcp_svr_init(args: &[Value]) -> Result { let args = scan_args(args)?; let _: () = args.required; let (hostname,): (Option,) = args.optional; let _: () = args.splat; let (port,): (u16,) = args.trailing; let _: () = args.keywords; let _: () = args.block; // ... } fn example(ruby: &Ruby) -> Result<(), Error> { let class = ruby.define_class("TCPServer", ruby.class_object())?; class.define_singleton_method("new", function!(tcp_svr_init, -1))?; Ok(()) } ``` -------------------------------- ### Get RArray Length Source: https://docs.rs/magnus/latest/magnus/r_array/struct.RArray.html?search= Retrieve the number of elements in the RArray. ```rust use magnus::{Error, RArray, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let ary = ruby.ary_new(); assert_eq!(ary.len(), 0); let ary: RArray = ruby.eval("[:a, :b, :c]")?; assert_eq!(ary.len(), 3); Ok(()) } ``` -------------------------------- ### Get Main Thread Source: https://docs.rs/magnus/latest/magnus/embed/struct.Cleanup.html?search= Returns the main Ruby thread. ```rust use magnus::{prelude::*, Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let t = ruby.thread_main(); t.is_kind_of(ruby.class_thread()); Ok(()) } ``` -------------------------------- ### Implement TCPServer::new argument handling Source: https://docs.rs/magnus/latest/magnus/scan_args/fn.scan_args.html?search=u32+-%3E+bool Demonstrates parsing arguments for a method equivalent to def new(hostname=nil, port). ```rust use magnus::{function, prelude::*, scan_args::scan_args, Error, Ruby, Value}; fn tcp_svr_init(args: &[Value]) -> Result { let args = scan_args(args)?; let _: () = args.required; let (hostname,): (Option,) = args.optional; let _: () = args.splat; let (port,): (u16,) = args.trailing; let _: () = args.keywords; let _: () = args.block; // ... } fn example(ruby: &Ruby) -> Result<(), Error> { let class = ruby.define_class("TCPServer", ruby.class_object())?; class.define_singleton_method("new", function!(tcp_svr_init, -1))?; Ok(()) } ``` ```rust use magnus::{function, prelude::*, scan_args::scan_args, Error, Ruby, Value}; fn tcp_svr_init(args: &[Value]) -> Result { let args = scan_args::<(), (Option,), (), (u16,), (), ()>(args)?; let (hostname,) = args.optional; let (port,) = args.trailing; // ... } fn example(ruby: &Ruby) -> Result<(), Error> { let class = ruby.define_class("TCPServer", ruby.class_object())?; class.define_singleton_method("new", function!(tcp_svr_init, -1))?; Ok(()) } ``` -------------------------------- ### ascget Source: https://docs.rs/magnus/latest/magnus/encoding/struct.RbEncoding.html?search=u32+-%3E+bool Attempts to retrieve an ASCII character and its length from the start of the slice. ```APIDOC ## pub fn ascget(&self, slice: &[u8]) -> Option<(u8, usize)> ### Description If the first character in `slice` is included in ASCII, return it and its encoded length in `slice`, otherwise returns None. ``` -------------------------------- ### Basic init macro usage Source: https://docs.rs/magnus/latest/magnus/attr.init.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Apply the attribute to a function to register it as the library entry point. ```rust #[init] ``` -------------------------------- ### gc_start Source: https://docs.rs/magnus/latest/magnus/struct.Ruby.html?search=u32+-%3E+bool Triggers a full GC run. ```APIDOC ## pub fn gc_start(&self) ### Description Trigger a full GC run. This will perform a full mark phase and a complete sweep phase, but may not run every single process associated with garbage collection. ``` -------------------------------- ### Get RString Character Length Source: https://docs.rs/magnus/latest/magnus/r_string/struct.RString.html?search=std%3A%3Avec Returns the number of characters in the RString. ```rust use magnus::{Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let s = ruby.str_new("🦀 Hello, Ferris"); assert_eq!(s.length(), 15); Ok(()) } ``` -------------------------------- ### Get Current Thread Source: https://docs.rs/magnus/latest/magnus/embed/struct.Cleanup.html?search= Returns the currently executing Ruby thread. ```rust use magnus::{prelude::*, Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let t = ruby.thread_current(); t.is_kind_of(ruby.class_thread()); Ok(()) } ``` -------------------------------- ### gc_start Source: https://docs.rs/magnus/latest/magnus/embed/struct.Cleanup.html?search=u32+-%3E+bool Triggers a full garbage collection run. ```APIDOC ## pub fn gc_start(&self) ### Description Trigger a “full” GC run. This will perform a full mark phase and a complete sweep phase, but may not run every single process associated with garbage collection. Finalisers will be deferred to run later. ``` -------------------------------- ### rb_assert Failure Output Source: https://docs.rs/magnus/latest/magnus/macro.rb_assert.html Example of the panic output generated when an assertion fails. ```text thread 'main' panicked at ' 1 + 2 == 4 | | | false 3', src/lib.rs:5:1 ``` -------------------------------- ### Initialize Ruby VM Source: https://docs.rs/magnus/latest/magnus/embed/fn.init.html Initializes the Ruby VM and returns a Cleanup object that must be kept in scope until the end of the process. ```rust let ruby = unsafe { magnus::embed::init() }; let result: i64 = ruby.eval("2 + 2").unwrap(); assert_eq!(result, 4); ``` -------------------------------- ### Retrieve Superclass Source: https://docs.rs/magnus/latest/magnus/class/trait.Class.html?search=u32+-%3E+bool Examples of retrieving the parent class of a given Ruby class. ```rust use magnus::{prelude::*, Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let klass = ruby.class_hash().superclass()?; assert!(klass.equal(ruby.class_object())?); Ok(()) } ``` ```rust use magnus::{prelude::*, Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let klass = ruby.exception_exception().superclass()?; assert!(klass.equal(ruby.class_object())?); Ok(()) } ``` -------------------------------- ### Inspect RRegexp options Source: https://docs.rs/magnus/latest/magnus/r_regexp/struct.RRegexp.html?search=u32+-%3E+bool Retrieve the configuration options applied to a regex object. ```rust use magnus::{Error, RRegexp, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let regexp: RRegexp = ruby.eval("/x/i").unwrap(); assert!(regexp.options().is_ignorecase()); assert!(!regexp.options().is_multiline()); let regexp: RRegexp = ruby.eval("/x/m").unwrap(); assert!(!regexp.options().is_ignorecase()); assert!(regexp.options().is_multiline()); Ok(()) } ``` -------------------------------- ### fn new_instance(self, args: T) -> Result Source: https://docs.rs/magnus/latest/magnus/class/trait.Class.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new instance of the class, invoking the class's initialize method with the provided arguments. ```APIDOC ## fn new_instance(self, args: T) -> Result ### Description Create a new object, an instance of `self`, passing the arguments `args` to the initialiser. ### Parameters - **args** (T: ArgList) - The arguments to pass to the class initializer. ### Returns - **Result** - The new instance of the class or an error. ``` -------------------------------- ### Get imaginary part of RComplex Source: https://docs.rs/magnus/latest/magnus/struct.RComplex.html?search= Extract the imaginary component of the complex number. ```rust use magnus::{Error, RComplex, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let complex = RComplex::new(ruby.integer_from_i64(9), ruby.integer_from_i64(-4)); assert_eq!(complex.imag::()?, -4); Ok(()) } ``` -------------------------------- ### Get real part of RComplex Source: https://docs.rs/magnus/latest/magnus/struct.RComplex.html?search= Extract the real component of the complex number. ```rust use magnus::{Error, RComplex, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let complex = RComplex::new(ruby.integer_from_i64(9), ruby.integer_from_i64(-4)); assert_eq!(complex.real::()?, 9); Ok(()) } ``` -------------------------------- ### fn new_instance(self, args: T) -> Result Source: https://docs.rs/magnus/latest/magnus/class/trait.Class.html?search= Creates a new instance of the class, invoking the Ruby initialize method with the provided arguments. ```APIDOC ## fn new_instance(self, args: T) -> Result ### Description Creates a new object as an instance of the class, passing the provided arguments to the Ruby initialize method. ### Parameters - **args** (T) - Arguments to pass to the initialize method, must implement ArgList. ### Returns - **Result** - The new instance or an error. ``` -------------------------------- ### Get RString Byte Length Source: https://docs.rs/magnus/latest/magnus/r_string/struct.RString.html?search=std%3A%3Avec Returns the total number of bytes in the RString. ```rust use magnus::{Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let s = ruby.str_new("🦀 Hello, Ferris"); assert_eq!(s.len(), 18); Ok(()) } ``` -------------------------------- ### magnus::embed::setup Source: https://docs.rs/magnus/latest/magnus/embed/fn.setup.html Initializes the Ruby VM core functionality. This function is intended for use when embedding Ruby within a Rust application. ```APIDOC ## magnus::embed::setup ### Description Performs basic initialization of the Ruby VM. This function is required only when embedding Ruby in Rust and should be called in `main()` or a function higher up the stack. ### Signature `pub unsafe fn setup() -> Cleanup` ### Safety Must be called in `main()`, or at least a function higher up the stack than any code calling Ruby. The returned `Cleanup` object must not be dropped until the very end of the process, after all Ruby execution has finished. ### Panics Panics if this function, `init`, or `Ruby::init` are collectively called more than once. ### Example ```rust let ruby = unsafe { magnus::embed::setup() }; let result: i64 = ruby.eval("2 + 2").unwrap(); assert_eq!(result, 4); ``` ``` -------------------------------- ### Get member by identifier Source: https://docs.rs/magnus/latest/magnus/r_struct/struct.RStruct.html?search= Access a member value specifically by its name identifier. ```rust use magnus::{prelude::*, Error, RStruct, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let struct_class = ruby.define_struct(None, ("foo", "bar"))?; let instance = RStruct::from_value(struct_class.new_instance((1, 2))?).unwrap(); assert_eq!(instance.getmember::<_, i64>("foo")?, 1); assert_eq!(instance.getmember::<_, i64>("bar")?, 2); Ok() } ``` -------------------------------- ### Get struct member names Source: https://docs.rs/magnus/latest/magnus/r_struct/struct.RStruct.html?search= Retrieve a list of all member names as strings. ```rust use magnus::{prelude::*, Error, RStruct, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let struct_class = ruby.define_struct(None, ("foo", "bar", "baz"))?; let instance = RStruct::from_value(struct_class.new_instance(())?).unwrap(); assert_eq!(instance.members()?, &["foo", "bar", "baz"]); Ok() } ``` -------------------------------- ### Ruby::init Source: https://docs.rs/magnus/latest/magnus/struct.Ruby.html Initializes the Ruby VM. This function is required when embedding Ruby in Rust and can only be called once per process. ```APIDOC ## pub fn init(func: fn(&Ruby) -> Result<(), Error>) -> Result<(), String> ### Description Initialises the Ruby VM. Calling this function is only required when embedding Ruby in Rust. It is not required when embedding Rust in Ruby, e.g. in a Ruby Gem. ### Parameters - **func** (fn(&Ruby) -> Result<(), Error>) - Required - A function pointer to execute within the Ruby VM context. ### Notes - Available on crate feature `embed` only. - The Ruby VM can only be initialised once per process. - Panics if this, `init`, or `setup` are collectively called more than once. ``` -------------------------------- ### Get struct size Source: https://docs.rs/magnus/latest/magnus/r_struct/struct.RStruct.html?search= Returns the total number of members defined in the struct. ```rust use magnus::{prelude::*, Error, RStruct, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let struct_class = ruby.define_struct(None, ("foo", "bar", "baz"))?; let instance = RStruct::from_value(struct_class.new_instance(())?).unwrap(); assert_eq!(instance.size(), 3); Ok() } ``` -------------------------------- ### magnus::embed::setup Source: https://docs.rs/magnus/latest/magnus/embed/fn.setup.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes the Ruby VM core functionality. This function is required when embedding Ruby in Rust and must be called early in the execution stack. ```APIDOC ## Function: magnus::embed::setup ### Description Performs basic initialization of the Ruby VM. This function initializes the core of Ruby's functionality and is required when embedding Ruby in Rust. ### Signature `pub unsafe fn setup() -> Cleanup` ### Safety - Must be called in `main()` or a function higher up the stack than any code calling Ruby. - The returned `Cleanup` object must not be dropped until the very end of the process, after all Ruby execution has finished. - Do not use Ruby values after `Cleanup` has been dropped. ### Panics Panics if this function, `init`, or `Ruby::init` are collectively called more than once. ### Example ```rust let ruby = unsafe { magnus::embed::setup() }; let result: i64 = ruby.eval("2 + 2").unwrap(); assert_eq!(result, 4); ``` ``` -------------------------------- ### Get encoding with enc_get Source: https://docs.rs/magnus/latest/magnus/encoding/trait.EncodingCapable.html Retrieves the current encoding index of a Ruby object. ```rust use magnus::{encoding::EncodingCapable, Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { assert!(ruby.str_new("example").enc_get() == ruby.utf8_encindex()); Ok(()) } ``` -------------------------------- ### Initialize Ruby VM Source: https://docs.rs/magnus/latest/magnus/struct.Ruby.html?search=u32+-%3E+bool Initializes the Ruby VM when embedding Ruby in Rust. This must be called only once per process. ```rust magnus::Ruby::init(|ruby| { let result: i64 = ruby.eval("2 + 2")?; assert_eq!(result, 4); Ok(()) }) .unwrap() ``` -------------------------------- ### Using InnerValue with Lazy Source: https://docs.rs/magnus/latest/magnus/value/trait.InnerValue.html?search= Example demonstrating how to retrieve an inner value from a Lazy wrapper. ```rust use magnus::{ rb_assert, value::{InnerValue, Lazy}, RString, Ruby, }; static STATIC_STR: Lazy = Lazy::new(|ruby| ruby.str_new("example")); let ruby = Ruby::get().unwrap(); // errors if Ruby not initialised let str = STATIC_STR.get_inner_with(&ruby); rb_assert!(ruby, r#"str == "example""#, str); ``` -------------------------------- ### Using InnerValue with Opaque Source: https://docs.rs/magnus/latest/magnus/value/trait.InnerValue.html?search= Example demonstrating how to retrieve an inner value from an Opaque wrapper. ```rust use magnus::{ rb_assert, value::{InnerValue, Opaque}, Ruby, }; let ruby = Ruby::get().unwrap(); let opaque_str = Opaque::from(ruby.str_new("example")); // send to another Ruby thread let ruby = Ruby::get().unwrap(); // errors on non-Ruby thread let str = opaque_str.get_inner_with(&ruby); rb_assert!(ruby, r#"str == "example""#, str); ``` -------------------------------- ### #[magnus::init] Source: https://docs.rs/magnus/latest/magnus/attr.init.html Marks a function as the initialization entry point for a Ruby extension. The function is executed when the library is required by Ruby. ```APIDOC ## #[magnus::init] ### Description Marks a function as the 'init' function to be run for a library when it is `require`d by Ruby code. This function is used to define Ruby modules, classes, and bind functions as Ruby methods. ### Attributes - **name** (string) - Optional - Sets the name of the init function exported for Ruby. Defaults to the current crate's name. The name is prepended with `Init_` and hyphens are replaced with underscores. This must match the name of the final `.so`/`.bundle` file. ### Usage ```rust #[magnus::init] fn init(ruby: &magnus::Ruby) { // Define modules, classes, and methods here } ``` ### Return Types The init function can return `()` or `Result<(), magnus::Error>` to handle initialization errors. ``` -------------------------------- ### #[magnus::init] Source: https://docs.rs/magnus/latest/magnus/attr.init.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Marks a function as the initialization entry point for a Ruby extension. The function is executed when the library is required by Ruby. ```APIDOC ## #[magnus::init] ### Description Marks a function as the 'init' function to be run for a library when it is `require`d by Ruby code. This function is used to define Ruby modules, classes, and bind Rust functions as Ruby methods. ### Attributes - **name** (string) - Optional - Sets the name of the init function exported for Ruby. Defaults to the crate name, prepended with `Init_` with hyphens replaced by underscores. ### Usage Example ```rust #[magnus::init] fn init(ruby: &magnus::Ruby) { ruby.define_global_function("distance", magnus::function!(distance, 2)); } ``` ### Return Types The init function can return `()` or `Result<(), magnus::Error>` to handle initialization errors. ``` -------------------------------- ### Implement TypedData::data_type Source: https://docs.rs/magnus/latest/magnus/typed_data/trait.TypedData.html?search= Example implementation of the data_type method using the data_type_builder macro. ```rust use magnus::{data_type_builder, DataType, DataTypeFunctions, TypedData}; #[derive(DataTypeFunctions)] struct Example(); unsafe impl TypedData for Example { // ... fn data_type() -> &'static DataType { static DATA_TYPE: DataType = data_type_builder!(Example, "example").build(); &DATA_TYPE } } ``` -------------------------------- ### Copying Result Contents Source: https://docs.rs/magnus/latest/magnus/error/type.Result.html Examples of copying or cloning the contents of a Result containing a reference. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Create and use kwargs in Ruby Source: https://docs.rs/magnus/latest/magnus/macro.kwargs.html Demonstrates creating keyword arguments in Rust and passing them to a Ruby method via funcall. ```rust use magnus::{eval, kwargs, prelude::*, RObject}; let kwargs = kwargs!("a" => 1, "b" => 2); let object: RObject = eval!( r#" class Adder def add(a:, b:) a + b end end Adder.new "# ) .unwrap(); let result: i32 = object.funcall("add", (kwargs,)).unwrap(); assert_eq!(3, result); ``` -------------------------------- ### StaticSymbol::new Source: https://docs.rs/magnus/latest/magnus/value/struct.StaticSymbol.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new StaticSymbol from a given name. Requires the 'old-api' feature. ```APIDOC ## StaticSymbol::new(name: T) -> Self ### Description Creates a new static symbol. Note: This method panics if called from a non-Ruby thread. ### Parameters - **name** (T: IntoId) - The name of the symbol to create. ``` -------------------------------- ### RComplex::new Source: https://docs.rs/magnus/latest/magnus/struct.RComplex.html?search= Creates a new RComplex instance from real and imaginary components. ```APIDOC ## pub fn new(real: T, imag: U) -> RComplex ### Description Create a new `RComplex`. ``` -------------------------------- ### Get Id from LazyId Source: https://docs.rs/magnus/latest/magnus/value/struct.LazyId.html?search= Retrieves the underlying Id from a LazyId, panicking if the instance is poisoned. ```rust use magnus::{value::LazyId, Error, Ruby}; static EXAMPLE: LazyId = LazyId::new("example"); fn example(ruby: &Ruby) -> Result<(), Error> { assert!(ruby.intern("example") == LazyId::get_inner_with(&EXAMPLE, &ruby)); Ok(()) } ``` -------------------------------- ### StaticSymbol::new Source: https://docs.rs/magnus/latest/magnus/value/struct.StaticSymbol.html?search=u32+-%3E+bool Creates a new StaticSymbol. Available only with the 'old-api' feature enabled. ```APIDOC ### pub fn new(name: T) -> Self where T: IntoId Creates a new StaticSymbol. Panics if called from a non-Ruby thread. ``` -------------------------------- ### Get string after match Source: https://docs.rs/magnus/latest/magnus/struct.RMatch.html Use post to retrieve the portion of the string following the match. ```rust use magnus::{Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let regexp = ruby.reg_new("b(.)r", Default::default())?; regexp.reg_match("foo bar baz")?; let match_data = ruby.backref_get().unwrap(); assert_eq!(match_data.post().to_string()?, " baz"); Ok(()) } ``` -------------------------------- ### fn new_instance(self, args: T) -> Result Source: https://docs.rs/magnus/latest/magnus/class/trait.Class.html?search=std%3A%3Avec Creates a new object as an instance of the class, passing the provided arguments to the Ruby initialize method. ```APIDOC ## fn new_instance(self, args: T) -> Result ### Description Create a new object, an instance of `self`, passing the arguments `args` to the initialiser. ### Parameters - **args** (T: ArgList) - The arguments to pass to the Ruby initialize method. ``` -------------------------------- ### Get string before match Source: https://docs.rs/magnus/latest/magnus/struct.RMatch.html Use pre to retrieve the portion of the string preceding the match. ```rust use magnus::{Error, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let regexp = ruby.reg_new("b(.)r", Default::default())?; regexp.reg_match("foo bar baz")?; let match_data = ruby.backref_get().unwrap(); assert_eq!(match_data.pre().to_string()?, "foo "); Ok(()) } ``` -------------------------------- ### Get struct member by index Source: https://docs.rs/magnus/latest/magnus/r_struct/struct.RStruct.html?search= Retrieve a member value using its integer index. ```rust use magnus::{prelude::*, Error, RStruct, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let struct_class = ruby.define_struct(None, ("foo", "bar"))?; let instance = RStruct::from_value(struct_class.new_instance((1, 2))?).unwrap(); assert_eq!(instance.get::(0)?, 1); assert_eq!(instance.get::(1)?, 2); Ok() } ``` -------------------------------- ### Integer Methods Source: https://docs.rs/magnus/latest/magnus/struct.Integer.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Methods for creating and converting Integer instances. ```APIDOC ## pub fn from_value(val: Value) -> Option ### Description Returns `Some(Integer)` if the provided `Value` is an `Integer`, otherwise returns `None`. ## pub fn from_i64(n: i64) -> Self ### Description Creates a new `Integer` from an `i64`. Note: This requires the `old-api` feature and will panic if called from a non-Ruby thread. ## pub fn from_u64(n: u64) -> Self ### Description Creates a new `Integer` from a `u64`. Note: This requires the `old-api` feature and will panic if called from a non-Ruby thread. ## pub fn to_i8(self) -> Result ### Description Converts the `Integer` to an `i8`. Returns an `Err` if the value is out of range for `i8`. ## pub fn to_i16(self) -> Result ### Description Converts the `Integer` to an `i16`. Returns an `Err` if the value is out of range for `i16`. ## pub fn to_i32(self) -> Result ### Description Converts the `Integer` to an `i32`. Returns an `Err` if the value is out of range for `i32`. ## pub fn to_i64(self) -> Result ### Description Converts the `Integer` to an `i64`. Returns an `Err` if the value is out of range for `i64`. ## pub fn to_i128(self) -> Result ### Description Converts the `Integer` to an `i128`. Returns an `Err` if the value is out of range for `i128`. ``` -------------------------------- ### Get RHash length as usize Source: https://docs.rs/magnus/latest/magnus/r_hash/struct.RHash.html?search= Returns the number of entries in the RHash as a Rust usize. ```rust use magnus::{Error, RHash, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let hash: RHash = ruby.eval(r#"{"foo" => 1, "bar" => 2, "baz" => 4}"#)?; assert_eq!(hash.len(), 3); Ok(()) } ``` -------------------------------- ### StaticSymbol::new Source: https://docs.rs/magnus/latest/magnus/value/struct.StaticSymbol.html?search= Creates a new StaticSymbol from a given name. Available only with the 'old-api' feature flag. ```APIDOC ## pub fn new(name: T) -> Self ### Description Create a new StaticSymbol. Panics if called from a non-Ruby thread. ### Parameters - **name** (T: IntoId) - The name of the symbol. ``` -------------------------------- ### Get RHash size as Fixnum Source: https://docs.rs/magnus/latest/magnus/r_hash/struct.RHash.html?search= Returns the number of entries in the RHash as a Ruby Fixnum. ```rust use magnus::{Error, RHash, Ruby}; fn example(ruby: &Ruby) -> Result<(), Error> { let hash: RHash = ruby.eval(r#"{"foo" => 1, "bar" => 2, "baz" => 4}"#)?; assert_eq!(hash.size().to_i64(), 3); Ok(()) } ``` -------------------------------- ### StaticSymbol::new Source: https://docs.rs/magnus/latest/magnus/value/struct.StaticSymbol.html?search=std%3A%3Avec Creates a new StaticSymbol from a given name. Available only with the 'old-api' feature flag. ```APIDOC ## pub fn new(name: T) -> Self ### Description Create a new StaticSymbol. Panics if called from a non-Ruby thread. ### Parameters - **name** (T: IntoId) - Required - The name of the symbol. ``` -------------------------------- ### Implement Addrinfo::getaddrinfo argument handling Source: https://docs.rs/magnus/latest/magnus/scan_args/fn.scan_args.html Handles a complex signature including required, optional, and keyword arguments. ```rust use magnus::{function, prelude::*, scan_args::{get_kwargs, scan_args}, Error, Ruby, Symbol, Value}; fn getaddrinfo(args: &[Value]) -> Result { let args = scan_args::<_, _, (), (), _, ()>(args)?; let (nodename, service): (String, u16) = args.required; let (family, socktype, protocol, flags): ( Option, Option, Option, Option, ) = args.optional; let kw = get_kwargs::<_, (), (Option,), ()>(args.keywords, &[], &["timeout"])?; let (timeout,) = kw.optional; // ... } fn example(ruby: &Ruby) -> Result<(), Error> { let class = ruby.define_class("Addrinfo", ruby.class_object())?; class.define_singleton_method("getaddrinfo", function!(getaddrinfo, -1))?; Ok(()) } ``` -------------------------------- ### Function Signature Source: https://docs.rs/magnus/latest/magnus/embed/fn.init.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E The signature for the init function. ```rust pub unsafe fn init() -> Cleanup ```