Make all PerThing types implement all trait methods on the type (#5422)

This removes the requirement to import `PerThing` to use a type that
implements the trait.
This commit is contained in:
Bastian Köcher
2020-03-27 11:21:14 +01:00
committed by GitHub
parent acab5f0570
commit bd5758932b
8 changed files with 53 additions and 17 deletions
@@ -19,9 +19,7 @@ use serde::{Serialize, Deserialize};
use sp_std::{ops, fmt, prelude::*, convert::TryInto};
use codec::{Encode, Decode, CompactAs};
use crate::{
traits::{SaturatedConversion, UniqueSaturatedInto, Saturating, BaseArithmetic, Bounded},
};
use crate::traits::{SaturatedConversion, UniqueSaturatedInto, Saturating, BaseArithmetic, Bounded};
use sp_debug_derive::RuntimeDebug;
/// Something that implements a fixed point ration with an arbitrary granularity `X`, as _parts per
@@ -103,8 +101,8 @@ pub trait PerThing:
/// # }
/// ```
fn mul_collapse<N>(self, b: N) -> N
where N: Clone + From<Self::Inner> + UniqueSaturatedInto<Self::Inner> + ops::Rem<N, Output=N>
+ ops::Div<N, Output=N> + ops::Mul<N, Output=N> + ops::Add<N, Output=N>;
where N: Clone + From<Self::Inner> + UniqueSaturatedInto<Self::Inner> + ops::Rem<N, Output=N>
+ ops::Div<N, Output=N> + ops::Mul<N, Output=N> + ops::Add<N, Output=N>;
}
macro_rules! implement_per_thing {
@@ -259,13 +257,52 @@ macro_rules! implement_per_thing {
Self([x, 100][(x > 100) as usize] * ($max / 100))
}
/// Everything.
///
/// To avoid having to import `PerThing` when one needs to be used in test mocks.
#[cfg(feature = "std")]
/// See [`PerThing::one`].
pub fn one() -> Self {
<Self as PerThing>::one()
}
/// See [`PerThing::zero`].
pub fn zero() -> Self {
<Self as PerThing>::zero()
}
/// See [`PerThing::is_zero`].
pub fn is_zero(&self) -> bool {
PerThing::is_zero(self)
}
/// See [`PerThing::deconstruct`].
pub fn deconstruct(self) -> $type {
PerThing::deconstruct(self)
}
/// See [`PerThing::square`].
pub fn square(self) -> Self {
PerThing::square(self)
}
/// See [`PerThing::from_fraction`].
#[cfg(feature = "std")]
pub fn from_fraction(x: f64) -> Self {
<Self as PerThing>::from_fraction(x)
}
/// See [`PerThing::from_rational_approximation`].
pub fn from_rational_approximation<N>(p: N, q: N) -> Self
where N: Clone + Ord + From<$type> + TryInto<$type> +
TryInto<$upper_type> + ops::Div<N, Output=N> + ops::Rem<N, Output=N> +
ops::Add<N, Output=N> {
<Self as PerThing>::from_rational_approximation(p, q)
}
/// See [`PerThing::mul_collapse`].
pub fn mul_collapse<N>(self, b: N) -> N
where N: Clone + From<$type> + UniqueSaturatedInto<$type> +
ops::Rem<N, Output=N> + ops::Div<N, Output=N> + ops::Mul<N, Output=N> +
ops::Add<N, Output=N> {
PerThing::mul_collapse(self, b)
}
}
impl Saturating for $name {