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.
10use alloc::vec::Vec;
11use std::mem::MaybeUninit;
12
13use crate::imp_prelude::*;
14use crate::low_level_util::AbortIfPanic;
15
16/// # Methods For 1-D Arrays
17impl<A, S> ArrayBase<S, Ix1>
18where
19    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
38        S: DataMut,
39    {
40        // use swapping to keep all elements initialized (as required by owned storage)
41        let mut lane_iter = self.iter_mut();
42        let mut dst = if let Some(dst) = lane_iter.next() { dst } else { return };
43
44        // Logically we do a circular swap here, all elements in a chain
45        // Using MaybeUninit to avoid unnecessary writes in the safe swap solution
46        //
47        //  for elt in lane_iter {
48        //      std::mem::swap(dst, elt);
49        //      dst = elt;
50        //  }
51        //
52        let guard = AbortIfPanic(&"rotate1_front: temporarily moving out of owned value");
53        let mut slot = MaybeUninit::<A>::uninit();
54        unsafe {
55            slot.as_mut_ptr().copy_from_nonoverlapping(dst, 1);
56            for elt in lane_iter {
57                (dst as *mut A).copy_from_nonoverlapping(elt, 1);
58                dst = elt;
59            }
60            (dst as *mut A).copy_from_nonoverlapping(slot.as_ptr(), 1);
61        }
62        guard.defuse();
63    }
64}