der/asn1/
set_of.rs

1//! ASN.1 `SET OF` support.
2
3use crate::{
4    arrayvec, ArrayVec, Decodable, DecodeValue, Decoder, DerOrd, Encodable, EncodeValue, Encoder,
5    ErrorKind, FixedTag, Length, Result, Tag,
6};
7use core::cmp::Ordering;
8
9#[cfg(feature = "alloc")]
10use {alloc::vec::Vec, core::slice};
11
12/// ASN.1 `SET OF` backed by an array.
13///
14/// This type implements an append-only `SET OF` type which is stack-based
15/// and does not depend on `alloc` support.
16// TODO(tarcieri): use `ArrayVec` when/if it's merged into `core`
17// See: https://github.com/rust-lang/rfcs/pull/2990
18#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
19pub struct SetOf<T, const N: usize>
20where
21    T: Clone + DerOrd,
22{
23    inner: ArrayVec<T, N>,
24}
25
26impl<T, const N: usize> SetOf<T, N>
27where
28    T: Clone + DerOrd,
29{
30    /// Create a new [`SetOf`].
31    pub fn new() -> Self {
32        Self {
33            inner: ArrayVec::default(),
34        }
35    }
36
37    /// Add an element to this [`SetOf`].
38    ///
39    /// Items MUST be added in lexicographical order according to the
40    /// [`DerOrd`] impl on `T`.
41    pub fn add(&mut self, new_elem: T) -> Result<()> {
42        // Ensure set elements are lexicographically ordered
43        if let Some(last_elem) = self.inner.last() {
44            if new_elem.der_cmp(last_elem)? != Ordering::Greater {
45                return Err(ErrorKind::SetOrdering.into());
46            }
47        }
48
49        self.inner.add(new_elem)
50    }
51
52    /// Get the nth element from this [`SetOf`].
53    pub fn get(&self, index: usize) -> Option<&T> {
54        self.inner.get(index)
55    }
56
57    /// Iterate over the elements of this [`SetOf`].
58    pub fn iter(&self) -> SetOfIter<'_, T> {
59        SetOfIter {
60            inner: self.inner.iter(),
61        }
62    }
63
64    /// Is this [`SetOf`] empty?
65    pub fn is_empty(&self) -> bool {
66        self.inner.is_empty()
67    }
68
69    /// Number of elements in this [`SetOf`].
70    pub fn len(&self) -> usize {
71        self.inner.len()
72    }
73}
74
75impl<T, const N: usize> Default for SetOf<T, N>
76where
77    T: Clone + DerOrd,
78{
79    fn default() -> Self {
80        Self::new()
81    }
82}
83
84impl<'a, T, const N: usize> DecodeValue<'a> for SetOf<T, N>
85where
86    T: Clone + Decodable<'a> + DerOrd,
87{
88    fn decode_value(decoder: &mut Decoder<'a>, length: Length) -> Result<Self> {
89        let end_pos = (decoder.position() + length)?;
90        let mut result = Self::new();
91
92        while decoder.position() < end_pos {
93            result.add(decoder.decode()?)?;
94        }
95
96        if decoder.position() != end_pos {
97            decoder.error(ErrorKind::Length { tag: Self::TAG });
98        }
99
100        Ok(result)
101    }
102}
103
104impl<'a, T, const N: usize> EncodeValue for SetOf<T, N>
105where
106    T: 'a + Clone + Decodable<'a> + Encodable + DerOrd,
107{
108    fn value_len(&self) -> Result<Length> {
109        self.iter()
110            .fold(Ok(Length::ZERO), |len, elem| len + elem.encoded_len()?)
111    }
112
113    fn encode_value(&self, encoder: &mut Encoder<'_>) -> Result<()> {
114        for elem in self.iter() {
115            elem.encode(encoder)?;
116        }
117
118        Ok(())
119    }
120}
121
122impl<'a, T, const N: usize> FixedTag for SetOf<T, N>
123where
124    T: Clone + Decodable<'a> + DerOrd,
125{
126    const TAG: Tag = Tag::Set;
127}
128
129/// Iterator over the elements of an [`SetOf`].
130#[derive(Clone, Debug)]
131pub struct SetOfIter<'a, T> {
132    /// Inner iterator.
133    inner: arrayvec::Iter<'a, T>,
134}
135
136impl<'a, T> Iterator for SetOfIter<'a, T> {
137    type Item = &'a T;
138
139    fn next(&mut self) -> Option<&'a T> {
140        self.inner.next()
141    }
142}
143
144/// ASN.1 `SET OF` backed by a [`Vec`].
145///
146/// This type implements an append-only `SET OF` type which is heap-backed
147/// and depends on `alloc` support.
148#[cfg(feature = "alloc")]
149#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
150#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
151pub struct SetOfVec<T>
152where
153    T: Clone + DerOrd,
154{
155    inner: Vec<T>,
156}
157
158#[cfg(feature = "alloc")]
159#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
160impl<T> SetOfVec<T>
161where
162    T: Clone + DerOrd,
163{
164    /// Create a new [`SetOfVec`].
165    pub fn new() -> Self {
166        Self {
167            inner: Vec::default(),
168        }
169    }
170
171    /// Add an element to this [`SetOfVec`].
172    ///
173    /// Items MUST be added in lexicographical order according to the
174    /// [`DerOrd`] impl on `T`.
175    pub fn add(&mut self, new_elem: T) -> Result<()> {
176        // Ensure set elements are lexicographically ordered
177        if let Some(last_elem) = self.inner.last() {
178            if new_elem.der_cmp(last_elem)? != Ordering::Greater {
179                return Err(ErrorKind::SetOrdering.into());
180            }
181        }
182
183        self.inner.push(new_elem);
184        Ok(())
185    }
186
187    /// Get the nth element from this [`SetOfVec`].
188    pub fn get(&self, index: usize) -> Option<&T> {
189        self.inner.get(index)
190    }
191
192    /// Iterate over the elements of this [`SetOfVec`].
193    pub fn iter(&self) -> slice::Iter<'_, T> {
194        self.inner.iter()
195    }
196
197    /// Is this [`SetOfVec`] empty?
198    pub fn is_empty(&self) -> bool {
199        self.inner.is_empty()
200    }
201
202    /// Number of elements in this [`SetOfVec`].
203    pub fn len(&self) -> usize {
204        self.inner.len()
205    }
206}
207
208#[cfg(feature = "alloc")]
209#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
210impl<'a, T> DecodeValue<'a> for SetOfVec<T>
211where
212    T: Clone + Decodable<'a> + DerOrd,
213{
214    fn decode_value(decoder: &mut Decoder<'a>, length: Length) -> Result<Self> {
215        let end_pos = (decoder.position() + length)?;
216        let mut result = Self::new();
217
218        while decoder.position() < end_pos {
219            result.add(decoder.decode()?)?;
220        }
221
222        if decoder.position() != end_pos {
223            decoder.error(ErrorKind::Length { tag: Self::TAG });
224        }
225
226        Ok(result)
227    }
228}
229
230#[cfg(feature = "alloc")]
231#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
232impl<'a, T> EncodeValue for SetOfVec<T>
233where
234    T: 'a + Clone + Decodable<'a> + Encodable + DerOrd,
235{
236    fn value_len(&self) -> Result<Length> {
237        self.iter()
238            .fold(Ok(Length::ZERO), |len, elem| len + elem.encoded_len()?)
239    }
240
241    fn encode_value(&self, encoder: &mut Encoder<'_>) -> Result<()> {
242        for elem in self.iter() {
243            elem.encode(encoder)?;
244        }
245
246        Ok(())
247    }
248}
249
250#[cfg(feature = "alloc")]
251#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
252impl<T> FixedTag for SetOfVec<T>
253where
254    T: Clone + DerOrd,
255{
256    const TAG: Tag = Tag::Set;
257}