use std::cmp::Ordering;
use std::panic::{self, AssertUnwindSafe};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::thread::JoinHandle;
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WebPWorkerStatus(pub u32);
impl WebPWorkerStatus {
pub const NOT_OK: Self = Self(0);
pub const OK: Self = Self(1);
pub const WORK: Self = Self(2);
}
pub type WebPWorkerHook<D1, D2> = fn(&mut D1, &mut D2) -> bool;
struct Job<D1, D2> {
hook: WebPWorkerHook<D1, D2>,
data1: D1,
data2: D2,
}
struct State<D1, D2> {
status: WebPWorkerStatus,
had_error: bool,
job: Option<Job<D1, D2>>,
}
struct Shared<D1, D2> {
state: Mutex<State<D1, D2>>,
changed: Condvar,
}
impl<D1, D2> Shared<D1, D2> {
fn lock(&self) -> MutexGuard<'_, State<D1, D2>> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
fn wait<'a>(&self, guard: MutexGuard<'a, State<D1, D2>>) -> MutexGuard<'a, State<D1, D2>> {
self.changed
.wait(guard)
.unwrap_or_else(PoisonError::into_inner)
}
}
fn return_job<D1, D2>(job: &mut Option<Job<D1, D2>>, state: &mut State<D1, D2>) {
if let Some(returned) = state.job.take() {
*job = Some(returned);
}
}
pub struct WebPWorker<D1, D2> {
job: Option<Job<D1, D2>>,
shared: Arc<Shared<D1, D2>>,
thread: Option<JoinHandle<()>>,
working: bool,
}
impl<D1, D2> Default for WebPWorker<D1, D2> {
fn default() -> Self {
Self::init()
}
}
impl<D1, D2> WebPWorker<D1, D2> {
#[must_use]
pub fn init() -> Self {
Self {
job: None,
shared: Arc::new(Shared {
state: Mutex::new(State {
status: WebPWorkerStatus::NOT_OK,
had_error: false,
job: None,
}),
changed: Condvar::new(),
}),
thread: None,
working: false,
}
}
pub fn set_job(&mut self, hook: WebPWorkerHook<D1, D2>, data1: D1, data2: D2) {
assert!(
!self.working,
"the job of a working worker belongs to its thread until sync"
);
self.job = Some(Job { hook, data1, data2 });
}
#[must_use]
pub fn job_data(&self) -> Option<(&D1, &D2)> {
self.job.as_ref().map(|job| (&job.data1, &job.data2))
}
pub fn job_data_mut(&mut self) -> Option<(&mut D1, &mut D2)> {
self.job
.as_mut()
.map(|job| (&mut job.data1, &mut job.data2))
}
#[must_use]
pub fn status(&self) -> WebPWorkerStatus {
self.shared.lock().status
}
#[must_use]
pub fn had_error(&self) -> bool {
self.shared.lock().had_error
}
pub fn execute(&mut self) {
if let Some(job) = self.job.as_mut()
&& !(job.hook)(&mut job.data1, &mut job.data2)
{
self.shared.lock().had_error = true;
}
}
fn change_state(&mut self, new_status: WebPWorkerStatus) {
if self.thread.is_none() {
return;
}
let mut state = self.shared.lock();
if state.status >= WebPWorkerStatus::OK {
while state.status != WebPWorkerStatus::OK {
state = self.shared.wait(state);
}
if new_status != WebPWorkerStatus::OK {
state.status = new_status;
drop(state);
self.shared.changed.notify_all();
}
}
}
pub fn launch(&mut self) {
if self.thread.is_none() {
return;
}
let mut state = self.shared.lock();
if state.status >= WebPWorkerStatus::OK {
while state.status != WebPWorkerStatus::OK {
state = self.shared.wait(state);
}
return_job(&mut self.job, &mut state);
state.status = WebPWorkerStatus::WORK;
state.job = self.job.take();
self.working = true;
drop(state);
self.shared.changed.notify_all();
}
}
#[must_use]
pub fn sync(&mut self) -> bool {
self.change_state(WebPWorkerStatus::OK);
let mut state = self.shared.lock();
debug_assert!(state.status <= WebPWorkerStatus::OK);
return_job(&mut self.job, &mut state);
self.working = false;
!state.had_error
}
pub fn end(&mut self) {
if self.thread.is_none() {
return;
}
self.change_state(WebPWorkerStatus::NOT_OK);
if let Some(handle) = self.thread.take() {
let _ = handle.join();
}
let mut state = self.shared.lock();
return_job(&mut self.job, &mut state);
self.working = false;
}
}
impl<D1: Send + 'static, D2: Send + 'static> WebPWorker<D1, D2> {
#[must_use]
pub fn reset(&mut self) -> bool {
let mut state = self.shared.lock();
state.had_error = false;
match state.status.cmp(&WebPWorkerStatus::OK) {
Ordering::Less => {
state.status = WebPWorkerStatus::OK;
let shared = Arc::clone(&self.shared);
if let Ok(handle) = std::thread::Builder::new().spawn(move || thread_loop(&shared))
{
self.thread = Some(handle);
true
} else {
state.status = WebPWorkerStatus::NOT_OK;
false
}
}
Ordering::Greater => {
drop(state);
self.sync()
}
Ordering::Equal => true,
}
}
}
impl<D1, D2> Drop for WebPWorker<D1, D2> {
fn drop(&mut self) {
self.end();
}
}
fn run_job<D1, D2>(state: &mut State<D1, D2>) {
let State { had_error, job, .. } = state;
let Some(job) = job.as_mut() else {
return;
};
let ok = panic::catch_unwind(AssertUnwindSafe(|| {
(job.hook)(&mut job.data1, &mut job.data2)
}))
.unwrap_or(false);
if !ok {
*had_error = true;
}
}
fn thread_loop<D1, D2>(shared: &Shared<D1, D2>) {
let mut done = false;
while !done {
let mut state = shared.lock();
while state.status == WebPWorkerStatus::OK {
state = shared.wait(state);
}
if state.status == WebPWorkerStatus::WORK {
run_job(&mut state);
state.status = WebPWorkerStatus::OK;
} else if state.status == WebPWorkerStatus::NOT_OK {
done = true;
}
drop(state);
shared.changed.notify_all();
}
}