Skip to content

Instantly share code, notes, and snippets.

@steveklabnik
Created September 29, 2015 14:39
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save steveklabnik/1a3ec0ca676aaddf766e to your computer and use it in GitHub Desktop.
Save steveklabnik/1a3ec0ca676aaddf766e to your computer and use it in GitHub Desktop.
my summary of "using Rust with Ruby: a deep dive with Yehuda Katz"

My summary of https://www.youtube.com/watch?v=IqrwPVtSHZI

TL;DR:

Rails has a library, ActiveSupport, which adds methods to Ruby core classes. One of those methods is String#blank?, which returns a boolean (sometimes I miss this convention in Rust, the ?) if the whole string is whitespace or not. It looks like this: https://github.com/rails/rails/blob/b3eac823006eb6a346f88793aabef28a6d4f928c/activesupport/lib/active_support/core_ext/object/blank.rb#L99-L117

It's pretty slow. So Discourse (which you may know from {users,internals}.rust-lang.org) uses the fast_blank gem, which provides this method via a C implementation instead. It looks like this: https://github.com/SamSaffron/fast_blank/blob/master/ext/fast_blank/fast_blank.c

For fun, Yehuda tried to re-write fast_blank in Rust. Which looks like this:

extern crate libc;
mod buf; // a small buffer struct + impl, not shown
use buf::Buf;

#[no_mangle]
pub extern "C" fn tr_str_is_blank(b: Buf) -> bool {
    let s = b.as_slice().unwrap();

    s.chars().all(|c| c.is_whitespace())
}

Turns out, this implementation ends up being faster than that C one, while also being significantly more straightforward. This video is a two-hour dive into why that is.

@epinault
Copy link

do you have a summary on how you compile and integrate that with Ruby? Cause I could see myself writting Rust extension for Ruby :)

@searls
Copy link

searls commented Sep 29, 2015

Omg so great.

@ZhangHanDong
Copy link

Cool

@steveklabnik
Copy link
Author

@epinault sorry, GitHub doesn't notify me about gist comments :( https://doc.rust-lang.org/book/rust-inside-other-languages.html has a quick summary. You can also go the "Rust masquerading as a cext" route, which is https://github.com/steveklabnik/rust_example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment