From 434d23ab06cc5fe6028482fbe78c910d18067427 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20L=C3=B8vbr=C3=B8tte=20Olsen?= Date: Thu, 26 Mar 2020 21:55:13 +0100 Subject: [PATCH] use a hashmap --- src/main.rs | 28 ++++++++++++++++++++-------- src/workunit.rs | 4 ++-- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/main.rs b/src/main.rs index 1392fa5..89dfb1c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,9 +6,12 @@ use rocket::response::status::NotFound; use rocket_contrib::json::Json; use serde_json::Value; +use serde_json::json; +use serde::{Serialize, Deserialize}; use rocket_contrib::uuid::Uuid; use std::sync::Mutex; +use std::collections::HashMap; mod workunit; use workunit::WUnit; @@ -18,7 +21,7 @@ const VERSION: &str = "0.1.0"; #[derive(Default, Debug)] struct SharedState { - list: Mutex> + jobs: Mutex> } #[get("/")] @@ -33,15 +36,21 @@ fn version() -> &'static str { #[get("/get_jobs")] fn get_jobs(shared: State) -> Json { - let list = shared.list.lock().unwrap(); - Json(serde_json::to_value(&list[..]).unwrap()) + let list = shared.jobs.lock().unwrap().clone(); + + println!("{:#?}", list); + + //Json(json!("god hlep me")) + Json(serde_json::to_value(&list).unwrap()) } #[get("/request_job")] fn request_job(shared: State) -> Result, NotFound> { - let mut list = shared.list.lock().unwrap().clone(); + let mut list: Vec = shared.jobs.lock().unwrap() + .values().cloned() + .filter(|x| x.status == EStatus::Queued) + .collect(); - list.retain(|x| x.status == EStatus::Queued); list.sort_by(|a, b| b.description.length.cmp(&a.description.length)); let job = list.get(0); @@ -51,9 +60,9 @@ fn request_job(shared: State) -> Result, NotFound")] fn get_job(id: Uuid, shared: State) -> Result, NotFound> { - let list = shared.list.lock().unwrap().clone(); + let list = shared.jobs.lock().unwrap(); - let job = list.into_iter().find(|x| x.id == *id).ok_or(NotFound(format!("Job not Found: {id}", id = id))); + let job = list.get(&id).ok_or(NotFound(format!("Job not Found: {id}", id = id))); match job { Ok(j) => Ok(Json(serde_json::to_value(&j).unwrap())), @@ -65,7 +74,10 @@ fn get_job(id: Uuid, shared: State) -> Result, NotFound fn add_job(message: Json, shared: State) -> Result { println!("{:#?}", message); let job = message.into_inner(); - shared.list.lock().unwrap().push(WUnit::new(job)); + + let id = uuid::Uuid::new_v4(); + + shared.jobs.lock().unwrap().insert(id, WUnit::new(id, job)); Ok(format!("{:#?}", shared)) } diff --git a/src/workunit.rs b/src/workunit.rs index 3d61dab..dfb4588 100644 --- a/src/workunit.rs +++ b/src/workunit.rs @@ -8,9 +8,9 @@ pub struct WUnit { pub status: EStatus } impl WUnit { - pub fn new(description: WDesc) -> Self { + pub fn new(id: Uuid, description: WDesc) -> Self { WUnit { - id: Uuid::new_v4(), + id: id, description: description, status: EStatus::Queued }