burn_std/tensor/
container.rs1use alloc::boxed::Box;
2use core::any::Any;
3
4#[cfg(not(feature = "std"))]
5use alloc::vec::Vec;
6#[cfg(not(feature = "std"))]
7use hashbrown::HashMap;
8
9#[cfg(feature = "std")]
10use std::collections::HashMap;
11
12#[derive(Debug)]
14pub struct TensorContainer<ID> {
15 tensors: HashMap<ID, Box<dyn Any + Send>>,
16}
17
18impl<ID> Default for TensorContainer<ID>
19where
20 ID: core::hash::Hash + PartialEq + Eq + core::fmt::Debug,
21{
22 fn default() -> Self {
23 Self::new()
24 }
25}
26
27impl<ID> TensorContainer<ID>
28where
29 ID: core::hash::Hash + PartialEq + Eq + core::fmt::Debug,
30{
31 pub fn new() -> Self {
33 Self {
34 tensors: HashMap::new(),
35 }
36 }
37
38 pub fn get<T: Clone + Send + 'static>(&self, id: &ID) -> Option<T> {
40 let grad = self.tensors.get(id)?;
41
42 let tensor = grad.downcast_ref::<T>().unwrap();
43
44 Some(tensor.clone())
45 }
46
47 pub fn get_mut_ref<T: Clone + Send + 'static>(&mut self, id: &ID) -> Option<&mut T> {
49 let grad = self.tensors.get_mut(id)?;
50
51 let tensor = grad.downcast_mut::<T>().unwrap();
52
53 Some(tensor)
54 }
55
56 pub fn register<T: Clone + Send + 'static>(&mut self, id: ID, value: T) {
62 self.tensors.insert(id, Box::new(value));
63 }
64
65 pub fn remove<T: Clone + Send + 'static>(&mut self, id: &ID) -> Option<T> {
67 self.tensors
68 .remove(id)
69 .map(|item| *item.downcast::<T>().unwrap())
70 }
71
72 pub fn len(&self) -> usize {
74 self.tensors.len()
75 }
76
77 pub fn is_empty(&self) -> bool {
79 self.len() == 0
80 }
81
82 pub fn ids(&self) -> Vec<&ID> {
84 self.tensors.keys().collect()
85 }
86}