]> git.bitcoin.ninja Git - rust-lightning/commitdiff
Pass Event by reference to EventHandler
authorJeffrey Czyz <jkczyz@gmail.com>
Tue, 17 Aug 2021 16:12:18 +0000 (11:12 -0500)
committerJeffrey Czyz <jkczyz@gmail.com>
Fri, 10 Sep 2021 03:57:51 +0000 (22:57 -0500)
Passing an Event by reference rather and by move gives more flexibility
for composing event handlers without needing to clone events.

lightning-background-processor/src/lib.rs
lightning-net-tokio/src/lib.rs
lightning/src/chain/chainmonitor.rs
lightning/src/ln/channelmanager.rs
lightning/src/util/events.rs

index 34cddd1a6aa8b83ea36699e0bb39c4a21b97480a..45b33fd1fc52ff5a28ad97a9aa61aad69e3d52e3 100644 (file)
@@ -345,7 +345,7 @@ mod tests {
                        begin_open_channel!($node_a, $node_b, $channel_value);
                        let events = $node_a.node.get_and_clear_pending_events();
                        assert_eq!(events.len(), 1);
-                       let (temporary_channel_id, tx) = handle_funding_generation_ready!(events[0], $channel_value);
+                       let (temporary_channel_id, tx) = handle_funding_generation_ready!(&events[0], $channel_value);
                        end_open_channel!($node_a, $node_b, temporary_channel_id, tx);
                        tx
                }}
