Use Rust’s std::convert::TryFrom for a type conversion that may fail. Unlike a From conversion, a TryFrom conversion reports whether it succeeded or produced an error. Prefer From when the conversion is mathematically equivalent. section 5.5 section 5.8
A fixed-point conversion decision
A conversion from f64 to the fixed-point Q7 type uses From and clamps values outside its range: 10.0 becomes the same Q7 value as 1.0. If losing that information is unacceptable, treat out-of-range input as a possible failure and consider TryFrom instead. The Q7 example does not implement TryFrom. section 5.5
Listing 5.12 Converting from f64 to Q7
impl From<f64> for Q7 {
fn from (n: f64) -> Self {
// assert!(n >= -1.0);
// assert!(n <= 1.0);
if n >= 1.0 { #1
Q7(127)
} else if n <= -1.0 { #1
Q7(-128)
} else {
Q7((n * 128.0) as i8)
}
}
}
impl From<Q7> for f64 {
fn from(n: Q7) -> f64 {
(n.0 as f64) * 2_f64.powf(-7.0) #2
}
}
The From<f64> implementation shows where out-of-range inputs are clamped rather than rejected. section 5.5


