1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
use crate::ascii;
#[cfg(not(test))]
impl<const N: usize> [u8; N] {
/// 将此字节数组转换为 ASCII 字符数组,如果任何字符为非 ASCII,则返回 `None`。
///
///
/// # Examples
///
/// ```
/// #![feature(ascii_char)]
/// #![feature(const_option)]
///
/// const HEX_DIGITS: [std::ascii::Char; 16] =
/// *b"0123456789abcdef".as_ascii().unwrap();
///
/// assert_eq!(HEX_DIGITS[1].as_str(), "1");
/// assert_eq!(HEX_DIGITS[10].as_str(), "a");
/// ```
#[unstable(feature = "ascii_char", issue = "110998")]
#[must_use]
#[inline]
pub const fn as_ascii(&self) -> Option<&[ascii::Char; N]> {
if self.is_ascii() {
// SAFETY: 刚刚检查它是 ASCII
Some(unsafe { self.as_ascii_unchecked() })
} else {
None
}
}
/// 将此字节数组转换为 ASCII 字符数组,而不检查它们是否有效。
///
///
/// # Safety
///
/// 数组中的每个字节都必须在 `0..=127` 中,否则就是 UB。
#[unstable(feature = "ascii_char", issue = "110998")]
#[must_use]
#[inline]
pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char; N] {
let byte_ptr: *const [u8; N] = self;
let ascii_ptr = byte_ptr as *const [ascii::Char; N];
// SAFETY: 调用者承诺所有字节都是 ASCII
unsafe { &*ascii_ptr }
}
}