Rustler - 使用 Rust 编写 Erlang NIF 库


MIT/Apache
跨平台
ErLang

软件简介

Rustler 实现了用安全的 Rust 代码编写 Erlang NIF 的库。 这意味着应该没有办法让BEAM(Erlang VM)崩溃。
该库提供了用于生成样板的工具,用于与BEAM交互,处理Erlang术语的编码和解码,并在它们展开到C之前捕获 Rust 错误。

Erlang 的 NIF(Native Implemented
Function)被用来扩展erlang的某些功能,一般用来实现一些erlang很难实现的,或者一些erlang实现效率不高的功能。

NIF使用C开发,效率和C接近,比纯erlang实现要高。NIF会编译成动态库,直接动态加载到erlang进程空间调用,也是erlang扩展新方法最高效的做法。调用NIF不用上下文的切换开销,但是也有代价,NIF的crash会导致整个Erlang进程crash。

该库提供了 Erlang 和 Elixir 的功能,但目前 Elixir 更受欢迎。

特性:

  • 安全 - The code you write in a Rust NIF should never be able to crash the BEAM.
  • 互操作 - Decoding and encoding rust values into Erlang terms is as easy as a function call.
  • 类型组合 - Making a Rust struct encodable and decodable to Erlang or Elixir can be done with a single attribute.
  • 资源对象 - Enables you to safely pass a reference to a Rust struct into Erlang code. The struct will be automatically dropped when it’s no longer referenced.

开始使用

最简单的入门是使用 rustler elixir library.

注意: 如果你以前用过 Rustler, 你需要先运行 mix archive.uninstall rustler_installer.ez
来移除之前生成的 NIF。

示例代码:

use rustler::{Encoder, Env, Error, Term};

mod atoms {
    rustler::rustler_atoms! {
        atom ok;
    }
}

rustler::rustler_export_nifs!(
    "Elixir.Math",
    [
        ("add", 2, add)
    ],
    None
);

fn add<'a>(env: Env<'a>, args: &[Term<'a>]) -> Result<Term<'a>, Error> {
    let a: i64 = args[0].decode()?;
    let b: i64 = args[1].decode()?;

    Ok((atoms::ok(), a + b).encode(env))
}