use std::{
fmt::{self, Debug, Formatter},
sync::{
Arc, Mutex,
atomic::{AtomicUsize, Ordering},
},
};
use crate::{
context::Context,
error::{Error, Result},
graph::owned::{Recordable, Recording},
stream::{Stream, StreamFlags, StreamOptions},
submission::{Completion, Execution, Resources, Submission},
};
pub unsafe trait Operation: Sized {
type Pending;
type Output: 'static;
fn enqueue(self, execution: &mut Execution) -> Result<Self::Pending>;
unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output>;
fn submit_on(self, stream: &Stream) -> Result<Submission<Self::Output, Self::Pending>> {
let mut execution = Execution::create(stream)?;
let output = self.enqueue(&mut execution)?;
execution.finish_with(output, Self::resolve)
}
fn then<F, N>(self, next: F) -> Then<Self, F>
where
Self: DeviceOperation,
F: FnOnce(Self::Output) -> N,
N: Operation,
{
Then { first: self, next }
}
fn pair<O: Operation>(self, other: O) -> Pair<Self, O> {
Pair(self, other)
}
fn map<F, T: 'static>(self, map: F) -> Map<Self, F>
where
F: FnOnce(Self::Output) -> T,
{
Map {
operation: self,
map,
}
}
fn shared(self) -> Shared<Self>
where
Self: DeviceOperation,
Self::Output: Send + Sync,
{
Shared {
state: Arc::new(Mutex::new(SharedState::New(Some(self)))),
}
}
}
pub unsafe trait DeviceOperation: Operation<Pending = <Self as Operation>::Output> {}
#[derive(Debug)]
pub struct Then<O, F> {
first: O,
next: F,
}
unsafe impl<O, F, N> Operation for Then<O, F>
where
O: DeviceOperation,
F: FnOnce(O::Output) -> N,
N: Operation,
{
type Pending = N::Pending;
type Output = N::Output;
fn enqueue(self, execution: &mut Execution) -> Result<Self::Pending> {
let output = self.first.enqueue(execution)?;
(self.next)(output).enqueue(execution)
}
unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
unsafe { N::resolve(pending) }
}
}
#[derive(Debug)]
pub struct Pair<A, B>(A, B);
unsafe impl<A: Operation, B: Operation> Operation for Pair<A, B> {
type Pending = (A::Pending, B::Pending);
type Output = (A::Output, B::Output);
fn enqueue(self, execution: &mut Execution) -> Result<Self::Pending> {
Ok((self.0.enqueue(execution)?, self.1.enqueue(execution)?))
}
unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
unsafe { Ok((A::resolve(pending.0)?, B::resolve(pending.1)?)) }
}
}
#[derive(Debug)]
pub struct Map<O, F> {
operation: O,
map: F,
}
unsafe impl<O, F, T: 'static> Operation for Map<O, F>
where
O: Operation,
F: FnOnce(O::Output) -> T,
{
type Pending = (O::Pending, F);
type Output = T;
fn enqueue(self, execution: &mut Execution) -> Result<Self::Pending> {
Ok((self.operation.enqueue(execution)?, self.map))
}
unsafe fn resolve((pending, map): Self::Pending) -> Result<T> {
Ok(map(unsafe { O::resolve(pending)? }))
}
}
#[derive(Debug)]
enum SharedState<O: DeviceOperation> {
New(Option<O>),
Submitted {
output: Arc<O::Output>,
completion: Completion,
},
Failed(Arc<Error>),
}
pub struct Shared<O: DeviceOperation> {
state: Arc<Mutex<SharedState<O>>>,
}
impl<O: DeviceOperation> Debug for Shared<O> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Shared").finish_non_exhaustive()
}
}
impl<O: DeviceOperation> Clone for Shared<O> {
fn clone(&self) -> Self {
Self {
state: Arc::clone(&self.state),
}
}
}
unsafe impl<O: DeviceOperation> Operation for Shared<O>
where
O::Output: Send + Sync,
{
type Pending = Arc<O::Output>;
type Output = Arc<O::Output>;
unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
Ok(pending)
}
fn enqueue(self, execution: &mut Execution) -> Result<Self::Output> {
let mut state = self
.state
.lock()
.map_err(|_| Error::lock_poisoned("shared operation"))?;
if let SharedState::New(operation) = &mut *state {
let operation = operation.take().expect("shared operation has not executed");
*state = match operation.submit_on(execution.stream()) {
Ok(mut submission) => SharedState::Submitted {
output: Arc::new(submission.pending.take().expect("new shared output")),
completion: submission.completion.clone(),
},
Err(error) => SharedState::Failed(Arc::new(error)),
};
}
match &*state {
SharedState::Submitted { output, completion } => {
let mut resources = Resources::new();
resources.depend_on(completion.clone());
resources.retain(Arc::clone(output));
unsafe {
execution.enqueue(resources, |_| Ok::<_, Error>(()))?;
}
Ok(Arc::clone(output))
}
SharedState::Failed(error) => Err(Error::Completion(Arc::clone(error))),
SharedState::New(_) => unreachable!("shared operation was submitted"),
}
}
}
#[derive(Debug)]
pub struct StreamPool {
streams: Vec<Stream>,
next: AtomicUsize,
}
impl StreamPool {
pub fn create(context: &Arc<Context>, streams: usize) -> Result<Self> {
if streams == 0 {
return Err(Error::not_positive("stream pool size"));
}
Ok(Self {
streams: (0..streams)
.map(|_| {
context.create_stream(StreamOptions {
flags: StreamFlags::NON_BLOCKING,
..StreamOptions::default()
})
})
.collect::<Result<_>>()?,
next: AtomicUsize::new(0),
})
}
pub fn submit<O: Operation>(&self, operation: O) -> Result<Submission<O::Output, O::Pending>> {
let index = self.next.fetch_add(1, Ordering::Relaxed) % self.streams.len();
operation.submit_on(&self.streams[index])
}
pub fn streams(&self) -> &[Stream] {
&self.streams
}
}
unsafe impl<A: Recordable, B: Recordable> Recordable for Pair<A, B> {
type Output = (A::Output, B::Output);
fn record(self, recording: &mut Recording) -> Result<Self::Output> {
Ok((self.0.record(recording)?, self.1.record(recording)?))
}
}
unsafe impl<O: Operation> Operation for Result<O> {
type Pending = O::Pending;
type Output = O::Output;
fn enqueue(self, execution: &mut Execution) -> Result<Self::Pending> {
self?.enqueue(execution)
}
unsafe fn resolve(pending: Self::Pending) -> Result<Self::Output> {
unsafe { O::resolve(pending) }
}
}
unsafe impl<O: DeviceOperation, F, N: DeviceOperation> DeviceOperation for Then<O, F> where
F: FnOnce(O::Output) -> N
{
}
unsafe impl<A: DeviceOperation, B: DeviceOperation> DeviceOperation for Pair<A, B> {}
unsafe impl<O: DeviceOperation> DeviceOperation for Result<O> {}
unsafe impl<O: DeviceOperation> DeviceOperation for Shared<O> where O::Output: Send + Sync {}