mirror of
https://github.com/mainmatter/100-exercises-to-learn-rust
synced 2025-02-15 20:48:07 +01:00
![Jack Moffitt](/assets/img/avatar_default.png)
Some checks failed
CI / build (push) Has been cancelled
CI / formatter (push) Has been cancelled
66 lines
1.7 KiB
Rust
66 lines
1.7 KiB
Rust
use crate::data::{Ticket, TicketDraft};
|
|
use crate::store::{TicketId, TicketStore};
|
|
use std::sync::mpsc::{Receiver, Sender};
|
|
|
|
pub mod data;
|
|
pub mod store;
|
|
|
|
#[derive(Clone)]
|
|
// TODO: flesh out the client implementation.
|
|
pub struct TicketStoreClient {}
|
|
|
|
impl TicketStoreClient {
|
|
// Feel free to panic on all errors, for simplicity.
|
|
pub fn insert(&self, draft: TicketDraft) -> TicketId {
|
|
todo!()
|
|
}
|
|
|
|
pub fn get(&self, id: TicketId) -> Option<Ticket> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
pub fn launch() -> TicketStoreClient {
|
|
let (sender, receiver) = std::sync::mpsc::channel();
|
|
std::thread::spawn(move || server(receiver));
|
|
todo!()
|
|
}
|
|
|
|
// No longer public! This becomes an internal detail of the library now.
|
|
enum Command {
|
|
Insert {
|
|
draft: TicketDraft,
|
|
response_channel: Sender<TicketId>,
|
|
},
|
|
Get {
|
|
id: TicketId,
|
|
response_channel: Sender<Option<Ticket>>,
|
|
},
|
|
}
|
|
|
|
fn server(receiver: Receiver<Command>) {
|
|
let mut store = TicketStore::new();
|
|
loop {
|
|
match receiver.recv() {
|
|
Ok(Command::Insert {
|
|
draft,
|
|
response_channel,
|
|
}) => {
|
|
let id = store.add_ticket(draft);
|
|
let _ = response_channel.send(id);
|
|
}
|
|
Ok(Command::Get {
|
|
id,
|
|
response_channel,
|
|
}) => {
|
|
let ticket = store.get(id);
|
|
let _ = response_channel.send(ticket.cloned());
|
|
}
|
|
Err(_) => {
|
|
// There are no more senders, so we can safely break
|
|
// and shut down the server.
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|