string_concat/
lib.rs

1#![no_std]
2
3extern crate alloc;
4
5#[doc(hidden)]
6pub use alloc::string::String;
7
8#[macro_export]
9macro_rules! string_concat {
10    ( $( $x:expr ),* ) => {{
11        $crate::string_concat_impl!{[] $($x),*}
12    }};
13}
14
15#[doc(hidden)]
16#[macro_export]
17macro_rules! string_concat_impl {
18    ([$($x:ident)*] ) => {{
19        let mut temp_string = $crate::String::with_capacity(0$(+$x.len())*);
20        $(
21            temp_string.push_str($x);
22        )*
23        temp_string
24    }};
25    ([$($ident:ident)*] $x:expr $(, $rest:expr)*) => {
26        let ref x = $x;
27        string_concat_impl!{[$($ident)* x] $($rest),*}
28    };
29}
30
31#[cfg(test)]
32mod tests {
33    use alloc::string::ToString;
34    use crate::String;
35    
36    #[test]
37    fn it_works() {
38        let s: String = string_concat!("hello");
39        assert_eq!(s, "hello");
40    }
41
42    #[test]
43    fn it_works_more_complicated() {
44        let s: String = string_concat!("hello", "world");
45        assert_eq!(s, "helloworld");
46    }
47
48    #[test]
49    fn it_works_with_stringss() {
50        let name = "richard".to_string();
51        let s: String = string_concat!("hello ", name, "!");
52        assert_eq!(s, "hello richard!");
53    }
54
55    #[test]
56    fn it_works_with_str() {
57        let name = "richard";
58        let s: String = string_concat!("hello ", name, "!");
59        assert_eq!(s, "hello richard!");
60    }
61}