format_memory_size

Function format_memory_size 

Source
pub fn format_memory_size(bytes: u64) -> String
Expand description

High-performance memory size formatting function

Converts byte count to human-readable memory size string, automatically selecting appropriate units. Uses bit shift operations for performance optimization, supports memory sizes from bytes to PB level.

§Arguments

  • bytes - The number of bytes to format

§Returns

Returns formatted string, for example:

  • 1024"1KB"
  • 1536"1.5KB"
  • 1073741824"1GB"

§Supported Units

  • B - Bytes (< 1024)
  • KB - Kilobytes (1024 B)
  • MB - Megabytes (1024 KB)
  • GB - Gigabytes (1024 MB)
  • TB - Terabytes (1024 GB)
  • PB - Petabytes (1024 TB)

§Performance Features

  • Uses bit shift operations instead of division for performance optimization
  • Hardware-optimized leading zero count instructions
  • Retains only 1 decimal place for improved performance
  • Zero-copy string construction

§Examples

use auto_allocator;

// Basic usage
assert_eq!(auto_allocator::format_memory_size(0), "0B");
assert_eq!(auto_allocator::format_memory_size(1024), "1KB");
assert_eq!(auto_allocator::format_memory_size(1536), "1.5KB");
assert_eq!(auto_allocator::format_memory_size(1048576), "1MB");
assert_eq!(auto_allocator::format_memory_size(1073741824), "1GB");

// Use in combination with system information
let info = auto_allocator::get_allocator_info();
let memory_str = auto_allocator::format_memory_size(info.system_info.total_memory_bytes);
println!("Total system memory: {}", memory_str);

// Display memory usage in application
fn display_memory_usage() {
    let info = auto_allocator::get_allocator_info();
    println!("Memory information:");
    println!("  Total memory: {}", auto_allocator::format_memory_size(info.system_info.total_memory_bytes));
}

§Precision Notes

For performance considerations, decimal places are limited to 1 digit. For scenarios requiring higher precision, it is recommended to calculate directly using byte counts.