const_str/__ctfe/
str.rs

1#![allow(unsafe_code)]
2
3pub struct StrBuf<const N: usize>([u8; N]);
4
5impl<const N: usize> StrBuf<N> {
6    /// # Safety
7    /// `buf` must contain valid utf-8 bytes.
8    pub const unsafe fn new_unchecked(buf: [u8; N]) -> Self {
9        #[cfg(debug_assertions)]
10        {
11            assert!(core::str::from_utf8(&buf).is_ok())
12        }
13        Self(buf)
14    }
15
16    // const since 1.55
17    pub const fn as_str(&self) -> &str {
18        unsafe { core::str::from_utf8_unchecked(&self.0) }
19    }
20
21    pub const fn as_bytes(&self) -> &[u8] {
22        &self.0
23    }
24
25    pub const fn from_str(s: &str) -> Self {
26        let buf = crate::bytes::clone::<N>(s.as_bytes());
27        unsafe { Self::new_unchecked(buf) }
28    }
29}
30
31/// Converts a byte string to a string slice
32///
33/// This macro is [const-context only](./index.html#const-context-only).
34///
35/// # Examples
36/// ```
37/// const BYTE_PATH: &[u8] = b"/tmp/file";
38/// const PATH: &str = const_str::from_utf8!(BYTE_PATH);
39///
40/// assert_eq!(PATH, "/tmp/file");
41/// ```
42///
43#[macro_export]
44macro_rules! from_utf8 {
45    ($s: expr) => {{
46        use ::core::primitive::str;
47        // const since 1.63
48        const OUTPUT: &str = match ::core::str::from_utf8($s) {
49            Ok(s) => s,
50            Err(_) => panic!("invalid utf-8 bytes"),
51        };
52        OUTPUT
53    }};
54}