use alloc::boxed::Box;
use core::any::Any;
#[cfg(not(feature = "std"))]
use hashbrown::HashMap;
#[cfg(feature = "std")]
use std::collections::HashMap;
use crate::{backend::Backend, Tensor};
#[derive(Debug)]
pub struct TensorContainer<ID> {
tensors: HashMap<ID, Box<dyn Any + Send + Sync>>,
}
impl<ID> Default for TensorContainer<ID>
where
ID: core::hash::Hash + PartialEq + Eq + core::fmt::Debug,
{
fn default() -> Self {
Self::new()
}
}
type TensorPrimitive<B, const D: usize> = <B as Backend>::TensorPrimitive<D>;
impl<ID> TensorContainer<ID>
where
ID: core::hash::Hash + PartialEq + Eq + core::fmt::Debug,
{
pub fn new() -> Self {
Self {
tensors: HashMap::new(),
}
}
pub fn get<B, const D: usize>(&self, id: &ID) -> Option<Tensor<B, D>>
where
B: Backend,
{
let grad = match self.tensors.get(id) {
Some(grad) => grad,
None => return None,
};
let tensor = grad
.downcast_ref::<TensorPrimitive<B, D>>()
.map(|primitive| Tensor::<B, D>::from_primitive(primitive.clone()))
.unwrap();
Some(tensor)
}
pub fn register<B, const D: usize>(&mut self, id: ID, value: Tensor<B, D>)
where
B: Backend,
{
self.tensors.insert(id, Box::new(value.into_primitive()));
}
pub fn remove<B, const D: usize>(&mut self, id: &ID) -> Option<Tensor<B, D>>
where
B: Backend,
{
self.tensors
.remove(id)
.map(|item| item.downcast::<TensorPrimitive<B, D>>().unwrap())
.map(|primitive| Tensor::from_primitive(*primitive))
}
pub fn len(&self) -> usize {
self.tensors.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}