1 unstable release
Uses new Rust 2024
new 0.1.0 | May 22, 2025 |
---|
#875 in Rust patterns
13KB
109 lines
A generic wrapper for non-negative floating point values.
Ensures that values are >= 0 and finite, providing safe construction methods and a convenient macro.
Supports any float type implementing num_traits::Float
.
Examples
use nonneg_float::{NonNegative, nonneg};
let zero = NonNegative::<f64>::zero();
let val = NonNegative::try_new(3.14).unwrap();
let macro_val = nonneg!(5.0f64).unwrap();
assert_eq!(zero.get(), 0.0);
assert_eq!(val.get(), 3.14);
assert_eq!(macro_val.get(), 5.0);
nonneg-float
A generic Rust crate providing a wrapper for non-negative floating-point numbers with a convenient macro for safe construction.
Features
- Generic over any floating-point type (
f32
,f64
, etc.) implementingnum_traits::Float
. - Ensures values are non-negative and finite.
- Macro
nonneg!
for easy, safe instantiation with optional defaulting to zero. - Panics at runtime if negative values are used with the macro.
Usage
Add this to your Cargo.toml
:
[dependencies]
nonneg-float = "0.1.0"
num-traits = "0.2"
Examples
fn main() {
let a = nonneg!(f64); // defaults to 0.0
let b = nonneg!(5.5f64); // from literal
let c = nonneg!(f32, 3.14); // explicit type and value
println!("{}, {}, {}", a.get(), b.get(), c.get());
}
Dependencies
~89–295KB