const_str/__ctfe/
to_byte_array.rs

1pub struct ToByteArray<T>(pub T);
2
3impl ToByteArray<&str> {
4    pub const fn const_eval<const N: usize>(&self) -> [u8; N] {
5        crate::bytes::clone(self.0.as_bytes())
6    }
7}
8
9impl<const L: usize> ToByteArray<&[u8; L]> {
10    pub const fn const_eval<const N: usize>(&self) -> [u8; N] {
11        crate::bytes::clone(self.0)
12    }
13}
14
15/// Converts a string slice or a byte string to a byte array.
16///
17/// This macro is [const-context only](./index.html#const-context-only).
18///
19/// # Examples
20/// ```
21/// const S: &str = "hello";
22/// const B: &[u8; 6] = b"hello\0";
23/// assert_eq!(const_str::to_byte_array!(S), [b'h', b'e', b'l', b'l', b'o']);
24/// assert_eq!(const_str::to_byte_array!(B), [b'h', b'e', b'l', b'l', b'o', b'\0']);
25/// ```
26///
27#[macro_export]
28macro_rules! to_byte_array {
29    ($s: expr) => {{
30        const OUTPUT_LEN: usize = $s.len();
31        $crate::__ctfe::ToByteArray($s).const_eval::<OUTPUT_LEN>()
32    }};
33}