Skip to main content

metatensor/data/
empty.rs

1use dlpk::sys::{DLDevice, DLPackVersion, DLDataType};
2use dlpk::{DLPackTensor};
3
4use crate::errors::Error;
5use crate::c_api::mts_data_movement_t;
6
7use super::{Array, MtsArray};
8
9
10/// An implementation of the [`Array`] trait without any data.
11///
12/// This only tracks the shape of the array.
13#[derive(Debug, Clone)]
14pub struct EmptyArray {
15    shape: Vec<usize>,
16}
17
18impl EmptyArray {
19    /// Create a new `EmptyArray` with the given shape.
20    pub fn new(shape: Vec<usize>) -> EmptyArray {
21        EmptyArray { shape }
22    }
23}
24
25impl Array for EmptyArray {
26    fn as_any(&self) -> &dyn std::any::Any {
27        self
28    }
29
30    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
31        self
32    }
33
34    fn create(&self, shape: &[usize], _fill_value: MtsArray) -> Box<dyn Array> {
35        Box::new(EmptyArray { shape: shape.to_vec() })
36    }
37
38    fn copy(&self, device: DLDevice) -> Box<dyn Array> {
39        assert_eq!(device, DLDevice::cpu());
40        Box::new(EmptyArray { shape: self.shape.clone() })
41    }
42
43    fn shape(&self) -> Vec<usize> {
44        self.shape.clone()
45    }
46
47    fn reshape(&mut self, shape: &[usize]) {
48        self.shape = shape.to_vec();
49    }
50
51    fn swap_axes(&mut self, axis_1: usize, axis_2: usize) {
52        self.shape.swap(axis_1, axis_2);
53    }
54
55    fn move_data(&mut self, _: &dyn Array, _: &[mts_data_movement_t]) {
56        panic!("can not call Array::move_data() for EmptyArray");
57    }
58
59    fn device(&self) -> DLDevice {
60        DLDevice::cpu()
61    }
62
63    fn dtype(&self) -> DLDataType {
64        // Default to f64, consistent with metatensor-core's EmptyDataArray
65        DLDataType {
66            code: dlpk::sys::DLDataTypeCode::kDLFloat,
67            bits: 64,
68            lanes: 1,
69        }
70    }
71
72    fn as_dlpack(
73        &self,
74        _device: DLDevice,
75        _stream: Option<i64>,
76        _max_version: DLPackVersion
77    ) -> Result<DLPackTensor, Error> {
78        panic!("can not call Array::as_dlpack() for EmptyArray");
79    }
80
81    fn from_dlpack(&self, _dlpack_tensor: DLPackTensor) -> Result<Box<dyn Array>, Error> {
82        panic!("can not call Array::from_dlpack() for EmptyArray");
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use dlpk::sys::DLDevice;
89    use crate::Array;
90
91    use super::*;
92
93    #[test]
94    fn empty_array_device() {
95        let array = EmptyArray::new(vec![2, 3]);
96        assert_eq!(array.device(), DLDevice::cpu());
97    }
98}