Skip to content

Commit 0564d22

Browse files
committed
FEAT: Implement internal Array::maybe_uninit and assume_init
Use MaybeUninit to handle uninitialized data safely.
1 parent 2ab90e9 commit 0564d22

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/impl_constructors.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#![allow(clippy::match_wild_err_arm)]
1414

1515
use num_traits::{Float, One, Zero};
16+
use std::mem::MaybeUninit;
1617

1718
use crate::dimension;
1819
use crate::error::{self, ShapeError};
@@ -517,3 +518,22 @@ where
517518
Self::from_shape_vec_unchecked(shape, v)
518519
}
519520
}
521+
522+
impl<S, A, D> ArrayBase<S, D>
523+
where
524+
S: DataOwned<Elem = MaybeUninit<A>>,
525+
D: Dimension,
526+
{
527+
pub(crate) fn maybe_uninit<Sh>(shape: Sh) -> Self
528+
where
529+
Sh: ShapeBuilder<Dim = D>,
530+
{
531+
unsafe {
532+
let shape = shape.into_shape();
533+
let size = size_of_shape_checked_unwrap!(&shape.dim);
534+
let mut v = Vec::with_capacity(size);
535+
v.set_len(size);
536+
Self::from_shape_vec_unchecked(shape, v)
537+
}
538+
}
539+
}

src/impl_owned_array.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1+
use std::mem::MaybeUninit;
2+
use std::mem::transmute;
3+
14
use crate::imp_prelude::*;
5+
use crate::OwnedRepr;
26

37
/// Methods specific to `Array0`.
48
///
@@ -57,3 +61,33 @@ where
5761
self.data.0
5862
}
5963
}
64+
65+
/// Methods specific to `Array` of `MaybeUninit`.
66+
///
67+
/// ***See also all methods for [`ArrayBase`]***
68+
///
69+
/// [`ArrayBase`]: struct.ArrayBase.html
70+
impl<A, D> Array<MaybeUninit<A>, D>
71+
where
72+
D: Dimension,
73+
{
74+
/// Assert that the array's storage's elements are all fully initialized, and conver
75+
/// the array from element type `MaybeUninit<A>` to `A`.
76+
pub(crate) unsafe fn assume_init(self) -> Array<A, D> {
77+
// NOTE: Fully initialized includes elements not reachable in current slicing/view.
78+
//
79+
// Should this method be generalized to all array types?
80+
// (Will need a way to map the RawData<Elem=X> to RawData<Elem=Y> of same kind)
81+
let data = transmute::<OwnedRepr<MaybeUninit<A>>, OwnedRepr<A>>(self.data);
82+
let ptr = self.ptr.cast::<A>();
83+
let dim = self.dim;
84+
let strides = self.strides;
85+
86+
Array {
87+
data,
88+
ptr,
89+
dim,
90+
strides,
91+
}
92+
}
93+
}

0 commit comments

Comments
 (0)