use crate::account_address::AccountAddress;
#[cfg(any(test, feature = "fuzzing"))]
use rand::{rngs::OsRng, RngCore};
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct EventKey {
creation_number: u64,
account_address: AccountAddress,
}
impl EventKey {
pub fn new(creation_number: u64, account_address: AccountAddress) -> Self {
Self {
creation_number,
account_address,
}
}
pub fn to_bytes(&self) -> Vec<u8> {
bcs::to_bytes(&self).unwrap()
}
pub fn get_creator_address(&self) -> AccountAddress {
self.account_address
}
pub fn get_creation_number(&self) -> u64 {
self.creation_number
}
#[cfg(any(test, feature = "fuzzing"))]
pub fn random() -> Self {
let mut rng = OsRng;
let salt = rng.next_u64();
EventKey::new(salt, AccountAddress::random())
}
}
impl fmt::LowerHex for EventKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write!(f, "0x")?;
}
for byte in self.to_bytes() {
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
impl fmt::Display for EventKey {
fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
write!(f, "{:x}", self)
}
}
#[derive(Clone, Copy, Debug)]
pub struct EventKeyParseError;
impl fmt::Display for EventKeyParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
write!(f, "unable to parse EventKey")
}
}
impl std::error::Error for EventKeyParseError {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EventHandle {
count: u64,
key: EventKey,
}
impl EventHandle {
pub fn new(key: EventKey, count: u64) -> Self {
EventHandle { count, key }
}
pub fn key(&self) -> &EventKey {
&self.key
}
pub fn count(&self) -> u64 {
self.count
}
#[cfg(any(test, feature = "fuzzing"))]
pub fn random(count: u64) -> Self {
Self {
key: EventKey::random(),
count,
}
}
#[cfg(any(test, feature = "fuzzing"))]
pub fn count_mut(&mut self) -> &mut u64 {
&mut self.count
}
}