Skip to content

Commit

Permalink
util/libm: add f32 libm support
Browse files Browse the repository at this point in the history
This is basically just vendoring the 'f' variants (e.g., 'truncf') from
the `libm` crate.
  • Loading branch information
BurntSushi committed Aug 9, 2024
1 parent 37fe7cb commit 7853ead
Showing 1 changed file with 125 additions and 0 deletions.
125 changes: 125 additions & 0 deletions src/util/libm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,135 @@ impl Float for f64 {
}
}

impl Float for f32 {
fn abs(self) -> f32 {
if self.is_sign_negative() {
-self
} else {
self
}
}

fn ceil(self) -> f32 {
let x = self;
let mut ui = x.to_bits();
let e = (((ui >> 23) & 0xff).wrapping_sub(0x7f)) as i32;

if e >= 23 {
return x;
}
if e >= 0 {
let m = 0x007fffff >> e;
if (ui & m) == 0 {
return x;
}
unsafe {
force_eval!(x + f32::from_bits(0x7b800000));
}
if ui >> 31 == 0 {
ui += m;
}
ui &= !m;
} else {
unsafe {
force_eval!(x + f32::from_bits(0x7b800000));
}
if ui >> 31 != 0 {
return -0.0;
} else if ui << 1 != 0 {
return 1.0;
}
}
f32::from_bits(ui)
}

fn floor(self) -> f32 {
let x = self;
let mut ui = x.to_bits();
let e = (((ui >> 23) as i32) & 0xff) - 0x7f;

if e >= 23 {
return x;
}
if e >= 0 {
let m: u32 = 0x007fffff >> e;
if (ui & m) == 0 {
return x;
}
unsafe {
force_eval!(x + f32::from_bits(0x7b800000));
}
if ui >> 31 != 0 {
ui += m;
}
ui &= !m;
} else {
unsafe {
force_eval!(x + f32::from_bits(0x7b800000));
}
if ui >> 31 == 0 {
ui = 0;
} else if ui << 1 != 0 {
return -1.0;
}
}
f32::from_bits(ui)
}

fn round(self) -> f32 {
(self + copysign32(0.5 - 0.25 * f32::EPSILON, self)).trunc()
}

fn signum(self) -> f32 {
if self.is_nan() {
Self::NAN
} else {
copysign32(1.0, self)
}
}

fn trunc(self) -> f32 {
let x = self;
let x1p120 = f32::from_bits(0x7b800000); // 0x1p120f === 2 ^ 120

let mut i: u32 = x.to_bits();
let mut e: i32 = (i >> 23 & 0xff) as i32 - 0x7f + 9;
let m: u32;

if e >= 23 + 9 {
return x;
}
if e < 9 {
e = 1;
}
m = -1i32 as u32 >> e;
if (i & m) == 0 {
return x;
}
unsafe {
force_eval!(x + x1p120);
}
i &= !m;
f32::from_bits(i)
}

fn fract(self) -> f32 {
self - self.trunc()
}
}

fn copysign64(x: f64, y: f64) -> f64 {
let mut ux = x.to_bits();
let uy = y.to_bits();
ux &= (!0) >> 1;
ux |= uy & (1 << 63);
f64::from_bits(ux)
}

fn copysign32(x: f32, y: f32) -> f32 {
let mut ux = x.to_bits();
let uy = y.to_bits();
ux &= 0x7fffffff;
ux |= uy & 0x80000000;
f32::from_bits(ux)
}

0 comments on commit 7853ead

Please sign in to comment.