Tweaked convert() api, added comments

main
nick 2024-07-21 20:22:40 -04:00
parent 0ca5d93248
commit d97f397afc
1 changed files with 18 additions and 9 deletions

View File

@ -34,19 +34,22 @@ impl Unit {
"blk" | "blks"
| "blck" |"blcks"
| "block" | "blocks" => Ok(Self::Blocks),
_ => Err(s),
_ => Err("use --help to get a list of units".into()),
}
}
pub fn convert(self, n: u64) -> String {
let n = if self == Self::Blocks {
n.next_multiple_of(self.integer_value())
} else {
n
};
format!("{}{}", n/self.integer_value(), self.units_pretty())
format!("{}", n/self.integer_value())
}
pub fn convert_with_units(self, n: u64) -> String {
self.convert(n) + self.units_pretty()
}
/// Units to print for each different unit.
/// They all have a space between at the front
/// for style reasons, except for bytes which are
/// basically unindicated
const fn units_pretty(self) -> &'static str {
match self {
Self::Byte => "",
@ -62,9 +65,16 @@ impl Unit {
}
}
/// The size is always held in bytes, so
/// this returns the scale factor.
/// A special case is made for
/// blocks, because the number of blocks
/// is repeatedly queried throughout
/// the search process, it needn't be
/// altered here
const fn integer_value(self) -> u64 {
match self {
Self::Byte => 1,
Self::Byte | Self::Blocks => 1,
Self::Kilo => 1_000,
Self::Kibi => 1_024,
Self::Mega => 1_000_000,
@ -73,7 +83,6 @@ impl Unit {
Self::Gibi => 1_073_741_824,
Self::Tera => 1_000_000_000_000,
Self::Tibi => 1_099_511_627_776,
Self::Blocks => 512,
}
}
}