-
Notifications
You must be signed in to change notification settings - Fork 5
Open
Description
The following complete program demonstrates two (hopefully correct) ways of working with uninitialized tensors:
use std::mem::MaybeUninit;
use mdarray::{Tensor, DTensor, DenseMapping, Shape};
fn use_with_capacity_mut() {
let mut a = DTensor::<f64, 2>::with_capacity(9);
let data = a.spare_capacity_mut();
for (i, val) in data.iter_mut().enumerate() {
val.write(i as f64);
}
// SAFETY: We initialized all elements.
unsafe {
a.set_mapping(DenseMapping::new((3, 3)));
}
dbg!(&a);
}
/// # Safety
/// All elements must have been initialized.
unsafe fn tensor_assume_init<T, S: Shape>(tensor: Tensor<MaybeUninit<T>, S>) -> Tensor<T, S>
{
let (ptr, mapping, capacity) = tensor.into_raw_parts();
unsafe {
Tensor::from_raw_parts(ptr as *mut T, mapping, capacity)
}
}
fn use_tensor_of_maybe_uninit() {
// let mut b = tensor![[MaybeUninit::<f64>::uninit(); 3]; 3];
let mut a = Tensor::from_elem((3, 3), MaybeUninit::<f64>::uninit());
for (i, val) in a.iter_mut().enumerate() {
val.write(i as f64);
}
let a = unsafe { tensor_assume_init(a) };
dbg!(&a);
}
fn main() {
use_with_capacity_mut();
use_tensor_of_maybe_uninit();
}Could you confirm that use_with_capacity_mut is OK? If it is, then I think that there is a typo in the documentation of Tensor::spare_capacity_mut. It refers to a method set_shape that no longer exists. It probably should refer to set_mapping.
The second function, use_tensor_of_maybe_uninit demonstrates another way of working with uninitialized data. If correct, this way seems safer/easier to me (because the user does not have to construct a correct mapping). It is also more compact.
Perhaps a method similar to tensor_assume_init would be an useful addition to Tensor? (But perhaps not – it is quickly written if needed.)
Metadata
Metadata
Assignees
Labels
No labels