- Notifications
You must be signed in to change notification settings - Fork37
Native Ruby extensions written in Rust
License
d-unsed/ruru
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Have you ever considered rewriting some parts of yourslow Ruby application?
Just replace your Ruby application with Rust, method by method, class by class. It does not require youto change the interface of your classes or to change any other Ruby code.
As simple as Ruby, as efficient as Rust.
The fastString#blank?
implementation by Yehuda Katz
#[macro_use]externcrate ruru;use ruru::{Boolean,Class,Object,RString};methods!(RString, itself,fn string_is_blank() ->Boolean{Boolean::new(itself.to_string().chars().all(|c| c.is_whitespace()))});#[no_mangle]pubexternfninitialize_string(){Class::from_existing("String").define(|itself|{ itself.def("blank?", string_is_blank);});}
Since 0.8.0 safe conversions are available for built-in Ruby types and for custom types.
Let's imagine that we are writing an HTTP server. It should handle requests which are passed fromRuby side.
Any object which responds to#body
method is considered as a valid request.
#[macro_use]externcrate ruru;use std::error::Error;use ruru::{Class,Object,RString,VerifiedObject,VM};class!(Request);implVerifiedObjectforRequest{fnis_correct_type<T:Object>(object:&T) ->bool{ object.respond_to("body")}fnerror_message() ->&'staticstr{"Not a valid request"}}class!(Server);methods!(Server, itself,fn process_request(request:Request) ->RString{let body = request.and_then(|request| request.send("body", vec![]).try_convert_to::<RString>()).map(|body| body.to_string());// Either request does not respond to `body` or `body` is not a StringifletErr(ref error) = body{VM::raise(error.to_exception(), error.description());}let formatted_body = format!("[BODY] {}", body.unwrap());RString::new(&formatted_body)});#[no_mangle]pubexternfninitialize_server(){Class::new("Server",None).define(|itself|{ itself.def("process_request", process_request);});}
WrapServer
s toRubyServer
objects
#[macro_use]externcrate ruru;#[macro_use]externcrate lazy_static;use ruru::{AnyObject,Class,Fixnum,Object,RString,VM};// The structure which we want to wrappubstructServer{host:String,port:u16,}implServer{fnnew(host:String,port:u16) ->Self{Server{host: host,port: port,}}fnhost(&self) ->&str{&self.host}fnport(&self) ->u16{self.port}}wrappable_struct!(Server,ServerWrapper,SERVER_WRAPPER);class!(RubyServer);methods!(RubyServer, itself,fn ruby_server_new(host:RString, port:Fixnum) ->AnyObject{let server =Server::new(host.unwrap().to_string(), port.unwrap().to_i64()asu16);Class::from_existing("RubyServer").wrap_data(server,&*SERVER_WRAPPER)}fn ruby_server_host() ->RString{let host = itself.get_data(&*SERVER_WRAPPER).host();RString::new(host)}fn ruby_server_port() ->Fixnum{let port = itself.get_data(&*SERVER_WRAPPER).port();Fixnum::new(portasi64)});fnmain(){let data_class =Class::from_existing("Data");Class::new("RubyServer",Some(&data_class)).define(|itself|{ itself.def_self("new", ruby_server_new); itself.def("host", ruby_server_host); itself.def("port", ruby_server_port);});}
Ruru provides a way to enable true parallelism for Ruby threads by releasing GVL (GIL).
It means that a thread with released GVL runs in parallel with other threads withoutbeing interrupted by GVL.
Current example demonstrates a "heavy" computation (2 * 2
for simplicity) run in parallel.
#[macro_use]externcrate ruru;use ruru::{Class,Fixnum,Object,VM};class!(Calculator);methods!(Calculator, itself,fn heavy_computation() ->Fixnum{let computation = ||{2*2};let unblocking_function = ||{};// release GVL for current thread until `computation` is completedlet result =VM::thread_call_without_gvl( computation,Some(unblocking_function));Fixnum::new(result)});fnmain(){Class::new("Calculator",None).define(|itself|{ itself.def("heavy_computation", heavy_computation);});}
Let's say you have aCalculator
class.
classCalculatordefpow_3(number)(1..number).each_with_object({})do |index,hash|hash[index]=index **3endendend# ... somewhere in the application code ...Calculator.new.pow_3(5)#=> { 1 => 1, 2 => 8, 3 => 27, 4 => 64, 5 => 125 }
You have found that it's very slow to callpow_3
for big numbers and decided to replace the whole classwith Rust.
#[macro_use]externcrate ruru;use std::error::Error;use ruru::{Class,Fixnum,Hash,Object,VM};class!(Calculator);methods!(Calculator, itself,fn pow_3(number:Fixnum) ->Hash{letmut result =Hash::new();// Raise an exception if `number` is not a FixnumifletErr(ref error) = number{VM::raise(error.to_exception(), error.description());}for i in1..number.unwrap().to_i64() +1{ result.store(Fixnum::new(i),Fixnum::new(i.pow(3)));} result});#[no_mangle]pubexternfninitialize_calculator(){Class::new("Calculator",None).define(|itself|{ itself.def("pow_3", pow_3);});}
Ruby:
# No Calculator class in Ruby anymore# ... somewhere in the application ...Calculator.new.pow_3(5)#=> { 1 => 1, 2 => 8, 3 => 27, 4 => 64, 5 => 125 }
Nothing has changed in the API of class, thus there is no need to change any code elsewhere in the app.
If theCalculator
class from the example above has more Ruby methods, but we want toreplace onlypow_3
, useClass::from_existing()
Class::from_existing("Calculator").define(|itself|{ itself.def("pow_3", pow_3);});
Class::new("Hello",None).define(|itself|{ itself.const_set("GREETING",&RString::new("Hello, World!").freeze()); itself.attr_reader("reader"); itself.def_self("greeting", greeting); itself.def("many_greetings", many_greetings); itself.define_nested_class("Nested",None).define(|itself|{ itself.def_self("nested_greeting", nested_greeting);});});
Which corresponds to the following Ruby code:
classHelloGREETING="Hello, World".freezeattr_reader:readerdefself.greeting# ...enddefmany_greetings# ...endclassNesteddefself.nested_greeting# ...endendend
See documentation forClass
andObject
for more information.
Getting an account balance of someUser
whose name is John and who is 18 or 19 years old.
default_balance=0account_balance=User.find_by(age:[18,19],name:'John').account_balanceaccount_balance=default_balanceunlessaccount_balance.is_a?(Fixnum)
#[macro_use]externcrate ruru;use ruru::{Array,Class,Fixnum,Hash,Object,RString,Symbol};fnmain(){let default_balance =0;letmut conditions =Hash::new(); conditions.store(Symbol::new("age"),Array::new().push(Fixnum::new(18)).push(Fixnum::new(19))); conditions.store(Symbol::new("name"),RString::new("John"));// Fetch user and his balance// and set it to 0 if balance is not a Fixnum (for example `nil`)let account_balance =Class::from_existing("User").send("find_by",vec![conditions.to_any_object()]).send("account_balance",vec![]).try_convert_to::<Fixnum>().map(|balance| balance.to_i64()).unwrap_or(default_balance);}
Check outDocumentation for many moreexamples!
No support of native Ruby types;
No way to create a standalone application to run the Ruby VM separately;
No way to call your Ruby code from Rust;
Warning! The crate is a WIP.
It is recommended to useThermite gem,a Rake-based helper for building and distributing Rust-based Ruby extensions.
To be able to use Ruru, make sure that your Ruby version is 2.3.0 or higher.
- Your local MRI copy has to be built with the
--enable-shared
option. Forexample, using rbenv:
CONFIGURE_OPTS=--enable-shared rbenv install 2.3.0
- Add Ruru to
Cargo.toml
[dependencies]ruru ="0.9.0"
- Compile your library as a
dylib
[lib]crate-type = ["dylib"]
- Create a function which will initialize the extension
#[no_mangle]pubexternfninitialize_my_app(){Class::new("SomeClass");// ... etc}
- Build extension
$ cargo build --release
or using Thermite
$ rake thermite:build
- On the ruby side, open the compiled
dylib
and call the function to initialize extension
require'fiddle'library=Fiddle::dlopen('path_to_dylib/libmy_library.dylib')Fiddle::Function.new(library['initialize_my_app'],[],Fiddle::TYPE_VOIDP).call
- Ruru is ready ❤️
If you have any questions, join Ruru onGitter
MIT License
Copyright (c) 2015-2016 Dmitry Gritsay
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.
Icon is designed byGithub.
About
Native Ruby extensions written in Rust