1use serde::{Deserialize, Serialize};
12
13pub type TermId = String;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
21#[serde(rename_all = "snake_case")]
22pub enum Sphere {
23 Selfhood,
25 #[default]
27 Personhood,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct TaxonomyTerm {
34 pub id: TermId,
35 pub label: String,
36 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub category: Option<TermId>,
39 #[serde(default)]
40 pub description: String,
41 #[serde(default)]
44 pub attributes: Vec<(String, String)>,
45}
46
47impl TaxonomyTerm {
48 pub fn new(id: impl Into<TermId>, label: impl Into<String>) -> Self {
50 Self {
51 id: id.into(),
52 label: label.into(),
53 category: None,
54 description: String::new(),
55 attributes: Vec::new(),
56 }
57 }
58
59 pub fn in_category(mut self, category: impl Into<TermId>) -> Self {
61 self.category = Some(category.into());
62 self
63 }
64
65 pub fn described(mut self, description: impl Into<String>) -> Self {
67 self.description = description.into();
68 self
69 }
70
71 pub fn with_attr(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
73 self.attributes.push((key.into(), value.into()));
74 self
75 }
76
77 pub fn attr(&self, key: &str) -> Option<&str> {
79 self.attributes
80 .iter()
81 .find(|(k, _)| k == key)
82 .map(|(_, v)| v.as_str())
83 }
84
85 pub fn attr_list(&self, key: &str) -> Vec<String> {
87 self.attr(key)
88 .map(|v| {
89 v.split(',')
90 .map(|s| s.trim().to_string())
91 .filter(|s| !s.is_empty())
92 .collect()
93 })
94 .unwrap_or_default()
95 }
96
97 pub fn sphere(&self) -> Sphere {
99 match self.attr("sphere") {
100 Some("selfhood") => Sphere::Selfhood,
101 _ => Sphere::Personhood,
102 }
103 }
104}
105
106#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
109pub struct Taxonomy {
110 terms: Vec<TaxonomyTerm>,
111}
112
113impl Taxonomy {
114 pub fn new() -> Self {
116 Self::default()
117 }
118
119 pub fn from_terms(terms: impl IntoIterator<Item = TaxonomyTerm>) -> Self {
121 let mut t = Self::new();
122 for term in terms {
123 t.insert(term);
124 }
125 t
126 }
127
128 pub fn insert(&mut self, term: TaxonomyTerm) {
131 if let Some(existing) = self.terms.iter_mut().find(|t| t.id == term.id) {
132 *existing = term;
133 } else {
134 self.terms.push(term);
135 }
136 }
137
138 pub fn extend_with(&mut self, other: &Taxonomy) {
140 for term in &other.terms {
141 self.insert(term.clone());
142 }
143 }
144
145 pub fn get(&self, id: &str) -> Option<&TaxonomyTerm> {
147 self.terms.iter().find(|t| t.id == id)
148 }
149
150 pub fn contains(&self, id: &str) -> bool {
152 self.get(id).is_some()
153 }
154
155 pub fn in_category(&self, category_id: &str) -> Vec<&TaxonomyTerm> {
157 self.terms
158 .iter()
159 .filter(|t| t.category.as_deref() == Some(category_id))
160 .collect()
161 }
162
163 pub fn all(&self) -> &[TaxonomyTerm] {
165 &self.terms
166 }
167
168 pub fn len(&self) -> usize {
170 self.terms.len()
171 }
172
173 pub fn is_empty(&self) -> bool {
175 self.terms.is_empty()
176 }
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182
183 #[test]
184 fn insert_get_and_replace_by_id() {
185 let mut tax = Taxonomy::new();
186 tax.insert(TaxonomyTerm::new("urn:x:a", "A").with_attr("v", "1"));
187 assert_eq!(tax.get("urn:x:a").unwrap().attr("v"), Some("1"));
188 tax.insert(TaxonomyTerm::new("urn:x:a", "A2").with_attr("v", "2"));
190 assert_eq!(tax.len(), 1);
191 assert_eq!(tax.get("urn:x:a").unwrap().label, "A2");
192 assert_eq!(tax.get("urn:x:a").unwrap().attr("v"), Some("2"));
193 }
194
195 #[test]
196 fn category_membership() {
197 let tax = Taxonomy::from_terms([
198 TaxonomyTerm::new("urn:cat", "Cat"),
199 TaxonomyTerm::new("urn:x:1", "One").in_category("urn:cat"),
200 TaxonomyTerm::new("urn:x:2", "Two").in_category("urn:cat"),
201 TaxonomyTerm::new("urn:y:1", "Other").in_category("urn:othercat"),
202 ]);
203 let members = tax.in_category("urn:cat");
204 assert_eq!(members.len(), 2);
205 }
206
207 #[test]
208 fn extensible_at_runtime_with_custom_term() {
209 let mut tax = Taxonomy::new();
211 tax.insert(
212 TaxonomyTerm::new("urn:custom:role:beekeeping-steward", "Beekeeping Steward")
213 .in_category("urn:qualia:guardianship-role:socio-economic")
214 .with_attr("domains", "custodial,welfare")
215 .with_attr("sphere", "personhood"),
216 );
217 assert!(tax.contains("urn:custom:role:beekeeping-steward"));
218 assert_eq!(
219 tax.get("urn:custom:role:beekeeping-steward")
220 .unwrap()
221 .sphere(),
222 Sphere::Personhood
223 );
224 }
225
226 #[test]
227 fn attr_list_parses_comma_members() {
228 let t = TaxonomyTerm::new("urn:x", "X").with_attr("domains", "health, welfare ,legal");
229 assert_eq!(t.attr_list("domains"), vec!["health", "welfare", "legal"]);
230 }
231
232 #[test]
233 fn sphere_defaults_to_personhood() {
234 assert_eq!(TaxonomyTerm::new("urn:x", "X").sphere(), Sphere::Personhood);
235 assert_eq!(
236 TaxonomyTerm::new("urn:x", "X")
237 .with_attr("sphere", "selfhood")
238 .sphere(),
239 Sphere::Selfhood
240 );
241 }
242}