eclipse-cyclonedds 0.0.2

Rust binding for Eclipse Cyclone DDS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! Types representing received DDS samples and their associated metadata.
//!
//! A received sample is either a full data sample of type
//! [`T`](crate::Topicable) or a key-only sample carrying the instance key
//! [`T::Key`](crate::Topicable::Key).
//!
//! This distinction arises in DDS when an instance is disposed or unregistered,
//! the reader receives a notification carrying only the key rather than a full
//! payload.
//!
//! Samples are obtained via [`Reader::peek`](crate::Reader::peek),
//! [`Reader::read`](crate::Reader::read), and
//! [`Reader::take`](crate::Reader::take), or their equivalents on
//! [`ReadCondition`](crate::ReadCondition) and
//! [`QueryCondition`](crate::QueryCondition).

use crate::Topicable;

#[derive(Clone, Debug)]
pub(crate) enum SampleOrKeyInner<T>
where
    T: crate::Topicable,
{
    Sample {
        sample: Box<T>,
        materialized_key: std::cell::OnceCell<Box<T::Key>>,
    },
    Key {
        key: Box<T::Key>,
        materialized_sample: std::cell::OnceCell<Box<T>>,
    },
}

impl<T> SampleOrKeyInner<T>
where
    T: crate::Topicable,
{
    pub fn new_sample(sample: T) -> Self {
        Self::Sample {
            sample: Box::new(sample),
            materialized_key: std::cell::OnceCell::new(),
        }
    }

    pub fn new_key(key: T::Key) -> Self {
        Self::Key {
            key: Box::new(key),
            materialized_sample: std::cell::OnceCell::new(),
        }
    }

    pub fn key(&self) -> &T::Key {
        match self {
            Self::Sample {
                sample,
                materialized_key,
            } => materialized_key.get_or_init(|| Box::new(sample.as_key())),
            Self::Key { key, .. } => key,
        }
    }

    pub fn sample(&self) -> &T {
        match self {
            Self::Sample { sample, .. } => sample,
            Self::Key {
                key,
                materialized_sample,
            } => materialized_sample.get_or_init(|| Box::new(T::from_key(key))),
        }
    }
}

/// A received sample, which is either a full payload of type
/// [`T`](crate::Topicable) or a key-only payload carrying
/// [`T::Key`](crate::Topicable::Key).
///
/// Key-only samples are produced when an instance is disposed or unregistered
/// by a writer. [`SampleOrKey`] derefs to `T` in both cases: for key-only
/// samples this materializes a default `T` from the key via
/// [`Topicable::from_key`].
///
/// Use [`view`](SampleOrKey::view) to distinguish between the two cases without
/// triggering materialisation.
pub struct SampleOrKey<T>
where
    T: crate::Topicable,
{
    inner: SampleOrKeyInner<T>,
    pub(crate) info: Info,
}

impl<T> std::clone::Clone for SampleOrKey<T>
where
    T: Topicable + std::clone::Clone,
    T::Key: std::clone::Clone,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            info: self.info,
        }
    }
}

impl<T> std::fmt::Debug for SampleOrKey<T>
where
    T: Topicable + std::fmt::Debug,
    T::Key: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut f = f.debug_struct("SampleOrKey");

        let f = match &self.inner {
            SampleOrKeyInner::Sample { sample, .. } => f.field("sample", sample),
            SampleOrKeyInner::Key { key, .. } => f.field("key", key),
        };

        f.field("info", &self.info).finish()
    }
}

