Skip to content

Commit a095b70

Browse files
authored
Merge pull request #303 from tarcieri/constant-traits
Add `ConstZero` and `ConstOne` traits
2 parents 29c5b46 + 67d9e74 commit a095b70

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/identities.rs

+36
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,13 @@ pub trait Zero: Sized + Add<Self, Output = Self> {
2828
fn is_zero(&self) -> bool;
2929
}
3030

31+
/// Defines an associated constant representing the additive identity element
32+
/// for `Self`.
33+
pub trait ConstZero: Zero {
34+
/// The additive identity element of `Self`, `0`.
35+
const ZERO: Self;
36+
}
37+
3138
macro_rules! zero_impl {
3239
($t:ty, $v:expr) => {
3340
impl Zero for $t {
@@ -40,6 +47,10 @@ macro_rules! zero_impl {
4047
*self == $v
4148
}
4249
}
50+
51+
impl ConstZero for $t {
52+
const ZERO: Self = $v;
53+
}
4354
};
4455
}
4556

@@ -77,6 +88,13 @@ where
7788
}
7889
}
7990

91+
impl<T: ConstZero> ConstZero for Wrapping<T>
92+
where
93+
Wrapping<T>: Add<Output = Wrapping<T>>,
94+
{
95+
const ZERO: Self = Wrapping(T::ZERO);
96+
}
97+
8098
/// Defines a multiplicative identity element for `Self`.
8199
///
82100
/// # Laws
@@ -115,6 +133,13 @@ pub trait One: Sized + Mul<Self, Output = Self> {
115133
}
116134
}
117135

136+
/// Defines an associated constant representing the multiplicative identity
137+
/// element for `Self`.
138+
pub trait ConstOne: One {
139+
/// The multiplicative identity element of `Self`, `1`.
140+
const ONE: Self;
141+
}
142+
118143
macro_rules! one_impl {
119144
($t:ty, $v:expr) => {
120145
impl One for $t {
@@ -127,6 +152,10 @@ macro_rules! one_impl {
127152
*self == $v
128153
}
129154
}
155+
156+
impl ConstOne for $t {
157+
const ONE: Self = $v;
158+
}
130159
};
131160
}
132161

@@ -160,6 +189,13 @@ where
160189
}
161190
}
162191

192+
impl<T: ConstOne> ConstOne for Wrapping<T>
193+
where
194+
Wrapping<T>: Mul<Output = Wrapping<T>>,
195+
{
196+
const ONE: Self = Wrapping(T::ONE);
197+
}
198+
163199
// Some helper functions provided for backwards compatibility.
164200

165201
/// Returns the additive identity, `0`.

src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ pub use crate::float::Float;
3333
pub use crate::float::FloatConst;
3434
// pub use real::{FloatCore, Real}; // NOTE: Don't do this, it breaks `use num_traits::*;`.
3535
pub use crate::cast::{cast, AsPrimitive, FromPrimitive, NumCast, ToPrimitive};
36-
pub use crate::identities::{one, zero, One, Zero};
36+
pub use crate::identities::{one, zero, ConstOne, ConstZero, One, Zero};
3737
pub use crate::int::PrimInt;
3838
pub use crate::ops::bytes::{FromBytes, ToBytes};
3939
pub use crate::ops::checked::{

0 commit comments

Comments
 (0)