Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ConstZero and ConstOne traits #303

Merged
merged 6 commits into from Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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