narrow concept

This commit is contained in:
Quaternions 2024-08-23 14:50:23 -07:00
parent 5f8104d531
commit 47f6e75de9
3 changed files with 38 additions and 23 deletions

View File

@ -1,2 +1,3 @@
pub mod wide;
pub mod types;
pub mod narrow;

37
fixed_wide/src/narrow.rs Normal file
View File

@ -0,0 +1,37 @@
pub trait Narrow{
type Output;
fn narrow(self)->Self::Output;
}
#[derive(Debug)]
pub enum NarrowError{
Overflow,
Underflow,
}
pub trait TryNarrow{
type Output;
fn try_narrow(self)->Result<Self::Output,NarrowError>;
}
#[cfg(test)]
mod tests {
use super::*;
impl TryNarrow for i16{
type Output=i8;
fn try_narrow(self)->Result<Self::Output,NarrowError>{
if self<i8::MIN as i16{
return Err(NarrowError::Underflow);
}
if (i8::MAX as i16)<self{
return Err(NarrowError::Overflow);
}
Ok(self as i8)
}
}
#[test]
fn test_i16_i8(){
assert!(matches!(257i16.try_narrow(),Err(NarrowError::Overflow)));
assert!(matches!(64i16.try_narrow(),Ok(64i8)));
assert!(matches!((-257i16).try_narrow(),Err(NarrowError::Underflow)));
}
}

View File

@ -61,26 +61,3 @@ impl<A,B> WideMul<FixedI256<B>> for FixedI256<A>
}
}
}
pub enum Narrower<T>{
Fits(T),
Max,
Min,
}
fn tat(){
let a:i8=match 257i64.try_into() {
Ok(it) => it,
Err(err) => panic!(),
};
}
//i16 -> i8
// 257i16.try_narrow::<i8>() -> Narrower::Max
// 128i16.try_narrow::<i8>() -> Narrower::Fits(128i8)
// -257i16.try_narrow::<i8>() -> Narrower::Min
pub trait TryNarrow<Rhs=Self>{
type Output;
fn wide_mul(self,rhs:Rhs)->Self::Output;
}