Skip to content
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
19 changes: 1 addition & 18 deletions rustler/src/codegen_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@ pub use inventory;
pub use crate::resource::Registration as ResourceRegistration;

// Names used by the `rustler::init!` macro or other generated code.
pub use crate::wrapper::{
c_char, c_int, c_uint, c_void, get_nif_resource_type_init_size, NIF_MAJOR_VERSION,
NIF_MINOR_VERSION,
};
pub use crate::sys::{c_char, c_int, c_uint, c_void};

pub use crate::sys::{
internal_set_symbols, internal_write_symbols, DynNifCallbacks, ErlNifEntry, ErlNifEnv,
Expand Down Expand Up @@ -141,17 +138,3 @@ where
}
}
}

pub const fn min_erts() -> &'static [u8] {
if cfg!(feature = "nif_version_2_18") {
b"OTP-29.0\0"
} else if cfg!(feature = "nif_version_2_17") {
b"OTP-26.0\0"
} else if cfg!(feature = "nif_version_2_16") {
b"OTP-24.0\0"
} else if cfg!(feature = "nif_version_2_15") {
b"OTP-22.0\0"
} else {
b"OTP-21.0\0"
}
}
27 changes: 13 additions & 14 deletions rustler/src/dynamic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::ffi::c_double;
#[cfg(feature = "nif_version_2_15")]
use crate::sys::ErlNifTermType;

use crate::wrapper::check;
use crate::Term;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -77,9 +76,9 @@ pub fn get_type(term: Term) -> TermType {
}

macro_rules! impl_check {
($check_fun:ident) => {
($check_fun:ident, $sys_fun:ident) => {
pub fn $check_fun(self) -> bool {
unsafe { check::$check_fun(self.get_env().as_c_arg(), self.as_c_arg()) }
unsafe { crate::sys::$sys_fun(self.get_env().as_c_arg(), self.as_c_arg()) == 1 }
}
};
}
Expand All @@ -93,17 +92,17 @@ impl Term<'_> {
get_type(self)
}

impl_check!(is_atom);
impl_check!(is_binary);
impl_check!(is_empty_list);
impl_check!(is_fun);
impl_check!(is_list);
impl_check!(is_map);
impl_check!(is_number);
impl_check!(is_pid);
impl_check!(is_port);
impl_check!(is_ref);
impl_check!(is_tuple);
impl_check!(is_atom, enif_is_atom);
impl_check!(is_binary, enif_is_binary);
impl_check!(is_empty_list, enif_is_empty_list);
impl_check!(is_fun, enif_is_fun);
impl_check!(is_list, enif_is_list);
impl_check!(is_map, enif_is_map);
impl_check!(is_number, enif_is_number);
impl_check!(is_pid, enif_is_pid);
impl_check!(is_port, enif_is_port);
impl_check!(is_ref, enif_is_ref);
impl_check!(is_tuple, enif_is_tuple);

