Created
November 27, 2022 04:40
-
-
Save jayhuang75/0d48cf16822123df3df328da783ea05f to your computer and use it in GitHub Desktop.
mediator_coordinator.rs
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
// Coordinator is playing a mediator role which ensure the only place to | |
pub trait Coordinator { | |
fn arrival(&mut self, aircraft_id: &str) -> bool; | |
fn gate_available(&mut self) -> Option<i8>; | |
fn departure(&mut self, aircraft_id: &str); | |
} | |
impl Coordinator for Airport { | |
fn arrival(&mut self, aircraft_id: &str) -> bool { | |
/* | |
There is 3 condition to meet in order to let the aircraft arrival | |
1. get the available platform | |
1.1. update arrival aircraft_on_gate | |
1.2. update arrival update the gate available hashmaps | |
2. if not available then put the aircraft to the aircraft queue and denied the arrival | |
*/ | |
match self.gate_available() { | |
Some(gate_id) => { | |
println!("[{:?}] gate [{:?}] available for aircraft : {:?}", self.name, gate_id, aircraft_id); | |
self.aircraft_on_gate.insert(gate_id, aircraft_id.into()); | |
self.gates.entry(gate_id).and_modify(|available| *available = false ).or_insert(false); | |
return true; | |
}, | |
None => { | |
println!("[{:?}] no gate available for aircraft : {:?}", self.name, aircraft_id); | |
self.aircraft_queue.push_back(aircraft_id.into()); | |
return false | |
}, | |
} | |
} | |
fn gate_available(&mut self) -> Option<i8> { | |
/* | |
Iterate over the available platform and get the first available platform id | |
*/ | |
self.gates | |
.iter() | |
.find_map(|(gate_id, &val)| if val { Some(*gate_id) } else { None }) | |
} | |
fn departure(&mut self, aircraft_id: &str) { | |
/* | |
There are 3 steps for notification | |
1. get the aircraft gate_id from the aircraft_on_gate by the aircraft_id. | |
2. update the gates available by the gate_id. | |
3. get the first aircraft in the aircraft queue and go over the can_arrival verfication process. | |
*/ | |
let gate_id = self.aircraft_on_gate | |
.iter() | |
.find_map(|(gate_id, val)| if val== aircraft_id { Some(*gate_id) } else { None }).unwrap(); | |
self.gates.entry(gate_id).and_modify(|available| *available = true ).or_insert(true); | |
if let Some(next_aircraft_id) = self.aircraft_queue.pop_front() { | |
self.arrival(&next_aircraft_id); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment