pow_mut now returns Result.

This commit is contained in:
Violeta Hernández 2021-04-10 00:12:26 -05:00
parent 81f2fc38d7
commit 341091f647

View File

@ -14,22 +14,23 @@ where
{ {
/// Attempts to raise this matrix to an integral power `e` in-place. If this /// Attempts to raise this matrix to an integral power `e` in-place. If this
/// matrix is non-invertible and `e` is negative, it leaves this matrix /// matrix is non-invertible and `e` is negative, it leaves this matrix
/// untouched and returns `false`. Otherwise, it returns `true` and /// untouched and returns `Err(())`. Otherwise, it returns `Ok(())` and
/// overwrites this matrix with the result. /// overwrites this matrix with the result.
pub fn pow_mut<T: PrimInt + DivAssign>(&mut self, mut e: T) -> bool { #[must_use]
pub fn pow_mut<T: PrimInt + DivAssign>(&mut self, mut e: T) -> Result<(), ()> {
let zero = T::zero(); let zero = T::zero();
// A matrix raised to the zeroth power is just the identity. // A matrix raised to the zeroth power is just the identity.
if e == zero { if e == zero {
self.fill_with_identity(); self.fill_with_identity();
return true; return Ok(());
} }
// If e is negative, we compute the inverse matrix, then raise it to the // If e is negative, we compute the inverse matrix, then raise it to the
// power of -e. // power of -e.
if e < zero { if e < zero {
if !self.try_inverse_mut() { if !self.try_inverse_mut() {
return false; return Err(());
} }
} }
@ -52,7 +53,7 @@ where
multiplier.copy_from(&buf); multiplier.copy_from(&buf);
if e == zero { if e == zero {
return true; return Ok(());
} }
} }
} }
@ -63,10 +64,9 @@ where
pub fn pow<T: PrimInt + DivAssign>(&self, e: T) -> Option<Self> { pub fn pow<T: PrimInt + DivAssign>(&self, e: T) -> Option<Self> {
let mut clone = self.clone(); let mut clone = self.clone();
if clone.pow_mut(e) { match clone.pow_mut(e) {
Some(clone) Ok(()) => Some(clone),
} else { Err(()) => None,
None
} }
} }
} }