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> ArrayRef<A, Ix1>
19{
20    /// Return an vector with the elements of the one-dimensional array.
21    pub fn to_vec(&self) -> Vec<A>
22    where A: Clone
23    {
24        if let Some(slc) = self.as_slice() {
25            slc.to_vec()
26        } else {
27            crate::iterators::to_vec(self.iter().cloned())
28        }
29    }
30
31    /// Rotate the elements of the array by 1 element towards the front;
32    /// the former first element becomes the last.
33    pub(crate) fn rotate1_front(&mut self)
34    {
35        // use swapping to keep all elements initialized (as required by owned storage)
36        let mut lane_iter = self.iter_mut();
37        let mut dst = if let Some(dst) = lane_iter.next() { dst } else { return };
38
39        // Logically we do a circular swap here, all elements in a chain
40        // Using MaybeUninit to avoid unnecessary writes in the safe swap solution
41        //
42        //  for elt in lane_iter {
43        //      std::mem::swap(dst, elt);
44        //      dst = elt;
45        //  }
46        //
47        let guard = AbortIfPanic(&"rotate1_front: temporarily moving out of owned value");
48        let mut slot = MaybeUninit::<A>::uninit();
49        unsafe {
50            slot.as_mut_ptr().copy_from_nonoverlapping(dst, 1);
51            for elt in lane_iter {
52                (dst as *mut A).copy_from_nonoverlapping(elt, 1);
53                dst = elt;
54            }
55            (dst as *mut A).copy_from_nonoverlapping(slot.as_ptr(), 1);
56        }
57        guard.defuse();
58    }
59}