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 pub const fn as_ascii(&self) -> Option<&[ascii::Char; N]> {
22 if self.is_ascii() {
23 // SAFETY: Just checked that it's ASCII
24 Some(unsafe { self.as_ascii_unchecked() })
25 } else {
26 None
27 }
28 }
29
30 /// Converts this array of bytes into an array of ASCII characters,
31 /// without checking whether they're valid.
32 ///
33 /// # Safety
34 ///
35 /// Every byte in the array must be in `0..=127`, or else this is UB.
36 #[unstable(feature = "ascii_char", issue = "110998")]
37 #[must_use]
38 #[inline]
39 pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char; N] {
40 let byte_ptr: *const [u8; N] = self;
41 let ascii_ptr = byte_ptr as *const [ascii::Char; N];
42 // SAFETY: The caller promised all the bytes are ASCII
43 unsafe { &*ascii_ptr }
44 }
45}