ndarray/
lib.rs

1// Copyright 2014-2020 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#![crate_name = "ndarray"]
9#![doc(html_root_url = "https://docs.rs/ndarray/0.15/")]
10#![doc(html_logo_url = "https://rust-ndarray.github.io/images/rust-ndarray_logo.svg")]
11#![allow(
12    clippy::many_single_char_names,
13    clippy::deref_addrof,
14    clippy::unreadable_literal,
15    clippy::manual_map, // is not an error
16    clippy::while_let_on_iterator, // is not an error
17    clippy::from_iter_instead_of_collect, // using from_iter is good style
18    clippy::redundant_closure, // false positives clippy #7812
19)]
20#![doc(test(attr(deny(warnings))))]
21#![doc(test(attr(allow(unused_variables))))]
22#![doc(test(attr(allow(deprecated))))]
23#![cfg_attr(not(feature = "std"), no_std)]
24
25//! The `ndarray` crate provides an *n*-dimensional container for general elements
26//! and for numerics.
27//!
28//! In *n*-dimensional we include, for example, 1-dimensional rows or columns,
29//! 2-dimensional matrices, and higher dimensional arrays. If the array has *n*
30//! dimensions, then an element in the array is accessed by using that many indices.
31//! Each dimension is also called an *axis*.
32//!
33//! - **[`ArrayBase`]**:
34//!   The *n*-dimensional array type itself.<br>
35//!   It is used to implement both the owned arrays and the views; see its docs
36//!   for an overview of all array features.<br>
37//! - The main specific array type is **[`Array`]**, which owns
38//! its elements.
39//!
40//! ## Highlights
41//!
42//! - Generic *n*-dimensional array
43//! - [Slicing](ArrayBase#slicing), also with arbitrary step size, and negative
44//!   indices to mean elements from the end of the axis.
45//! - Views and subviews of arrays; iterators that yield subviews.
46//! - Higher order operations and arithmetic are performant
47//! - Array views can be used to slice and mutate any `[T]` data using
48//!   `ArrayView::from` and `ArrayViewMut::from`.
49//! - [`Zip`] for lock step function application across two or more arrays or other
50//!   item producers ([`NdProducer`] trait).
51//!
52//! ## Crate Status
53//!
54//! - Still iterating on and evolving the crate
55//!   + The crate is continuously developing, and breaking changes are expected
56//!     during evolution from version to version. We adopt the newest stable
57//!     rust features if we need them.
58//!   + Note that functions/methods/traits/etc. hidden from the docs are not
59//!     considered part of the public API, so changes to them are not
60//!     considered breaking changes.
61//! - Performance:
62//!   + Prefer higher order methods and arithmetic operations on arrays first,
63//!     then iteration, and as a last priority using indexed algorithms.
64//!   + The higher order functions like [`.map()`](ArrayBase::map),
65//!     [`.map_inplace()`](ArrayBase::map_inplace), [`.zip_mut_with()`](ArrayBase::zip_mut_with),
66//!     [`Zip`] and [`azip!()`](azip) are the most efficient ways
67//!     to perform single traversal and lock step traversal respectively.
68//!   + Performance of an operation depends on the memory layout of the array
69//!     or array view. Especially if it's a binary operation, which
70//!     needs matching memory layout to be efficient (with some exceptions).
71//!   + Efficient floating point matrix multiplication even for very large
72//!     matrices; can optionally use BLAS to improve it further.
73//! - **Requires Rust 1.49 or later**
74//!
75//! ## Crate Feature Flags
76//!
77//! The following crate feature flags are available. They are configured in your
78//! `Cargo.toml`. See [`doc::crate_feature_flags`] for more information.
79//!
80//! - `std`: Rust standard library-using functionality (enabled by default)
81//! - `serde`: serialization support for serde 1.x
82//! - `rayon`: Parallel iterators, parallelized methods, the [`parallel`] module and [`par_azip!`].
83//! - `approx` Implementations of traits from version 0.4 of the [`approx`] crate.
84//! - `approx-0_5`: Implementations of traits from version 0.5 of the [`approx`] crate.
85//! - `blas`: transparent BLAS support for matrix multiplication, needs configuration.
86//! - `matrixmultiply-threading`: Use threading from `matrixmultiply`.
87//!
88//! ## Documentation
89//!
90//! * The docs for [`ArrayBase`] provide an overview of
91//!   the *n*-dimensional array type. Other good pages to look at are the
92//!   documentation for the [`s![]`](s!) and
93//!   [`azip!()`](azip!) macros.
94//!
95//! * If you have experience with NumPy, you may also be interested in
96//!   [`ndarray_for_numpy_users`](doc::ndarray_for_numpy_users).
97//!
98//! ## The ndarray ecosystem
99//!
100//! `ndarray` provides a lot of functionality, but it's not a one-stop solution.
101//!
102//! `ndarray` includes matrix multiplication and other binary/unary operations out of the box.
103//! More advanced linear algebra routines (e.g. SVD decomposition or eigenvalue computation)
104//! can be found in [`ndarray-linalg`](https://crates.io/crates/ndarray-linalg).
105//!
106//! The same holds for statistics: `ndarray` provides some basic functionalities (e.g. `mean`)
107//! but more advanced routines can be found in [`ndarray-stats`](https://crates.io/crates/ndarray-stats).
108//!
109//! If you are looking to generate random arrays instead, check out [`ndarray-rand`](https://crates.io/crates/ndarray-rand).
110//!
111//! For conversion between `ndarray`, [`nalgebra`](https://crates.io/crates/nalgebra) and
112//! [`image`](https://crates.io/crates/image) check out [`nshare`](https://crates.io/crates/nshare).
113
114
115extern crate alloc;
116
117#[cfg(feature = "std")]
118extern crate std;
119#[cfg(not(feature = "std"))]
120extern crate core as std;
121
122#[cfg(feature = "blas")]
123extern crate cblas_sys;
124
125#[cfg(feature = "docs")]
126pub mod doc;
127
128use std::marker::PhantomData;
129use alloc::sync::Arc;
130
131pub use crate::dimension::dim::*;
132pub use crate::dimension::{Axis, AxisDescription, Dimension, IntoDimension, RemoveAxis};
133pub use crate::dimension::{DimAdd, DimMax};
134
135pub use crate::dimension::IxDynImpl;
136pub use crate::dimension::NdIndex;
137pub use crate::error::{ErrorKind, ShapeError};
138pub use crate::indexes::{indices, indices_of};
139pub use crate::order::Order;
140pub use crate::slice::{
141    MultiSliceArg, NewAxis, Slice, SliceArg, SliceInfo, SliceInfoElem, SliceNextDim,
142};
143
144use crate::iterators::Baseiter;
145use crate::iterators::{ElementsBase, ElementsBaseMut, Iter, IterMut};
146
147pub use crate::arraytraits::AsArray;
148#[cfg(feature = "std")]
149pub use crate::linalg_traits::NdFloat;
150pub use crate::linalg_traits::LinalgScalar;
151
152#[allow(deprecated)] // stack_new_axis
153pub use crate::stacking::{concatenate, stack, stack_new_axis};
154
155pub use crate::math_cell::MathCell;
156pub use crate::impl_views::IndexLonger;
157pub use crate::shape_builder::{Shape, ShapeBuilder, ShapeArg, StrideShape};
158
159#[macro_use]
160mod macro_utils;
161#[macro_use]
162mod private;
163mod aliases;
164#[macro_use]
165mod itertools;
166mod argument_traits;
167#[cfg(feature = "serde")]
168mod array_serde;
169mod arrayformat;
170mod arraytraits;
171pub use crate::argument_traits::AssignElem;
172mod data_repr;
173mod data_traits;
174
175pub use crate::aliases::*;
176
177pub use crate::data_traits::{
178    Data, DataMut, DataOwned, DataShared, RawData, RawDataClone, RawDataMut,
179    RawDataSubst,
180};
181
182mod free_functions;
183pub use crate::free_functions::*;
184pub use crate::iterators::iter;
185
186mod error;
187mod extension;
188mod geomspace;
189mod indexes;
190mod iterators;
191mod layout;
192mod linalg_traits;
193mod linspace;
194mod logspace;
195mod math_cell;
196mod numeric_util;
197mod order;
198mod partial;
199mod shape_builder;
200#[macro_use]
201mod slice;
202mod split_at;
203mod stacking;
204mod low_level_util;
205#[macro_use]
206mod zip;
207
208mod dimension;
209
210pub use crate::zip::{FoldWhile, IntoNdProducer, NdProducer, Zip};
211
212pub use crate::layout::Layout;
213
214/// Implementation's prelude. Common types used everywhere.
215mod imp_prelude {
216    pub use crate::dimension::DimensionExt;
217    pub use crate::prelude::*;
218    pub use crate::ArcArray;
219    pub use crate::{
220        CowRepr, Data, DataMut, DataOwned, DataShared, Ix, Ixs, RawData, RawDataMut, RawViewRepr,
221        RemoveAxis, ViewRepr,
222    };
223}
224
225pub mod prelude;
226
227/// Array index type
228pub type Ix = usize;
229/// Array index type (signed)
230pub type Ixs = isize;
231
232/// An *n*-dimensional array.
233///
234/// The array is a general container of elements.
235/// The array supports arithmetic operations by applying them elementwise, if the
236/// elements are numeric, but it supports non-numeric elements too.
237///
238/// The arrays rarely grow or shrink, since those operations can be costly. On
239/// the other hand there is a rich set of methods and operations for taking views,
240/// slices, and making traversals over one or more arrays.
241///
242/// In *n*-dimensional we include for example 1-dimensional rows or columns,
243/// 2-dimensional matrices, and higher dimensional arrays. If the array has *n*
244/// dimensions, then an element is accessed by using that many indices.
245///
246/// The `ArrayBase<S, D>` is parameterized by `S` for the data container and
247/// `D` for the dimensionality.
248///
249/// Type aliases [`Array`], [`ArcArray`], [`CowArray`], [`ArrayView`], and
250/// [`ArrayViewMut`] refer to `ArrayBase` with different types for the data
251/// container: arrays with different kinds of ownership or different kinds of array views.
252///
253/// ## Contents
254///
255/// + [Array](#array)
256/// + [ArcArray](#arcarray)
257/// + [CowArray](#cowarray)
258/// + [Array Views](#array-views)
259/// + [Indexing and Dimension](#indexing-and-dimension)
260/// + [Loops, Producers and Iterators](#loops-producers-and-iterators)
261/// + [Slicing](#slicing)
262/// + [Subviews](#subviews)
263/// + [Arithmetic Operations](#arithmetic-operations)
264/// + [Broadcasting](#broadcasting)
265/// + [Conversions](#conversions)
266/// + [Constructor Methods for Owned Arrays](#constructor-methods-for-owned-arrays)
267/// + [Methods For All Array Types](#methods-for-all-array-types)
268/// + [Methods For 1-D Arrays](#methods-for-1-d-arrays)
269/// + [Methods For 2-D Arrays](#methods-for-2-d-arrays)
270/// + [Methods for Dynamic-Dimensional Arrays](#methods-for-dynamic-dimensional-arrays)
271/// + [Numerical Methods for Arrays](#numerical-methods-for-arrays)
272///
273/// ## `Array`
274///
275/// [`Array`] is an owned array that owns the underlying array
276/// elements directly (just like a `Vec`) and it is the default way to create and
277/// store n-dimensional data. `Array<A, D>` has two type parameters: `A` for
278/// the element type, and `D` for the dimensionality. A particular
279/// dimensionality's type alias like `Array3<A>` just has the type parameter
280/// `A` for element type.
281///
282/// An example:
283///
284/// ```
285/// // Create a three-dimensional f64 array, initialized with zeros
286/// use ndarray::Array3;
287/// let mut temperature = Array3::<f64>::zeros((3, 4, 5));
288/// // Increase the temperature in this location
289/// temperature[[2, 2, 2]] += 0.5;
290/// ```
291///
292/// ## `ArcArray`
293///
294/// [`ArcArray`] is an owned array with reference counted
295/// data (shared ownership).
296/// Sharing requires that it uses copy-on-write for mutable operations.
297/// Calling a method for mutating elements on `ArcArray`, for example
298/// [`view_mut()`](Self::view_mut) or [`get_mut()`](Self::get_mut),
299/// will break sharing and require a clone of the data (if it is not uniquely held).
300///
301/// ## `CowArray`
302///
303/// [`CowArray`] is analogous to [`std::borrow::Cow`].
304/// It can represent either an immutable view or a uniquely owned array. If a
305/// `CowArray` instance is the immutable view variant, then calling a method
306/// for mutating elements in the array will cause it to be converted into the
307/// owned variant (by cloning all the elements) before the modification is
308/// performed.
309///
310/// ## Array Views
311///
312/// [`ArrayView`] and [`ArrayViewMut`] are read-only and read-write array views
313/// respectively. They use dimensionality, indexing, and almost all other
314/// methods the same way as the other array types.
315///
316/// Methods for `ArrayBase` apply to array views too, when the trait bounds
317/// allow.
318///
319/// Please see the documentation for the respective array view for an overview
320/// of methods specific to array views: [`ArrayView`], [`ArrayViewMut`].
321///
322/// A view is created from an array using [`.view()`](ArrayBase::view),
323/// [`.view_mut()`](ArrayBase::view_mut), using
324/// slicing ([`.slice()`](ArrayBase::slice), [`.slice_mut()`](ArrayBase::slice_mut)) or from one of
325/// the many iterators that yield array views.
326///
327/// You can also create an array view from a regular slice of data not
328/// allocated with `Array` — see array view methods or their `From` impls.
329///
330/// Note that all `ArrayBase` variants can change their view (slicing) of the
331/// data freely, even when their data can’t be mutated.
332///
333/// ## Indexing and Dimension
334///
335/// The dimensionality of the array determines the number of *axes*, for example
336/// a 2D array has two axes. These are listed in “big endian” order, so that
337/// the greatest dimension is listed first, the lowest dimension with the most
338/// rapidly varying index is the last.
339///
340/// In a 2D array the index of each element is `[row, column]` as seen in this
341/// 4 × 3 example:
342///
343/// ```ignore
344/// [[ [0, 0], [0, 1], [0, 2] ],  // row 0
345///  [ [1, 0], [1, 1], [1, 2] ],  // row 1
346///  [ [2, 0], [2, 1], [2, 2] ],  // row 2
347///  [ [3, 0], [3, 1], [3, 2] ]]  // row 3
348/// //    \       \       \
349/// //   column 0  \     column 2
350/// //            column 1
351/// ```
352///
353/// The number of axes for an array is fixed by its `D` type parameter: `Ix1`
354/// for a 1D array, `Ix2` for a 2D array etc. The dimension type `IxDyn` allows
355/// a dynamic number of axes.
356///
357/// A fixed size array (`[usize; N]`) of the corresponding dimensionality is
358/// used to index the `Array`, making the syntax `array[[` i, j,  ...`]]`
359///
360/// ```
361/// use ndarray::Array2;
362/// let mut array = Array2::zeros((4, 3));
363/// array[[1, 1]] = 7;
364/// ```
365///
366/// Important traits and types for dimension and indexing:
367///
368/// - A [`struct@Dim`] value represents a dimensionality or index.
369/// - Trait [`Dimension`] is implemented by all
370/// dimensionalities. It defines many operations for dimensions and indices.
371/// - Trait [`IntoDimension`] is used to convert into a
372/// `Dim` value.
373/// - Trait [`ShapeBuilder`] is an extension of
374/// `IntoDimension` and is used when constructing an array. A shape describes
375/// not just the extent of each axis but also their strides.
376/// - Trait [`NdIndex`] is an extension of `Dimension` and is
377/// for values that can be used with indexing syntax.
378///
379///
380/// The default memory order of an array is *row major* order (a.k.a “c” order),
381/// where each row is contiguous in memory.
382/// A *column major* (a.k.a. “f” or fortran) memory order array has
383/// columns (or, in general, the outermost axis) with contiguous elements.
384///
385/// The logical order of any array’s elements is the row major order
386/// (the rightmost index is varying the fastest).
387/// The iterators `.iter(), .iter_mut()` always adhere to this order, for example.
388///
389/// ## Loops, Producers and Iterators
390///
391/// Using [`Zip`] is the most general way to apply a procedure
392/// across one or several arrays or *producers*.
393///
394/// [`NdProducer`] is like an iterable but for
395/// multidimensional data. All producers have dimensions and axes, like an
396/// array view, and they can be split and used with parallelization using `Zip`.
397///
398/// For example, `ArrayView<A, D>` is a producer, it has the same dimensions
399/// as the array view and for each iteration it produces a reference to
400/// the array element (`&A` in this case).
401///
402/// Another example, if we have a 10 × 10 array and use `.exact_chunks((2, 2))`
403/// we get a producer of chunks which has the dimensions 5 × 5 (because
404/// there are *10 / 2 = 5* chunks in either direction). The 5 × 5 chunks producer
405/// can be paired with any other producers of the same dimension with `Zip`, for
406/// example 5 × 5 arrays.
407///
408/// ### `.iter()` and `.iter_mut()`
409///
410/// These are the element iterators of arrays and they produce an element
411/// sequence in the logical order of the array, that means that the elements
412/// will be visited in the sequence that corresponds to increasing the
413/// last index first: *0, ..., 0,  0*; *0, ..., 0, 1*; *0, ...0, 2* and so on.
414///
415/// ### `.outer_iter()` and `.axis_iter()`
416///
417/// These iterators produce array views of one smaller dimension.
418///
419/// For example, for a 2D array, `.outer_iter()` will produce the 1D rows.
420/// For a 3D array, `.outer_iter()` produces 2D subviews.
421///
422/// `.axis_iter()` is like `outer_iter()` but allows you to pick which
423/// axis to traverse.
424///
425/// The `outer_iter` and `axis_iter` are one dimensional producers.
426///
427/// ## `.rows()`, `.columns()` and `.lanes()`
428///
429/// [`.rows()`][gr] is a producer (and iterable) of all rows in an array.
430///
431/// ```
432/// use ndarray::Array;
433///
434/// // 1. Loop over the rows of a 2D array
435/// let mut a = Array::zeros((10, 10));
436/// for mut row in a.rows_mut() {
437///     row.fill(1.);
438/// }
439///
440/// // 2. Use Zip to pair each row in 2D `a` with elements in 1D `b`
441/// use ndarray::Zip;
442/// let mut b = Array::zeros(a.nrows());
443///
444/// Zip::from(a.rows())
445///     .and(&mut b)
446///     .for_each(|a_row, b_elt| {
447///         *b_elt = a_row[a.ncols() - 1] - a_row[0];
448///     });
449/// ```
450///
451/// The *lanes* of an array are 1D segments along an axis and when pointed
452/// along the last axis they are *rows*, when pointed along the first axis
453/// they are *columns*.
454///
455/// A *m* × *n* array has *m* rows each of length *n* and conversely
456/// *n* columns each of length *m*.
457///
458/// To generalize this, we say that an array of dimension *a* × *m* × *n*
459/// has *a m* rows. It's composed of *a* times the previous array, so it
460/// has *a* times as many rows.
461///
462/// All methods: [`.rows()`][gr], [`.rows_mut()`][grm],
463/// [`.columns()`][gc], [`.columns_mut()`][gcm],
464/// [`.lanes(axis)`][l], [`.lanes_mut(axis)`][lm].
465///
466/// [gr]: Self::rows
467/// [grm]: Self::rows_mut
468/// [gc]: Self::columns
469/// [gcm]: Self::columns_mut
470/// [l]: Self::lanes
471/// [lm]: Self::lanes_mut
472///
473/// Yes, for 2D arrays `.rows()` and `.outer_iter()` have about the same
474/// effect:
475///
476///  + `rows()` is a producer with *n* - 1 dimensions of 1 dimensional items
477///  + `outer_iter()` is a producer with 1 dimension of *n* - 1 dimensional items
478///
479/// ## Slicing
480///
481/// You can use slicing to create a view of a subset of the data in
482/// the array. Slicing methods include [`.slice()`], [`.slice_mut()`],
483/// [`.slice_move()`], and [`.slice_collapse()`].
484///
485/// The slicing argument can be passed using the macro [`s![]`](s!),
486/// which will be used in all examples. (The explicit form is an instance of
487/// [`SliceInfo`] or another type which implements [`SliceArg`]; see their docs
488/// for more information.)
489///
490/// If a range is used, the axis is preserved. If an index is used, that index
491/// is selected and the axis is removed; this selects a subview. See
492/// [*Subviews*](#subviews) for more information about subviews. If a
493/// [`NewAxis`] instance is used, a new axis is inserted. Note that
494/// [`.slice_collapse()`] panics on `NewAxis` elements and behaves like
495/// [`.collapse_axis()`] by preserving the number of dimensions.
496///
497/// [`.slice()`]: Self::slice
498/// [`.slice_mut()`]: Self::slice_mut
499/// [`.slice_move()`]: Self::slice_move
500/// [`.slice_collapse()`]: Self::slice_collapse
501///
502/// When slicing arrays with generic dimensionality, creating an instance of
503/// [`SliceInfo`] to pass to the multi-axis slicing methods like [`.slice()`]
504/// is awkward. In these cases, it's usually more convenient to use
505/// [`.slice_each_axis()`]/[`.slice_each_axis_mut()`]/[`.slice_each_axis_inplace()`]
506/// or to create a view and then slice individual axes of the view using
507/// methods such as [`.slice_axis_inplace()`] and [`.collapse_axis()`].
508///
509/// [`.slice_each_axis()`]: Self::slice_each_axis
510/// [`.slice_each_axis_mut()`]: Self::slice_each_axis_mut
511/// [`.slice_each_axis_inplace()`]: Self::slice_each_axis_inplace
512/// [`.slice_axis_inplace()`]: Self::slice_axis_inplace
513/// [`.collapse_axis()`]: Self::collapse_axis
514///
515/// It's possible to take multiple simultaneous *mutable* slices with
516/// [`.multi_slice_mut()`] or (for [`ArrayViewMut`] only)
517/// [`.multi_slice_move()`].
518///
519/// [`.multi_slice_mut()`]: Self::multi_slice_mut
520/// [`.multi_slice_move()`]: ArrayViewMut#method.multi_slice_move
521///
522/// ```
523/// use ndarray::{arr2, arr3, s, ArrayBase, DataMut, Dimension, NewAxis, Slice};
524///
525/// // 2 submatrices of 2 rows with 3 elements per row, means a shape of `[2, 2, 3]`.
526///
527/// let a = arr3(&[[[ 1,  2,  3],     // -- 2 rows  \_
528///                 [ 4,  5,  6]],    // --         /
529///                [[ 7,  8,  9],     //            \_ 2 submatrices
530///                 [10, 11, 12]]]);  //            /
531/// //  3 columns ..../.../.../
532///
533/// assert_eq!(a.shape(), &[2, 2, 3]);
534///
535/// // Let’s create a slice with
536/// //
537/// // - Both of the submatrices of the greatest dimension: `..`
538/// // - Only the first row in each submatrix: `0..1`
539/// // - Every element in each row: `..`
540///
541/// let b = a.slice(s![.., 0..1, ..]);
542/// let c = arr3(&[[[ 1,  2,  3]],
543///                [[ 7,  8,  9]]]);
544/// assert_eq!(b, c);
545/// assert_eq!(b.shape(), &[2, 1, 3]);
546///
547/// // Let’s create a slice with
548/// //
549/// // - Both submatrices of the greatest dimension: `..`
550/// // - The last row in each submatrix: `-1..`
551/// // - Row elements in reverse order: `..;-1`
552/// let d = a.slice(s![.., -1.., ..;-1]);
553/// let e = arr3(&[[[ 6,  5,  4]],
554///                [[12, 11, 10]]]);
555/// assert_eq!(d, e);
556/// assert_eq!(d.shape(), &[2, 1, 3]);
557///
558/// // Let’s create a slice while selecting a subview and inserting a new axis with
559/// //
560/// // - Both submatrices of the greatest dimension: `..`
561/// // - The last row in each submatrix, removing that axis: `-1`
562/// // - Row elements in reverse order: `..;-1`
563/// // - A new axis at the end.
564/// let f = a.slice(s![.., -1, ..;-1, NewAxis]);
565/// let g = arr3(&[[ [6],  [5],  [4]],
566///                [[12], [11], [10]]]);
567/// assert_eq!(f, g);
568/// assert_eq!(f.shape(), &[2, 3, 1]);
569///
570/// // Let's take two disjoint, mutable slices of a matrix with
571/// //
572/// // - One containing all the even-index columns in the matrix
573/// // - One containing all the odd-index columns in the matrix
574/// let mut h = arr2(&[[0, 1, 2, 3],
575///                    [4, 5, 6, 7]]);
576/// let (s0, s1) = h.multi_slice_mut((s![.., ..;2], s![.., 1..;2]));
577/// let i = arr2(&[[0, 2],
578///                [4, 6]]);
579/// let j = arr2(&[[1, 3],
580///                [5, 7]]);
581/// assert_eq!(s0, i);
582/// assert_eq!(s1, j);
583///
584/// // Generic function which assigns the specified value to the elements which
585/// // have indices in the lower half along all axes.
586/// fn fill_lower<S, D>(arr: &mut ArrayBase<S, D>, x: S::Elem)
587/// where
588///     S: DataMut,
589///     S::Elem: Clone,
590///     D: Dimension,
591/// {
592///     arr.slice_each_axis_mut(|ax| Slice::from(0..ax.len / 2)).fill(x);
593/// }
594/// fill_lower(&mut h, 9);
595/// let k = arr2(&[[9, 9, 2, 3],
596///                [4, 5, 6, 7]]);
597/// assert_eq!(h, k);
598/// ```
599///
600/// ## Subviews
601///
602/// Subview methods allow you to restrict the array view while removing one
603/// axis from the array. Methods for selecting individual subviews include
604/// [`.index_axis()`], [`.index_axis_mut()`], [`.index_axis_move()`], and
605/// [`.index_axis_inplace()`]. You can also select a subview by using a single
606/// index instead of a range when slicing. Some other methods, such as
607/// [`.fold_axis()`], [`.axis_iter()`], [`.axis_iter_mut()`],
608/// [`.outer_iter()`], and [`.outer_iter_mut()`] operate on all the subviews
609/// along an axis.
610///
611/// A related method is [`.collapse_axis()`], which modifies the view in the
612/// same way as [`.index_axis()`] except for removing the collapsed axis, since
613/// it operates *in place*. The length of the axis becomes 1.
614///
615/// Methods for selecting an individual subview take two arguments: `axis` and
616/// `index`.
617///
618/// [`.axis_iter()`]: Self::axis_iter
619/// [`.axis_iter_mut()`]: Self::axis_iter_mut
620/// [`.fold_axis()`]: Self::fold_axis
621/// [`.index_axis()`]: Self::index_axis
622/// [`.index_axis_inplace()`]: Self::index_axis_inplace
623/// [`.index_axis_mut()`]: Self::index_axis_mut
624/// [`.index_axis_move()`]: Self::index_axis_move
625/// [`.collapse_axis()`]: Self::collapse_axis
626/// [`.outer_iter()`]: Self::outer_iter
627/// [`.outer_iter_mut()`]: Self::outer_iter_mut
628///
629/// ```
630///
631/// use ndarray::{arr3, aview1, aview2, s, Axis};
632///
633///
634/// // 2 submatrices of 2 rows with 3 elements per row, means a shape of `[2, 2, 3]`.
635///
636/// let a = arr3(&[[[ 1,  2,  3],    // \ axis 0, submatrix 0
637///                 [ 4,  5,  6]],   // /
638///                [[ 7,  8,  9],    // \ axis 0, submatrix 1
639///                 [10, 11, 12]]]); // /
640///         //        \
641///         //         axis 2, column 0
642///
643/// assert_eq!(a.shape(), &[2, 2, 3]);
644///
645/// // Let’s take a subview along the greatest dimension (axis 0),
646/// // taking submatrix 0, then submatrix 1
647///
648/// let sub_0 = a.index_axis(Axis(0), 0);
649/// let sub_1 = a.index_axis(Axis(0), 1);
650///
651/// assert_eq!(sub_0, aview2(&[[ 1,  2,  3],
652///                            [ 4,  5,  6]]));
653/// assert_eq!(sub_1, aview2(&[[ 7,  8,  9],
654///                            [10, 11, 12]]));
655/// assert_eq!(sub_0.shape(), &[2, 3]);
656///
657/// // This is the subview picking only axis 2, column 0
658/// let sub_col = a.index_axis(Axis(2), 0);
659///
660/// assert_eq!(sub_col, aview2(&[[ 1,  4],
661///                              [ 7, 10]]));
662///
663/// // You can take multiple subviews at once (and slice at the same time)
664/// let double_sub = a.slice(s![1, .., 0]);
665/// assert_eq!(double_sub, aview1(&[7, 10]));
666/// ```
667///
668/// ## Arithmetic Operations
669///
670/// Arrays support all arithmetic operations the same way: they apply elementwise.
671///
672/// Since the trait implementations are hard to overview, here is a summary.
673///
674/// ### Binary Operators with Two Arrays
675///
676/// Let `A` be an array or view of any kind. Let `B` be an array
677/// with owned storage (either `Array` or `ArcArray`).
678/// Let `C` be an array with mutable data (either `Array`, `ArcArray`
679/// or `ArrayViewMut`).
680/// The following combinations of operands
681/// are supported for an arbitrary binary operator denoted by `@` (it can be
682/// `+`, `-`, `*`, `/` and so on).
683///
684/// - `&A @ &A` which produces a new `Array`
685/// - `B @ A` which consumes `B`, updates it with the result, and returns it
686/// - `B @ &A` which consumes `B`, updates it with the result, and returns it
687/// - `C @= &A` which performs an arithmetic operation in place
688///
689/// Note that the element type needs to implement the operator trait and the
690/// `Clone` trait.
691///
692/// ```
693/// use ndarray::{array, ArrayView1};
694///
695/// let owned1 = array![1, 2];
696/// let owned2 = array![3, 4];
697/// let view1 = ArrayView1::from(&[5, 6]);
698/// let view2 = ArrayView1::from(&[7, 8]);
699/// let mut mutable = array![9, 10];
700///
701/// let sum1 = &view1 + &view2;   // Allocates a new array. Note the explicit `&`.
702/// // let sum2 = view1 + &view2; // This doesn't work because `view1` is not an owned array.
703/// let sum3 = owned1 + view1;    // Consumes `owned1`, updates it, and returns it.
704/// let sum4 = owned2 + &view2;   // Consumes `owned2`, updates it, and returns it.
705/// mutable += &view2;            // Updates `mutable` in-place.
706/// ```
707///
708/// ### Binary Operators with Array and Scalar
709///
710/// The trait [`ScalarOperand`] marks types that can be used in arithmetic
711/// with arrays directly. For a scalar `K` the following combinations of operands
712/// are supported (scalar can be on either the left or right side, but
713/// `ScalarOperand` docs has the detailed conditions).
714///
715/// - `&A @ K` or `K @ &A` which produces a new `Array`
716/// - `B @ K` or `K @ B` which consumes `B`, updates it with the result and returns it
717/// - `C @= K` which performs an arithmetic operation in place
718///
719/// ### Unary Operators
720///
721/// Let `A` be an array or view of any kind. Let `B` be an array with owned
722/// storage (either `Array` or `ArcArray`). The following operands are supported
723/// for an arbitrary unary operator denoted by `@` (it can be `-` or `!`).
724///
725/// - `@&A` which produces a new `Array`
726/// - `@B` which consumes `B`, updates it with the result, and returns it
727///
728/// ## Broadcasting
729///
730/// Arrays support limited *broadcasting*, where arithmetic operations with
731/// array operands of different sizes can be carried out by repeating the
732/// elements of the smaller dimension array. See
733/// [`.broadcast()`](Self::broadcast) for a more detailed
734/// description.
735///
736/// ```
737/// use ndarray::arr2;
738///
739/// let a = arr2(&[[1., 1.],
740///                [1., 2.],
741///                [0., 3.],
742///                [0., 4.]]);
743///
744/// let b = arr2(&[[0., 1.]]);
745///
746/// let c = arr2(&[[1., 2.],
747///                [1., 3.],
748///                [0., 4.],
749///                [0., 5.]]);
750/// // We can add because the shapes are compatible even if not equal.
751/// // The `b` array is shape 1 × 2 but acts like a 4 × 2 array.
752/// assert!(
753///     c == a + b
754/// );
755/// ```
756///
757/// ## Conversions
758///
759/// ### Conversions Between Array Types
760///
761/// This table is a summary of the conversions between arrays of different
762/// ownership, dimensionality, and element type. All of the conversions in this
763/// table preserve the shape of the array.
764///
765/// <table>
766/// <tr>
767/// <th rowspan="2">Output</th>
768/// <th colspan="5">Input</th>
769/// </tr>
770///
771/// <tr>
772/// <td>
773///
774/// `Array<A, D>`
775///
776/// </td>
777/// <td>
778///
779/// `ArcArray<A, D>`
780///
781/// </td>
782/// <td>
783///
784/// `CowArray<'a, A, D>`
785///
786/// </td>
787/// <td>
788///
789/// `ArrayView<'a, A, D>`
790///
791/// </td>
792/// <td>
793///
794/// `ArrayViewMut<'a, A, D>`
795///
796/// </td>
797/// </tr>
798///
799/// <!--Conversions to `Array<A, D>`-->
800///
801/// <tr>
802/// <td>
803///
804/// `Array<A, D>`
805///
806/// </td>
807/// <td>
808///
809/// no-op
810///
811/// </td>
812/// <td>
813///
814/// [`a.into_owned()`][.into_owned()]
815///
816/// </td>
817/// <td>
818///
819/// [`a.into_owned()`][.into_owned()]
820///
821/// </td>
822/// <td>
823///
824/// [`a.to_owned()`][.to_owned()]
825///
826/// </td>
827/// <td>
828///
829/// [`a.to_owned()`][.to_owned()]
830///
831/// </td>
832/// </tr>
833///
834/// <!--Conversions to `ArcArray<A, D>`-->
835///
836/// <tr>
837/// <td>
838///
839/// `ArcArray<A, D>`
840///
841/// </td>
842/// <td>
843///
844/// [`a.into_shared()`][.into_shared()]
845///
846/// </td>
847/// <td>
848///
849/// no-op
850///
851/// </td>
852/// <td>
853///
854/// [`a.into_owned().into_shared()`][.into_shared()]
855///
856/// </td>
857/// <td>
858///
859/// [`a.to_owned().into_shared()`][.into_shared()]
860///
861/// </td>
862/// <td>
863///
864/// [`a.to_owned().into_shared()`][.into_shared()]
865///
866/// </td>
867/// </tr>
868///
869/// <!--Conversions to `CowArray<'a, A, D>`-->
870///
871/// <tr>
872/// <td>
873///
874/// `CowArray<'a, A, D>`
875///
876/// </td>
877/// <td>
878///
879/// [`CowArray::from(a)`](CowArray#impl-From<ArrayBase<OwnedRepr<A>%2C%20D>>)
880///
881/// </td>
882/// <td>
883///
884/// [`CowArray::from(a.into_owned())`](CowArray#impl-From<ArrayBase<OwnedRepr<A>%2C%20D>>)
885///
886/// </td>
887/// <td>
888///
889/// no-op
890///
891/// </td>
892/// <td>
893///
894/// [`CowArray::from(a)`](CowArray#impl-From<ArrayBase<ViewRepr<%26%27a%20A>%2C%20D>>)
895///
896/// </td>
897/// <td>
898///
899/// [`CowArray::from(a.view())`](CowArray#impl-From<ArrayBase<ViewRepr<%26%27a%20A>%2C%20D>>)
900///
901/// </td>
902/// </tr>
903///
904/// <!--Conversions to `ArrayView<'b, A, D>`-->
905///
906/// <tr>
907/// <td>
908///
909/// `ArrayView<'b, A, D>`
910///
911/// </td>
912/// <td>
913///
914/// [`a.view()`][.view()]
915///
916/// </td>
917/// <td>
918///
919/// [`a.view()`][.view()]
920///
921/// </td>
922/// <td>
923///
924/// [`a.view()`][.view()]
925///
926/// </td>
927/// <td>
928///
929/// [`a.view()`][.view()] or [`a.reborrow()`][ArrayView::reborrow()]
930///
931/// </td>
932/// <td>
933///
934/// [`a.view()`][.view()]
935///
936/// </td>
937/// </tr>
938///
939/// <!--Conversions to `ArrayViewMut<'b, A, D>`-->
940///
941/// <tr>
942/// <td>
943///
944/// `ArrayViewMut<'b, A, D>`
945///
946/// </td>
947/// <td>
948///
949/// [`a.view_mut()`][.view_mut()]
950///
951/// </td>
952/// <td>
953///
954/// [`a.view_mut()`][.view_mut()]
955///
956/// </td>
957/// <td>
958///
959/// [`a.view_mut()`][.view_mut()]
960///
961/// </td>
962/// <td>
963///
964/// illegal
965///
966/// </td>
967/// <td>
968///
969/// [`a.view_mut()`][.view_mut()] or [`a.reborrow()`][ArrayViewMut::reborrow()]
970///
971/// </td>
972/// </tr>
973///
974/// <!--Conversions to equivalent with dim `D2`-->
975///
976/// <tr>
977/// <td>
978///
979/// equivalent with dim `D2` (e.g. converting from dynamic dim to const dim)
980///
981/// </td>
982/// <td colspan="5">
983///
984/// [`a.into_dimensionality::<D2>()`][.into_dimensionality()]
985///
986/// </td>
987/// </tr>
988///
989/// <!--Conversions to equivalent with dim `IxDyn`-->
990///
991/// <tr>
992/// <td>
993///
994/// equivalent with dim `IxDyn`
995///
996/// </td>
997/// <td colspan="5">
998///
999/// [`a.into_dyn()`][.into_dyn()]
1000///
1001/// </td>
1002/// </tr>
1003///
1004/// <!--Conversions to `Array<B, D>`-->
1005///
1006/// <tr>
1007/// <td>
1008///
1009/// `Array<B, D>` (new element type)
1010///
1011/// </td>
1012/// <td colspan="5">
1013///
1014/// [`a.map(|x| x.do_your_conversion())`][.map()]
1015///
1016/// </td>
1017/// </tr>
1018/// </table>
1019///
1020/// ### Conversions Between Arrays and `Vec`s/Slices/Scalars
1021///
1022/// This is a table of the safe conversions between arrays and
1023/// `Vec`s/slices/scalars. Note that some of the return values are actually
1024/// `Result`/`Option` wrappers around the indicated output types.
1025///
1026/// Input | Output | Methods
1027/// ------|--------|--------
1028/// `Vec<A>` | `ArrayBase<S: DataOwned, Ix1>` | [`::from_vec()`](Self::from_vec)
1029/// `Vec<A>` | `ArrayBase<S: DataOwned, D>` | [`::from_shape_vec()`](Self::from_shape_vec)
1030/// `&[A]` | `ArrayView1<A>` | [`::from()`](ArrayView#method.from)
1031/// `&[A]` | `ArrayView<A, D>` | [`::from_shape()`](ArrayView#method.from_shape)
1032/// `&mut [A]` | `ArrayViewMut1<A>` | [`::from()`](ArrayViewMut#method.from)
1033/// `&mut [A]` | `ArrayViewMut<A, D>` | [`::from_shape()`](ArrayViewMut#method.from_shape)
1034/// `&ArrayBase<S, Ix1>` | `Vec<A>` | [`.to_vec()`](Self::to_vec)
1035/// `Array<A, D>` | `Vec<A>` | [`.into_raw_vec()`](Array#method.into_raw_vec)<sup>[1](#into_raw_vec)</sup>
1036/// `&ArrayBase<S, D>` | `&[A]` | [`.as_slice()`](Self::as_slice)<sup>[2](#req_contig_std)</sup>, [`.as_slice_memory_order()`](Self::as_slice_memory_order)<sup>[3](#req_contig)</sup>
1037/// `&mut ArrayBase<S: DataMut, D>` | `&mut [A]` | [`.as_slice_mut()`](Self::as_slice_mut)<sup>[2](#req_contig_std)</sup>, [`.as_slice_memory_order_mut()`](Self::as_slice_memory_order_mut)<sup>[3](#req_contig)</sup>
1038/// `ArrayView<A, D>` | `&[A]` | [`.to_slice()`](ArrayView#method.to_slice)<sup>[2](#req_contig_std)</sup>
1039/// `ArrayViewMut<A, D>` | `&mut [A]` | [`.into_slice()`](ArrayViewMut#method.into_slice)<sup>[2](#req_contig_std)</sup>
1040/// `Array0<A>` | `A` | [`.into_scalar()`](Array#method.into_scalar)
1041///
1042/// <sup><a name="into_raw_vec">1</a></sup>Returns the data in memory order.
1043///
1044/// <sup><a name="req_contig_std">2</a></sup>Works only if the array is
1045/// contiguous and in standard order.
1046///
1047/// <sup><a name="req_contig">3</a></sup>Works only if the array is contiguous.
1048///
1049/// The table above does not include all the constructors; it only shows
1050/// conversions to/from `Vec`s/slices. See
1051/// [below](#constructor-methods-for-owned-arrays) for more constructors.
1052///
1053/// [ArrayView::reborrow()]: ArrayView#method.reborrow
1054/// [ArrayViewMut::reborrow()]: ArrayViewMut#method.reborrow
1055/// [.into_dimensionality()]: Self::into_dimensionality
1056/// [.into_dyn()]: Self::into_dyn
1057/// [.into_owned()]: Self::into_owned
1058/// [.into_shared()]: Self::into_shared
1059/// [.to_owned()]: Self::to_owned
1060/// [.map()]: Self::map
1061/// [.view()]: Self::view
1062/// [.view_mut()]: Self::view_mut
1063///
1064/// ### Conversions from Nested `Vec`s/`Array`s
1065///
1066/// It's generally a good idea to avoid nested `Vec`/`Array` types, such as
1067/// `Vec<Vec<A>>` or `Vec<Array2<A>>` because:
1068///
1069/// * they require extra heap allocations compared to a single `Array`,
1070///
1071/// * they can scatter data all over memory (because of multiple allocations),
1072///
1073/// * they cause unnecessary indirection (traversing multiple pointers to reach
1074///   the data),
1075///
1076/// * they don't enforce consistent shape within the nested
1077///   `Vec`s/`ArrayBase`s, and
1078///
1079/// * they are generally more difficult to work with.
1080///
1081/// The most common case where users might consider using nested
1082/// `Vec`s/`Array`s is when creating an array by appending rows/subviews in a
1083/// loop, where the rows/subviews are computed within the loop. However, there
1084/// are better ways than using nested `Vec`s/`Array`s.
1085///
1086/// If you know ahead-of-time the shape of the final array, the cleanest
1087/// solution is to allocate the final array before the loop, and then assign
1088/// the data to it within the loop, like this:
1089///
1090/// ```rust
1091/// use ndarray::{array, Array2, Axis};
1092///
1093/// let mut arr = Array2::zeros((2, 3));
1094/// for (i, mut row) in arr.axis_iter_mut(Axis(0)).enumerate() {
1095///     // Perform calculations and assign to `row`; this is a trivial example:
1096///     row.fill(i);
1097/// }
1098/// assert_eq!(arr, array![[0, 0, 0], [1, 1, 1]]);
1099/// ```
1100///
1101/// If you don't know ahead-of-time the shape of the final array, then the
1102/// cleanest solution is generally to append the data to a flat `Vec`, and then
1103/// convert it to an `Array` at the end with
1104/// [`::from_shape_vec()`](Self::from_shape_vec). You just have to be careful
1105/// that the layout of the data (the order of the elements in the flat `Vec`)
1106/// is correct.
1107///
1108/// ```rust
1109/// use ndarray::{array, Array2};
1110///
1111/// let ncols = 3;
1112/// let mut data = Vec::new();
1113/// let mut nrows = 0;
1114/// for i in 0..2 {
1115///     // Compute `row` and append it to `data`; this is a trivial example:
1116///     let row = vec![i; ncols];
1117///     data.extend_from_slice(&row);
1118///     nrows += 1;
1119/// }
1120/// let arr = Array2::from_shape_vec((nrows, ncols), data)?;
1121/// assert_eq!(arr, array![[0, 0, 0], [1, 1, 1]]);
1122/// # Ok::<(), ndarray::ShapeError>(())
1123/// ```
1124///
1125/// If neither of these options works for you, and you really need to convert
1126/// nested `Vec`/`Array` instances to an `Array`, the cleanest solution is
1127/// generally to use [`Iterator::flatten()`]
1128/// to get a flat `Vec`, and then convert the `Vec` to an `Array` with
1129/// [`::from_shape_vec()`](Self::from_shape_vec), like this:
1130///
1131/// ```rust
1132/// use ndarray::{array, Array2, Array3};
1133///
1134/// let nested: Vec<Array2<i32>> = vec![
1135///     array![[1, 2, 3], [4, 5, 6]],
1136///     array![[7, 8, 9], [10, 11, 12]],
1137/// ];
1138/// let inner_shape = nested[0].dim();
1139/// let shape = (nested.len(), inner_shape.0, inner_shape.1);
1140/// let flat: Vec<i32> = nested.iter().flatten().cloned().collect();
1141/// let arr = Array3::from_shape_vec(shape, flat)?;
1142/// assert_eq!(arr, array![
1143///     [[1, 2, 3], [4, 5, 6]],
1144///     [[7, 8, 9], [10, 11, 12]],
1145/// ]);
1146/// # Ok::<(), ndarray::ShapeError>(())
1147/// ```
1148///
1149/// Note that this implementation assumes that the nested `Vec`s are all the
1150/// same shape and that the `Vec` is non-empty. Depending on your application,
1151/// it may be a good idea to add checks for these assumptions and possibly
1152/// choose a different way to handle the empty case.
1153///
1154// # For implementors
1155//
1156// All methods must uphold the following constraints:
1157//
1158// 1. `data` must correctly represent the data buffer / ownership information,
1159//    `ptr` must point into the data represented by `data`, and the `dim` and
1160//    `strides` must be consistent with `data`. For example,
1161//
1162//    * If `data` is `OwnedRepr<A>`, all elements represented by `ptr`, `dim`,
1163//      and `strides` must be owned by the `Vec` and not aliased by multiple
1164//      indices.
1165//
1166//    * If `data` is `ViewRepr<&'a mut A>`, all elements represented by `ptr`,
1167//      `dim`, and `strides` must be exclusively borrowed and not aliased by
1168//      multiple indices.
1169//
1170// 2. If the type of `data` implements `Data`, then `ptr` must be aligned.
1171//
1172// 3. `ptr` must be non-null, and it must be safe to [`.offset()`] `ptr` by
1173//    zero.
1174//
1175// 4. It must be safe to [`.offset()`] the pointer repeatedly along all axes
1176//    and calculate the `count`s for the `.offset()` calls without overflow,
1177//    even if the array is empty or the elements are zero-sized.
1178//
1179//    More specifically, the set of all possible (signed) offset counts
1180//    relative to `ptr` can be determined by the following (the casts and
1181//    arithmetic must not overflow):
1182//
1183//    ```rust
1184//    /// Returns all the possible offset `count`s relative to `ptr`.
1185//    fn all_offset_counts(shape: &[usize], strides: &[isize]) -> BTreeSet<isize> {
1186//        assert_eq!(shape.len(), strides.len());
1187//        let mut all_offsets = BTreeSet::<isize>::new();
1188//        all_offsets.insert(0);
1189//        for axis in 0..shape.len() {
1190//            let old_offsets = all_offsets.clone();
1191//            for index in 0..shape[axis] {
1192//                assert!(index <= isize::MAX as usize);
1193//                let off = (index as isize).checked_mul(strides[axis]).unwrap();
1194//                for &old_offset in &old_offsets {
1195//                    all_offsets.insert(old_offset.checked_add(off).unwrap());
1196//                }
1197//            }
1198//        }
1199//        all_offsets
1200//    }
1201//    ```
1202//
1203//    Note that it must be safe to offset the pointer *repeatedly* along all
1204//    axes, so in addition for it being safe to offset `ptr` by each of these
1205//    counts, the difference between the least and greatest address reachable
1206//    by these offsets in units of `A` and in units of bytes must not be
1207//    greater than `isize::MAX`.
1208//
1209//    In other words,
1210//
1211//    * All possible pointers generated by moving along all axes must be in
1212//      bounds or one byte past the end of a single allocation with element
1213//      type `A`. The only exceptions are if the array is empty or the element
1214//      type is zero-sized. In these cases, `ptr` may be dangling, but it must
1215//      still be safe to [`.offset()`] the pointer along the axes.
1216//
1217//    * The offset in units of bytes between the least address and greatest
1218//      address by moving along all axes must not exceed `isize::MAX`. This
1219//      constraint prevents the computed offset, in bytes, from overflowing
1220//      `isize` regardless of the starting point due to past offsets.
1221//
1222//    * The offset in units of `A` between the least address and greatest
1223//      address by moving along all axes must not exceed `isize::MAX`. This
1224//      constraint prevents overflow when calculating the `count` parameter to
1225//      [`.offset()`] regardless of the starting point due to past offsets.
1226//
1227//    For example, if the shape is [2, 0, 3] and the strides are [3, 6, -1],
1228//    the offsets of interest relative to `ptr` are -2, -1, 0, 1, 2, 3. So,
1229//    `ptr.offset(-2)`, `ptr.offset(-1)`, …, `ptr.offset(3)` must be pointers
1230//    within a single allocation with element type `A`; `(3 - (-2)) *
1231//    size_of::<A>()` must not exceed `isize::MAX`, and `3 - (-2)` must not
1232//    exceed `isize::MAX`. Note that this is a requirement even though the
1233//    array is empty (axis 1 has length 0).
1234//
1235//    A dangling pointer can be used when creating an empty array, but this
1236//    usually means all the strides have to be zero. A dangling pointer that
1237//    can safely be offset by zero bytes can be constructed with
1238//    `::std::ptr::NonNull::<A>::dangling().as_ptr()`. (It isn't entirely clear
1239//    from the documentation that a pointer created this way is safe to
1240//    `.offset()` at all, even by zero bytes, but the implementation of
1241//    `Vec<A>` does this, so we can too. See rust-lang/rust#54857 for details.)
1242//
1243// 5. The product of non-zero axis lengths must not exceed `isize::MAX`. (This
1244//    also implies that the length of any individual axis must not exceed
1245//    `isize::MAX`, and an array can contain at most `isize::MAX` elements.)
1246//    This constraint makes various calculations easier because they don't have
1247//    to worry about overflow and axis lengths can be freely cast to `isize`.
1248//
1249// Constraints 2–5 are carefully designed such that if they're upheld for the
1250// array, they're also upheld for any subset of axes of the array as well as
1251// slices/subviews/reshapes of the array. This is important for iterators that
1252// produce subviews (and other similar cases) to be safe without extra (easy to
1253// forget) checks for zero-length axes. Constraint 1 is similarly upheld for
1254// any subset of axes and slices/subviews/reshapes, except when removing a
1255// zero-length axis (since if the other axes are non-zero-length, that would
1256// allow accessing elements that should not be possible to access).
1257//
1258// Method/function implementations can rely on these constraints being upheld.
1259// The constraints can be temporarily violated within a method/function
1260// implementation since `ArrayBase` doesn't implement `Drop` and `&mut
1261// ArrayBase` is `!UnwindSafe`, but the implementation must not call
1262// methods/functions on the array while it violates the constraints.
1263//
1264// Users of the `ndarray` crate cannot rely on these constraints because they
1265// may change in the future.
1266//
1267// [`.offset()`]: https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.offset-1
1268pub struct ArrayBase<S, D>
1269where
1270    S: RawData,
1271{
1272    /// Data buffer / ownership information. (If owned, contains the data
1273    /// buffer; if borrowed, contains the lifetime and mutability.)
1274    data: S,
1275    /// A non-null pointer into the buffer held by `data`; may point anywhere
1276    /// in its range. If `S: Data`, this pointer must be aligned.
1277    ptr: std::ptr::NonNull<S::Elem>,
1278    /// The lengths of the axes.
1279    dim: D,
1280    /// The element count stride per axis. To be parsed as `isize`.
1281    strides: D,
1282}
1283
1284/// An array where the data has shared ownership and is copy on write.
1285///
1286/// The `ArcArray<A, D>` is parameterized by `A` for the element type and `D` for
1287/// the dimensionality.
1288///
1289/// It can act as both an owner as the data as well as a shared reference (view
1290/// like).
1291/// Calling a method for mutating elements on `ArcArray`, for example
1292/// [`view_mut()`](ArrayBase::view_mut) or
1293/// [`get_mut()`](ArrayBase::get_mut), will break sharing and
1294/// require a clone of the data (if it is not uniquely held).
1295///
1296/// `ArcArray` uses atomic reference counting like `Arc`, so it is `Send` and
1297/// `Sync` (when allowed by the element type of the array too).
1298///
1299/// **[`ArrayBase`]** is used to implement both the owned
1300/// arrays and the views; see its docs for an overview of all array features.
1301///
1302/// See also:
1303///
1304/// + [Constructor Methods for Owned Arrays](ArrayBase#constructor-methods-for-owned-arrays)
1305/// + [Methods For All Array Types](ArrayBase#methods-for-all-array-types)
1306pub type ArcArray<A, D> = ArrayBase<OwnedArcRepr<A>, D>;
1307
1308/// An array that owns its data uniquely.
1309///
1310/// `Array` is the main n-dimensional array type, and it owns all its array
1311/// elements.
1312///
1313/// The `Array<A, D>` is parameterized by `A` for the element type and `D` for
1314/// the dimensionality.
1315///
1316/// **[`ArrayBase`]** is used to implement both the owned
1317/// arrays and the views; see its docs for an overview of all array features.
1318///
1319/// See also:
1320///
1321/// + [Constructor Methods for Owned Arrays](ArrayBase#constructor-methods-for-owned-arrays)
1322/// + [Methods For All Array Types](ArrayBase#methods-for-all-array-types)
1323/// + Dimensionality-specific type alises
1324/// [`Array1`],
1325/// [`Array2`],
1326/// [`Array3`], ...,
1327/// [`ArrayD`],
1328/// and so on.
1329pub type Array<A, D> = ArrayBase<OwnedRepr<A>, D>;
1330
1331/// An array with copy-on-write behavior.
1332///
1333/// An `CowArray` represents either a uniquely owned array or a view of an
1334/// array. The `'a` corresponds to the lifetime of the view variant.
1335///
1336/// This type is analogous to [`std::borrow::Cow`].
1337/// If a `CowArray` instance is the immutable view variant, then calling a
1338/// method for mutating elements in the array will cause it to be converted
1339/// into the owned variant (by cloning all the elements) before the
1340/// modification is performed.
1341///
1342/// Array views have all the methods of an array (see [`ArrayBase`]).
1343///
1344/// See also [`ArcArray`], which also provides
1345/// copy-on-write behavior but has a reference-counted pointer to the data
1346/// instead of either a view or a uniquely owned copy.
1347pub type CowArray<'a, A, D> = ArrayBase<CowRepr<'a, A>, D>;
1348
1349/// A read-only array view.
1350///
1351/// An array view represents an array or a part of it, created from
1352/// an iterator, subview or slice of an array.
1353///
1354/// The `ArrayView<'a, A, D>` is parameterized by `'a` for the scope of the
1355/// borrow, `A` for the element type and `D` for the dimensionality.
1356///
1357/// Array views have all the methods of an array (see [`ArrayBase`]).
1358///
1359/// See also [`ArrayViewMut`].
1360pub type ArrayView<'a, A, D> = ArrayBase<ViewRepr<&'a A>, D>;
1361
1362/// A read-write array view.
1363///
1364/// An array view represents an array or a part of it, created from
1365/// an iterator, subview or slice of an array.
1366///
1367/// The `ArrayViewMut<'a, A, D>` is parameterized by `'a` for the scope of the
1368/// borrow, `A` for the element type and `D` for the dimensionality.
1369///
1370/// Array views have all the methods of an array (see [`ArrayBase`]).
1371///
1372/// See also [`ArrayView`].
1373pub type ArrayViewMut<'a, A, D> = ArrayBase<ViewRepr<&'a mut A>, D>;
1374
1375/// A read-only array view without a lifetime.
1376///
1377/// This is similar to [`ArrayView`] but does not carry any lifetime or
1378/// ownership information, and its data cannot be read without an unsafe
1379/// conversion into an [`ArrayView`]. The relationship between `RawArrayView`
1380/// and [`ArrayView`] is somewhat analogous to the relationship between `*const
1381/// T` and `&T`, but `RawArrayView` has additional requirements that `*const T`
1382/// does not, such as non-nullness.
1383///
1384/// The `RawArrayView<A, D>` is parameterized by `A` for the element type and
1385/// `D` for the dimensionality.
1386///
1387/// Raw array views have all the methods of an array (see
1388/// [`ArrayBase`]).
1389///
1390/// See also [`RawArrayViewMut`].
1391///
1392/// # Warning
1393///
1394/// You can't use this type with an arbitrary raw pointer; see
1395/// [`from_shape_ptr`](#method.from_shape_ptr) for details.
1396pub type RawArrayView<A, D> = ArrayBase<RawViewRepr<*const A>, D>;
1397
1398/// A mutable array view without a lifetime.
1399///
1400/// This is similar to [`ArrayViewMut`] but does not carry any lifetime or
1401/// ownership information, and its data cannot be read/written without an
1402/// unsafe conversion into an [`ArrayViewMut`]. The relationship between
1403/// `RawArrayViewMut` and [`ArrayViewMut`] is somewhat analogous to the
1404/// relationship between `*mut T` and `&mut T`, but `RawArrayViewMut` has
1405/// additional requirements that `*mut T` does not, such as non-nullness.
1406///
1407/// The `RawArrayViewMut<A, D>` is parameterized by `A` for the element type
1408/// and `D` for the dimensionality.
1409///
1410/// Raw array views have all the methods of an array (see
1411/// [`ArrayBase`]).
1412///
1413/// See also [`RawArrayView`].
1414///
1415/// # Warning
1416///
1417/// You can't use this type with an arbitrary raw pointer; see
1418/// [`from_shape_ptr`](#method.from_shape_ptr) for details.
1419pub type RawArrayViewMut<A, D> = ArrayBase<RawViewRepr<*mut A>, D>;
1420
1421pub use data_repr::OwnedRepr;
1422
1423/// ArcArray's representation.
1424///
1425/// *Don’t use this type directly—use the type alias
1426/// [`ArcArray`] for the array type!*
1427#[derive(Debug)]
1428pub struct OwnedArcRepr<A>(Arc<OwnedRepr<A>>);
1429
1430impl<A> Clone for OwnedArcRepr<A> {
1431    fn clone(&self) -> Self {
1432        OwnedArcRepr(self.0.clone())
1433    }
1434}
1435
1436/// Array pointer’s representation.
1437///
1438/// *Don’t use this type directly—use the type aliases
1439/// [`RawArrayView`] / [`RawArrayViewMut`] for the array type!*
1440#[derive(Copy, Clone)]
1441// This is just a marker type, to carry the mutability and element type.
1442pub struct RawViewRepr<A> {
1443    ptr: PhantomData<A>,
1444}
1445
1446impl<A> RawViewRepr<A> {
1447    #[inline(always)]
1448    fn new() -> Self {
1449        RawViewRepr { ptr: PhantomData }
1450    }
1451}
1452
1453/// Array view’s representation.
1454///
1455/// *Don’t use this type directly—use the type aliases
1456/// [`ArrayView`] / [`ArrayViewMut`] for the array type!*
1457#[derive(Copy, Clone)]
1458// This is just a marker type, to carry the lifetime parameter.
1459pub struct ViewRepr<A> {
1460    life: PhantomData<A>,
1461}
1462
1463impl<A> ViewRepr<A> {
1464    #[inline(always)]
1465    fn new() -> Self {
1466        ViewRepr { life: PhantomData }
1467    }
1468}
1469
1470/// CowArray's representation.
1471///
1472/// *Don't use this type directly—use the type alias
1473/// [`CowArray`] for the array type!*
1474pub enum CowRepr<'a, A> {
1475    /// Borrowed data.
1476    View(ViewRepr<&'a A>),
1477    /// Owned data.
1478    Owned(OwnedRepr<A>),
1479}
1480
1481impl<'a, A> CowRepr<'a, A> {
1482    /// Returns `true` iff the data is the `View` variant.
1483    pub fn is_view(&self) -> bool {
1484        match self {
1485            CowRepr::View(_) => true,
1486            CowRepr::Owned(_) => false,
1487        }
1488    }
1489
1490    /// Returns `true` iff the data is the `Owned` variant.
1491    pub fn is_owned(&self) -> bool {
1492        match self {
1493            CowRepr::View(_) => false,
1494            CowRepr::Owned(_) => true,
1495        }
1496    }
1497}
1498
1499// NOTE: The order of modules decides in which order methods on the type ArrayBase
1500// (mainly mentioning that as the most relevant type) show up in the documentation.
1501// Consider the doc effect of ordering modules here.
1502mod impl_clone;
1503
1504mod impl_internal_constructors;
1505mod impl_constructors;
1506
1507mod impl_methods;
1508mod impl_owned_array;
1509mod impl_special_element_types;
1510
1511/// Private Methods
1512impl<A, S, D> ArrayBase<S, D>
1513where
1514    S: Data<Elem = A>,
1515    D: Dimension,
1516{
1517    #[inline]
1518    fn broadcast_unwrap<E>(&self, dim: E) -> ArrayView<'_, A, E>
1519    where
1520        E: Dimension,
1521    {
1522        #[cold]
1523        #[inline(never)]
1524        fn broadcast_panic<D, E>(from: &D, to: &E) -> !
1525        where
1526            D: Dimension,
1527            E: Dimension,
1528        {
1529            panic!(
1530                "ndarray: could not broadcast array from shape: {:?} to: {:?}",
1531                from.slice(),
1532                to.slice()
1533            )
1534        }
1535
1536        match self.broadcast(dim.clone()) {
1537            Some(it) => it,
1538            None => broadcast_panic(&self.dim, &dim),
1539        }
1540    }
1541
1542    // Broadcast to dimension `E`, without checking that the dimensions match
1543    // (Checked in debug assertions).
1544    #[inline]
1545    fn broadcast_assume<E>(&self, dim: E) -> ArrayView<'_, A, E>
1546    where
1547        E: Dimension,
1548    {
1549        let dim = dim.into_dimension();
1550        debug_assert_eq!(self.shape(), dim.slice());
1551        let ptr = self.ptr;
1552        let mut strides = dim.clone();
1553        strides.slice_mut().copy_from_slice(self.strides.slice());
1554        unsafe { ArrayView::new(ptr, dim, strides) }
1555    }
1556
1557    fn raw_strides(&self) -> D {
1558        self.strides.clone()
1559    }
1560
1561    /// Remove array axis `axis` and return the result.
1562    fn try_remove_axis(self, axis: Axis) -> ArrayBase<S, D::Smaller> {
1563        let d = self.dim.try_remove_axis(axis);
1564        let s = self.strides.try_remove_axis(axis);
1565        // safe because new dimension, strides allow access to a subset of old data
1566        unsafe {
1567            self.with_strides_dim(s, d)
1568        }
1569    }
1570}
1571
1572// parallel methods
1573#[cfg(feature = "rayon")]
1574extern crate rayon_ as rayon;
1575#[cfg(feature = "rayon")]
1576pub mod parallel;
1577
1578mod impl_1d;
1579mod impl_2d;
1580mod impl_dyn;
1581
1582mod numeric;
1583
1584pub mod linalg;
1585
1586mod impl_ops;
1587pub use crate::impl_ops::ScalarOperand;
1588
1589#[cfg(any(feature = "approx", feature = "approx-0_5"))]
1590mod array_approx;
1591
1592// Array view methods
1593mod impl_views;
1594
1595// Array raw view methods
1596mod impl_raw_views;
1597
1598// Copy-on-write array methods
1599mod impl_cow;
1600
1601/// Returns `true` if the pointer is aligned.
1602pub(crate) fn is_aligned<T>(ptr: *const T) -> bool {
1603    (ptr as usize) % ::std::mem::align_of::<T>() == 0
1604}