Skip to content

Commit

Permalink
2.5.0: Add u64 -> Float conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
rpitasky committed Aug 24, 2024
1 parent 9ee0158 commit 0c9f3cc
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tifloats"
version = "2.4.0"
version = "2.5.0"
edition = "2021"
license = "MIT OR Apache-2.0"
homepage = "https://github.com/TI-Toolkit/tifloats_lib_rs"
Expand Down
9 changes: 9 additions & 0 deletions benches/float.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::hint::black_box;
use criterion::{criterion_group, criterion_main, Criterion};
use tifloats::{tifloat, Float};

Expand Down Expand Up @@ -37,6 +38,14 @@ fn criterion_benchmark(c: &mut Criterion) {
);
})
});

c.bench_function("float_from_num", |b| {
b.iter(|| {
let n = black_box(tifloats::Float::from(12345));

assert_eq!(n, tifloat!(0x12345000000000 * 10 ^ 4));
})
});
}

criterion_group!(benches, criterion_benchmark);
Expand Down
13 changes: 13 additions & 0 deletions src/float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,19 @@ impl Debug for Float {
}
}

impl From<u64> for Float {
fn from(value: u64) -> Self {
if value == 0 {
Float::new_unchecked(false, 0, 0)
} else {
let exp = value.ilog10() as i8;
let mantissa = Mantissa::from_dec_normalized(value);

Float::new_unchecked(false, exp, mantissa.0.bits())
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
14 changes: 13 additions & 1 deletion src/mantissa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const DEC_TO_BCD: [u64; 100] = [
];

#[derive(Copy, Clone, Debug)]
pub(super) struct Mantissa {
pub(crate) struct Mantissa {
data: u64,
}

Expand Down Expand Up @@ -115,6 +115,18 @@ impl Mantissa {

Mantissa { data: result }
}

pub fn from_dec_normalized(mut data: u64) -> (Self, u8) {
if data == 0 {
return (Mantissa::from_unchecked(data), 0)
}

let mut mantissa = Mantissa::from_dec(data);

let mut count = (mantissa.data.leading_zeros()/4) as u8 - 2;

(mantissa.shl(count), count)
}
}

impl Add for Mantissa {
Expand Down

0 comments on commit 0c9f3cc

Please sign in to comment.