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