Skip to content
Draft
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
6 changes: 5 additions & 1 deletion rustler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
//!
//! Language-specific helpers live in [`elixir`] and [`erlang`], while shared term types live
//! in [`types`].
//! The [`terms`] module provides transparent raw term wrappers, classified by [`FreeTerm`]
//! and [`BoundTerm`], alongside the existing higher-level APIs.
//!
//! # Getting Started
//! There is a [`:rustler`](https://hex.pm/packages/rustler) package on hex.pm that provides
Expand All @@ -38,13 +40,15 @@ pub mod types;

pub mod elixir;
pub mod erlang;
pub mod terms;

mod term;

pub use crate::traits::{Decoder, Encoder};
pub use crate::traits::{BoundTerm, Decoder, Encoder, FreeTerm};

pub use crate::erlang::ErlOption;
pub use crate::term::Term;
pub use crate::terms::TypedTerm;
pub use crate::types::{
Atom, Binary, ListIterator, LocalPid, MapIterator, NewBinary, OwnedBinary, Reference,
};
Expand Down
2 changes: 1 addition & 1 deletion rustler/src/term.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ impl<'a> Term<'a> {
///
/// # Unsafe
/// The caller must ensure that `env` is the environment that `inner` belongs to,
/// unless `inner` is an atom term.
/// unless `inner` is environment-independent, such as an atom or local pid.
#[inline]
pub unsafe fn new(env: Env<'a>, inner: ErlNifTerm) -> Self {
Term { term: inner, env }
Expand Down
49 changes: 49 additions & 0 deletions rustler/src/terms/atom.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//! Environment-independent atom terms.

use crate::sys::{c_char, c_uint, enif_get_atom, enif_get_atom_length, ErlNifCharEncoding};
use crate::{Env, Error, NifResult};

free_term!(Atom, crate::Term::is_atom);

impl Atom {
/// Get the atom's string representation using any environment.
pub fn to_string(self, env: Env<'_>) -> NifResult<String> {
#[cfg(feature = "nif_version_2_17")]
let encoding = ErlNifCharEncoding::ERL_NIF_UTF8;
#[cfg(not(feature = "nif_version_2_17"))]
let encoding = ErlNifCharEncoding::ERL_NIF_LATIN1;

let mut len = 0;
if unsafe { enif_get_atom_length(env.as_c_arg(), self.as_c_arg(), &mut len, encoding) } == 0
{
return Err(Error::BadArg);
}
let mut bytes: Vec<u8> = Vec::with_capacity(len as usize + 1);
unsafe {
let nbytes = enif_get_atom(
env.as_c_arg(),
self.as_c_arg(),
bytes.as_mut_ptr() as *mut c_char,
len + 1,
encoding,
);
assert!(nbytes as c_uint == len + 1);
bytes.set_len(len as usize);
}
#[cfg(feature = "nif_version_2_17")]
return Ok(unsafe { String::from_utf8_unchecked(bytes) });
#[cfg(not(feature = "nif_version_2_17"))]
{
let nonascii_count = bytes.iter().filter(|&&b| b >= 128).count();
if nonascii_count == 0 {
Ok(unsafe { String::from_utf8_unchecked(bytes) })
} else {
let mut out = String::with_capacity(bytes.len() + nonascii_count);
for b in bytes {
out.push(b as char);
}
Ok(out)
}
}
}
}
24 changes: 24 additions & 0 deletions rustler/src/terms/binary.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//! Byte-aligned binary terms, without an inspected byte slice.

use crate::sys::enif_inspect_binary;
use crate::{Encoder, Env, Error, NifResult};
use std::mem::MaybeUninit;

bound_term!(Binary, crate::Term::is_binary);

impl<'a> Binary<'a> {
/// Inspect the binary to access its byte slice through the high-level binary API.
pub fn into_binary<'b>(self, env: Env<'b>) -> NifResult<crate::Binary<'b>> {
let term = self.encode(env);
let mut binary = MaybeUninit::uninit();
if unsafe { enif_inspect_binary(env.as_c_arg(), term.as_c_arg(), binary.as_mut_ptr()) } == 0
{
return Err(Error::BadArg);
}
let binary = unsafe { binary.assume_init() };
unsafe {
let bytes = std::slice::from_raw_parts(binary.data, binary.size);
Ok(crate::Binary::from_term_and_slice(term, bytes))
}
}
}
10 changes: 10 additions & 0 deletions rustler/src/terms/bitstring.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//! Bitstring terms, including byte-aligned binaries.
//!
//! Requires NIF 2.15's term-type inspection API.

bound_term!(Bitstring, |term: crate::Term<'_>| {
matches!(
term.get_erl_type(),
crate::sys::ErlNifTermType::ERL_NIF_TERM_TYPE_BITSTRING
)
});
3 changes: 3 additions & 0 deletions rustler/src/terms/float.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
//! Floating-point terms.

