Skip to main content

rustorb_rtps/
parameter.rs

1//! Parameter lists (DDSI-RTPS 2.5, 8.3.5.9 and 9.4.2.11).
2//!
3//! Only the framing is handled here: each parameter's value is kept as raw
4//! octets. Reading the values (PL_CDR) belongs to discovery (SPDP/SEDP).
5
6use crate::error::{DecodeError, EncodeError};
7use crate::wire::{Endianness, Reader, Writer};
8
9/// A parameter id (DDSI-RTPS 2.5, 9.4.2.11.2).
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
11pub struct ParameterId(pub u16);
12
13impl ParameterId {
14    /// `PID_PAD`: padding, skipped when reading.
15    pub const PAD: ParameterId = ParameterId(0x0000);
16    /// `PID_SENTINEL`: ends the list.
17    pub const SENTINEL: ParameterId = ParameterId(0x0001);
18
19    /// Whether the id is in the vendor-specific range (bit `0x8000`).
20    pub const fn is_vendor_specific(self) -> bool {
21        self.0 & 0x8000 != 0
22    }
23
24    /// Whether a receiver that does not know the id must treat it as an
25    /// error rather than skip it (bit `0x4000`, Table 9.6).
26    pub const fn must_understand(self) -> bool {
27        self.0 & 0x4000 != 0
28    }
29}
30
31/// One parameter: an id and its value.
32#[derive(Clone, Debug, PartialEq, Eq, Hash)]
33pub struct Parameter {
34    /// The parameter id.
35    pub id: ParameterId,
36    /// The value octets, including any trailing padding the sender put in
37    /// the length.
38    pub value: Vec<u8>,
39}
40
41impl Parameter {
42    /// A parameter with the given id and value.
43    pub fn new(id: ParameterId, value: impl Into<Vec<u8>>) -> Self {
44        Parameter {
45            id,
46            value: value.into(),
47        }
48    }
49}
50
51/// The parameters of DDS Security in a discovery parameter list (ids
52/// `0x1000..=0x1fff` and `0x5000..=0x5fff`, DDS Security 1.2, 7.5.1.3),
53/// kept as octets for the security plugins. Their values depend on the
54/// byte order of the list, so each order has its own copy: a list read
55/// fills the one of its order; a list to write uses the one of its order.
56#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
57pub struct SecurityParameters {
58    /// The parameters with little-endian values.
59    pub little: Vec<Parameter>,
60    /// The parameters with big-endian values.
61    pub big: Vec<Parameter>,
62}
63
64impl SecurityParameters {
65    /// Whether `id` is one of DDS Security's.
66    pub const fn is_security(id: ParameterId) -> bool {
67        matches!(id.0, 0x1000..=0x1fff | 0x5000..=0x5fff)
68    }
69
70    /// Whether there are none.
71    pub fn is_empty(&self) -> bool {
72        self.little.is_empty() && self.big.is_empty()
73    }
74
75    /// The parameters in `e` order.
76    pub fn of(&self, e: Endianness) -> &[Parameter] {
77        match e {
78            Endianness::Little => &self.little,
79            Endianness::Big => &self.big,
80        }
81    }
82
83    /// The parameters in either order, and that order: what a list read
84    /// had.
85    pub fn any(&self) -> Option<(&[Parameter], Endianness)> {
86        if !self.little.is_empty() {
87            Some((&self.little, Endianness::Little))
88        } else if !self.big.is_empty() {
89            Some((&self.big, Endianness::Big))
90        } else {
91            None
92        }
93    }
94
95    /// Keeps `p`, read in `e` order.
96    pub fn push(&mut self, p: Parameter, e: Endianness) {
97        match e {
98            Endianness::Little => self.little.push(p),
99            Endianness::Big => self.big.push(p),
100        }
101    }
102}
103
104/// A list of parameters.
105///
106/// `PID_PAD` entries are dropped when reading and never written. The
107/// sentinel is not stored: it is written by [`ParameterList::encode`] when
108/// asked for.
109#[derive(Clone, Debug, Default)]
110pub struct ParameterList {
111    /// The parameters in wire order. An id may appear more than once.
112    pub parameters: Vec<Parameter>,
113    /// The byte order of the values, for a list that was read: that of
114    /// its submessage or encapsulation. Lists compare by their
115    /// parameters alone.
116    endianness: Option<Endianness>,
117}
118
119impl PartialEq for ParameterList {
120    fn eq(&self, other: &Self) -> bool {
121        self.parameters == other.parameters
122    }
123}
124
125impl Eq for ParameterList {}
126
127impl std::hash::Hash for ParameterList {
128    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
129        self.parameters.hash(state)
130    }
131}
132
133impl ParameterList {
134    /// An empty list.
135    pub fn new() -> Self {
136        ParameterList::default()
137    }
138
139    /// The first parameter with the given id.
140    pub fn get(&self, id: ParameterId) -> Option<&Parameter> {
141        self.parameters.iter().find(|p| p.id == id)
142    }
143
144    /// All parameters with the given id, in order.
145    pub fn get_all(&self, id: ParameterId) -> impl Iterator<Item = &Parameter> {
146        self.parameters.iter().filter(move |p| p.id == id)
147    }
148
149    /// Appends a parameter.
150    pub fn push(&mut self, parameter: Parameter) {
151        self.parameters.push(parameter);
152    }
153
154    /// Reads a parameter list from the start of `bytes`.
155    ///
156    /// With `require_sentinel`, the list must end with `PID_SENTINEL`
157    /// (every parameter list except the one in a HeaderExtension,
158    /// 9.4.2.11.1); without it, the list may also end at the end of
159    /// `bytes`. Returns the list and the number of octets read, including
160    /// the sentinel.
161    pub fn decode(
162        bytes: &[u8],
163        endianness: Endianness,
164        require_sentinel: bool,
165    ) -> Result<(ParameterList, usize), DecodeError> {
166        let mut r = Reader::new(bytes, endianness);
167        let list = Self::read(&mut r, require_sentinel)?;
168        Ok((list, r.position()))
169    }
170
171    pub(crate) fn read(
172        r: &mut Reader<'_>,
173        require_sentinel: bool,
174    ) -> Result<ParameterList, DecodeError> {
175        let mut parameters = Vec::new();
176        loop {
177            if r.is_empty() && !require_sentinel {
178                break;
179            }
180            let id = ParameterId(
181                r.u16()
182                    .map_err(|_| DecodeError::InvalidParameterList("missing PID_SENTINEL"))?,
183            );
184            let length = r
185                .u16()
186                .map_err(|_| DecodeError::InvalidParameterList("truncated parameter header"))?;
187            if id == ParameterId::SENTINEL {
188                // "its length is ignored" (9.4.2.11.1).
189                break;
190            }
191            let value = r
192                .bytes(length as usize)
193                .map_err(|_| DecodeError::InvalidParameterList("parameter goes past the end"))?;
194            if id != ParameterId::PAD {
195                parameters.push(Parameter::new(id, value));
196            }
197        }
198        Ok(ParameterList {
199            parameters,
200            endianness: Some(r.endianness()),
201        })
202    }
203
204    /// The byte order of the values of a list that was read, `None` for
205    /// one that was built.
206    pub fn endianness(&self) -> Option<Endianness> {
207        self.endianness
208    }
209
210    /// Writes the list to the end of `out`.
211    ///
212    /// Each value is padded with zeros to a multiple of four octets, so
213    /// that every parameter starts on a 4-octet boundary (9.4.2.11.1).
214    /// With `sentinel`, `PID_SENTINEL` is written at the end.
215    pub fn encode(
216        &self,
217        out: &mut Vec<u8>,
218        endianness: Endianness,
219        sentinel: bool,
220    ) -> Result<(), EncodeError> {
221        self.write(&mut Writer::new(out, endianness), sentinel)
222    }
223
224    pub(crate) fn write(&self, w: &mut Writer<'_>, sentinel: bool) -> Result<(), EncodeError> {
225        for p in &self.parameters {
226            let padded = p.value.len().next_multiple_of(4);
227            let length = u16::try_from(padded).map_err(|_| EncodeError::ParameterTooLong)?;
228            w.u16(p.id.0);
229            w.u16(length);
230            w.bytes(&p.value);
231            w.zeros(padded - p.value.len());
232        }
233        if sentinel {
234            w.u16(ParameterId::SENTINEL.0);
235            w.u16(0);
236        }
237        Ok(())
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn round_trip_both_endians() {
247        let mut list = ParameterList::new();
248        list.push(Parameter::new(ParameterId(0x0050), [1, 2, 3, 4]));
249        list.push(Parameter::new(ParameterId(0x8001), [9; 8]));
250        for e in [Endianness::Big, Endianness::Little] {
251            let mut out = Vec::new();
252            list.encode(&mut out, e, true).unwrap();
253            assert_eq!(out.len(), 4 + 4 + 4 + 8 + 4);
254            let (back, used) = ParameterList::decode(&out, e, true).unwrap();
255            assert_eq!(back, list);
256            assert_eq!(used, out.len());
257        }
258    }
259
260    #[test]
261    fn big_endian_layout() {
262        let mut list = ParameterList::new();
263        list.push(Parameter::new(ParameterId(0x0015), [2, 5]));
264        let mut out = Vec::new();
265        list.encode(&mut out, Endianness::Big, true).unwrap();
266        assert_eq!(
267            out,
268            [0x00, 0x15, 0x00, 0x04, 2, 5, 0, 0, 0x00, 0x01, 0x00, 0x00]
269        );
270    }
271
272    #[test]
273    fn pad_is_skipped_and_sentinel_length_ignored() {
274        let bytes = [
275            0x00, 0x00, 0x00, 0x04, 0xaa, 0xbb, 0xcc, 0xdd, // PID_PAD
276            0x00, 0x30, 0x00, 0x04, 1, 2, 3, 4, // 0x0030
277            0x00, 0x01, 0x12, 0x34, // sentinel with a junk length
278            0xff, 0xff, // after the list
279        ];
280        let (list, used) = ParameterList::decode(&bytes, Endianness::Big, true).unwrap();
281        assert_eq!(used, 20);
282        assert_eq!(
283            list.parameters,
284            [Parameter::new(ParameterId(0x30), [1, 2, 3, 4])]
285        );
286    }
287
288    #[test]
289    fn missing_sentinel() {
290        let bytes = [0x30, 0x00, 0x04, 0x00, 1, 2, 3, 4];
291        assert!(ParameterList::decode(&bytes, Endianness::Little, true).is_err());
292        let (list, used) = ParameterList::decode(&bytes, Endianness::Little, false).unwrap();
293        assert_eq!(used, 8);
294        assert_eq!(list.parameters.len(), 1);
295    }
296
297    #[test]
298    fn value_past_end() {
299        let bytes = [0x00, 0x30, 0x00, 0x08, 1, 2, 3, 4];
300        assert_eq!(
301            ParameterList::decode(&bytes, Endianness::Big, false),
302            Err(DecodeError::InvalidParameterList(
303                "parameter goes past the end"
304            ))
305        );
306    }
307
308    #[test]
309    fn id_bits() {
310        assert!(ParameterId(0x8000).is_vendor_specific());
311        assert!(!ParameterId(0x7fff).is_vendor_specific());
312        assert!(ParameterId(0x4001).must_understand());
313        assert!(!ParameterId(0x0001).must_understand());
314    }
315}