radix_common/data/scrypto/model/
reference.rs

1use crate::data::manifest::ManifestCustomValueKind;
2use crate::data::scrypto::*;
3use crate::types::NodeId;
4use crate::*;
5#[cfg(feature = "fuzzing")]
6use arbitrary::Arbitrary;
7use radix_rust::copy_u8_array;
8use sbor::rust::fmt;
9use sbor::rust::vec::Vec;
10use sbor::*;
11
12#[cfg_attr(feature = "fuzzing", derive(Arbitrary))]
13#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct Reference(pub NodeId);
15
16impl Reference {
17    pub fn to_vec(&self) -> Vec<u8> {
18        self.0.to_vec()
19    }
20
21    pub fn as_node_id(&self) -> &NodeId {
22        &self.0
23    }
24}
25
26impl TryFrom<&[u8]> for Reference {
27    type Error = ParseReferenceError;
28
29    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
30        match slice.len() {
31            NodeId::LENGTH => Ok(Self(NodeId(copy_u8_array(slice)))),
32            _ => Err(ParseReferenceError::InvalidLength(slice.len())),
33        }
34    }
35}
36
37//========
38// error
39//========
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum ParseReferenceError {
43    InvalidLength(usize),
44}
45
46#[cfg(not(feature = "alloc"))]
47impl std::error::Error for ParseReferenceError {}
48
49#[cfg(not(feature = "alloc"))]
50impl fmt::Display for ParseReferenceError {
51    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52        write!(f, "{:?}", self)
53    }
54}
55
56//========
57// binary
58//========
59
60well_known_scrypto_custom_type!(
61    Reference,
62    ScryptoCustomValueKind::Reference,
63    Type::Reference,
64    NodeId::LENGTH,
65    REFERENCE_TYPE,
66    reference_type_data
67);
68
69//==================
70// binary (manifest)
71//==================
72
73manifest_type!(Reference, ManifestCustomValueKind::Address, NodeId::LENGTH);
74
75//======
76// text
77//======
78
79impl fmt::Debug for Reference {
80    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
81        write!(f, "Reference({})", hex::encode(&self.0))
82    }
83}