Skip to content

Commit 0d9d9c4

Browse files
committed
Add DecimalDisplay for ByteSize decimal prefixes printing helper
1 parent 296ad68 commit 0d9d9c4

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/lib.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,24 @@ impl ByteSize {
205205
pub fn binary_display(&self) -> BinaryDisplay {
206206
BinaryDisplay(self)
207207
}
208+
209+
/// Returns an object that implements [`Display`] for SI(decimal) prefixes printing.
210+
///
211+
/// [`Display`]: fmt::Display
212+
///
213+
/// # Examples
214+
///
215+
/// ```
216+
/// use bytesize::ByteSize;
217+
///
218+
/// assert_eq!("100 B", format!("{}", ByteSize::b(100).decimal_display()));
219+
/// assert_eq!("3.0 MB", format!("{}", ByteSize::mb(3).decimal_display()));
220+
/// assert_eq!("5.0 TB", format!("{}", ByteSize::tb(5).decimal_display()));
221+
/// ```
222+
#[inline(always)]
223+
pub fn decimal_display(&self) -> DecimalDisplay {
224+
DecimalDisplay(self)
225+
}
208226
}
209227

210228
pub fn to_string(bytes: u64, si_prefix: bool) -> String {
@@ -379,6 +397,17 @@ impl Display for BinaryDisplay<'_> {
379397
}
380398
}
381399

400+
/// Helper struct for SI(decimal) prefixes printing with [`format!`] and `{}`.
401+
///
402+
/// This `struct` implements the [`Display`] trait.
403+
/// It is created by the [`decimal_display`](ByteSize::decimal_display) method on [`ByteSize`].
404+
pub struct DecimalDisplay<'b>(&'b ByteSize);
405+
406+
impl Display for DecimalDisplay<'_> {
407+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
408+
write!(f, "{}", to_string(self.0 .0, false))
409+
}
410+
}
382411

383412
#[cfg(test)]
384413
mod tests {

0 commit comments

Comments
 (0)