1use alloc::string::{String, ToString};
5
6use crate::channel::{self, Publisher, Subscribable, Subscriber};
7use crate::pod::Pod;
8use hashbrown::HashMap;
9use spin::Mutex;
10
11pub struct Photon<T: Pod> {
24 topics: Mutex<HashMap<String, TopicEntry<T>>>,
25 default_capacity: usize,
26}
27
28struct TopicEntry<T: Pod> {
29 subscribable: Subscribable<T>,
30 publisher: Option<Publisher<T>>,
31}
32
33impl<T: Pod> Photon<T> {
34 pub fn new(capacity: usize) -> Self {
36 Photon {
37 topics: Mutex::new(HashMap::new()),
38 default_capacity: capacity,
39 }
40 }
41
42 pub fn publisher(&self, topic: &str) -> Publisher<T> {
47 let mut topics = self.topics.lock();
48 if !topics.contains_key(topic) {
49 topics.insert(topic.to_string(), Self::make_entry(self.default_capacity));
50 }
51 let entry = topics.get_mut(topic).unwrap();
52 entry
53 .publisher
54 .take()
55 .unwrap_or_else(|| panic!("publisher already taken for topic '{}'", topic))
56 }
57
58 pub fn try_publisher(&self, topic: &str) -> Option<Publisher<T>> {
61 let mut topics = self.topics.lock();
62 if !topics.contains_key(topic) {
63 topics.insert(topic.to_string(), Self::make_entry(self.default_capacity));
64 }
65 let entry = topics.get_mut(topic).unwrap();
66 entry.publisher.take()
67 }
68
69 pub fn subscribe(&self, topic: &str) -> Subscriber<T> {
71 let mut topics = self.topics.lock();
72 if !topics.contains_key(topic) {
73 topics.insert(topic.to_string(), Self::make_entry(self.default_capacity));
74 }
75 let entry = topics.get_mut(topic).unwrap();
76 entry.subscribable.subscribe()
77 }
78
79 pub fn subscribable(&self, topic: &str) -> Subscribable<T> {
81 let mut topics = self.topics.lock();
82 if !topics.contains_key(topic) {
83 topics.insert(topic.to_string(), Self::make_entry(self.default_capacity));
84 }
85 let entry = topics.get_mut(topic).unwrap();
86 entry.subscribable.clone()
87 }
88
89 fn make_entry(capacity: usize) -> TopicEntry<T> {
90 let (pub_, sub_) = channel::channel(capacity);
91 TopicEntry {
92 subscribable: sub_,
93 publisher: Some(pub_),
94 }
95 }
96}