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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
use std::cmp::Ordering;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::ops::{BitAnd, BitOr, BitXor, Deref, DerefMut};
use std::str::FromStr;

use derive_more::{From, Into, IntoIterator};
use serde::{Deserialize, Serialize};
use strum::{EnumMessage, IntoEnumIterator};

/// Represents the kinds of capabilities available.
pub use crate::request::RequestKind as CapabilityKind;

/// Set of supported capabilities for a server
#[derive(Clone, Debug, From, Into, PartialEq, Eq, IntoIterator, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Capabilities(#[into_iterator(owned, ref)] HashSet<Capability>);

impl Capabilities {
    /// Return set of capabilities encompassing all possible capabilities
    pub fn all() -> Self {
        Self(CapabilityKind::iter().map(Capability::from).collect())
    }

    /// Return empty set of capabilities
    pub fn none() -> Self {
        Self(HashSet::new())
    }

    /// Returns true if the capability with described kind is included
    pub fn contains(&self, kind: impl AsRef<str>) -> bool {
        let cap = Capability {
            kind: kind.as_ref().to_string(),
            description: String::new(),
        };
        self.0.contains(&cap)
    }

    /// Adds the specified capability to the set of capabilities
    ///
    /// * If the set did not have this capability, returns `true`
    /// * If the set did have this capability, returns `false`
    pub fn insert(&mut self, cap: impl Into<Capability>) -> bool {
        self.0.insert(cap.into())
    }

    /// Removes the capability with the described kind, returning the capability
    pub fn take(&mut self, kind: impl AsRef<str>) -> Option<Capability> {
        let cap = Capability {
            kind: kind.as_ref().to_string(),
            description: String::new(),
        };
        self.0.take(&cap)
    }

    /// Removes the capability with the described kind, returning true if it existed
    pub fn remove(&mut self, kind: impl AsRef<str>) -> bool {
        let cap = Capability {
            kind: kind.as_ref().to_string(),
            description: String::new(),
        };
        self.0.remove(&cap)
    }

    /// Converts into vec of capabilities sorted by kind
    pub fn into_sorted_vec(self) -> Vec<Capability> {
        let mut this = self.0.into_iter().collect::<Vec<_>>();

        this.sort_unstable();

        this
    }
}

impl AsRef<HashSet<Capability>> for Capabilities {
    fn as_ref(&self) -> &HashSet<Capability> {
        &self.0
    }
}

impl AsMut<HashSet<Capability>> for Capabilities {
    fn as_mut(&mut self) -> &mut HashSet<Capability> {
        &mut self.0
    }
}

impl Deref for Capabilities {
    type Target = HashSet<Capability>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Capabilities {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl BitAnd for &Capabilities {
    type Output = Capabilities;

    fn bitand(self, rhs: Self) -> Self::Output {
        Capabilities(self.0.bitand(&rhs.0))
    }
}

impl BitOr for &Capabilities {
    type Output = Capabilities;

    fn bitor(self, rhs: Self) -> Self::Output {
        Capabilities(self.0.bitor(&rhs.0))
    }
}

impl BitOr<Capability> for &Capabilities {
    type Output = Capabilities;

    fn bitor(self, rhs: Capability) -> Self::Output {
        let mut other = Capabilities::none();
        other.0.insert(rhs);

        self.bitor(&other)
    }
}

impl BitXor for &Capabilities {
    type Output = Capabilities;

    fn bitxor(self, rhs: Self) -> Self::Output {
        Capabilities(self.0.bitxor(&rhs.0))
    }
}

impl FromIterator<Capability> for Capabilities {
    fn from_iter<I: IntoIterator<Item = Capability>>(iter: I) -> Self {
        let mut this = Capabilities::none();

        for capability in iter {
            this.0.insert(capability);
        }

        this
    }
}

/// Capability tied to a server. A capability is equivalent based on its kind and not description.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub struct Capability {
    /// Label describing the kind of capability
    pub kind: String,

    /// Information about the capability
    pub description: String,
}

impl Capability {
    /// Will convert the [`Capability`]'s `kind` into a known [`CapabilityKind`] if possible,
    /// returning None if the capability is unknown
    pub fn to_capability_kind(&self) -> Option<CapabilityKind> {
        CapabilityKind::from_str(&self.kind).ok()
    }

