use serde::{Deserialize, Serialize};
use crate::prelude::*;
use crate::serializers::bytes::base64string;
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Event {
#[serde(rename = "type")]
pub kind: String,
pub attributes: Vec<EventAttribute>,
}
impl Event {
pub fn new<K, I>(kind: K, attributes: I) -> Self
where
K: Into<String>,
I: IntoIterator,
I::Item: Into<EventAttribute>,
{
Self {
kind: kind.into(),
attributes: attributes.into_iter().map(Into::into).collect(),
}
}
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct EventAttribute {
#[serde(
serialize_with = "base64string::serialize",
deserialize_with = "base64string::deserialize_to_string"
)]
pub key: String,
#[serde(
serialize_with = "base64string::serialize",
deserialize_with = "base64string::deserialize_to_string"
)]
pub value: String,
pub index: bool,
}
impl<K: Into<String>, V: Into<String>> From<(K, V, bool)> for EventAttribute {
fn from((key, value, index): (K, V, bool)) -> Self {
EventAttribute {
key: key.into(),
value: value.into(),
index,
}
}
}
#[allow(missing_docs)]
pub trait EventAttributeIndexExt: private::Sealed {
type Key;
type Value;
fn index(self) -> (Self::Key, Self::Value, bool);
fn no_index(self) -> (Self::Key, Self::Value, bool);
}
impl<K: Into<String>, V: Into<String>> EventAttributeIndexExt for (K, V) {
type Key = K;
type Value = V;
fn index(self) -> (K, V, bool) {
let (key, value) = self;
(key, value, true)
}
fn no_index(self) -> (K, V, bool) {
let (key, value) = self;
(key, value, false)
}
}
mod private {
use crate::prelude::*;
pub trait Sealed {}
impl<K: Into<String>, V: Into<String>> Sealed for (K, V) {}
}
impl<K: Into<String>, V: Into<String>> From<(K, V)> for EventAttribute {
fn from((key, value): (K, V)) -> Self {
(key, value, false).into()
}
}
use core::convert::{TryFrom, TryInto};
use tendermint_proto::{abci as pb, Protobuf};
impl From<EventAttribute> for pb::EventAttribute {
fn from(event: EventAttribute) -> Self {
Self {
key: event.key.into(),
value: event.value.into(),
index: event.index,
}
}
}
impl TryFrom<pb::EventAttribute> for EventAttribute {
type Error = crate::Error;
fn try_from(event: pb::EventAttribute) -> Result<Self, Self::Error> {
Ok(Self {
key: String::from_utf8(event.key.to_vec())
.map_err(|e| crate::Error::parse(e.to_string()))?,
value: String::from_utf8(event.value.to_vec())
.map_err(|e| crate::Error::parse(e.to_string()))?,
index: event.index,
})
}
}
impl Protobuf<pb::EventAttribute> for EventAttribute {}
impl From<Event> for pb::Event {
fn from(event: Event) -> Self {
Self {
r#type: event.kind,
attributes: event.attributes.into_iter().map(Into::into).collect(),
}
}
}
impl TryFrom<pb::Event> for Event {
type Error = crate::Error;
fn try_from(event: pb::Event) -> Result<Self, Self::Error> {
Ok(Self {
kind: event.r#type,
attributes: event
.attributes
.into_iter()
.map(TryInto::try_into)
.collect::<Result<_, _>>()?,
})
}
}
impl Protobuf<pb::Event> for Event {}