@@ -660,55 +660,35 @@ impl IntoLua for char {
660
660
fn into_lua ( self , lua : & Lua ) -> Result < Value > {
661
661
let mut char_bytes = [ 0 ; 4 ] ;
662
662
self . encode_utf8 ( & mut char_bytes) ;
663
- Ok ( Value :: String ( lua. create_string ( char_bytes) ?) )
663
+ Ok ( Value :: String ( lua. create_string ( & char_bytes[ .. self . len_utf8 ( ) ] ) ?) )
664
664
}
665
665
}
666
666
667
667
impl FromLua for char {
668
- #[ inline]
669
668
fn from_lua ( value : Value , _lua : & Lua ) -> Result < Self > {
670
669
let ty = value. type_name ( ) ;
671
670
match value {
672
- // When integer: reduce it to u8 and try to convert to char
673
671
Value :: Integer ( i) => {
674
- if i <= u8:: MAX . into ( ) && i >= 0 {
675
- Ok ( char:: from ( i as u8 ) )
676
- } else {
677
- Err ( Error :: FromLuaConversionError {
672
+ cast ( i)
673
+ . and_then ( char:: from_u32)
674
+ . ok_or_else ( || Error :: FromLuaConversionError {
678
675
from : ty,
679
- to : Self :: type_name ( ) ,
680
- message : Some (
681
- "expected int to be a u8 when converting to char. You can also use strings."
682
- . to_string ( ) ,
683
- ) ,
676
+ to : "char" . to_string ( ) ,
677
+ message : Some ( "integer out of range when converting to char" . to_string ( ) ) ,
684
678
} )
685
- }
686
679
}
687
- // When String: first char, and only if there is one char
688
680
Value :: String ( s) => {
689
681
let str = s. to_str ( ) ?;
690
682
let mut str_iter = str. chars ( ) ;
691
- let Some ( char) = str_iter. next ( ) else {
692
- return Err ( Error :: FromLuaConversionError {
683
+ match ( str_iter. next ( ) , str_iter. next ( ) ) {
684
+ ( Some ( char) , None ) => Ok ( char) ,
685
+ _ => Err ( Error :: FromLuaConversionError {
693
686
from : ty,
694
- to : Self :: type_name ( ) ,
687
+ to : "char" . to_string ( ) ,
695
688
message : Some (
696
- "string must have one char when converting to char. (empty string) " . to_string ( ) ,
689
+ "expected string to have exactly one char when converting to char" . to_string ( ) ,
697
690
) ,
698
- } ) ;
699
- } ;
700
-
701
- if let Some ( _extra_char) = str_iter. next ( ) {
702
- Err ( Error :: FromLuaConversionError {
703
- from : ty,
704
- to : Self :: type_name ( ) ,
705
- message : Some (
706
- "expected lua string to have exactly one char when converting to char"
707
- . to_string ( ) ,
708
- ) ,
709
- } )
710
- } else {
711
- Ok ( char)
691
+ } ) ,
712
692
}
713
693
}
714
694
_ => Err ( Error :: FromLuaConversionError {
0 commit comments