Skip to main content

canic_types/
lib.rs

1use candid::CandidType;
2use canic_memory::impl_storable_bounded;
3use serde::{Deserialize, Serialize};
4use std::{borrow::Borrow, borrow::Cow, fmt, str::FromStr};
5
6const ROOT_ROLE: &str = "root";
7const WASM_STORE_ROLE: &str = "wasm_store";
8
9///
10/// CanisterRole
11///
12
13#[derive(
14    CandidType, Clone, Debug, Eq, Ord, PartialOrd, Deserialize, Serialize, PartialEq, Hash,
15)]
16#[serde(transparent)]
17pub struct CanisterRole(pub Cow<'static, str>);
18
19impl CanisterRole {
20    pub const ROOT: Self = Self(Cow::Borrowed(ROOT_ROLE));
21    pub const WASM_STORE: Self = Self(Cow::Borrowed(WASM_STORE_ROLE));
22
23    #[must_use]
24    pub const fn new(s: &'static str) -> Self {
25        Self(Cow::Borrowed(s))
26    }
27
28    #[must_use]
29    pub const fn owned(s: String) -> Self {
30        Self(Cow::Owned(s))
31    }
32
33    #[must_use]
34    pub fn as_str(&self) -> &str {
35        &self.0
36    }
37
38    #[must_use]
39    pub fn is_root(&self) -> bool {
40        self.0.as_ref() == ROOT_ROLE
41    }
42
43    #[must_use]
44    pub fn is_wasm_store(&self) -> bool {
45        self.0.as_ref() == WASM_STORE_ROLE
46    }
47
48    #[must_use]
49    pub fn into_string(self) -> String {
50        self.0.into_owned()
51    }
52}
53
54impl FromStr for CanisterRole {
55    type Err = String;
56
57    fn from_str(s: &str) -> Result<Self, Self::Err> {
58        Ok(Self::owned(s.to_string()))
59    }
60}
61
62impl From<&'static str> for CanisterRole {
63    fn from(s: &'static str) -> Self {
64        Self(Cow::Borrowed(s))
65    }
66}
67
68impl From<&String> for CanisterRole {
69    fn from(s: &String) -> Self {
70        Self(Cow::Owned(s.clone()))
71    }
72}
73
74impl From<String> for CanisterRole {
75    fn from(s: String) -> Self {
76        Self(Cow::Owned(s))
77    }
78}
79
80impl From<CanisterRole> for String {
81    fn from(role: CanisterRole) -> Self {
82        role.into_string()
83    }
84}
85
86impl AsRef<str> for CanisterRole {
87    fn as_ref(&self) -> &str {
88        self.as_str()
89    }
90}
91
92impl Borrow<str> for CanisterRole {
93    fn borrow(&self) -> &str {
94        self.as_str()
95    }
96}
97
98impl fmt::Display for CanisterRole {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.write_str(self.as_str())
101    }
102}
103
104impl_storable_bounded!(CanisterRole, 64, false);