use crate::DeltaPack;
pub struct SyncSession<T: DeltaPack + Clone> {
view: Option<T>,
}
impl<T: DeltaPack + Clone> SyncSession<T> {
pub fn new() -> Self {
Self { view: None }
}
pub fn encode(&mut self, state: &T) -> Vec<u8> {
match &self.view {
None => {
let bytes = state.encode();
self.view = Some(state.clone());
bytes
}
Some(view) => {
let bytes = T::encode_diff(view, state);
self.view = Some(T::decode_diff(view, &bytes));
bytes
}
}
}
pub fn decode(&mut self, bytes: &[u8]) -> &T {
self.view = Some(match &self.view {
None => T::decode(bytes),
Some(view) => T::decode_diff(view, bytes),
});
self.view.as_ref().expect("view just assigned")
}
pub fn current(&self) -> Option<&T> {
self.view.as_ref()
}
}
impl<T: DeltaPack + Clone> Default for SyncSession<T> {
fn default() -> Self {
Self::new()
}
}