format.rs 722 B

12345678910111213141516171819202122232425
  1. static METRIC_PREFIXES: &'static [&'static str] = &[
  2. "", "K", "M", "G", "T", "P", "E", "Z", "Y"
  3. ];
  4. static IEC_PREFIXES: &'static [&'static str] = &[
  5. "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"
  6. ];
  7. fn format_bytes(mut amount: u64, kilo: u64, prefixes: &[&str]) -> (String, String) {
  8. let mut prefix = 0;
  9. while amount > kilo {
  10. amount /= kilo;
  11. prefix += 1;
  12. }
  13. return (format!("{}", amount), prefixes[prefix].to_string());
  14. }
  15. #[allow(non_snake_case_functions)]
  16. pub fn format_IEC_bytes(amount: u64) -> (String, String) {
  17. format_bytes(amount, 1024, IEC_PREFIXES)
  18. }
  19. pub fn format_metric_bytes(amount: u64) -> (String, String) {
  20. format_bytes(amount, 1000, METRIC_PREFIXES)
  21. }