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

Draft: Start implementing generic wrapper types #666

Draft
wants to merge 7 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Fix more tests, some renamings, move function to Env
  • Loading branch information
filmor committed Jan 12, 2025
commit b93691f6f1eb26e8733e35ba461048064efa1e92
4 changes: 2 additions & 2 deletions rustler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ mod wrapped_types;

pub use crate::term::Term;
pub use crate::types::{
Atom, Binary, Decoder, Encoder, ErlOption, LocalPid, NewBinary, OwnedBinary
Atom, Binary, Decoder, Encoder, ErlOption, LocalPid, NewBinary, OwnedBinary,
};

pub use crate::wrapped_types::{ListIterator, Reference, MapIterator, Map, Tuple};
pub use crate::wrapped_types::{ListIterator, Map, MapIterator, Reference, Tuple};

#[cfg(feature = "big_integer")]
pub use crate::types::BigInt;
Expand Down
4 changes: 2 additions & 2 deletions rustler/src/serde/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::io::Write;

use crate::serde::{atoms, error::Error, util};
use crate::wrapper::list::make_list;
use crate::{Encoder, Env, OwnedBinary, Term, Tuple};
use crate::{Encoder, Env, OwnedBinary, Term};
use serde::ser::{self, Serialize};

#[inline]
Expand Down Expand Up @@ -336,7 +336,7 @@ impl<'a> SequenceSerializer<'a> {

#[inline]
fn to_tuple(&self) -> Result<Term<'a>, Error> {
Ok(Tuple::make(self.ser.env, &self.items))
Ok(self.ser.env.make_tuple(&self.items).into())
}
}

Expand Down
4 changes: 2 additions & 2 deletions rustler/src/wrapped_types/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ where
}
}

impl<'a, T> Encoder for &'a [T]
impl<T> Encoder for &[T]
where
T: Encoder,
{
Expand Down Expand Up @@ -131,7 +131,7 @@ impl<'a> ListIterator<'a> {
Some(len as usize)
}

pub fn empty(&self) -> bool {
pub fn is_empty(&self) -> bool {
self.is_empty_list()
}

Expand Down
2 changes: 1 addition & 1 deletion rustler/src/wrapped_types/reference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::sys::enif_make_ref;

use super::wrapper;

wrapper!{
wrapper! {
struct Reference(TermType::Ref)
}

Expand Down
21 changes: 13 additions & 8 deletions rustler/src/wrapped_types/tuple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ wrapper!(
struct Tuple(TermType::Tuple)
);

pub unsafe fn get_tuple<'a>(term: Term<'a>) -> NifResult<&'a [ERL_NIF_TERM]> {
pub unsafe fn get_tuple(term: Term<'_>) -> NifResult<&[ERL_NIF_TERM]> {
let env = term.get_env();
let mut arity: c_int = 0;
let mut array_ptr = MaybeUninit::uninit();
Expand All @@ -27,11 +27,11 @@ pub unsafe fn get_tuple<'a>(term: Term<'a>) -> NifResult<&'a [ERL_NIF_TERM]> {
}

impl<'a> Tuple<'a> {
pub fn make(env: Env<'a>, terms: &[Term<'a>]) -> Term<'a> {
make_tuple(env, terms)
pub fn is_empty(&self) -> bool {
self.len() == 0
}

pub fn size(&self) -> usize {
pub fn len(&self) -> usize {
self.get_elements().len()
}

Expand All @@ -58,16 +58,21 @@ impl<'a> Tuple<'a> {
}
}

impl<'a> Env<'a> {
pub fn make_tuple(&self, terms: &[Term<'a>]) -> Tuple<'a> {
make_tuple(*self, terms)
}
}

/// Convert a vector of terms to an Erlang tuple. (To convert from a Rust tuple to an Erlang tuple,
/// use `Encoder` instead.)
pub fn make_tuple<'a>(env: Env<'a>, terms: &[Term]) -> Term<'a> {
pub fn make_tuple<'a>(env: Env<'a>, terms: &[Term]) -> Tuple<'a> {
let c_terms: Vec<ERL_NIF_TERM> = terms.iter().map(|term| term.as_c_arg()).collect();
unsafe {
let term =
enif_make_tuple_from_array(env.as_c_arg(), c_terms.as_ptr(), c_terms.len() as u32);
Term::new(env, term)
Term::new(env, term).try_into().unwrap()
}
// unsafe { Term::new(env, tuple::make_tuple(env.as_c_arg(), &c_terms)) }
}