pub fn is_float(self) -> bool {
let mut val: c_double = 0.0;
Expand Down
26 changes: 24 additions & 2 deletions rustler/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,19 +173,41 @@ impl<'a> Env<'a> {
/// [External Term Format](http://erlang.org/doc/apps/erts/erl_ext_dist.html).
pub fn binary_to_term(self, data: &[u8]) -> Option<(Term<'a>, usize)> {
unsafe {
crate::wrapper::env::binary_to_term(self.as_c_arg(), data, true)
binary_to_term(self.as_c_arg(), data, true)
.map(|(term, size)| (Term::new(self, term), size))
}
}

/// Like `binary_to_term`, but can only be called on valid
/// and trusted data.
pub unsafe fn binary_to_term_trusted(self, data: &[u8]) -> Option<(Term<'a>, usize)> {
crate::wrapper::env::binary_to_term(self.as_c_arg(), data, false)
binary_to_term(self.as_c_arg(), data, false)
.map(|(term, size)| (Term::new(self, term), size))
}
}

unsafe fn binary_to_term(
env: *mut ErlNifEnv,
data: &[u8],
safe: bool,
) -> Option<(ErlNifTerm, usize)> {
let opts = if safe {
crate::sys::ERL_NIF_BIN2TERM_SAFE
} else {
0
};

let mut result = std::mem::MaybeUninit::uninit();
let read_count =
crate::sys::enif_binary_to_term(env, data.as_ptr(), data.len(), result.as_mut_ptr(), opts);

if read_count == 0 {
return None;
}

Some((result.assume_init(), read_count))
}

/// A process-independent environment, a place where Erlang terms can be created outside of a NIF
/// call.
///
Expand Down
3 changes: 0 additions & 3 deletions rustler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@
//! For more information about this, see [the documentation for
//! rustler](https://hexdocs.pm/rustler).

#[doc(hidden)]
pub mod wrapper;

#[doc(hidden)]
pub mod codegen_runtime;

Expand Down
8 changes: 4 additions & 4 deletions rustler/src/schedule.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use crate::sys::enif_consume_timeslice;
use crate::wrapper::ErlNifTaskFlags;
use crate::Env;

#[derive(Clone, Copy, Debug)]
pub enum SchedulerFlags {
Normal = ErlNifTaskFlags::ERL_NIF_NORMAL_JOB as isize,
DirtyCpu = ErlNifTaskFlags::ERL_NIF_DIRTY_JOB_CPU_BOUND as isize,
DirtyIo = ErlNifTaskFlags::ERL_NIF_DIRTY_JOB_IO_BOUND as isize,
Normal = crate::sys::ERL_NIF_NORMAL_JOB as isize,
DirtyCpu = crate::sys::ERL_NIF_DIRTY_JOB_CPU_BOUND as isize,
DirtyIo = crate::sys::ERL_NIF_DIRTY_JOB_IO_BOUND as isize,
}

pub fn consume_timeslice(env: Env, percent: i32) -> bool {
Expand Down
2 changes: 1 addition & 1 deletion rustler/src/serde/ser.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::io::Write;

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

Expand Down
77 changes: 53 additions & 24 deletions rustler/src/sys/types.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![allow(clippy::missing_safety_doc)]
#![allow(clippy::upper_case_acronyms)]

pub use std::ffi::{c_char, c_double, c_int, c_long, c_uchar, c_uint, c_ulong, c_void};
pub use std::ffi::{c_char, c_double, c_int, c_long, c_uchar, c_uint, c_ulong, c_void, CStr};

use std::os;

Expand Down Expand Up @@ -49,6 +49,21 @@ pub struct ErlNifFunc {
pub flags: c_uint,
}

type LoadFun = unsafe extern "C" fn(
env: *mut ErlNifEnv,
priv_data: *mut *mut c_void,
load_info: ErlNifTerm,
) -> c_int;

type UpgradeFun = unsafe extern "C" fn(
env: *mut ErlNifEnv,
priv_data: *mut *mut c_void,
old_priv_data: *mut *mut c_void,
load_info: ErlNifTerm,
) -> c_int;

type UnloadFun = unsafe extern "C" fn(env: *mut ErlNifEnv, priv_data: *mut c_void) -> ();

// #[allow(missing_copy_implementations)]
#[doc(hidden)]
#[derive(Debug)]
Expand All @@ -60,35 +75,48 @@ pub struct ErlNifEntry {
pub name: *const c_char,
pub num_of_funcs: c_int,
pub funcs: *const ErlNifFunc,
pub load: Option<
unsafe extern "C" fn(
env: *mut ErlNifEnv,
priv_data: *mut *mut c_void,
load_info: ErlNifTerm,
) -> c_int,
>,
pub reload: Option<
unsafe extern "C" fn(
env: *mut ErlNifEnv,
priv_data: *mut *mut c_void,
load_info: ErlNifTerm,
) -> c_int,
>,
pub upgrade: Option<
unsafe extern "C" fn(
env: *mut ErlNifEnv,
priv_data: *mut *mut c_void,
old_priv_data: *mut *mut c_void,
load_info: ErlNifTerm,
) -> c_int,
>,
pub unload: Option<unsafe extern "C" fn(env: *mut ErlNifEnv, priv_data: *mut c_void) -> ()>,
pub load: Option<LoadFun>,
pub reload: Option<LoadFun>,
pub upgrade: Option<UpgradeFun>,
pub unload: Option<UnloadFun>,
pub vm_variant: *const c_char,
pub options: c_uint, // added in 2.7
pub sizeof_ErlNifResourceTypeInit: usize, // added in 2.12
pub min_erts: *const c_char, // added in 2.14
}

impl ErlNifEntry {
pub const fn new(name: &CStr, nif_funcs: &[ErlNifFunc], load: LoadFun) -> Self {
let min_erts = if cfg!(feature = "nif_version_2_18") {
c"OTP-29.0"
} else if cfg!(feature = "nif_version_2_17") {
c"OTP-26.0"
} else if cfg!(feature = "nif_version_2_16") {
c"OTP-24.0"
} else if cfg!(feature = "nif_version_2_15") {
c"OTP-22.0"
} else {
c"OTP-21.0"
};

Self {
major: super::NIF_MAJOR_VERSION,
minor: super::NIF_MINOR_VERSION,
name: name.as_ptr(),
num_of_funcs: nif_funcs.len() as c_int,
funcs: nif_funcs.as_ptr(),
load: Some(load),
reload: None,
upgrade: None,
unload: None,
vm_variant: c"beam.vanilla".as_ptr(),
options: 0,
sizeof_ErlNifResourceTypeInit: std::mem::size_of::<ErlNifResourceTypeInit>(),
min_erts: min_erts.as_ptr(),
}
}
}

pub const ERL_NIF_DIRTY_NIF_OPTION: c_uint = 1;

/// See [ErlNifBinary](http://www.erlang.org/doc/man/erl_nif.html#ErlNifBinary) in the Erlang docs.
Expand Down Expand Up @@ -234,6 +262,7 @@ pub struct ErlNifSysInfo {
// }

pub type ErlNifDirtyTaskFlags = c_uint;
pub const ERL_NIF_NORMAL_JOB: ErlNifDirtyTaskFlags = 0;
pub const ERL_NIF_DIRTY_JOB_CPU_BOUND: ErlNifDirtyTaskFlags = 1;
pub const ERL_NIF_DIRTY_JOB_IO_BOUND: ErlNifDirtyTaskFlags = 2;

Expand Down
51 changes: 48 additions & 3 deletions rustler/src/term.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::sys::*;
use crate::types::binary::OwnedBinary;
use crate::wrapper::env::term_to_binary;
use crate::{Binary, Decoder, Env, NifResult};
use std::cmp::Ordering;
use std::fmt::{self, Debug};
Expand All @@ -16,9 +15,50 @@ pub struct Term<'a> {
env: Env<'a>,
}

pub(crate) fn fmt(term: ErlNifTerm, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
const SIZE: usize = 1024;
let mut bytes: Vec<u8> = Vec::with_capacity(SIZE);

let mut n = 0;
for _ in 0..10 {
let i = unsafe {
enif_snprintf!(
bytes.as_mut_ptr() as *mut c_char,
bytes.capacity(),
b"%T\x00" as *const u8 as *const c_char,
term
)
};
if i < 0 {
// Do not propagate an error, because string formatting is
// supposed to be infallible.
break;
}

n = i as usize;
if n >= bytes.capacity() {
// Bizarrely, enif_snprintf consistently underestimates the
// amount of memory it will need to write long lists. To try to
// avoid going around the loop again, double the estimate.
bytes.reserve_exact(2 * n + 1);

// Ensure that the `set_len` call below does not expose
// uninitialized bytes if we give up after 10 attempts.
n = 0;
} else {
break;
}
}

unsafe {
bytes.set_len(n);
}
f.write_str(&String::from_utf8_lossy(&bytes))
}

impl Debug for Term<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
crate::wrapper::term::fmt(self.as_c_arg(), f)
fmt(self.as_c_arg(), f)
}
}

Expand Down Expand Up @@ -94,7 +134,12 @@ impl<'a> Term<'a> {

#[inline]
pub fn to_binary(self) -> OwnedBinary {
let raw_binary = unsafe { term_to_binary(self.env.as_c_arg(), self.as_c_arg()) }.unwrap();
let mut binary = std::mem::MaybeUninit::uninit();
let success = unsafe {
enif_term_to_binary(self.env.as_c_arg(), self.as_c_arg(), binary.as_mut_ptr())
};
assert_ne!(success, 0, "term_to_binary failed");
let raw_binary = unsafe { binary.assume_init() };
unsafe { OwnedBinary::from_raw(raw_binary) }
}

Expand Down
Loading
Loading