1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
use std::{
	fmt,
	hash::{
		Hash,
		Hasher,
	},
	os::raw,
	ptr::NonNull,
};

#[cfg(feature = "rust-log")]
use log::{debug, error, info, warn};

use crate::{
	as_void_ptr,
	FFI,
	LogLevel,
	void_ptr_as
};

type LogHandler<'cb> = dyn FnMut(LogLevel, &str, &str) + Send + 'cb;

/// Wrapper around the underlying `xmpp_log_t` struct.
///
/// The best option to get a logger is to call [`Logger::default()`]. It will return you a logger that
/// is tied into Rust logging facility provided by [`log`] crate. This functionality is available when
/// compiling with the default `rust-log` feature.
///
/// This struct implements:
///
///   * `Eq` by comparing internal pointers
///   * `Hash` by hashing internal pointer
///   * `Send`
///
/// [`Logger::default()`]: struct.Logger.html#method.default
/// [`log`]: https://crates.io/crates/log
pub struct Logger<'cb> {
	inner: NonNull<sys::xmpp_log_t>,
	owned: bool,
	_handler: Box<LogHandler<'cb>>,
}

impl<'cb> Logger<'cb> {
	/// Create a new custom logger.
	///
	/// The callback argument will be called every time a log message needs to be printed.
	pub fn new<CB>(handler: CB) -> Self
		where
			CB: FnMut(LogLevel, &str, &str) + Send + 'cb,
	{
		let handler = Box::new(handler);
		Logger::with_inner(Box::into_raw(Box::new(sys::xmpp_log_t {
			handler: Some(Self::log_handler_cb::<CB>),
			userdata: as_void_ptr(&*handler),
		})), handler, true)
	}

	#[inline]
	fn with_inner(inner: *mut sys::xmpp_log_t, handler: Box<LogHandler<'cb>>, owned: bool) -> Self {
		Logger { inner: NonNull::new(inner).expect("Cannot allocate memory for Logger"), owned, _handler: handler }
	}

	/// [xmpp_get_default_logger](http://strophe.im/libstrophe/doc/0.9.2/group___context.html#ga33abde406c7a057006b109cf1b23c8f8)
	///
	/// This method returns default `libstrophe` logger that just outputs log lines to stderr. Use it
	/// if you compile without `rust-log` feature and want a quick debug log output.
	pub fn new_internal(log_level: LogLevel) -> Logger<'static> {
		Logger::with_inner(
			unsafe { sys::xmpp_get_default_logger(log_level) },
			Box::new(|_, _, _| {}),
			false,
		)
	}

	/// This method returns null logger that doesn't output any information.
	pub fn new_null() -> Logger<'static> {
		Logger::new(|_, _, _| {})
	}

	extern "C" fn log_handler_cb<CB>(userdata: *mut raw::c_void, level: sys::xmpp_log_level_t, area: *const raw::c_char, msg: *const raw::c_char)
		where
			CB: FnMut(LogLevel, &str, &str) + Send + 'cb,
	{
		let area = unsafe { FFI(area).receive() }.unwrap();
		let msg = unsafe { FFI(msg).receive() }.unwrap();
		unsafe {
			void_ptr_as::<CB>(userdata)(level, &area, &msg);
		}
	}

	pub fn as_inner(&self) -> *const sys::xmpp_log_t {
		self.inner.as_ptr()
	}
}

impl Default for Logger<'static> {
	/// Return a new logger that logs to standard Rust logging facilities.
	///
	/// Logging facilities are provided by [`log`] crate. Only available when compiling with `rust-log`
	/// feature.
	///
	/// [`log`]: https://crates.io/crates/log
	#[cfg(feature = "rust-log")]
	fn default() -> Self {
		Logger::new(|log_level, area, message| {
			match log_level {
				LogLevel::XMPP_LEVEL_DEBUG => debug!("{}: {}", area, message),
				LogLevel::XMPP_LEVEL_INFO => info!("{}: {}", area, message),
				LogLevel::XMPP_LEVEL_WARN => warn!("{}: {}", area, message),
				LogLevel::XMPP_LEVEL_ERROR => error!("{}: {}", area, message),
			}
		})
	}

	/// Create a new default logger by calling [`new_internal()`] with debug log level.
	///
	/// Used when the crate is compiled without `rust-log` feature.
	///
	/// [`new_internal()`]: struct.Logger.html#method.new_internal
	#[cfg(not(feature = "rust-log"))]
	fn default() -> Self {
		Logger::new_internal(LogLevel::XMPP_LEVEL_DEBUG)
	}
}

impl PartialEq for Logger<'_> {
	fn eq(&self, other: &Logger) -> bool {
		self.inner == other.inner
	}
}

impl Eq for Logger<'_> {}

impl fmt::Debug for Logger<'_> {
	fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
		f.debug_struct("Logger")
			.field("inner", &self.inner)
			.field("owned", &self.owned)
			.finish()
	}
}

impl Hash for Logger<'_> {
	fn hash<H: Hasher>(&self, state: &mut H) {
		self.inner.hash(state);
	}
}

impl Drop for Logger<'_> {
	fn drop(&mut self) {
		if self.owned {
			unsafe {
				Box::from_raw(self.inner.as_mut());
			}
		}
	}
}

unsafe impl Send for Logger<'_> {}