use bitcoin::secp256k1::PublicKey;
use core::cmp;
use core::fmt;
use core::ops::Deref;
static LOG_LEVEL_NAMES: [&str; 6] = ["GOSSIP", "TRACE", "DEBUG", "INFO", "WARN", "ERROR"];
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub enum Level {
Gossip,
Trace,
Debug,
Info,
Warn,
Error,
}
impl PartialOrd for Level {
#[inline]
fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
#[inline]
fn lt(&self, other: &Level) -> bool {
(*self as usize) < *other as usize
}
#[inline]
fn le(&self, other: &Level) -> bool {
*self as usize <= *other as usize
}
#[inline]
fn gt(&self, other: &Level) -> bool {
*self as usize > *other as usize
}
#[inline]
fn ge(&self, other: &Level) -> bool {
*self as usize >= *other as usize
}
}
impl Ord for Level {
#[inline]
fn cmp(&self, other: &Level) -> cmp::Ordering {
(*self as usize).cmp(&(*other as usize))
}
}
impl fmt::Display for Level {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad(LOG_LEVEL_NAMES[*self as usize])
}
}
impl Level {
#[inline]
pub fn max() -> Level {
Level::Gossip
}
}
#[derive(Clone, Debug)]
pub struct Record {
pub peer_id: Option<PublicKey>,
}
pub trait Logger {
fn log(&self, record: Record);
}
pub struct WithContext<'a, L: Deref>
where
L::Target: Logger,
{
logger: &'a L,
peer_id: Option<PublicKey>,
}
impl<'a, L: Deref> Logger for WithContext<'a, L>
where
L::Target: Logger,
{
fn log(&self, mut record: Record) {
if self.peer_id.is_some() {
record.peer_id = self.peer_id
};
self.logger.log(record)
}
}
#[doc(hidden)]
pub struct DebugPubKey<'a>(pub &'a PublicKey);
impl<'a> core::fmt::Display for DebugPubKey<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
for i in self.0.serialize().iter() {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
#[doc(hidden)]
pub struct DebugBytes<'a>(pub &'a [u8]);
impl<'a> core::fmt::Display for DebugBytes<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
for i in self.0 {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
#[doc(hidden)]
pub struct DebugIter<T: fmt::Display, I: core::iter::Iterator<Item = T> + Clone>(pub 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> {
write!(f, "[")?;
let mut iter = self.0.clone();
if let Some(item) = iter.next() {
write!(f, "{}", item)?;
}
for item in iter {
write!(f, ", {}", item)?;
}
write!(f, "]")?;
Ok(())
}
}