proxy_sdk/
shared_data.rs

1use crate::{check_concern, hostcalls, Status};
2
3/// A VM ID local atomic field. Any WASM VM in the same VM ID can read or write to any key in it's VM ID.
4/// SharedData cannot cross VM IDs.
5#[derive(Clone)]
6pub struct SharedData<T: AsRef<str>>(T);
7
8impl<T: AsRef<str>> SharedData<T> {
9    /// Create a new/reference an existing SharedData.
10    pub fn from_key(key: T) -> Self {
11        Self(key)
12    }
13
14    /// Gets the value of the SharedData. Doesn't return the check-and-set (CAS) number.
15    pub fn get(&self) -> Option<Vec<u8>> {
16        check_concern(
17            "shared-data-get",
18            hostcalls::get_shared_data(self.0.as_ref()),
19        )
20        .and_then(|x| x.0)
21    }
22
23    /// Gets the value and the check-and-set (CAS) number of the SharedData. CAS is `None` when the value has never been set before.
24    pub fn get_with_cas(&self) -> (Option<Vec<u8>>, Option<u32>) {
25        check_concern(
26            "shared-data-get-cas",
27            hostcalls::get_shared_data(self.0.as_ref()),
28        )
29        .unwrap_or_default()
30    }
31
32    /// Unconditionally sets the value of this SharedData.
33    pub fn set(&self, value: impl AsRef<[u8]>) {
34        check_concern(
35            "shared-data-set-casless",
36            hostcalls::set_shared_data(self.0.as_ref(), Some(value.as_ref()), None),
37        );
38    }
39
40    /// Sets the value of this SharedData only when the given `cas` number matches the one returned by a previous `get_with_cas`.
41    pub fn set_with_cas(&self, value: impl AsRef<[u8]>, cas: u32) -> bool {
42        match hostcalls::set_shared_data(self.0.as_ref(), Some(value.as_ref()), Some(cas)) {
43            Ok(()) => true,
44            Err(Status::CasMismatch) => false,
45            Err(e) => {
46                check_concern::<()>("shared-data-set-cas", Err(e));
47                false
48            }
49        }
50    }
51}