use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use crate::error::Error;
use crate::event::{Tag, TagCodec, impl_tag_codec_conversions};
use crate::nips::util::{missing_tag_kind, take_timestamp, unknown_tag};
use crate::types::time::Timestamp;
const EXPIRATION: &str = "expiration";
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Nip40Tag {
Expiration(Timestamp),
}
impl TagCodec for Nip40Tag {
type Error = Error;
fn parse<I, S>(tag: I) -> Result<Self, Self::Error>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut iter = tag.into_iter();
let kind: S = iter.next().ok_or(missing_tag_kind())?;
match kind.as_ref() {
EXPIRATION => {
let timestamp: Timestamp = take_timestamp(&mut iter)?;
Ok(Self::Expiration(timestamp))
}
_ => Err(unknown_tag()),
}
}
fn to_tag(&self) -> Tag {
let Self::Expiration(timestamp) = self;
let tag: Vec<String> = vec![String::from(EXPIRATION), timestamp.to_string()];
Tag::new(tag)
}
}
impl_tag_codec_conversions!(Nip40Tag);
#[cfg(test)]
mod tests {
use super::*;
use crate::error::ErrorKind;
#[test]
fn test_parse_empty_tag() {
let tag: Vec<String> = Vec::new();
let err = Nip40Tag::parse(&tag).unwrap_err();
assert_eq!(err.kind(), ErrorKind::Missing);
}
#[test]
fn test_non_existing_tag() {
let tag = vec!["hello"];
let err = Nip40Tag::parse(&tag).unwrap_err();
assert_eq!(err.kind(), ErrorKind::Malformed);
}
#[test]
fn test_standardized_expiration_tag() {
let raw = 1600000000;
let timestamp = Timestamp::from_secs(raw);
let tag = vec!["expiration".to_string(), raw.to_string()];
let parsed = Nip40Tag::parse(&tag).unwrap();
assert_eq!(parsed, Nip40Tag::Expiration(timestamp));
assert_eq!(parsed.to_tag(), Tag::parse(tag).unwrap());
let tag = vec!["expiration", "hello"];
let err = Nip40Tag::parse(&tag).unwrap_err();
assert_eq!(err.kind(), ErrorKind::Malformed);
let tag = vec!["expiration"];
let err = Nip40Tag::parse(&tag).unwrap_err();
assert_eq!(err.kind(), ErrorKind::Missing);
}
}