morethantext/src/client.rs

101 lines
1.8 KiB
Rust
Raw Normal View History

2025-03-27 07:18:19 -04:00
use std::{
sync::mpsc::{channel, Receiver, Sender},
thread::spawn,
};
pub struct Request {
tx: Sender<Reply>,
}
impl Request {
pub fn new(tx: Sender<Reply>) -> Self {
Self { tx: tx }
}
fn get_sender(&self) -> &Sender<Reply> {
&self.tx
}
}
#[cfg(test)]
mod requests {
use super::*;
use replies::create_reply;
pub fn create_request() -> (Request, Receiver<Reply>) {
let (tx, rx) = channel();
let req = Request::new(tx);
(req, rx)
}
#[test]
fn new_request() {
let (tx, rx) = channel();
let req = Request::new(tx);
let sender = req.get_sender();
sender.send(create_reply()).unwrap();
rx.recv().unwrap();
}
}
pub struct Reply;
impl Reply {
pub fn get_session(&self) -> String {
"id".to_string()
}
pub fn get_content(&self) -> String {
"Something goes here.".to_string()
}
}
#[cfg(test)]
mod replies {
use super::*;
pub fn create_reply() -> Reply {
Reply {}
}
}
pub struct Client {
rx: Receiver<Request>,
}
impl Client {
fn new(rx: Receiver<Request>) -> Self {
Self { rx: rx }
}
pub fn start() -> Sender<Request> {
let (tx, rx) = channel();
spawn(move || {
let client = Client::new(rx);
client.listen();
});
tx
}
fn listen(&self) {
loop {
let req = self.rx.recv().unwrap();
req.get_sender().send(Reply {}).unwrap();
}
}
}
#[cfg(test)]
mod clients {
use super::*;
use requests::create_request;
#[test]
fn start_client() {
let tx = Client::start();
let (req, rx) = create_request();
tx.send(req).unwrap();
rx.recv().unwrap();
}
}