Overview
Rusby is a Ruby to Rust transpiler for simple performance-oriented methods.
Computations in plain Ruby are painfully slow. Almost all internal methods in of Ruby are implemented in C, thus achieving acceptable performance on e.g. Array#sort.
On the other hand extension of ruby code with C or other low-level language functions is not to say hard... but at least is tricky. Rusby allows to write simple methods in plain ruby and convert them to rust with zero modifications.
Just mark method with rusby!
and you are ready to rust :/
N.B. It's a research project, so at least test for edge cases (e.g. overflows) before production usage.
Transpilation was tested only on cases in ./examples
directory.
How it works?
- You prefix your method definition with
!rusby
. - Native Ruby method is ran for the first time.
- Its arguments types and return type are recorded.
- These data along with source code of the method (as AST tree) are passed to the Rusby::Builder.
- Rusby::Builder calls Rusby::Rust, which recursively generates rust code based on AST tree (Rusby::Generators::*).
- Few hacks are applied along the way, see Rusby::Preprocessor, Rusby::Postrocessor.
- Generated Rust code is dumped to file into
./lib
Dir - Rust code is prettified and compiled into dynamic lib.
- At last we have ruby method and rust counterpart linked via FFI.
- Benchmark them and find the fastest one.
- Link the winner into the source class.
- Profit.
Features
- In-place ruby/rust method swapping based on benchmarks
- Recursive calls transpiling
- Nested functions transpiling
- Limited string operations support
- Integer matrix manipulation support
Quickstart
curl -sSf https://static.rust-lang.org/rustup.sh | sh # or install rust via your package manager
git clone https://github.com/rambler-digital-solutions/rusby
cd rusby/examples
bundle
ruby run_examples.rb
or
gem install rusby
Create file test.rb:
require 'rusby'
class FanaticGreeter
extend Rusby::Core
rusby!
def greet(name)
"Hello, #{name}!"
end
end
greeter = FanaticGreeter.new
2.times { greeter.greet('Ash') }
ruby test.rb
Tests
rake spec
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/rambler-digital-solutions/rusby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
License
The gem is available as open source under the terms of the MIT License.