From e40c337a28c4507a043973bdd1f06bca6cce0269 Mon Sep 17 00:00:00 2001 From: Max Audron Date: Sun, 25 Jul 2021 17:43:15 +0200 Subject: add Traits for syncable objects --- src/message/signalproxy/mod.rs | 80 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) (limited to 'src/message/signalproxy/mod.rs') diff --git a/src/message/signalproxy/mod.rs b/src/message/signalproxy/mod.rs index 2887407..b06bcee 100644 --- a/src/message/signalproxy/mod.rs +++ b/src/message/signalproxy/mod.rs @@ -1,4 +1,11 @@ -use crate::{deserialize::Deserialize, serialize::Serialize}; +use std::convert::TryInto; + +use crate::{ + deserialize::Deserialize, + primitive::{VariantList, VariantMap}, + serialize::Serialize, + session::Session, +}; use num_derive::{FromPrimitive, ToPrimitive}; @@ -18,6 +25,77 @@ pub use initrequest::*; pub use rpccall::*; pub use syncmessage::*; +/// SyncProxy sends sync and rpc messages +pub trait SyncProxy: Session { + fn sync( + &self, + class_name: &str, + object_name: Option<&str>, + function: &str, + params: VariantList, + ); + + /// Send a RpcCall + fn rpc(&self, function: &str, params: VariantList); +} + +/// A base Syncable Object +pub trait Syncable { + /// Send a SyncMessage. + /// + /// Must implement a call to session.sync() that sets the class and object names + /// + /// Example: + /// ```ignore + /// impl Syncable for AliasManager { + /// fn sync(&self, session: impl SyncProxy, function: &str, params: VariantList) { + /// session.sync("AliasManager", None, function, params) + /// } + /// } + /// ``` + fn sync(&self, session: impl SyncProxy, function: &str, params: VariantList); + + /// Send a RpcCall + fn rpc(&self, session: impl SyncProxy, function: &str, params: VariantList) { + session.rpc(function, params); + } +} + +// TODO handle client vs server with feature flag +/// A Stateful Syncable Object +#[allow(unused_variables)] +pub trait StatefulSyncable: Syncable { + /// Client -> Server: Update the whole object with received data + fn update(&mut self, session: impl SyncProxy, params: VariantMap) + where + Self: Sized + From, + { + #[cfg(feature = "client")] + { + self.sync(session, "update", vec![params.into()]); + } + #[cfg(feature = "server")] + { + *self = params.try_into().unwrap(); + } + } + + /// Server -> Client: Update the whole object with received data + fn request_update(&mut self, session: impl SyncProxy, params: VariantMap) + where + Self: Sized + From, + { + #[cfg(feature = "client")] + { + *self = params.try_into().unwrap(); + } + #[cfg(feature = "server")] + { + self.sync(session, "requestUpdate", vec![params.into()]); + } + } +} + #[derive(Clone, Debug, std::cmp::PartialEq)] pub enum Message { /// Bidirectional -- cgit v1.2.3