Skip to main content

kanidmd_lib/valueset/
index.rs

1use crate::{
2    prelude::*,
3    schema::SchemaAttribute,
4    valueset::{DbValueSetV2, ScimResolveStatus, ValueSet, ValueSetResolveStatus, ValueSetScimPut},
5};
6use kanidm_proto::scim_v1::JsonValue;
7
8use smolset::SmolSet;
9
10#[derive(Debug, Clone)]
11pub struct ValueSetIndex {
12    set: SmolSet<[IndexType; 3]>,
13}
14
15impl ValueSetIndex {
16    pub fn new(s: IndexType) -> Box<Self> {
17        let mut set = SmolSet::new();
18        set.insert(s);
19        Box::new(ValueSetIndex { set })
20    }
21
22    pub fn push(&mut self, s: IndexType) -> bool {
23        self.set.insert(s)
24    }
25
26    pub fn from_dbvs2(data: Vec<u16>) -> Result<ValueSet, OperationError> {
27        let set: Result<_, _> = data.into_iter().map(IndexType::try_from).collect();
28        let set = set.map_err(|_| OperationError::InvalidValueState)?;
29        Ok(Box::new(ValueSetIndex { set }))
30    }
31
32    // We need to allow this, because there seems to be a bug using it fromiterator in entry.rs
33    #[allow(clippy::should_implement_trait)]
34    pub fn from_iter<T>(iter: T) -> Option<Box<ValueSetIndex>>
35    where
36        T: IntoIterator<Item = IndexType>,
37    {
38        let set = iter.into_iter().collect();
39        Some(Box::new(ValueSetIndex { set }))
40    }
41}
42
43impl ValueSetScimPut for ValueSetIndex {
44    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
45        let value = serde_json::from_value::<Vec<String>>(value).map_err(|err| {
46            error!(?err, "SCIM IndexType syntax invalid");
47            OperationError::SC0009IndexTypeSyntaxInvalid
48        })?;
49
50        let set = value
51            .into_iter()
52            .map(|s| {
53                IndexType::try_from(s.as_str()).map_err(|_| {
54                    error!("SCIM IndexType syntax invalid value");
55                    OperationError::SC0009IndexTypeSyntaxInvalid
56                })
57            })
58            .collect::<Result<_, _>>()?;
59
60        Ok(ValueSetResolveStatus::Resolved(Box::new(ValueSetIndex {
61            set,
62        })))
63    }
64}
65
66impl ValueSetT for ValueSetIndex {
67    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
68        match value {
69            Value::Index(u) => Ok(self.set.insert(u)),
70            _ => {
71                debug_assert!(false);
72                Err(OperationError::InvalidValueState)
73            }
74        }
75    }
76
77    fn clear(&mut self) {
78        self.set.clear();
79    }
80
81    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
82        match pv {
83            PartialValue::Index(u) => {
84                self.set.remove(u);
85            }
86            _ => {
87                debug_assert!(false);
88            }
89        };
90        self.set.is_empty()
91    }
92
93    fn contains(&self, pv: &PartialValue) -> bool {
94        match pv {
95            PartialValue::Index(u) => self.set.contains(u),
96            _ => false,
97        }
98    }
99
100    fn substring(&self, _pv: &PartialValue) -> bool {
101        false
102    }
103
104    fn startswith(&self, _pv: &PartialValue) -> bool {
105        false
106    }
107
108    fn endswith(&self, _pv: &PartialValue) -> bool {
109        false
110    }
111
112    fn lessthan(&self, _pv: &PartialValue) -> bool {
113        false
114    }
115
116    fn len(&self) -> usize {
117        self.set.len()
118    }
119
120    fn generate_idx_eq_keys(&self) -> Vec<String> {
121        self.set.iter().map(|b| b.to_string()).collect()
122    }
123
124    fn syntax(&self) -> SyntaxType {
125        SyntaxType::IndexId
126    }
127
128    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
129        true
130    }
131
132    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
133        Box::new(self.set.iter().map(|b| b.to_string()))
134    }
135
136    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
137        Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
138            self.set.iter().map(|u| u.to_string()).collect::<Vec<_>>(),
139        )))
140    }
141
142    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
143        DbValueSetV2::IndexType(self.set.iter().map(|s| *s as u16).collect())
144    }
145
146    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
147        Box::new(self.set.iter().copied().map(PartialValue::Index))
148    }
149
150    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
151        Box::new(self.set.iter().copied().map(Value::Index))
152    }
153
154    fn equal(&self, other: &ValueSet) -> bool {
155        if let Some(other) = other.as_index_set() {
156            &self.set == other
157        } else {
158            debug_assert!(false);
159            false
160        }
161    }
162
163    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
164        if let Some(b) = other.as_index_set() {
165            mergesets!(self.set, b)
166        } else {
167            debug_assert!(false);
168            Err(OperationError::InvalidValueState)
169        }
170    }
171
172    fn as_indextype_iter(&self) -> Option<Box<dyn Iterator<Item = IndexType> + '_>> {
173        Some(Box::new(self.set.iter().copied()))
174    }
175
176    fn as_index_set(&self) -> Option<&SmolSet<[IndexType; 3]>> {
177        Some(&self.set)
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::ValueSetIndex;
184    use crate::prelude::{IndexType, ValueSet};
185
186    #[test]
187    fn test_scim_index() {
188        let vs: ValueSet = ValueSetIndex::new(IndexType::Equality);
189        crate::valueset::scim_json_reflexive(&vs, r#"["EQUALITY"]"#);
190
191        // Test that we can parse json values into a valueset.
192        crate::valueset::scim_json_put_reflexive::<ValueSetIndex>(&vs, &[])
193    }
194}