Concatenate constant strings

I wrote a code to concat two constant strings just like const_format crate does, but I'm not sure whether it is safe. Please help me to check, thanks.

use std::mem::transmute;

const A: &str = "This is a ";
const B: &str = "complete string";
const LEN: usize = A.len() + B.len();

const RESULT: &str = {
    const BYTES: [u8; LEN] = {
        #[repr(packed)]
        struct Concat<const X: usize, const Y: usize>([u8; X], [u8; Y]);
        unsafe { transmute(Concat(to_b::<{ A.len() }>(A), to_b::<{ B.len() }>(B))) }
    };

    unsafe { std::str::from_utf8_unchecked(&BYTES) }
};

const fn to_b<const N: usize>(s: &str) -> [u8; N] {
    if s.len() != N {
        panic!();
    }

    unsafe { *s.as_bytes().as_ptr().cast() }
}

fn main() {
    assert_eq!(RESULT, "This is a complete string")
}

It should be safe, but you don't really need to use unsafe for this.

const A: &str = "This is a ";
const B: &str = "complete string";

const RESULT: &str = {
    const LEN: usize = A.len() + B.len();
    const BYTES: [u8; LEN] = {
        let mut bytes = [0; LEN];
        
        let mut i = 0;
        while i < A.len() {
            bytes[i] = A.as_bytes()[i];
            i += 1;
        }
        
        let mut j = 0;
        while j < B.len() {
            bytes[A.len() + j] = B.as_bytes()[j];
            j += 1;
        }
        
        bytes
    };
    
    match std::str::from_utf8(&BYTES) {
        Ok(s) => s,
        Err(_) => unreachable!(),
    }
};

fn main() {
    assert_eq!(RESULT, "This is a complete string")
}
2 Likes

Thanks a lot. I never thought it could be that easy. :smile: