radix_common/data/scrypto/model/
reference.rs

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