Skip to content

Commit eac8e26

Browse files
committed
f Use HashMap instead of Vec<(..)>
1 parent e5c68ba commit eac8e26

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed

src/connection.rs

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use lightning::ln::msgs::SocketAddress;
66

77
use bitcoin::secp256k1::PublicKey;
88

9+
use std::collections::hash_map::{self, HashMap};
910
use std::net::ToSocketAddrs;
1011
use std::ops::Deref;
1112
use std::sync::{Arc, Mutex};
@@ -16,7 +17,7 @@ where
1617
L::Target: Logger,
1718
{
1819
pending_connections:
19-
Mutex<Vec<(PublicKey, Vec<tokio::sync::oneshot::Sender<Result<(), Error>>>)>>,
20+
Mutex<HashMap<PublicKey, Vec<tokio::sync::oneshot::Sender<Result<(), Error>>>>>,
2021
peer_manager: Arc<PeerManager>,
2122
logger: L,
2223
}
@@ -26,7 +27,7 @@ where
2627
L::Target: Logger,
2728
{
2829
pub(crate) fn new(peer_manager: Arc<PeerManager>, logger: L) -> Self {
29-
let pending_connections = Mutex::new(Vec::new());
30+
let pending_connections = Mutex::new(HashMap::new());
3031
Self { pending_connections, peer_manager, logger }
3132
}
3233

@@ -110,26 +111,23 @@ where
110111
&self, node_id: &PublicKey,
111112
) -> Option<tokio::sync::oneshot::Receiver<Result<(), Error>>> {
112113
let mut pending_connections_lock = self.pending_connections.lock().unwrap();
113-
if let Some((_, connection_ready_senders)) =
114-
pending_connections_lock.iter_mut().find(|(id, _)| id == node_id)
115-
{
116-
let (tx, rx) = tokio::sync::oneshot::channel();
117-
connection_ready_senders.push(tx);
118-
Some(rx)
119-
} else {
120-
pending_connections_lock.push((*node_id, Vec::new()));
121-
None
114+
match pending_connections_lock.entry(*node_id) {
115+
hash_map::Entry::Occupied(mut entry) => {
116+
let (tx, rx) = tokio::sync::oneshot::channel();
117+
entry.get_mut().push(tx);
118+
Some(rx)
119+
},
120+
hash_map::Entry::Vacant(entry) => {
121+
entry.insert(Vec::new());
122+
None
123+
},
122124
}
123125
}
124126

125127
fn propagate_result_to_subscribers(&self, node_id: &PublicKey, res: Result<(), Error>) {
126128
// Send the result to any other tasks that might be waiting on it by now.
127129
let mut pending_connections_lock = self.pending_connections.lock().unwrap();
128-
if let Some((_, connection_ready_senders)) = pending_connections_lock
129-
.iter()
130-
.position(|(id, _)| id == node_id)
131-
.map(|i| pending_connections_lock.remove(i))
132-
{
130+
if let Some(connection_ready_senders) = pending_connections_lock.remove(node_id) {
133131
for sender in connection_ready_senders {
134132
let _ = sender.send(res).map_err(|e| {
135133
debug_assert!(

0 commit comments

Comments
 (0)