wapod_types/
primitives.rs

1//! Some basic types used in the Wapod project.
2
3use alloc::string::{String, ToString};
4use alloc::vec::Vec;
5
6use core::ops::Deref;
7use scale::{Decode, Encode, MaxEncodedLen};
8use scale_info::TypeInfo;
9
10/// A 32-byte array.
11pub type Bytes32 = [u8; 32];
12/// Address of an application or a worker.
13pub type Address = Bytes32;
14/// A blake2b hash value.
15pub type Hash = Bytes32;
16/// Worker public key.
17pub type WorkerPubkey = Bytes32;
18
19/// A bounded vector with a maximum length.
20#[derive(Debug, Clone, PartialEq, Eq, Encode)]
21pub struct BoundedVec<T, const B: usize>(pub Vec<T>);
22
23impl<T, const B: usize> BoundedVec<T, B> {
24    /// The maximum length of the vector.
25    pub fn max_len(&self) -> usize {
26        B
27    }
28
29    /// The current length of the vector.
30    pub fn len(&self) -> usize {
31        self.0.len()
32    }
33
34    /// Whether the vector is empty.
35    pub fn is_empty(&self) -> bool {
36        self.0.is_empty()
37    }
38
39    /// Push a value to the vector.
40    pub fn push(&mut self, value: T) -> Result<(), T> {
41        if self.len() >= B {
42            return Err(value);
43        }
44        self.0.push(value);
45        Ok(())
46    }
47
48    /// Pop a value from the vector.
49    pub fn pop(&mut self) -> Option<T> {
50        self.0.pop()
51    }
52
53    /// Clear the vector.
54    pub fn clear(&mut self) {
55        self.0.clear()
56    }
57
58    /// Iterate over the vector.
59    pub fn iter(&self) -> core::slice::Iter<'_, T> {
60        self.0.iter()
61    }
62
63    /// Mutably iterate over the vector.
64    pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, T> {
65        self.0.iter_mut()
66    }
67
68    /// As a slice.
69    pub fn as_slice(&self) -> &[T] {
70        self.0.as_slice()
71    }
72
73    /// As a mutable slice.
74    pub fn as_mut_slice(&mut self) -> &mut [T] {
75        self.0.as_mut_slice()
76    }
77
78    /// Convert into the inner vector.
79    pub fn into_inner(self) -> Vec<T> {
80        self.0
81    }
82}
83
84impl<T, const B: usize> Default for BoundedVec<T, B> {
85    fn default() -> Self {
86        Self(Default::default())
87    }
88}
89
90impl<T: Decode, const B: usize> Decode for BoundedVec<T, B> {
91    fn decode<I: scale::Input>(input: &mut I) -> Result<Self, scale::Error> {
92        let vec = Vec::<T>::decode(input)?;
93        if vec.len() > B {
94            return Err(scale::Error::from("BoundedVec: length exceeds bound"));
95        }
96        Ok(Self(vec))
97    }
98}
99
100impl<T, const B: usize> Deref for BoundedVec<T, B> {
101    type Target = [T];
102
103    fn deref(&self) -> &Self::Target {
104        self.0.deref()
105    }
106}
107
108impl<T, const B: usize> From<Vec<T>> for BoundedVec<T, B> {
109    fn from(vec: Vec<T>) -> Self {
110        Self(vec)
111    }
112}
113
114impl<T, const B: usize> From<&[T]> for BoundedVec<T, B>
115where
116    T: Clone,
117{
118    fn from(slice: &[T]) -> Self {
119        Self(slice.to_vec())
120    }
121}
122
123impl<T, const B: usize> From<BoundedVec<T, B>> for Vec<T> {
124    fn from(bounded_vec: BoundedVec<T, B>) -> Self {
125        bounded_vec.0
126    }
127}
128impl<T: MaxEncodedLen, const B: usize> MaxEncodedLen for BoundedVec<T, B> {
129    fn max_encoded_len() -> usize {
130        B * T::max_encoded_len()
131    }
132}
133
134impl<T: TypeInfo + 'static, const B: usize> TypeInfo for BoundedVec<T, B> {
135    type Identity = <Vec<T> as TypeInfo>::Identity;
136
137    fn type_info() -> scale_info::Type {
138        <Vec<T> as TypeInfo>::type_info()
139    }
140}
141
142impl<T, const B: usize> IntoIterator for BoundedVec<T, B> {
143    type Item = <Vec<T> as IntoIterator>::Item;
144    type IntoIter = <Vec<T> as IntoIterator>::IntoIter;
145    fn into_iter(self) -> Self::IntoIter {
146        self.0.into_iter()
147    }
148}
149
150/// A bounded string with a maximum length.
151#[derive(Debug, Clone, PartialEq, Eq, Encode, Default)]
152pub struct BoundedString<const B: usize>(pub String);
153
154impl<const B: usize> Deref for BoundedString<B> {
155    type Target = str;
156
157    fn deref(&self) -> &Self::Target {
158        &self.0
159    }
160}
161
162impl<const B: usize> From<String> for BoundedString<B> {
163    fn from(s: String) -> Self {
164        Self(s)
165    }
166}
167
168impl<const B: usize> From<&str> for BoundedString<B> {
169    fn from(s: &str) -> Self {
170        Self(s.to_string())
171    }
172}
173
174impl<const B: usize> From<BoundedString<B>> for String {
175    fn from(bounded_string: BoundedString<B>) -> Self {
176        bounded_string.0
177    }
178}
179
180impl<const B: usize> TypeInfo for BoundedString<B> {
181    type Identity = <String as TypeInfo>::Identity;
182
183    fn type_info() -> scale_info::Type {
184        <String as TypeInfo>::type_info()
185    }
186}
187
188impl<const B: usize> Decode for BoundedString<B> {
189    fn decode<I: scale::Input>(input: &mut I) -> Result<Self, scale::Error> {
190        let s = String::decode(input)?;
191        if s.as_bytes().len() > B {
192            return Err(scale::Error::from("BoundedString: length exceeds bound"));
193        }
194        Ok(Self(s))
195    }
196}
197
198impl<const B: usize> core::fmt::Display for BoundedString<B> {
199    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
200        write!(f, "{}", self.0)
201    }
202}
203
204impl<const B: usize> MaxEncodedLen for BoundedString<B> {
205    fn max_encoded_len() -> usize {
206        B
207    }
208}