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