Skip to main content

stellar_xdr/generated/
hash.rs

1#[allow(unused_imports, clippy::wildcard_imports)]
2use super::*;
3
4/// Hash is an XDR Typedef defined as:
5///
6/// ```text
7/// typedef opaque Hash[32];
8/// ```
9///
10#[cfg_attr(feature = "serde", cfg_eval::cfg_eval)]
11#[cfg_attr(feature = "alloc", derive(Default))]
12#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
13#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
14#[cfg_attr(
15    all(feature = "serde", feature = "alloc"),
16    derive(serde_with::SerializeDisplay, serde_with::DeserializeFromStr)
17)]
18pub struct Hash(pub [u8; 32]);
19
20impl core::fmt::Debug for Hash {
21    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
22        let v = &self.0;
23        write!(f, "Hash(")?;
24        for b in v {
25            write!(f, "{b:02x}")?;
26        }
27        write!(f, ")")?;
28        Ok(())
29    }
30}
31impl core::fmt::Display for Hash {
32    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
33        let v = &self.0;
34        for b in v {
35            write!(f, "{b:02x}")?;
36        }
37        Ok(())
38    }
39}
40
41#[cfg(feature = "alloc")]
42impl core::str::FromStr for Hash {
43    type Err = Error;
44    fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
45        hex::decode(s).map_err(|_| Error::InvalidHex)?.try_into()
46    }
47}
48#[cfg(feature = "schemars")]
49impl schemars::JsonSchema for Hash {
50    fn schema_name() -> String {
51        "Hash".to_string()
52    }
53
54    fn is_referenceable() -> bool {
55        false
56    }
57
58    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
59        let schema = String::json_schema(gen);
60        if let schemars::schema::Schema::Object(mut schema) = schema {
61            schema.extensions.insert(
62                "contentEncoding".to_owned(),
63                serde_json::Value::String("hex".to_string()),
64            );
65            schema.extensions.insert(
66                "contentMediaType".to_owned(),
67                serde_json::Value::String("application/binary".to_string()),
68            );
69            let string = *schema.string.unwrap_or_default().clone();
70            schema.string = Some(Box::new(schemars::schema::StringValidation {
71                max_length: 32_u32.checked_mul(2).map(Some).unwrap_or_default(),
72                min_length: 32_u32.checked_mul(2).map(Some).unwrap_or_default(),
73                ..string
74            }));
75            schema.into()
76        } else {
77            schema
78        }
79    }
80}
81impl From<Hash> for [u8; 32] {
82    #[must_use]
83    fn from(x: Hash) -> Self {
84        x.0
85    }
86}
87
88impl From<[u8; 32]> for Hash {
89    #[must_use]
90    fn from(x: [u8; 32]) -> Self {
91        Hash(x)
92    }
93}
94
95impl AsRef<[u8; 32]> for Hash {
96    #[must_use]
97    fn as_ref(&self) -> &[u8; 32] {
98        &self.0
99    }
100}
101
102impl ReadXdr for Hash {
103    #[cfg(feature = "std")]
104    fn read_xdr<R: Read>(r: &mut Limited<R>) -> Result<Self, Error> {
105        r.with_limited_depth(|r| {
106            let i = <[u8; 32]>::read_xdr(r)?;
107            let v = Hash(i);
108            Ok(v)
109        })
110    }
111}
112
113impl WriteXdr for Hash {
114    #[cfg(feature = "std")]
115    fn write_xdr<W: Write>(&self, w: &mut Limited<W>) -> Result<(), Error> {
116        w.with_limited_depth(|w| self.0.write_xdr(w))
117    }
118}
119
120impl Hash {
121    #[must_use]
122    pub fn as_slice(&self) -> &[u8] {
123        &self.0
124    }
125}
126
127#[cfg(feature = "alloc")]
128impl TryFrom<Vec<u8>> for Hash {
129    type Error = Error;
130    fn try_from(x: Vec<u8>) -> Result<Self, Error> {
131        x.as_slice().try_into()
132    }
133}
134
135#[cfg(feature = "alloc")]
136impl TryFrom<&Vec<u8>> for Hash {
137    type Error = Error;
138    fn try_from(x: &Vec<u8>) -> Result<Self, Error> {
139        x.as_slice().try_into()
140    }
141}
142
143impl TryFrom<&[u8]> for Hash {
144    type Error = Error;
145    fn try_from(x: &[u8]) -> Result<Self, Error> {
146        Ok(Hash(x.try_into()?))
147    }
148}
149
150impl AsRef<[u8]> for Hash {
151    #[must_use]
152    fn as_ref(&self) -> &[u8] {
153        &self.0
154    }
155}