From f3869040c72ecfb6b8cf75e2222221dbdc909324 Mon Sep 17 00:00:00 2001 From: lcnr/Bastian Kauschke Date: Tue, 5 Mar 2019 14:34:49 +0100 Subject: [PATCH] add to_zero/one to Zero/One --- src/identities.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/identities.rs b/src/identities.rs index 12b9fca..437fbc1 100644 --- a/src/identities.rs +++ b/src/identities.rs @@ -1,5 +1,6 @@ use core::num::Wrapping; use core::ops::{Add, Mul}; +use core::mem; /// Defines an additive identity element for `Self`. pub trait Zero: Sized + Add { @@ -20,6 +21,24 @@ pub trait Zero: Sized + Add { // This cannot be an associated constant, because of bignums. 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. #[inline] fn is_zero(&self) -> bool; @@ -90,6 +109,23 @@ pub trait One: Sized + Mul { // This cannot be an associated constant, because of bignums. 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. /// /// For performance reasons, it's best to implement this manually.