| Crates.io | checked-float |
| lib.rs | checked-float |
| version | 0.1.5 |
| created_at | 2022-11-26 01:33:37.712548+00 |
| updated_at | 2023-11-23 15:54:43.284843+00 |
| description | A crate for making invariant-enforcing floating point wrappers |
| homepage | |
| repository | https://github.com/dragazo/checked-float |
| max_upload_size | |
| id | 723039 |
| size | 25,740 |
A no-std compatible crate which provides wrappers for imposing arbitrary invariants on floating point types.
The [FloatChecker] trait can be implemented on a type to create an invariant checker that can then
be used in the [CheckedFloat] type to create a wrapper that enforces the invariant for all operations.
The following is an example of how to use checked-float to create a floating point wrapper that forbids NaN.
# use checked_float::*;
#[derive(Debug)]
struct NanError;
struct NoNanChecker;
impl<T: Float> FloatChecker<T> for NoNanChecker {
type Error = NanError;
fn check(value: T) -> Result<T, Self::Error> {
if value.is_nan() { Err(NanError) } else { Ok(value) }
}
}
type NoNan64 = CheckedFloat<f64, NoNanChecker>; // our checked float wrapper
let y = NoNan64::new(0.0).unwrap(); // not nan, so we can unwrap
let x = NoNan64::new(2.0).unwrap(); // not nan, so we can unwrap
assert_eq!(x.powf(y).unwrap().get(), 1.0); // not nan, so we can unwrap
assert!(y.div(y).is_err()); // 0/0 is nan, so we get Err
no-std supportchecked-float supports building in no-std environments out of the box.
However, for future-proofing, you may like to explicitly opt out of default features in case
a dependency on std is ever added.
[dependencies]
checked-float = { version = "...", default-features = false }
| name | default | description |
|---|---|---|
serde |
off | Enables serialization of [CheckedFloat] |