Skip to main content

cuprate_p2p_core/client/
sync_callback.rs

1use std::{
2    fmt::{Debug, Formatter},
3    sync::Arc,
4};
5
6use cuprate_wire::CoreSyncData;
7
8/// Callbacks invoked when a peer's sync data changes or the peer disconnects.
9#[derive(Clone)]
10pub struct PeerSyncCallback {
11    on_sync: Arc<dyn Fn(&CoreSyncData) + Send + Sync>,
12    on_disconnect: Arc<dyn Fn() + Send + Sync>,
13}
14
15impl PeerSyncCallback {
16    /// Create a new [`PeerSyncCallback`].
17    pub fn new(
18        on_sync: impl Fn(&CoreSyncData) + Send + Sync + 'static,
19        on_disconnect: impl Fn() + Send + Sync + 'static,
20    ) -> Self {
21        Self {
22            on_sync: Arc::new(on_sync),
23            on_disconnect: Arc::new(on_disconnect),
24        }
25    }
26
27    /// Call the callback with the peer's [`CoreSyncData`].
28    pub fn call(&self, data: &CoreSyncData) {
29        (self.on_sync)(data);
30    }
31
32    /// Notify the callback that the peer disconnected.
33    pub(crate) fn disconnected(&self) {
34        (self.on_disconnect)();
35    }
36}
37
38impl Debug for PeerSyncCallback {
39    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
40        f.write_str("PeerSyncCallback")
41    }
42}