Created
March 24, 2024 15:19
-
-
Save lffg/877f625e4c46378880d036fbedecce0a to your computer and use it in GitHub Desktop.
This file contains 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
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