ouisync/network/
peer_source.rs

1use num_enum::{IntoPrimitive, TryFromPrimitive};
2use ouisync_macros::api;
3use serde::{Deserialize, Serialize};
4use std::fmt;
5
6/// How was the peer discovered.
7#[derive(
8    Clone,
9    Copy,
10    Debug,
11    Eq,
12    PartialEq,
13    Ord,
14    PartialOrd,
15    Serialize,
16    Deserialize,
17    IntoPrimitive,
18    TryFromPrimitive,
19)]
20#[repr(u8)]
21#[serde(into = "u8", try_from = "u8")]
22#[api]
23pub enum PeerSource {
24    /// Explicitly added by the user.
25    UserProvided = 0,
26    /// Peer connected to us.
27    Listener = 1,
28    /// Discovered on the Local Discovery.
29    LocalDiscovery = 2,
30    /// Discovered on the DHT.
31    Dht = 3,
32    /// Discovered on the Peer Exchange.
33    PeerExchange = 4,
34}
35
36impl PeerSource {
37    pub(super) fn direction(&self) -> ConnectionDirection {
38        match self {
39            Self::Listener => ConnectionDirection::Incoming,
40            Self::UserProvided | Self::LocalDiscovery | Self::Dht | Self::PeerExchange => {
41                ConnectionDirection::Outgoing
42            }
43        }
44    }
45}
46
47impl fmt::Display for PeerSource {
48    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
49        match self {
50            PeerSource::Listener => write!(f, "incoming"),
51            PeerSource::UserProvided => write!(f, "outgoing (user provided)"),
52            PeerSource::LocalDiscovery => write!(f, "outgoing (locally discovered)"),
53            PeerSource::Dht => write!(f, "outgoing (found on DHT)"),
54            PeerSource::PeerExchange => write!(f, "outgoing (found on peer exchange)"),
55        }
56    }
57}
58
59#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize)]
60pub(super) enum ConnectionDirection {
61    /// Peer connected to us
62    Incoming,
63    /// We connected to the peer
64    Outgoing,
65}
66
67impl ConnectionDirection {
68    pub fn glyph(&self) -> char {
69        match self {
70            Self::Incoming => '↓',
71            Self::Outgoing => '↑',
72        }
73    }
74}