Skip to main content

competitive/num/
zero_one.rs

1pub trait Zero: Sized {
2    fn zero() -> Self;
3    #[inline]
4    fn is_zero(&self) -> bool
5    where
6        Self: PartialEq,
7    {
8        self == &Self::zero()
9    }
10    #[inline]
11    fn set_zero(&mut self) {
12        *self = Self::zero();
13    }
14}
15pub trait One: Sized {
16    fn one() -> Self;
17    #[inline]
18    fn is_one(&self) -> bool
19    where
20        Self: PartialEq,
21    {
22        self == &Self::one()
23    }
24    #[inline]
25    fn set_one(&mut self) {
26        *self = Self::one();
27    }
28}
29macro_rules! impl_zero_one {
30    ($({$(<$T:ident: $Bound:ident>)? $Trait:ident $method:ident $($t:ty)*, $e:expr})*) => {$(
31        impl_zero_one!(@impl [$(<$T: $Bound>)?] $Trait $method [$($t)*], $e);
32    )*};
33    (@impl [<$T:ident: $Bound:ident>] $Trait:ident $method:ident [$($t:ty)*], $e:expr) => {$(
34        impl<$T: $Bound> $Trait for $t {
35            fn $method() -> Self {
36                $e
37            }
38        }
39    )*};
40    (@impl [] $Trait:ident $method:ident [$($t:ty)*], $e:expr) => {$(
41        impl $Trait for $t {
42            fn $method() -> Self {
43                $e
44            }
45        }
46    )*};
47}
48impl_zero_one!(
49    {Zero zero u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128, 0}
50    {Zero zero f32 f64, 0.}
51    {One one u8 u16 u32 u64 usize i8 i16 i32 i64 isize u128 i128, 1}
52    {One one f32 f64, 1.}
53    {<T: Zero> Zero zero std::num::Wrapping<T>, Self(T::zero())}
54    {<T: One> One one std::num::Wrapping<T>, Self(T::one())}
55);