Expand description
§unit-interval
Small constrained float types for values in the closed intervals [0, 1]
and [-1, 1].
This crate provides UnitInterval and SignedUnitInterval wrappers for
normalized floating-point values. They are useful for values such as opacity,
progress, blend factors, percentages represented as fractions, centered
offsets, joystick axes, and other quantities where the valid range is part of
the type.
Constructors reject out-of-range values and NaN; saturating constructors
clamp inputs into range. Operations that can leave the interval are available
in checked and saturating forms, while operations that are mathematically
closed over the interval return constrained values directly.
§Examples
use unit_intervals::UnitInterval;
let opacity = UnitInterval::new(0.8).unwrap();
let clamped = UnitInterval::saturating(1.2);
assert_eq!(opacity.get(), 0.8);
assert_eq!(clamped, UnitInterval::ONE);use unit_intervals::{SignedUnitInterval, UnitInterval};
let axis = SignedUnitInterval::new(-0.5).unwrap();
let scale = UnitInterval::new(0.25).unwrap();
assert_eq!((axis * scale).get(), -0.125);
assert_eq!(axis.saturating_add(scale).get(), -0.25);
assert_eq!(
axis.checked_add(SignedUnitInterval::<f32>::ONE),
Some(SignedUnitInterval::<f32>::HALF),
);§Crate features
assertions: enables internal invariant assertions in non-test builds. Tests always enable these assertions.arbitrary: enablesarbitrary::Arbitrarysupport for generating valid fuzz inputs.bytemuck: enablesbytemuck::Zeroable,bytemuck::NoUninit, andbytemuck::CheckedBitPatternsupport. These wrappers do not implementbytemuck::Podbecause not every backing float bit pattern satisfies their interval invariants.num-traits: enables conversion and bounds traits fromnum_traits.std: enables APIs that require the Rust standard library. The crate is otherwiseno_std.rand_distr: enablesrand_distrdistribution support forUnitIntervalandSignedUnitInterval.rkyv: enables zero-copy serialization and checked deserialization through the inner floating-point value.serde: enables transparent serialization and checked deserialization through the inner floating-point value.unsafe: allows unsafe code and enables unchecked constructors and operations such asUnitInterval::new_uncheckedandSignedUnitInterval::new_unchecked. These APIs assume the caller has already proven that the produced value is inside the relevant interval and is notNaN.
Modules§
- random
rand_distr - Random sampling support through
rand_distr.
Structs§
- Signed
Unit Interval - A floating-point value constrained to the closed signed unit interval
[-1, 1]. - Signed
Unit Interval Error - Error returned when converting an out-of-range value into a
SignedUnitInterval. - Unit
Interval - A floating-point value constrained to the closed unit interval
[0, 1]. - Unit
Interval Error - Error returned when converting an out-of-range value into a
UnitInterval.
Traits§
- Unit
Interval Float - Floating-point support required by
UnitInterval.