Skip to content

Commit

Permalink
Use FromIterator trait rather than custom method (#648)
Browse files Browse the repository at this point in the history
* use FromIterator trait rather than custom method

* use standard From over from_vec

* add notes re removing `from_iter` without deprecation

* find-replace for ([\w]*Array[0-9]*::)from_vec

* final from_vec

* forgot about --all

* fmt

* comments from @jturner314 review

* remove old method

* Fix docs for from_iter

* Fix unused import warnings
  • Loading branch information
max-sixty authored and LukeMathWalker committed Jul 20, 2019
1 parent 2075267 commit be3b74f
Show file tree
Hide file tree
Showing 16 changed files with 75 additions and 67 deletions.
1 change: 1 addition & 0 deletions benches/higher-order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
clippy::many_single_char_names
)]
extern crate test;
use std::iter::FromIterator;
use test::black_box;
use test::Bencher;

Expand Down
3 changes: 2 additions & 1 deletion blas-tests/tests/oper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use ndarray::linalg::general_mat_vec_mul;
use ndarray::prelude::*;
use ndarray::{Data, LinalgScalar};
use ndarray::{Ix, Ixs, SliceInfo, SliceOrIndex};
use std::iter::FromIterator;

use approx::{assert_abs_diff_eq, assert_relative_eq};
use defmac::defmac;
Expand Down Expand Up @@ -289,7 +290,7 @@ fn mat_mul_broadcast() {
let (m, n, k) = (16, 16, 16);
let a = range_mat(m, n);
let x1 = 1.;
let x = Array::from_vec(vec![x1]);
let x = Array::from(vec![x1]);
let b0 = x.broadcast((n, k)).unwrap();
let b1 = Array::from_elem(n, x1);
let b1 = b1.broadcast((n, k)).unwrap();
Expand Down
5 changes: 2 additions & 3 deletions examples/life.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@
extern crate ndarray;

use ndarray::prelude::*;
use std::iter::FromIterator;

const INPUT: &[u8] = include_bytes!("life.txt");
//const INPUT: &'static [u8] = include_bytes!("lifelite.txt");
const INPUT: &'static [u8] = include_bytes!("life.txt");

const N: usize = 100;
//const N: usize = 8;

type Board = Array2<u8>;

Expand Down
39 changes: 38 additions & 1 deletion src/arraytraits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
// except according to those terms.

use std::hash;
use std::isize;
use std::iter::FromIterator;
use std::iter::IntoIterator;
use std::mem;
Expand Down Expand Up @@ -119,15 +120,51 @@ where
{
}

impl<A, S> From<Vec<A>> for ArrayBase<S, Ix1>
where
S: DataOwned<Elem = A>,
{
/// Create a one-dimensional array from a vector (no copying needed).
///
/// **Panics** if the length is greater than `isize::MAX`.
///
/// ```rust
/// use ndarray::Array;
///
/// let array = Array::from(vec![1., 2., 3., 4.]);
/// ```
fn from(v: Vec<A>) -> Self {
if mem::size_of::<A>() == 0 {
assert!(
v.len() <= isize::MAX as usize,
"Length must fit in `isize`.",
);
}
unsafe { Self::from_shape_vec_unchecked(v.len() as Ix, v) }
}
}

impl<A, S> FromIterator<A> for ArrayBase<S, Ix1>
where
S: DataOwned<Elem = A>,
{
/// Create a one-dimensional array from an iterable.
///
/// **Panics** if the length is greater than `isize::MAX`.
///
/// ```rust
/// use ndarray::{Array, arr1};
/// use std::iter::FromIterator;
///
/// // Either use `from_iter` directly or use `Iterator::collect`.
/// let array = Array::from_iter((0..5).map(|x| x * x));
/// assert!(array == arr1(&[0, 1, 4, 9, 16]))
/// ```
fn from_iter<I>(iterable: I) -> ArrayBase<S, Ix1>
where
I: IntoIterator<Item = A>,
{
ArrayBase::from_iter(iterable)
Self::from(iterable.into_iter().collect::<Vec<A>>())
}
}

Expand Down
10 changes: 2 additions & 8 deletions src/free_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ macro_rules! array {
$crate::Array2::from(vec![$([$($x,)*],)*])
}};
($($x:expr),* $(,)*) => {{
$crate::Array::from_vec(vec![$($x,)*])
$crate::Array::from(vec![$($x,)*])
}};
}