impl<T> SampleOrKey<T>
where
    T: crate::Topicable,
{
    /// Create a new sample or key provided a full sample and sample info.
    pub(crate) fn new_sample(sample: T, info: Info) -> Self {
        let inner = SampleOrKeyInner::new_sample(sample);
        Self { inner, info }
    }

    /// Create a new sample or key provided a key and sample info.
    pub(crate) fn new_key(key: T::Key, info: Info) -> Self {
        let inner = SampleOrKeyInner::new_key(key);
        Self { inner, info }
    }

    /// Returns the metadata associated with this sample.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cyclonedds::{Domain, Participant, Topic, Reader, Writer};
    /// # let domain = Domain::default();
    /// # let participant = Participant::new(&domain)?;
    /// # #[derive(
    /// #     cyclonedds::Topicable, serde::Serialize, serde::Deserialize, Clone, Debug, Default,
    /// # )]
    /// # struct Data {
    /// #     x: i32,
    /// # }
    /// # let topic = Topic::<Data>::new(&participant, "MyTopic")?;
    /// # let reader = Reader::new(&topic)?;
    /// # let writer = Writer::new(&topic)?;
    /// # writer.write(&Data::default())?;
    /// let sample = &reader.take()?[0];
    /// let info = sample.info();
    /// println!("source timestamp: {:?}", info.source_timestamp);
    /// # Ok::<_, cyclonedds::Error>(())
    /// ```
    pub const fn info(&self) -> &Info {
        &self.info
    }

    /// Returns a reference to the full sample payload, or `None` if this is a
    /// key-only sample.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cyclonedds::{Domain, Participant, Topic, Reader, Writer};
    /// # let domain = Domain::default();
    /// # let participant = Participant::new(&domain)?;
    /// # #[derive(
    /// #     cyclonedds::Topicable, serde::Serialize, serde::Deserialize, Clone, Debug, Default,
    /// # )]
    /// # struct Data {
    /// #     x: i32,
    /// # }
    /// # let topic = Topic::<Data>::new(&participant, "MyTopic")?;
    /// # let reader = Reader::new(&topic)?;
    /// # let writer = Writer::new(&topic)?;
    /// # writer.write(&Data::default())?;
    /// let sample = &reader.take()?[0];
    /// if let Some(data) = sample.sample() {
    ///     println!("payload: {data:?}");
    /// }
    /// # Ok::<_, cyclonedds::Error>(())
    /// ```
    pub fn sample(&self) -> Option<&T> {
        match &self.inner {
            SampleOrKeyInner::Sample { sample, .. } => Some(sample),
            SampleOrKeyInner::Key { .. } => None,
        }
    }

    /// Consumes `self` and returns the full sample payload, or `None` if this
    /// is a key-only sample.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cyclonedds::{Domain, Participant, Topic, Reader, Writer};
    /// # let domain = Domain::default();
    /// # let participant = Participant::new(&domain)?;
    /// # #[derive(
    /// #     cyclonedds::Topicable, serde::Serialize, serde::Deserialize, Clone, Debug, Default,
    /// # )]
    /// # struct Data {
    /// #     x: i32,
    /// # }
    /// # let topic = Topic::<Data>::new(&participant, "MyTopic")?;
    /// # let reader = Reader::new(&topic)?;
    /// # let writer = Writer::new(&topic)?;
    /// # writer.write(&Data::default())?;
    /// let sample = reader.take()?.into_iter().next().unwrap();
    /// if let Some(data) = sample.into_sample() {
    ///     println!("payload: {data:?}");
    /// }
    /// # Ok::<_, cyclonedds::Error>(())
    /// ```
    pub fn into_sample(self) -> Option<T> {
        match self.inner {
            SampleOrKeyInner::Sample { sample, .. } => Some(*sample),
            SampleOrKeyInner::Key { .. } => None,
        }
    }

    /// Returns `true` if this is a full sample.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cyclonedds::{Domain, Participant, Topic, Reader, Writer};
    /// # let domain = Domain::default();
    /// # let participant = Participant::new(&domain)?;
    /// # #[derive(
    /// #     cyclonedds::Topicable, serde::Serialize, serde::Deserialize, Clone, Debug, Default,
    /// # )]
    /// # struct Data {
    /// #     x: i32,
    /// # }
    /// # let topic = Topic::<Data>::new(&participant, "MyTopic")?;
    /// # let reader = Reader::new(&topic)?;
    /// # let writer = Writer::new(&topic)?;
    /// # writer.write(&Data::default())?;
    /// let sample = reader.take()?.into_iter().next().unwrap();
    /// assert!(sample.is_sample());
    /// # Ok::<_, cyclonedds::Error>(())
    /// ```
    pub const fn is_sample(&self) -> bool {
        matches!(self.inner, SampleOrKeyInner::Sample { .. })
    }

    /// Returns `true` if this is a full sample and `f` returns `true` for its
    /// payload.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cyclonedds::{Domain, Participant, Topic, Reader, Writer};
    /// # let domain = Domain::default();
    /// # let participant = Participant::new(&domain)?;
    /// # #[derive(
    /// #     cyclonedds::Topicable, serde::Serialize, serde::Deserialize, Clone, Debug, Default,
    /// # )]
    /// # struct Data {
    /// #     #[dds(key)]
    /// #     x: i32,
    /// # }
    /// # let topic = Topic::<Data>::new(&participant, "MyTopic")?;
    /// # let reader = Reader::new(&topic)?;
    /// # let writer = Writer::new(&topic)?;
    /// # writer.write(&Data::default())?;
    /// let sample = reader.take()?.into_iter().next().unwrap();
    /// assert!(sample.is_sample_and(|data| data.x == 0));
    /// # Ok::<_, cyclonedds::Error>(())
    /// ```
    pub fn is_sample_and(&self, f: impl FnOnce(&T) -> bool) -> bool {
        match &self.inner {
            SampleOrKeyInner::Sample { sample, .. } => f(sample),
            SampleOrKeyInner::Key { .. } => false,
        }
    }

    /// Returns a reference to the instance key, or `None` if this is a full
    /// sample.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cyclonedds::{Domain, Participant, Topic, Reader, Writer};
    /// # let domain = Domain::default();
    /// # let participant = Participant::new(&domain)?;
    /// # #[derive(
    /// #     cyclonedds::Topicable, serde::Serialize, serde::Deserialize, Clone, Debug, Default,
    /// # )]
    /// # struct Data {
    /// #     x: i32,
    /// # }
    /// # let topic = Topic::<Data>::new(&participant, "MyTopic")?;
    /// # let reader = Reader::new(&topic)?;
    /// # let writer = Writer::new(&topic)?;
    /// # writer.write(&Data::default())?;
    /// let sample = reader.take()?.into_iter().next().unwrap();
    /// if let Some(key) = sample.key() {
    ///     println!("key-only notification: {key:?}");
    /// }
    /// # Ok::<_, cyclonedds::Error>(())
    /// ```
    pub fn key(&self) -> Option<&T::Key> {
        match &self.inner {
            SampleOrKeyInner::Sample { .. } => None,
            SampleOrKeyInner::Key { key, .. } => Some(key),
        }
    }

    /// Consumes `self` and returns the instance key, or `None` if this is a
    /// full sample.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cyclonedds::{Domain, Participant, Topic, Reader, Writer};
    /// # let domain = Domain::default();
    /// # let participant = Participant::new(&domain)?;
    /// # #[derive(
    /// #     cyclonedds::Topicable, serde::Serialize, serde::Deserialize, Clone, Debug, Default,
    /// # )]
    /// # struct Data {
    /// #     x: i32,
    /// # }
    /// # let topic = Topic::<Data>::new(&participant, "MyTopic")?;
    /// # let reader = Reader::new(&topic)?;
    /// # let writer = Writer::new(&topic)?;
    /// # writer.write(&Data::default())?;
    /// let sample = reader.take()?.into_iter().next().unwrap();
    /// if let Some(key) = sample.into_key() {
    ///     println!("key-only notification: {key:?}");
    /// }
    /// # Ok::<_, cyclonedds::Error>(())
    /// ```
    pub fn into_key(self) -> Option<T::Key> {
        match self.inner {
            SampleOrKeyInner::Sample { .. } => None,
            SampleOrKeyInner::Key { key, .. } => Some(*key),
        }
    }

    /// Returns `true` if this is a key-only sample.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cyclonedds::{Domain, Participant, Topic, Reader, Writer};
    /// # let domain = Domain::default();
    /// # let participant = Participant::new(&domain)?;
    /// # #[derive(
    /// #     cyclonedds::Topicable, serde::Serialize, serde::Deserialize, Clone, Debug, Default,
    /// # )]
    /// # struct Data {
    /// #     x: i32,
    /// # }
    /// # let topic = Topic::<Data>::new(&participant, "MyTopic")?;
    /// # let reader = Reader::new(&topic)?;
    /// # let writer = Writer::new(&topic)?;
    /// # writer.write(&Data::default())?;
    /// let sample = reader.take()?.into_iter().next().unwrap();
    /// assert!(!sample.is_key());
    /// # Ok::<_, cyclonedds::Error>(())
    /// ```
    pub const fn is_key(&self) -> bool {
        matches!(self.inner, SampleOrKeyInner::Key { .. })
    }

    /// Returns `true` if this is a key-only sample and `f` returns `true` for
    /// its key.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cyclonedds::{Domain, Participant, Topic, Reader, Writer};
    /// # let domain = Domain::default();
    /// # let participant = Participant::new(&domain)?;
    /// # #[derive(
    /// #     cyclonedds::Topicable, serde::Serialize, serde::Deserialize, Clone, Debug, Default,
    /// # )]
    /// # struct Data {
    /// #     #[dds(key)]
    /// #     x: i32,
    /// # }
    /// # let topic = Topic::<Data>::new(&participant, "MyTopic")?;
    /// # let reader = Reader::new(&topic)?;
    /// # let writer = Writer::new(&topic)?;
    /// # writer.write(&Data::default())?;
    /// let sample = reader.take()?.into_iter().next().unwrap();
    /// assert!(!sample.is_key_and(|key| key.x == 1));
    /// # Ok::<_, cyclonedds::Error>(())
    /// ```
    pub fn is_key_and(&self, f: impl FnOnce(&T::Key) -> bool) -> bool {
        match &self.inner {
            SampleOrKeyInner::Sample { .. } => false,
            SampleOrKeyInner::Key { key, .. } => f(key),
        }
    }

    /// Returns a borrowed [`View`] of this sample for pattern matching without
    /// triggering key or sample materialisation.
    ///
    /// # Examples
    ///
    /// ```
    /// use cyclonedds::sample::View;
    /// # use cyclonedds::{Domain, Participant, Topic, Reader, Writer};
    /// # let domain = Domain::default();
    /// # let participant = Participant::new(&domain)?;
    /// # #[derive(
    /// #     cyclonedds::Topicable, serde::Serialize, serde::Deserialize, Clone, Debug, Default,
    /// # )]
    /// # struct Data {
    /// #     x: i32,
    /// # }
    /// # let topic = Topic::<Data>::new(&participant, "MyTopic")?;
    /// # let reader = Reader::new(&topic)?;
    /// # let writer = Writer::new(&topic)?;
    /// # writer.write(&Data::default())?;
    ///
    /// for sample in reader.take()? {
    ///     match sample.view() {
    ///         View::Sample(data) => println!("sample: {data:?}"),
    ///         View::Key(key) => println!("key-only: {key:?}"),
    ///     }
    /// }
    /// # Ok::<_, cyclonedds::Error>(())
    /// ```
    pub fn view(&self) -> View<'_, T> {
        match &self.inner {
            SampleOrKeyInner::Sample { sample, .. } => View::Sample(sample.as_ref()),
            SampleOrKeyInner::Key { key, .. } => View::Key(key.as_ref()),
        }
    }
}

