#![allow(clippy::missing_errors_doc)]
use crate::sched::flynnel_ring::{FlynnelRing, PopResult, PushResult};
pub const DEFAULT_INJECTOR_CAPACITY: usize = 4096;
#[derive(Debug, PartialEq, Eq)]
pub enum InjectorSteal<T> {
Success(T),
Empty,
Retry,
}
pub struct Injector<T: Send> {
ring: FlynnelRing<T>,
}
impl<T: Send> Injector<T> {
#[inline]
pub fn new() -> Self {
Self::with_capacity(DEFAULT_INJECTOR_CAPACITY)
}
#[inline]
pub fn with_capacity(cap: usize) -> Self {
Self { ring: FlynnelRing::new(cap) }
}
#[inline]
pub fn push(&self, mut item: T) {
loop {
match self.ring.push(item) {
PushResult::Ok => return,
PushResult::Full(t) => {
item = t;
core::hint::spin_loop();
}
}
}
}
#[inline]
pub fn try_push(&self, item: T) -> Result<(), T> {
match self.ring.push(item) {
PushResult::Ok => Ok(()),
PushResult::Full(t) => Err(t),
}
}
#[inline]
pub fn steal(&self) -> InjectorSteal<T> {
match self.ring.pop() {
PopResult::Ok(t) => InjectorSteal::Success(t),
PopResult::Empty => InjectorSteal::Empty,
}
}
#[inline]
pub fn is_empty(&self) -> bool {
self.ring.is_empty()
}
#[inline]
pub fn len(&self) -> usize {
self.ring.len()
}
#[inline]
pub fn capacity(&self) -> usize {
self.ring.capacity()
}
}
impl<T: Send> Default for Injector<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Send> std::fmt::Debug for Injector<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Injector")
.field("capacity", &self.capacity())
.field("is_empty", &self.is_empty())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering as O};
use std::thread;
#[test]
fn push_then_steal_returns_item() {
let inj = Injector::<u32>::with_capacity(16);
inj.push(42);
match inj.steal() {
InjectorSteal::Success(v) => assert_eq!(v, 42),
other => panic!("expected Success(42), got {other:?}"),
}
}
#[test]
fn steal_empty_returns_empty() {
let inj = Injector::<u32>::with_capacity(8);
assert!(matches!(inj.steal(), InjectorSteal::Empty));
}
#[test]
fn try_push_returns_err_on_full() {
let inj = Injector::<u32>::with_capacity(2);
assert!(inj.try_push(1).is_ok());
assert!(inj.try_push(2).is_ok());
match inj.try_push(3) {
Err(v) => assert_eq!(v, 3),
Ok(()) => panic!("expected full"),
}
}
#[test]
fn mpmc_round_trip() {
let inj = Arc::new(Injector::<u32>::with_capacity(64));
let total = 10_000usize;
let n_producers = 4;
let n_consumers = 4;
let per_producer = (total / n_producers) as u32;
let consumed = Arc::new(AtomicUsize::new(0));
let mut handles = Vec::new();
for _ in 0..n_consumers {
let inj = Arc::clone(&inj);
let consumed = Arc::clone(&consumed);
handles.push(thread::spawn(move || {
while consumed.load(O::Relaxed) < total {
match inj.steal() {
InjectorSteal::Success(_) => {
consumed.fetch_add(1, O::Relaxed);
}
_ => std::thread::yield_now(),
}
}
}));
}
for p in 0..n_producers {
let inj = Arc::clone(&inj);
handles.push(thread::spawn(move || {
for i in 0..per_producer {
inj.push(p as u32 * per_producer + i);
}
}));
}
for h in handles {
h.join().expect("worker");
}
assert_eq!(consumed.load(O::Relaxed), total);
}
}