libp2p_kad/
addresses.rs

1// Copyright 2019 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use libp2p_core::Multiaddr;
22use smallvec::SmallVec;
23use std::fmt;
24
25/// A non-empty list of (unique) addresses of a peer in the routing table.
26#[derive(Clone, PartialEq, Eq)]
27pub struct Addresses {
28    addrs: SmallVec<[Multiaddr; 6]>,
29}
30
31#[derive(PartialEq, Eq, Debug)]
32pub enum Remove {
33    Completely = 0,
34    KeepLast = 1
35}
36
37#[allow(clippy::len_without_is_empty)]
38impl Addresses {
39    /// Creates a new list of addresses.
40    pub fn new(addr: Multiaddr) -> Addresses {
41        let mut addrs = SmallVec::new();
42        addrs.push(addr);
43        Addresses { addrs }
44    }
45
46    /// Gets a reference to the first address in the list.
47    pub fn first(&self) -> &Multiaddr {
48        &self.addrs[0]
49    }
50
51    /// Returns an iterator over the addresses.
52    pub fn iter(&self) -> impl Iterator<Item = &Multiaddr> {
53        self.addrs.iter()
54    }
55
56    /// Returns a mutable iterator over the addresses.
57    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Multiaddr> {
58        self.addrs.iter_mut()
59    }
60
61    /// Returns the number of addresses in the list.
62    pub fn len(&self) -> usize {
63        self.addrs.len()
64    }
65
66    /// Converts the addresses into a `Vec`.
67    pub fn into_vec(self) -> Vec<Multiaddr> {
68        self.addrs.into_vec()
69    }
70
71    /// Removes the given address from the list.
72    ///
73    /// Returns `Ok(())` if the address is either not in the list or was found and
74    /// removed. Returns `Err(())` if the address is the last remaining address,
75    /// which cannot be removed.
76    ///
77    /// An address should only be removed if is determined to be invalid or
78    /// otherwise unreachable.
79    pub fn remove(&mut self, addr: &Multiaddr, mode: Remove) -> Result<(),()> {
80        if mode == Remove::KeepLast && self.addrs.len() == 1 {
81            return Err(())
82        }
83
84        if let Some(pos) = self.addrs.iter().position(|a| a == addr) {
85            self.addrs.remove(pos);
86            if self.addrs.len() <= self.addrs.inline_size() {
87                self.addrs.shrink_to_fit();
88            }
89        }
90
91        Ok(())
92    }
93
94    /// Adds a new address to the end of the list.
95    ///
96    /// Returns true if the address was added, false otherwise (i.e. if the
97    /// address is already in the list).
98    pub fn insert(&mut self, addr: Multiaddr) -> bool {
99        if self.addrs.iter().all(|a| *a != addr) {
100            self.addrs.push(addr);
101            true
102        } else {
103            false
104        }
105    }
106
107    /// Replaces an old address with a new address.
108    ///
109    /// Returns true if the previous address was found and replaced with a clone
110    /// of the new address, returns false otherwise.
111    pub fn replace(&mut self, old: &Multiaddr, new: &Multiaddr) -> bool {
112        if let Some(a) = self.addrs.iter_mut().find(|a| *a == old) {
113            *a = new.clone();
114            return true
115        }
116
117        false
118    }
119}
120
121impl From<SmallVec<[Multiaddr; 6]>> for Addresses {
122    fn from(addrs: SmallVec<[Multiaddr; 6]>) -> Self {
123        Addresses {
124            addrs
125        }
126    }
127}
128
129impl fmt::Debug for Addresses {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        f.debug_list()
132            .entries(self.addrs.iter())
133            .finish()
134    }
135}