Skip to content

Commit 41d4a00

Browse files
committed
Add AsciiChar::try_new()
1 parent 43ba1a3 commit 41d4a00

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/ascii_char.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,32 @@ impl AsciiChar {
360360
ALL[ch as usize]
361361
}
362362

363+
/// Create an `AsciiChar` from a `char`, in a `const fn` way.
364+
///
365+
/// Within non-`const fn` functions the more general
366+
/// [`from_ascii()`](#method.from_ascii) should be used instead.
367+
///
368+
/// # Examples
369+
/// ```
370+
/// # use ascii::AsciiChar;
371+
/// assert!(AsciiChar::try_new('-').is_ok());
372+
/// assert!(AsciiChar::try_new('—').is_err());
373+
/// assert_eq!(AsciiChar::try_new('\x7f'), Ok(AsciiChar::DEL));
374+
/// ```
375+
///
376+
/// # Errors
377+
///
378+
/// Fails for non-ASCII characters.
379+
#[inline]
380+
pub const fn try_new(ch: char) -> Result<Self, ToAsciiCharError> {
381+
unsafe {
382+
match ch as u32 {
383+
0..=127 => Ok(mem::transmute(ch as u8)),
384+
_ => Err(ToAsciiCharError(())),
385+
}
386+
}
387+
}
388+
363389
/// Constructs an ASCII character from a `u8`, `char` or other character
364390
/// type without any checks.
365391
///

0 commit comments

Comments
 (0)
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