From: Matt Corallo Date: Mon, 24 Aug 2020 18:14:05 +0000 (-0400) Subject: Add a C-bindings-compatible read lock type for NetworkGraph X-Git-Tag: v0.0.12~32^2 X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=commitdiff_plain;h=d224c1def44f167afd711515484207f2f4966d2d;p=rust-lightning 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. --- diff --git a/lightning/src/routing/network_graph.rs b/lightning/src/routing/network_graph.rs index 44f2ed237..c46781d11 100644 --- a/lightning/src/routing/network_graph.rs +++ b/lightning/src/routing/network_graph.rs @@ -27,7 +27,7 @@ use util::ser::{Writeable, Readable, Writer}; use util::logger::Logger; use std::{cmp, fmt}; -use std::sync::RwLock; +use std::sync::{RwLock, RwLockReadGuard}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::collections::BTreeMap; use std::collections::btree_map::Entry as BtreeEntry; @@ -41,6 +41,11 @@ pub struct NetworkGraph { nodes: BTreeMap, } +/// A simple newtype for RwLockReadGuard<'a, NetworkGraph>. +/// This exists only to make accessing a RwLock possible from +/// the C bindings, as it can be done directly in Rust code. +pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>); + /// Receives and validates network updates from peers, /// stores authentic and relevant data as a network graph. /// This network graph is then used for routing payments. @@ -85,6 +90,21 @@ impl NetGraphMsgHandler where C::Target: ChainWatchInt logger, } } + + /// Take a read lock on the network_graph and return it in the C-bindings + /// newtype helper. This is likely only useful when called via the C + /// bindings as you can call `self.network_graph.read().unwrap()` in Rust + /// yourself. + pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> { + LockedNetworkGraph(self.network_graph.read().unwrap()) + } +} + +impl<'a> LockedNetworkGraph<'a> { + /// Get a reference to the NetworkGraph which this read-lock contains. + pub fn graph(&self) -> &NetworkGraph { + &*self.0 + } }