Skip to content

Commit a67a5c3

Browse files
committed
Add AsciiChar::try_new()
1 parent 1ba5396 commit a67a5c3

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/ascii_char.rs

+26
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)