pub mod helpers;
pub(crate) mod serialization;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use crate::error::MatcherError;
pub type AttributeMap<K, V> = IndexMap<K, V>;
pub const TOPIC_STR: &str = "topic";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AttributeValue {
String(String),
Integer(i64),
Float(f64),
Boolean(bool),
List(Vec<AttributeValue>),
Map(AttributeMap<String, AttributeValue>),
}
impl AttributeValue {
pub fn as_str(&self) -> Option<&str> {
match self {
AttributeValue::String(s) => Some(s),
_ => None,
}
}
}
pub trait Event {
fn topic(&self) -> &str;
fn get_attribute(&self, name: &str) -> Option<&AttributeValue>;
fn attributes(&self) -> &AttributeMap<String, AttributeValue>;
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DefaultEvent {
attributes: AttributeMap<String, AttributeValue>,
}
impl DefaultEvent {
pub fn new<T: Into<String>>(topic: T) -> Self {
let mut attributes = AttributeMap::new();
attributes.insert(TOPIC_STR.to_string(), AttributeValue::String(topic.into()));
Self { attributes }
}
pub fn with_attribute<T: Into<String>>(mut self, name: T, value: AttributeValue) -> Self {
self.attributes.insert(name.into(), value);
self
}
pub(crate) fn from_attributes(
attributes: AttributeMap<String, AttributeValue>,
) -> Result<Self, MatcherError> {
if let Some(AttributeValue::String(_)) = attributes.get(TOPIC_STR) {
Ok(Self { attributes })
} else {
Err(MatcherError::MissingAttribute(TOPIC_STR.to_string()))
}
}
}
impl Event for DefaultEvent {
fn topic(&self) -> &str {
if let AttributeValue::String(topic) = &self.attributes[TOPIC_STR] {
topic
} else {
""
}
}
fn get_attribute(&self, name: &str) -> Option<&AttributeValue> {
self.attributes.get(name)
}
fn attributes(&self) -> &AttributeMap<String, AttributeValue> {
&self.attributes
}
}