impl<T> std::ops::Deref for SampleOrKey<T>
where
    T: crate::Topicable,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.inner.sample()
    }
}

/// A borrowed view into a [`SampleOrKey`] for pattern matching.
///
/// Obtained via [`SampleOrKey::view`]. Distinguishes between a full sample and
/// a key-only sample without consuming the [`SampleOrKey`] and without
/// implicitly materializing the other half.
///
/// # Examples
///
/// ```
/// use cyclonedds::sample::View;
/// # use cyclonedds::{Reader, Topic};
/// # #[derive(
/// #     cyclonedds::Topicable, serde::Serialize, serde::Deserialize, Clone, Debug, Default,
/// # )]
/// # struct Data {
/// #     x: i32,
/// # }
/// # let domain = cyclonedds::Domain::default();
/// # let participant = cyclonedds::Participant::new(&domain)?;
/// # let topic = Topic::<Data>::new(&participant, "MyData")?;
/// # let reader = Reader::<Data>::new(&topic)?;
///
/// for sample in reader.read()? {
///     match sample.view() {
///         View::Sample(sample) => println!("got sample: {sample:?}"),
///         View::Key(key) => println!("got key-only: {key:?}"),
///     }
/// }
/// # Ok::<_, cyclonedds::Error>(())
/// ```
pub enum View<'sample, T>
where
    T: Topicable,
{
    /// A full data sample.
    Sample(&'sample T),
    /// A key-only notification, produced when an instance is disposed or
    /// unregistered.
    Key(&'sample T::Key),
}

impl<T> std::fmt::Debug for View<'_, T>
where
    T: Topicable,
    T::Key: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Sample(sample) => f.debug_tuple("Sample").field(sample).finish(),
            Self::Key(key) => f.debug_tuple("Key").field(key).finish(),
        }
    }
}

impl<T> std::cmp::PartialEq for View<'_, T>
where
    T: Topicable + std::cmp::PartialEq,
    T::Key: std::cmp::PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (View::Sample(lhs), View::Sample(rhs)) => lhs == rhs,
            (View::Key(lhs), View::Key(rhs)) => lhs == rhs,
            _ => false,
        }
    }
}

/// Metadata associated with a received sample.
///
/// Attached to every [`SampleOrKey`] and carries the metadata related to the
/// transmission of the sample.
///
/// <div class="warning">
///
/// The `valid_data` flag from the DDS specification is not present here as it
/// is encoded structurally in the type system via [`SampleOrKey`]. A
/// [`View::Sample`] variant guarantees valid data and a [`View::Key`] variant
/// guarantees the absence of it.
///
/// </div>
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Info {
    /// [`sample`](crate::state::sample), [`view`](crate::state::view), and
    /// [`instance`](crate::state::instance) state flags at the time of receipt.
    pub state: crate::State,
    /// Timestamp at which the sample was written by the publisher.
    pub source_timestamp: crate::Time,
    /// Handle identifying the instance this sample belongs to.
    pub instance_handle: crate::entity::InstanceHandle,
    /// Handle identifying the writer that published this sample.
    pub publication_handle: crate::entity::InstanceHandle,
    /// Number of times the instance was disposed before this sample was
    /// received.
    pub disposed_generation_count: u32,
    /// Number of times the instance transitioned to the no-writers state before
    /// this sample was received.
    pub no_writers_generation_count: u32,
    /// Position of this sample relative to other samples for the same instance
    /// in the current read or take call.
    pub sample_rank: u32,
    /// Difference in generation count between this sample and the most recent
    /// sample for the same instance in the current read or take call.
    pub generation_rank: u32,
    /// Difference in generation count between this sample and the most recent
    /// sample for the same instance in the reader's cache.
    pub absolute_generation_rank: u32,
}

impl From<&cyclonedds_sys::dds_sample_info> for Info {
    fn from(sample_info: &cyclonedds_sys::dds_sample_info) -> Self {
        #[allow(clippy::cast_sign_loss, clippy::unnecessary_cast)]
        let state = crate::State::from_bits_truncate(sample_info.sample_state as u32)
            | crate::State::from_bits_truncate(sample_info.view_state as u32)
            | crate::State::from_bits_truncate(sample_info.instance_state as u32);
        let instance_handle = crate::entity::InstanceHandle {
            inner: sample_info.instance_handle,
        };
        let publication_handle = crate::entity::InstanceHandle {
            inner: sample_info.publication_handle,
        };
        let source_timestamp = crate::Time::from_nanos(sample_info.source_timestamp);

        let disposed_generation_count = sample_info.disposed_generation_count;
        let no_writers_generation_count = sample_info.no_writers_generation_count;
        let sample_rank = sample_info.sample_rank;
        let generation_rank = sample_info.generation_rank;
        let absolute_generation_rank = sample_info.absolute_generation_rank;

        Self {
            state,
            source_timestamp,
            instance_handle,
            publication_handle,
            disposed_generation_count,
            no_writers_generation_count,
            sample_rank,
            generation_rank,
            absolute_generation_rank,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn is_sample_callback(sample: &crate::tests::topic::Data) -> bool {
        sample.x.is_multiple_of(2)
    }

    // NOTE: the general interface expects the key to be passed by ref (even if the
    // key is trivially copyable and small).
    #[allow(clippy::trivially_copy_pass_by_ref)]
    fn is_key_callback(key: &(u32, i32)) -> bool {
        key.0.is_multiple_of(2)
    }

    #[test]
    fn test_sample_or_key_sample_ref() {
        let info = Info {
            state: crate::State::empty(),
            source_timestamp: crate::Time::default(),
            instance_handle: crate::entity::InstanceHandle { inner: 0 },
            publication_handle: crate::entity::InstanceHandle { inner: 0 },
            disposed_generation_count: Default::default(),
            no_writers_generation_count: Default::default(),
            sample_rank: Default::default(),
            generation_rank: Default::default(),
            absolute_generation_rank: Default::default(),
        };
        let data = crate::tests::topic::Data {
            x: 10,
            y: 11,
            message: "sample".to_string(),
        };
        let sample = SampleOrKey::new_sample(data.clone(), info);

        assert!(sample.is_sample());
        assert!(sample.is_sample_and(is_sample_callback));
        assert!(!sample.is_key_and(is_key_callback));
        assert!(!sample.is_key());
        assert_eq!(sample.info(), &info);
        assert_eq!(*sample, data);
        assert_eq!(sample.sample().unwrap(), &data);
        assert_eq!(sample.key(), None);
        assert_eq!(sample.clone().into_sample().unwrap(), data);
        assert_eq!(sample.clone().into_key(), None);
    }

    #[test]
    fn test_sample_or_key_key_ref() {
        let info = Info {
            state: crate::State::empty(),
            source_timestamp: crate::Time::default(),
            instance_handle: crate::entity::InstanceHandle { inner: 0 },
            publication_handle: crate::entity::InstanceHandle { inner: 0 },
            disposed_generation_count: Default::default(),
            no_writers_generation_count: Default::default(),
            sample_rank: Default::default(),
            generation_rank: Default::default(),
            absolute_generation_rank: Default::default(),
        };
        let data = crate::tests::topic::Data {
            x: 10,
            y: 11,
            message: String::new(),
        };
        let key = data.as_key();
        let sample = SampleOrKey::<crate::tests::topic::Data>::new_key(key, info);

        assert!(sample.is_key());
        assert!(sample.is_key_and(is_key_callback));
        assert!(!sample.is_sample_and(is_sample_callback));
        assert!(!sample.is_sample());
        assert_eq!(sample.info(), &info);
        assert_eq!(*sample, data);
        assert_eq!(sample.key().unwrap(), &key);
        assert_eq!(sample.sample(), None);
        assert_eq!(sample.clone().into_key().unwrap(), key);
        assert_eq!(sample.clone().into_sample(), None);
    }

    #[test]
    fn test_sample_or_key_view() {
        let info = Info {
            state: crate::State::empty(),
            source_timestamp: crate::Time::default(),
            instance_handle: crate::entity::InstanceHandle { inner: 0 },
            publication_handle: crate::entity::InstanceHandle { inner: 0 },
            disposed_generation_count: Default::default(),
            no_writers_generation_count: Default::default(),
            sample_rank: Default::default(),
            generation_rank: Default::default(),
            absolute_generation_rank: Default::default(),
        };
        let sample_data = crate::tests::topic::Data {
            x: 10,
            y: 11,
            message: "sample".to_string(),
        };
        let sample_key = sample_data.as_key();

        let sample =
            SampleOrKey::<crate::tests::topic::Data>::new_sample(sample_data.clone(), info);
        let key = SampleOrKey::<crate::tests::topic::Data>::new_key(sample_key, info);

        let sample_display = format!("{sample:?}");
        let key_display = format!("{key:?}");
        assert!(sample_display.contains(&format!("{sample_data:?}")));
        assert!(key_display.contains(&format!("{sample_key:?}")));
        assert!(sample_display.contains(&format!("{sample_data:?}")));
        assert!(sample_display.contains(&format!("{info:?}")));
        assert!(key_display.contains(&format!("{sample_key:?}")));
        assert!(key_display.contains(&format!("{info:?}")));

        let view_sample_display = format!("{:?}", sample.view());
        let view_key_display = format!("{:?}", key.view());
        assert!(view_sample_display.contains(&format!("{sample_data:?}")));
        assert!(view_key_display.contains(&format!("{sample_key:?}")));
        assert!(view_sample_display.contains(&format!("{sample_data:?}")));

        assert!(sample.view() != key.view());
        assert_eq!(sample.view(), View::Sample(&sample_data));
        assert_eq!(key.view(), View::Key(&sample_key));
    }
}