ndarray/impl_owned_array.rs
1
2use alloc::vec::Vec;
3use crate::imp_prelude::*;
4
5/// Methods specific to `Array0`.
6///
7/// ***See also all methods for [`ArrayBase`]***
8///
9/// [`ArrayBase`]: struct.ArrayBase.html
10impl<A> Array<A, Ix0> {
11 /// Returns the single element in the array without cloning it.
12 ///
13 /// ```
14 /// use ndarray::{arr0, Array0};
15 ///
16 /// // `Foo` doesn't implement `Clone`.
17 /// #[derive(Debug, Eq, PartialEq)]
18 /// struct Foo;
19 ///
20 /// let array: Array0<Foo> = arr0(Foo);
21 /// let scalar: Foo = array.into_scalar();
22 /// assert_eq!(scalar, Foo);
23 /// ```
24 pub fn into_scalar(self) -> A {
25 let size = ::std::mem::size_of::<A>();
26 if size == 0 {
27 // Any index in the `Vec` is fine since all elements are identical.
28 self.data.into_vec().remove(0)
29 } else {
30 // Find the index in the `Vec` corresponding to `self.ptr`.
31 // (This is necessary because the element in the array might not be
32 // the first element in the `Vec`, such as if the array was created
33 // by `array![1, 2, 3, 4].slice_move(s![2])`.)
34 let first = self.ptr.as_ptr() as usize;
35 let base = self.data.as_ptr() as usize;
36 let index = (first - base) / size;
37 debug_assert_eq!((first - base) % size, 0);
38 // Remove the element at the index and return it.
39 self.data.into_vec().remove(index)
40 }
41 }
42}
43
44/// Methods specific to `Array`.
45///
46/// ***See also all methods for [`ArrayBase`]***
47///
48/// [`ArrayBase`]: struct.ArrayBase.html
49impl<A, D> Array<A, D>
50where
51 D: Dimension,
52{
53 /// Return a vector of the elements in the array, in the way they are
54 /// stored internally.
55 ///
56 /// If the array is in standard memory layout, the logical element order
57 /// of the array (`.iter()` order) and of the returned vector will be the same.
58 pub fn into_raw_vec(self) -> Vec<A> {
59 self.data.into_vec()
60 }
61}