fixed_wide_vectors/fixed_wide_traits/src/narrow.rs

58 lines
1.2 KiB
Rust
Raw Normal View History

2024-08-23 21:50:23 +00:00
pub trait Narrow{
type Output;
fn narrow(self)->Self::Output;
}
#[derive(Debug)]
2024-08-27 00:04:41 +00:00
pub enum Error{
2024-08-23 21:50:23 +00:00
Overflow,
Underflow,
}
2024-08-27 00:04:41 +00:00
impl std::fmt::Display for Error{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for Error{}
2024-08-23 21:50:23 +00:00
pub trait TryNarrow{
type Output;
2024-08-27 00:04:41 +00:00
fn try_narrow(self)->Result<Self::Output,Error>;
2024-08-23 21:50:23 +00:00
}
#[cfg(test)]
mod tests {
use super::*;
2024-08-24 00:55:14 +00:00
//TODO: use num_traits to do a blanket implementation (self<T::MIN as U)
2024-08-23 21:50:23 +00:00
impl TryNarrow for i16{
type Output=i8;
2024-08-27 00:04:41 +00:00
fn try_narrow(self)->Result<Self::Output,Error>{
2024-08-23 21:50:23 +00:00
if self<i8::MIN as i16{
2024-08-27 00:04:41 +00:00
return Err(Error::Underflow);
2024-08-23 21:50:23 +00:00
}
if (i8::MAX as i16)<self{
2024-08-27 00:04:41 +00:00
return Err(Error::Overflow);
2024-08-23 21:50:23 +00:00
}
Ok(self as i8)
}
}
#[test]
fn test_i16_i8(){
2024-08-27 00:04:41 +00:00
assert!(matches!(257i16.try_narrow(),Err(Error::Overflow)));
2024-08-23 21:50:23 +00:00
assert!(matches!(64i16.try_narrow(),Ok(64i8)));
2024-08-27 00:04:41 +00:00
assert!(matches!((-257i16).try_narrow(),Err(Error::Underflow)));
2024-08-23 21:50:23 +00:00
}
impl Narrow for fixed::FixedI16<typenum::consts::U8>{
type Output=i8;
fn narrow(self)->Self::Output{
(self.to_bits()>>8) as i8
}
}
#[test]
fn test_fixed_i16_i8(){
let a=fixed::FixedI16::<typenum::consts::U8>::from(5)/2;
assert_eq!(a.narrow(),2);
}
2024-08-23 21:50:23 +00:00
}