@@ -186,6 +186,25 @@ impl ByteSize {
186186 pub fn to_string_as ( & self , si_unit : bool ) -> String {
187187 to_string ( self . 0 , si_unit)
188188 }
189+
190+ /// Returns an object that implements [`Display`] for binary prefixes printing.
191+ ///
192+ /// [`Display`]: fmt::Display
193+ ///
194+ /// # Examples
195+ ///
196+ /// ```
197+ /// use bytesize::ByteSize;
198+ ///
199+ /// assert_eq!("100 B", format!("{}", ByteSize::b(100).binary_display()));
200+ /// assert_eq!("3.0 MiB", format!("{}", ByteSize::mib(3).binary_display()));
201+ /// assert_eq!("1.8 TiB", format!("{}", ByteSize::tb(2).binary_display()));
202+ /// assert_eq!("5.0 TiB", format!("{}", ByteSize::tib(5).binary_display()));
203+ /// ```
204+ #[ inline( always) ]
205+ pub fn binary_display ( & self ) -> BinaryDisplay {
206+ BinaryDisplay ( self )
207+ }
189208}
190209
191210pub fn to_string ( bytes : u64 , si_prefix : bool ) -> String {
@@ -348,6 +367,19 @@ where
348367 }
349368}
350369
370+ /// Helper struct for binary prefixes printing with [`format!`] and `{}`.
371+ ///
372+ /// This `struct` implements the [`Display`] trait.
373+ /// It is created by the [`binary_display`](ByteSize::binary_display) method on [`ByteSize`].
374+ pub struct BinaryDisplay < ' b > ( & ' b ByteSize ) ;
375+
376+ impl < ' b > Display for BinaryDisplay < ' b > {
377+ fn fmt ( & self , f : & mut Formatter < ' _ > ) -> fmt:: Result {
378+ write ! ( f, "{}" , to_string( self . 0 . 0 , true ) )
379+ }
380+ }
381+
382+
351383#[ cfg( test) ]
352384mod tests {
353385 use super :: * ;
0 commit comments