const_str/__ctfe/
repeat.rs

1#![allow(unsafe_code)]
2
3use super::StrBuf;
4
5pub struct Repeat<T>(pub T, pub usize);
6
7impl Repeat<&str> {
8    pub const fn const_eval<const N: usize>(&self) -> StrBuf<N> {
9        let buf = bytes_repeat(self.0.as_bytes(), self.1);
10        unsafe { StrBuf::new_unchecked(buf) }
11    }
12}
13
14const fn bytes_repeat<const N: usize>(bytes: &[u8], n: usize) -> [u8; N] {
15    assert!(bytes.len().checked_mul(n).is_some());
16    assert!(bytes.len() * n == N);
17    let mut buf = [0; N];
18    let mut i = 0;
19    let mut j = 0;
20    while i < n {
21        let mut k = 0;
22        while k < bytes.len() {
23            buf[j] = bytes[k];
24            j += 1;
25            k += 1;
26        }
27        i += 1;
28    }
29    buf
30}
31
32/// Creates a new string slice by repeating a string slice n times.
33///
34/// This macro is [const-context only](./index.html#const-context-only).
35///
36/// # Examples
37///
38/// ```
39/// const S: &str = "abc";
40/// const SSSS: &str = const_str::repeat!(S, 4);
41/// assert_eq!(SSSS, "abcabcabcabc");
42/// ```
43///
44#[macro_export]
45macro_rules! repeat {
46    ($s: expr, $n: expr) => {{
47        const INPUT: &str = $s;
48        const N: usize = $n;
49        const OUTPUT_LEN: usize = INPUT.len() * N;
50        const OUTPUT_BUF: $crate::__ctfe::StrBuf<OUTPUT_LEN> =
51            $crate::__ctfe::Repeat(INPUT, N).const_eval();
52        OUTPUT_BUF.as_str()
53    }};
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn test_repeat() {
62        const S1: &str = "abc";
63        const R1: &str = repeat!(S1, 4);
64        assert_eq!(R1, "abcabcabcabc");
65
66        const S2: &str = "x";
67        const R2: &str = repeat!(S2, 5);
68        assert_eq!(R2, "xxxxx");
69
70        const S3: &str = "hello";
71        const R3: &str = repeat!(S3, 2);
72        assert_eq!(R3, "hellohello");
73
74        const S4: &str = "test";
75        const R4: &str = repeat!(S4, 0);
76        assert_eq!(R4, "");
77
78        const S5: &str = "test";
79        const R5: &str = repeat!(S5, 1);
80        assert_eq!(R5, "test");
81    }
82
83    #[test]
84    fn test_repeat_runtime() {
85        // Runtime tests for Repeat
86        let repeat = Repeat("abc", 3);
87        let buf: StrBuf<9> = repeat.const_eval();
88        assert_eq!(buf.as_str(), "abcabcabc");
89
90        let repeat_single = Repeat("x", 10);
91        let buf2: StrBuf<10> = repeat_single.const_eval();
92        assert_eq!(buf2.as_str(), "xxxxxxxxxx");
93
94        let repeat_zero = Repeat("test", 0);
95        let buf3: StrBuf<0> = repeat_zero.const_eval();
96        assert_eq!(buf3.as_str(), "");
97
98        // Test bytes_repeat directly
99        let bytes = b"hi";
100        let result: [u8; 6] = bytes_repeat(bytes, 3);
101        assert_eq!(&result, b"hihihi");
102
103        let result2: [u8; 0] = bytes_repeat(b"x", 0);
104        assert_eq!(&result2, b"");
105    }
106}