diff --git a/src/main.rs b/src/main.rs index 7c2179578c53a10ea943623c6737baf45a257d77..24cc811e90b3f15d5ff146bb8b20b91310617237 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,4 @@ use rocket::{get, launch, post, routes, serde::json::Json}; -use serde::{Deserialize, Serialize}; const INDEX_TEXT: &str = r#"\ Cette application permet d'executer des calculs simple. @@ -30,16 +29,8 @@ Pour envoyer une requĂȘte avec curl: curl -X POST http://monurl -H 'Content-Type: application/json' -d '{"Plus", [3, 4]}' "#; -#[derive(Serialize, Deserialize, Copy, Clone, Debug)] -enum Operation { - Plus(i32,i32), -} - -#[derive(Deserialize, Serialize, PartialEq, Debug)] -struct OperationResult { - operation: String, - resultat: i32, -} +mod operations; +use operations::{Operation, OperationResult}; #[get("/")] fn index() -> &'static str { @@ -48,12 +39,7 @@ fn index() -> &'static str { #[post("/", data = "<operation>")] fn do_calc(operation: Json<Operation>) -> Json<OperationResult> { - match operation.into_inner() { - Operation::Plus(op1, op2) => OperationResult { - operation: format!("{op1} + {op2}"), - resultat: op1 + op2, - }.into() - } + OperationResult::from(operation.into_inner()).into() } #[get("/test")] @@ -91,10 +77,7 @@ mod tests { let response = req.dispatch(); assert_eq!(response.status(), Status::Ok); - let expected = OperationResult { - operation: "3 + 8".into(), - resultat: 11, - }; + let expected = OperationResult::new("3 + 8", 11); assert_eq!(response.into_json::<OperationResult>().unwrap(), expected); } } diff --git a/src/operations.rs b/src/operations.rs new file mode 100644 index 0000000000000000000000000000000000000000..45644e7ced43f8ed212726b097154415d992cd50 --- /dev/null +++ b/src/operations.rs @@ -0,0 +1,59 @@ +//! This modules defines the possible operation and provide methods +//! to do the actual computation + +use serde::{Deserialize, Serialize}; + + +#[derive(Serialize, Deserialize, Copy, Clone, Debug)] +pub enum Operation { + Plus(i32,i32), +} + +#[derive(Deserialize, Serialize, PartialEq, Debug)] +pub struct OperationResult { + operation: String, + resultat: i32, +} + +impl OperationResult { + /// Creates a new operation result from a [`&str`] and a value. + pub fn new(s: &str, value: i32) -> Self { + Self { + operation: String::from(s), + resultat: value, + } + } +} + +impl From<&Operation> for OperationResult { + fn from(value: &Operation) -> Self { + match value { + Operation::Plus(op1, op2) => OperationResult { + operation: format!("{op1} + {op2}"), + resultat: op1 + op2, + } + } + } +} + +impl From<Operation> for OperationResult { + fn from(value: Operation) -> Self { + OperationResult::from(&value) + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plus() { + let operation = Operation::Plus(4, 5); + let result = OperationResult::from(operation); + let expected = OperationResult::new("4 + 5", 9); + + assert_eq!(result, expected); + } + +}