File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff 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 ///
You can’t perform that action at this time.
0 commit comments