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