use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
#[cfg(test)]
mod tests;
#[must_use]
pub fn line_queue(most: usize) -> (LineQueue, Lines) {
let shared = Arc::new(Shared {
most: most.max(1),
state: Mutex::new(State::default()),
changed: Condvar::new(),
});
(LineQueue(Arc::clone(&shared)), Lines(shared))
}
#[derive(Debug)]
struct Shared {
most: usize,
state: Mutex<State>,
changed: Condvar,
}
#[derive(Debug, Default)]
struct State {
lines: VecDeque<Vec<u8>>,
lost: Option<Vec<u8>>,
stopping: bool,
drain_until: Option<Instant>,
ended: bool,
abandoned: bool,
}
#[derive(Clone)]
pub struct LineQueue(Arc<Shared>);
impl fmt::Debug for LineQueue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LineQueue")
.field("most", &self.0.most)
.finish_non_exhaustive()
}
}
impl LineQueue {
pub(crate) fn push(&self, line: Vec<u8>) -> bool {
let shared = &*self.0;
let mut state = shared.lock();
while state.lines.len() >= shared.most && !state.stopping && !state.abandoned {
state = if let Some(deadline) = state.drain_until {
let Some(left) = deadline.checked_duration_since(Instant::now()) else {
break;
};
shared
.changed
.wait_timeout(state, left)
.unwrap_or_else(PoisonError::into_inner)
.0
} else {
shared
.changed
.wait(state)
.unwrap_or_else(PoisonError::into_inner)
};
}
if state.abandoned {
return false;
}
if state.lines.len() < shared.most {
state.lines.push_back(line);
state.lost = None;
shared.changed.notify_all();
} else {
state.lost = Some(line);
}
true
}
pub(crate) fn stopping(&self) {
self.0.lock().stopping = true;
self.0.changed.notify_all();
}
pub(crate) fn drain_until(&self, deadline: Instant) {
self.0.lock().drain_until = Some(deadline);
self.0.changed.notify_all();
}
pub(crate) fn end(&self) {
self.0.lock().ended = true;
self.0.changed.notify_all();
}
}
pub struct Lines(Arc<Shared>);
impl fmt::Debug for Lines {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Lines")
.field("most", &self.0.most)
.finish_non_exhaustive()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Silent;
impl fmt::Display for Silent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("no line arrived in time")
}
}
impl std::error::Error for Silent {}
impl Lines {
#[must_use]
pub fn recv(&self) -> Option<Vec<u8>> {
let shared = &*self.0;
let mut state = shared.lock();
while state.lines.is_empty() && !state.ended {
state = shared
.changed
.wait(state)
.unwrap_or_else(PoisonError::into_inner);
}
shared.take(&mut state)
}
pub fn recv_timeout(&self, timeout: Duration) -> Result<Option<Vec<u8>>, Silent> {
let shared = &*self.0;
let deadline = Instant::now().checked_add(timeout);
let mut state = shared.lock();
while state.lines.is_empty() && !state.ended {
let left = deadline.map_or(timeout, |deadline| {
deadline.saturating_duration_since(Instant::now())
});
if left.is_zero() {
return Err(Silent);
}
state = shared
.changed
.wait_timeout(state, left)
.unwrap_or_else(PoisonError::into_inner)
.0;
}
Ok(shared.take(&mut state))
}
#[must_use]
pub fn lost(&self) -> Option<Vec<u8>> {
let mut state = self.0.lock();
if state.ended { state.lost.take() } else { None }
}
}
impl Drop for Lines {
fn drop(&mut self) {
self.0.lock().abandoned = true;
self.0.changed.notify_all();
}
}
impl Shared {
fn take(&self, state: &mut State) -> Option<Vec<u8>> {
let line = state.lines.pop_front();
if line.is_some() {
self.changed.notify_all();
}
line
}
fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
}