Skip to content

Commit 44b8197

Browse files
committed
Add a C-bindings-compatible read lock type for NetworkGraph
In order to calculate a route, it is likely that users need to take a read()-lock on NetGraphMsgHandler::network_graph. This is not possible naively from C bindings, as Rust's native RwLock is not exposed. Thus, we provide a simple wrapper around the RwLockReadGuard and expose simple accessor methods.
1 parent 773bd10 commit 44b8197

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

lightning/src/routing/network_graph.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use util::ser::{Writeable, Readable, Writer};
2727
use util::logger::Logger;
2828

2929
use std::{cmp, fmt};
30-
use std::sync::RwLock;
30+
use std::sync::{RwLock, RwLockReadGuard};
3131
use std::sync::atomic::{AtomicUsize, Ordering};
3232
use std::collections::BTreeMap;
3333
use std::collections::btree_map::Entry as BtreeEntry;
@@ -41,6 +41,11 @@ pub struct NetworkGraph {
4141
nodes: BTreeMap<PublicKey, NodeInfo>,
4242
}
4343

44+
/// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
45+
/// This exists only to make accessing a RwLock<NetworkGraph> possible from
46+
/// the C bindings, as it can be done directly in Rust code.
47+
pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
48+
4449
/// Receives and validates network updates from peers,
4550
/// stores authentic and relevant data as a network graph.
4651
/// This network graph is then used for routing payments.
@@ -85,6 +90,21 @@ impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: ChainWatchInt
8590
logger,
8691
}
8792
}
93+
94+
/// Take a read lock on the network_graph and return it in the C-bindings
95+
/// newtype helper. This is likely only useful when called via the C
96+
/// bindings as you can call `self.network_graph.read().unwrap()` in Rust
97+
/// yourself.
98+
pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
99+
LockedNetworkGraph(self.network_graph.read().unwrap())
100+
}
101+
}
102+
103+
impl<'a> LockedNetworkGraph<'a> {
104+
/// Get a reference to the NetworkGraph which this read-lock contains.
105+
pub fn graph(&self) -> &NetworkGraph {
106+
&*self.0
107+
}
88108
}
89109

90110

0 commit comments

Comments
 (0)