ndarray/
impl_1d.rs

1// Copyright 2016 bluss and ndarray developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Methods for one-dimensional arrays.
10#[cfg(not(feature = "std"))]
11use alloc::vec::Vec;
12use std::mem::MaybeUninit;
13
14use crate::imp_prelude::*;
15use crate::low_level_util::AbortIfPanic;
16
17/// # Methods For 1-D Arrays
18impl<A, S> ArrayBase<S, Ix1>
19where S: RawData<Elem = A>
20{
21    /// Return an vector with the elements of the one-dimensional array.
22    pub fn to_vec(&self) -> Vec<A>
23    where
24        A: Clone,
25        S: Data,
26    {
27        if let Some(slc) = self.as_slice() {
28            slc.to_vec()
29        } else {
30            crate::iterators::to_vec(self.iter().cloned())
31        }
32    }
33
34    /// Rotate the elements of the array by 1 element towards the front;
35    /// the former first element becomes the last.
36    pub(crate) fn rotate1_front(&mut self)
37    where S: DataMut
38    {
39        // use swapping to keep all elements initialized (as required by owned storage)
40        let mut lane_iter = self.iter_mut();
41        let mut dst = if let Some(dst) = lane_iter.next() { dst } else { return };
42
43        // Logically we do a circular swap here, all elements in a chain
44        // Using MaybeUninit to avoid unnecessary writes in the safe swap solution
45        //
46        //  for elt in lane_iter {
47        //      std::mem::swap(dst, elt);
48        //      dst = elt;
49        //  }
50        //
51        let guard = AbortIfPanic(&"rotate1_front: temporarily moving out of owned value");
52        let mut slot = MaybeUninit::<A>::uninit();
53        unsafe {
54            slot.as_mut_ptr().copy_from_nonoverlapping(dst, 1);
55            for elt in lane_iter {
56                (dst as *mut A).copy_from_nonoverlapping(elt, 1);
57                dst = elt;
58            }
59            (dst as *mut A).copy_from_nonoverlapping(slot.as_ptr(), 1);
60        }
61        guard.defuse();
62    }
63}