freenet_stdlib/
parameters.rs

1use std::borrow::Cow;
2
3use serde::{Deserialize, Deserializer, Serialize};
4use serde_with::serde_as;
5
6/// Data that forms part of a contract or a delegate along with the WebAssembly code.
7///
8/// This is supplied to the contract as a parameter to the contract's functions. Parameters are
9/// typically be used to configure a contract, much like the parameters of a constructor function.
10#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
11#[serde_as]
12#[cfg_attr(feature = "testing", derive(arbitrary::Arbitrary))]
13pub struct Parameters<'a>(
14    // TODO: conver this to Arc<u8> instead
15    #[serde_as(as = "serde_with::Bytes")]
16    #[serde(borrow)]
17    Cow<'a, [u8]>,
18);
19
20impl Parameters<'_> {
21    /// Gets the number of bytes of data stored in the `Parameters`.
22    pub fn size(&self) -> usize {
23        self.0.len()
24    }
25
26    /// Returns the bytes of parameters.
27    pub fn into_bytes(self) -> Vec<u8> {
28        self.0.into_owned()
29    }
30
31    /// Copies the data if not owned and returns an owned version of self.
32    pub fn into_owned(self) -> Parameters<'static> {
33        let data: Cow<'static, _> = Cow::from(self.0.into_owned());
34        Parameters(data)
35    }
36
37    pub fn deser_params<'de, D>(deser: D) -> Result<Parameters<'static>, D::Error>
38    where
39        D: Deserializer<'de>,
40    {
41        let data: Parameters<'de> = Deserialize::deserialize(deser)?;
42        Ok(data.into_owned())
43    }
44}
45
46impl From<Vec<u8>> for Parameters<'_> {
47    fn from(data: Vec<u8>) -> Self {
48        Parameters(Cow::from(data))
49    }
50}
51
52impl<'a> From<&'a [u8]> for Parameters<'a> {
53    fn from(s: &'a [u8]) -> Self {
54        Parameters(Cow::from(s))
55    }
56}
57
58impl AsRef<[u8]> for Parameters<'_> {
59    fn as_ref(&self) -> &[u8] {
60        match &self.0 {
61            Cow::Borrowed(arr) => arr,
62            Cow::Owned(arr) => arr.as_ref(),
63        }
64    }
65}