ssi_vc/syntax/
non_empty_vec.rs

1use serde::{Deserialize, Serialize};
2use std::ops::{Deref, DerefMut};
3
4#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
5#[serde(transparent)]
6pub struct NonEmptyVec<T>(Vec<T>);
7
8#[derive(Debug, thiserror::Error)]
9#[error("empty vec")]
10pub struct EmptyVecError;
11
12impl<T> NonEmptyVec<T> {
13    pub fn new(t: T) -> Self {
14        Self(vec![t])
15    }
16
17    pub fn try_from_vec(v: Vec<T>) -> Result<Self, EmptyVecError> {
18        Self::try_from(v)
19    }
20
21    pub fn push(&mut self, t: T) {
22        self.0.push(t)
23    }
24
25    pub fn into_inner(self) -> Vec<T> {
26        self.0
27    }
28}
29
30impl<T> TryFrom<Vec<T>> for NonEmptyVec<T> {
31    type Error = EmptyVecError;
32
33    fn try_from(v: Vec<T>) -> Result<NonEmptyVec<T>, Self::Error> {
34        if v.is_empty() {
35            return Err(EmptyVecError);
36        }
37        Ok(NonEmptyVec(v))
38    }
39}
40
41impl<T> From<NonEmptyVec<T>> for Vec<T> {
42    fn from(NonEmptyVec(v): NonEmptyVec<T>) -> Vec<T> {
43        v
44    }
45}
46
47impl<T> AsRef<[T]> for NonEmptyVec<T> {
48    fn as_ref(&self) -> &[T] {
49        &self.0
50    }
51}
52
53impl<T> Deref for NonEmptyVec<T> {
54    type Target = [T];
55
56    fn deref(&self) -> &[T] {
57        &self.0
58    }
59}
60
61impl<T> DerefMut for NonEmptyVec<T> {
62    fn deref_mut(&mut self) -> &mut [T] {
63        &mut self.0
64    }
65}
66
67impl<T> IntoIterator for NonEmptyVec<T> {
68    type Item = T;
69    type IntoIter = std::vec::IntoIter<Self::Item>;
70
71    fn into_iter(self) -> Self::IntoIter {
72        self.0.into_iter()
73    }
74}
75
76impl<'a, T> IntoIterator for &'a NonEmptyVec<T> {
77    type Item = &'a T;
78    type IntoIter = std::vec::IntoIter<Self::Item>;
79
80    fn into_iter(self) -> Self::IntoIter {
81        self.0.iter().collect::<Vec<Self::Item>>().into_iter()
82    }
83}
84
85impl<'a, T> IntoIterator for &'a mut NonEmptyVec<T> {
86    type Item = &'a mut T;
87    type IntoIter = std::slice::IterMut<'a, T>;
88
89    fn into_iter(self) -> Self::IntoIter {
90        self.0.iter_mut()
91    }
92}
93
94impl<'de, T: Deserialize<'de>> Deserialize<'de> for NonEmptyVec<T> {
95    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
96    where
97        D: serde::Deserializer<'de>,
98    {
99        Vec::<T>::deserialize(deserializer)?
100            .try_into()
101            .map_err(serde::de::Error::custom)
102    }
103}