use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, Weak};
use std::time::{Duration, Instant};
use rustorb_rtps::Guid;
use crate::error::{Error, Result};
use crate::instance::StateFilter;
use crate::participant::Shared;
use crate::status::StatusMask;
#[derive(Debug, Default)]
pub(crate) struct Waker {
generation: Mutex<u64>,
cv: Condvar,
}
impl Waker {
pub(crate) fn wake(&self) {
*self.generation.lock().unwrap_or_else(|e| e.into_inner()) += 1;
self.cv.notify_all();
}
fn generation(&self) -> u64 {
*self.generation.lock().unwrap_or_else(|e| e.into_inner())
}
fn wait(&self, generation: u64, deadline: Option<Instant>) {
let mut g = self.generation.lock().unwrap_or_else(|e| e.into_inner());
while *g == generation {
match deadline {
None => g = self.cv.wait(g).unwrap_or_else(|e| e.into_inner()),
Some(d) => {
let now = Instant::now();
if now >= d {
return;
}
g = match self.cv.wait_timeout(g, d - now) {
Ok((g, _)) => g,
Err(e) => e.into_inner().0,
};
}
}
}
}
}
fn register(list: &Mutex<Vec<Weak<Waker>>>, waker: &Arc<Waker>) {
let mut l = list.lock().unwrap_or_else(|e| e.into_inner());
l.retain(|w| w.strong_count() > 0);
if !l.iter().any(|w| w.as_ptr() == Arc::as_ptr(waker)) {
l.push(Arc::downgrade(waker));
}
}
#[derive(Debug, Default)]
struct GuardState {
trigger: Mutex<bool>,
waitsets: Mutex<Vec<Weak<Waker>>>,
}
#[derive(Clone, Debug, Default)]
pub struct GuardCondition {
state: Arc<GuardState>,
}
impl GuardCondition {
pub fn new() -> Self {
Self::default()
}
pub fn set_trigger_value(&self, value: bool) {
*self.state.trigger.lock().unwrap_or_else(|e| e.into_inner()) = value;
let l = self
.state
.waitsets
.lock()
.unwrap_or_else(|e| e.into_inner());
for w in l.iter().filter_map(Weak::upgrade) {
w.wake();
}
}
pub fn trigger_value(&self) -> bool {
*self.state.trigger.lock().unwrap_or_else(|e| e.into_inner())
}
}
#[derive(Clone)]
pub struct StatusCondition {
shared: Arc<Shared>,
entity: Guid,
}
impl std::fmt::Debug for StatusCondition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StatusCondition")
.field("entity", &self.entity)
.finish()
}
}
impl PartialEq for StatusCondition {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.shared, &other.shared) && self.entity == other.entity
}
}
impl StatusCondition {
pub(crate) fn new(shared: Arc<Shared>, entity: Guid) -> Self {
StatusCondition { shared, entity }
}
pub fn entity(&self) -> Guid {
self.entity
}
pub fn set_enabled_statuses(&self, mask: StatusMask) {
{
let mut g = self.shared.lock_any();
if let Some(w) = g.writers.get_mut(&self.entity) {
w.enabled = mask;
} else if let Some(r) = g.readers.get_mut(&self.entity) {
r.enabled = mask;
}
}
self.shared.wake_waitsets();
}
pub fn enabled_statuses(&self) -> StatusMask {
let g = self.shared.lock_any();
if let Some(w) = g.writers.get(&self.entity) {
w.enabled
} else if let Some(r) = g.readers.get(&self.entity) {
r.enabled
} else {
StatusMask::NONE
}
}
pub fn trigger_value(&self) -> bool {
let g = self.shared.lock_any();
if let Some(w) = g.writers.get(&self.entity) {
w.changes.intersects(w.enabled)
} else if let Some(r) = g.readers.get(&self.entity) {
r.changes.intersects(r.enabled)
} else {
false
}
}
}
#[derive(Clone)]
pub struct ReadCondition {
shared: Arc<Shared>,
reader: Guid,
filter: StateFilter,
id: Arc<()>,
}
impl std::fmt::Debug for ReadCondition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ReadCondition")
.field("reader", &self.reader)
.field("filter", &self.filter)
.finish()
}
}
impl PartialEq for ReadCondition {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.id, &other.id)
}
}
impl ReadCondition {
pub(crate) fn new(shared: Arc<Shared>, reader: Guid, filter: StateFilter) -> Self {
ReadCondition {
shared,
reader,
filter,
id: Arc::new(()),
}
}
pub fn reader(&self) -> Guid {
self.reader
}
pub fn filter(&self) -> StateFilter {
self.filter
}
pub fn trigger_value(&self) -> bool {
let g = self.shared.lock_any();
g.readers
.get(&self.reader)
.is_some_and(|r| r.samples.has_matching(self.filter))
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Condition {
Guard(GuardCondition),
Status(StatusCondition),
Read(ReadCondition),
}
impl PartialEq for GuardCondition {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.state, &other.state)
}
}
impl Condition {
pub fn trigger_value(&self) -> bool {
match self {
Condition::Guard(c) => c.trigger_value(),
Condition::Status(c) => c.trigger_value(),
Condition::Read(c) => c.trigger_value(),
}
}
fn register(&self, waker: &Arc<Waker>) {
match self {
Condition::Guard(c) => register(&c.state.waitsets, waker),
Condition::Status(c) => register(&c.shared.waitsets, waker),
Condition::Read(c) => register(&c.shared.waitsets, waker),
}
}
}
macro_rules! from_condition {
($t:ident, $v:ident) => {
impl From<$t> for Condition {
fn from(c: $t) -> Condition {
Condition::$v(c)
}
}
impl From<&$t> for Condition {
fn from(c: &$t) -> Condition {
Condition::$v(c.clone())
}
}
impl PartialEq<$t> for Condition {
fn eq(&self, other: &$t) -> bool {
matches!(self, Condition::$v(c) if c == other)
}
}
};
}
from_condition!(GuardCondition, Guard);
from_condition!(StatusCondition, Status);
from_condition!(ReadCondition, Read);
#[derive(Debug, Default)]
pub struct WaitSet {
waker: Arc<Waker>,
conditions: Mutex<Vec<Condition>>,
waiting: AtomicBool,
}
struct Waiting<'a>(&'a AtomicBool);
impl Drop for Waiting<'_> {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
impl WaitSet {
pub fn new() -> Self {
Self::default()
}
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Condition>> {
self.conditions.lock().unwrap_or_else(|e| e.into_inner())
}
pub fn attach_condition(&self, condition: impl Into<Condition>) -> Result<()> {
let c = condition.into();
{
let mut l = self.lock();
if l.contains(&c) {
return Ok(());
}
c.register(&self.waker);
l.push(c);
}
self.waker.wake();
Ok(())
}
pub fn detach_condition(&self, condition: impl Into<Condition>) -> Result<()> {
let c = condition.into();
let mut l = self.lock();
let Some(i) = l.iter().position(|x| *x == c) else {
return Err(Error::PreconditionNotMet);
};
l.remove(i);
Ok(())
}
pub fn conditions(&self) -> Vec<Condition> {
self.lock().clone()
}
pub fn wait(&self, timeout: Duration) -> Result<Vec<Condition>> {
if self.waiting.swap(true, Ordering::AcqRel) {
return Err(Error::PreconditionNotMet);
}
let _waiting = Waiting(&self.waiting);
let deadline = Instant::now().checked_add(timeout);
loop {
let generation = self.waker.generation();
let active: Vec<Condition> = self
.conditions()
.into_iter()
.filter(Condition::trigger_value)
.collect();
if !active.is_empty() {
return Ok(active);
}
if deadline.is_some_and(|d| Instant::now() >= d) {
return Err(Error::Timeout);
}
self.waker.wait(generation, deadline);
}
}
}