ndarray/
free_functions.rs

1// Copyright 2014-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
9use std::mem::{forget, size_of};
10use alloc::slice;
11use alloc::vec;
12use alloc::vec::Vec;
13
14use crate::imp_prelude::*;
15use crate::{dimension, ArcArray1, ArcArray2};
16
17/// Create an [**`Array`**](type.Array.html) with one, two or
18/// three dimensions.
19///
20/// ```
21/// use ndarray::array;
22/// let a1 = array![1, 2, 3, 4];
23///
24/// let a2 = array![[1, 2],
25///                 [3, 4]];
26///
27/// let a3 = array![[[1, 2], [3, 4]],
28///                 [[5, 6], [7, 8]]];
29///
30/// assert_eq!(a1.shape(), &[4]);
31/// assert_eq!(a2.shape(), &[2, 2]);
32/// assert_eq!(a3.shape(), &[2, 2, 2]);
33/// ```
34///
35/// This macro uses `vec![]`, and has the same ownership semantics;
36/// elements are moved into the resulting `Array`.
37///
38/// Use `array![...].into_shared()` to create an `ArcArray`.
39#[macro_export]
40macro_rules! array {
41    ($([$([$($x:expr),* $(,)*]),+ $(,)*]),+ $(,)*) => {{
42        $crate::Array3::from(vec![$([$([$($x,)*],)*],)*])
43    }};
44    ($([$($x:expr),* $(,)*]),+ $(,)*) => {{
45        $crate::Array2::from(vec![$([$($x,)*],)*])
46    }};
47    ($($x:expr),* $(,)*) => {{
48        $crate::Array::from(vec![$($x,)*])
49    }};
50}
51
52/// Create a zero-dimensional array with the element `x`.
53pub fn arr0<A>(x: A) -> Array0<A> {
54    unsafe { ArrayBase::from_shape_vec_unchecked((), vec![x]) }
55}
56
57/// Create a one-dimensional array with elements from `xs`.
58pub fn arr1<A: Clone>(xs: &[A]) -> Array1<A> {
59    ArrayBase::from(xs.to_vec())
60}
61
62/// Create a one-dimensional array with elements from `xs`.
63pub fn rcarr1<A: Clone>(xs: &[A]) -> ArcArray1<A> {
64    arr1(xs).into_shared()
65}
66
67/// Create a zero-dimensional array view borrowing `x`.
68pub fn aview0<A>(x: &A) -> ArrayView0<'_, A> {
69    unsafe { ArrayView::from_shape_ptr(Ix0(), x) }
70}
71
72/// Create a one-dimensional array view with elements borrowing `xs`.
73///
74/// ```
75/// use ndarray::aview1;
76///
77/// let data = [1.0; 1024];
78///
79/// // Create a 2D array view from borrowed data
80/// let a2d = aview1(&data).into_shape((32, 32)).unwrap();
81///
82/// assert_eq!(a2d.sum(), 1024.0);
83/// ```
84pub fn aview1<A>(xs: &[A]) -> ArrayView1<'_, A> {
85    ArrayView::from(xs)
86}
87
88/// Create a two-dimensional array view with elements borrowing `xs`.
89///
90/// **Panics** if the product of non-zero axis lengths overflows `isize`. (This
91/// can only occur when `V` is zero-sized.)
92pub fn aview2<A, V: FixedInitializer<Elem = A>>(xs: &[V]) -> ArrayView2<'_, A> {
93    let cols = V::len();
94    let rows = xs.len();
95    let dim = Ix2(rows, cols);
96    if size_of::<V>() == 0 {
97        dimension::size_of_shape_checked(&dim)
98            .expect("Product of non-zero axis lengths must not overflow isize.");
99    }
100    // `rows` is guaranteed to fit in `isize` because we've checked the ZST
101    // case and slices never contain > `isize::MAX` bytes. `cols` is guaranteed
102    // to fit in `isize` because `FixedInitializer` is not implemented for any
103    // array lengths > `isize::MAX`. `cols * rows` is guaranteed to fit in
104    // `isize` because we've checked the ZST case and slices never contain >
105    // `isize::MAX` bytes.
106    unsafe {
107        let data = slice::from_raw_parts(xs.as_ptr() as *const A, cols * rows);
108        ArrayView::from_shape_ptr(dim, data.as_ptr())
109    }
110}
111
112/// Create a one-dimensional read-write array view with elements borrowing `xs`.
113///
114/// ```
115/// use ndarray::{aview_mut1, s};
116/// // Create an array view over some data, then slice it and modify it.
117/// let mut data = [0; 1024];
118/// {
119///     let mut a = aview_mut1(&mut data).into_shape((32, 32)).unwrap();
120///     a.slice_mut(s![.., ..;3]).fill(5);
121/// }
122/// assert_eq!(&data[..10], [5, 0, 0, 5, 0, 0, 5, 0, 0, 5]);
123/// ```
124pub fn aview_mut1<A>(xs: &mut [A]) -> ArrayViewMut1<'_, A> {
125    ArrayViewMut::from(xs)
126}
127
128/// Create a two-dimensional read-write array view with elements borrowing `xs`.
129///
130/// **Panics** if the product of non-zero axis lengths overflows `isize`. (This
131/// can only occur when `V` is zero-sized.)
132///
133/// # Example
134///
135/// ```
136/// use ndarray::aview_mut2;
137///
138/// // The inner (nested) array must be of length 1 to 16, but the outer
139/// // can be of any length.
140/// let mut data = [[0.; 2]; 128];
141/// {
142///     // Make a 128 x 2 mut array view then turn it into 2 x 128
143///     let mut a = aview_mut2(&mut data).reversed_axes();
144///     // Make the first row ones and second row minus ones.
145///     a.row_mut(0).fill(1.);
146///     a.row_mut(1).fill(-1.);
147/// }
148/// // look at the start of the result
149/// assert_eq!(&data[..3], [[1., -1.], [1., -1.], [1., -1.]]);
150/// ```
151pub fn aview_mut2<A, V: FixedInitializer<Elem = A>>(xs: &mut [V]) -> ArrayViewMut2<'_, A> {
152    let cols = V::len();
153    let rows = xs.len();
154    let dim = Ix2(rows, cols);
155    if size_of::<V>() == 0 {
156        dimension::size_of_shape_checked(&dim)
157            .expect("Product of non-zero axis lengths must not overflow isize.");
158    }
159    // `rows` is guaranteed to fit in `isize` because we've checked the ZST
160    // case and slices never contain > `isize::MAX` bytes. `cols` is guaranteed
161    // to fit in `isize` because `FixedInitializer` is not implemented for any
162    // array lengths > `isize::MAX`. `cols * rows` is guaranteed to fit in
163    // `isize` because we've checked the ZST case and slices never contain >
164    // `isize::MAX` bytes.
165    unsafe {
166        let data = slice::from_raw_parts_mut(xs.as_mut_ptr() as *mut A, cols * rows);
167        ArrayViewMut::from_shape_ptr(dim, data.as_mut_ptr())
168    }
169}
170
171/// Fixed-size array used for array initialization
172pub unsafe trait FixedInitializer {
173    type Elem;
174    fn as_init_slice(&self) -> &[Self::Elem];
175    fn len() -> usize;
176}
177
178macro_rules! impl_arr_init {
179    (__impl $n: expr) => (
180        unsafe impl<T> FixedInitializer for [T;  $n] {
181            type Elem = T;
182            fn as_init_slice(&self) -> &[T] { self }
183            fn len() -> usize { $n }
184        }
185    );
186    () => ();
187    ($n: expr, $($m:expr,)*) => (
188        impl_arr_init!(__impl $n);
189        impl_arr_init!($($m,)*);
190    )
191
192}
193
194// For implementors: If you ever implement `FixedInitializer` for array lengths
195// > `isize::MAX` (e.g. once Rust adds const generics), you must update
196// `aview2` and `aview_mut2` to perform the necessary checks. In particular,
197// the assumption that `cols` can never exceed `isize::MAX` would be incorrect.
198// (Consider e.g. `let xs: &[[i32; ::std::usize::MAX]] = &[]`.)
199impl_arr_init!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,);
200
201/// Create a two-dimensional array with elements from `xs`.
202///
203/// ```
204/// use ndarray::arr2;
205///
206/// let a = arr2(&[[1, 2, 3],
207///                [4, 5, 6]]);
208/// assert!(
209///     a.shape() == [2, 3]
210/// );
211/// ```
212pub fn arr2<A: Clone, V: FixedInitializer<Elem = A>>(xs: &[V]) -> Array2<A>
213where
214    V: Clone,
215{
216    Array2::from(xs.to_vec())
217}
218
219impl<A, V> From<Vec<V>> for Array2<A>
220where
221    V: FixedInitializer<Elem = A>,
222{
223    /// Converts the `Vec` of arrays to an owned 2-D array.
224    ///
225    /// **Panics** if the product of non-zero axis lengths overflows `isize`.
226    fn from(mut xs: Vec<V>) -> Self {
227        let dim = Ix2(xs.len(), V::len());
228        let ptr = xs.as_mut_ptr();
229        let cap = xs.capacity();
230        let expand_len = dimension::size_of_shape_checked(&dim)
231            .expect("Product of non-zero axis lengths must not overflow isize.");
232        forget(xs);
233        unsafe {
234            let v = if size_of::<A>() == 0 {
235                Vec::from_raw_parts(ptr as *mut A, expand_len, expand_len)
236            } else if V::len() == 0 {
237                Vec::new()
238            } else {
239                // Guaranteed not to overflow in this case since A is non-ZST
240                // and Vec never allocates more than isize bytes.
241                let expand_cap = cap * V::len();
242                Vec::from_raw_parts(ptr as *mut A, expand_len, expand_cap)
243            };
244            ArrayBase::from_shape_vec_unchecked(dim, v)
245        }
246    }
247}
248
249impl<A, V, U> From<Vec<V>> for Array3<A>
250where
251    V: FixedInitializer<Elem = U>,
252    U: FixedInitializer<Elem = A>,
253{
254    /// Converts the `Vec` of arrays to an owned 3-D array.
255    ///
256    /// **Panics** if the product of non-zero axis lengths overflows `isize`.
257    fn from(mut xs: Vec<V>) -> Self {
258        let dim = Ix3(xs.len(), V::len(), U::len());
259        let ptr = xs.as_mut_ptr();
260        let cap = xs.capacity();
261        let expand_len = dimension::size_of_shape_checked(&dim)
262            .expect("Product of non-zero axis lengths must not overflow isize.");
263        forget(xs);
264        unsafe {
265            let v = if size_of::<A>() == 0 {
266                Vec::from_raw_parts(ptr as *mut A, expand_len, expand_len)
267            } else if V::len() == 0 || U::len() == 0 {
268                Vec::new()
269            } else {
270                // Guaranteed not to overflow in this case since A is non-ZST
271                // and Vec never allocates more than isize bytes.
272                let expand_cap = cap * V::len() * U::len();
273                Vec::from_raw_parts(ptr as *mut A, expand_len, expand_cap)
274            };
275            ArrayBase::from_shape_vec_unchecked(dim, v)
276        }
277    }
278}
279
280/// Create a two-dimensional array with elements from `xs`.
281///
282pub fn rcarr2<A: Clone, V: Clone + FixedInitializer<Elem = A>>(xs: &[V]) -> ArcArray2<A> {
283    arr2(xs).into_shared()
284}
285
286/// Create a three-dimensional array with elements from `xs`.
287///
288/// **Panics** if the slices are not all of the same length.
289///
290/// ```
291/// use ndarray::arr3;
292///
293/// let a = arr3(&[[[1, 2],
294///                 [3, 4]],
295///                [[5, 6],
296///                 [7, 8]],
297///                [[9, 0],
298///                 [1, 2]]]);
299/// assert!(
300///     a.shape() == [3, 2, 2]
301/// );
302/// ```
303pub fn arr3<A: Clone, V: FixedInitializer<Elem = U>, U: FixedInitializer<Elem = A>>(
304    xs: &[V],
305) -> Array3<A>
306where
307    V: Clone,
308    U: Clone,
309{
310    Array3::from(xs.to_vec())
311}
312
313/// Create a three-dimensional array with elements from `xs`.
314pub fn rcarr3<A: Clone, V: FixedInitializer<Elem = U>, U: FixedInitializer<Elem = A>>(
315    xs: &[V],
316) -> ArcArray<A, Ix3>
317where
318    V: Clone,
319    U: Clone,
320{
321    arr3(xs).into_shared()
322}