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(
13    any(feature = "testing", all(test, any(unix, windows))),
14    derive(arbitrary::Arbitrary)
15)]
16pub struct Parameters<'a>(
17    // TODO: conver this to Arc<u8> instead
18    #[serde_as(as = "serde_with::Bytes")]
19    #[serde(borrow)]
20    Cow<'a, [u8]>,
21);
22
23impl Parameters<'_> {
24    /// Gets the number of bytes of data stored in the `Parameters`.
25    pub fn size(&self) -> usize {
26        self.0.len()
27    }
28
29    /// Returns the bytes of parameters.
30    pub fn into_bytes(self) -> Vec<u8> {
31        self.0.into_owned()
32    }
33
34    /// Copies the data if not owned and returns an owned version of self.
35    pub fn into_owned(self) -> Parameters<'static> {
36        let data: Cow<'static, _> = Cow::from(self.0.into_owned());
37        Parameters(data)
38    }
39
40    pub fn deser_params<'de, D>(deser: D) -> Result<Parameters<'static>, D::Error>
41    where
42        D: Deserializer<'de>,
43    {
44        let data: Parameters<'de> = Deserialize::deserialize(deser)?;
45        Ok(data.into_owned())
46    }
47}
48
49impl From<Vec<u8>> for Parameters<'_> {
50    fn from(data: Vec<u8>) -> Self {
51        Parameters(Cow::from(data))
52    }
53}
54
55impl<'a> From<&'a [u8]> for Parameters<'a> {
56    fn from(s: &'a [u8]) -> Self {
57        Parameters(Cow::from(s))
58    }
59}
60
61impl AsRef<[u8]> for Parameters<'_> {
62    fn as_ref(&self) -> &[u8] {
63        match &self.0 {
64            Cow::Borrowed(arr) => arr,
65            Cow::Owned(arr) => arr.as_ref(),
66        }
67    }
68}