Expand All @@ -59,7 +59,7 @@ pub fn arr0<A>(x: A) -> Array0<A> {

/// Create a one-dimensional array with elements from `xs`.
pub fn arr1<A: Clone>(xs: &[A]) -> Array1<A> {
ArrayBase::from_vec(xs.to_vec())
ArrayBase::from(xs.to_vec())
}

/// Create a one-dimensional array with elements from `xs`.
Expand Down Expand Up @@ -226,12 +226,6 @@ where
Array2::from(xs.to_vec())
}

impl<A> From<Vec<A>> for Array1<A> {
fn from(xs: Vec<A>) -> Self {
Array1::from_vec(xs)
}
}

impl<A, V> From<Vec<V>> for Array2<A>
where
V: FixedInitializer<Elem = A>,
Expand Down
40 changes: 7 additions & 33 deletions src/impl_constructors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
#![allow(clippy::match_wild_err_arm)]

use num_traits::{Float, One, Zero};
use std::isize;
use std::mem;

use crate::dimension;
use crate::error::{self, ShapeError};
Expand Down Expand Up @@ -42,35 +40,11 @@ where
/// ```rust
/// use ndarray::Array;
///
/// let array = Array::from_vec(vec![1., 2., 3., 4.]);
/// let array = Array::from(vec![1., 2., 3., 4.]);
/// ```
#[deprecated(note = "use standard `from`", since = "0.13.0")]
pub fn from_vec(v: Vec<A>) -> Self {
if mem::size_of::<A>() == 0 {
assert!(
v.len() <= isize::MAX as usize,
"Length must fit in `isize`.",
);
}
unsafe { Self::from_shape_vec_unchecked(v.len() as Ix, v) }
}

/// Create a one-dimensional array from an iterable.
///
/// **Panics** if the length is greater than `isize::MAX`.
///
/// ```rust
/// use ndarray::{Array, arr1};
///
/// let array = Array::from_iter((0..5).map(|x| x * x));
/// assert!(array == arr1(&[0, 1, 4, 9, 16]))
/// ```
// Potentially remove; see https://github.com/rust-ndarray/ndarray/pull/642#discussion_r296068930
#[allow(clippy::should_implement_trait)]
pub fn from_iter<I>(iterable: I) -> Self
where
I: IntoIterator<Item = A>,
{
Self::from_vec(iterable.into_iter().collect())
Self::from(v)
}

/// Create a one-dimensional array with `n` evenly spaced elements from
Expand All @@ -94,7 +68,7 @@ where
where
A: Float,
{
Self::from_vec(to_vec(linspace::linspace(start, end, n)))
Self::from(to_vec(linspace::linspace(start, end, n)))
}

/// Create a one-dimensional array with elements from `start` to `end`
Expand All @@ -112,7 +86,7 @@ where
where
A: Float,
{
Self::from_vec(to_vec(linspace::range(start, end, step)))
Self::from(to_vec(linspace::range(start, end, step)))
}

/// Create a one-dimensional array with `n` logarithmically spaced
Expand Down Expand Up @@ -140,7 +114,7 @@ where
where
A: Float,
{
Self::from_vec(to_vec(logspace::logspace(base, start, end, n)))
Self::from(to_vec(logspace::logspace(base, start, end, n)))
}

/// Create a one-dimensional array with `n` geometrically spaced elements
Expand Down Expand Up @@ -174,7 +148,7 @@ where
where
A: Float,
{
Some(Self::from_vec(to_vec(geomspace::geomspace(start, end, n)?)))
Some(Self::from(to_vec(geomspace::geomspace(start, end, n)?)))
}
}

