use alloc::vec::Vec;
use core::cmp::Ordering;
use core::hash::{Hash, Hasher};
use secp256k1::schnorr::Signature;
use super::tag::cow::CowTag;
use crate::{Event, EventId, Kind, PublicKey, Tags, Timestamp};
#[derive(Debug, Clone)]
pub struct EventBorrow<'a> {
pub id: &'a [u8; 32],
pub pubkey: &'a [u8; 32],
pub created_at: Timestamp,
pub kind: u16,
pub tags: Vec<CowTag<'a>>,
pub content: &'a str,
pub sig: &'a [u8; 64],
}
impl PartialEq for EventBorrow<'_> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for EventBorrow<'_> {}
impl PartialOrd for EventBorrow<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for EventBorrow<'_> {
fn cmp(&self, other: &Self) -> Ordering {
if self.created_at != other.created_at {
self.created_at.cmp(&other.created_at).reverse()
} else {
self.id.cmp(other.id)
}
}
}
impl Hash for EventBorrow<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl EventBorrow<'_> {
pub fn into_owned(self) -> Event {
Event::new(
EventId::from_byte_array(*self.id),
PublicKey::from_byte_array(*self.pubkey),
self.created_at,
Kind::from_u16(self.kind),
Tags::from_list(self.tags.into_iter().map(|t| t.into_owned()).collect()),
self.content,
Signature::from_slice(self.sig.as_slice()).expect("valid signature"),
)
}
}
impl<'a> From<&'a Event> for EventBorrow<'a> {
fn from(event: &'a Event) -> Self {
Self {
id: event.id.as_bytes(),
pubkey: event.pubkey.as_bytes(),
created_at: event.created_at,
kind: event.kind.as_u16(),
tags: event.tags.iter().map(CowTag::from).collect(),
content: &event.content,
sig: event.sig.as_ref(),
}
}
}