From eae97c6b1499579907207024051cd4735621a731 Mon Sep 17 00:00:00 2001 From: Trevor Spiteri Date: Tue, 6 Aug 2019 22:48:13 +0200 Subject: [PATCH] make traits::Fixed more comprehensive Lots of supertraits, add {mul,div,rem}_int --- src/traits.rs | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/src/traits.rs b/src/traits.rs index a54f08b..11e2b31 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -23,11 +23,31 @@ use crate::{ FixedI128, FixedI16, FixedI32, FixedI64, FixedI8, FixedU128, FixedU16, FixedU32, FixedU64, FixedU8, }; +use core::{ + fmt::{Binary, Debug, Display, LowerHex, Octal, UpperHex}, + hash::Hash, + ops::{ + Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, + DivAssign, Mul, MulAssign, Neg, Not, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, + }, +}; #[cfg(feature = "f16")] use half::f16; /// This trait provides common methods to all fixed-point numbers. -pub trait Fixed: Copy + FromFixed + ToFixed + sealed::Fixed { +pub trait Fixed +where + Self: Clone + Copy + Default, + Self: Debug + Display + Binary + Octal + LowerHex + UpperHex, + Self: Eq + Hash + Ord, + Self: FromFixed + ToFixed + sealed::Fixed, + Self: Add + Sub + Mul + Div, + Self: Neg + Not, + Self: BitAnd + BitOr + BitXor, + Self: Shl + Shr, + Self: AddAssign + SubAssign + MulAssign + DivAssign, + Self: BitAndAssign + BitOrAssign + BitXorAssign + ShlAssign + ShrAssign, +{ /// The primitive integer underlying type. type Bits; @@ -157,6 +177,15 @@ pub trait Fixed: Copy + FromFixed + ToFixed + sealed::Fixed { /// Shifts to the right by *n* bits, wrapping the truncated bits to the left end. fn rotate_right(self, n: u32) -> Self; + /// Multiplication by an integer. + fn mul_int(self, rhs: Self::Bits) -> Self; + + /// Division by an integer. + fn div_int(self, rhs: Self::Bits) -> Self; + + /// Remainder for division by an integer. + fn rem_int(self, rhs: Self::Bits) -> Self; + /// Checked negation. Returns the negated value, or [`None`] on overflow. /// /// [`None`]: https://doc.rust-lang.org/nightly/std/option/enum.Option.html#variant.None @@ -964,6 +993,18 @@ macro_rules! impl_fixed { trait_delegate! { fn trailing_zeros(self) -> u32 } trait_delegate! { fn rotate_left(self, n: u32) -> Self } trait_delegate! { fn rotate_right(self, n: u32) -> Self } + #[inline] + fn mul_int(self, rhs: Self::Bits) -> Self { + self * rhs + } + #[inline] + fn div_int(self, rhs: Self::Bits) -> Self { + self / rhs + } + #[inline] + fn rem_int(self, rhs: Self::Bits) -> Self { + self % rhs + } trait_delegate! { fn checked_neg(self) -> Option } trait_delegate! { fn checked_add(self, rhs: Self) -> Option } trait_delegate! { fn checked_sub(self, rhs: Self) -> Option }