Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for tuples in nif macro #527

Merged
merged 2 commits into from
Mar 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions rustler_codegen/src/nif.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,16 @@ fn extract_inputs(inputs: Punctuated<syn::FnArg, Comma>) -> TokenStream {
}
}
}
syn::Type::Tuple(typ) => {
let decoder = quote! {
let #name: #typ = match args[#idx].decode() {
Ok(value) => value,
Err(err) => return Err(err)
};
};

tokens.extend(decoder);
}
other => {
panic!("unsupported input given: {:?}", other);
}
Expand Down
11 changes: 8 additions & 3 deletions rustler_tests/lib/rustler_test.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ defmodule RustlerTest do
otp_app: :rustler_test,
crate: :rustler_test

defp err do
throw(NifNotLoadedError)
end
defp err, do: :erlang.nif_error(:nif_not_loaded)

def add_u32(_, _), do: err()
def add_i32(_, _), do: err()
Expand Down Expand Up @@ -95,4 +93,11 @@ defmodule RustlerTest do
def term_with_tuple_error(), do: err()

def nif_attrs_can_rename(), do: err()

def add_from_tuple(_tuple), do: err()
def add_one_to_tuple(_tuple), do: err()
def join_tuple_elements(_tuple), do: err()
def maybe_add_one_to_tuple(_tuple), do: err()
def add_i32_from_tuple(_tuple), do: err()
def greeting_person_from_tuple(_tuple), do: err()
end
7 changes: 7 additions & 0 deletions rustler_tests/native/rustler_test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod test_range;
mod test_resource;
mod test_term;
mod test_thread;
mod test_tuple;

rustler::init!(
"Elixir.RustlerTest",
Expand Down Expand Up @@ -85,6 +86,12 @@ rustler::init!(
test_error::raise_term_with_atom_error,
test_error::term_with_tuple_error,
test_nif_attrs::can_rename,
test_tuple::add_from_tuple,
test_tuple::add_one_to_tuple,
test_tuple::join_tuple_elements,
test_tuple::maybe_add_one_to_tuple,
test_tuple::add_i32_from_tuple,
test_tuple::greeting_person_from_tuple,
test_codegen::reserved_keywords::reserved_keywords_type_echo
],
load = load
Expand Down
41 changes: 41 additions & 0 deletions rustler_tests/native/rustler_test/src/test_tuple.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#[rustler::nif]
pub fn add_from_tuple(items: (i64, i64)) -> i64 {
items.0 + items.1
}

#[rustler::nif]
pub fn add_one_to_tuple(items: (usize, usize)) -> (usize, usize) {
(items.0 + 1, items.1 + 1)
}

#[rustler::nif]
pub fn join_tuple_elements(items: (&str, &str)) -> String {
format!("{}{}", items.0, items.1)
}

#[rustler::nif]
pub fn maybe_add_one_to_tuple(items: Option<(usize, usize)>) -> Option<(usize, usize)> {
items.map(|tuple| (tuple.0 + 1, tuple.1 + 1))
}

#[rustler::nif]
pub fn add_i32_from_tuple(items: (i32, i32)) -> Result<i32, String> {
match items.0.checked_add(items.1) {
Some(number) => Ok(number),
None => Err(format!(
"Cannot sum {} + {} because the result is bigger than an i32 number.",
items.0, items.1
)),
}
}

#[rustler::nif]
pub fn greeting_person_from_tuple(age_and_name: (u8, &str)) -> String {
let (age, name) = age_and_name;

if age > 18 {
format!("Hello, {name}! You are allowed in the bar area.")
} else {
format!("Hi, {name}! I'm sorry, but you are not allowed in the bar area.")
}
}
45 changes: 45 additions & 0 deletions rustler_tests/test/tuple_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
defmodule RustlerTest.TupleTest do
use ExUnit.Case, async: true

test "sum from two integer in a tuple" do
assert RustlerTest.add_from_tuple({1, 2}) == 3
assert RustlerTest.add_from_tuple({15, 4}) == 19
assert RustlerTest.add_from_tuple({-56, 7}) == -49
end

test "add one on each element of a tuple" do
assert RustlerTest.add_one_to_tuple({1, 2}) == {2, 3}
assert RustlerTest.add_one_to_tuple({15, 4}) == {16, 5}
end

test "join two strings from tuple" do
assert RustlerTest.join_tuple_elements({"rus", "tler"}) == "rustler"
assert RustlerTest.join_tuple_elements({"eli", "xir"}) == "elixir"
end

test "add one to elements of tuple if present" do
assert RustlerTest.maybe_add_one_to_tuple({1, 2}) == {2, 3}
assert RustlerTest.maybe_add_one_to_tuple({41, 19}) == {42, 20}

assert RustlerTest.maybe_add_one_to_tuple(nil) == nil
end

test "sum from two i32 numbers and return result" do
assert RustlerTest.add_i32_from_tuple({9, 1}) == {:ok, 10}
assert RustlerTest.add_i32_from_tuple({2_147_483_646, 1}) == {:ok, 2_147_483_647}

assert RustlerTest.add_i32_from_tuple({1, 2_147_483_647}) ==
{:error,
"Cannot sum 1 + 2147483647 because the result is bigger than an i32 number."}
end

test "mix two types in a tuple" do
assert RustlerTest.greeting_person_from_tuple({22, "Alice"}) ==
"Hello, Alice! You are allowed in the bar area."

assert RustlerTest.greeting_person_from_tuple({16, "Bob"}) ==
"Hi, Bob! I'm sorry, but you are not allowed in the bar area."

assert catch_error(RustlerTest.greeting_person_from_tuple("Godzilla")) == :badarg
end
end