Skip to content

Commit 3036904

Browse files
committed
Add DecimalDisplay for ByteSize decimal prefixes printing helper
1 parent 2eb2a0c commit 3036904

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/lib.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,24 @@ impl ByteSize {
196196
pub fn binary_display(&self) -> BinaryDisplay {
197197
BinaryDisplay(self)
198198
}
199+
200+
/// Returns an object that implements [`Display`] for SI(decimal) prefixes printing.
201+
///
202+
/// [`Display`]: fmt::Display
203+
///
204+
/// # Examples
205+
///
206+
/// ```
207+
/// use bytesize::ByteSize;
208+
///
209+
/// assert_eq!("100 B", format!("{}", ByteSize::b(100).decimal_display()));
210+
/// assert_eq!("3.0 MB", format!("{}", ByteSize::mb(3).decimal_display()));
211+
/// assert_eq!("5.0 TB", format!("{}", ByteSize::tb(5).decimal_display()));
212+
/// ```
213+
#[inline(always)]
214+
pub fn decimal_display(&self) -> DecimalDisplay {
215+
DecimalDisplay(self)
216+
}
199217
}
200218

201219
pub fn to_string(bytes: u64, si_prefix: bool) -> String {
@@ -325,6 +343,18 @@ impl<'b> Display for BinaryDisplay<'b> {
325343
}
326344
}
327345

346+
/// Helper struct for SI(decimal) prefixes printing with [`format!`] and `{}`.
347+
///
348+
/// This `struct` implements the [`Display`] trait.
349+
/// It is created by the [`decimal_display`](ByteSize::decimal_display) method on [`ByteSize`].
350+
pub struct DecimalDisplay<'b>(&'b ByteSize);
351+
352+
impl<'b> Display for DecimalDisplay<'b> {
353+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
354+
write!(f, "{}", to_string(self.0 .0, false))
355+
}
356+
}
357+
328358
#[cfg(feature = "serde")]
329359
impl<'de> Deserialize<'de> for ByteSize {
330360
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>

0 commit comments

Comments
 (0)