1use crate::{check_concern, hostcalls, Status};
2
3#[derive(Clone)]
6pub struct SharedData<T: AsRef<str>>(T);
7
8impl<T: AsRef<str>> SharedData<T> {
9 pub fn from_key(key: T) -> Self {
11 Self(key)
12 }
13
14 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 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 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 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}