add to_zero/one to Zero/One

This commit is contained in:
lcnr/Bastian Kauschke 2019-03-05 14:34:49 +01:00
parent d668985fae
commit f3869040c7
1 changed files with 36 additions and 0 deletions

View File

@ -1,5 +1,6 @@
use core::num::Wrapping; use core::num::Wrapping;
use core::ops::{Add, Mul}; use core::ops::{Add, Mul};
use core::mem;
/// Defines an additive identity element for `Self`. /// Defines an additive identity element for `Self`.
pub trait Zero: Sized + Add<Self, Output = Self> { pub trait Zero: Sized + Add<Self, Output = Self> {
@ -20,6 +21,24 @@ pub trait Zero: Sized + Add<Self, Output = Self> {
// This cannot be an associated constant, because of bignums. // This cannot be an associated constant, because of bignums.
fn zero() -> Self; fn zero() -> Self;
/// Sets `self` to the additive identity element of `Self`, `0`.
/// This function may be faster than replacing self with `Zero::zero()`.
///
/// # Laws
///
/// ```{.text}
/// a + 0 = a ∀ a ∈ Self
/// 0 + a = a ∀ a ∈ Self
/// ```
///
/// # Purity
///
/// This function may return different results depending on the previous state of `self`.
fn to_zero(&mut self) -> &mut Self {
mem::replace(self, Zero::zero());
self
}
/// Returns `true` if `self` is equal to the additive identity. /// Returns `true` if `self` is equal to the additive identity.
#[inline] #[inline]
fn is_zero(&self) -> bool; fn is_zero(&self) -> bool;
@ -90,6 +109,23 @@ pub trait One: Sized + Mul<Self, Output = Self> {
// This cannot be an associated constant, because of bignums. // This cannot be an associated constant, because of bignums.
fn one() -> Self; fn one() -> Self;
/// Sets `self` to the multiplicative identity element of `Self`, `1`.
///
/// # Laws
///
/// ```{.text}
/// a * 1 = a ∀ a ∈ Self
/// 1 * a = a ∀ a ∈ Self
/// ```
///
/// # Purity
///
/// This function may return different results depending on the previous state of `self`.
fn to_zero(&mut self) -> &mut Self {
mem::replace(self, One::one());
self
}
/// Returns `true` if `self` is equal to the multiplicative identity. /// Returns `true` if `self` is equal to the multiplicative identity.
/// ///
/// For performance reasons, it's best to implement this manually. /// For performance reasons, it's best to implement this manually.