    /// Returns true if the described capability is unknown
    pub fn is_unknown(&self) -> bool {
        self.to_capability_kind().is_none()
    }
}

impl PartialEq for Capability {
    fn eq(&self, other: &Self) -> bool {
        self.kind.eq_ignore_ascii_case(&other.kind)
    }
}

impl Eq for Capability {}

impl PartialOrd for Capability {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Capability {
    fn cmp(&self, other: &Self) -> Ordering {
        self.kind
            .to_ascii_lowercase()
            .cmp(&other.kind.to_ascii_lowercase())
    }
}

impl Hash for Capability {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.kind.to_ascii_lowercase().hash(state);
    }
}

impl From<CapabilityKind> for Capability {
    /// Creates a new capability using the kind's default message
    fn from(kind: CapabilityKind) -> Self {
        Self {
            kind: kind.to_string(),
            description: kind
                .get_message()
                .map(ToString::to_string)
                .unwrap_or_default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod capabilities {
        use super::*;

        #[test]
        fn should_be_able_to_serialize_to_json() {
            let capabilities: Capabilities = [Capability {
                kind: "some kind".to_string(),
                description: "some description".to_string(),
            }]
            .into_iter()
            .collect();

            let value = serde_json::to_value(capabilities).unwrap();
            assert_eq!(
                value,
                serde_json::json!([
                    {
                        "kind": "some kind",
                        "description": "some description",
                    }
                ])
            );
        }

        #[test]
        fn should_be_able_to_deserialize_from_json() {
            let value = serde_json::json!([
                {
                    "kind": "some kind",
                    "description": "some description",
                }
            ]);

            let capabilities: Capabilities = serde_json::from_value(value).unwrap();
            assert_eq!(
                capabilities,
                [Capability {
                    kind: "some kind".to_string(),
                    description: "some description".to_string(),
                }]
                .into_iter()
                .collect()
            );
        }

        #[test]
        fn should_be_able_to_serialize_to_msgpack() {
            let capabilities: Capabilities = [Capability {
                kind: "some kind".to_string(),
                description: "some description".to_string(),
            }]
            .into_iter()
            .collect();

            // NOTE: We don't actually check the output here because it's an implementation detail
            // and could change as we change how serialization is done. This is merely to verify
            // that we can serialize since there are times when serde fails to serialize at
            // runtime.
            let _ = rmp_serde::encode::to_vec_named(&capabilities).unwrap();
        }

        #[test]
        fn should_be_able_to_deserialize_from_msgpack() {
            // NOTE: It may seem odd that we are serializing just to deserialize, but this is to
            // verify that we are not corrupting or preventing issues when serializing on a
            // client/server and then trying to deserialize on the other side. This has happened
            // enough times with minor changes that we need tests to verify.
            let buf = rmp_serde::encode::to_vec_named(
                &[Capability {
                    kind: "some kind".to_string(),
                    description: "some description".to_string(),
                }]
                .into_iter()
                .collect::<Capabilities>(),
            )
            .unwrap();

            let capabilities: Capabilities = rmp_serde::decode::from_slice(&buf).unwrap();
            assert_eq!(
                capabilities,
                [Capability {
                    kind: "some kind".to_string(),
                    description: "some description".to_string(),
                }]
                .into_iter()
                .collect()
            );
        }
    }

    mod capability {
        use super::*;

        #[test]
        fn should_be_able_to_serialize_to_json() {
            let capability = Capability {
                kind: "some kind".to_string(),
                description: "some description".to_string(),
            };

            let value = serde_json::to_value(capability).unwrap();
            assert_eq!(
                value,
                serde_json::json!({
                    "kind": "some kind",
                    "description": "some description",
                })
            );
        }

        #[test]
        fn should_be_able_to_deserialize_from_json() {
            let value = serde_json::json!({
                "kind": "some kind",
                "description": "some description",
            });

            let capability: Capability = serde_json::from_value(value).unwrap();
            assert_eq!(
                capability,
                Capability {
                    kind: "some kind".to_string(),
                    description: "some description".to_string(),
                }
            );
        }

        #[test]
        fn should_be_able_to_serialize_to_msgpack() {
            let capability = Capability {
                kind: "some kind".to_string(),
                description: "some description".to_string(),
            };

            // NOTE: We don't actually check the output here because it's an implementation detail
            // and could change as we change how serialization is done. This is merely to verify
            // that we can serialize since there are times when serde fails to serialize at
            // runtime.
            let _ = rmp_serde::encode::to_vec_named(&capability).unwrap();
        }

        #[test]
        fn should_be_able_to_deserialize_from_msgpack() {
            // NOTE: It may seem odd that we are serializing just to deserialize, but this is to
            // verify that we are not corrupting or causing issues when serializing on a
            // client/server and then trying to deserialize on the other side. This has happened
            // enough times with minor changes that we need tests to verify.
            let buf = rmp_serde::encode::to_vec_named(&Capability {
                kind: "some kind".to_string(),
                description: "some description".to_string(),
            })
            .unwrap();

            let capability: Capability = rmp_serde::decode::from_slice(&buf).unwrap();
            assert_eq!(
                capability,
                Capability {
                    kind: "some kind".to_string(),
                    description: "some description".to_string(),
                }
            );
        }
    }
}