Skip to main content

budget_context/
resource.rs

1use std::fmt;
2use std::sync::Arc;
3
4use crate::ResourceError;
5
6/// An application-defined resource category.
7///
8/// Names are non-empty, case-sensitive UTF-8 strings. The crate does not
9/// normalize them or attach meaning to namespace separators.
10#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub struct Resource(Arc<str>);
13
14impl Resource {
15    /// Creates a resource, rejecting an empty name.
16    ///
17    /// # Errors
18    ///
19    /// Returns [`ResourceError::EmptyName`] when `name` is empty.
20    pub fn new(name: impl Into<Arc<str>>) -> Result<Self, ResourceError> {
21        let name = name.into();
22        if name.is_empty() {
23            return Err(ResourceError::EmptyName);
24        }
25        Ok(Self(name))
26    }
27
28    /// Returns the resource name.
29    #[must_use]
30    pub fn as_str(&self) -> &str {
31        &self.0
32    }
33}
34
35impl fmt::Display for Resource {
36    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
37        formatter.write_str(&self.0)
38    }
39}
40
41/// A process-local identifier for a budget node.
42#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
43#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
44pub struct BudgetId(pub(crate) u64);
45
46impl BudgetId {
47    /// Returns the numeric process-local identifier.
48    #[must_use]
49    pub const fn get(self) -> u64 {
50        self.0
51    }
52}
53
54impl fmt::Display for BudgetId {
55    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
56        self.0.fmt(formatter)
57    }
58}