Ratio Parity trait

This commit is contained in:
Quaternions 2024-09-23 11:20:11 -07:00
parent ba357ee99b
commit 102ea607ab
2 changed files with 57 additions and 6 deletions

View File

@ -408,7 +408,12 @@ impl<const LHS_N:usize,const LHS_F:usize,const RHS_N:usize,const RHS_F:usize> co
ratio_ops::ratio::Ratio::new(self,other) ratio_ops::ratio::Ratio::new(self,other)
} }
} }
#[cfg(feature="deferred-division")]
impl<const N:usize,const F:usize> ratio_ops::ratio::Parity for Fixed<N,F>{
fn parity(&self)->bool{
self.is_negative()
}
}
macro_rules! impl_shift_operator { macro_rules! impl_shift_operator {
( $struct: ident, $trait: ident, $method: ident, $output: ty ) => { ( $struct: ident, $trait: ident, $method: ident, $output: ty ) => {
impl<const N:usize,const F:usize> core::ops::$trait<u32> for $struct<N,F>{ impl<const N:usize,const F:usize> core::ops::$trait<u32> for $struct<N,F>{

View File

@ -68,17 +68,63 @@ impl_ratio_method!(Add,add,add_ratio);
impl_ratio_method!(Sub,sub,sub_ratio); impl_ratio_method!(Sub,sub,sub_ratio);
impl_ratio_method!(Rem,rem,rem_ratio); impl_ratio_method!(Rem,rem,rem_ratio);
macro_rules! impl_ratio_ord_method { /// Comparing two ratios needs to know the parity of the denominators
($method:ident, $ratio_method:ident, $output:ty) => { /// For signed integers this can be implemented with is_negative()
impl<LhsNum,LhsDen> Ratio<LhsNum,LhsDen>{ pub trait Parity{
fn parity(&self)->bool;
}
macro_rules! impl_parity_unsigned{
($($type:ty),*)=>{
$(
impl Parity for $type{
fn parity(&self)->bool{
false
}
}
)*
};
}
macro_rules! impl_parity_signed{
($($type:ty),*)=>{
$(
impl Parity for $type{
fn parity(&self)->bool{
self.is_negative()
}
}
)*
};
}
macro_rules! impl_parity_float{
($($type:ty),*)=>{
$(
impl Parity for $type{
fn parity(&self)->bool{
self.is_sign_negative()
}
}
)*
};
}
impl_parity_unsigned!(u8,u16,u32,u64,u128,usize);
impl_parity_signed!(i8,i16,i32,i64,i128,isize);
impl_parity_float!(f32,f64);
macro_rules! impl_ratio_ord_method{
($method:ident, $ratio_method:ident, $output:ty)=>{
impl<LhsNum,LhsDen:Parity> Ratio<LhsNum,LhsDen>{
#[inline] #[inline]
pub fn $ratio_method<RhsNum,RhsDen,T>(self,rhs:Ratio<RhsNum,RhsDen>)->$output pub fn $ratio_method<RhsNum,RhsDen:Parity,T>(self,rhs:Ratio<RhsNum,RhsDen>)->$output
where where
LhsNum:core::ops::Mul<RhsDen,Output=T>, LhsNum:core::ops::Mul<RhsDen,Output=T>,
LhsDen:core::ops::Mul<RhsNum,Output=T>, LhsDen:core::ops::Mul<RhsNum,Output=T>,
T:Ord, T:Ord,
{ {
(self.num*rhs.den).$method(&(self.den*rhs.num)) match self.den.parity()^rhs.den.parity(){
true=>(self.den*rhs.num).$method(&(self.num*rhs.den)),
false=>(self.num*rhs.den).$method(&(self.den*rhs.num)),
}
} }
} }
} }