2017-04-04 02:06:30 +00:00
|
|
|
#![feature(plugin, custom_derive)]
|
|
|
|
#![plugin(rocket_codegen)]
|
|
|
|
|
|
|
|
extern crate rocket;
|
|
|
|
|
|
|
|
use rocket::request::{FromForm, FromFormValue, FormItems};
|
|
|
|
use rocket::http::RawStr;
|
|
|
|
|
|
|
|
#[derive(Debug, PartialEq, FromForm)]
|
|
|
|
struct Form {
|
|
|
|
single: usize,
|
|
|
|
#[form(field = "camelCase")]
|
|
|
|
camel_case: String,
|
|
|
|
#[form(field = "TitleCase")]
|
|
|
|
title_case: String,
|
|
|
|
#[form(field = "type")]
|
|
|
|
field_type: isize,
|
|
|
|
#[form(field = "DOUBLE")]
|
|
|
|
double: String,
|
2017-08-03 00:37:20 +00:00
|
|
|
#[form(field = "a.b")]
|
|
|
|
dot: isize,
|
2017-04-04 02:06:30 +00:00
|
|
|
}
|
|
|
|
|
2017-06-18 08:59:22 +00:00
|
|
|
fn parse<'f, T: FromForm<'f>>(string: &'f str, strict: bool) -> Option<T> {
|
2017-04-04 02:06:30 +00:00
|
|
|
let mut items = FormItems::from(string);
|
2017-06-18 08:59:22 +00:00
|
|
|
let result = T::from_form(items.by_ref(), strict);
|
2017-04-04 02:06:30 +00:00
|
|
|
if !items.exhaust() {
|
|
|
|
panic!("Invalid form input.");
|
|
|
|
}
|
|
|
|
|
|
|
|
result.ok()
|
|
|
|
}
|
|
|
|
|
2017-06-18 08:59:22 +00:00
|
|
|
fn parse_strict<'f, T: FromForm<'f>>(string: &'f str) -> Option<T> {
|
|
|
|
parse(string, true)
|
|
|
|
}
|
|
|
|
|
2017-04-04 02:06:30 +00:00
|
|
|
fn main() {
|
|
|
|
let form_string = &[
|
|
|
|
"single=100", "camelCase=helloThere", "TitleCase=HiHi", "type=-2",
|
2017-08-03 00:37:20 +00:00
|
|
|
"DOUBLE=bing_bong", "a.b=123",
|
2017-04-04 02:06:30 +00:00
|
|
|
].join("&");
|
|
|
|
|
2017-06-18 08:59:22 +00:00
|
|
|
let form: Option<Form> = parse_strict(&form_string);
|
2017-04-04 02:06:30 +00:00
|
|
|
assert_eq!(form, Some(Form {
|
|
|
|
single: 100,
|
|
|
|
camel_case: "helloThere".into(),
|
|
|
|
title_case: "HiHi".into(),
|
|
|
|
field_type: -2,
|
2017-08-03 00:37:20 +00:00
|
|
|
double: "bing_bong".into(),
|
|
|
|
dot: 123,
|
2017-04-04 02:06:30 +00:00
|
|
|
}));
|
|
|
|
|
|
|
|
let form_string = &[
|
|
|
|
"single=100", "camel_case=helloThere", "TitleCase=HiHi", "type=-2",
|
2017-08-03 00:37:20 +00:00
|
|
|
"DOUBLE=bing_bong", "dot=123",
|
2017-04-04 02:06:30 +00:00
|
|
|
].join("&");
|
|
|
|
|
2017-06-18 08:59:22 +00:00
|
|
|
let form: Option<Form> = parse_strict(&form_string);
|
2017-04-04 02:06:30 +00:00
|
|
|
assert!(form.is_none());
|
|
|
|
}
|