sc_network/utils.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! `sc-network` utilities
20
21use futures::{stream::unfold, FutureExt, Stream, StreamExt};
22use futures_timer::Delay;
23use linked_hash_set::LinkedHashSet;
24
25use std::{hash::Hash, num::NonZeroUsize, time::Duration};
26
27/// Creates a stream that returns a new value every `duration`.
28pub fn interval(duration: Duration) -> impl Stream<Item = ()> + Unpin {
29 unfold((), move |_| Delay::new(duration).map(|_| Some(((), ())))).map(drop)
30}
31
32/// Wrapper around `LinkedHashSet` with bounded growth.
33///
34/// In the limit, for each element inserted the oldest existing element will be removed.
35#[derive(Debug, Clone)]
36pub struct LruHashSet<T: Hash + Eq> {
37 set: LinkedHashSet<T>,
38 limit: NonZeroUsize,
39}
40
41impl<T: Hash + Eq> LruHashSet<T> {
42 /// Create a new `LruHashSet` with the given (exclusive) limit.
43 pub fn new(limit: NonZeroUsize) -> Self {
44 Self { set: LinkedHashSet::new(), limit }
45 }
46
47 /// Insert element into the set.
48 ///
49 /// Returns `true` if this is a new element to the set, `false` otherwise.
50 /// Maintains the limit of the set by removing the oldest entry if necessary.
51 /// Inserting the same element will update its LRU position.
52 pub fn insert(&mut self, e: T) -> bool {
53 if self.set.insert(e) {
54 if self.set.len() == usize::from(self.limit) {
55 self.set.pop_front(); // remove oldest entry
56 }
57 return true
58 }
59 false
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 #[test]
68 fn maintains_limit() {
69 let three = NonZeroUsize::new(3).unwrap();
70 let mut set = LruHashSet::<u8>::new(three);
71
72 // First element.
73 assert!(set.insert(1));
74 assert_eq!(vec![&1], set.set.iter().collect::<Vec<_>>());
75
76 // Second element.
77 assert!(set.insert(2));
78 assert_eq!(vec![&1, &2], set.set.iter().collect::<Vec<_>>());
79
80 // Inserting the same element updates its LRU position.
81 assert!(!set.insert(1));
82 assert_eq!(vec![&2, &1], set.set.iter().collect::<Vec<_>>());
83
84 // We reached the limit. The next element forces the oldest one out.
85 assert!(set.insert(3));
86 assert_eq!(vec![&1, &3], set.set.iter().collect::<Vec<_>>());
87 }
88}