Skip to content

adds AsciiChar::as_str() #104

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/ascii_char.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down