Add log_iter utility macro

This is a useful primitive to have that formats the contents of the
iterator as a comma-separated list.
This commit is contained in:
Wilmer Paulino 2023-07-14 14:44:00 -07:00
parent eac1bc18e3
commit c18013c2b6
No known key found for this signature in database
GPG key ID: 634FE5FC544DCA31
2 changed files with 29 additions and 0 deletions

View file

@ -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<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone>(pub core::cell::RefCell<I>);
impl<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone> fmt::Display for DebugIter<T, I> {
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};

View file

@ -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 {