ndarray/
data_repr.rs

1use std::mem;
2use std::mem::ManuallyDrop;
3use std::ptr::NonNull;
4use alloc::slice;
5use alloc::borrow::ToOwned;
6use alloc::vec::Vec;
7use crate::extension::nonnull;
8
9/// Array's representation.
10///
11/// *Don’t use this type directly—use the type alias
12/// [`Array`](type.Array.html) for the array type!*
13// Like a Vec, but with non-unique ownership semantics
14//
15// repr(C) to make it transmutable OwnedRepr<A> -> OwnedRepr<B> if
16// transmutable A -> B.
17#[derive(Debug)]
18#[repr(C)]
19pub struct OwnedRepr<A> {
20    ptr: NonNull<A>,
21    len: usize,
22    capacity: usize,
23}
24
25impl<A> OwnedRepr<A> {
26    pub(crate) fn from(v: Vec<A>) -> Self {
27        let mut v = ManuallyDrop::new(v);
28        let len = v.len();
29        let capacity = v.capacity();
30        let ptr = nonnull::nonnull_from_vec_data(&mut v);
31        Self {
32            ptr,
33            len,
34            capacity,
35        }
36    }
37
38    pub(crate) fn into_vec(self) -> Vec<A> {
39        ManuallyDrop::new(self).take_as_vec()
40    }
41
42    pub(crate) fn as_slice(&self) -> &[A] {
43        unsafe {
44            slice::from_raw_parts(self.ptr.as_ptr(), self.len)
45        }
46    }
47
48    pub(crate) fn len(&self) -> usize { self.len }
49
50    pub(crate) fn as_ptr(&self) -> *const A {
51        self.ptr.as_ptr()
52    }
53
54    pub(crate) fn as_nonnull_mut(&mut self) -> NonNull<A> {
55        self.ptr
56    }
57
58    /// Cast self into equivalent repr of other element type
59    ///
60    /// ## Safety
61    ///
62    /// Caller must ensure the two types have the same representation.
63    /// **Panics** if sizes don't match (which is not a sufficient check).
64    pub(crate) unsafe fn data_subst<B>(self) -> OwnedRepr<B> {
65        // necessary but not sufficient check
66        assert_eq!(mem::size_of::<A>(), mem::size_of::<B>());
67        let self_ = ManuallyDrop::new(self);
68        OwnedRepr {
69            ptr: self_.ptr.cast::<B>(),
70            len: self_.len,
71            capacity: self_.capacity,
72        }
73    }
74
75    fn take_as_vec(&mut self) -> Vec<A> {
76        let capacity = self.capacity;
77        let len = self.len;
78        self.len = 0;
79        self.capacity = 0;
80        unsafe {
81            Vec::from_raw_parts(self.ptr.as_ptr(), len, capacity)
82        }
83    }
84}
85
86impl<A> Clone for OwnedRepr<A>
87    where A: Clone
88{
89    fn clone(&self) -> Self {
90        Self::from(self.as_slice().to_owned())
91    }
92
93    fn clone_from(&mut self, other: &Self) {
94        let mut v = self.take_as_vec();
95        let other = other.as_slice();
96
97        if v.len() > other.len() {
98            v.truncate(other.len());
99        }
100        let (front, back) = other.split_at(v.len());
101        v.clone_from_slice(front);
102        v.extend_from_slice(back);
103        *self = Self::from(v);
104    }
105}
106
107impl<A> Drop for OwnedRepr<A> {
108    fn drop(&mut self) {
109        if self.capacity > 0 {
110            // correct because: If the elements don't need dropping, an
111            // empty Vec is ok. Only the Vec's allocation needs dropping.
112            //
113            // implemented because: in some places in ndarray
114            // where A: Copy (hence does not need drop) we use uninitialized elements in
115            // vectors. Setting the length to 0 avoids that the vector tries to
116            // drop, slice or otherwise produce values of these elements.
117            // (The details of the validity letting this happen with nonzero len, are
118            // under discussion as of this writing.)
119            if !mem::needs_drop::<A>() {
120                self.len = 0;
121            }
122            // drop as a Vec.
123            self.take_as_vec();
124        }
125    }
126}
127
128unsafe impl<A> Sync for OwnedRepr<A> where A: Sync { }
129unsafe impl<A> Send for OwnedRepr<A> where A: Send { }
130