You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.1 KiB
Rust

use async_std::sync::{Arc, Mutex};
use crate::bus::{Request, RequestEnvelope, ResponseEnvelope};
use std::fmt::{Debug, Formatter, Error};
#[async_trait]
pub trait RawBusClient: Send {
async fn send(&mut self, request: RequestEnvelope) -> ResponseEnvelope;
}
#[derive(Clone)]
pub struct BusClient(Arc<Mutex<BusClientState>>);
impl Debug for BusClient {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(f, "BusClient()")
}
}
pub struct BusClientState {
id: u64,
raw_client: Box<dyn RawBusClient>,
}
impl BusClient {
pub fn new(raw_client: Box<dyn RawBusClient>) -> BusClient {
BusClient(Arc::new(Mutex::new(
BusClientState {
id: 0,
raw_client,
}
)))
}
pub async fn send(&mut self, request: Request) -> ResponseEnvelope {
let mut state = self.0.lock().await;
let id = state.id;
state.id += 1;
let envelope = RequestEnvelope {
id,
request,
};
state.raw_client.send(envelope).await
}
}