use std::{
cell::Cell,
error::Error as StdError,
fmt,
marker::PhantomData,
mem::{self, ManuallyDrop, MaybeUninit},
ptr,
sync::Arc,
};
use singe_core::report_cleanup_failure;
use singe_cuda_sys::runtime;
use crate::{
context::Context,
error::Error as CudaError,
stream::{AsStream, Stream, StreamBinding},
view::DeviceRegion,
};
pub unsafe trait NativeHandle: 'static {
type Raw: Copy + fmt::Debug;
type State: fmt::Debug + Send;
type Error: From<CudaError> + StdError + 'static;
const OBJECT: &'static str;
fn null_handle() -> Self::Error;
fn is_null(raw: Self::Raw) -> bool;
unsafe fn destroy(raw: Self::Raw, state: Self::State) -> Result<(), Self::Error>;
}
pub unsafe trait CreateHandle: NativeHandle<State = ()> {
unsafe fn create(raw: *mut Self::Raw) -> Result<(), Self::Error>;
}
pub unsafe trait StreamHandle: NativeHandle {
unsafe fn set_stream(raw: Self::Raw, stream: runtime::cudaStream_t) -> Result<(), Self::Error>;
}
pub struct Handle<H: NativeHandle> {
raw: H::Raw,
state: ManuallyDrop<H::State>,
stream: Option<Stream>,
cuda_context: Arc<Context>,
_not_sync: PhantomData<Cell<()>>,
}
pub struct RawHandle<H: NativeHandle> {
pub handle: H::Raw,
pub cuda_context: Arc<Context>,
pub stream: Option<Stream>,
pub state: H::State,
}
unsafe impl<H: NativeHandle> Send for Handle<H> {}
unsafe impl<H: NativeHandle> Send for RawHandle<H> {}
impl<H: NativeHandle> fmt::Debug for Handle<H> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Handle")
.field("object", &H::OBJECT)
.field("raw", &self.raw)
.field("state", &*self.state)
.field("stream", &self.stream)
.field("cuda_context", &self.cuda_context)
.finish()
}
}
impl<H: NativeHandle> fmt::Debug for RawHandle<H> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RawHandle")
.field("object", &H::OBJECT)
.field("handle", &self.handle)
.field("state", &self.state)
.field("stream", &self.stream)
.field("cuda_context", &self.cuda_context)
.finish()
}
}
impl<H: CreateHandle> Handle<H> {
pub fn create(cuda_context: &Arc<Context>) -> Result<Self, H::Error> {
cuda_context.bind()?;
let mut raw = MaybeUninit::uninit();
unsafe { H::create(raw.as_mut_ptr())? };
let raw = unsafe { raw.assume_init() };
if H::is_null(raw) {
return Err(H::null_handle());
}
Ok(Self {
raw,
state: ManuallyDrop::new(()),
stream: None,
cuda_context: Arc::clone(cuda_context),
_not_sync: PhantomData,
})
}
}
impl<H: NativeHandle> Handle<H> {
pub unsafe fn from_raw(raw: RawHandle<H>) -> Result<Self, H::Error> {
if H::is_null(raw.handle) {
return Err(H::null_handle());
}
if raw
.stream
.as_ref()
.is_some_and(|stream| stream.context() != &raw.cuda_context)
{
return Err(CudaError::StreamContextMismatch.into());
}
Ok(Self {
raw: raw.handle,
state: ManuallyDrop::new(raw.state),
stream: raw.stream,
cuda_context: raw.cuda_context,
_not_sync: PhantomData,
})
}
#[must_use]
pub fn into_raw(self) -> RawHandle<H> {
let this = ManuallyDrop::new(self);
unsafe {
RawHandle {
handle: this.raw,
cuda_context: ptr::read(&raw const this.cuda_context),
stream: ptr::read(&raw const this.stream),
state: ManuallyDrop::into_inner(ptr::read(&raw const this.state)),
}
}
}
pub fn destroy(self) -> Result<(), H::Error> {
let raw = self.into_raw();
if let Err(error) = raw.cuda_context.bind() {
mem::forget(raw.state);
return Err(error.into());
}
unsafe { H::destroy(raw.handle, raw.state) }
}
#[must_use]
pub fn state(&self) -> &H::State {
&self.state
}
#[must_use]
pub fn as_raw(&self) -> H::Raw {
self.raw
}
#[must_use]
pub fn cuda_context(&self) -> &Arc<Context> {
&self.cuda_context
}
pub fn bind(&self) -> Result<(), H::Error> {
Ok(self.cuda_context.bind()?)
}
#[must_use]
pub fn stream(&self) -> Option<&Stream> {
self.stream.as_ref()
}
#[must_use]
pub fn stream_binding(&self) -> StreamBinding {
self.stream.as_ref().map_or_else(
|| StreamBinding::Default(Arc::clone(&self.cuda_context)),
|stream| StreamBinding::Borrowed(stream.to_borrowed()),
)
}
pub fn sync_scope<R>(&self, f: impl FnOnce() -> Result<R, H::Error>) -> Result<R, H::Error> {
self.stream_binding().sync_scope(f)
}
pub fn prepare_regions(&self, regions: &[DeviceRegion<'_>]) -> Result<(), H::Error> {
Ok(self.stream_binding().join_regions(regions)?)
}
}
impl<H: StreamHandle> Handle<H> {
pub fn set_stream(&mut self, stream: Option<&Stream>) -> Result<(), H::Error> {
if stream.is_some_and(|stream| stream.context() != &self.cuda_context) {
return Err(CudaError::StreamContextMismatch.into());
}
self.bind()?;
unsafe { H::set_stream(self.raw, stream.map_or(ptr::null_mut(), Stream::as_raw))? };
self.stream = stream.cloned();
Ok(())
}
}
impl<H: NativeHandle> Drop for Handle<H> {
fn drop(&mut self) {
let state = unsafe { ManuallyDrop::take(&mut self.state) };
if H::is_null(self.raw) {
return;
}
if let Err(error) = self.cuda_context.bind() {
report_cleanup_failure("bind the cuda context to destroy", H::OBJECT, &error);
mem::forget(state);
return;
}
if let Err(error) = unsafe { H::destroy(self.raw, state) } {
report_cleanup_failure("destroy", H::OBJECT, &error);
}
}
}