@@ -19,7 +19,7 @@ use char_private::is_printable;
19
19
use convert:: TryFrom ;
20
20
use fmt:: { self , Write } ;
21
21
use slice;
22
- use str:: from_utf8_unchecked_mut;
22
+ use str:: { from_utf8_unchecked_mut, FromStr } ;
23
23
use iter:: FusedIterator ;
24
24
use mem:: transmute;
25
25
@@ -208,6 +208,63 @@ impl From<u8> for char {
208
208
}
209
209
}
210
210
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
+
211
268
#[ unstable( feature = "try_from" , issue = "33417" ) ]
212
269
impl TryFrom < u32 > for char {
213
270
type Error = CharTryFromError ;
0 commit comments