Expand Down
1 change: 1 addition & 0 deletions src/impl_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1010,6 +1010,7 @@ where
/// ```
/// use ndarray::Array;
/// use ndarray::{arr3, Axis};
/// use std::iter::FromIterator;
///
/// let a = Array::from_iter(0..28).into_shape((2, 7, 2)).unwrap();
/// let mut iter = a.axis_chunks_iter(Axis(1), 2);
Expand Down
6 changes: 3 additions & 3 deletions src/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,7 @@ pub unsafe fn deref_raw_view_mut_into_view_mut_with_life<'a, A, D: Dimension>(
/// use ndarray::prelude::*;
///
/// # fn main() {
/// let mut arr = Array1::from_iter(0..12);
/// let mut arr: Array1<_> = (0..12).collect();
/// let (a, b, c, d) = multislice!(arr, [0..5], mut [6..;2], [1..6], mut [7..;2]);
/// assert_eq!(a, array![0, 1, 2, 3, 4]);
/// assert_eq!(b, array![6, 8, 10]);
Expand All @@ -714,7 +714,7 @@ pub unsafe fn deref_raw_view_mut_into_view_mut_with_life<'a, A, D: Dimension>(
/// # use ndarray::multislice;
/// # use ndarray::prelude::*;
/// # fn main() {
/// let mut arr = Array1::from_iter(0..12);
/// let mut arr: Array1<_> = (0..12).collect();
/// multislice!(arr, [0..5], mut [1..;2]); // panic!
/// # }
/// ```
Expand All @@ -726,7 +726,7 @@ pub unsafe fn deref_raw_view_mut_into_view_mut_with_life<'a, A, D: Dimension>(
/// # use ndarray::multislice;
/// # use ndarray::prelude::*;
/// # fn main() {
/// let mut arr = Array1::from_iter(0..12);
/// let mut arr: Array1<_> = (0..12).collect();
/// multislice!(arr, mut [0..5], mut [1..;2]); // panic!
/// # }
/// ```
Expand Down
11 changes: 6 additions & 5 deletions tests/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use ndarray::indices;
use ndarray::prelude::*;
use ndarray::{arr3, multislice, rcarr2};
use ndarray::{Slice, SliceInfo, SliceOrIndex};
use std::iter::FromIterator;

