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

Encode expected/actual info in ShapeError #962

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ defmac = "0.2"
quickcheck = { version = "0.9", default-features = false }
approx = "0.4"
itertools = { version = "0.10.0", default-features = false, features = ["use_std"] }
matches = "0.1.8"

[features]
default = ["std"]
Expand Down
110 changes: 110 additions & 0 deletions benches/error-handling.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#![feature(test)]
#![allow(
clippy::many_single_char_names,
clippy::deref_addrof,
clippy::unreadable_literal,
clippy::many_single_char_names
)]
extern crate test;
use test::Bencher;

use ndarray::prelude::*;
use ndarray::ErrorKind;

// Use ZST elements to remove allocation from the benchmarks

#[derive(Copy, Clone, Debug)]
struct Zst;

type A4 = Array4<Zst>;

#[bench]
fn from_elem(bench: &mut Bencher) {
bench.iter(|| {
A4::from_elem((1, 2, 3, 4), Zst)
})
}

#[bench]
fn from_shape_vec_ok(bench: &mut Bencher) {
bench.iter(|| {
let v: Vec<Zst> = vec![Zst; 1 * 2 * 3 * 4];
let x = A4::from_shape_vec((1, 2, 3, 4).strides((24, 12, 4, 1)), v);
debug_assert!(x.is_ok(), "problem with {:?}", x);
x
})
}

#[bench]
fn from_shape_vec_fail(bench: &mut Bencher) {
bench.iter(|| {
let v: Vec<Zst> = vec![Zst; 1 * 2 * 3 * 4];
let x = A4::from_shape_vec((1, 2, 3, 4).strides((4, 3, 2, 1)), v);
debug_assert!(x.is_err());
x
})
}

#[bench]
fn into_shape_fail(bench: &mut Bencher) {
let a = A4::from_elem((1, 2, 3, 4), Zst);
let v = a.view();
bench.iter(|| {
v.clone().into_shape((5, 3, 2, 1))
})
}

#[bench]
fn into_shape_ok_c(bench: &mut Bencher) {
let a = A4::from_elem((1, 2, 3, 4), Zst);
let v = a.view();
bench.iter(|| {
v.clone().into_shape((4, 3, 2, 1))
})
}

#[bench]
fn into_shape_ok_f(bench: &mut Bencher) {
let a = A4::from_elem((1, 2, 3, 4).f(), Zst);
let v = a.view();
bench.iter(|| {
v.clone().into_shape((4, 3, 2, 1))
})
}

#[bench]
fn stack_ok(bench: &mut Bencher) {
let a = Array::from_elem((15, 15), Zst);
let rows = a.rows().into_iter().collect::<Vec<_>>();
bench.iter(|| {
let res = ndarray::stack(Axis(1), &rows);
debug_assert!(res.is_ok(), "err {:?}", res);
res
});
}

#[bench]
fn stack_err_axis(bench: &mut Bencher) {
let a = Array::from_elem((15, 15), Zst);
let rows = a.rows().into_iter().collect::<Vec<_>>();
bench.iter(|| {
let res = ndarray::stack(Axis(2), &rows);
debug_assert!(res.is_err());
res
});
}

#[bench]
fn stack_err_shape(bench: &mut Bencher) {
let a = Array::from_elem((15, 15), Zst);
let rows = a.rows().into_iter()
.enumerate()
.map(|(i, mut row)| { row.slice_collapse(s![..(i as isize)]); row })
.collect::<Vec<_>>();
bench.iter(|| {
let res = ndarray::stack(Axis(1), &rows);
debug_assert!(res.is_err());
debug_assert_eq!(res.clone().unwrap_err().kind(), ErrorKind::IncompatibleShape);
res
});
}
1 change: 1 addition & 0 deletions src/dimension/broadcast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ where
if *out == 1 {
*out = *s2
} else if *s2 != 1 {
// TODO More specific error axis length mismatch
return Err(from_kind(ErrorKind::IncompatibleShape));
}
}
Expand Down
16 changes: 12 additions & 4 deletions src/dimension/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ pub fn size_of_shape_checked<D: Dimension>(dim: &D) -> Result<usize, ShapeError>
.try_fold(1usize, |acc, &d| acc.checked_mul(d))
.ok_or_else(|| from_kind(ErrorKind::Overflow))?;
if size_nonzero > ::std::isize::MAX as usize {
// TODO More specific error
Err(from_kind(ErrorKind::Overflow))
} else {
Ok(dim.size())
Expand Down Expand Up @@ -137,7 +138,7 @@ pub(crate) fn can_index_slice_not_custom<D: Dimension>(data_len: usize, dim: &D)
let len = size_of_shape_checked(dim)?;
// Condition 2.
if len > data_len {
return Err(from_kind(ErrorKind::OutOfBounds));
return Err(ShapeError::shape_length_exceeds_data_length(data_len, len));
}
Ok(())
}
Expand Down Expand Up @@ -170,6 +171,7 @@ where
{
// Condition 1.
if dim.ndim() != strides.ndim() {
// TODO More specific error for dimension stride dimensionality mismatch
return Err(from_kind(ErrorKind::IncompatibleLayout));
}

Expand All @@ -185,19 +187,23 @@ where
let off = d.saturating_sub(1).checked_mul(s.abs() as usize)?;
acc.checked_add(off)
})
// TODO More specific error
.ok_or_else(|| from_kind(ErrorKind::Overflow))?;
// Condition 2a.
if max_offset > isize::MAX as usize {
// TODO More specific error
return Err(from_kind(ErrorKind::Overflow));
}

// Determine absolute difference in units of bytes between least and
// greatest address accessible by moving along all axes
let max_offset_bytes = max_offset
.checked_mul(elem_size)
// TODO More specific error
.ok_or_else(|| from_kind(ErrorKind::Overflow))?;
// Condition 2b.
if max_offset_bytes > isize::MAX as usize {
// TODO More specific error
return Err(from_kind(ErrorKind::Overflow));
}

Expand Down Expand Up @@ -256,15 +262,16 @@ fn can_index_slice_impl<D: Dimension>(
// Check condition 3.
let is_empty = dim.slice().iter().any(|&d| d == 0);
if is_empty && max_offset > data_len {
return Err(from_kind(ErrorKind::OutOfBounds));
return Err(ShapeError::shape_length_exceeds_data_length(data_len, max_offset));
}
if !is_empty && max_offset >= data_len {
return Err(from_kind(ErrorKind::OutOfBounds));
return Err(ShapeError::shape_length_exceeds_data_length(data_len.wrapping_sub(1), max_offset));
}

// Check condition 4.
if !is_empty && dim_stride_overlap(dim, strides) {
return Err(from_kind(ErrorKind::Unsupported));
// TODO: More specific error kind Strides result in overlapping elements
return Err(ShapeError::from_kind(ErrorKind::Unsupported));
}

Ok(())
Expand Down Expand Up @@ -293,6 +300,7 @@ where
{
for &stride in strides.slice() {
if (stride as isize) < 0 {
// TODO: More specific error kind Non-negative strides required
return Err(from_kind(ErrorKind::Unsupported));
}
}
Expand Down
Loading