use std::ops::{
Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, Sub, SubAssign,
};
pub trait Numeric:
Copy
+ Clone
+ Send
+ Sync
+ PartialEq
+ PartialOrd
+ Add<Output = Self>
+ Sub<Output = Self>
+ Mul<Output = Self>
+ Div<Output = Self>
+ AddAssign
+ SubAssign
+ MulAssign
+ DivAssign
{
}
impl<T> Numeric for T where
T: Copy
+ Clone
+ Send
+ Sync
+ PartialEq
+ PartialOrd
+ Add<Output = T>
+ Sub<Output = T>
+ Mul<Output = T>
+ Div<Output = T>
+ AddAssign
+ SubAssign
+ MulAssign
+ DivAssign
{
}
pub trait Integer: Numeric + Rem<Output = Self> {
fn zero() -> Self;
fn one() -> Self;
}
pub trait Float: Numeric + Neg<Output = Self> {
fn zero() -> Self;
fn one() -> Self;
fn from_usize(val: usize) -> Self;
fn epsilon() -> Self;
fn abs(self) -> Self;
fn sqrt(self) -> Self;
fn exp(self) -> Self;
fn ln(self) -> Self;
fn powf(self, n: Self) -> Self;
fn is_nan(self) -> bool;
fn is_finite(self) -> bool;
}
pub trait Accumulate {
type Output: Numeric;
fn to_acc(self) -> Self::Output;
}
macro_rules! impl_signed_integer {
($($t:ty),*) => {
$(
impl Integer for $t {
#[inline]
fn zero() -> Self { 0 }
#[inline]
fn one() -> Self { 1 }
}
impl Accumulate for $t {
type Output = i64;
#[inline]
fn to_acc(self) -> Self::Output {
self as i64
}
}
)*
};
}
impl_signed_integer!(i8, i16, i32, i64, isize);
macro_rules! impl_unsigned_integer {
($($t:ty),*) => {
$(
impl Integer for $t {
#[inline]
fn zero() -> Self { 0 }
#[inline]
fn one() -> Self { 1 }
}
impl Accumulate for $t {
type Output = u64;
#[inline]
fn to_acc(self) -> Self::Output {
self as u64
}
}
)*
};
}
impl_unsigned_integer!(u8, u16, u32, u64, usize);
macro_rules! impl_float {
($t:ty) => {
impl Float for $t {
#[inline]
fn zero() -> Self { 0.0 }
#[inline]
fn one() -> Self { 1.0 }
#[inline]
fn from_usize(val: usize) -> Self {
val as $t
}
#[inline]
fn epsilon() -> Self {
<$t>::EPSILON
}
#[inline]
fn abs(self) -> Self {
<$t>::abs(self)
}
#[inline]
fn sqrt(self) -> Self {
<$t>::sqrt(self)
}
#[inline]
fn exp(self) -> Self {
<$t>::exp(self)
}
#[inline]
fn ln(self) -> Self {
<$t>::ln(self)
}
#[inline]
fn powf(self, n: Self) -> Self {
<$t>::powf(self, n)
}
#[inline]
fn is_nan(self) -> bool {
<$t>::is_nan(self)
}
#[inline]
fn is_finite(self) -> bool {
<$t>::is_finite(self)
}
}
impl Accumulate for $t {
type Output = f64;
#[inline]
fn to_acc(self) -> Self::Output {
self as f64
}
}
};
}
impl_float!(f32);
impl_float!(f64);