Add initial driver implementation

This commit is contained in:
Sam W 2019-02-16 11:53:28 +00:00 committed by Sam Willcocks
parent 267a99d6b9
commit 6bc88ef6b0
3 changed files with 51 additions and 8 deletions

View File

@ -40,10 +40,9 @@ impl Adaptor for FakeAdaptor {
fn run(&mut self) -> Receiver<TallyState> {
println!("arse");
let (tx, rx): (Sender<TallyState>, Receiver<TallyState>) = mpsc::channel();
let thread_tx = tx.clone();
let thread_numchannels = self.numchannels.clone();
self.thread = Some(thread::spawn(move || {
FakeAdaptor::_run(thread_numchannels, thread_tx);
FakeAdaptor::_run(thread_numchannels, tx);
}));
return rx;
}

40
src/drivers.rs Normal file
View File

@ -0,0 +1,40 @@
use crate::TallyState;
use std::sync::mpsc;
use std::sync::mpsc::{Sender, Receiver};
use std::thread;
/// A Driver displays the Tallies on a physical tally system.
pub trait Driver {
/// Run the driver, returning a channel sender which takes TallyStates
fn run(&mut self) -> Sender<TallyState>;
}
pub struct FakeDriver {
thread: Option<thread::JoinHandle<()>>
}
impl Driver for FakeDriver {
fn run(&mut self) -> Sender<TallyState> {
let (tx, rx): (Sender<TallyState>, Receiver<TallyState>) = mpsc::channel();
self.thread = Some(thread::spawn(move || {
FakeDriver::_run(rx);
}));
return tx;
}
}
impl FakeDriver {
pub fn new() -> FakeDriver {
FakeDriver{
thread: None
}
}
fn _run(rx: Receiver<TallyState>) {
loop {
let state = rx.recv().unwrap();
println!("{}", state);
}
}
}

View File

@ -1,5 +1,7 @@
mod adaptors;
mod drivers;
use crate::adaptors::{Adaptor,FakeAdaptor};
use crate::drivers::{Driver, FakeDriver};
use std::fmt;
#[derive(Clone)]
@ -26,16 +28,17 @@ impl fmt::Display for TallyState {
}
}
struct Server<T:Adaptor> {
struct Server<T:Adaptor,U:Driver> {
adaptor: T,
driver: U,
}
impl<T:Adaptor> Server<T> {
impl<T:Adaptor,U:Driver> Server<T,U> {
fn run(&mut self) {
let rx = self.adaptor.run();
let tx = self.driver.run();
loop{
let newstate = rx.recv().unwrap();
println!("{}", newstate);
tx.send(rx.recv().unwrap()).unwrap();
}
}
}
@ -43,6 +46,7 @@ impl<T:Adaptor> Server<T> {
fn main() {
let mut s = Server{
adaptor: FakeAdaptor::new(8),
driver: FakeDriver::new(),
};
s.run();