macro_rules! assert_panics {
($body:expr) => {
Expand Down Expand Up @@ -670,7 +671,7 @@ fn test_sub() {
assert_eq!(s2.shape(), &[4, 2]);
let n = ArcArray::linspace(8., 15., 8).reshape((4, 2));
assert_eq!(n, s2);
let m = ArcArray::from_vec(vec![2., 3., 10., 11.]).reshape((2, 2));
let m = ArcArray::from(vec![2., 3., 10., 11.]).reshape((2, 2));
assert_eq!(m, mat.index_axis(Axis(1), 1));
}

Expand Down Expand Up @@ -1036,7 +1037,7 @@ fn array0_into_scalar() {

#[test]
fn owned_array1() {
let mut a = Array::from_vec(vec![1, 2, 3, 4]);
let mut a = Array::from(vec![1, 2, 3, 4]);
for elt in a.iter_mut() {
*elt = 2;
}
Expand Down Expand Up @@ -1239,7 +1240,7 @@ fn from_vec_dim_stride_2d_rejects() {

#[test]
fn views() {
let a = ArcArray::from_vec(vec![1, 2, 3, 4]).reshape((2, 2));
let a = ArcArray::from(vec![1, 2, 3, 4]).reshape((2, 2));
let b = a.view();
assert_eq!(a, b);
assert_eq!(a.shape(), b.shape());
Expand All @@ -1256,7 +1257,7 @@ fn views() {

#[test]
fn view_mut() {
let mut a = ArcArray::from_vec(vec![1, 2, 3, 4]).reshape((2, 2));
let mut a = ArcArray::from(vec![1, 2, 3, 4]).reshape((2, 2));
for elt in &mut a.view_mut() {
*elt = 0;
}
Expand All @@ -1275,7 +1276,7 @@ fn view_mut() {

#[test]
fn slice_mut() {
let mut a = ArcArray::from_vec(vec![1, 2, 3, 4]).reshape((2, 2));
let mut a = ArcArray::from(vec![1, 2, 3, 4]).reshape((2, 2));
for elt in a.slice_mut(s![.., ..]) {
*elt = 0;
}
Expand Down
1 change: 1 addition & 0 deletions tests/azip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ extern crate ndarray;

use ndarray::prelude::*;
use ndarray::Zip;
use std::iter::FromIterator;

use itertools::{assert_equal, cloned};

Expand Down
4 changes: 2 additions & 2 deletions tests/broadcast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ fn test_broadcast() {
let (_, n, k) = (16, 16, 16);
let x1 = 1.;
// b0 broadcast 1 -> n, k
let x = Array::from_vec(vec![x1]);
let x = Array::from(vec![x1]);
let b0 = x.broadcast((n, k)).unwrap();
// b1 broadcast n -> n, k
let b1 = Array::from_elem(n, x1);
Expand All @@ -72,7 +72,7 @@ fn test_broadcast_1d() {
let n = 16;
let x1 = 1.;
// b0 broadcast 1 -> n
let x = Array::from_vec(vec![x1]);
let x = Array::from(vec![x1]);
let b0 = x.broadcast(n).unwrap();
let b2 = Array::from_elem(n, x1);

Expand Down
13 changes: 5 additions & 8 deletions tests/iterators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use ndarray::{arr2, arr3, aview1, indices, s, Axis, Data, Dimension, Slice};

use itertools::assert_equal;
use itertools::{enumerate, rev};
use std::iter::FromIterator;

#[test]
fn double_ended() {
Expand Down Expand Up @@ -401,9 +402,7 @@ fn axis_chunks_iter_corner_cases() {
fn axis_chunks_iter_zero_stride() {
{
// stride 0 case
let b = Array::from_vec(vec![0f32; 0])
.into_shape((5, 0, 3))
.unwrap();
let b = Array::from(vec![0f32; 0]).into_shape((5, 0, 3)).unwrap();
let shapes: Vec<_> = b
.axis_chunks_iter(Axis(0), 2)
.map(|v| v.raw_dim())
Expand All @@ -413,9 +412,7 @@ fn axis_chunks_iter_zero_stride() {

{
// stride 0 case reverse
let b = Array::from_vec(vec![0f32; 0])
.into_shape((5, 0, 3))
.unwrap();
let b = Array::from(vec![0f32; 0]).into_shape((5, 0, 3)).unwrap();
let shapes: Vec<_> = b
.axis_chunks_iter(Axis(0), 2)
.rev()
Expand All @@ -426,7 +423,7 @@ fn axis_chunks_iter_zero_stride() {

// From issue #542, ZST element
{
let a = Array::from_vec(vec![(); 3]);
let a = Array::from(vec![(); 3]);
let chunks: Vec<_> = a.axis_chunks_iter(Axis(0), 2).collect();
assert_eq!(chunks, vec![a.slice(s![0..2]), a.slice(s![2..])]);
}
Expand Down Expand Up @@ -609,7 +606,7 @@ fn test_rfold() {
acc
});
assert_eq!(
Array1::from_vec(output),
Array1::from(output),
Array::from_iter((1..10).rev().map(|i| i * 2))
);
}
Expand Down
2 changes: 1 addition & 1 deletion tests/ix0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ fn test_ix0_add_add() {

#[test]
fn test_ix0_add_broad() {
let mut b = Array::from_vec(vec![5., 6.]);
let mut b = Array::from(vec![5., 6.]);
let mut a = Array::zeros(Ix0());
a += 1.;
b += &a;
Expand Down
2 changes: 1 addition & 1 deletion tests/ixdyn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ fn test_0_add_add() {

#[test]
fn test_0_add_broad() {
let mut b = Array::from_vec(vec![5., 6.]);
let mut b = Array::from(vec![5., 6.]);
let mut a = Array::zeros(vec![]);
a += 1.;
b += &a;
Expand Down
Loading

0 comments on commit be3b74f

Please sign in to comment.