use crate::tcb::{TaskControlBlock, TaskState};
use core::ptr;
pub unsafe fn insert_after(current: *mut TaskControlBlock, node: *mut TaskControlBlock) {
debug_assert!(!node.is_null());
if current.is_null() {
(*node).next = node;
(*node).prev = node;
return;
}
let after = (*current).next;
debug_assert!(
!after.is_null(),
"ring invariant: linked node has a successor"
);
(*node).prev = current;
(*node).next = after;
(*current).next = node;
(*after).prev = node;
}
pub unsafe fn unlink(node: *mut TaskControlBlock) -> *mut TaskControlBlock {
debug_assert!(!node.is_null());
let next = (*node).next;
let prev = (*node).prev;
if next == node {
(*node).next = ptr::null_mut();
(*node).prev = ptr::null_mut();
return ptr::null_mut();
}
debug_assert!(!next.is_null() && !prev.is_null());
(*prev).next = next;
(*next).prev = prev;
(*node).next = ptr::null_mut();
(*node).prev = ptr::null_mut();
next
}
#[inline]
fn not_runnable(state: TaskState) -> bool {
matches!(state, TaskState::Dead | TaskState::Blocked)
}
pub unsafe fn first_runnable_from(from: *mut TaskControlBlock) -> *mut TaskControlBlock {
if from.is_null() || !not_runnable((*from).state) {
return from;
}
next_runnable(from)
}
pub unsafe fn next_runnable(from: *mut TaskControlBlock) -> *mut TaskControlBlock {
if from.is_null() {
return ptr::null_mut();
}
let mut p = (*from).next;
while !p.is_null() && not_runnable((*p).state) {
p = (*p).next;
if p == from {
return if not_runnable((*from).state) {
ptr::null_mut()
} else {
from
};
}
}
if p.is_null() {
return ptr::null_mut();
}
p
}
pub unsafe fn len(any: *mut TaskControlBlock) -> usize {
if any.is_null() {
return 0;
}
let mut n = 1usize;
let mut p = (*any).next;
while p != any && !p.is_null() {
n += 1;
p = (*p).next;
}
n
}
pub unsafe fn check(any: *mut TaskControlBlock) -> Result<usize, &'static str> {
if any.is_null() {
return Ok(0);
}
if (*any).next.is_null() && (*any).prev.is_null() {
return Ok(0);
}
if (*any).prev.is_null() || (*any).next.is_null() {
return Err("half-linked node: exactly one of next/prev is null");
}
let mut n = 1usize;
let mut p = (*any).next;
let mut guard = 0usize;
while p != any {
if p.is_null() {
return Err("ring not circular (hit null)");
}
if (*p).prev != (if n == 0 { any } else { prev_of(p, any) }) {
return Err("ring not doubly linked (prev mismatch)");
}
n += 1;
p = (*p).next;
guard += 1;
if guard > 1_000_000 {
return Err("ring walk did not terminate");
}
}
if (*any).prev != prev_of(any, any) {
return Err("head prev does not point at tail");
}
Ok(n)
}
unsafe fn prev_of(p: *mut TaskControlBlock, any: *mut TaskControlBlock) -> *mut TaskControlBlock {
let mut q = p;
let mut guard = 0usize;
loop {
let prev = (*q).prev;
if prev.is_null() {
return ptr::null_mut();
}
if (*prev).next == p {
return prev;
}
q = prev;
guard += 1;
if guard > 1_000_000 || q == any {
return (*p).prev;
}
}
}