Skip to main content

identity_kit/jose/
one_or_many.rs

1//! `OneOrMany`, the one-value-or-a-list shape of JSON members such as `aud`.
2
3use serde::{Deserialize, Serialize};
4
5/// A value that is either one `T` or a list of them, serialized without the list when single.
6///
7/// RFC 7519 uses this for `aud`; DID Core for `controller` and the `type` of a service.
8#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
9#[serde(untagged)]
10pub enum OneOrMany<T> {
11    /// A single value.
12    One(T),
13    /// A list of values, kept as a list even when it holds one.
14    Many(Vec<T>),
15}
16
17impl<T> OneOrMany<T> {
18    /// The values, in order.
19    pub fn iter(&self) -> impl Iterator<Item = &T> {
20        match self {
21            Self::One(one) => core::slice::from_ref(one).iter(),
22            Self::Many(many) => many.iter(),
23        }
24    }
25
26    /// The values, mutably.
27    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
28        match self {
29            Self::One(one) => core::slice::from_mut(one).iter_mut(),
30            Self::Many(many) => many.iter_mut(),
31        }
32    }
33
34    /// The number of values.
35    pub fn len(&self) -> usize {
36        match self {
37            Self::One(_) => 1,
38            Self::Many(many) => many.len(),
39        }
40    }
41
42    /// Whether there are no values (an empty list).
43    pub fn is_empty(&self) -> bool {
44        self.len() == 0
45    }
46
47    /// The first value, if any.
48    pub fn first(&self) -> Option<&T> {
49        self.iter().next()
50    }
51
52    /// Whether `value` is among the values.
53    pub fn contains(&self, value: &T) -> bool
54    where
55        T: PartialEq,
56    {
57        self.iter().any(|v| v == value)
58    }
59
60    /// The values as a `Vec`.
61    pub fn into_vec(self) -> Vec<T> {
62        match self {
63            Self::One(one) => vec![one],
64            Self::Many(many) => many,
65        }
66    }
67}
68
69impl<T> From<T> for OneOrMany<T> {
70    fn from(value: T) -> Self {
71        Self::One(value)
72    }
73}
74
75impl<T> From<Vec<T>> for OneOrMany<T> {
76    fn from(values: Vec<T>) -> Self {
77        Self::Many(values)
78    }
79}
80
81impl From<&str> for OneOrMany<String> {
82    fn from(value: &str) -> Self {
83        Self::One(value.to_owned())
84    }
85}