Skip to content

Commit 2eb2a0c

Browse files
committed
Add BinaryDisplay for ByteSize binary prefixes printing helper
1 parent 5235bf4 commit 2eb2a0c

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/lib.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,25 @@ impl ByteSize {
177177
pub fn to_string_as(&self, si_unit: bool) -> String {
178178
to_string(self.0, si_unit)
179179
}
180+
181+
/// Returns an object that implements [`Display`] for binary prefixes printing.
182+
///
183+
/// [`Display`]: fmt::Display
184+
///
185+
/// # Examples
186+
///
187+
/// ```
188+
/// use bytesize::ByteSize;
189+
///
190+
/// assert_eq!("100 B", format!("{}", ByteSize::b(100).binary_display()));
191+
/// assert_eq!("3.0 MiB", format!("{}", ByteSize::mib(3).binary_display()));
192+
/// assert_eq!("1.8 TiB", format!("{}", ByteSize::tb(2).binary_display()));
193+
/// assert_eq!("5.0 TiB", format!("{}", ByteSize::tib(5).binary_display()));
194+
/// ```
195+
#[inline(always)]
196+
pub fn binary_display(&self) -> BinaryDisplay {
197+
BinaryDisplay(self)
198+
}
180199
}
181200

182201
pub fn to_string(bytes: u64, si_prefix: bool) -> String {
@@ -294,6 +313,18 @@ impl<T> MulAssign<T> for ByteSize
294313
}
295314
}
296315

316+
/// Helper struct for binary prefixes printing with [`format!`] and `{}`.
317+
///
318+
/// This `struct` implements the [`Display`] trait.
319+
/// It is created by the [`binary_display`](ByteSize::binary_display) method on [`ByteSize`].
320+
pub struct BinaryDisplay<'b>(&'b ByteSize);
321+
322+
impl<'b> Display for BinaryDisplay<'b> {
323+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
324+
write!(f, "{}", to_string(self.0 .0, true))
325+
}
326+
}
327+
297328
#[cfg(feature = "serde")]
298329
impl<'de> Deserialize<'de> for ByteSize {
299330
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>

0 commit comments

Comments
 (0)