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)]
27pub struct Addresses {
28    addrs: SmallVec<[Multiaddr; 6]>,
29}
30
31#[allow(clippy::len_without_is_empty)]
32impl Addresses {
33    /// Creates a new list of addresses.
34    pub fn new(addr: Multiaddr) -> Addresses {
35        let mut addrs = SmallVec::new();
36        addrs.push(addr);
37        Addresses { addrs }
38    }
39
40    /// Gets a reference to the first address in the list.
41    pub fn first(&self) -> &Multiaddr {
42        &self.addrs[0]
43    }
44
45    /// Returns an iterator over the addresses.
46    pub fn iter(&self) -> impl Iterator<Item = &Multiaddr> {
47        self.addrs.iter()
48    }
49
50    /// Returns the number of addresses in the list.
51    pub fn len(&self) -> usize {
52        self.addrs.len()
53    }
54
55    /// Converts the addresses into a `Vec`.
56    pub fn into_vec(self) -> Vec<Multiaddr> {
57        self.addrs.into_vec()
58    }
59
60    /// Removes the given address from the list.
61    ///
62    /// Returns `Ok(())` if the address is either not in the list or was found and
63    /// removed. Returns `Err(())` if the address is the last remaining address,
64    /// which cannot be removed.
65    ///
66    /// An address should only be removed if is determined to be invalid or
67    /// otherwise unreachable.
68    #[allow(clippy::result_unit_err)]
69    pub fn remove(&mut self, addr: &Multiaddr) -> Result<(), ()> {
70        if self.addrs.len() == 1 {
71            return Err(());
72        }
73
74        if let Some(pos) = self.addrs.iter().position(|a| a == addr) {
75            self.addrs.remove(pos);
76            if self.addrs.len() <= self.addrs.inline_size() {
77                self.addrs.shrink_to_fit();
78            }
79        }
80
81        Ok(())
82    }
83
84    /// Adds a new address to the end of the list.
85    ///
86    /// Returns true if the address was added, false otherwise (i.e. if the
87    /// address is already in the list).
88    pub fn insert(&mut self, addr: Multiaddr) -> bool {
89        if self.addrs.iter().all(|a| *a != addr) {
90            self.addrs.push(addr);
91            true
92        } else {
93            false
94        }
95    }
96
97    /// Replaces an old address with a new address.
98    ///
99    /// Returns true if the previous address was found and replaced with a clone
100    /// of the new address, returns false otherwise.
101    pub fn replace(&mut self, old: &Multiaddr, new: &Multiaddr) -> bool {
102        if let Some(a) = self.addrs.iter_mut().find(|a| *a == old) {
103            *a = new.clone();
104            return true;
105        }
106
107        false
108    }
109}
110
111impl fmt::Debug for Addresses {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        f.debug_list().entries(self.addrs.iter()).finish()
114    }
115}