@@ -362,14 +362,14 @@ mod tests {
        macro_rules! handle_funding_generation_ready {
                ($event: expr, $channel_value: expr) => {{
                        match $event {
-                               Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
-                                       assert_eq!(*channel_value_satoshis, $channel_value);
+                               &Event::FundingGenerationReady { temporary_channel_id, channel_value_satoshis, ref output_script, user_channel_id } => {
+                                       assert_eq!(channel_value_satoshis, $channel_value);
                                        assert_eq!(user_channel_id, 42);
 
                                        let tx = Transaction { version: 1 as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
-                                               value: *channel_value_satoshis, script_pubkey: output_script.clone(),
+                                               value: channel_value_satoshis, script_pubkey: output_script.clone(),
                                        }]};
-                                       (*temporary_channel_id, tx)
+                                       (temporary_channel_id, tx)
                                },
                                _ => panic!("Unexpected event"),
                        }
@@ -423,7 +423,7 @@ mod tests {
                // Initiate the background processors to watch each node.
                let data_dir = nodes[0].persister.get_data_dir();
                let persister = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
-               let event_handler = |_| {};
+               let event_handler = |_: &_| {};
                let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
 
                macro_rules! check_persisted_data {
@@ -476,7 +476,7 @@ mod tests {
                let nodes = create_nodes(1, "test_timer_tick_called".to_string());
                let data_dir = nodes[0].persister.get_data_dir();
                let persister = move |node: &ChannelManager<InMemorySigner, Arc<ChainMonitor>, Arc<test_utils::TestBroadcaster>, Arc<KeysManager>, Arc<test_utils::TestFeeEstimator>, Arc<test_utils::TestLogger>>| FilesystemPersister::persist_manager(data_dir.clone(), node);
-               let event_handler = |_| {};
+               let event_handler = |_: &_| {};
                let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
                loop {
                        let log_entries = nodes[0].logger.lines.lock().unwrap();
@@ -498,7 +498,7 @@ mod tests {
                open_channel!(nodes[0], nodes[1], 100000);
 
                let persister = |_: &_| Err(std::io::Error::new(std::io::ErrorKind::Other, "test"));
-               let event_handler = |_| {};
+               let event_handler = |_: &_| {};
                let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
                match bg_processor.join() {
                        Ok(_) => panic!("Expected error persisting manager"),
@@ -518,7 +518,7 @@ mod tests {
 
                // Set up a background event handler for FundingGenerationReady events.
                let (sender, receiver) = std::sync::mpsc::sync_channel(1);
-               let event_handler = move |event| {
+               let event_handler = move |event: &Event| {
                        sender.send(handle_funding_generation_ready!(event, channel_value)).unwrap();
                };
                let bg_processor = BackgroundProcessor::start(persister.clone(), event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
@@ -544,7 +544,7 @@ mod tests {
 
                // Set up a background event handler for SpendableOutputs events.
                let (sender, receiver) = std::sync::mpsc::sync_channel(1);
-               let event_handler = move |event| sender.send(event).unwrap();
+               let event_handler = move |event: &Event| sender.send(event.clone()).unwrap();
                let bg_processor = BackgroundProcessor::start(persister, event_handler, nodes[0].chain_monitor.clone(), nodes[0].node.clone(), nodes[0].peer_manager.clone(), nodes[0].logger.clone());
 
                // Force close the channel and check that the SpendableOutputs event was handled.
index 25c161d2aeb07f8ba5305956e93c9299aca303f1..bf411211fdbb81b1e077c75eab92889e6bb5e54b 100644 (file)
 //! async fn connect_to_node(peer_manager: PeerManager, chain_monitor: Arc<ChainMonitor>, channel_manager: ChannelManager, their_node_id: PublicKey, addr: SocketAddr) {
 //!    lightning_net_tokio::connect_outbound(peer_manager, their_node_id, addr).await;
 //!    loop {
-//!            channel_manager.await_persistable_update();
-//!            channel_manager.process_pending_events(&|event| {
-//!                    // Handle the event!
-//!            });
-//!            chain_monitor.process_pending_events(&|event| {
+//!            let event_handler = |event: &Event| {
 //!                    // Handle the event!
-//!            });
+//!            };
+//!            channel_manager.await_persistable_update();
+//!            channel_manager.process_pending_events(&event_handler);
+//!            chain_monitor.process_pending_events(&event_handler);
 //!    }
 //! }
 //!
 //! async fn accept_socket(peer_manager: PeerManager, chain_monitor: Arc<ChainMonitor>, channel_manager: ChannelManager, socket: TcpStream) {
 //!    lightning_net_tokio::setup_inbound(peer_manager, socket);
 //!    loop {
-//!            channel_manager.await_persistable_update();
-//!            channel_manager.process_pending_events(&|event| {
-//!                    // Handle the event!
-//!            });
-//!            chain_monitor.process_pending_events(&|event| {
+//!            let event_handler = |event: &Event| {
 //!                    // Handle the event!
-//!            });
+//!            };
+//!            channel_manager.await_persistable_update();
+//!            channel_manager.process_pending_events(&event_handler);
+//!            chain_monitor.process_pending_events(&event_handler);
 //!    }
 //! }
 //! ```
index 8969427a0f960bc5766c153c8479a46974035b93..524035e96d76bb8f829931e8fbdd58b69e41dd06 100644 (file)
@@ -144,7 +144,7 @@ where C::Target: chain::Filter,
        pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
                use util::events::EventsProvider;
                let events = core::cell::RefCell::new(Vec::new());
-               let event_handler = |event| events.borrow_mut().push(event);
+               let event_handler = |event: &events::Event| events.borrow_mut().push(event.clone());
                self.process_pending_events(&event_handler);
                events.into_inner()
        }
@@ -332,7 +332,7 @@ impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> even
                        pending_events.append(&mut monitor.get_and_clear_pending_events());
                }
                for event in pending_events.drain(..) {
-                       handler.handle_event(event);
+                       handler.handle_event(&event);
                }
        }
 }
index ac2297f86aeab74651b7f2f86ba2f903870be565..7ecdd8eaade80a227374654c14de684e4f1ef8a0 100644 (file)
@@ -4167,7 +4167,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
        #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
        pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
                let events = core::cell::RefCell::new(Vec::new());
-               let event_handler = |event| events.borrow_mut().push(event);
+               let event_handler = |event: &events::Event| events.borrow_mut().push(event.clone());
                self.process_pending_events(&event_handler);
                events.into_inner()
        }
@@ -4244,7 +4244,7 @@ where
                        }
 
                        for event in pending_events.drain(..) {
-                               handler.handle_event(event);
+                               handler.handle_event(&event);
                        }
 
                        result
index 1780483cb8b9e01bcab8d5f0c18e812522d27a7f..d4288164cd972e23230ac86af64d42c6bf254952 100644 (file)
@@ -561,11 +561,11 @@ pub trait EventHandler {
        /// Handles the given [`Event`].
        ///
        /// See [`EventsProvider`] for details that must be considered when implementing this method.
-       fn handle_event(&self, event: Event);
+       fn handle_event(&self, event: &Event);
 }
 
-impl<F> EventHandler for F where F: Fn(Event) {
-       fn handle_event(&self, event: Event) {
+impl<F> EventHandler for F where F: Fn(&Event) {
+       fn handle_event(&self, event: &Event) {
                self(event)
        }
 }