Skip to main content

iota_types/block/address/
nft.rs

1// Copyright 2021 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use core::str::FromStr;
5
6use derive_more::{AsRef, Deref, From};
7
8use crate::block::{output::NftId, Error};
9
10/// An NFT address.
11#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, From, AsRef, Deref, packable::Packable)]
12#[as_ref(forward)]
13pub struct NftAddress(NftId);
14
15impl NftAddress {
16    /// The [`Address`](crate::block::address::Address) kind of an NFT address.
17    pub const KIND: u8 = 16;
18    /// The length of a [`NftAddress`].
19    pub const LENGTH: usize = NftId::LENGTH;
20
21    /// Creates a new [`NftAddress`].
22    #[inline(always)]
23    pub fn new(id: NftId) -> Self {
24        Self::from(id)
25    }
26
27    /// Returns the [`NftId`] of an [`NftAddress`].
28    #[inline(always)]
29    pub fn nft_id(&self) -> &NftId {
30        &self.0
31    }
32
33    /// Consumes an [`NftAddress`] and returns its [`NftId`].
34    #[inline(always)]
35    pub fn into_nft_id(self) -> NftId {
36        self.0
37    }
38}
39
40#[cfg(feature = "serde")]
41string_serde_impl!(NftAddress);
42
43impl FromStr for NftAddress {
44    type Err = Error;
45
46    fn from_str(s: &str) -> Result<Self, Self::Err> {
47        Ok(Self::from(NftId::from_str(s)?))
48    }
49}
50
51impl core::fmt::Display for NftAddress {
52    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
53        write!(f, "{}", self.0)
54    }
55}
56
57impl core::fmt::Debug for NftAddress {
58    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
59        write!(f, "NftAddress({self})")
60    }
61}
62
63#[cfg(feature = "dto")]
64#[allow(missing_docs)]
65pub mod dto {
66    use serde::{Deserialize, Serialize};
67
68    use super::*;
69    use crate::block::error::dto::DtoError;
70
71    /// Describes an NFT address.
72    #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
73    pub struct NftAddressDto {
74        #[serde(rename = "type")]
75        pub kind: u8,
76        #[serde(rename = "nftId")]
77        pub nft_id: String,
78    }
79
80    impl From<&NftAddress> for NftAddressDto {
81        fn from(value: &NftAddress) -> Self {
82            Self {
83                kind: NftAddress::KIND,
84                nft_id: value.to_string(),
85            }
86        }
87    }
88
89    impl TryFrom<&NftAddressDto> for NftAddress {
90        type Error = DtoError;
91
92        fn try_from(value: &NftAddressDto) -> Result<Self, Self::Error> {
93            value
94                .nft_id
95                .parse::<Self>()
96                .map_err(|_| DtoError::InvalidField("nftId"))
97        }
98    }
99}