core/array/
ascii.rs

1use crate::ascii;
2
3#[cfg(not(test))]
4impl<const N: usize> [u8; N] {
5    /// Converts this array of bytes into an array of ASCII characters,
6    /// or returns `None` if any of the characters is non-ASCII.
7    ///
8    /// # Examples
9    ///
10    /// ```
11    /// #![feature(ascii_char)]
12    ///
13    /// const HEX_DIGITS: [std::ascii::Char; 16] =
14    ///     *b"0123456789abcdef".as_ascii().unwrap();
15    ///
16    /// assert_eq!(HEX_DIGITS[1].as_str(), "1");
17    /// assert_eq!(HEX_DIGITS[10].as_str(), "a");
18    /// ```
19    #[unstable(feature = "ascii_char", issue = "110998")]
20    #[must_use]
21    #[inline]
22    pub const fn as_ascii(&self) -> Option<&[ascii::Char; N]> {
23        if self.is_ascii() {
24            // SAFETY: Just checked that it's ASCII
25            Some(unsafe { self.as_ascii_unchecked() })
26        } else {
27            None
28        }
29    }
30
31    /// Converts this array of bytes into an array of ASCII characters,
32    /// without checking whether they're valid.
33    ///
34    /// # Safety
35    ///
36    /// Every byte in the array must be in `0..=127`, or else this is UB.
37    #[unstable(feature = "ascii_char", issue = "110998")]
38    #[must_use]
39    #[inline]
40    pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char; N] {
41        let byte_ptr: *const [u8; N] = self;
42        let ascii_ptr = byte_ptr as *const [ascii::Char; N];
43        // SAFETY: The caller promised all the bytes are ASCII
44        unsafe { &*ascii_ptr }
45    }
46}