bound_term!(Float, crate::Term::is_float);
3 changes: 3 additions & 0 deletions rustler/src/terms/fun.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
//! Function terms.

bound_term!(Fun, crate::Term::is_fun);
3 changes: 3 additions & 0 deletions rustler/src/terms/integer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
//! Integer terms of any size.

bound_term!(Integer, crate::Term::is_integer);
99 changes: 99 additions & 0 deletions rustler/src/terms/list.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
//! List terms, including empty and improper lists.

use crate::sys::{
enif_get_list_cell, enif_get_list_length, enif_make_list_cell, enif_make_list_from_array,
enif_make_reverse_list, ErlNifEnv, ErlNifTerm,
};
use crate::{BoundTerm, Encoder, Env, Error, ListIterator, NifResult, Term};
use std::mem::MaybeUninit;

bound_term!(List, |term: crate::Term<'_>| {
term.is_list() || term.is_empty_list()
});

impl<'a> List<'a> {
/// Construct an empty list.
pub fn new_empty(env: Env<'a>) -> Self {
unsafe { Self::from_raw(make_list(env.as_c_arg(), &[]), env) }
}

/// Iterate without checking the list's type again.
///
/// As with `ListIterator`, reaching an improper tail panics.
pub fn into_iterator<'b>(self, env: Env<'b>) -> ListIterator<'b> {
unsafe { ListIterator::new_unchecked(self.encode(env)) }
}

/// Get the length of a proper list. Improper lists return `BadArg`.
pub fn length(self, env: Env<'_>) -> NifResult<usize> {
let list = self.encode(env);
let mut length = 0;
let success = unsafe { enif_get_list_length(env.as_c_arg(), list.as_c_arg(), &mut length) };
if success != 1 {
return Err(Error::BadArg);
}
Ok(length as usize)
}

/// Get the head and tail, returning `BadArg` for an empty list.
///
/// The tail may be any term when this is an improper list.
pub fn get_cell<'b>(self, env: Env<'b>) -> NifResult<(Term<'b>, Term<'b>)> {
let list = self.encode(env);
unsafe {
get_list_cell(env.as_c_arg(), list.as_c_arg())
.map(|(head, tail)| (Term::new(env, head), Term::new(env, tail)))
.ok_or(Error::BadArg)
}
}

/// Reverse a proper list. Improper lists return `BadArg`.
pub fn reverse<'b>(self, env: Env<'b>) -> NifResult<List<'b>> {
let list = self.encode(env);
let mut result = MaybeUninit::uninit();
let success =
unsafe { enif_make_reverse_list(env.as_c_arg(), list.as_c_arg(), result.as_mut_ptr()) };
if success != 1 {
return Err(Error::BadArg);
}
Ok(unsafe { List::from_raw(result.assume_init(), env) })
}

/// Add a head while preserving this list as the tail.
pub fn prepend<'b>(self, env: Env<'b>, head: impl Encoder) -> List<'b> {
unsafe {
List::from_raw(
make_list_cell(
env.as_c_arg(),
head.encode(env).as_c_arg(),
self.encode(env).as_c_arg(),
),
env,
)
}
}
}

pub(crate) unsafe fn get_list_cell(
env: *mut ErlNifEnv,
list: ErlNifTerm,
) -> Option<(ErlNifTerm, ErlNifTerm)> {
let mut head = MaybeUninit::uninit();
let mut tail = MaybeUninit::uninit();
if enif_get_list_cell(env, list, head.as_mut_ptr(), tail.as_mut_ptr()) != 1 {
return None;
}
Some((head.assume_init(), tail.assume_init()))
}

pub(crate) unsafe fn make_list(env: *mut ErlNifEnv, arr: &[ErlNifTerm]) -> ErlNifTerm {
enif_make_list_from_array(env, arr.as_ptr(), arr.len() as u32)
}

pub(crate) unsafe fn make_list_cell(
env: *mut ErlNifEnv,
head: ErlNifTerm,
tail: ErlNifTerm,
) -> ErlNifTerm {
enif_make_list_cell(env, head, tail)
}
7 changes: 7 additions & 0 deletions rustler/src/terms/local_pid.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//! Environment-independent local process identifiers.
//!
//! Remote pids are represented by [`super::Pid`] instead.

free_term!(LocalPid, |term: crate::Term<'_>| {
term.decode::<crate::LocalPid>().is_ok()
});
14 changes: 14 additions & 0 deletions rustler/src/terms/local_port.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//! Environment-independent local port identifiers.
//!
//! External ports are represented by [`super::Port`] instead.

free_term!(LocalPort, |term: crate::Term<'_>| {
let mut port = std::mem::MaybeUninit::<crate::sys::ErlNifPort>::uninit();
unsafe {
crate::sys::enif_get_local_port(
term.get_env().as_c_arg(),
term.as_c_arg(),
port.as_mut_ptr(),
) != 0
}
});
Loading
Loading