imservice: Use TryFrom for u32->enum conversions

This commit is contained in:
Dorota Czaplejewicz
2019-07-31 09:59:25 +00:00
parent 58d01bf502
commit 98a2e33d78

View File

@ -5,6 +5,10 @@ use std::string::String;
use super::bitflags; use super::bitflags;
// Traits
use std::convert::TryFrom;
/// Gathers stuff defined in C or called by C /// Gathers stuff defined in C or called by C
pub mod c { pub mod c {
use super::*; use super::*;
@ -108,8 +112,8 @@ pub mod c {
}) })
}, },
content_purpose: { content_purpose: {
ContentPurpose::from_num(purpose).unwrap_or_else(|| { ContentPurpose::try_from(purpose).unwrap_or_else(|_e| {
eprintln!("Warning: Received invalid purpose flags"); eprintln!("Warning: Received invalid purpose value");
ContentPurpose::Normal ContentPurpose::Normal
}) })
}, },
@ -126,8 +130,8 @@ pub mod c {
let imservice = &mut *imservice; let imservice = &mut *imservice;
imservice.pending = IMProtocolState { imservice.pending = IMProtocolState {
text_change_cause: { text_change_cause: {
ChangeCause::from_num(cause).unwrap_or_else(|| { ChangeCause::try_from(cause).unwrap_or_else(|_e| {
eprintln!("Warning: received invalid cause flags"); eprintln!("Warning: received invalid cause value");
ChangeCause::InputMethod ChangeCause::InputMethod
}) })
}, },
@ -222,25 +226,28 @@ pub enum ContentPurpose {
Terminal = 13, Terminal = 13,
} }
impl ContentPurpose { impl TryFrom<u32> for ContentPurpose {
fn from_num(num: u32) -> Option<ContentPurpose> { // There's only one way to fail: number not in protocol,
// so no special error type is needed
type Error = ();
fn try_from(num: u32) -> Result<Self, Self::Error> {
use self::ContentPurpose::*; use self::ContentPurpose::*;
match num { match num {
0 => Some(Normal), 0 => Ok(Normal),
1 => Some(Alpha), 1 => Ok(Alpha),
2 => Some(Digits), 2 => Ok(Digits),
3 => Some(Number), 3 => Ok(Number),
4 => Some(Phone), 4 => Ok(Phone),
5 => Some(Url), 5 => Ok(Url),
6 => Some(Email), 6 => Ok(Email),
7 => Some(Name), 7 => Ok(Name),
8 => Some(Password), 8 => Ok(Password),
9 => Some(Pin), 9 => Ok(Pin),
10 => Some(Date), 10 => Ok(Date),
11 => Some(Time), 11 => Ok(Time),
12 => Some(Datetime), 12 => Ok(Datetime),
13 => Some(Terminal), 13 => Ok(Terminal),
_ => None, _ => Err(()),
} }
} }
} }
@ -252,12 +259,15 @@ pub enum ChangeCause {
Other = 1, Other = 1,
} }
impl ChangeCause { impl TryFrom<u32> for ChangeCause {
pub fn from_num(num: u32) -> Option<ChangeCause> { // There's only one way to fail: number not in protocol,
// so no special error type is needed
type Error = ();
fn try_from(num: u32) -> Result<Self, Self::Error> {
match num { match num {
0 => Some(ChangeCause::InputMethod), 0 => Ok(ChangeCause::InputMethod),
1 => Some(ChangeCause::Other), 1 => Ok(ChangeCause::Other),
_ => None _ => Err(())
} }
} }
} }