Skip to content

Commit

Permalink
Fix f32 type conversion to be safe
Browse files Browse the repository at this point in the history
  • Loading branch information
Virviil committed Mar 6, 2021
1 parent 49a3c26 commit e210aa4
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion rustler/src/types/primitive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ impl_number_transcoder!(i8, i32, enif_make_int, enif_get_int);
impl_number_transcoder!(u8, u32, enif_make_uint, enif_get_uint);
impl_number_transcoder!(i16, i32, enif_make_int, enif_get_int);
impl_number_transcoder!(u16, u32, enif_make_uint, enif_get_uint);
impl_number_transcoder!(f32, f64, enif_make_double, enif_get_double);
impl_number_transcoder!(usize, u64, enif_make_uint64, enif_get_uint64);
impl_number_transcoder!(isize, i64, enif_make_int64, enif_get_int64);

Expand All @@ -60,3 +59,36 @@ impl<'a> Decoder<'a> for bool {
atom::decode_bool(term)
}
}


impl Encoder for f32 {
fn encode<'a>(&self, env: Env<'a>) -> Term<'a> {
#[allow(clippy::cast_lossless)]
unsafe {
Term::new(
env,
rustler_sys::enif_make_double(env.as_c_arg(), *self as f64),
)
}
}
}
impl<'a> Decoder<'a> for f32 {
fn decode(term: Term) -> NifResult<f32> {
#![allow(unused_unsafe)]
let mut res: f64 = Default::default();
if unsafe {
rustler_sys::enif_get_double(term.get_env().as_c_arg(), term.as_c_arg(), &mut res)
} == 0
{
return Err(Error::BadArg);
}
let res = res as f32;
// Values bigger then f32 are coerced as infinity
if res.is_finite() {
Ok(res)
}
else {
Err(Error::BadArg)
}
}
}

0 comments on commit e210aa4

Please sign in to comment.