Skip to main content

pistonite_cu/str/
byte_format.rs

1/// Format integer in SI bytes.
2///
3/// The accuracy is 1 decimal, i.e `999.9T`.
4///
5/// Available units are `T`, `G`, `M`, `k`, `B`
6pub struct ByteFormat(pub u64);
7impl std::fmt::Display for ByteFormat {
8    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9        for (unit_bytes, unit_char) in [
10            (1_000_000_000_000, 'T'),
11            (1_000_000_000, 'G'),
12            (1_000_000, 'M'),
13            (1_000, 'k'),
14        ] {
15            if self.0 >= unit_bytes {
16                let whole = self.0 / unit_bytes;
17                let deci = (self.0 % unit_bytes) * 10 / unit_bytes;
18                return write!(f, "{whole}.{deci}{unit_char}");
19            }
20        }
21        write!(f, "{}B", self.0)
22    }
23}