2 unstable releases
0.3.0  May 24, 2024 

0.2.0  May 23, 2024 
0.1.0 

#488 in Embedded development
24 downloads per month
30KB
451 lines
This is a Rust crate providing fixedpoint arithmetic with statically verified overflow safety and bit shift correctness, and zero runtime overhead.
Please note: this crate requires nightly Rust, for the generic_const_exprs
feature. In addition, this is an "alpha" release with incomplete documentation
and incomplete test coverage. The fixed
package provides a widelyused, productionready option for fixedpoint
arithmetic  although it does not provide compiletime overflow safety, nor the
guarantee of zero runtime overhead.
Fixedpoint arithmetic represents fractional values as integers with an implicit
bit shift. For example, the decimal number 2.375 (in base 2: 10.011) could
be represented in fixedpoint as the integer 0b10011
(decimal 19) with an
implicit bit shift of 3. It is typically the programmer's responsibility to
keep track of all the bit shifts used in a program, ensure they are consistent
with each other, and avoid any overflows during arithmetic operations.
In contrast, floatingpoint numbers automatically adjust the "bit shift" (i.e. the exponent) to provide the largest possible resolution which will not overflow. They are easy to use, and they do the right thing most of the time. However, they can cause subtle rounding bugs which are famously difficult to identify and prevent. In the immortal words of Professor Gerald Sussman, "Nothing brings fear to my heart more than a floatingpoint number."
This crate uses the Rust type system to provide fixedpoint numbers with compiletime bit shift checking and overflow protection. Each fixedpoint type has two const generic parameters, one describing the bit shift and one describing the maximum number of bits which could be nonzero. Each arithmetic operation is implemented with an output type which correctly reflects the bits and shift of the result. For example, the result of multiplying a 10bit number (shifted by 2) and a 12bit number (shifted by 3) is a 22bit number (shifted by 5).
The fp::Num
trait represents any fixedpoint number stored as an integer,
and the generic structs fp::X??<const BITS: u32, const SHIFT: i32>
implement
the fp::Num
trait for each width and shift of fixedpoint number which could
be represented by the integer type x??
. Arithmetic operations on the
fixedpoint types are guaranteed to provide correctness and overflow safety with
zero runtime overhead.