use std::ops::Deref;
#[cfg(feature = "cuda")]
#[derive(Debug)]
pub struct PinnedAlloc(cujson_sys::cujson_tape);
#[cfg(feature = "cuda")]
unsafe impl Send for PinnedAlloc {}
#[cfg(feature = "cuda")]
unsafe impl Sync for PinnedAlloc {}
#[cfg(feature = "cuda")]
impl Drop for PinnedAlloc {
fn drop(&mut self) {
unsafe { cujson_sys::cujson_tape_free(&mut self.0) }
}
}
#[derive(Debug, Clone)]
pub enum TapeStorage {
Owned(Box<[i32]>),
#[cfg(feature = "cuda")]
Pinned {
alloc: std::sync::Arc<PinnedAlloc>,
ptr: *const i32,
len: usize,
},
}
unsafe impl Send for TapeStorage {}
unsafe impl Sync for TapeStorage {}
impl Deref for TapeStorage {
type Target = [i32];
fn deref(&self) -> &[i32] {
match self {
TapeStorage::Owned(b) => b,
#[cfg(feature = "cuda")]
TapeStorage::Pinned { ptr, len, .. } => unsafe {
std::slice::from_raw_parts(*ptr, *len)
},
}
}
}
impl From<Vec<i32>> for TapeStorage {
fn from(v: Vec<i32>) -> Self {
TapeStorage::Owned(v.into_boxed_slice())
}
}
impl From<Box<[i32]>> for TapeStorage {
fn from(b: Box<[i32]>) -> Self {
TapeStorage::Owned(b)
}
}
#[derive(Debug, Clone)]
pub struct Tape {
pub structural: TapeStorage,
pub pair_pos: TapeStorage,
}
impl Tape {
pub fn len(&self) -> usize {
self.structural.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[cfg(feature = "cuda")]
pub(crate) fn tape_from_ffi(raw: cujson_sys::cujson_tape) -> Tape {
let len = raw.len;
let structural_ptr = raw.structural as *const i32;
let pair_pos_ptr = raw.pair_pos as *const i32;
let alloc = std::sync::Arc::new(PinnedAlloc(raw));
let structural = TapeStorage::Pinned {
alloc: alloc.clone(),
ptr: structural_ptr,
len,
};
let pair_pos = TapeStorage::Pinned {
alloc,
ptr: pair_pos_ptr,
len,
};
Tape {
structural,
pair_pos,
}
}