Created
March 8, 2019 13:14
-
-
Save Vrixyz/50850b5a46a9e32c17b8baa136d3066f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Serialize, Deserialize, Debug)] | |
struct NewCardForm { | |
answer_0: String, | |
answer_1: String, | |
answer_2: String, | |
lie_index: i32, | |
targets: Vec<String>, | |
} | |
enum NewCardFormError { | |
Parse, | |
UnknownParameter, | |
LackingParameter, | |
} | |
impl<'f> rocket::request::FromForm<'f> for NewCardForm { | |
type Error = NewCardFormError; | |
fn from_form( | |
items: &mut rocket::request::FormItems<'f>, | |
strict: bool, | |
) -> Result<NewCardForm, NewCardFormError> { | |
let mut answer_0: Option<String> = None; | |
let mut answer_1: Option<String> = None; | |
let mut answer_2: Option<String> = None; | |
let mut lie_index: Option<i32> = None; | |
let mut targets: Vec<String> = vec![]; | |
for item in items { | |
match item.key.as_str() { | |
"answer_0" => { | |
answer_0 = Some(item.value.to_string()); | |
} | |
"answer_1" => { | |
answer_1 = Some(item.value.to_string()); | |
} | |
"answer_2" => { | |
answer_2 = Some(item.value.to_string()); | |
} | |
"lie_index" => { | |
if let Ok(value) = item.value.parse() { | |
lie_index = Some(value); | |
} else if strict { | |
return Err(NewCardFormError::Parse); | |
} | |
} | |
"targets" => { | |
targets.push(item.value.to_string()); | |
} | |
_ if strict => return Err(NewCardFormError::UnknownParameter), | |
_ => { /* allow extra value when not strict */ } | |
} | |
} | |
match (answer_0, answer_1, answer_2, lie_index) { | |
(Some(answer_0), Some(answer_1), Some(answer_2), Some(lie_index)) => Ok(NewCardForm { | |
answer_0, | |
answer_1, | |
answer_2, | |
lie_index, | |
targets, | |
}), | |
_ => Err(NewCardFormError::LackingParameter), | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment