rosrust/api/slave/
publications.rs

1use crate::api::error;
2use crate::tcpros::{Publisher, PublisherStream, Topic};
3use crate::util::FAILED_TO_LOCK;
4use crate::{Message, RawMessageDescription};
5use std::collections::HashMap;
6use std::iter::FromIterator;
7use std::sync::{Arc, Mutex};
8
9#[derive(Clone, Default)]
10pub struct PublicationsTracker {
11    mapping: Arc<Mutex<HashMap<String, Publisher>>>,
12}
13
14impl PublicationsTracker {
15    #[inline]
16    pub fn get_topic_names<T: FromIterator<String>>(&self) -> T {
17        self.mapping
18            .lock()
19            .expect(FAILED_TO_LOCK)
20            .keys()
21            .cloned()
22            .collect()
23    }
24
25    #[inline]
26    pub fn get_topics<T: FromIterator<Topic>>(&self) -> T {
27        self.mapping
28            .lock()
29            .expect(FAILED_TO_LOCK)
30            .values()
31            .map(Publisher::get_topic)
32            .cloned()
33            .collect()
34    }
35
36    #[inline]
37    pub fn get_port(&self, topic: &str) -> Option<i32> {
38        self.mapping
39            .lock()
40            .expect(FAILED_TO_LOCK)
41            .get(topic)
42            .map(|publisher| i32::from(publisher.port))
43    }
44
45    pub fn add<T: Message>(
46        &self,
47        hostname: &str,
48        topic: &str,
49        queue_size: usize,
50        caller_id: &str,
51        message_description: RawMessageDescription,
52    ) -> error::tcpros::Result<PublisherStream<T>> {
53        use std::collections::hash_map::Entry;
54        match self
55            .mapping
56            .lock()
57            .expect(FAILED_TO_LOCK)
58            .entry(String::from(topic))
59        {
60            Entry::Occupied(publisher_entry) => publisher_entry
61                .get()
62                .stream(queue_size, message_description),
63            Entry::Vacant(entry) => {
64                let publisher = Publisher::new(
65                    format!("{}:0", hostname).as_str(),
66                    topic,
67                    queue_size,
68                    caller_id,
69                    message_description.clone(),
70                )?;
71                entry
72                    .insert(publisher)
73                    .stream(queue_size, message_description)
74            }
75        }
76    }
77
78    #[inline]
79    pub fn remove(&self, topic: &str) {
80        self.mapping.lock().expect(FAILED_TO_LOCK).remove(topic);
81    }
82}