Skip to main content

rustorb_dds/
subscriber.rs

1//! `Subscriber` and `DataReader`.
2
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use rustorb_rtps::sedp::EndpointData;
7use rustorb_rtps::{Guid, entity_kind};
8
9use crate::condition::{ReadCondition, StatusCondition};
10use crate::error::{Error, Result};
11#[cfg(feature = "shm")]
12use crate::instance::Payload;
13use crate::instance::{InstanceHandle, SampleInfo, Selected, StateFilter};
14use crate::listener::{DataReaderListener, SubscriberEntity, SubscriberListener};
15use crate::loan::{PlainType, ReadLoan};
16use crate::participant::{ReaderEvent, ReaderListener, ReaderState, Shared};
17use crate::qos::{DataReaderQos, SubscriberQos, TypeConsistency, duration_to_rtps};
18use crate::status::{
19    DeadlineMissedStatus, IncompatibleQosStatus, LivelinessChangedStatus, MatchedStatus,
20    SampleLostStatus, SampleRejectedStatus, StatusMask,
21};
22use crate::topic::TopicDescription;
23use crate::typed::SampleType;
24
25/// A DDS subscriber (DDS 1.4, 2.2.2.5.1): creates data readers.
26#[derive(Clone)]
27pub struct Subscriber {
28    shared: Arc<Shared>,
29    entity: Arc<SubscriberEntity>,
30}
31
32impl std::fmt::Debug for Subscriber {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        f.debug_struct("Subscriber").finish_non_exhaustive()
35    }
36}
37
38impl Subscriber {
39    pub(crate) fn from_entity(shared: Arc<Shared>, entity: Arc<SubscriberEntity>) -> Self {
40        Subscriber { shared, entity }
41    }
42
43    /// The subscriber's QoS.
44    pub fn qos(&self) -> &SubscriberQos {
45        &self.entity.qos
46    }
47
48    /// Sets the subscriber's listener (`set_listener`), replacing any
49    /// earlier one: it is called for DATA_ON_READERS, and for the
50    /// statuses in `mask` of its readers that their own listeners do not
51    /// take (DDS 1.4, 2.2.4.3). See [`SubscriberListener`].
52    pub fn set_listener(&self, listener: impl SubscriberListener + 'static, mask: StatusMask) {
53        *self
54            .entity
55            .listener
56            .lock()
57            .unwrap_or_else(|e| e.into_inner()) = Some((Arc::new(listener), mask));
58    }
59
60    /// Removes the subscriber's listener.
61    pub fn clear_listener(&self) {
62        *self
63            .entity
64            .listener
65            .lock()
66            .unwrap_or_else(|e| e.into_inner()) = None;
67    }
68
69    /// Calls `on_data_available` of the listeners of its readers that
70    /// have new data (`notify_datareaders`, DDS 1.4, 2.2.2.5.2.8): from
71    /// `on_data_on_readers`, to have each reader handle its own.
72    pub fn notify_datareaders(&self) {
73        self.shared.notify_datareaders(&self.entity);
74    }
75
76    /// Whether `self` and `other` are handles of the same subscriber.
77    pub fn same_as(&self, other: &Subscriber) -> bool {
78        Arc::ptr_eq(&self.entity, &other.entity)
79    }
80
81    /// Creates a reader for `topic` with the default QoS: BEST_EFFORT,
82    /// KEEP_LAST(1), VOLATILE. `topic` is a [`Topic`](crate::Topic) or a
83    /// [`ContentFilteredTopic`](crate::ContentFilteredTopic).
84    pub fn create_datareader<T>(&self, topic: &impl TopicDescription<T>) -> Result<DataReader<T>> {
85        self.create_datareader_with_qos(topic, DataReaderQos::default())
86    }
87
88    /// Creates a reader for `topic`.
89    ///
90    /// A RELIABLE reader gets the samples of each writer in order and
91    /// without gaps, asking for those lost on the way; it matches only
92    /// RELIABLE writers. A BEST_EFFORT reader takes what arrives, in
93    /// order, and matches any writer.
94    pub fn create_datareader_with_qos<T>(
95        &self,
96        topic: &impl TopicDescription<T>,
97        qos: DataReaderQos,
98    ) -> Result<DataReader<T>> {
99        self.create(topic, qos, None, |_| {})
100    }
101
102    /// Creates a reader whose announcement `f` changes before it is
103    /// matched (as with the topic aliases of DDS-RPC).
104    pub(crate) fn create_datareader_with<T>(
105        &self,
106        topic: &impl TopicDescription<T>,
107        qos: DataReaderQos,
108        f: impl FnOnce(&mut EndpointData),
109    ) -> Result<DataReader<T>> {
110        self.create(topic, qos, None, f)
111    }
112
113    /// Creates a reader for `topic` with a listener for the statuses in
114    /// `mask`, set before the reader is matched, so that it is told of
115    /// the writers already there and of the samples they kept
116    /// (DDS 1.4, 2.2.2.5.2.5).
117    pub fn create_datareader_with_listener<T: 'static>(
118        &self,
119        topic: &impl TopicDescription<T>,
120        qos: DataReaderQos,
121        listener: impl DataReaderListener<T> + 'static,
122        mask: StatusMask,
123    ) -> Result<DataReader<T>> {
124        let l = reader_listener(topic.topic().samples.clone(), listener);
125        self.create(topic, qos, Some((l, mask)), |_| {})
126    }
127
128    fn create<T>(
129        &self,
130        description: &impl TopicDescription<T>,
131        qos: DataReaderQos,
132        listener: Option<(ReaderListener, StatusMask)>,
133        f: impl FnOnce(&mut EndpointData),
134    ) -> Result<DataReader<T>> {
135        let topic = description.topic();
136        let cft = description.content_filter();
137        let kind = if topic.samples.keyed() {
138            entity_kind::USER_READER_WITH_KEY
139        } else {
140            entity_kind::USER_READER_NO_KEY
141        };
142        let guid = self.shared.new_guid(kind)?;
143        let type_name = topic.type_name();
144        let mut data = EndpointData::reader(guid, topic.name(), type_name);
145        data.type_information = self.shared.type_information(type_name)?;
146        data.data_representation = qos.data_representation.clone();
147        if qos.type_consistency != TypeConsistency::default() {
148            data.type_consistency = Some(qos.type_consistency);
149        }
150        data.reliability = qos.reliability.to_rtps();
151        data.durability = qos.durability;
152        data.deadline = duration_to_rtps(qos.deadline);
153        data.liveliness = qos.liveliness.to_rtps();
154        data.user_data = qos.user_data.clone();
155        data.data_tags = qos.data_tags.clone();
156        data.partitions = self.entity.qos.partition.clone();
157        let filter = cft.map(|c| {
158            let (filter, property) = c.reader_filter();
159            data.content_filter = Some(property);
160            filter
161        });
162        f(&mut data);
163        self.shared.add_reader(
164            data,
165            qos,
166            topic.samples.key_ops(),
167            listener,
168            filter,
169            self.entity.clone(),
170        )?;
171        if let Some(c) = cft {
172            c.add_reader(guid);
173        }
174        Ok(DataReader {
175            shared: self.shared.clone(),
176            guid,
177            owned: true,
178            samples: topic.samples.clone(),
179        })
180    }
181}
182
183/// A sample with its information.
184#[derive(Clone, Debug, PartialEq)]
185pub struct Sample<T> {
186    /// The value; `None` for a sample without data
187    /// (`info.valid_data == false`), which only tells of a change in the
188    /// state of its instance.
189    pub data: Option<T>,
190    /// The information.
191    pub info: SampleInfo,
192}
193
194/// A DDS data reader (DDS 1.4, 2.2.2.5.3) of samples of type `T`: a
195/// [`TopicType`](crate::TopicType), or [`DynamicData`](crate::DynamicData)
196/// for a topic of a type known at run time (a `DynamicDataReader`,
197/// DDS-XTypes 1.3, 7.5.2.12).
198///
199/// Samples that cannot be deserialized as `T` are dropped when they are
200/// read or taken. Dropping the reader tells the other participants it is
201/// gone.
202pub struct DataReader<T> {
203    pub(crate) shared: Arc<Shared>,
204    pub(crate) guid: Guid,
205    /// Whether dropping this handle deletes the reader: not for the
206    /// handle given to a listener.
207    owned: bool,
208    samples: Arc<dyn SampleType<T>>,
209}
210
211/// A [`DataReaderListener`] for DATA_AVAILABLE alone, from a function.
212struct DataAvailable<F>(F);
213
214impl<T, F: Fn(&DataReader<T>) + Send + Sync> DataReaderListener<T> for DataAvailable<F> {
215    fn on_data_available(&self, reader: &DataReader<T>) {
216        (self.0)(reader)
217    }
218}
219
220impl<T> std::fmt::Debug for DataReader<T> {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        f.debug_struct("DataReader")
223            .field("guid", &self.guid)
224            .field("type_name", &self.samples.type_name())
225            .finish()
226    }
227}
228
229fn decode<T>(samples: &dyn SampleType<T>, (payload, info): Selected) -> Option<Sample<T>> {
230    let data = match payload {
231        Some(p) => Some(samples.decode(&p)?),
232        None => None,
233    };
234    Some(Sample { data, info })
235}
236
237impl<T> DataReader<T> {
238    /// The reader's GUID.
239    pub fn guid(&self) -> Guid {
240        self.guid
241    }
242
243    fn select(
244        &self,
245        filter: StateFilter,
246        instance: Option<InstanceHandle>,
247        take: bool,
248    ) -> Vec<Sample<T>> {
249        self.select_max(filter, instance, take, usize::MAX)
250    }
251
252    fn select_max(
253        &self,
254        filter: StateFilter,
255        instance: Option<InstanceHandle>,
256        take: bool,
257        max: usize,
258    ) -> Vec<Sample<T>> {
259        self.select_raw(filter, instance, take, max)
260            .into_iter()
261            .filter_map(|r| decode(&*self.samples, r))
262            .collect()
263    }
264
265    fn select_raw(
266        &self,
267        filter: StateFilter,
268        instance: Option<InstanceHandle>,
269        take: bool,
270        max: usize,
271    ) -> Vec<Selected> {
272        let mut g = self.shared.lock_any();
273        match g.readers.get_mut(&self.guid) {
274            Some(r) => {
275                r.changes = r.changes & !StatusMask::DATA_AVAILABLE;
276                r.samples.select_max(filter, instance, take, max)
277            }
278            None => Vec::new(),
279        }
280    }
281
282    /// Removes and returns the samples received, still serialized.
283    pub(crate) fn take_raw(&self) -> Vec<(Option<Vec<u8>>, SampleInfo)> {
284        self.select_raw(StateFilter::ANY, None, true, usize::MAX)
285            .into_iter()
286            .map(|(p, i)| (p.map(|p| p.to_vec()), i))
287            .collect()
288    }
289
290    /// Deserializes a payload of the reader's type.
291    pub(crate) fn decode_raw(&self, payload: &[u8]) -> Option<T> {
292        self.samples.decode(payload)
293    }
294
295    /// Removes and returns the samples received, in the order they
296    /// arrived.
297    pub fn take(&self) -> Vec<Sample<T>> {
298        self.select(StateFilter::ANY, None, true)
299    }
300
301    /// Returns the samples received, in the order they arrived, and
302    /// leaves them in the reader, marked as read.
303    pub fn read(&self) -> Vec<Sample<T>> {
304        self.select(StateFilter::ANY, None, false)
305    }
306
307    /// Like [`Self::take`], for the samples whose states pass `filter`.
308    pub fn take_with(&self, filter: StateFilter) -> Vec<Sample<T>> {
309        self.select(filter, None, true)
310    }
311
312    /// Like [`Self::read`], for the samples whose states pass `filter`.
313    pub fn read_with(&self, filter: StateFilter) -> Vec<Sample<T>> {
314        self.select(filter, None, false)
315    }
316
317    /// Takes the samples of one instance (`take_instance`).
318    pub fn take_instance(&self, instance: InstanceHandle) -> Vec<Sample<T>> {
319        self.select(StateFilter::ANY, Some(instance), true)
320    }
321
322    /// Reads the samples of one instance (`read_instance`).
323    pub fn read_instance(&self, instance: InstanceHandle) -> Vec<Sample<T>> {
324        self.select(StateFilter::ANY, Some(instance), false)
325    }
326
327    /// Takes the samples of the instance after `previous`, in handle
328    /// order, that has samples passing `filter`; from the first instance
329    /// when `previous` is `None` (`take_next_instance`). Empty when there
330    /// is no such instance.
331    pub fn take_next_instance(
332        &self,
333        previous: Option<InstanceHandle>,
334        filter: StateFilter,
335    ) -> Vec<Sample<T>> {
336        self.next_instance(previous, filter, true, usize::MAX)
337    }
338
339    /// Like [`Self::take_next_instance`], reading (`read_next_instance`).
340    pub fn read_next_instance(
341        &self,
342        previous: Option<InstanceHandle>,
343        filter: StateFilter,
344    ) -> Vec<Sample<T>> {
345        self.next_instance(previous, filter, false, usize::MAX)
346    }
347
348    fn next_instance(
349        &self,
350        previous: Option<InstanceHandle>,
351        filter: StateFilter,
352        take: bool,
353        max: usize,
354    ) -> Vec<Sample<T>> {
355        let raw = {
356            let mut g = self.shared.lock_any();
357            let Some(r) = g.readers.get_mut(&self.guid) else {
358                return Vec::new();
359            };
360            r.changes = r.changes & !StatusMask::DATA_AVAILABLE;
361            match r.samples.next_instance(previous, filter) {
362                Some(h) => r.samples.select_max(filter, Some(h), take, max),
363                None => Vec::new(),
364            }
365        };
366        raw.into_iter()
367            .filter_map(|r| decode(&*self.samples, r))
368            .collect()
369    }
370
371    /// The reads and takes of at most `max_samples` samples (the
372    /// `max_samples` argument of DDS 1.4, 2.2.2.5.3.8): the first to
373    /// arrive of those selected. The others stay in the reader as they
374    /// were.
375    pub fn max_samples(&self, max_samples: usize) -> MaxSamples<'_, T> {
376        MaxSamples {
377            reader: self,
378            max: max_samples,
379        }
380    }
381
382    /// The handle of the instance of `instance` (`lookup_instance`), if
383    /// the reader has it.
384    pub fn lookup_instance(&self, instance: &T) -> Option<InstanceHandle> {
385        let h = self.samples.instance_of(instance).ok()?;
386        let g = self.shared.lock_any();
387        let r = g.readers.get(&self.guid)?;
388        r.samples.has_instance(&h).then_some(h)
389    }
390
391    /// The key of an instance (`get_key_value`): the last value received
392    /// for it, whose key members identify it. `None` on a keyless topic,
393    /// if the reader has not received a value for it, or if it has
394    /// forgotten the instance: one with no samples left and no writers is
395    /// forgotten at the read or take after the one that emptied it.
396    pub fn get_key_value(&self, instance: InstanceHandle) -> Option<T> {
397        let g = self.shared.lock_any();
398        let r = g.readers.get(&self.guid)?;
399        self.samples.decode(r.samples.last_value(&instance)?)
400    }
401
402    /// Waits until there is a sample not yet read, or `timeout` passes.
403    /// Returns whether there is one.
404    pub fn wait_for_data(&self, timeout: Duration) -> bool {
405        let deadline = Instant::now() + timeout;
406        let mut g = self.shared.lock_any();
407        loop {
408            let has = g
409                .readers
410                .get(&self.guid)
411                .is_some_and(|r| r.samples.has_unread());
412            if has {
413                return true;
414            }
415            let now = Instant::now();
416            if now >= deadline {
417                return false;
418            }
419            g = match self.shared.data_arrived.wait_timeout(g, deadline - now) {
420                Ok((g, _)) => g,
421                Err(e) => e.into_inner().0,
422            };
423        }
424    }
425
426    /// Sets the listener (`set_listener`), replacing any earlier one:
427    /// its methods are called for the statuses in `mask` when they
428    /// change. See [`DataReaderListener`].
429    pub fn set_listener(&self, listener: impl DataReaderListener<T> + 'static, mask: StatusMask)
430    where
431        T: 'static,
432    {
433        let l = reader_listener(self.samples.clone(), listener);
434        // The one before is dropped with no lock held (#117).
435        let before = {
436            let mut g = self.shared.lock_any();
437            g.readers
438                .get_mut(&self.guid)
439                .and_then(|r| r.listener.replace((l, mask)))
440        };
441        drop(before);
442    }
443
444    /// Sets a listener for DATA_AVAILABLE alone: `f` is called with the
445    /// reader when samples arrive. It may take them, or send to a
446    /// channel:
447    ///
448    /// ```no_run
449    /// # fn f<T: rustorb_typesupport::TopicType + Send + 'static>(
450    /// #     reader: &rustorb_dds::DataReader<T>,
451    /// # ) {
452    /// let (tx, rx) = std::sync::mpsc::channel();
453    /// reader.on_data_available(move |r| {
454    ///     for s in r.take() {
455    ///         let _ = tx.send(s);
456    ///     }
457    /// });
458    /// # }
459    /// ```
460    pub fn on_data_available(&self, f: impl Fn(&DataReader<T>) + Send + Sync + 'static)
461    where
462        T: 'static,
463    {
464        self.set_listener(DataAvailable(f), StatusMask::DATA_AVAILABLE);
465    }
466
467    /// Removes the listener.
468    pub fn clear_listener(&self) {
469        let before = {
470            let mut g = self.shared.lock_any();
471            g.readers
472                .get_mut(&self.guid)
473                .and_then(|r| r.listener.take())
474        };
475        drop(before);
476    }
477
478    /// The statuses changed since they were last read
479    /// (`get_status_changes`).
480    pub fn status_changes(&self) -> StatusMask {
481        let g = self.shared.lock_any();
482        g.readers
483            .get(&self.guid)
484            .map_or(StatusMask::NONE, |r| r.changes)
485    }
486
487    /// The reader's StatusCondition (`get_statuscondition`).
488    pub fn status_condition(&self) -> StatusCondition {
489        StatusCondition::new(self.shared.clone(), self.guid)
490    }
491
492    /// A ReadCondition that is true while the reader has samples whose
493    /// states pass `filter` (`create_readcondition`). Dropping every
494    /// clone of it deletes it.
495    pub fn create_readcondition(&self, filter: StateFilter) -> ReadCondition {
496        ReadCondition::new(self.shared.clone(), self.guid, filter)
497    }
498
499    fn check_condition(&self, condition: &ReadCondition) -> Result<StateFilter> {
500        if condition.reader() != self.guid {
501            return Err(Error::PreconditionNotMet);
502        }
503        Ok(condition.filter())
504    }
505
506    /// Takes the samples `condition` is true for (`take_w_condition`).
507    /// Fails with [`Error::PreconditionNotMet`] for a condition of
508    /// another reader.
509    pub fn take_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
510        Ok(self.select(self.check_condition(condition)?, None, true))
511    }
512
513    /// Reads the samples `condition` is true for (`read_w_condition`).
514    pub fn read_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
515        Ok(self.select(self.check_condition(condition)?, None, false))
516    }
517
518    /// Reads a status, clearing its changed flag.
519    fn status<R: Default>(&self, k: StatusMask, f: impl FnOnce(&mut ReaderState) -> R) -> R {
520        let mut g = self.shared.lock_any();
521        g.readers
522            .get_mut(&self.guid)
523            .map(|r| {
524                r.changes = r.changes & !k;
525                f(r)
526            })
527            .unwrap_or_default()
528    }
529
530    /// The SUBSCRIPTION_MATCHED status: the writers matched. Reading it
531    /// resets the `*_change` counts.
532    pub fn subscription_matched_status(&self) -> MatchedStatus {
533        self.status(StatusMask::SUBSCRIPTION_MATCHED, |r| {
534            r.matched_status.take()
535        })
536    }
537
538    /// The SAMPLE_LOST status: samples of matched writers that never
539    /// arrived (gaps in their sequence numbers, for a BEST_EFFORT reader).
540    /// Reading it resets `total_count_change`.
541    pub fn sample_lost_status(&self) -> SampleLostStatus {
542        self.status(StatusMask::SAMPLE_LOST, |r| r.samples.lost.take())
543    }
544
545    /// The writers matched now (`get_matched_publications`).
546    pub fn matched_publications(&self) -> Vec<Guid> {
547        let g = self.shared.lock_any();
548        g.readers
549            .get(&self.guid)
550            .map(|r| r.matched.iter().copied().collect())
551            .unwrap_or_default()
552    }
553
554    /// The REQUESTED_INCOMPATIBLE_QOS status: writers of the same topic,
555    /// type and partition that this reader did not match because of
556    /// their QoS. Reading it resets `total_count_change`.
557    pub fn requested_incompatible_qos_status(&self) -> IncompatibleQosStatus {
558        self.status(StatusMask::REQUESTED_INCOMPATIBLE_QOS, |r| {
559            r.incompatible.take()
560        })
561    }
562
563    /// The SAMPLE_REJECTED status: samples dropped because of the
564    /// reader's RESOURCE_LIMITS. Reading it resets `total_count_change`.
565    pub fn sample_rejected_status(&self) -> SampleRejectedStatus {
566        self.status(StatusMask::SAMPLE_REJECTED, |r| {
567            r.samples.take_rejected_status()
568        })
569    }
570
571    /// The LIVELINESS_CHANGED status: how many matched writers are alive
572    /// and how many are not. Reading it resets the `*_change` counts.
573    pub fn liveliness_changed_status(&self) -> LivelinessChangedStatus {
574        self.status(StatusMask::LIVELINESS_CHANGED, |r| {
575            r.liveliness_changed.take()
576        })
577    }
578
579    /// The REQUESTED_DEADLINE_MISSED status: DEADLINE periods in which an
580    /// alive instance got no sample. Reading it resets
581    /// `total_count_change`.
582    pub fn requested_deadline_missed_status(&self) -> DeadlineMissedStatus {
583        self.status(StatusMask::REQUESTED_DEADLINE_MISSED, |r| {
584            r.deadlines.missed.take()
585        })
586    }
587
588    /// Waits until at least `count` writers are matched, or `timeout`
589    /// passes. Returns whether they are.
590    pub fn wait_for_publications(&self, count: usize, timeout: Duration) -> bool {
591        let deadline = Instant::now() + timeout;
592        loop {
593            if self.matched_publications().len() >= count {
594                return true;
595            }
596            if Instant::now() >= deadline {
597                return false;
598            }
599            std::thread::sleep(Duration::from_millis(10));
600        }
601    }
602}
603
604impl<T: PlainType> DataReader<T> {
605    /// Removes and returns the samples received, in the order they
606    /// arrived, without copying them: the samples that a writer of this
607    /// host loaned (see
608    /// [`DataWriter::loan_sample`](crate::DataWriter::loan_sample)) are
609    /// read in place in its shared memory, and its slot stays held until
610    /// the [`ReadLoan`] is dropped. Other samples are deserialized.
611    pub fn take_loaned(&self) -> Vec<Sample<ReadLoan<T>>> {
612        self.select_loaned(StateFilter::ANY, None, true, usize::MAX)
613    }
614
615    /// Like [`Self::take_loaned`], leaving the samples in the reader,
616    /// marked as read.
617    pub fn read_loaned(&self) -> Vec<Sample<ReadLoan<T>>> {
618        self.select_loaned(StateFilter::ANY, None, false, usize::MAX)
619    }
620
621    /// Like [`Self::take_loaned`], at most `max` samples.
622    pub fn take_loaned_max(&self, max: usize) -> Vec<Sample<ReadLoan<T>>> {
623        self.select_loaned(StateFilter::ANY, None, true, max)
624    }
625
626    fn select_loaned(
627        &self,
628        filter: StateFilter,
629        instance: Option<InstanceHandle>,
630        take: bool,
631        max: usize,
632    ) -> Vec<Sample<ReadLoan<T>>> {
633        self.select_raw(filter, instance, take, max)
634            .into_iter()
635            .filter_map(|(payload, info)| {
636                let data = match payload {
637                    None => None,
638                    Some(p) => {
639                        #[cfg(feature = "shm")]
640                        if let Payload::Loaned(l) = &p
641                            && let Some(r) = ReadLoan::shared(l)
642                        {
643                            return Some(Sample {
644                                data: Some(r),
645                                info,
646                            });
647                        }
648                        Some(ReadLoan::owned(self.samples.decode(&p)?))
649                    }
650                };
651                Some(Sample { data, info })
652            })
653            .collect()
654    }
655}
656
657impl<T> Drop for DataReader<T> {
658    fn drop(&mut self) {
659        if self.owned {
660            self.shared.remove_reader(&self.guid);
661        }
662    }
663}
664
665/// The listener of a reader, as kept by the participant: `listener`
666/// called with a handle to the reader.
667fn reader_listener<T: 'static>(
668    samples: Arc<dyn SampleType<T>>,
669    listener: impl DataReaderListener<T> + 'static,
670) -> ReaderListener {
671    Arc::new(move |shared: &Arc<Shared>, guid, event| {
672        let reader = DataReader::<T> {
673            shared: shared.clone(),
674            guid,
675            owned: false,
676            samples: samples.clone(),
677        };
678        match event {
679            ReaderEvent::DataAvailable => listener.on_data_available(&reader),
680            ReaderEvent::SubscriptionMatched(s) => listener.on_subscription_matched(&reader, s),
681            ReaderEvent::LivelinessChanged(s) => listener.on_liveliness_changed(&reader, s),
682            ReaderEvent::RequestedDeadlineMissed(s) => {
683                listener.on_requested_deadline_missed(&reader, s)
684            }
685            ReaderEvent::RequestedIncompatibleQos(s) => {
686                listener.on_requested_incompatible_qos(&reader, s)
687            }
688            ReaderEvent::SampleRejected(s) => listener.on_sample_rejected(&reader, s),
689            ReaderEvent::SampleLost(s) => listener.on_sample_lost(&reader, s),
690        }
691    })
692}
693
694/// The reads and takes of a [`DataReader`] limited to a number of
695/// samples ([`DataReader::max_samples`]).
696pub struct MaxSamples<'a, T> {
697    reader: &'a DataReader<T>,
698    max: usize,
699}
700
701impl<T> std::fmt::Debug for MaxSamples<'_, T> {
702    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
703        f.debug_struct("MaxSamples")
704            .field("reader", self.reader)
705            .field("max", &self.max)
706            .finish()
707    }
708}
709
710impl<T> MaxSamples<'_, T> {
711    /// Like [`DataReader::take_with`].
712    pub fn take_with(&self, filter: StateFilter) -> Vec<Sample<T>> {
713        self.reader.select_max(filter, None, true, self.max)
714    }
715
716    /// Like [`DataReader::read_with`].
717    pub fn read_with(&self, filter: StateFilter) -> Vec<Sample<T>> {
718        self.reader.select_max(filter, None, false, self.max)
719    }
720
721    /// Like [`DataReader::take`].
722    pub fn take(&self) -> Vec<Sample<T>> {
723        self.take_with(StateFilter::ANY)
724    }
725
726    /// Like [`DataReader::read`].
727    pub fn read(&self) -> Vec<Sample<T>> {
728        self.read_with(StateFilter::ANY)
729    }
730
731    /// Like [`DataReader::take_instance`].
732    pub fn take_instance(&self, instance: InstanceHandle) -> Vec<Sample<T>> {
733        self.reader
734            .select_max(StateFilter::ANY, Some(instance), true, self.max)
735    }
736
737    /// Like [`DataReader::read_instance`].
738    pub fn read_instance(&self, instance: InstanceHandle) -> Vec<Sample<T>> {
739        self.reader
740            .select_max(StateFilter::ANY, Some(instance), false, self.max)
741    }
742
743    /// Like [`DataReader::take_next_instance`].
744    pub fn take_next_instance(
745        &self,
746        previous: Option<InstanceHandle>,
747        filter: StateFilter,
748    ) -> Vec<Sample<T>> {
749        self.reader.next_instance(previous, filter, true, self.max)
750    }
751
752    /// Like [`DataReader::read_next_instance`].
753    pub fn read_next_instance(
754        &self,
755        previous: Option<InstanceHandle>,
756        filter: StateFilter,
757    ) -> Vec<Sample<T>> {
758        self.reader.next_instance(previous, filter, false, self.max)
759    }
760
761    /// Like [`DataReader::take_w_condition`].
762    pub fn take_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
763        let f = self.reader.check_condition(condition)?;
764        Ok(self.reader.select_max(f, None, true, self.max))
765    }
766
767    /// Like [`DataReader::read_w_condition`].
768    pub fn read_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
769        let f = self.reader.check_condition(condition)?;
770        Ok(self.reader.select_max(f, None, false, self.max))
771    }
772}