/// Helper macro to emit tuple-like syntax. Wraps its arguments in parentheses, and adds a comma if
Expand All @@ -94,7 +99,7 @@ macro_rules! impl_nifencoder_nifdecoder_for_tuple {
{
fn encode<'a>(&self, env: Env<'a>) -> Term<'a> {
let arr = [ $( Encoder::encode(&self.$index, env) ),* ];
make_tuple(env, &arr)
make_tuple(env, &arr).into()
}
}

Expand Down
2 changes: 1 addition & 1 deletion rustler_codegen/src/encode_decode_templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ pub(crate) fn encoder(ctx: &Context, inner: TokenStream) -> TokenStream {
impl #impl_generics ::rustler::Encoder for #ident #ty_generics #where_clause {
#[allow(clippy::needless_borrow)]
fn encode<'__rustler__encode_lifetime>(&self, env: ::rustler::Env<'__rustler__encode_lifetime>) -> ::rustler::Term<'__rustler__encode_lifetime> {
#inner
#inner.into()
}
}
}
Expand Down
17 changes: 11 additions & 6 deletions rustler_codegen/src/record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ fn gen_decoder(ctx: &Context, fields: &[&Field], atoms_module_name: &Ident) -> T
quote! {
use #atoms_module_name::*;

let terms = match ::rustler::types::tuple::get_tuple(term) {
let terms = match ::rustler::Tuple::try_from(term) {
Err(_) => return Err(::rustler::Error::RaiseTerm(
Box::new(format!("Invalid Record structure for {}", #struct_name_str)))),
Ok(value) => value,
Expand All @@ -113,19 +113,24 @@ fn gen_decoder(ctx: &Context, fields: &[&Field], atoms_module_name: &Ident) -> T
return Err(::rustler::Error::RaiseAtom("invalid_record"));
}

let tag : ::rustler::types::atom::Atom = terms[0].decode()?;
let tag : ::rustler::types::atom::Atom = terms.get(0).unwrap().decode()?;

if tag != atom_tag() {
return Err(::rustler::Error::RaiseAtom("invalid_record"));
}

fn try_decode_index<'a, T>(terms: &[::rustler::Term<'a>], pos_in_struct: &str, index: usize) -> ::rustler::NifResult<T>
fn try_decode_index<'a, T>(terms: &::rustler::Tuple<'a>, pos_in_struct: &str, index: usize) -> ::rustler::NifResult<T>
where
T: rustler::Decoder<'a>,
{
match ::rustler::Decoder::decode(terms[index]) {
use ::rustler::{Decoder, Error};

let term = terms.get(index).ok_or_else(|| Error::BadArg)?;

match term.decode() {
Err(_) => Err(::rustler::Error::RaiseTerm(Box::new(
format!("Could not decode field {} on Record {}", pos_in_struct, #struct_name_str)))),
format!("Could not decode field {} on Record {}", pos_in_struct, #struct_name_str))
)),
Ok(value) => Ok(value)
}
}
Expand Down Expand Up @@ -166,7 +171,7 @@ fn gen_encoder(ctx: &Context, fields: &[&Field], atoms_module_name: &Ident) -> T

use ::rustler::Encoder;
let arr = #field_list_ast;
::rustler::types::tuple::make_tuple(env, &arr)
env.make_tuple(&arr)
},
)
}
Expand Down
12 changes: 6 additions & 6 deletions rustler_codegen/src/tagged_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,10 @@ fn gen_decoder(ctx: &Context, variants: &[&Variant], atoms_module_name: &Ident)

if let Ok(unit) = ::rustler::types::atom::Atom::from_term(term) {
#(#unit_decoders)*
} else if let Ok(tuple) = ::rustler::types::tuple::get_tuple(term) {
} else if let Ok(tuple) = ::rustler::Tuple::try_from(term) {
let name = tuple
.get(0)
.and_then(|&first| ::rustler::types::atom::Atom::from_term(first).ok())
.and_then(|first| ::rustler::types::atom::Atom::from_term(first).ok())
.ok_or(::rustler::Error::RaiseAtom("invalid_variant"))?;
#(#named_unnamed_decoders)*
}
Expand Down Expand Up @@ -208,7 +208,7 @@ fn gen_unnamed_decoder<'a>(
let i = i + 1;
let ty = &f.ty;
quote! {
<#ty as ::rustler::Decoder>::decode(tuple[#i]).map_err(|_| ::rustler::Error::RaiseTerm(
<#ty as ::rustler::Decoder>::decode(tuple.get(#i).unwrap()).map_err(|_| ::rustler::Error::RaiseTerm(
Box::new(format!("Could not decode field on position {}", #i))
))?
}
Expand Down Expand Up @@ -250,7 +250,7 @@ fn gen_named_decoder(
let enum_name_string = enum_name.to_string();

let assignment = quote_spanned! { field.span() =>
let #variable = try_decode_field(tuple[1], #atom_fun()).map_err(|_|{
let #variable = try_decode_field(tuple.get(1).unwrap(), #atom_fun()).map_err(|_|{
::rustler::Error::RaiseTerm(Box::new(format!(
"Could not decode field '{}' on Enum '{}'",
#ident_string, #enum_name_string
Expand All @@ -267,7 +267,7 @@ fn gen_named_decoder(

quote! {
if tuple.len() == 2 && name == #atom_fn() {
let len = tuple[1].map_size().map_err(|_| ::rustler::Error::RaiseTerm(Box::new(
let len = tuple.get(1).unwrap().map_size().map_err(|_| ::rustler::Error::RaiseTerm(Box::new(
"The second element of the tuple must be a map"
)))?;
#(#assignments)*
Expand Down Expand Up @@ -334,7 +334,7 @@ fn gen_named_encoder(
} => {
let map = ::rustler::Term::map_from_term_arrays(env, &[#(#keys),*], &[#(#values),*])
.expect("Failed to create map");
::rustler::types::tuple::make_tuple(env, &[::rustler::Encoder::encode(&#atom_fn(), env), map])
env.make_tuple(&[::rustler::Encoder::encode(&#atom_fn(), env), map]).into()
}
}
}
16 changes: 10 additions & 6 deletions rustler_codegen/src/tuple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,18 +84,22 @@ fn gen_decoder(ctx: &Context, fields: &[&Field]) -> TokenStream {
super::encode_decode_templates::decoder(
ctx,
quote! {
let terms = ::rustler::types::tuple::get_tuple(term)?;
let terms = ::rustler::Tuple::try_from(term)?;
if terms.len() != #field_num {
return Err(::rustler::Error::BadArg);
}

fn try_decode_index<'a, T>(terms: &[::rustler::Term<'a>], pos_in_struct: &str, index: usize) -> ::rustler::NifResult<T>
fn try_decode_index<'a, T>(terms: &::rustler::Tuple<'a>, pos_in_struct: &str, index: usize) -> ::rustler::NifResult<T>
where
T: rustler::Decoder<'a>,
{
match ::rustler::Decoder::decode(terms[index]) {
Err(_) => Err(::rustler::Error::RaiseTerm(Box::new(
format!("Could not decode field {} on {}", pos_in_struct, #struct_name_str)))),
use ::rustler::{Decoder, Error};

let term = terms.get(index).ok_or_else(|| Error::BadArg)?;
match term.decode() {
Err(_) => Err(Error::RaiseTerm(Box::new(
format!("Could not decode field {} on {}", pos_in_struct, #struct_name_str))
)),
Ok(value) => Ok(value)
}
}
Expand Down Expand Up @@ -131,7 +135,7 @@ fn gen_encoder(ctx: &Context, fields: &[&Field]) -> TokenStream {
quote! {
use ::rustler::Encoder;
let arr = #field_list_ast;
::rustler::types::tuple::make_tuple(env, &arr)
env.make_tuple(&arr)
},
)
}
6 changes: 3 additions & 3 deletions rustler_tests/native/rustler_serde_test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ mod types;

use crate::types::Animal;
use rustler::serde::{atoms, Deserializer, Error, Serializer};
use rustler::{types::tuple, Encoder, Env, NifResult, SerdeTerm, Term};
use rustler::{Encoder, Env, NifResult, SerdeTerm, Term};

init!("Elixir.SerdeRustlerTests");

Expand Down Expand Up @@ -56,10 +56,10 @@ where

fn ok_tuple<'a>(env: Env<'a>, term: Term<'a>) -> Term<'a> {
let ok_atom_term = atoms::ok().encode(env);
tuple::make_tuple(env, &[ok_atom_term, term])
env.make_tuple(&[ok_atom_term, term]).into()
}

fn error_tuple<'a>(env: Env<'a>, reason_term: Term<'a>) -> Term<'a> {
let err_atom_term = atoms::error().encode(env);
tuple::make_tuple(env, &[err_atom_term, reason_term])
env.make_tuple(&[err_atom_term, reason_term]).into()
}
3 changes: 1 addition & 2 deletions rustler_tests/native/rustler_test/src/test_env.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use rustler::env::{OwnedEnv, SavedTerm, SendError};
use rustler::types::atom;
use rustler::types::list::ListIterator;
use rustler::types::LocalPid;
use rustler::{Atom, Encoder, Env, NifResult, Reference, Term};
use rustler::{Atom, Encoder, Env, ListIterator, NifResult, Reference, Term};
use std::thread;

// Send a message to several PIDs.
Expand Down
16 changes: 7 additions & 9 deletions rustler_tests/native/rustler_test/src/test_map.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use rustler::types::map::MapIterator;
use rustler::types::tuple::make_tuple;
use rustler::{Encoder, Env, Error, ListIterator, NifResult, Term};
use rustler::{Encoder, Env, Error, ListIterator, MapIterator, NifResult, Term, Tuple};

#[rustler::nif]
pub fn sum_map_values(iter: MapIterator) -> NifResult<i64> {
Expand All @@ -11,31 +9,31 @@ pub fn sum_map_values(iter: MapIterator) -> NifResult<i64> {
}

#[rustler::nif]
pub fn map_entries<'a>(env: Env<'a>, iter: MapIterator<'a>) -> NifResult<Vec<Term<'a>>> {
pub fn map_entries<'a>(env: Env<'a>, iter: MapIterator<'a>) -> NifResult<Vec<Tuple<'a>>> {
let mut vec = vec![];
for (key, value) in iter {
let key_string = key.decode::<String>()?;
vec.push((key_string, value));
}

let erlang_pairs: Vec<Term> = vec
let erlang_pairs: Vec<_> = vec
.into_iter()
.map(|(key, value)| make_tuple(env, &[key.encode(env), value]))
.map(|(key, value)| env.make_tuple(&[key.encode(env), value]))
.collect();
Ok(erlang_pairs)
}

#[rustler::nif]
pub fn map_entries_reversed<'a>(env: Env<'a>, iter: MapIterator<'a>) -> NifResult<Vec<Term<'a>>> {
pub fn map_entries_reversed<'a>(env: Env<'a>, iter: MapIterator<'a>) -> NifResult<Vec<Tuple<'a>>> {
let mut vec = vec![];
for (key, value) in iter.rev() {
let key_string = key.decode::<String>()?;
vec.push((key_string, value));
}

let erlang_pairs: Vec<Term> = vec
let erlang_pairs: Vec<_> = vec
.into_iter()
.map(|(key, value)| make_tuple(env, &[key.encode(env), value]))
.map(|(key, value)| env.make_tuple(&[key.encode(env), value]))
.collect();
Ok(erlang_pairs)
}
Expand Down
Loading