1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
use crate::Smooth;
/// Extension trait to consistently make multiple numbers human-readable.
// ALLOW module is not public, type is re-exported
#[allow(clippy::module_name_repetitions)]
pub trait MultiSmooth {
/// Rounds all numbers to the specified decimals.
///
/// # Examples
///
/// ```rust
/// # use smooth::MultiSmooth;
/// let mut numbers = [1.1111, 5.5555, 9.9999];
/// numbers.round_to_mut(2);
///
/// assert_eq!(numbers, [1.11, 5.56, 10.0]);
/// ```
fn round_to_mut(&mut self, decimals: u32);
/// Returns formatted, consistently rounded numbers.
///
/// # Examples
///
/// ```rust
/// # use smooth::MultiSmooth;
/// let numbers = [1.1111, 5.5555, 9.9999];
///
/// assert_eq!(numbers.round_to_str(2), ["1.11", "5.56", "10"]);
/// ```
fn round_to_str(&self, decimals: u32) -> Vec<String>;
/// Consistently smoothes all numbers.
///
/// # Examples
///
/// ```rust
/// # use smooth::MultiSmooth;
/// let mut numbers = [1.1111, 5.5555, 9.9999];
/// numbers.smooth_mut();
///
/// assert_eq!(numbers, [1.1, 5.6, 10.0]);
/// ```
fn smooth_mut(&mut self);
/// Returns formatted, consistently smoothed numbers.
///
/// # Examples
///
/// ```rust
/// # use smooth::MultiSmooth;
/// let numbers = [1.1111, 5.5555, 9.9999];
///
/// assert_eq!(numbers.smooth_str(), ["1.1", "5.6", "10"]);
/// ```
fn smooth_str(&self) -> Vec<String>;
#[doc(hidden)]
fn max_td(&self) -> Option<u32>;
}
macro_rules! smooth_impl {
($t:ty) => {
impl MultiSmooth for [$t] {
fn round_to_mut(&mut self, decimals: u32) {
for number in self.iter_mut() {
number.round_to_mut(decimals);
}
}
fn round_to_str(&self, decimals: u32) -> Vec<String> {
self.iter()
.map(|number| format!("{}", number.round_to(decimals)))
.collect()
}
fn smooth_mut(&mut self) {
if let Some(max_td) = self.max_td() {
for number in self.iter_mut() {
let decimals =
2_u32.checked_sub(max_td).unwrap_or_default();
number.round_to_mut(decimals);
}
}
}
fn smooth_str(&self) -> Vec<String> {
self.max_td()
.map(|max_td| {
self.iter()
.map(|number| {
let decimals = 2_u32
.checked_sub(max_td)
.unwrap_or_default();
format!("{}", number.round_to(decimals))
})
.collect()
})
.unwrap_or_default()
}
fn max_td(&self) -> Option<u32> {
self.iter().map(|number| number.trunc_digits()).max()
}
}
};
}
smooth_impl!(f32);
smooth_impl!(f64);