From c18013c2b66ca7dd743ec2b2c7d379d42ee454a7 Mon Sep 17 00:00:00 2001 From: Wilmer Paulino Date: Fri, 14 Jul 2023 14:44:00 -0700 Subject: [PATCH] Add log_iter utility macro This is a useful primitive to have that formats the contents of the iterator as a comma-separated list. --- lightning/src/util/logger.rs | 23 +++++++++++++++++++++++ lightning/src/util/macro_logger.rs | 6 ++++++ 2 files changed, 29 insertions(+) diff --git a/lightning/src/util/logger.rs b/lightning/src/util/logger.rs index aac83f42a..722a81f7a 100644 --- a/lightning/src/util/logger.rs +++ b/lightning/src/util/logger.rs @@ -169,6 +169,29 @@ impl<'a> core::fmt::Display for DebugBytes<'a> { } } +/// Wrapper for logging `Iterator`s. +/// +/// This is not exported to bindings users as fmt can't be used in C +#[doc(hidden)] +pub struct DebugIter + Clone>(pub core::cell::RefCell); +impl + Clone> fmt::Display for DebugIter { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + use core::ops::DerefMut; + write!(f, "[")?; + let iter_ref = self.0.clone(); + let mut iter = iter_ref.borrow_mut(); + for item in iter.deref_mut() { + write!(f, "{}", item)?; + break; + } + for item in iter.deref_mut() { + write!(f, ", {}", item)?; + } + write!(f, "]")?; + Ok(()) + } +} + #[cfg(test)] mod tests { use crate::util::logger::{Logger, Level}; diff --git a/lightning/src/util/macro_logger.rs b/lightning/src/util/macro_logger.rs index 8742e8e84..4703bcdb3 100644 --- a/lightning/src/util/macro_logger.rs +++ b/lightning/src/util/macro_logger.rs @@ -17,6 +17,12 @@ use crate::routing::router::Route; use crate::ln::chan_utils::HTLCClaim; use crate::util::logger::DebugBytes; +macro_rules! log_iter { + ($obj: expr) => { + $crate::util::logger::DebugIter(core::cell::RefCell::new($obj)) + } +} + /// Logs a pubkey in hex format. #[macro_export] macro_rules! log_pubkey { -- 2.39.5