Skip to content

Commit c18013c

Browse files
committed
Add log_iter utility macro
This is a useful primitive to have that formats the contents of the iterator as a comma-separated list.
1 parent eac1bc1 commit c18013c

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

lightning/src/util/logger.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,29 @@ impl<'a> core::fmt::Display for DebugBytes<'a> {
169169
}
170170
}
171171

172+
/// Wrapper for logging `Iterator`s.
173+
///
174+
/// This is not exported to bindings users as fmt can't be used in C
175+
#[doc(hidden)]
176+
pub struct DebugIter<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone>(pub core::cell::RefCell<I>);
177+
impl<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone> fmt::Display for DebugIter<T, I> {
178+
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
179+
use core::ops::DerefMut;
180+
write!(f, "[")?;
181+
let iter_ref = self.0.clone();
182+
let mut iter = iter_ref.borrow_mut();
183+
for item in iter.deref_mut() {
184+
write!(f, "{}", item)?;
185+
break;
186+
}
187+
for item in iter.deref_mut() {
188+
write!(f, ", {}", item)?;
189+
}
190+
write!(f, "]")?;
191+
Ok(())
192+
}
193+
}
194+
172195
#[cfg(test)]
173196
mod tests {
174197
use crate::util::logger::{Logger, Level};

lightning/src/util/macro_logger.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ use crate::routing::router::Route;
1717
use crate::ln::chan_utils::HTLCClaim;
1818
use crate::util::logger::DebugBytes;
1919

20+
macro_rules! log_iter {
21+
($obj: expr) => {
22+
$crate::util::logger::DebugIter(core::cell::RefCell::new($obj))
23+
}
24+
}
25+
2026
/// Logs a pubkey in hex format.
2127
#[macro_export]
2228
macro_rules! log_pubkey {

0 commit comments

Comments
 (0)