Created
February 20, 2024 08:33
-
-
Save romac/a589466ff0733380e94ea00718db0cbd to your computer and use it in GitHub Desktop.
Compile-time computation of prefix size on stable Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const PREFIX_TYPES: &[&str] = &["Compiling", "Downloading", "Fetching", "Printing", "Doing"]; | |
const fn max_prefix_width() -> usize { | |
let mut max_width = 0; | |
let mut i = 0; | |
loop { | |
if i == PREFIX_TYPES.len() { | |
break; | |
} | |
let msg = PREFIX_TYPES[i]; | |
if msg.len() > max_width { | |
max_width = msg.len(); | |
} | |
i += 1; | |
} | |
max_width | |
} | |
const _: () = assert!(max_prefix_width() != 0, "No messages"); | |
const BOLD: &str = "\x1b[1m"; | |
const BLUE: &str = "\x1b[34m"; | |
const RESET: &str = "\x1b[0m"; | |
fn msg(prefix: &str, msg: &str) { | |
println!( | |
"{BOLD}{BLUE}{prefix: >width$}{RESET} {msg}", | |
width = max_prefix_width() + 2 | |
); | |
} | |
fn main() { | |
msg("Compiling", "main.rs"); | |
msg("Downloading", "rustc"); | |
msg("Fetching", "crates"); | |
msg("Printing", "output"); | |
msg("Doing", "stuff"); | |
} | |
/* | |
Compiling main.rs | |
Downloading rustc | |
Fetching crates | |
Printing output | |
Doing stuff | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment