1use std::{fmt, str::FromStr};
2
3use near_account_id::AccountId;
4
5use crate::{TokenIdType, error::TokenIdError};
6
7#[cfg_attr(any(feature = "arbitrary", test), derive(::arbitrary::Arbitrary))]
9#[cfg_attr(
10 feature = "borsh",
11 derive(::borsh::BorshSerialize, ::borsh::BorshDeserialize),
12 cfg_attr(feature = "borsh-schema", derive(::borsh::BorshSchema))
13)]
14#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub struct ImtTokenId {
16 pub minter_id: AccountId,
17
18 pub token_id: String,
19}
20
21impl ImtTokenId {
22 pub fn new(minter_id: impl Into<AccountId>, token_id: impl Into<String>) -> Self {
23 Self {
24 minter_id: minter_id.into(),
25 token_id: token_id.into(),
26 }
27 }
28}
29
30impl std::fmt::Debug for ImtTokenId {
31 #[inline]
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 write!(f, "{}:{}", self.minter_id, self.token_id)
34 }
35}
36
37impl std::fmt::Display for ImtTokenId {
38 #[inline]
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 fmt::Debug::fmt(&self, f)
41 }
42}
43
44impl FromStr for ImtTokenId {
45 type Err = TokenIdError;
46
47 fn from_str(data: &str) -> Result<Self, Self::Err> {
48 let (minter_id, token_id) = data
49 .split_once(':')
50 .ok_or(strum::ParseError::VariantNotFound)?;
51 Ok(Self::new(minter_id.parse::<AccountId>()?, token_id))
52 }
53}
54
55impl From<&ImtTokenId> for TokenIdType {
56 #[inline]
57 fn from(_: &ImtTokenId) -> Self {
58 Self::Imt
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 use defuse_test_utils::random::make_arbitrary;
67 use rstest::rstest;
68
69 #[rstest]
70 #[trace]
71 fn display_from_str_roundtrip(#[from(make_arbitrary)] token_id: ImtTokenId) {
72 let s = token_id.to_string();
73 let got: ImtTokenId = s.parse().unwrap();
74 assert_eq!(got, token_id);
75 }
76}