olai_store/reference.rs
1use uuid::Uuid;
2
3use crate::ResourceName;
4
5/// A reference to a resource, by id, by name, or unspecified.
6///
7/// A resource can be addressed two ways: by its stable [`Uuid`] or by its
8/// human-readable [`ResourceName`]. [`Undefined`] is a third state for when no
9/// particular resource is meant (a wildcard), used chiefly in policy checks.
10///
11/// [`Undefined`]: ResourceRef::Undefined
12#[derive(Debug, Clone, PartialEq, Hash, Eq)]
13pub enum ResourceRef {
14 /// References a resource by its stable unique identifier.
15 Uuid(Uuid),
16 /// References a resource by its hierarchical [`ResourceName`].
17 Name(ResourceName),
18 /// Not referencing a specific resource.
19 ///
20 /// This is used to represent a wildcard in a policy
21 /// which can be useful to check if a user can create
22 /// or manage resources at a specific level.
23 Undefined,
24}
25
26impl ResourceRef {
27 /// Returns `true` if this reference is [`ResourceRef::Undefined`] (a wildcard).
28 pub fn is_undefined(&self) -> bool {
29 matches!(self, Self::Undefined)
30 }
31
32 /// Constructs a [`ResourceRef::Name`] from anything convertible into a
33 /// [`ResourceName`].
34 pub fn name(name: impl Into<ResourceName>) -> Self {
35 Self::Name(name.into())
36 }
37}
38
39impl std::fmt::Display for ResourceRef {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 match self {
42 Self::Uuid(u) => write!(f, "{}", u.hyphenated()),
43 Self::Name(name) => {
44 write!(f, "{name}")
45 }
46 Self::Undefined => write!(f, "*"),
47 }
48 }
49}
50
51impl From<Uuid> for ResourceRef {
52 fn from(val: Uuid) -> Self {
53 Self::Uuid(val)
54 }
55}
56
57impl From<&Uuid> for ResourceRef {
58 fn from(val: &Uuid) -> Self {
59 Self::Uuid(*val)
60 }
61}
62
63impl From<ResourceName> for ResourceRef {
64 fn from(val: ResourceName) -> Self {
65 Self::Name(val)
66 }
67}