Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use FromIterator trait rather than custom method #648

Merged
merged 13 commits into from
Jul 20, 2019
1 change: 1 addition & 0 deletions benches/higher-order.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![feature(test)]

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
3 changes: 1 addition & 2 deletions examples/life.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
extern crate ndarray;

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

const INPUT: &'static [u8] = include_bytes!("life.txt");
//const INPUT: &'static [u8] = include_bytes!("lifelite.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
max-sixty marked this conversation as resolved.
Show resolved Hide resolved
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
38 changes: 7 additions & 31 deletions src/impl_constructors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
//!

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

use crate::dimension;
use crate::error::{self, ShapeError};
Expand Down Expand Up @@ -40,33 +38,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]))
/// ```
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 @@ -90,7 +66,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 @@ -108,7 +84,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 @@ -136,7 +112,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 @@ -170,7 +146,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 @@ -699,7 +699,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 @@ -717,7 +717,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 @@ -729,7 +729,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 @@ -10,6 +10,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 @@ -661,7 +662,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 @@ -1026,7 +1027,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 @@ -1229,7 +1230,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 @@ -1246,7 +1247,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 @@ -1265,7 +1266,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 @@ -3,6 +3,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 @@ -7,6 +7,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 @@ -395,9 +396,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 @@ -407,9 +406,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 @@ -420,7 +417,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 @@ -602,7 +599,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 @@ -44,7 +44,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 @@ -140,7 +140,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