Skip to main content

made_core/value_objects/agentic_system/
capability.rs

1use std::fmt;
2
3use serde::{Deserialize, Deserializer, Serialize};
4
5use crate::error::DomainError;
6
7use super::slug;
8
9const MAX_LEN: usize = 128;
10
11/// Something a participant can do, named the way hosts name it.
12///
13/// A design requires capabilities; whether one exists is the host's
14/// answer, and a capability nobody supplies makes a ceremony skip
15/// rather than pretend.
16#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
17#[serde(transparent)]
18pub struct Capability(String);
19
20impl Capability {
21    pub fn new(raw: impl AsRef<str>) -> Result<Self, DomainError> {
22        slug::slug("capability", raw.as_ref(), MAX_LEN).map(Self)
23    }
24
25    #[must_use]
26    pub fn as_str(&self) -> &str {
27        &self.0
28    }
29
30    #[must_use]
31    pub fn into_inner(self) -> String {
32        self.0
33    }
34}
35
36impl fmt::Display for Capability {
37    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38        formatter.write_str(&self.0)
39    }
40}
41
42impl TryFrom<&str> for Capability {
43    type Error = DomainError;
44
45    fn try_from(value: &str) -> Result<Self, Self::Error> {
46        Self::new(value)
47    }
48}
49
50impl TryFrom<String> for Capability {
51    type Error = DomainError;
52
53    fn try_from(value: String) -> Result<Self, Self::Error> {
54        Self::new(value)
55    }
56}
57
58/// Decoding goes through the constructor.
59///
60/// A derived implementation would accept a stored or transmitted value
61/// this type refuses to be built from, and the invariant would hold
62/// everywhere except where the document came from outside — which is
63/// the only place it was ever at risk.
64impl<'de> Deserialize<'de> for Capability {
65    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
66        Self::new(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
67    }
68}