@@ -19,7 +19,7 @@ use char_private::is_printable;
1919use convert:: TryFrom ;
2020use fmt:: { self , Write } ;
2121use slice;
22- use str:: from_utf8_unchecked_mut;
22+ use str:: { from_utf8_unchecked_mut, FromStr } ;
2323use iter:: FusedIterator ;
2424use mem:: transmute;
2525
@@ -208,6 +208,63 @@ impl From<u8> for char {
208208 }
209209}
210210
211+
212+ /// An error which can be returned when parsing a char.
213+ #[ stable( feature = "char_from_str" , since = "1.19.0" ) ]
214+ #[ derive( Clone , Debug ) ]
215+ pub struct ParseCharError {
216+ kind : CharErrorKind ,
217+ }
218+
219+ impl ParseCharError {
220+ #[ unstable( feature = "char_error_internals" ,
221+ reason = "this method should not be available publicly" ,
222+ issue = "0" ) ]
223+ #[ doc( hidden) ]
224+ pub fn __description ( & self ) -> & str {
225+ match self . kind {
226+ CharErrorKind :: EmptyString => {
227+ "cannot parse char from empty string"
228+ } ,
229+ CharErrorKind :: TooManyChars => "too many characters in string"
230+ }
231+ }
232+ }
233+
234+ #[ derive( Copy , Clone , Debug , PartialEq , Eq ) ]
235+ enum CharErrorKind {
236+ EmptyString ,
237+ TooManyChars ,
238+ }
239+
240+ #[ stable( feature = "char_from_str" , since = "1.19.0" ) ]
241+ impl fmt:: Display for ParseCharError {
242+ fn fmt ( & self , f : & mut fmt:: Formatter ) -> fmt:: Result {
243+ self . __description ( ) . fmt ( f)
244+ }
245+ }
246+
247+
248+ #[ stable( feature = "char_from_str" , since = "1.19.0" ) ]
249+ impl FromStr for char {
250+ type Err = ParseCharError ;
251+
252+ #[ inline]
253+ fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
254+ let mut chars = s. chars ( ) ;
255+ match ( chars. next ( ) , chars. next ( ) ) {
256+ ( None , _) => {
257+ Err ( ParseCharError { kind : CharErrorKind :: EmptyString } )
258+ } ,
259+ ( Some ( c) , None ) => Ok ( c) ,
260+ _ => {
261+ Err ( ParseCharError { kind : CharErrorKind :: TooManyChars } )
262+ }
263+ }
264+ }
265+ }
266+
267+
211268#[ unstable( feature = "try_from" , issue = "33417" ) ]
212269impl TryFrom < u32 > for char {
213270 type Error = CharTryFromError ;
0 commit comments