1use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::{Arc, Condvar, Mutex, Weak};
7use std::time::{Duration, Instant};
8
9use rustorb_rtps::Guid;
10
11use crate::error::{Error, Result};
12use crate::instance::StateFilter;
13use crate::participant::Shared;
14use crate::status::StatusMask;
15
16#[derive(Debug, Default)]
19pub(crate) struct Waker {
20 generation: Mutex<u64>,
23 cv: Condvar,
24}
25
26impl Waker {
27 pub(crate) fn wake(&self) {
28 *self.generation.lock().unwrap_or_else(|e| e.into_inner()) += 1;
29 self.cv.notify_all();
30 }
31
32 fn generation(&self) -> u64 {
33 *self.generation.lock().unwrap_or_else(|e| e.into_inner())
34 }
35
36 fn wait(&self, generation: u64, deadline: Option<Instant>) {
38 let mut g = self.generation.lock().unwrap_or_else(|e| e.into_inner());
39 while *g == generation {
40 match deadline {
41 None => g = self.cv.wait(g).unwrap_or_else(|e| e.into_inner()),
42 Some(d) => {
43 let now = Instant::now();
44 if now >= d {
45 return;
46 }
47 g = match self.cv.wait_timeout(g, d - now) {
48 Ok((g, _)) => g,
49 Err(e) => e.into_inner().0,
50 };
51 }
52 }
53 }
54 }
55}
56
57fn register(list: &Mutex<Vec<Weak<Waker>>>, waker: &Arc<Waker>) {
59 let mut l = list.lock().unwrap_or_else(|e| e.into_inner());
60 l.retain(|w| w.strong_count() > 0);
61 if !l.iter().any(|w| w.as_ptr() == Arc::as_ptr(waker)) {
62 l.push(Arc::downgrade(waker));
63 }
64}
65
66#[derive(Debug, Default)]
67struct GuardState {
68 trigger: Mutex<bool>,
69 waitsets: Mutex<Vec<Weak<Waker>>>,
70}
71
72#[derive(Clone, Debug, Default)]
77pub struct GuardCondition {
78 state: Arc<GuardState>,
79}
80
81impl GuardCondition {
82 pub fn new() -> Self {
84 Self::default()
85 }
86
87 pub fn set_trigger_value(&self, value: bool) {
90 *self.state.trigger.lock().unwrap_or_else(|e| e.into_inner()) = value;
91 let l = self
92 .state
93 .waitsets
94 .lock()
95 .unwrap_or_else(|e| e.into_inner());
96 for w in l.iter().filter_map(Weak::upgrade) {
97 w.wake();
98 }
99 }
100
101 pub fn trigger_value(&self) -> bool {
103 *self.state.trigger.lock().unwrap_or_else(|e| e.into_inner())
104 }
105}
106
107#[derive(Clone)]
115pub struct StatusCondition {
116 shared: Arc<Shared>,
117 entity: Guid,
118}
119
120impl std::fmt::Debug for StatusCondition {
121 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122 f.debug_struct("StatusCondition")
123 .field("entity", &self.entity)
124 .finish()
125 }
126}
127
128impl PartialEq for StatusCondition {
129 fn eq(&self, other: &Self) -> bool {
130 Arc::ptr_eq(&self.shared, &other.shared) && self.entity == other.entity
131 }
132}
133
134impl StatusCondition {
135 pub(crate) fn new(shared: Arc<Shared>, entity: Guid) -> Self {
136 StatusCondition { shared, entity }
137 }
138
139 pub fn entity(&self) -> Guid {
141 self.entity
142 }
143
144 pub fn set_enabled_statuses(&self, mask: StatusMask) {
147 {
148 let mut g = self.shared.lock_any();
149 if let Some(w) = g.writers.get_mut(&self.entity) {
150 w.enabled = mask;
151 } else if let Some(r) = g.readers.get_mut(&self.entity) {
152 r.enabled = mask;
153 }
154 }
155 self.shared.wake_waitsets();
156 }
157
158 pub fn enabled_statuses(&self) -> StatusMask {
161 let g = self.shared.lock_any();
162 if let Some(w) = g.writers.get(&self.entity) {
163 w.enabled
164 } else if let Some(r) = g.readers.get(&self.entity) {
165 r.enabled
166 } else {
167 StatusMask::NONE
168 }
169 }
170
171 pub fn trigger_value(&self) -> bool {
173 let g = self.shared.lock_any();
174 if let Some(w) = g.writers.get(&self.entity) {
175 w.changes.intersects(w.enabled)
176 } else if let Some(r) = g.readers.get(&self.entity) {
177 r.changes.intersects(r.enabled)
178 } else {
179 false
180 }
181 }
182}
183
184#[derive(Clone)]
192pub struct ReadCondition {
193 shared: Arc<Shared>,
194 reader: Guid,
195 filter: StateFilter,
196 id: Arc<()>,
198}
199
200impl std::fmt::Debug for ReadCondition {
201 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202 f.debug_struct("ReadCondition")
203 .field("reader", &self.reader)
204 .field("filter", &self.filter)
205 .finish()
206 }
207}
208
209impl PartialEq for ReadCondition {
210 fn eq(&self, other: &Self) -> bool {
211 Arc::ptr_eq(&self.id, &other.id)
212 }
213}
214
215impl ReadCondition {
216 pub(crate) fn new(shared: Arc<Shared>, reader: Guid, filter: StateFilter) -> Self {
217 ReadCondition {
218 shared,
219 reader,
220 filter,
221 id: Arc::new(()),
222 }
223 }
224
225 pub fn reader(&self) -> Guid {
227 self.reader
228 }
229
230 pub fn filter(&self) -> StateFilter {
233 self.filter
234 }
235
236 pub fn trigger_value(&self) -> bool {
238 let g = self.shared.lock_any();
239 g.readers
240 .get(&self.reader)
241 .is_some_and(|r| r.samples.has_matching(self.filter))
242 }
243}
244
245#[derive(Clone, Debug, PartialEq)]
248pub enum Condition {
249 Guard(GuardCondition),
251 Status(StatusCondition),
253 Read(ReadCondition),
255}
256
257impl PartialEq for GuardCondition {
258 fn eq(&self, other: &Self) -> bool {
259 Arc::ptr_eq(&self.state, &other.state)
260 }
261}
262
263impl Condition {
264 pub fn trigger_value(&self) -> bool {
266 match self {
267 Condition::Guard(c) => c.trigger_value(),
268 Condition::Status(c) => c.trigger_value(),
269 Condition::Read(c) => c.trigger_value(),
270 }
271 }
272
273 fn register(&self, waker: &Arc<Waker>) {
275 match self {
276 Condition::Guard(c) => register(&c.state.waitsets, waker),
277 Condition::Status(c) => register(&c.shared.waitsets, waker),
278 Condition::Read(c) => register(&c.shared.waitsets, waker),
279 }
280 }
281}
282
283macro_rules! from_condition {
284 ($t:ident, $v:ident) => {
285 impl From<$t> for Condition {
286 fn from(c: $t) -> Condition {
287 Condition::$v(c)
288 }
289 }
290
291 impl From<&$t> for Condition {
292 fn from(c: &$t) -> Condition {
293 Condition::$v(c.clone())
294 }
295 }
296
297 impl PartialEq<$t> for Condition {
298 fn eq(&self, other: &$t) -> bool {
299 matches!(self, Condition::$v(c) if c == other)
300 }
301 }
302 };
303}
304
305from_condition!(GuardCondition, Guard);
306from_condition!(StatusCondition, Status);
307from_condition!(ReadCondition, Read);
308
309#[derive(Debug, Default)]
340pub struct WaitSet {
341 waker: Arc<Waker>,
342 conditions: Mutex<Vec<Condition>>,
343 waiting: AtomicBool,
344}
345
346struct Waiting<'a>(&'a AtomicBool);
348
349impl Drop for Waiting<'_> {
350 fn drop(&mut self) {
351 self.0.store(false, Ordering::Release);
352 }
353}
354
355impl WaitSet {
356 pub fn new() -> Self {
358 Self::default()
359 }
360
361 fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Condition>> {
362 self.conditions.lock().unwrap_or_else(|e| e.into_inner())
363 }
364
365 pub fn attach_condition(&self, condition: impl Into<Condition>) -> Result<()> {
369 let c = condition.into();
370 {
371 let mut l = self.lock();
372 if l.contains(&c) {
373 return Ok(());
374 }
375 c.register(&self.waker);
376 l.push(c);
377 }
378 self.waker.wake();
379 Ok(())
380 }
381
382 pub fn detach_condition(&self, condition: impl Into<Condition>) -> Result<()> {
385 let c = condition.into();
386 let mut l = self.lock();
387 let Some(i) = l.iter().position(|x| *x == c) else {
388 return Err(Error::PreconditionNotMet);
389 };
390 l.remove(i);
391 Ok(())
392 }
393
394 pub fn conditions(&self) -> Vec<Condition> {
396 self.lock().clone()
397 }
398
399 pub fn wait(&self, timeout: Duration) -> Result<Vec<Condition>> {
406 if self.waiting.swap(true, Ordering::AcqRel) {
407 return Err(Error::PreconditionNotMet);
408 }
409 let _waiting = Waiting(&self.waiting);
410 let deadline = Instant::now().checked_add(timeout);
411 loop {
412 let generation = self.waker.generation();
415 let active: Vec<Condition> = self
416 .conditions()
417 .into_iter()
418 .filter(Condition::trigger_value)
419 .collect();
420 if !active.is_empty() {
421 return Ok(active);
422 }
423 if deadline.is_some_and(|d| Instant::now() >= d) {
424 return Err(Error::Timeout);
425 }
426 self.waker.wait(generation, deadline);
427 }
428 }
429}