1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use crate::prelude::*;
use crate::schema::SchemaAttribute;
use crate::valueset::ScimResolveStatus;
use crate::valueset::{DbValueSetV2, ValueSet};
use kanidm_proto::internal::Filter as ProtoFilter;

use smolset::SmolSet;

#[derive(Debug, Clone)]
pub struct ValueSetJsonFilter {
    set: SmolSet<[ProtoFilter; 1]>,
}

impl ValueSetJsonFilter {
    pub fn new(b: ProtoFilter) -> Box<Self> {
        let mut set = SmolSet::new();
        set.insert(b);
        Box::new(ValueSetJsonFilter { set })
    }

    pub fn push(&mut self, b: ProtoFilter) -> bool {
        self.set.insert(b)
    }

    pub fn from_dbvs2(data: &[String]) -> Result<ValueSet, OperationError> {
        let set = data
            .iter()
            .map(|s| serde_json::from_str(s).map_err(|_| OperationError::SerdeJsonError))
            .collect::<Result<_, _>>()?;
        Ok(Box::new(ValueSetJsonFilter { set }))
    }

    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
    // types, and protofilter is foreign.
    #[allow(clippy::should_implement_trait)]
    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
    where
        T: IntoIterator<Item = ProtoFilter>,
    {
        let set = iter.into_iter().collect();
        Some(Box::new(ValueSetJsonFilter { set }))
    }
}

impl ValueSetT for ValueSetJsonFilter {
    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
        match value {
            Value::JsonFilt(u) => Ok(self.set.insert(u)),
            _ => {
                debug_assert!(false);
                Err(OperationError::InvalidValueState)
            }
        }
    }

    fn clear(&mut self) {
        self.set.clear();
    }

    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
        match pv {
            PartialValue::JsonFilt(u) => self.set.remove(u),
            _ => {
                debug_assert!(false);
                true
            }
        }
    }

    fn contains(&self, pv: &PartialValue) -> bool {
        match pv {
            PartialValue::JsonFilt(u) => self.set.contains(u),
            _ => false,
        }
    }

    fn substring(&self, _pv: &PartialValue) -> bool {
        false
    }

    fn startswith(&self, _pv: &PartialValue) -> bool {
        false
    }

    fn endswith(&self, _pv: &PartialValue) -> bool {
        false
    }

    fn lessthan(&self, _pv: &PartialValue) -> bool {
        false
    }

    fn len(&self) -> usize {
        self.set.len()
    }

    fn generate_idx_eq_keys(&self) -> Vec<String> {
        self.set
            .iter()
            .map(|s| {
                #[allow(clippy::expect_used)]
                serde_json::to_string(s).expect("A json filter value was corrupted during run-time")
            })
            .collect()
    }

    fn syntax(&self) -> SyntaxType {
        SyntaxType::JsonFilter
    }

    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
        true
    }

    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
        Box::new(self.set.iter().filter_map(|i| {
            serde_json::to_string(i)
                .inspect_err(|err| {
                    error!(?err, "A json filter value was corrupted during run-time")
                })
                .ok()
        }))
    }

    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
        Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
            self.set
                .iter()
                .filter_map(|s| {
                    serde_json::to_string(s)
                        .inspect_err(|err| {
                            error!(?err, "A json filter value was corrupted during run-time")
                        })
                        .ok()
                })
                .collect::<Vec<_>>(),
        )))
    }

    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
        DbValueSetV2::JsonFilter(
            self.set
                .iter()
                .filter_map(|s| {
                    serde_json::to_string(s)
                        .inspect_err(|err| {
                            error!(?err, "A json filter value was corrupted during run-time")
                        })
                        .ok()
                })
                .collect(),
        )
    }

    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
        Box::new(self.set.iter().cloned().map(PartialValue::JsonFilt))
    }

    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
        Box::new(self.set.iter().cloned().map(Value::JsonFilt))
    }

    fn equal(&self, other: &ValueSet) -> bool {
        if let Some(other) = other.as_json_filter_set() {
            &self.set == other
        } else {
            debug_assert!(false);
            false
        }
    }

    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
        if let Some(b) = other.as_json_filter_set() {
            mergesets!(self.set, b)
        } else {
            debug_assert!(false);
            Err(OperationError::InvalidValueState)
        }
    }

    fn to_json_filter_single(&self) -> Option<&ProtoFilter> {
        if self.set.len() == 1 {
            self.set.iter().take(1).next()
        } else {
            None
        }
    }

    fn as_json_filter_set(&self) -> Option<&SmolSet<[ProtoFilter; 1]>> {
        Some(&self.set)
    }
}

#[cfg(test)]
mod tests {
    use super::{ProtoFilter, ValueSetJsonFilter};
    use crate::prelude::{Attribute, ValueSet};

    #[test]
    fn test_scim_json_filter() {
        let filter = ProtoFilter::Pres(Attribute::Class.to_string());
        let vs: ValueSet = ValueSetJsonFilter::new(filter);

        let data = r#"
[
  "{\"pres\":\"class\"}"
]
        "#;
        crate::valueset::scim_json_reflexive(vs, data);
    }
}