2017-02-21 17:38:29 +01:00
|
|
|
//! Provides an abstract event type which can be downcasted into a more specific one.
|
|
|
|
|
//!
|
|
|
|
|
//! # Examples
|
|
|
|
|
//!
|
|
|
|
|
//! ```
|
|
|
|
|
//! use xmpp::event::{Event, AbstractEvent};
|
|
|
|
|
//!
|
|
|
|
|
//! #[derive(Debug, PartialEq, Eq)]
|
|
|
|
|
//! struct EventA;
|
|
|
|
|
//!
|
|
|
|
|
//! impl Event for EventA {}
|
|
|
|
|
//!
|
|
|
|
|
//! #[derive(Debug, PartialEq, Eq)]
|
|
|
|
|
//! struct EventB;
|
|
|
|
|
//!
|
|
|
|
|
//! impl Event for EventB {}
|
|
|
|
|
//!
|
|
|
|
|
//! let event_a = AbstractEvent::new(EventA);
|
|
|
|
|
//!
|
|
|
|
|
//! assert_eq!(event_a.is::<EventA>(), true);
|
|
|
|
|
//! assert_eq!(event_a.is::<EventB>(), false);
|
|
|
|
|
//!
|
|
|
|
|
//! assert_eq!(event_a.downcast::<EventA>(), Some(&EventA));
|
|
|
|
|
//! assert_eq!(event_a.downcast::<EventB>(), None);
|
|
|
|
|
//! ```
|
|
|
|
|
|
2017-02-20 16:28:51 +01:00
|
|
|
use std::fmt::Debug;
|
|
|
|
|
|
|
|
|
|
use std::any::Any;
|
|
|
|
|
|
2017-02-21 17:38:29 +01:00
|
|
|
/// An abstract event.
|
2017-02-20 16:28:51 +01:00
|
|
|
pub struct AbstractEvent {
|
|
|
|
|
inner: Box<Any>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl AbstractEvent {
|
2017-02-21 17:38:29 +01:00
|
|
|
/// Creates an abstract event from a concrete event.
|
2017-02-20 16:28:51 +01:00
|
|
|
pub fn new<E: Event>(event: E) -> AbstractEvent {
|
|
|
|
|
AbstractEvent {
|
|
|
|
|
inner: Box::new(event),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-02-21 17:38:29 +01:00
|
|
|
/// Downcasts this abstract event into a concrete event.
|
2017-02-20 16:28:51 +01:00
|
|
|
pub fn downcast<E: Event + 'static>(&self) -> Option<&E> {
|
|
|
|
|
self.inner.downcast_ref::<E>()
|
|
|
|
|
}
|
|
|
|
|
|
2017-02-21 17:38:29 +01:00
|
|
|
/// Checks whether this abstract event is a specific concrete event.
|
2017-02-20 16:28:51 +01:00
|
|
|
pub fn is<E: Event + 'static>(&self) -> bool {
|
|
|
|
|
self.inner.is::<E>()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-02-21 17:38:29 +01:00
|
|
|
/// A marker trait which all events must implement.
|
2017-02-20 16:28:51 +01:00
|
|
|
pub trait Event: Any + Debug {}
|