From 7e8ee5ed9cad6484e9f13f81731b102ced58402e Mon Sep 17 00:00:00 2001 From: Adam Carpenter Date: Tue, 9 Jul 2019 15:14:04 -0400 Subject: Init. --- meap/meap-code/ch4/ch4-short-lived-strategy.rs | 82 ++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100755 meap/meap-code/ch4/ch4-short-lived-strategy.rs (limited to 'meap/meap-code/ch4/ch4-short-lived-strategy.rs') diff --git a/meap/meap-code/ch4/ch4-short-lived-strategy.rs b/meap/meap-code/ch4/ch4-short-lived-strategy.rs new file mode 100755 index 0000000..1082469 --- /dev/null +++ b/meap/meap-code/ch4/ch4-short-lived-strategy.rs @@ -0,0 +1,82 @@ +#![allow(unused_variables)] + +#[derive(Debug)] +struct CubeSat { + id: u64, +} + +#[derive(Debug)] +struct Mailbox { + messages: Vec, +} + +#[derive(Debug)] +struct Message { + to: u64, + content: String, +} + +struct GroundStation {} + +impl Mailbox { + fn post(&mut self, msg: Message) { + self.messages.push(msg); + } + + fn deliver(&mut self, recipient: &CubeSat) -> Option { + for i in 0..self.messages.len() { + if self.messages[i].to == recipient.id { + let msg = self.messages.remove(i); + return Some(msg); + } + } + + None + } +} + +impl GroundStation { + fn connect(&self, sat_id: u64) -> CubeSat { + CubeSat { + id: sat_id, + } + } + + fn send(&self, mailbox: &mut Mailbox, msg: Message) { + mailbox.post(msg); + } +} + +impl CubeSat { + fn recv(&self, mailbox: &mut Mailbox) -> Option { + mailbox.deliver(&self) + } +} + +fn fetch_sat_ids() -> Vec { + vec![1,2,3] +} + + +fn main() { + let mut mail = Mailbox { messages: vec![] }; + + let base = GroundStation {}; + + let sat_ids = fetch_sat_ids(); + + for sat_id in sat_ids { + let sat = base.connect(sat_id); + let msg = Message { to: sat_id, content: String::from("hello") }; + base.send(&mut mail, msg); + } + + let sat_ids = fetch_sat_ids(); + + for sat_id in sat_ids { + let sat = base.connect(sat_id); + + let msg = sat.recv(&mut mail); + println!("{:?}: {:?}", sat, msg); + } +} \ No newline at end of file -- cgit v1.2.3