rust
19 lines · 5 steps
Formatting byte counts as human-readable sizes
A Rust function that turns a raw byte count into a compact string like 2.5 MiB using bit tricks to pick the right unit.
Explained by
highlit
1pub fn format_size(bytes: u64) -> String {
2 const UNITS: [&str; 7] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
3
4 if bytes < 1024 {
5 return format!("{bytes} B");
6 }
7
8 let exponent = (63 - bytes.leading_zeros()) / 10;
9 let exponent = exponent.min(UNITS.len() as u32 - 1);
10 let value = bytes as f64 / 1024_f64.powi(exponent as i32);
11
12 if value >= 100.0 {
13 format!("{:.0} {}", value, UNITS[exponent as usize])
14 } else if value >= 10.0 {
15 format!("{:.1} {}", value, UNITS[exponent as usize])
16 } else {
17 format!("{:.2} {}", value, UNITS[exponent as usize])
18 }
19}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The base-2 log of a number equals its highest set bit position, which leading_zeros gives you for free.
- 2Dividing by 1024 raised to that exponent scales any byte count into its natural unit.
- 3Varying decimal precision by magnitude keeps output width roughly constant and readable.
Related explainers
rust
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use base64::{DecodeError, Engine}; pub fn encode_standard(data: &[u8]) -> String {
Base64 encode and decode in Rust
base64
encoding
error-handling
Beginner
7 steps
rust
use std::collections::HashMap; #[derive(Debug)] pub struct RequestHead {
Parsing an HTTP request head in Rust
parsing
error-handling
iterators
Intermediate
9 steps
rust
#[derive(Debug, Default)] pub struct RequestBuilder { url: String, method: String,
The builder pattern in Rust
builder-pattern
method-chaining
ergonomic-api
Intermediate
8 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/formatting-byte-counts-as-human-readable-sizes-explained-rust-a01f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.