Skip to main content

kanidmd_lib/valueset/
iutf8.rs

1use crate::{
2    prelude::*,
3    schema::SchemaAttribute,
4    utils::trigraph_iter,
5    valueset::{DbValueSetV2, ScimResolveStatus, ValueSet, ValueSetResolveStatus, ValueSetScimPut},
6};
7use kanidm_proto::scim_v1::{client::ScimStrings, JsonValue};
8use std::collections::BTreeSet;
9
10#[derive(Debug, Clone)]
11pub struct ValueSetIutf8 {
12    value: String,
13}
14
15impl ValueSetIutf8 {
16    pub fn new(s: &str) -> Box<Self> {
17        Box::new(ValueSetIutf8 {
18            value: s.to_lowercase(),
19        })
20    }
21
22    pub fn from_dbvs2(value: String) -> Result<ValueSet, OperationError> {
23        Ok(Box::new(ValueSetIutf8 { value }))
24    }
25}
26
27impl ValueSetScimPut for ValueSetIutf8 {
28    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
29        let value: String = serde_json::from_value(value).map_err(|err| {
30            error!(?err, "SCIM Iutf8 Syntax Invalid");
31            OperationError::SC0017Iutf8SyntaxInvalid
32        })?;
33
34        Ok(ValueSetResolveStatus::Resolved(Box::new(ValueSetIutf8 {
35            value: value.to_lowercase(),
36        })))
37    }
38}
39
40impl ValueSetT for ValueSetIutf8 {
41    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
42        match value {
43            Value::Iutf8(s) => {
44                if self.value != s {
45                    self.value = s;
46                    Ok(true)
47                } else {
48                    Ok(false)
49                }
50            }
51            _ => {
52                debug_assert!(false);
53                Err(OperationError::InvalidValueState)
54            }
55        }
56    }
57
58    fn clear(&mut self) {}
59
60    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
61        match pv {
62            PartialValue::Iutf8(s) => *s == self.value,
63            _ => {
64                debug_assert!(false);
65                false
66            }
67        }
68    }
69
70    fn contains(&self, pv: &PartialValue) -> bool {
71        match pv {
72            PartialValue::Iutf8(s) => *s == self.value,
73            _ => false,
74        }
75    }
76
77    fn substring(&self, pv: &PartialValue) -> bool {
78        match pv {
79            PartialValue::Iutf8(s2) => self.value.contains(s2),
80            _ => {
81                debug_assert!(false);
82                false
83            }
84        }
85    }
86
87    fn startswith(&self, pv: &PartialValue) -> bool {
88        match pv {
89            PartialValue::Iutf8(s2) => self.value.starts_with(s2),
90            _ => {
91                debug_assert!(false);
92                false
93            }
94        }
95    }
96
97    fn endswith(&self, pv: &PartialValue) -> bool {
98        match pv {
99            PartialValue::Iutf8(s2) => self.value.ends_with(s2),
100            _ => {
101                debug_assert!(false);
102                false
103            }
104        }
105    }
106
107    fn lessthan(&self, _pv: &PartialValue) -> bool {
108        false
109    }
110
111    fn len(&self) -> usize {
112        1
113    }
114
115    fn generate_idx_eq_keys(&self) -> Vec<String> {
116        std::iter::once(self.value.clone()).collect()
117    }
118
119    fn generate_idx_sub_keys(&self) -> Vec<String> {
120        debug_assert!(self.value == self.value.to_lowercase());
121
122        let mut trigraphs: Vec<_> = trigraph_iter(&self.value).collect();
123
124        trigraphs.sort_unstable();
125        trigraphs.dedup();
126
127        trigraphs.into_iter().map(String::from).collect()
128    }
129
130    fn syntax(&self) -> SyntaxType {
131        SyntaxType::Utf8StringInsensitive
132    }
133
134    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
135        Value::validate_str_escapes(&self.value) && Value::validate_singleline(&self.value) &&
136                // I'm sure there is a better way ...
137                self.value.to_lowercase().as_str() == self.value.as_str()
138    }
139
140    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
141        Box::new(std::iter::once(self.value.clone()))
142    }
143
144    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
145        Some(self.value.clone().into())
146    }
147
148    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
149        DbValueSetV2::Iutf8Single(self.value.clone())
150    }
151
152    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
153        Box::new(std::iter::once(PartialValue::Iutf8(self.value.clone())))
154    }
155
156    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
157        Box::new(std::iter::once(Value::Iutf8(self.value.clone())))
158    }
159
160    fn equal(&self, other: &ValueSet) -> bool {
161        if let Some(other) = other.to_iutf8_single() {
162            self.value == other
163        } else {
164            debug_assert!(false);
165            false
166        }
167    }
168
169    fn merge(&mut self, _other: &ValueSet) -> Result<(), OperationError> {
170        debug_assert!(false);
171        Err(OperationError::InvalidValueState)
172    }
173
174    fn to_iutf8_single(&self) -> Option<&str> {
175        Some(self.value.as_str())
176    }
177}
178
179#[derive(Debug, Clone)]
180pub struct ValueSetIutf8N {
181    set: BTreeSet<String>,
182}
183
184impl ValueSetIutf8N {
185    pub fn new(s: &str) -> Box<Self> {
186        let mut set = BTreeSet::new();
187        set.insert(s.to_lowercase());
188        Box::new(ValueSetIutf8N { set })
189    }
190
191    pub fn push(&mut self, s: &str) -> bool {
192        self.set.insert(s.to_lowercase())
193    }
194
195    pub fn from_dbvs2(data: Vec<String>) -> Result<ValueSet, OperationError> {
196        let set = data.into_iter().collect();
197        Ok(Box::new(ValueSetIutf8N { set }))
198    }
199
200    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
201    // types, and str is foreign.
202    #[allow(clippy::should_implement_trait)]
203    pub fn from_iter<'a, T>(iter: T) -> Option<ValueSet>
204    where
205        T: IntoIterator<Item = &'a str>,
206    {
207        let set: BTreeSet<_> = iter.into_iter().map(str::to_string).collect();
208        if set.is_empty() {
209            None
210        } else {
211            Some(Box::new(ValueSetIutf8N { set }))
212        }
213    }
214}
215
216impl ValueSetScimPut for ValueSetIutf8N {
217    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
218        let ScimStrings(values) = serde_json::from_value(value).map_err(|err| {
219            error!(?err, "SCIM Iutf8 Syntax Invalid");
220            OperationError::SC0017Iutf8SyntaxInvalid
221        })?;
222
223        let set = values.iter().map(|s| s.to_lowercase()).collect();
224
225        Ok(ValueSetResolveStatus::Resolved(Box::new(ValueSetIutf8N {
226            set,
227        })))
228    }
229}
230
231impl ValueSetT for ValueSetIutf8N {
232    fn migrate(&self) -> Result<Option<ValueSet>, OperationError> {
233        Ok(self.to_iutf8_single().map(|value| {
234            Box::new(ValueSetIutf8 {
235                value: value.to_string(),
236            }) as ValueSet
237        }))
238    }
239
240    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
241        match value {
242            Value::Iutf8N(s) => Ok(self.set.insert(s)),
243            _ => {
244                debug_assert!(false);
245                Err(OperationError::InvalidValueState)
246            }
247        }
248    }
249
250    fn clear(&mut self) {
251        self.set.clear();
252    }
253
254    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
255        match pv {
256            PartialValue::Iutf8(s) => {
257                self.set.remove(s);
258            }
259            _ => {
260                debug_assert!(false);
261            }
262        };
263        self.set.is_empty()
264    }
265
266    fn contains(&self, pv: &PartialValue) -> bool {
267        match pv {
268            PartialValue::Iutf8(s) => self.set.contains(s.as_str()),
269            _ => false,
270        }
271    }
272
273    fn substring(&self, pv: &PartialValue) -> bool {
274        match pv {
275            PartialValue::Iutf8(s2) => self.set.iter().any(|s1| s1.contains(s2)),
276            _ => {
277                debug_assert!(false);
278                false
279            }
280        }
281    }
282
283    fn startswith(&self, pv: &PartialValue) -> bool {
284        match pv {
285            PartialValue::Iutf8(s2) => self.set.iter().any(|s1| s1.starts_with(s2)),
286            _ => {
287                debug_assert!(false);
288                false
289            }
290        }
291    }
292
293    fn endswith(&self, pv: &PartialValue) -> bool {
294        match pv {
295            PartialValue::Iutf8(s2) => self.set.iter().any(|s1| s1.ends_with(s2)),
296            _ => {
297                debug_assert!(false);
298                false
299            }
300        }
301    }
302
303    fn lessthan(&self, _pv: &PartialValue) -> bool {
304        false
305    }
306
307    fn len(&self) -> usize {
308        self.set.len()
309    }
310
311    fn generate_idx_eq_keys(&self) -> Vec<String> {
312        self.set.iter().cloned().collect()
313    }
314
315    fn generate_idx_sub_keys(&self) -> Vec<String> {
316        let mut trigraphs: Vec<_> = self.set.iter().flat_map(|v| trigraph_iter(v)).collect();
317
318        trigraphs.sort_unstable();
319        trigraphs.dedup();
320
321        trigraphs.into_iter().map(String::from).collect()
322    }
323
324    fn syntax(&self) -> SyntaxType {
325        SyntaxType::Utf8StringInsensitiveN
326    }
327
328    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
329        self.set.iter().all(|s| {
330            Value::validate_str_escapes(s) && Value::validate_singleline(s) &&
331                // I'm sure there is a better way ...
332                s.to_lowercase().as_str() == s.as_str()
333        })
334    }
335
336    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
337        Box::new(self.set.iter().cloned())
338    }
339
340    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
341        // In future we'll make this array only in the response.
342        /*
343        let arr = self.set.iter().cloned().collect::<Vec<_>>();
344        Some(arr.into())
345        */
346        let mut iter = self.set.iter().cloned();
347        if self.len() == 1 {
348            let v = iter.next().unwrap_or_default();
349            Some(v.into())
350        } else {
351            let arr = iter.collect::<Vec<_>>();
352            Some(arr.into())
353        }
354    }
355
356    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
357        DbValueSetV2::Iutf8(self.set.iter().cloned().collect())
358    }
359
360    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
361        Box::new(self.set.iter().map(|i| PartialValue::new_iutf8(i.as_str())))
362    }
363
364    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
365        Box::new(self.set.iter().cloned().map(Value::Iutf8N))
366    }
367
368    fn equal(&self, other: &ValueSet) -> bool {
369        if let Some(other) = other.as_iutf8_set() {
370            &self.set == other
371        } else {
372            debug_assert!(false);
373            false
374        }
375    }
376
377    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
378        if let Some(b) = other.as_iutf8_set() {
379            mergesets!(self.set, b)
380        } else {
381            debug_assert!(false);
382            Err(OperationError::InvalidValueState)
383        }
384    }
385
386    fn to_iutf8_single(&self) -> Option<&str> {
387        if self.set.len() == 1 {
388            self.set.iter().take(1).next().map(|s| s.as_str())
389        } else {
390            None
391        }
392    }
393
394    fn as_iutf8_set(&self) -> Option<&BTreeSet<String>> {
395        Some(&self.set)
396    }
397
398    fn as_iutf8_iter(&self) -> Option<Box<dyn Iterator<Item = &str> + '_>> {
399        Some(Box::new(self.set.iter().map(|s| s.as_str())))
400    }
401
402    /*
403    fn migrate_iutf8_iname(&self) -> Result<Option<ValueSet>, OperationError> {
404        let vsi: Option<ValueSet> =
405            ValueSetIname::from_iter(self.set.iter().map(|s| s.as_str())).map(|vs| vs as _);
406        Ok(vsi)
407    }
408    */
409}
410
411#[cfg(test)]
412mod tests {
413    use super::{ValueSetIutf8, ValueSetIutf8N};
414    use crate::prelude::ValueSet;
415
416    #[test]
417    fn test_scim_iutf8_single() {
418        let vs: ValueSet = ValueSetIutf8::new("lowercase string");
419        crate::valueset::scim_json_reflexive(&vs, r#""lowercase string""#);
420
421        // Test that we can parse json values into a valueset.
422        crate::valueset::scim_json_put_reflexive::<ValueSetIutf8>(&vs, &[])
423    }
424
425    #[test]
426    fn test_scim_iutf8_multi() {
427        let vs: ValueSet = ValueSetIutf8N::from_iter(["lowercase string", "more string"]).unwrap();
428        crate::valueset::scim_json_reflexive(&vs, r#"["lowercase string", "more string"]"#);
429
430        // Test that we can parse json values into a valueset.
431        crate::valueset::scim_json_put_reflexive::<ValueSetIutf8N>(&vs, &[])
432    }
433}