Skip to main content

core/array/
ascii.rs

1use crate::ascii;
2
3impl<const N: usize> [u8; N] {
4    /// Converts this array of bytes into an array of ASCII characters,
5    /// or returns `None` if any of the characters is non-ASCII.
6    ///
7    /// # Examples
8    ///
9    /// ```
10    /// #![feature(ascii_char)]
11    ///
12    /// const HEX_DIGITS: [std::ascii::Char; 16] =
13    ///     *b"0123456789abcdef".as_ascii().unwrap();
14    ///
15    /// assert_eq!(HEX_DIGITS[1].as_str(), "1");
16    /// assert_eq!(HEX_DIGITS[10].as_str(), "a");
17    /// ```
18    #[unstable(feature = "ascii_char", issue = "110998")]
19    #[must_use]
20    #[inline]
21    #[ferrocene::prevalidated]
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    #[ferrocene::prevalidated]
41    pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char; N] {
42        let byte_ptr: *const [u8; N] = self;
43        let ascii_ptr = byte_ptr as *const [ascii::Char; N];
44        // SAFETY: The caller promised all the bytes are ASCII
45        unsafe { &*ascii_ptr }
46    }
47}