use crate::{Encoding, Graph, Target};
use nanoglia_core::{Allocator, Block, Result};
pub unsafe trait GraphHandle {
type Allocator: Allocator;
fn graph(&self) -> &Graph<'_, Self::Allocator>;
}
unsafe impl<A: Allocator> GraphHandle for Graph<'_, A> {
type Allocator = A;
fn graph(&self) -> &Graph<'_, A> {
self
}
}
unsafe impl<A: Allocator> GraphHandle for &Graph<'_, A> {
type Allocator = A;
fn graph(&self) -> &Graph<'_, A> {
self
}
}
pub struct OwnedGraph<A: Allocator, M: Allocator = A> {
graph: Graph<'static, A>,
model: Block<M>,
}
impl<A: Allocator, M: Allocator> OwnedGraph<A, M> {
pub fn load_in(model: Block<M>, encoding: Encoding, target: Target, alloc: A) -> Result<Self> {
let bytes = unsafe { core::slice::from_raw_parts(model.as_slice().as_ptr(), model.len()) };
let graph = Graph::load_in(&[bytes], encoding, target, alloc)?;
Ok(Self { graph, model })
}
pub fn graph(&self) -> &Graph<'_, A> {
&self.graph
}
pub fn model_bytes(&self) -> usize {
self.model.len()
}
}
unsafe impl<A: Allocator, M: Allocator> GraphHandle for OwnedGraph<A, M> {
type Allocator = A;
fn graph(&self) -> &Graph<'_, A> {
self.graph()
}
}
#[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
mod shared {
extern crate alloc;
use super::*;
use alloc::sync::Arc;
unsafe impl<G: GraphHandle> GraphHandle for Arc<G> {
type Allocator = G::Allocator;
fn graph(&self) -> &Graph<'_, G::Allocator> {
self.as_ref().graph()
}
}
}