Skip to content

Instantly share code, notes, and snippets.

@lffg
Created March 24, 2024 15:19
Show Gist options
  • Save lffg/877f625e4c46378880d036fbedecce0a to your computer and use it in GitHub Desktop.
Save lffg/877f625e4c46378880d036fbedecce0a to your computer and use it in GitHub Desktop.
macro_rules! cat {
($($str:expr),*) => {{
const LEN: usize = $($str.len() + )* 0;
to_str(&combine::<LEN>(&[$($str),*]))
}};
}
const fn combine<const LEN: usize>(list: &[&'static str]) -> [u8; LEN] {
let mut bytes = [0; LEN];
let mut i = 0;
let mut cursor = 0;
while i < list.len() {
let str = list[i].as_bytes();
// write
{
let mut j = 0;
while j < str.len() {
bytes[cursor + j] = str[j];
j += 1;
}
}
cursor += str.len();
i += 1;
}
bytes
}
const fn to_str(bytes: &'static [u8]) -> &'static str {
match std::str::from_utf8(bytes) {
Ok(s) => s,
// `combine` only accept UTF-8 strings
Err(_) => unreachable!(),
}
}
const S1: &'static str = cat!("a", "bc");
const S2: &'static str = cat!("A", "B", S1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment