rustorb-dds 0.4.0

DDS (Data Distribution Service) DCPS API in Rust
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//! `Subscriber` and `DataReader`.

use std::sync::Arc;
use std::time::{Duration, Instant};

use rustorb_rtps::sedp::EndpointData;
use rustorb_rtps::{Guid, entity_kind};

use crate::condition::{ReadCondition, StatusCondition};
use crate::error::{Error, Result};
#[cfg(feature = "shm")]
use crate::instance::Payload;
use crate::instance::{InstanceHandle, SampleInfo, Selected, StateFilter};
use crate::listener::{DataReaderListener, SubscriberEntity, SubscriberListener};
use crate::loan::{PlainType, ReadLoan};
use crate::participant::{ReaderEvent, ReaderListener, ReaderState, Shared};
use crate::qos::{DataReaderQos, SubscriberQos, TypeConsistency, duration_to_rtps};
use crate::status::{
    DeadlineMissedStatus, IncompatibleQosStatus, LivelinessChangedStatus, MatchedStatus,
    SampleLostStatus, SampleRejectedStatus, StatusMask,
};
use crate::topic::TopicDescription;
use crate::typed::SampleType;

/// A DDS subscriber (DDS 1.4, 2.2.2.5.1): creates data readers.
#[derive(Clone)]
pub struct Subscriber {
    shared: Arc<Shared>,
    entity: Arc<SubscriberEntity>,
}

impl std::fmt::Debug for Subscriber {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Subscriber").finish_non_exhaustive()
    }
}

impl Subscriber {
    pub(crate) fn from_entity(shared: Arc<Shared>, entity: Arc<SubscriberEntity>) -> Self {
        Subscriber { shared, entity }
    }

    /// The subscriber's QoS.
    pub fn qos(&self) -> &SubscriberQos {
        &self.entity.qos
    }

    /// Sets the subscriber's listener (`set_listener`), replacing any
    /// earlier one: it is called for DATA_ON_READERS, and for the
    /// statuses in `mask` of its readers that their own listeners do not
    /// take (DDS 1.4, 2.2.4.3). See [`SubscriberListener`].
    pub fn set_listener(&self, listener: impl SubscriberListener + 'static, mask: StatusMask) {
        *self
            .entity
            .listener
            .lock()
            .unwrap_or_else(|e| e.into_inner()) = Some((Arc::new(listener), mask));
    }

    /// Removes the subscriber's listener.
    pub fn clear_listener(&self) {
        *self
            .entity
            .listener
            .lock()
            .unwrap_or_else(|e| e.into_inner()) = None;
    }

    /// Calls `on_data_available` of the listeners of its readers that
    /// have new data (`notify_datareaders`, DDS 1.4, 2.2.2.5.2.8): from
    /// `on_data_on_readers`, to have each reader handle its own.
    pub fn notify_datareaders(&self) {
        self.shared.notify_datareaders(&self.entity);
    }

    /// Whether `self` and `other` are handles of the same subscriber.
    pub fn same_as(&self, other: &Subscriber) -> bool {
        Arc::ptr_eq(&self.entity, &other.entity)
    }

    /// Creates a reader for `topic` with the default QoS: BEST_EFFORT,
    /// KEEP_LAST(1), VOLATILE. `topic` is a [`Topic`](crate::Topic) or a
    /// [`ContentFilteredTopic`](crate::ContentFilteredTopic).
    pub fn create_datareader<T>(&self, topic: &impl TopicDescription<T>) -> Result<DataReader<T>> {
        self.create_datareader_with_qos(topic, DataReaderQos::default())
    }

    /// Creates a reader for `topic`.
    ///
    /// A RELIABLE reader gets the samples of each writer in order and
    /// without gaps, asking for those lost on the way; it matches only
    /// RELIABLE writers. A BEST_EFFORT reader takes what arrives, in
    /// order, and matches any writer.
    pub fn create_datareader_with_qos<T>(
        &self,
        topic: &impl TopicDescription<T>,
        qos: DataReaderQos,
    ) -> Result<DataReader<T>> {
        self.create(topic, qos, None, |_| {})
    }

    /// Creates a reader whose announcement `f` changes before it is
    /// matched (as with the topic aliases of DDS-RPC).
    pub(crate) fn create_datareader_with<T>(
        &self,
        topic: &impl TopicDescription<T>,
        qos: DataReaderQos,
        f: impl FnOnce(&mut EndpointData),
    ) -> Result<DataReader<T>> {
        self.create(topic, qos, None, f)
    }

    /// Creates a reader for `topic` with a listener for the statuses in
    /// `mask`, set before the reader is matched, so that it is told of
    /// the writers already there and of the samples they kept
    /// (DDS 1.4, 2.2.2.5.2.5).
    pub fn create_datareader_with_listener<T: 'static>(
        &self,
        topic: &impl TopicDescription<T>,
        qos: DataReaderQos,
        listener: impl DataReaderListener<T> + 'static,
        mask: StatusMask,
    ) -> Result<DataReader<T>> {
        let l = reader_listener(topic.topic().samples.clone(), listener);
        self.create(topic, qos, Some((l, mask)), |_| {})
    }

    fn create<T>(
        &self,
        description: &impl TopicDescription<T>,
        qos: DataReaderQos,
        listener: Option<(ReaderListener, StatusMask)>,
        f: impl FnOnce(&mut EndpointData),
    ) -> Result<DataReader<T>> {
        let topic = description.topic();
        let cft = description.content_filter();
        let kind = if topic.samples.keyed() {
            entity_kind::USER_READER_WITH_KEY
        } else {
            entity_kind::USER_READER_NO_KEY
        };
        let guid = self.shared.new_guid(kind)?;
        let type_name = topic.type_name();
        let mut data = EndpointData::reader(guid, topic.name(), type_name);
        data.type_information = self.shared.type_information(type_name)?;
        data.data_representation = qos.data_representation.clone();
        if qos.type_consistency != TypeConsistency::default() {
            data.type_consistency = Some(qos.type_consistency);
        }
        data.reliability = qos.reliability.to_rtps();
        data.durability = qos.durability;
        data.deadline = duration_to_rtps(qos.deadline);
        data.liveliness = qos.liveliness.to_rtps();
        data.user_data = qos.user_data.clone();
        data.data_tags = qos.data_tags.clone();
        data.partitions = self.entity.qos.partition.clone();
        let filter = cft.map(|c| {
            let (filter, property) = c.reader_filter();
            data.content_filter = Some(property);
            filter
        });
        f(&mut data);
        self.shared.add_reader(
            data,
            qos,
            topic.samples.key_ops(),
            listener,
            filter,
            self.entity.clone(),
        )?;
        if let Some(c) = cft {
            c.add_reader(guid);
        }
        Ok(DataReader {
            shared: self.shared.clone(),
            guid,
            owned: true,
            samples: topic.samples.clone(),
        })
    }
}

/// A sample with its information.
#[derive(Clone, Debug, PartialEq)]
pub struct Sample<T> {
    /// The value; `None` for a sample without data
    /// (`info.valid_data == false`), which only tells of a change in the
    /// state of its instance.
    pub data: Option<T>,
    /// The information.
    pub info: SampleInfo,
}

/// A DDS data reader (DDS 1.4, 2.2.2.5.3) of samples of type `T`: a
/// [`TopicType`](crate::TopicType), or [`DynamicData`](crate::DynamicData)
/// for a topic of a type known at run time (a `DynamicDataReader`,
/// DDS-XTypes 1.3, 7.5.2.12).
///
/// Samples that cannot be deserialized as `T` are dropped when they are
/// read or taken. Dropping the reader tells the other participants it is
/// gone.
pub struct DataReader<T> {
    pub(crate) shared: Arc<Shared>,
    pub(crate) guid: Guid,
    /// Whether dropping this handle deletes the reader: not for the
    /// handle given to a listener.
    owned: bool,
    samples: Arc<dyn SampleType<T>>,
}

/// A [`DataReaderListener`] for DATA_AVAILABLE alone, from a function.
struct DataAvailable<F>(F);

impl<T, F: Fn(&DataReader<T>) + Send + Sync> DataReaderListener<T> for DataAvailable<F> {
    fn on_data_available(&self, reader: &DataReader<T>) {
        (self.0)(reader)
    }
}

impl<T> std::fmt::Debug for DataReader<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DataReader")
            .field("guid", &self.guid)
            .field("type_name", &self.samples.type_name())
            .finish()
    }
}

fn decode<T>(samples: &dyn SampleType<T>, (payload, info): Selected) -> Option<Sample<T>> {
    let data = match payload {
        Some(p) => Some(samples.decode(&p)?),
        None => None,
    };
    Some(Sample { data, info })
}

impl<T> DataReader<T> {
    /// The reader's GUID.
    pub fn guid(&self) -> Guid {
        self.guid
    }

    fn select(
        &self,
        filter: StateFilter,
        instance: Option<InstanceHandle>,
        take: bool,
    ) -> Vec<Sample<T>> {
        self.select_max(filter, instance, take, usize::MAX)
    }

    fn select_max(
        &self,
        filter: StateFilter,
        instance: Option<InstanceHandle>,
        take: bool,
        max: usize,
    ) -> Vec<Sample<T>> {
        self.select_raw(filter, instance, take, max)
            .into_iter()
            .filter_map(|r| decode(&*self.samples, r))
            .collect()
    }

    fn select_raw(
        &self,
        filter: StateFilter,
        instance: Option<InstanceHandle>,
        take: bool,
        max: usize,
    ) -> Vec<Selected> {
        let mut g = self.shared.lock_any();
        match g.readers.get_mut(&self.guid) {
            Some(r) => {
                r.changes = r.changes & !StatusMask::DATA_AVAILABLE;
                r.samples.select_max(filter, instance, take, max)
            }
            None => Vec::new(),
        }
    }

    /// Removes and returns the samples received, still serialized.
    pub(crate) fn take_raw(&self) -> Vec<(Option<Vec<u8>>, SampleInfo)> {
        self.select_raw(StateFilter::ANY, None, true, usize::MAX)
            .into_iter()
            .map(|(p, i)| (p.map(|p| p.to_vec()), i))
            .collect()
    }

    /// Deserializes a payload of the reader's type.
    pub(crate) fn decode_raw(&self, payload: &[u8]) -> Option<T> {
        self.samples.decode(payload)
    }

    /// Removes and returns the samples received, in the order they
    /// arrived.
    pub fn take(&self) -> Vec<Sample<T>> {
        self.select(StateFilter::ANY, None, true)
    }

    /// Returns the samples received, in the order they arrived, and
    /// leaves them in the reader, marked as read.
    pub fn read(&self) -> Vec<Sample<T>> {
        self.select(StateFilter::ANY, None, false)
    }

    /// Like [`Self::take`], for the samples whose states pass `filter`.
    pub fn take_with(&self, filter: StateFilter) -> Vec<Sample<T>> {
        self.select(filter, None, true)
    }

    /// Like [`Self::read`], for the samples whose states pass `filter`.
    pub fn read_with(&self, filter: StateFilter) -> Vec<Sample<T>> {
        self.select(filter, None, false)
    }

    /// Takes the samples of one instance (`take_instance`).
    pub fn take_instance(&self, instance: InstanceHandle) -> Vec<Sample<T>> {
        self.select(StateFilter::ANY, Some(instance), true)
    }

    /// Reads the samples of one instance (`read_instance`).
    pub fn read_instance(&self, instance: InstanceHandle) -> Vec<Sample<T>> {
        self.select(StateFilter::ANY, Some(instance), false)
    }

    /// Takes the samples of the instance after `previous`, in handle
    /// order, that has samples passing `filter`; from the first instance
    /// when `previous` is `None` (`take_next_instance`). Empty when there
    /// is no such instance.
    pub fn take_next_instance(
        &self,
        previous: Option<InstanceHandle>,
        filter: StateFilter,
    ) -> Vec<Sample<T>> {
        self.next_instance(previous, filter, true, usize::MAX)
    }

    /// Like [`Self::take_next_instance`], reading (`read_next_instance`).
    pub fn read_next_instance(
        &self,
        previous: Option<InstanceHandle>,
        filter: StateFilter,
    ) -> Vec<Sample<T>> {
        self.next_instance(previous, filter, false, usize::MAX)
    }

    fn next_instance(
        &self,
        previous: Option<InstanceHandle>,
        filter: StateFilter,
        take: bool,
        max: usize,
    ) -> Vec<Sample<T>> {
        let raw = {
            let mut g = self.shared.lock_any();
            let Some(r) = g.readers.get_mut(&self.guid) else {
                return Vec::new();
            };
            r.changes = r.changes & !StatusMask::DATA_AVAILABLE;
            match r.samples.next_instance(previous, filter) {
                Some(h) => r.samples.select_max(filter, Some(h), take, max),
                None => Vec::new(),
            }
        };
        raw.into_iter()
            .filter_map(|r| decode(&*self.samples, r))
            .collect()
    }

    /// The reads and takes of at most `max_samples` samples (the
    /// `max_samples` argument of DDS 1.4, 2.2.2.5.3.8): the first to
    /// arrive of those selected. The others stay in the reader as they
    /// were.
    pub fn max_samples(&self, max_samples: usize) -> MaxSamples<'_, T> {
        MaxSamples {
            reader: self,
            max: max_samples,
        }
    }

    /// The handle of the instance of `instance` (`lookup_instance`), if
    /// the reader has it.
    pub fn lookup_instance(&self, instance: &T) -> Option<InstanceHandle> {
        let h = self.samples.instance_of(instance).ok()?;
        let g = self.shared.lock_any();
        let r = g.readers.get(&self.guid)?;
        r.samples.has_instance(&h).then_some(h)
    }

    /// The key of an instance (`get_key_value`): the last value received
    /// for it, whose key members identify it. `None` on a keyless topic,
    /// if the reader has not received a value for it, or if it has
    /// forgotten the instance: one with no samples left and no writers is
    /// forgotten at the read or take after the one that emptied it.
    pub fn get_key_value(&self, instance: InstanceHandle) -> Option<T> {
        let g = self.shared.lock_any();
        let r = g.readers.get(&self.guid)?;
        self.samples.decode(r.samples.last_value(&instance)?)
    }

    /// Waits until there is a sample not yet read, or `timeout` passes.
    /// Returns whether there is one.
    pub fn wait_for_data(&self, timeout: Duration) -> bool {
        let deadline = Instant::now() + timeout;
        let mut g = self.shared.lock_any();
        loop {
            let has = g
                .readers
                .get(&self.guid)
                .is_some_and(|r| r.samples.has_unread());
            if has {
                return true;
            }
            let now = Instant::now();
            if now >= deadline {
                return false;
            }
            g = match self.shared.data_arrived.wait_timeout(g, deadline - now) {
                Ok((g, _)) => g,
                Err(e) => e.into_inner().0,
            };
        }
    }

    /// Sets the listener (`set_listener`), replacing any earlier one:
    /// its methods are called for the statuses in `mask` when they
    /// change. See [`DataReaderListener`].
    pub fn set_listener(&self, listener: impl DataReaderListener<T> + 'static, mask: StatusMask)
    where
        T: 'static,
    {
        let l = reader_listener(self.samples.clone(), listener);
        // The one before is dropped with no lock held (#117).
        let before = {
            let mut g = self.shared.lock_any();
            g.readers
                .get_mut(&self.guid)
                .and_then(|r| r.listener.replace((l, mask)))
        };
        drop(before);
    }

    /// Sets a listener for DATA_AVAILABLE alone: `f` is called with the
    /// reader when samples arrive. It may take them, or send to a
    /// channel:
    ///
    /// ```no_run
    /// # fn f<T: rustorb_typesupport::TopicType + Send + 'static>(
    /// #     reader: &rustorb_dds::DataReader<T>,
    /// # ) {
    /// let (tx, rx) = std::sync::mpsc::channel();
    /// reader.on_data_available(move |r| {
    ///     for s in r.take() {
    ///         let _ = tx.send(s);
    ///     }
    /// });
    /// # }
    /// ```
    pub fn on_data_available(&self, f: impl Fn(&DataReader<T>) + Send + Sync + 'static)
    where
        T: 'static,
    {
        self.set_listener(DataAvailable(f), StatusMask::DATA_AVAILABLE);
    }

    /// Removes the listener.
    pub fn clear_listener(&self) {
        let before = {
            let mut g = self.shared.lock_any();
            g.readers
                .get_mut(&self.guid)
                .and_then(|r| r.listener.take())
        };
        drop(before);
    }

    /// The statuses changed since they were last read
    /// (`get_status_changes`).
    pub fn status_changes(&self) -> StatusMask {
        let g = self.shared.lock_any();
        g.readers
            .get(&self.guid)
            .map_or(StatusMask::NONE, |r| r.changes)
    }

    /// The reader's StatusCondition (`get_statuscondition`).
    pub fn status_condition(&self) -> StatusCondition {
        StatusCondition::new(self.shared.clone(), self.guid)
    }

    /// A ReadCondition that is true while the reader has samples whose
    /// states pass `filter` (`create_readcondition`). Dropping every
    /// clone of it deletes it.
    pub fn create_readcondition(&self, filter: StateFilter) -> ReadCondition {
        ReadCondition::new(self.shared.clone(), self.guid, filter)
    }

    fn check_condition(&self, condition: &ReadCondition) -> Result<StateFilter> {
        if condition.reader() != self.guid {
            return Err(Error::PreconditionNotMet);
        }
        Ok(condition.filter())
    }

    /// Takes the samples `condition` is true for (`take_w_condition`).
    /// Fails with [`Error::PreconditionNotMet`] for a condition of
    /// another reader.
    pub fn take_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
        Ok(self.select(self.check_condition(condition)?, None, true))
    }

    /// Reads the samples `condition` is true for (`read_w_condition`).
    pub fn read_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
        Ok(self.select(self.check_condition(condition)?, None, false))
    }

    /// Reads a status, clearing its changed flag.
    fn status<R: Default>(&self, k: StatusMask, f: impl FnOnce(&mut ReaderState) -> R) -> R {
        let mut g = self.shared.lock_any();
        g.readers
            .get_mut(&self.guid)
            .map(|r| {
                r.changes = r.changes & !k;
                f(r)
            })
            .unwrap_or_default()
    }

    /// The SUBSCRIPTION_MATCHED status: the writers matched. Reading it
    /// resets the `*_change` counts.
    pub fn subscription_matched_status(&self) -> MatchedStatus {
        self.status(StatusMask::SUBSCRIPTION_MATCHED, |r| {
            r.matched_status.take()
        })
    }

    /// The SAMPLE_LOST status: samples of matched writers that never
    /// arrived (gaps in their sequence numbers, for a BEST_EFFORT reader).
    /// Reading it resets `total_count_change`.
    pub fn sample_lost_status(&self) -> SampleLostStatus {
        self.status(StatusMask::SAMPLE_LOST, |r| r.samples.lost.take())
    }

    /// The writers matched now (`get_matched_publications`).
    pub fn matched_publications(&self) -> Vec<Guid> {
        let g = self.shared.lock_any();
        g.readers
            .get(&self.guid)
            .map(|r| r.matched.iter().copied().collect())
            .unwrap_or_default()
    }

    /// The REQUESTED_INCOMPATIBLE_QOS status: writers of the same topic,
    /// type and partition that this reader did not match because of
    /// their QoS. Reading it resets `total_count_change`.
    pub fn requested_incompatible_qos_status(&self) -> IncompatibleQosStatus {
        self.status(StatusMask::REQUESTED_INCOMPATIBLE_QOS, |r| {
            r.incompatible.take()
        })
    }

    /// The SAMPLE_REJECTED status: samples dropped because of the
    /// reader's RESOURCE_LIMITS. Reading it resets `total_count_change`.
    pub fn sample_rejected_status(&self) -> SampleRejectedStatus {
        self.status(StatusMask::SAMPLE_REJECTED, |r| {
            r.samples.take_rejected_status()
        })
    }

    /// The LIVELINESS_CHANGED status: how many matched writers are alive
    /// and how many are not. Reading it resets the `*_change` counts.
    pub fn liveliness_changed_status(&self) -> LivelinessChangedStatus {
        self.status(StatusMask::LIVELINESS_CHANGED, |r| {
            r.liveliness_changed.take()
        })
    }

    /// The REQUESTED_DEADLINE_MISSED status: DEADLINE periods in which an
    /// alive instance got no sample. Reading it resets
    /// `total_count_change`.
    pub fn requested_deadline_missed_status(&self) -> DeadlineMissedStatus {
        self.status(StatusMask::REQUESTED_DEADLINE_MISSED, |r| {
            r.deadlines.missed.take()
        })
    }

    /// Waits until at least `count` writers are matched, or `timeout`
    /// passes. Returns whether they are.
    pub fn wait_for_publications(&self, count: usize, timeout: Duration) -> bool {
        let deadline = Instant::now() + timeout;
        loop {
            if self.matched_publications().len() >= count {
                return true;
            }
            if Instant::now() >= deadline {
                return false;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
    }
}

impl<T: PlainType> DataReader<T> {
    /// Removes and returns the samples received, in the order they
    /// arrived, without copying them: the samples that a writer of this
    /// host loaned (see
    /// [`DataWriter::loan_sample`](crate::DataWriter::loan_sample)) are
    /// read in place in its shared memory, and its slot stays held until
    /// the [`ReadLoan`] is dropped. Other samples are deserialized.
    pub fn take_loaned(&self) -> Vec<Sample<ReadLoan<T>>> {
        self.select_loaned(StateFilter::ANY, None, true, usize::MAX)
    }

    /// Like [`Self::take_loaned`], leaving the samples in the reader,
    /// marked as read.
    pub fn read_loaned(&self) -> Vec<Sample<ReadLoan<T>>> {
        self.select_loaned(StateFilter::ANY, None, false, usize::MAX)
    }

    /// Like [`Self::take_loaned`], at most `max` samples.
    pub fn take_loaned_max(&self, max: usize) -> Vec<Sample<ReadLoan<T>>> {
        self.select_loaned(StateFilter::ANY, None, true, max)
    }

    fn select_loaned(
        &self,
        filter: StateFilter,
        instance: Option<InstanceHandle>,
        take: bool,
        max: usize,
    ) -> Vec<Sample<ReadLoan<T>>> {
        self.select_raw(filter, instance, take, max)
            .into_iter()
            .filter_map(|(payload, info)| {
                let data = match payload {
                    None => None,
                    Some(p) => {
                        #[cfg(feature = "shm")]
                        if let Payload::Loaned(l) = &p
                            && let Some(r) = ReadLoan::shared(l)
                        {
                            return Some(Sample {
                                data: Some(r),
                                info,
                            });
                        }
                        Some(ReadLoan::owned(self.samples.decode(&p)?))
                    }
                };
                Some(Sample { data, info })
            })
            .collect()
    }
}

impl<T> Drop for DataReader<T> {
    fn drop(&mut self) {
        if self.owned {
            self.shared.remove_reader(&self.guid);
        }
    }
}

/// The listener of a reader, as kept by the participant: `listener`
/// called with a handle to the reader.
fn reader_listener<T: 'static>(
    samples: Arc<dyn SampleType<T>>,
    listener: impl DataReaderListener<T> + 'static,
) -> ReaderListener {
    Arc::new(move |shared: &Arc<Shared>, guid, event| {
        let reader = DataReader::<T> {
            shared: shared.clone(),
            guid,
            owned: false,
            samples: samples.clone(),
        };
        match event {
            ReaderEvent::DataAvailable => listener.on_data_available(&reader),
            ReaderEvent::SubscriptionMatched(s) => listener.on_subscription_matched(&reader, s),
            ReaderEvent::LivelinessChanged(s) => listener.on_liveliness_changed(&reader, s),
            ReaderEvent::RequestedDeadlineMissed(s) => {
                listener.on_requested_deadline_missed(&reader, s)
            }
            ReaderEvent::RequestedIncompatibleQos(s) => {
                listener.on_requested_incompatible_qos(&reader, s)
            }
            ReaderEvent::SampleRejected(s) => listener.on_sample_rejected(&reader, s),
            ReaderEvent::SampleLost(s) => listener.on_sample_lost(&reader, s),
        }
    })
}

/// The reads and takes of a [`DataReader`] limited to a number of
/// samples ([`DataReader::max_samples`]).
pub struct MaxSamples<'a, T> {
    reader: &'a DataReader<T>,
    max: usize,
}

impl<T> std::fmt::Debug for MaxSamples<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MaxSamples")
            .field("reader", self.reader)
            .field("max", &self.max)
            .finish()
    }
}

impl<T> MaxSamples<'_, T> {
    /// Like [`DataReader::take_with`].
    pub fn take_with(&self, filter: StateFilter) -> Vec<Sample<T>> {
        self.reader.select_max(filter, None, true, self.max)
    }

    /// Like [`DataReader::read_with`].
    pub fn read_with(&self, filter: StateFilter) -> Vec<Sample<T>> {
        self.reader.select_max(filter, None, false, self.max)
    }

    /// Like [`DataReader::take`].
    pub fn take(&self) -> Vec<Sample<T>> {
        self.take_with(StateFilter::ANY)
    }

    /// Like [`DataReader::read`].
    pub fn read(&self) -> Vec<Sample<T>> {
        self.read_with(StateFilter::ANY)
    }

    /// Like [`DataReader::take_instance`].
    pub fn take_instance(&self, instance: InstanceHandle) -> Vec<Sample<T>> {
        self.reader
            .select_max(StateFilter::ANY, Some(instance), true, self.max)
    }

    /// Like [`DataReader::read_instance`].
    pub fn read_instance(&self, instance: InstanceHandle) -> Vec<Sample<T>> {
        self.reader
            .select_max(StateFilter::ANY, Some(instance), false, self.max)
    }

    /// Like [`DataReader::take_next_instance`].
    pub fn take_next_instance(
        &self,
        previous: Option<InstanceHandle>,
        filter: StateFilter,
    ) -> Vec<Sample<T>> {
        self.reader.next_instance(previous, filter, true, self.max)
    }

    /// Like [`DataReader::read_next_instance`].
    pub fn read_next_instance(
        &self,
        previous: Option<InstanceHandle>,
        filter: StateFilter,
    ) -> Vec<Sample<T>> {
        self.reader.next_instance(previous, filter, false, self.max)
    }

    /// Like [`DataReader::take_w_condition`].
    pub fn take_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
        let f = self.reader.check_condition(condition)?;
        Ok(self.reader.select_max(f, None, true, self.max))
    }

    /// Like [`DataReader::read_w_condition`].
    pub fn read_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
        let f = self.reader.check_condition(condition)?;
        Ok(self.reader.select_max(f, None, false, self.max))
    }
}