Skip to main content

rustorb_rtps/
pl.rs

1//! PL_CDR: parameter lists whose values are CDR, as used by the payloads
2//! of the discovery built-in endpoints (DDSI-RTPS 2.5, 9.6.3 and 10.3).
3//!
4//! The payload starts with the 4-octet SerializedPayloadHeader
5//! (`PL_CDR_BE` or `PL_CDR_LE`), followed by a parameter list ending with
6//! `PID_SENTINEL`. Each value is its own CDR stream: alignment restarts at
7//! the start of the value (9.4.2.11.1).
8
9use crate::error::DecodeError;
10use crate::parameter::{Parameter, ParameterId, ParameterList};
11use crate::types::{Duration, EntityId, Guid, GuidPrefix, Locator, ProtocolVersion, VendorId};
12use crate::wire::{Endianness, Reader, Writer};
13
14/// Parameter ids (DDSI-RTPS 2.5, Tables 9.18 and 9.20).
15pub mod pid {
16    use crate::parameter::ParameterId;
17
18    /// `PID_PAD`.
19    pub const PAD: ParameterId = ParameterId(0x0000);
20    /// `PID_SENTINEL`.
21    pub const SENTINEL: ParameterId = ParameterId(0x0001);
22    /// `PID_PARTICIPANT_LEASE_DURATION`.
23    pub const PARTICIPANT_LEASE_DURATION: ParameterId = ParameterId(0x0002);
24    /// `PID_TIME_BASED_FILTER`.
25    pub const TIME_BASED_FILTER: ParameterId = ParameterId(0x0004);
26    /// `PID_TOPIC_NAME`.
27    pub const TOPIC_NAME: ParameterId = ParameterId(0x0005);
28    /// `PID_OWNERSHIP_STRENGTH`.
29    pub const OWNERSHIP_STRENGTH: ParameterId = ParameterId(0x0006);
30    /// `PID_TYPE_NAME`.
31    pub const TYPE_NAME: ParameterId = ParameterId(0x0007);
32    /// `PID_DOMAIN_ID`.
33    pub const DOMAIN_ID: ParameterId = ParameterId(0x000f);
34    /// `PID_PROTOCOL_VERSION`.
35    pub const PROTOCOL_VERSION: ParameterId = ParameterId(0x0015);
36    /// `PID_VENDORID`.
37    pub const VENDORID: ParameterId = ParameterId(0x0016);
38    /// `PID_RELIABILITY`.
39    pub const RELIABILITY: ParameterId = ParameterId(0x001a);
40    /// `PID_LIVELINESS`.
41    pub const LIVELINESS: ParameterId = ParameterId(0x001b);
42    /// `PID_DURABILITY`.
43    pub const DURABILITY: ParameterId = ParameterId(0x001d);
44    /// `PID_DURABILITY_SERVICE`.
45    pub const DURABILITY_SERVICE: ParameterId = ParameterId(0x001e);
46    /// `PID_OWNERSHIP`.
47    pub const OWNERSHIP: ParameterId = ParameterId(0x001f);
48    /// `PID_PRESENTATION`.
49    pub const PRESENTATION: ParameterId = ParameterId(0x0021);
50    /// `PID_DEADLINE`.
51    pub const DEADLINE: ParameterId = ParameterId(0x0023);
52    /// `PID_DESTINATION_ORDER`.
53    pub const DESTINATION_ORDER: ParameterId = ParameterId(0x0025);
54    /// `PID_LATENCY_BUDGET`.
55    pub const LATENCY_BUDGET: ParameterId = ParameterId(0x0027);
56    /// `PID_PARTITION`.
57    pub const PARTITION: ParameterId = ParameterId(0x0029);
58    /// `PID_LIFESPAN`.
59    pub const LIFESPAN: ParameterId = ParameterId(0x002b);
60    /// `PID_USER_DATA`.
61    pub const USER_DATA: ParameterId = ParameterId(0x002c);
62    /// `PID_GROUP_DATA`.
63    pub const GROUP_DATA: ParameterId = ParameterId(0x002d);
64    /// `PID_TOPIC_DATA`.
65    pub const TOPIC_DATA: ParameterId = ParameterId(0x002e);
66    /// `PID_UNICAST_LOCATOR`.
67    pub const UNICAST_LOCATOR: ParameterId = ParameterId(0x002f);
68    /// `PID_MULTICAST_LOCATOR`.
69    pub const MULTICAST_LOCATOR: ParameterId = ParameterId(0x0030);
70    /// `PID_DEFAULT_UNICAST_LOCATOR`.
71    pub const DEFAULT_UNICAST_LOCATOR: ParameterId = ParameterId(0x0031);
72    /// `PID_METATRAFFIC_UNICAST_LOCATOR`.
73    pub const METATRAFFIC_UNICAST_LOCATOR: ParameterId = ParameterId(0x0032);
74    /// `PID_SERVICE_INSTANCE_NAME` (DDS-RPC 1.0, 7.6.2.1).
75    pub const SERVICE_INSTANCE_NAME: ParameterId = ParameterId(0x0080);
76    /// `PID_RELATED_ENTITY_GUID` (DDS-RPC 1.0, 7.6.2.1).
77    pub const RELATED_ENTITY_GUID: ParameterId = ParameterId(0x0081);
78    /// `PID_TOPIC_ALIASES` (DDS-RPC 1.0, 7.6.2.1).
79    pub const TOPIC_ALIASES: ParameterId = ParameterId(0x0082);
80    /// `PID_RELATED_SAMPLE_IDENTITY`, in-line (DDS-RPC 1.0, 7.8.2).
81    pub const RELATED_SAMPLE_IDENTITY: ParameterId = ParameterId(0x0083);
82    /// `PID_IDENTITY_TOKEN` (DDS Security 1.2, 7.5.1.4).
83    pub const IDENTITY_TOKEN: ParameterId = ParameterId(0x1001);
84    /// `PID_PERMISSIONS_TOKEN` (DDS Security 1.2, 7.5.1.4).
85    pub const PERMISSIONS_TOKEN: ParameterId = ParameterId(0x1002);
86    /// `PID_DATA_TAGS` (DDS Security 1.2, 7.5.1.7).
87    pub const DATA_TAGS: ParameterId = ParameterId(0x1003);
88    /// `PID_ENDPOINT_SECURITY_INFO` (DDS Security 1.2, 7.5.1.5).
89    pub const ENDPOINT_SECURITY_INFO: ParameterId = ParameterId(0x1004);
90    /// `PID_PARTICIPANT_SECURITY_INFO` (DDS Security 1.2, 7.5.1.4).
91    pub const PARTICIPANT_SECURITY_INFO: ParameterId = ParameterId(0x1005);
92    /// `PID_IDENTITY_STATUS_TOKEN` (DDS Security 1.2, 7.5.1.6).
93    pub const IDENTITY_STATUS_TOKEN: ParameterId = ParameterId(0x1006);
94    /// `PID_METATRAFFIC_MULTICAST_LOCATOR`.
95    pub const METATRAFFIC_MULTICAST_LOCATOR: ParameterId = ParameterId(0x0033);
96    /// `PID_PARTICIPANT_MANUAL_LIVELINESS_COUNT`.
97    pub const PARTICIPANT_MANUAL_LIVELINESS_COUNT: ParameterId = ParameterId(0x0034);
98    /// `PID_CONTENT_FILTER_PROPERTY`.
99    pub const CONTENT_FILTER_PROPERTY: ParameterId = ParameterId(0x0035);
100    /// `PID_HISTORY`.
101    pub const HISTORY: ParameterId = ParameterId(0x0040);
102    /// `PID_RESOURCE_LIMITS`.
103    pub const RESOURCE_LIMITS: ParameterId = ParameterId(0x0041);
104    /// `PID_EXPECTS_INLINE_QOS`.
105    pub const EXPECTS_INLINE_QOS: ParameterId = ParameterId(0x0043);
106    /// `PID_DEFAULT_MULTICAST_LOCATOR`.
107    pub const DEFAULT_MULTICAST_LOCATOR: ParameterId = ParameterId(0x0048);
108    /// `PID_TRANSPORT_PRIORITY`.
109    pub const TRANSPORT_PRIORITY: ParameterId = ParameterId(0x0049);
110    /// `PID_PARTICIPANT_GUID`.
111    pub const PARTICIPANT_GUID: ParameterId = ParameterId(0x0050);
112    /// `PID_GROUP_GUID`.
113    pub const GROUP_GUID: ParameterId = ParameterId(0x0052);
114    /// `PID_GROUP_ENTITY_ID`.
115    pub const GROUP_ENTITY_ID: ParameterId = ParameterId(0x0053);
116    /// `PID_CONTENT_FILTER_INFO`.
117    pub const CONTENT_FILTER_INFO: ParameterId = ParameterId(0x0055);
118    /// `PID_COHERENT_SET`.
119    pub const COHERENT_SET: ParameterId = ParameterId(0x0056);
120    /// `PID_DIRECTED_WRITE`.
121    pub const DIRECTED_WRITE: ParameterId = ParameterId(0x0057);
122    /// `PID_BUILTIN_ENDPOINT_SET`.
123    pub const BUILTIN_ENDPOINT_SET: ParameterId = ParameterId(0x0058);
124    /// `PID_PROPERTY_LIST`.
125    pub const PROPERTY_LIST: ParameterId = ParameterId(0x0059);
126    /// `PID_ENDPOINT_GUID`.
127    pub const ENDPOINT_GUID: ParameterId = ParameterId(0x005a);
128    /// `PID_TYPE_MAX_SIZE_SERIALIZED`.
129    pub const TYPE_MAX_SIZE_SERIALIZED: ParameterId = ParameterId(0x0060);
130    /// `PID_ORIGINAL_WRITER_INFO`.
131    pub const ORIGINAL_WRITER_INFO: ParameterId = ParameterId(0x0061);
132    /// `PID_ENTITY_NAME`.
133    pub const ENTITY_NAME: ParameterId = ParameterId(0x0062);
134    /// `PID_GROUP_COHERENT_SET`.
135    pub const GROUP_COHERENT_SET: ParameterId = ParameterId(0x0063);
136    /// `PID_GROUP_SEQ_NUM`.
137    pub const GROUP_SEQ_NUM: ParameterId = ParameterId(0x0064);
138    /// `PID_WRITER_GROUP_INFO`.
139    pub const WRITER_GROUP_INFO: ParameterId = ParameterId(0x0065);
140    /// `PID_SECURE_WRITER_GROUP_INFO`.
141    pub const SECURE_WRITER_GROUP_INFO: ParameterId = ParameterId(0x0066);
142    /// `PID_KEY_HASH`.
143    pub const KEY_HASH: ParameterId = ParameterId(0x0070);
144    /// `PID_STATUS_INFO`.
145    pub const STATUS_INFO: ParameterId = ParameterId(0x0071);
146    /// `PID_DATA_REPRESENTATION` (DDS-XTypes 1.3, 7.6.3.1).
147    pub const DATA_REPRESENTATION: ParameterId = ParameterId(0x0073);
148    /// `PID_TYPE_CONSISTENCY_ENFORCEMENT` (DDS-XTypes 1.3, 7.6.3.4).
149    pub const TYPE_CONSISTENCY_ENFORCEMENT: ParameterId = ParameterId(0x0074);
150    /// `PID_TYPE_INFORMATION` (DDS-XTypes 1.3, 7.6.3.2.2).
151    pub const TYPE_INFORMATION: ParameterId = ParameterId(0x0075);
152    /// `PID_BUILTIN_ENDPOINT_QOS`.
153    pub const BUILTIN_ENDPOINT_QOS: ParameterId = ParameterId(0x0077);
154    /// `PID_DOMAIN_TAG`.
155    pub const DOMAIN_TAG: ParameterId = ParameterId(0x4014);
156}
157
158/// `PL_CDR_BE` (Table 10.1).
159pub const PL_CDR_BE: [u8; 2] = [0x00, 0x02];
160/// `PL_CDR_LE` (Table 10.1).
161pub const PL_CDR_LE: [u8; 2] = [0x00, 0x03];
162
163/// Writes a payload: the `PL_CDR_*` header, the list and the sentinel.
164/// The options are zero (10.3).
165pub fn encode_pl_payload(list: &ParameterList, endianness: Endianness) -> Vec<u8> {
166    let mut out = Vec::new();
167    out.extend_from_slice(match endianness {
168        Endianness::Big => &PL_CDR_BE,
169        Endianness::Little => &PL_CDR_LE,
170    });
171    out.extend_from_slice(&[0, 0]);
172    list.encode(&mut out, endianness, true)
173        .expect("values built by this module are short");
174    out
175}
176
177/// Reads a payload written with `PL_CDR_BE` or `PL_CDR_LE`. The options
178/// are ignored (10.3).
179pub fn decode_pl_payload(bytes: &[u8]) -> Result<(ParameterList, Endianness), DecodeError> {
180    if bytes.len() < 4 {
181        return Err(DecodeError::UnexpectedEnd);
182    }
183    let id = [bytes[0], bytes[1]];
184    let endianness = match id {
185        PL_CDR_BE => Endianness::Big,
186        PL_CDR_LE => Endianness::Little,
187        _ => return Err(DecodeError::UnknownRepresentation(id)),
188    };
189    let (list, _) = ParameterList::decode(&bytes[4..], endianness, true)?;
190    Ok((list, endianness))
191}
192
193fn bad(id: ParameterId) -> DecodeError {
194    DecodeError::InvalidParameterValue(id)
195}
196
197fn read_string(r: &mut Reader<'_>) -> Option<String> {
198    let len = r.u32().ok()? as usize;
199    let bytes = r.bytes(len).ok()?;
200    let bytes = match bytes.split_last() {
201        Some((0, rest)) => rest,
202        Some(_) => return None,
203        // A length of 0 is not valid CDR, but means the empty string.
204        None => bytes,
205    };
206    String::from_utf8(bytes.to_vec()).ok()
207}
208
209fn write_string(w: &mut Writer<'_>, v: &str) {
210    w.u32(v.len() as u32 + 1);
211    w.bytes(v.as_bytes());
212    w.bytes(&[0]);
213}
214
215/// Reads parameter values in the byte order of their list.
216#[derive(Clone, Copy, Debug)]
217pub struct PlValues {
218    endianness: Endianness,
219}
220
221impl PlValues {
222    /// Values in the given byte order.
223    pub fn new(endianness: Endianness) -> Self {
224        PlValues { endianness }
225    }
226
227    fn reader<'a>(&self, p: &'a Parameter) -> Reader<'a> {
228        Reader::new(&p.value, self.endianness)
229    }
230
231    /// `unsigned long` or `long` as `u32`.
232    pub fn u32(&self, p: &Parameter) -> Result<u32, DecodeError> {
233        self.reader(p).u32().map_err(|_| bad(p.id))
234    }
235
236    /// `boolean`: one octet, non-zero is true.
237    pub fn bool(&self, p: &Parameter) -> Result<bool, DecodeError> {
238        p.value.first().map(|b| *b != 0).ok_or(bad(p.id))
239    }
240
241    /// `string`: length (with the terminating NUL), octets, NUL.
242    pub fn string(&self, p: &Parameter) -> Result<String, DecodeError> {
243        read_string(&mut self.reader(p)).ok_or(bad(p.id))
244    }
245
246    /// `sequence<string>`, as in `PartitionQosPolicy`. Each string's
247    /// length is aligned to 4 from the start of the value.
248    pub fn strings(&self, p: &Parameter) -> Result<Vec<String>, DecodeError> {
249        let mut r = self.reader(p);
250        let n = r.u32().map_err(|_| bad(p.id))? as usize;
251        // Each string takes at least 4 octets, which bounds `n`.
252        if n > r.remaining() / 4 {
253            return Err(bad(p.id));
254        }
255        let mut out = Vec::with_capacity(n);
256        for _ in 0..n {
257            let pad = (4 - r.position() % 4) % 4;
258            r.skip(pad).map_err(|_| bad(p.id))?;
259            out.push(read_string(&mut r).ok_or(bad(p.id))?);
260        }
261        Ok(out)
262    }
263
264    /// `sequence<struct { string; string; }>`, as `DataTags` (DDS
265    /// Security 1.2, 7.2.5): pairs of strings, each aligned to 4 from the
266    /// start of the value.
267    pub fn string_pairs(&self, p: &Parameter) -> Result<Vec<(String, String)>, DecodeError> {
268        let mut r = self.reader(p);
269        let n = r.u32().map_err(|_| bad(p.id))? as usize;
270        // Each pair takes at least 8 octets, which bounds `n`.
271        if n > r.remaining() / 8 {
272            return Err(bad(p.id));
273        }
274        let string = |r: &mut Reader<'_>| -> Result<String, DecodeError> {
275            let pad = (4 - r.position() % 4) % 4;
276            r.skip(pad).map_err(|_| bad(p.id))?;
277            read_string(r).ok_or(bad(p.id))
278        };
279        let mut out = Vec::with_capacity(n);
280        for _ in 0..n {
281            let a = string(&mut r)?;
282            let b = string(&mut r)?;
283            out.push((a, b));
284        }
285        Ok(out)
286    }
287
288    /// `ContentFilterProperty_t` (9.6.2.2.1): four strings and a
289    /// `sequence<string>`, each string aligned to 4 from the start of the
290    /// value.
291    pub fn content_filter(
292        &self,
293        p: &Parameter,
294    ) -> Result<crate::sedp::ContentFilterProperty, DecodeError> {
295        let mut r = self.reader(p);
296        let string = |r: &mut Reader<'_>| -> Result<String, DecodeError> {
297            let pad = (4 - r.position() % 4) % 4;
298            r.skip(pad).map_err(|_| bad(p.id))?;
299            read_string(r).ok_or(bad(p.id))
300        };
301        let content_filtered_topic_name = string(&mut r)?;
302        let related_topic_name = string(&mut r)?;
303        let filter_class_name = string(&mut r)?;
304        let filter_expression = string(&mut r)?;
305        let pad = (4 - r.position() % 4) % 4;
306        r.skip(pad).map_err(|_| bad(p.id))?;
307        let n = r.u32().map_err(|_| bad(p.id))? as usize;
308        if n > r.remaining() / 4 {
309            return Err(bad(p.id));
310        }
311        let mut expression_parameters = Vec::with_capacity(n);
312        for _ in 0..n {
313            expression_parameters.push(string(&mut r)?);
314        }
315        Ok(crate::sedp::ContentFilterProperty {
316            content_filtered_topic_name,
317            related_topic_name,
318            filter_class_name,
319            filter_expression,
320            expression_parameters,
321        })
322    }
323
324    /// `sequence<octet>`.
325    pub fn octets(&self, p: &Parameter) -> Result<Vec<u8>, DecodeError> {
326        let mut r = self.reader(p);
327        let len = r.u32().map_err(|_| bad(p.id))? as usize;
328        r.bytes(len).map(<[u8]>::to_vec).map_err(|_| bad(p.id))
329    }
330
331    /// `GUID_t`.
332    pub fn guid(&self, p: &Parameter) -> Result<Guid, DecodeError> {
333        let mut r = self.reader(p);
334        let prefix = GuidPrefix::read(&mut r).map_err(|_| bad(p.id))?;
335        let entity_id = EntityId::read(&mut r).map_err(|_| bad(p.id))?;
336        Ok(Guid::new(prefix, entity_id))
337    }
338
339    /// `EntityId_t`.
340    pub fn entity_id(&self, p: &Parameter) -> Result<EntityId, DecodeError> {
341        EntityId::read(&mut self.reader(p)).map_err(|_| bad(p.id))
342    }
343
344    /// `Locator_t`.
345    pub fn locator(&self, p: &Parameter) -> Result<Locator, DecodeError> {
346        Locator::read(&mut self.reader(p)).map_err(|_| bad(p.id))
347    }
348
349    /// `Duration_t`.
350    pub fn duration(&self, p: &Parameter) -> Result<Duration, DecodeError> {
351        let mut r = self.reader(p);
352        let seconds = r.i32().map_err(|_| bad(p.id))?;
353        let fraction = r.u32().map_err(|_| bad(p.id))?;
354        Ok(Duration { seconds, fraction })
355    }
356
357    /// `ProtocolVersion_t`.
358    pub fn protocol_version(&self, p: &Parameter) -> Result<ProtocolVersion, DecodeError> {
359        ProtocolVersion::read(&mut self.reader(p)).map_err(|_| bad(p.id))
360    }
361
362    /// `VendorId_t`.
363    pub fn vendor_id(&self, p: &Parameter) -> Result<VendorId, DecodeError> {
364        VendorId::read(&mut self.reader(p)).map_err(|_| bad(p.id))
365    }
366}
367
368/// Builds parameter values in a byte order.
369#[derive(Clone, Copy, Debug)]
370pub struct PlBuilder {
371    endianness: Endianness,
372}
373
374impl PlBuilder {
375    /// Values in the given byte order.
376    pub fn new(endianness: Endianness) -> Self {
377        PlBuilder { endianness }
378    }
379
380    fn build(&self, id: ParameterId, f: impl FnOnce(&mut Writer<'_>)) -> Parameter {
381        let mut value = Vec::new();
382        f(&mut Writer::new(&mut value, self.endianness));
383        Parameter::new(id, value)
384    }
385
386    /// `unsigned long` or `long`.
387    pub fn u32(&self, id: ParameterId, v: u32) -> Parameter {
388        self.build(id, |w| w.u32(v))
389    }
390
391    /// `boolean`.
392    pub fn bool(&self, id: ParameterId, v: bool) -> Parameter {
393        Parameter::new(id, [u8::from(v)])
394    }
395
396    /// `string`.
397    pub fn string(&self, id: ParameterId, v: &str) -> Parameter {
398        self.build(id, |w| write_string(w, v))
399    }
400
401    /// `sequence<string>`.
402    pub fn strings(&self, id: ParameterId, v: &[String]) -> Parameter {
403        self.build(id, |w| {
404            w.u32(v.len() as u32);
405            for s in v {
406                w.align4();
407                write_string(w, s);
408            }
409        })
410    }
411
412    /// `sequence<struct { string; string; }>`, as `DataTags`.
413    pub fn string_pairs(&self, id: ParameterId, v: &[(String, String)]) -> Parameter {
414        self.build(id, |w| {
415            w.u32(v.len() as u32);
416            for (a, b) in v {
417                w.align4();
418                write_string(w, a);
419                w.align4();
420                write_string(w, b);
421            }
422        })
423    }
424
425    /// `ContentFilterProperty_t` (9.6.2.2.1).
426    pub fn content_filter(
427        &self,
428        id: ParameterId,
429        v: &crate::sedp::ContentFilterProperty,
430    ) -> Parameter {
431        self.build(id, |w| {
432            for s in [
433                &v.content_filtered_topic_name,
434                &v.related_topic_name,
435                &v.filter_class_name,
436                &v.filter_expression,
437            ] {
438                w.align4();
439                write_string(w, s);
440            }
441            w.align4();
442            w.u32(v.expression_parameters.len() as u32);
443            for s in &v.expression_parameters {
444                w.align4();
445                write_string(w, s);
446            }
447        })
448    }
449
450    /// `sequence<octet>`.
451    pub fn octets(&self, id: ParameterId, v: &[u8]) -> Parameter {
452        self.build(id, |w| {
453            w.u32(v.len() as u32);
454            w.bytes(v);
455        })
456    }
457
458    /// `GUID_t`.
459    pub fn guid(&self, id: ParameterId, v: Guid) -> Parameter {
460        Parameter::new(id, v.to_bytes())
461    }
462
463    /// `EntityId_t`.
464    pub fn entity_id(&self, id: ParameterId, v: EntityId) -> Parameter {
465        Parameter::new(id, v.to_bytes())
466    }
467
468    /// `Locator_t`.
469    pub fn locator(&self, id: ParameterId, v: &Locator) -> Parameter {
470        self.build(id, |w| v.write(w))
471    }
472
473    /// `Duration_t`.
474    pub fn duration(&self, id: ParameterId, v: Duration) -> Parameter {
475        self.build(id, |w| {
476            w.i32(v.seconds);
477            w.u32(v.fraction);
478        })
479    }
480
481    /// `ProtocolVersion_t`.
482    pub fn protocol_version(&self, id: ParameterId, v: ProtocolVersion) -> Parameter {
483        Parameter::new(id, [v.major, v.minor])
484    }
485
486    /// `VendorId_t`.
487    pub fn vendor_id(&self, id: ParameterId, v: VendorId) -> Parameter {
488        Parameter::new(id, v.0)
489    }
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495
496    /// The example of 10.6, built with this module.
497    #[test]
498    fn example_10_6() {
499        let b = PlBuilder::new(Endianness::Little);
500        let guid = Guid::new(
501            GuidPrefix([0xc0, 0xa8, 0x02, 0x05, 0, 0, 0x3a, 0x20, 0, 0, 0, 0x02]),
502            EntityId::from_bytes([0x80, 0, 0, 0x07]),
503        );
504        let mut list = ParameterList::new();
505        list.push(b.guid(pid::ENDPOINT_GUID, guid));
506        list.push(b.string(pid::TOPIC_NAME, "Square"));
507        list.push(b.string(pid::TYPE_NAME, "ShapeType"));
508        list.push(b.u32(pid::DESTINATION_ORDER, 1));
509        list.push(b.duration(pid::DEADLINE, Duration::from_secs(3)));
510        let bytes = encode_pl_payload(&list, Endianness::Little);
511        let want: [u8; 84] = [
512            0x00, 0x03, 0x00, 0x00, // header
513            0x5a, 0x00, 0x10, 0x00, 0xc0, 0xa8, 0x02, 0x05, 0x00, 0x00, 0x3a, 0x20, 0x00, 0x00,
514            0x00, 0x02, 0x80, 0x00, 0x00, 0x07, // PID_ENDPOINT_GUID
515            0x05, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, b'S', b'q', b'u', b'a', b'r', b'e',
516            0x00, 0x00, // PID_TOPIC_NAME (padding written as zero)
517            0x07, 0x00, 0x10, 0x00, 0x0a, 0x00, 0x00, 0x00, b'S', b'h', b'a', b'p', b'e', b'T',
518            b'y', b'p', b'e', 0x00, 0x00, 0x00, // PID_TYPE_NAME
519            0x25, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, // PID_DESTINATION_ORDER
520            0x23, 0x00, 0x08, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
521            0x00, // DEADLINE
522            0x01, 0x00, 0x00, 0x00, // PID_SENTINEL
523        ];
524        assert_eq!(bytes, want);
525
526        let (back, e) = decode_pl_payload(&bytes).unwrap();
527        assert_eq!(e, Endianness::Little);
528        let v = PlValues::new(e);
529        assert_eq!(v.guid(back.get(pid::ENDPOINT_GUID).unwrap()).unwrap(), guid);
530        assert_eq!(
531            v.string(back.get(pid::TOPIC_NAME).unwrap()).unwrap(),
532            "Square"
533        );
534        assert_eq!(
535            v.string(back.get(pid::TYPE_NAME).unwrap()).unwrap(),
536            "ShapeType"
537        );
538        assert_eq!(
539            v.duration(back.get(pid::DEADLINE).unwrap()).unwrap(),
540            Duration::from_secs(3)
541        );
542    }
543
544    #[test]
545    fn values_round_trip_big_endian() {
546        let b = PlBuilder::new(Endianness::Big);
547        let v = PlValues::new(Endianness::Big);
548        let loc = Locator::udpv4("10.1.2.3:7410".parse().unwrap());
549        assert_eq!(
550            v.locator(&b.locator(pid::UNICAST_LOCATOR, &loc)).unwrap(),
551            loc
552        );
553        assert_eq!(
554            v.u32(&b.u32(pid::DOMAIN_ID, 0x1234_5678)).unwrap(),
555            0x1234_5678
556        );
557        assert!(v.bool(&b.bool(pid::EXPECTS_INLINE_QOS, true)).unwrap());
558        assert_eq!(
559            v.octets(&b.octets(pid::USER_DATA, &[1, 2, 3])).unwrap(),
560            [1, 2, 3]
561        );
562        assert_eq!(v.string(&b.string(pid::DOMAIN_TAG, "")).unwrap(), "");
563        let parts = vec!["a".to_string(), "".to_string(), "xyz12".to_string()];
564        let p = b.strings(pid::PARTITION, &parts);
565        // count, "a\0" + pad, "\0" + pad, "xyz12\0".
566        assert_eq!(p.value.len(), 4 + 8 + 8 + 10);
567        assert_eq!(v.strings(&p).unwrap(), parts);
568        assert!(
569            v.strings(&Parameter::new(pid::PARTITION, [0, 0, 0, 9]))
570                .is_err()
571        );
572        let d = Duration {
573            seconds: -2,
574            fraction: 7,
575        };
576        assert_eq!(v.duration(&b.duration(pid::DEADLINE, d)).unwrap(), d);
577    }
578
579    #[test]
580    fn bad_values() {
581        let v = PlValues::new(Endianness::Little);
582        let short = Parameter::new(pid::DOMAIN_ID, [1, 2]);
583        assert_eq!(
584            v.u32(&short),
585            Err(DecodeError::InvalidParameterValue(pid::DOMAIN_ID))
586        );
587        // String without its NUL.
588        let s = Parameter::new(pid::TOPIC_NAME, [2, 0, 0, 0, b'a', b'b', 0, 0]);
589        assert!(v.string(&s).is_err());
590        // String longer than the value.
591        let s = Parameter::new(pid::TOPIC_NAME, [9, 0, 0, 0, b'a', 0, 0, 0]);
592        assert!(v.string(&s).is_err());
593        assert!(matches!(
594            decode_pl_payload(&[0x00, 0x01, 0, 0, 1, 0, 0, 0]),
595            Err(DecodeError::UnknownRepresentation(_))
596        ));
597    }
598}