parallel_disk_usage/
size.rs1use super::bytes_format::{self, BytesFormat};
2use derive_more::{Add, AddAssign, From, Into, Sub, SubAssign, Sum};
3use std::{
4 fmt::{Debug, Display},
5 iter::Sum,
6 ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign},
7};
8
9#[cfg(feature = "json")]
10use serde::{Deserialize, Serialize};
11
12mod mul_traits {
13 use std::ops::{Mul, MulAssign};
14 pub trait MulAssignEx<Rhs>: Mul<Rhs, Output = Self> + MulAssign<Rhs> + Sized {}
15 impl<Lhs: Mul<Rhs, Output = Lhs> + MulAssign<Rhs>, Rhs> MulAssignEx<Rhs> for Lhs {}
16}
17use mul_traits::MulAssignEx;
18
19pub trait Size:
21 Debug
22 + Default
23 + Clone
24 + Copy
25 + PartialEq
26 + Eq
27 + PartialOrd
28 + Ord
29 + Add<Output = Self>
30 + AddAssign
31 + Sub<Output = Self>
32 + SubAssign
33 + Sum
34 + MulAssignEx<u8>
35 + MulAssignEx<u16>
36 + MulAssignEx<u32>
37 + MulAssignEx<u64>
38 + MulAssignEx<usize>
39{
40 type Inner: From<Self> + Into<Self> + Mul<Self, Output = Self>;
42 type DisplayFormat: Copy;
44 type DisplayOutput: Display;
46 fn display(self, input: Self::DisplayFormat) -> Self::DisplayOutput;
48}
49
50macro_rules! impl_mul {
51 ($name:ident: $inner:ident *= $($num_type:ident)+) => {
52 $(
53 impl Mul<$num_type> for $name {
54 type Output = Self;
55 fn mul(self, rhs: $num_type) -> Self::Output {
56 self.0.mul(rhs as $inner).into()
57 }
58 }
59
60 impl Mul<$name> for $num_type {
61 type Output = $name;
62 fn mul(self, rhs: $name) -> Self::Output {
63 rhs * self
64 }
65 }
66
67 impl MulAssign<$num_type> for $name {
68 fn mul_assign(&mut self, rhs: $num_type) {
69 self.0 *= rhs as $inner;
70 }
71 }
72 )+
73 };
74
75 ($name:ident: u64) => {
76 impl_mul!($name: u64 *= usize u8 u16 u32 u64);
77 };
78}
79
80macro_rules! newtype {
81 (
82 $(#[$attribute:meta])*
83 $name:ident = $inner:ty;
84 display: ($display_format:ty) -> $display_output:ty = $display_impl:expr;
85 ) => {
86 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
87 #[derive(From, Into, Add, AddAssign, Sub, SubAssign, Sum)]
88 #[cfg_attr(feature = "json", derive(Deserialize, Serialize))]
89 $(#[$attribute])*
90 pub struct $name($inner);
91
92 impl $name {
93 pub const fn new(inner: $inner) -> Self {
94 $name(inner)
95 }
96
97 pub const fn inner(self) -> $inner {
98 self.0
99 }
100 }
101
102 impl Size for $name {
103 type Inner = $inner;
104 type DisplayFormat = $display_format;
105 type DisplayOutput = $display_output;
106 #[inline]
107 fn display(self, format: Self::DisplayFormat) -> Self::DisplayOutput {
108 let display: fn(Self, Self::DisplayFormat) -> Self::DisplayOutput = $display_impl;
109 display(self, format)
110 }
111 }
112
113 impl_mul!($name: u64);
114 };
115}
116
117newtype!(
118 Bytes = u64;
120 display: (BytesFormat) -> bytes_format::Output = |bytes, format| {
121 format.format(bytes.into())
122 };
123);
124
125newtype!(
126 Blocks = u64;
128 display: (()) -> u64 = |blocks, ()| blocks.inner();
129);