Last active
February 5, 2023 11:59
-
-
Save arifd/e8c3d83b6fad752f0da2cfb81097cc02 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const QUANT: f32 = u16::MAX as f32; | |
struct CPoint(u16); | |
impl From<f32> for CPoint { | |
fn from(f: f32) -> Self { | |
assert!((0.0..=1.0).contains(&f), "given float {f} out of bounds"); | |
CPoint((f * QUANT) as u16) | |
} | |
} | |
impl From<CPoint> for f32 { | |
fn from(p: CPoint) -> Self { | |
(p.0 as f32) / QUANT | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn it_works() { | |
#[rustfmt::skip] | |
let numbers = [ | |
0., | |
0.000000001, | |
0.00000001, | |
0.0000001, | |
0.000001, | |
0.00001, | |
0.0001, | |
0.001, | |
0.01, | |
0.1, | |
1., | |
]; | |
for n in numbers { | |
let p = CPoint::from(n); | |
let f = f32::from(p); | |
println!("in: {n}, out: {f}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment