Skip to content

Commit

Permalink
Merge pull request #303 from tarcieri/constant-traits
Browse files Browse the repository at this point in the history
Add `ConstZero` and `ConstOne` traits
  • Loading branch information
cuviper committed Feb 8, 2024
2 parents 29c5b46 + 67d9e74 commit a095b70
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
36 changes: 36 additions & 0 deletions src/identities.rs
Expand Up @@ -28,6 +28,13 @@ pub trait Zero: Sized + Add<Self, Output = Self> {
fn is_zero(&self) -> bool;
}

/// Defines an associated constant representing the additive identity element
/// for `Self`.
pub trait ConstZero: Zero {
/// The additive identity element of `Self`, `0`.
const ZERO: Self;
}

macro_rules! zero_impl {
($t:ty, $v:expr) => {
impl Zero for $t {
Expand All @@ -40,6 +47,10 @@ macro_rules! zero_impl {
*self == $v
}
}

impl ConstZero for $t {
const ZERO: Self = $v;
}
};
}

Expand Down Expand Up @@ -77,6 +88,13 @@ where
}
}

impl<T: ConstZero> ConstZero for Wrapping<T>
where
Wrapping<T>: Add<Output = Wrapping<T>>,
{
const ZERO: Self = Wrapping(T::ZERO);
}

/// Defines a multiplicative identity element for `Self`.
///
/// # Laws
Expand Down Expand Up @@ -115,6 +133,13 @@ pub trait One: Sized + Mul<Self, Output = Self> {
}
}

/// Defines an associated constant representing the multiplicative identity
/// element for `Self`.
pub trait ConstOne: One {
/// The multiplicative identity element of `Self`, `1`.
const ONE: Self;
}

macro_rules! one_impl {
($t:ty, $v:expr) => {
impl One for $t {
Expand All @@ -127,6 +152,10 @@ macro_rules! one_impl {
*self == $v
}
}

impl ConstOne for $t {
const ONE: Self = $v;
}
};
}

Expand Down Expand Up @@ -160,6 +189,13 @@ where
}
}

impl<T: ConstOne> ConstOne for Wrapping<T>
where
Wrapping<T>: Mul<Output = Wrapping<T>>,
{
const ONE: Self = Wrapping(T::ONE);
}

// Some helper functions provided for backwards compatibility.

/// Returns the additive identity, `0`.
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Expand Up @@ -33,7 +33,7 @@ pub use crate::float::Float;
pub use crate::float::FloatConst;
// pub use real::{FloatCore, Real}; // NOTE: Don't do this, it breaks `use num_traits::*;`.
pub use crate::cast::{cast, AsPrimitive, FromPrimitive, NumCast, ToPrimitive};
pub use crate::identities::{one, zero, One, Zero};
pub use crate::identities::{one, zero, ConstOne, ConstZero, One, Zero};
pub use crate::int::PrimInt;
pub use crate::ops::bytes::{FromBytes, ToBytes};
pub use crate::ops::checked::{
Expand Down

0 comments on commit a095b70

Please sign in to comment.