use crate::external::TaskBatch;
use crate::management::QueueCleanupProgress;
use intrusive_collections::linked_list::LinkOps;
use intrusive_collections::{Adapter, DefaultPointerOps, LinkedList, LinkedListLink, UnsafeRef};
use pi_async_task::definitions::TaskOwnerId;
use pi_async_task::{QueueEntry, Runnable, TaskThread};
use pi_result::RawResult as Result;
use std::marker::PhantomData;
use std::ptr::NonNull;
use std::rc::Rc;
pub trait InternalTaskQueue {
fn try_push_internal_front(&mut self, task: Runnable) -> Result<(), QueuePushError>;
fn try_push_internal_back(&mut self, task: Runnable) -> Result<(), QueuePushError>;
fn pop_internal_front(&mut self) -> Option<Runnable>;
fn internal_len(&self) -> usize;
fn internal_owner_id(&self) -> Option<TaskOwnerId>;
fn is_internal_closed(&self) -> bool;
fn clear_internal(&mut self) -> pi_result::Result<QueueCleanupProgress>;
fn close_internal(&mut self) -> pi_result::Result<QueueCleanupProgress>;
}
pub struct TaskQueue<const ALLOW_UNBOUND: bool = false> {
owner: TaskOwnerId,
entries: LinkedList<QueueAdapter>,
count: usize,
closed: bool,
local: PhantomData<Rc<()>>,
}
pub struct QueuePushError {
pub task: Runnable,
pub cause: QueuePushErrorKind,
}
pub struct BatchPushError {
pub batch: TaskBatch,
pub cause: QueuePushErrorKind,
}
struct QueueAdapter {
links: LinkOps,
pointers: DefaultPointerOps<UnsafeRef<QueueEntry>>,
}
unsafe impl Adapter for QueueAdapter {
type LinkOps = LinkOps;
type PointerOps = DefaultPointerOps<UnsafeRef<QueueEntry>>;
unsafe fn get_value(&self, link: NonNull<LinkedListLink>) -> *const QueueEntry {
unsafe { adapter_value_inner(self, link) }
}
unsafe fn get_link(&self, value: *const QueueEntry) -> NonNull<LinkedListLink> {
unsafe { adapter_link_inner(self, value) }
}
fn link_ops(&self) -> &Self::LinkOps {
adapter_ops_inner(self)
}
fn link_ops_mut(&mut self) -> &mut Self::LinkOps {
adapter_ops_mut_inner(self)
}
fn pointer_ops(&self) -> &Self::PointerOps {
adapter_pointer_ops_inner(self)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum QueuePushErrorKind {
Closed,
WrongOwner,
LinkMissing,
AlreadyLinked,
CountOverflow,
}
impl TaskQueue<false> {
pub fn new(owner: &TaskThread) -> Self {
queue_new_inner(owner)
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
pub fn owner_id(&self) -> TaskOwnerId {
queue_owner_inner(self)
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
pub fn len(&self) -> usize {
queue_len_inner(self)
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
pub fn is_empty(&self) -> bool {
queue_is_empty_inner(self)
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
pub fn push_front(&mut self, task: Runnable) -> Result<(), QueuePushError> {
self.try_push::<true>(task)
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
pub fn pop_front(&mut self) -> Option<Runnable> {
let node = queue_unlink_inner::<ALLOW_UNBOUND, true>(self)?;
Some(unsafe { take_for_queue::<ALLOW_UNBOUND>(node, self.owner) })
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
pub fn push_back(&mut self, task: Runnable) -> Result<(), QueuePushError> {
self.try_push::<false>(task)
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
pub fn pop_back(&mut self) -> Option<Runnable> {
let node = queue_unlink_inner::<ALLOW_UNBOUND, false>(self)?;
Some(unsafe { take_for_queue::<ALLOW_UNBOUND>(node, self.owner) })
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
pub fn append_batch(&mut self, mut batch: TaskBatch) -> Result<usize, BatchPushError> {
if self.closed {
return Err(BatchPushError { batch, cause: QueuePushErrorKind::Closed });
}
let count = match queue_append_count_inner(self, &batch) {
Ok(value) => value,
Err(cause) => return Err(BatchPushError { batch, cause }),
};
let length = batch.tasks.len();
for checked in 0..length {
let task = batch.tasks.pop_front().unwrap_or_else(|| std::process::abort());
match unsafe { store_for_queue::<ALLOW_UNBOUND>(task, self.owner) } {
Ok(node) => {
let task = unsafe { take_for_queue::<ALLOW_UNBOUND>(node, self.owner) };
batch.tasks.push_back(task);
}
Err(task) => {
batch.tasks.push_front(task);
batch.tasks.rotate_right(checked);
return Err(BatchPushError { batch, cause: QueuePushErrorKind::LinkMissing });
}
}
}
for task in batch.tasks {
let node = unsafe { store_for_queue::<ALLOW_UNBOUND>(task, self.owner) }
.unwrap_or_else(|_| std::process::abort());
unsafe { self.link_stored::<false>(node) };
}
self.count = count;
Ok(length)
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
pub fn drain(&mut self) -> TaskBatch {
let mut tasks = std::collections::VecDeque::with_capacity(self.count);
while let Some(task) = self.pop_front() {
tasks.push_back(task);
}
TaskBatch::from_tasks(tasks)
}
}
impl<const ALLOW_UNBOUND: bool> Drop for TaskQueue<ALLOW_UNBOUND> {
fn drop(&mut self) {
let mut remaining = Remaining { queue: self };
remaining.release();
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
pub fn clear(&mut self) -> pi_result::Result<QueueCleanupProgress> {
drop(self.drain());
Ok(QueueCleanupProgress::Complete)
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
pub fn close(&mut self) -> pi_result::Result<QueueCleanupProgress> {
self.closed = true;
self.clear()
}
}
impl<const ALLOW_UNBOUND: bool> TaskQueue<ALLOW_UNBOUND> {
fn try_push<const FRONT: bool>(&mut self, task: Runnable) -> Result<(), QueuePushError> {
if self.closed {
return Err(QueuePushError { task, cause: QueuePushErrorKind::Closed });
}
let count = match queue_push_count_inner::<ALLOW_UNBOUND, FRONT>(self, &task) {
Ok(count) => count,
Err(cause) => return Err(QueuePushError { task, cause }),
};
let node = unsafe { store_for_queue::<ALLOW_UNBOUND>(task, self.owner) }
.map_err(|task| QueuePushError { task, cause: QueuePushErrorKind::LinkMissing })?;
let mut rollback = UnlinkedTicket::<ALLOW_UNBOUND> {
node,
owner: self.owner,
armed: true,
};
unsafe { self.link_stored::<FRONT>(node) };
self.count = count;
rollback.armed = false;
Ok(())
}
unsafe fn link_stored<const FRONT: bool>(&mut self, node: NonNull<QueueEntry>) {
unsafe { queue_link_inner::<ALLOW_UNBOUND, FRONT>(self, node) };
}
}
struct UnlinkedTicket<const ALLOW_UNBOUND: bool> {
node: NonNull<QueueEntry>,
owner: TaskOwnerId,
armed: bool,
}
impl<const ALLOW_UNBOUND: bool> Drop for UnlinkedTicket<ALLOW_UNBOUND> {
fn drop(&mut self) {
if self.armed {
let link = unsafe { QueueEntry::link_from_node(self.node) };
if !unsafe { link.as_ref() }.is_linked() {
drop(unsafe { take_for_queue::<ALLOW_UNBOUND>(self.node, self.owner) });
}
}
}
}
struct Remaining<'queue, const ALLOW_UNBOUND: bool> {
queue: &'queue mut TaskQueue<ALLOW_UNBOUND>,
}
impl<const ALLOW_UNBOUND: bool> Remaining<'_, ALLOW_UNBOUND> {
fn release(&mut self) {
while let Some(task) = self.queue.pop_front() {
drop(task);
}
}
}
impl<const ALLOW_UNBOUND: bool> Drop for Remaining<'_, ALLOW_UNBOUND> {
fn drop(&mut self) {
self.release();
}
}
#[inline(always)]
unsafe fn store_for_queue<const ALLOW_UNBOUND: bool>(
task: Runnable,
owner: TaskOwnerId,
) -> Result<NonNull<QueueEntry>, Runnable> {
if ALLOW_UNBOUND {
unsafe { QueueEntry::store_with_unbound(task, owner) }
} else {
unsafe { QueueEntry::store(task, owner) }
}
}
#[inline(always)]
unsafe fn take_for_queue<const ALLOW_UNBOUND: bool>(
node: NonNull<QueueEntry>,
owner: TaskOwnerId,
) -> Runnable {
if ALLOW_UNBOUND {
unsafe { QueueEntry::take_with_unbound(node, owner) }
} else {
unsafe { QueueEntry::take(node, owner) }
}
}
impl TaskQueue<true> {
pub fn new_with_unbound(owner: &TaskThread) -> Self {
queue_new_with_unbound_inner(owner)
}
}
impl<const ALLOW_UNBOUND: bool> InternalTaskQueue for TaskQueue<ALLOW_UNBOUND> {
fn try_push_internal_front(&mut self, task: Runnable) -> Result<(), QueuePushError> {
self.push_front(task)
}
fn try_push_internal_back(&mut self, task: Runnable) -> Result<(), QueuePushError> {
self.push_back(task)
}
fn pop_internal_front(&mut self) -> Option<Runnable> {
self.pop_front()
}
fn internal_len(&self) -> usize {
self.len()
}
fn internal_owner_id(&self) -> Option<TaskOwnerId> {
Some(self.owner_id())
}
fn is_internal_closed(&self) -> bool {
self.closed
}
fn clear_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
self.clear()
}
fn close_internal(&mut self) -> pi_result::Result<QueueCleanupProgress> {
self.close()
}
}
include!("local_inner.rs");