diff --git a/src/ascii_char.rs b/src/ascii_char.rs index 39f2ceb..a9a529e 100644 --- a/src/ascii_char.rs +++ b/src/ascii_char.rs @@ -431,6 +431,18 @@ impl AsciiChar { self as u8 as char } + /// Converts an ASCII character into a `&str`. + #[inline] + pub const fn as_str(&self) -> &str { + unsafe { + // SAFETY: Self is repr(u8) so casting *const Self to *const u8 is valid, + // and casting a *const T to *const [T; 1] is always valid (see core::array::from_ref). + let slice = &*(self as *const Self as *const [u8; 1]); + // SAFETY: an ASCII char is always valid UTF-8 + core::str::from_utf8_unchecked(slice) + } + } + // the following methods are like ctype, and the implementation is inspired by musl. // The ascii_ methods take self by reference for maximum compatibility // with the corresponding methods on u8 and char. @@ -999,6 +1011,11 @@ mod tests { assert_eq!(AsciiChar::A.as_char(), 'A'); } + #[test] + fn as_str() { + assert_eq!(AsciiChar::A.as_str(), "A"); + } + #[test] fn new_array_is_correct() { for byte in 0..128_u8 { pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy