1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use libp2p_core::Multiaddr;

/// Additional information about a peer.
#[derive(Clone, Debug)]
pub struct PeerInfo {
    /// The peer's address.
    pub address: Multiaddr,
    /// The peer's alias.
    pub alias: String,
    /// The type of relation regarding this peer.
    pub relation: PeerRelation,
}

/// Describes the relation with a peer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PeerRelation {
    /// Represents a persistent peer. If the connection to such a peer drops, the network will try to reconnect.
    Known,
    /// Represents an ephemeral peer. If the connection to such a peer drops, the network won't try to reconnect.
    Unknown,
}

impl PeerRelation {
    /// Returns whether the peer is known.
    pub fn is_known(&self) -> bool {
        matches!(self, Self::Known)
    }

    /// Returns whether the peer is unknown.
    pub fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown)
    }

    /// Sets the relation to `PeerRelation::Known`.
    pub fn set_known(&mut self) {
        *self = Self::Known;
    }

    /// Sets the relation to `PeerRelation::Unknown`.
    pub fn set_unknown(&mut self) {
        *self = Self::Unknown;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn is_and_set_api() {
        let mut pr = PeerRelation::Unknown;
        assert!(pr.is_unknown());

        pr.set_known();
        assert!(pr.is_known());

        pr.set_unknown();
        assert!(pr.is_unknown());
    }
}