1use 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
14pub mod pid {
16 use crate::parameter::ParameterId;
17
18 pub const PAD: ParameterId = ParameterId(0x0000);
20 pub const SENTINEL: ParameterId = ParameterId(0x0001);
22 pub const PARTICIPANT_LEASE_DURATION: ParameterId = ParameterId(0x0002);
24 pub const TIME_BASED_FILTER: ParameterId = ParameterId(0x0004);
26 pub const TOPIC_NAME: ParameterId = ParameterId(0x0005);
28 pub const OWNERSHIP_STRENGTH: ParameterId = ParameterId(0x0006);
30 pub const TYPE_NAME: ParameterId = ParameterId(0x0007);
32 pub const DOMAIN_ID: ParameterId = ParameterId(0x000f);
34 pub const PROTOCOL_VERSION: ParameterId = ParameterId(0x0015);
36 pub const VENDORID: ParameterId = ParameterId(0x0016);
38 pub const RELIABILITY: ParameterId = ParameterId(0x001a);
40 pub const LIVELINESS: ParameterId = ParameterId(0x001b);
42 pub const DURABILITY: ParameterId = ParameterId(0x001d);
44 pub const DURABILITY_SERVICE: ParameterId = ParameterId(0x001e);
46 pub const OWNERSHIP: ParameterId = ParameterId(0x001f);
48 pub const PRESENTATION: ParameterId = ParameterId(0x0021);
50 pub const DEADLINE: ParameterId = ParameterId(0x0023);
52 pub const DESTINATION_ORDER: ParameterId = ParameterId(0x0025);
54 pub const LATENCY_BUDGET: ParameterId = ParameterId(0x0027);
56 pub const PARTITION: ParameterId = ParameterId(0x0029);
58 pub const LIFESPAN: ParameterId = ParameterId(0x002b);
60 pub const USER_DATA: ParameterId = ParameterId(0x002c);
62 pub const GROUP_DATA: ParameterId = ParameterId(0x002d);
64 pub const TOPIC_DATA: ParameterId = ParameterId(0x002e);
66 pub const UNICAST_LOCATOR: ParameterId = ParameterId(0x002f);
68 pub const MULTICAST_LOCATOR: ParameterId = ParameterId(0x0030);
70 pub const DEFAULT_UNICAST_LOCATOR: ParameterId = ParameterId(0x0031);
72 pub const METATRAFFIC_UNICAST_LOCATOR: ParameterId = ParameterId(0x0032);
74 pub const SERVICE_INSTANCE_NAME: ParameterId = ParameterId(0x0080);
76 pub const RELATED_ENTITY_GUID: ParameterId = ParameterId(0x0081);
78 pub const TOPIC_ALIASES: ParameterId = ParameterId(0x0082);
80 pub const RELATED_SAMPLE_IDENTITY: ParameterId = ParameterId(0x0083);
82 pub const IDENTITY_TOKEN: ParameterId = ParameterId(0x1001);
84 pub const PERMISSIONS_TOKEN: ParameterId = ParameterId(0x1002);
86 pub const DATA_TAGS: ParameterId = ParameterId(0x1003);
88 pub const ENDPOINT_SECURITY_INFO: ParameterId = ParameterId(0x1004);
90 pub const PARTICIPANT_SECURITY_INFO: ParameterId = ParameterId(0x1005);
92 pub const IDENTITY_STATUS_TOKEN: ParameterId = ParameterId(0x1006);
94 pub const METATRAFFIC_MULTICAST_LOCATOR: ParameterId = ParameterId(0x0033);
96 pub const PARTICIPANT_MANUAL_LIVELINESS_COUNT: ParameterId = ParameterId(0x0034);
98 pub const CONTENT_FILTER_PROPERTY: ParameterId = ParameterId(0x0035);
100 pub const HISTORY: ParameterId = ParameterId(0x0040);
102 pub const RESOURCE_LIMITS: ParameterId = ParameterId(0x0041);
104 pub const EXPECTS_INLINE_QOS: ParameterId = ParameterId(0x0043);
106 pub const DEFAULT_MULTICAST_LOCATOR: ParameterId = ParameterId(0x0048);
108 pub const TRANSPORT_PRIORITY: ParameterId = ParameterId(0x0049);
110 pub const PARTICIPANT_GUID: ParameterId = ParameterId(0x0050);
112 pub const GROUP_GUID: ParameterId = ParameterId(0x0052);
114 pub const GROUP_ENTITY_ID: ParameterId = ParameterId(0x0053);
116 pub const CONTENT_FILTER_INFO: ParameterId = ParameterId(0x0055);
118 pub const COHERENT_SET: ParameterId = ParameterId(0x0056);
120 pub const DIRECTED_WRITE: ParameterId = ParameterId(0x0057);
122 pub const BUILTIN_ENDPOINT_SET: ParameterId = ParameterId(0x0058);
124 pub const PROPERTY_LIST: ParameterId = ParameterId(0x0059);
126 pub const ENDPOINT_GUID: ParameterId = ParameterId(0x005a);
128 pub const TYPE_MAX_SIZE_SERIALIZED: ParameterId = ParameterId(0x0060);
130 pub const ORIGINAL_WRITER_INFO: ParameterId = ParameterId(0x0061);
132 pub const ENTITY_NAME: ParameterId = ParameterId(0x0062);
134 pub const GROUP_COHERENT_SET: ParameterId = ParameterId(0x0063);
136 pub const GROUP_SEQ_NUM: ParameterId = ParameterId(0x0064);
138 pub const WRITER_GROUP_INFO: ParameterId = ParameterId(0x0065);
140 pub const SECURE_WRITER_GROUP_INFO: ParameterId = ParameterId(0x0066);
142 pub const KEY_HASH: ParameterId = ParameterId(0x0070);
144 pub const STATUS_INFO: ParameterId = ParameterId(0x0071);
146 pub const DATA_REPRESENTATION: ParameterId = ParameterId(0x0073);
148 pub const TYPE_CONSISTENCY_ENFORCEMENT: ParameterId = ParameterId(0x0074);
150 pub const TYPE_INFORMATION: ParameterId = ParameterId(0x0075);
152 pub const BUILTIN_ENDPOINT_QOS: ParameterId = ParameterId(0x0077);
154 pub const DOMAIN_TAG: ParameterId = ParameterId(0x4014);
156}
157
158pub const PL_CDR_BE: [u8; 2] = [0x00, 0x02];
160pub const PL_CDR_LE: [u8; 2] = [0x00, 0x03];
162
163pub 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
177pub 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 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#[derive(Clone, Copy, Debug)]
217pub struct PlValues {
218 endianness: Endianness,
219}
220
221impl PlValues {
222 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 pub fn u32(&self, p: &Parameter) -> Result<u32, DecodeError> {
233 self.reader(p).u32().map_err(|_| bad(p.id))
234 }
235
236 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 pub fn string(&self, p: &Parameter) -> Result<String, DecodeError> {
243 read_string(&mut self.reader(p)).ok_or(bad(p.id))
244 }
245
246 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 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 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 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 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 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 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 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 pub fn locator(&self, p: &Parameter) -> Result<Locator, DecodeError> {
346 Locator::read(&mut self.reader(p)).map_err(|_| bad(p.id))
347 }
348
349 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 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 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#[derive(Clone, Copy, Debug)]
370pub struct PlBuilder {
371 endianness: Endianness,
372}
373
374impl PlBuilder {
375 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 pub fn u32(&self, id: ParameterId, v: u32) -> Parameter {
388 self.build(id, |w| w.u32(v))
389 }
390
391 pub fn bool(&self, id: ParameterId, v: bool) -> Parameter {
393 Parameter::new(id, [u8::from(v)])
394 }
395
396 pub fn string(&self, id: ParameterId, v: &str) -> Parameter {
398 self.build(id, |w| write_string(w, v))
399 }
400
401 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 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 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 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 pub fn guid(&self, id: ParameterId, v: Guid) -> Parameter {
460 Parameter::new(id, v.to_bytes())
461 }
462
463 pub fn entity_id(&self, id: ParameterId, v: EntityId) -> Parameter {
465 Parameter::new(id, v.to_bytes())
466 }
467
468 pub fn locator(&self, id: ParameterId, v: &Locator) -> Parameter {
470 self.build(id, |w| v.write(w))
471 }
472
473 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 pub fn protocol_version(&self, id: ParameterId, v: ProtocolVersion) -> Parameter {
483 Parameter::new(id, [v.major, v.minor])
484 }
485
486 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 #[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, 0x5a, 0x00, 0x10, 0x00, 0xc0, 0xa8, 0x02, 0x05, 0x00, 0x00, 0x3a, 0x20, 0x00, 0x00,
514 0x00, 0x02, 0x80, 0x00, 0x00, 0x07, 0x05, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, b'S', b'q', b'u', b'a', b'r', b'e',
516 0x00, 0x00, 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, 0x25, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x23, 0x00, 0x08, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
521 0x00, 0x01, 0x00, 0x00, 0x00, ];
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 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 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 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}