unit-intervals
Small constrained float types for values in the closed intervals [0, 1] and
[-1, 1].
unit-interval provides UnitInterval and SignedUnitInterval wrappers for
normalized f32 and f64 values. Constructors reject out-of-range values and
NaN, while saturating constructors clamp inputs into the nearest valid value.
Operations that may leave the interval are available in checked and saturating
forms; operations that are closed over the interval return constrained values
directly.
Rationale
Many domains use floats whose valid range is smaller than the full floating-point space:
- Probabilities and confidence scores live in
[0, 1]. - Interpolation factors, progress values, weights, blend factors, and opacity
often live in
[0, 1]. - RGBA color channels are commonly represented as normalized channel values in
[0, 1]. - Sine and cosine results, joystick axes, audio pan, centered offsets, and
balance controls live in
[-1, 1].
Encoding those ranges in the type system keeps checks close to input boundaries
and lets later code state its requirements directly. A function that accepts
UnitInterval does not need to rediscover whether 1.2, -0.1, or NaN can
arrive.
Examples
use UnitInterval;
let probability = new.unwrap;
let clamped = saturating;
assert_eq!;
assert_eq!;
assert_eq!;
use ;
let axis = new.unwrap;
let weight = new.unwrap;
assert_eq!;
assert_eq!;
use UnitInterval;
assert_eq!;
Feature Flags
stdis enabled by default and provides APIs that require the Rust standard library. Disable default features forno_stduse.arbitraryenablesArbitrarysupport for generating valid fuzz inputs.bytemuckenablesZeroable,NoUninit, andCheckedBitPatternsupport. The interval wrappers intentionally do not implementPod, because not every backing float bit pattern is valid for these constrained types.num-traitsenables conversion and bounds traits fromnum-traits.serdeenables transparent serialization and checked deserialization through the inner floating-point value.rkyvenables zero-copy serialization and checked deserialization through the inner floating-point value.assertionsenables internal invariant assertions in non-test builds.unsafeenables unchecked constructors and operations such asUnitInterval::new_uncheckedandSignedUnitInterval::new_unchecked.
Unsafe code is forbidden unless the unsafe or bytemuck feature is explicitly
enabled. The unchecked APIs are behind the unsafe feature gate and require the
caller to prove the value is inside the relevant interval and is not NaN; the
bytemuck feature only enables unsafe marker-trait implementations.
Development
This repository uses the Taskfile as the local automation entry point: