diff --git a/src/lib.rs b/src/lib.rs index 3ab3483c..0d7925f4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -186,6 +186,43 @@ impl ByteSize { pub fn to_string_as(&self, si_unit: bool) -> String { to_string(self.0, si_unit) } + + /// Returns an object that implements [`Display`] for binary prefixes printing. + /// + /// [`Display`]: fmt::Display + /// + /// # Examples + /// + /// ``` + /// use bytesize::ByteSize; + /// + /// assert_eq!("100 B", format!("{}", ByteSize::b(100).binary_display())); + /// assert_eq!("3.0 MiB", format!("{}", ByteSize::mib(3).binary_display())); + /// assert_eq!("1.8 TiB", format!("{}", ByteSize::tb(2).binary_display())); + /// assert_eq!("5.0 TiB", format!("{}", ByteSize::tib(5).binary_display())); + /// ``` + #[inline(always)] + pub fn binary_display(&self) -> BinaryDisplay { + BinaryDisplay(self) + } + + /// Returns an object that implements [`Display`] for SI(decimal) prefixes printing. + /// + /// [`Display`]: fmt::Display + /// + /// # Examples + /// + /// ``` + /// use bytesize::ByteSize; + /// + /// assert_eq!("100 B", format!("{}", ByteSize::b(100).decimal_display())); + /// assert_eq!("3.0 MB", format!("{}", ByteSize::mb(3).decimal_display())); + /// assert_eq!("5.0 TB", format!("{}", ByteSize::tb(5).decimal_display())); + /// ``` + #[inline(always)] + pub fn decimal_display(&self) -> DecimalDisplay { + DecimalDisplay(self) + } } pub fn to_string(bytes: u64, si_prefix: bool) -> String { @@ -348,6 +385,30 @@ where } } +/// Helper struct for binary prefixes printing with [`format!`] and `{}`. +/// +/// This `struct` implements the [`Display`] trait. +/// It is created by the [`binary_display`](ByteSize::binary_display) method on [`ByteSize`]. +pub struct BinaryDisplay<'b>(&'b ByteSize); + +impl Display for BinaryDisplay<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{}", to_string(self.0 .0, true)) + } +} + +/// Helper struct for SI(decimal) prefixes printing with [`format!`] and `{}`. +/// +/// This `struct` implements the [`Display`] trait. +/// It is created by the [`decimal_display`](ByteSize::decimal_display) method on [`ByteSize`]. +pub struct DecimalDisplay<'b>(&'b ByteSize); + +impl Display for DecimalDisplay<'_> { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{}", to_string(self.0 .0, false)) + } +} + #[cfg(test)] mod tests { use super::*;