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` if the reader has
393    /// not received a value for it, or has forgotten the instance: one
394    /// with no samples left and no writers is forgotten at the read or
395    /// 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        let mut g = self.shared.lock_any();
435        if let Some(r) = g.readers.get_mut(&self.guid) {
436            r.listener = Some((l, mask));
437        }
438    }
439
440    /// Sets a listener for DATA_AVAILABLE alone: `f` is called with the
441    /// reader when samples arrive. It may take them, or send to a
442    /// channel:
443    ///
444    /// ```no_run
445    /// # fn f<T: rustorb_typesupport::TopicType + Send + 'static>(
446    /// #     reader: &rustorb_dds::DataReader<T>,
447    /// # ) {
448    /// let (tx, rx) = std::sync::mpsc::channel();
449    /// reader.on_data_available(move |r| {
450    ///     for s in r.take() {
451    ///         let _ = tx.send(s);
452    ///     }
453    /// });
454    /// # }
455    /// ```
456    pub fn on_data_available(&self, f: impl Fn(&DataReader<T>) + Send + Sync + 'static)
457    where
458        T: 'static,
459    {
460        self.set_listener(DataAvailable(f), StatusMask::DATA_AVAILABLE);
461    }
462
463    /// Removes the listener.
464    pub fn clear_listener(&self) {
465        let mut g = self.shared.lock_any();
466        if let Some(r) = g.readers.get_mut(&self.guid) {
467            r.listener = None;
468        }
469    }
470
471    /// The statuses changed since they were last read
472    /// (`get_status_changes`).
473    pub fn status_changes(&self) -> StatusMask {
474        let g = self.shared.lock_any();
475        g.readers
476            .get(&self.guid)
477            .map_or(StatusMask::NONE, |r| r.changes)
478    }
479
480    /// The reader's StatusCondition (`get_statuscondition`).
481    pub fn status_condition(&self) -> StatusCondition {
482        StatusCondition::new(self.shared.clone(), self.guid)
483    }
484
485    /// A ReadCondition that is true while the reader has samples whose
486    /// states pass `filter` (`create_readcondition`). Dropping every
487    /// clone of it deletes it.
488    pub fn create_readcondition(&self, filter: StateFilter) -> ReadCondition {
489        ReadCondition::new(self.shared.clone(), self.guid, filter)
490    }
491
492    fn check_condition(&self, condition: &ReadCondition) -> Result<StateFilter> {
493        if condition.reader() != self.guid {
494            return Err(Error::PreconditionNotMet);
495        }
496        Ok(condition.filter())
497    }
498
499    /// Takes the samples `condition` is true for (`take_w_condition`).
500    /// Fails with [`Error::PreconditionNotMet`] for a condition of
501    /// another reader.
502    pub fn take_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
503        Ok(self.select(self.check_condition(condition)?, None, true))
504    }
505
506    /// Reads the samples `condition` is true for (`read_w_condition`).
507    pub fn read_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
508        Ok(self.select(self.check_condition(condition)?, None, false))
509    }
510
511    /// Reads a status, clearing its changed flag.
512    fn status<R: Default>(&self, k: StatusMask, f: impl FnOnce(&mut ReaderState) -> R) -> R {
513        let mut g = self.shared.lock_any();
514        g.readers
515            .get_mut(&self.guid)
516            .map(|r| {
517                r.changes = r.changes & !k;
518                f(r)
519            })
520            .unwrap_or_default()
521    }
522
523    /// The SUBSCRIPTION_MATCHED status: the writers matched. Reading it
524    /// resets the `*_change` counts.
525    pub fn subscription_matched_status(&self) -> MatchedStatus {
526        self.status(StatusMask::SUBSCRIPTION_MATCHED, |r| {
527            r.matched_status.take()
528        })
529    }
530
531    /// The SAMPLE_LOST status: samples of matched writers that never
532    /// arrived (gaps in their sequence numbers, for a BEST_EFFORT reader).
533    /// Reading it resets `total_count_change`.
534    pub fn sample_lost_status(&self) -> SampleLostStatus {
535        self.status(StatusMask::SAMPLE_LOST, |r| r.samples.lost.take())
536    }
537
538    /// The writers matched now (`get_matched_publications`).
539    pub fn matched_publications(&self) -> Vec<Guid> {
540        let g = self.shared.lock_any();
541        g.readers
542            .get(&self.guid)
543            .map(|r| r.matched.iter().copied().collect())
544            .unwrap_or_default()
545    }
546
547    /// The REQUESTED_INCOMPATIBLE_QOS status: writers of the same topic,
548    /// type and partition that this reader did not match because of
549    /// their QoS. Reading it resets `total_count_change`.
550    pub fn requested_incompatible_qos_status(&self) -> IncompatibleQosStatus {
551        self.status(StatusMask::REQUESTED_INCOMPATIBLE_QOS, |r| {
552            r.incompatible.take()
553        })
554    }
555
556    /// The SAMPLE_REJECTED status: samples dropped because of the
557    /// reader's RESOURCE_LIMITS. Reading it resets `total_count_change`.
558    pub fn sample_rejected_status(&self) -> SampleRejectedStatus {
559        self.status(StatusMask::SAMPLE_REJECTED, |r| {
560            r.samples.take_rejected_status()
561        })
562    }
563
564    /// The LIVELINESS_CHANGED status: how many matched writers are alive
565    /// and how many are not. Reading it resets the `*_change` counts.
566    pub fn liveliness_changed_status(&self) -> LivelinessChangedStatus {
567        self.status(StatusMask::LIVELINESS_CHANGED, |r| {
568            r.liveliness_changed.take()
569        })
570    }
571
572    /// The REQUESTED_DEADLINE_MISSED status: DEADLINE periods in which an
573    /// alive instance got no sample. Reading it resets
574    /// `total_count_change`.
575    pub fn requested_deadline_missed_status(&self) -> DeadlineMissedStatus {
576        self.status(StatusMask::REQUESTED_DEADLINE_MISSED, |r| {
577            r.deadlines.missed.take()
578        })
579    }
580
581    /// Waits until at least `count` writers are matched, or `timeout`
582    /// passes. Returns whether they are.
583    pub fn wait_for_publications(&self, count: usize, timeout: Duration) -> bool {
584        let deadline = Instant::now() + timeout;
585        loop {
586            if self.matched_publications().len() >= count {
587                return true;
588            }
589            if Instant::now() >= deadline {
590                return false;
591            }
592            std::thread::sleep(Duration::from_millis(10));
593        }
594    }
595}
596
597impl<T: PlainType> DataReader<T> {
598    /// Removes and returns the samples received, in the order they
599    /// arrived, without copying them: the samples that a writer of this
600    /// host loaned (see
601    /// [`DataWriter::loan_sample`](crate::DataWriter::loan_sample)) are
602    /// read in place in its shared memory, and its slot stays held until
603    /// the [`ReadLoan`] is dropped. Other samples are deserialized.
604    pub fn take_loaned(&self) -> Vec<Sample<ReadLoan<T>>> {
605        self.select_loaned(StateFilter::ANY, None, true, usize::MAX)
606    }
607
608    /// Like [`Self::take_loaned`], leaving the samples in the reader,
609    /// marked as read.
610    pub fn read_loaned(&self) -> Vec<Sample<ReadLoan<T>>> {
611        self.select_loaned(StateFilter::ANY, None, false, usize::MAX)
612    }
613
614    /// Like [`Self::take_loaned`], at most `max` samples.
615    pub fn take_loaned_max(&self, max: usize) -> Vec<Sample<ReadLoan<T>>> {
616        self.select_loaned(StateFilter::ANY, None, true, max)
617    }
618
619    fn select_loaned(
620        &self,
621        filter: StateFilter,
622        instance: Option<InstanceHandle>,
623        take: bool,
624        max: usize,
625    ) -> Vec<Sample<ReadLoan<T>>> {
626        self.select_raw(filter, instance, take, max)
627            .into_iter()
628            .filter_map(|(payload, info)| {
629                let data = match payload {
630                    None => None,
631                    Some(p) => {
632                        #[cfg(feature = "shm")]
633                        if let Payload::Loaned(l) = &p
634                            && let Some(r) = ReadLoan::shared(l)
635                        {
636                            return Some(Sample {
637                                data: Some(r),
638                                info,
639                            });
640                        }
641                        Some(ReadLoan::owned(self.samples.decode(&p)?))
642                    }
643                };
644                Some(Sample { data, info })
645            })
646            .collect()
647    }
648}
649
650impl<T> Drop for DataReader<T> {
651    fn drop(&mut self) {
652        if self.owned {
653            self.shared.remove_reader(&self.guid);
654        }
655    }
656}
657
658/// The listener of a reader, as kept by the participant: `listener`
659/// called with a handle to the reader.
660fn reader_listener<T: 'static>(
661    samples: Arc<dyn SampleType<T>>,
662    listener: impl DataReaderListener<T> + 'static,
663) -> ReaderListener {
664    Arc::new(move |shared: &Arc<Shared>, guid, event| {
665        let reader = DataReader::<T> {
666            shared: shared.clone(),
667            guid,
668            owned: false,
669            samples: samples.clone(),
670        };
671        match event {
672            ReaderEvent::DataAvailable => listener.on_data_available(&reader),
673            ReaderEvent::SubscriptionMatched(s) => listener.on_subscription_matched(&reader, s),
674            ReaderEvent::LivelinessChanged(s) => listener.on_liveliness_changed(&reader, s),
675            ReaderEvent::RequestedDeadlineMissed(s) => {
676                listener.on_requested_deadline_missed(&reader, s)
677            }
678            ReaderEvent::RequestedIncompatibleQos(s) => {
679                listener.on_requested_incompatible_qos(&reader, s)
680            }
681            ReaderEvent::SampleRejected(s) => listener.on_sample_rejected(&reader, s),
682            ReaderEvent::SampleLost(s) => listener.on_sample_lost(&reader, s),
683        }
684    })
685}
686
687/// The reads and takes of a [`DataReader`] limited to a number of
688/// samples ([`DataReader::max_samples`]).
689pub struct MaxSamples<'a, T> {
690    reader: &'a DataReader<T>,
691    max: usize,
692}
693
694impl<T> std::fmt::Debug for MaxSamples<'_, T> {
695    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
696        f.debug_struct("MaxSamples")
697            .field("reader", self.reader)
698            .field("max", &self.max)
699            .finish()
700    }
701}
702
703impl<T> MaxSamples<'_, T> {
704    /// Like [`DataReader::take_with`].
705    pub fn take_with(&self, filter: StateFilter) -> Vec<Sample<T>> {
706        self.reader.select_max(filter, None, true, self.max)
707    }
708
709    /// Like [`DataReader::read_with`].
710    pub fn read_with(&self, filter: StateFilter) -> Vec<Sample<T>> {
711        self.reader.select_max(filter, None, false, self.max)
712    }
713
714    /// Like [`DataReader::take`].
715    pub fn take(&self) -> Vec<Sample<T>> {
716        self.take_with(StateFilter::ANY)
717    }
718
719    /// Like [`DataReader::read`].
720    pub fn read(&self) -> Vec<Sample<T>> {
721        self.read_with(StateFilter::ANY)
722    }
723
724    /// Like [`DataReader::take_instance`].
725    pub fn take_instance(&self, instance: InstanceHandle) -> Vec<Sample<T>> {
726        self.reader
727            .select_max(StateFilter::ANY, Some(instance), true, self.max)
728    }
729
730    /// Like [`DataReader::read_instance`].
731    pub fn read_instance(&self, instance: InstanceHandle) -> Vec<Sample<T>> {
732        self.reader
733            .select_max(StateFilter::ANY, Some(instance), false, self.max)
734    }
735
736    /// Like [`DataReader::take_next_instance`].
737    pub fn take_next_instance(
738        &self,
739        previous: Option<InstanceHandle>,
740        filter: StateFilter,
741    ) -> Vec<Sample<T>> {
742        self.reader.next_instance(previous, filter, true, self.max)
743    }
744
745    /// Like [`DataReader::read_next_instance`].
746    pub fn read_next_instance(
747        &self,
748        previous: Option<InstanceHandle>,
749        filter: StateFilter,
750    ) -> Vec<Sample<T>> {
751        self.reader.next_instance(previous, filter, false, self.max)
752    }
753
754    /// Like [`DataReader::take_w_condition`].
755    pub fn take_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
756        let f = self.reader.check_condition(condition)?;
757        Ok(self.reader.select_max(f, None, true, self.max))
758    }
759
760    /// Like [`DataReader::read_w_condition`].
761    pub fn read_w_condition(&self, condition: &ReadCondition) -> Result<Vec<Sample<T>>> {
762        let f = self.reader.check_condition(condition)?;
763        Ok(self.reader.select_max(f, None, false, self.max))
764    }
765}