Skip to content
Closed
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
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ matrixmultiply = { version = "0.2.0" }
# Use via the `serde-1` crate feature!
serde = { version = "1.0", optional = true }

# Error-handling
failure = "0.1"
failure_derive = "0.1"

[dev-dependencies]
defmac = "0.2"
quickcheck = { version = "0.8", default-features = false }
Expand Down
139 changes: 112 additions & 27 deletions src/dimension/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::error::{from_kind, ErrorKind, ShapeError};
use crate::error::{ShapeError, ShapeErrorKind};
use crate::{Ix, Ixs, Slice, SliceOrIndex};
use itertools::izip;
use num_integer::div_floor;
Expand Down Expand Up @@ -69,7 +69,7 @@ pub fn dim_stride_overlap<D: Dimension>(dim: &D, strides: &D) -> bool {
}

/// Returns the `size` of the `dim`, checking that the product of non-zero axis
/// lengths does not exceed `isize::MAX`.
/// lengths does not exceed `usize::MAX`.
///
/// If `size_of_checked_shape(dim)` returns `Ok(size)`, the data buffer is a
/// slice or `Vec` of length `size`, and `strides` are created with
Expand All @@ -83,9 +83,20 @@ pub fn size_of_shape_checked<D: Dimension>(dim: &D) -> Result<usize, ShapeError>
.iter()
.filter(|&&d| d != 0)
.try_fold(1usize, |acc, &d| acc.checked_mul(d))
.ok_or_else(|| from_kind(ErrorKind::Overflow))?;
.ok_or_else(|| {
ShapeError::from(ShapeErrorKind::Overflow {
message: format!(
"From dimensions: {:?}, the product of non-zero axis lengths \
exceed `usize::MAX`.",
dim
),
})
})?;

if size_nonzero > ::std::isize::MAX as usize {
Err(from_kind(ErrorKind::Overflow))
Err(ShapeError::from(ShapeErrorKind::Overflow {
message: format!("Size: {:?} exceed `isize::MAX`.", size_nonzero),
}))
} else {
Ok(dim.size())
}
Expand Down Expand Up @@ -117,10 +128,18 @@ pub fn size_of_shape_checked<D: Dimension>(dim: &D) -> Result<usize, ShapeError>
/// accessible by moving along all axes does not exceed `isize::MAX`.
pub fn can_index_slice_not_custom<A, D: Dimension>(data: &[A], dim: &D) -> Result<(), ShapeError> {
// Condition 1.
let len = size_of_shape_checked(dim)?;
let size = size_of_shape_checked(dim)?;

// Condition 2.
if len > data.len() {
return Err(from_kind(ErrorKind::OutOfBounds));
let length = data.len();
if size > length {
return Err(ShapeError::from(ShapeErrorKind::OutOfBounds {
message: format!(
"The dimension size: {:?} must be less than or equal to \
the length of the slice: {:?}.",
size, length
),
}));
}
Ok(())
}
Expand All @@ -145,7 +164,13 @@ where
{
// Condition 1.
if dim.ndim() != strides.ndim() {
return Err(from_kind(ErrorKind::IncompatibleLayout));
return Err(ShapeError::from(ShapeErrorKind::IncompatibleLayout {
message: format!(
"The number of dimension must be the same for dim {:?} and strides {:?}.",
dim.ndim(),
strides.ndim()
),
}));
}

// Condition 3.
Expand All @@ -160,20 +185,46 @@ where
let off = d.saturating_sub(1).checked_mul(s.abs() as usize)?;
acc.checked_add(off)
})
.ok_or_else(|| from_kind(ErrorKind::Overflow))?;
.ok_or_else(|| {
ShapeError::from(ShapeErrorKind::Overflow {
message: format!(
"From the dimensions: {:?} and strides: {:?}, \
the maximum possible absolute movement in units of `A` exceed `usize::MAX`.",
dim, strides
),
})
})?;
// Condition 2a.
if max_offset > isize::MAX as usize {
return Err(from_kind(ErrorKind::Overflow));
return Err(ShapeError::from(ShapeErrorKind::Overflow {
message: format!(
"The absolute difference between least and greatest address, \
max ofsset: {:?} in units of `A` exceed `isize::MAX`.",
max_offset
),
}));
}

// 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(mem::size_of::<A>())
.ok_or_else(|| from_kind(ErrorKind::Overflow))?;
let max_offset_bytes = max_offset.checked_mul(mem::size_of::<A>()).ok_or_else(|| {
ShapeError::from(ShapeErrorKind::Overflow {
message: format!(
"From the dimensions: {:?} and strides: {:?}, \
the maximum possible absolute movement in bytes exceed `usize::MAX`.",
dim, strides
),
})
})?;
// Condition 2b.
if max_offset_bytes > isize::MAX as usize {
return Err(from_kind(ErrorKind::Overflow));
return Err(ShapeError::from(ShapeErrorKind::Overflow {
message: format!(
"The absolute difference between least and greatest address, \
max ofsset: {:?} in units of bytes, exceed `isize::MAX`.",
max_offset_bytes
),
}));
}

Ok(max_offset)
Expand Down Expand Up @@ -219,25 +270,47 @@ pub fn can_index_slice<A, D: Dimension>(
let max_offset = max_abs_offset_check_overflow::<A, _>(dim, strides)?;

// Check condition 4.
let length = data.len();
let is_empty = dim.slice().iter().any(|&d| d == 0);
if is_empty && max_offset > data.len() {
return Err(from_kind(ErrorKind::OutOfBounds));
}
if !is_empty && max_offset >= data.len() {
return Err(from_kind(ErrorKind::OutOfBounds));
if is_empty && max_offset > length {
return Err(ShapeError::from(ShapeErrorKind::OutOfBounds {
message: format!(
"If the array will be empty, the difference between \
least and greatest address, max ofsset: {:?}, must be less than or \
equal to the length of data{:?}.",
max_offset, length
),
}));
}
if !is_empty && max_offset >= length {
return Err(ShapeError::from(ShapeErrorKind::OutOfBounds {
message: format!(
"If the array will not be empty, the difference between \
least and greatest address, max ofsset: {:?}, must be less than \
the length of data {:?}.",
max_offset, length
),
}));
}

// Check condition 3.
for (&d, &s) in izip!(dim.slice(), strides.slice()) {
let s = s as isize;
if d > 1 && s < 0 {
return Err(from_kind(ErrorKind::Unsupported));
return Err(ShapeError::from(ShapeErrorKind::Unsupported {
message: format!("Strides must be strictly positive: {}.", s),
}));
}
}

// Check condition 5.
if !is_empty && dim_stride_overlap(dim, strides) {
return Err(from_kind(ErrorKind::Unsupported));
return Err(ShapeError::from(ShapeErrorKind::Unsupported {
message: format!(
"Dimension {:?} has overlapping indices with strides {:?}.",
dim, strides
),
}));
}

Ok(())
Expand Down Expand Up @@ -644,7 +717,7 @@ mod test {
max_abs_offset_check_overflow, slice_min_max, slices_intersect,
solve_linear_diophantine_eq, IntoDimension,
};
use crate::error::{from_kind, ErrorKind};
use crate::error::{ShapeError, ShapeErrorKind};
use crate::slice::Slice;
use crate::{Dim, Dimension, Ix0, Ix1, Ix2, Ix3, IxDyn};
use num_integer::gcd;
Expand All @@ -660,7 +733,14 @@ mod test {
let strides = (2, 4, 12).into_dimension();
assert_eq!(
super::can_index_slice(&v, &dim, &strides),
Err(from_kind(ErrorKind::OutOfBounds))
Err(ShapeError::from(ShapeErrorKind::OutOfBounds {
message: format!(
"If the array will not be empty, the difference \
between least and greatest address, max ofsset: {:?}, must be \
less than the length of data {:?}.",
22, 12
)
}))
);
}

Expand Down Expand Up @@ -765,11 +845,16 @@ mod test {
let result = can_index_slice_not_custom(&data, &dim);
if dim.size_checked().is_none() {
// Avoid overflow `dim.default_strides()` or `dim.fortran_strides()`.
result.is_err()
} else {
result == can_index_slice(&data, &dim, &dim.default_strides()) &&
result == can_index_slice(&data, &dim, &dim.fortran_strides())
return result.is_err();
}

if dim.size() > data.len() {
// Avoid out of bounds, can index slice not custom.
return result.is_err();
}

result == can_index_slice(&data, &dim, &dim.default_strides()) &&
result == can_index_slice(&data, &dim, &dim.fortran_strides())
}
}

Expand Down
108 changes: 42 additions & 66 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,101 +5,77 @@
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::Dimension;
use std::error::Error;
use failure::{Backtrace, Context, Fail};
use std::fmt;

/// An error related to array shape or layout.
#[derive(Clone)]
#[derive(Debug)]
pub struct ShapeError {
// we want to be able to change this representation later
repr: ErrorKind,
}

impl ShapeError {
/// Return the `ErrorKind` of this error.
#[inline]
pub fn kind(&self) -> ErrorKind {
self.repr
}

/// Create a new `ShapeError`
pub fn from_kind(error: ErrorKind) -> Self {
from_kind(error)
}
inner: Context<ShapeErrorKind>,
}

/// Error code for an error related to array shape or layout.
///
/// This enumeration is not exhaustive. The representation of the enum
/// is not guaranteed.
#[derive(Copy, Clone, Debug)]
pub enum ErrorKind {
/// incompatible shape
IncompatibleShape = 1,
/// incompatible memory layout
IncompatibleLayout,
/// the shape does not fit inside type limits
#[derive(Clone, PartialEq, Debug, Fail)]
pub enum ShapeErrorKind {
#[fail(display = "Incompatible shape. {}", message)]
IncompatibleShape { message: String },
#[fail(display = "Incompatible layout. {}", message)]
IncompatibleLayout { message: String },
#[fail(display = "Out of bounds indexing. {}", message)]
OutOfBounds { message: String },
#[fail(display = "Aliasing array elements. {}", message)]
Unsupported { message: String },
#[fail(display = "Overflow dimensions. {}", message)]
Overflow { message: String },
#[fail(display = "The shape does not fit inside type limits.")]
RangeLimited,
/// out of bounds indexing
OutOfBounds,
/// aliasing array elements
Unsupported,
/// overflow when computing offset, length, etc.
Overflow,
#[fail(display = "Incomplete")]
#[doc(hidden)]
__Incomplete,
}

#[inline(always)]
pub fn from_kind(k: ErrorKind) -> ShapeError {
ShapeError { repr: k }
}
impl Fail for ShapeError {
fn cause(&self) -> Option<&Fail> {
self.inner.cause()
}

impl PartialEq for ErrorKind {
#[inline(always)]
fn eq(&self, rhs: &Self) -> bool {
*self as u8 == *rhs as u8
fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}

impl PartialEq for ShapeError {
#[inline(always)]
fn eq(&self, rhs: &Self) -> bool {
self.repr == rhs.repr
impl fmt::Display for ShapeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.inner, f)
}
}

impl Error for ShapeError {
fn description(&self) -> &str {
match self.kind() {
ErrorKind::IncompatibleShape => "incompatible shapes",
ErrorKind::IncompatibleLayout => "incompatible memory layout",
ErrorKind::RangeLimited => "the shape does not fit in type limits",
ErrorKind::OutOfBounds => "out of bounds indexing",
ErrorKind::Unsupported => "unsupported operation",
ErrorKind::Overflow => "arithmetic overflow",
ErrorKind::__Incomplete => "this error variant is not in use",
}
impl ShapeError {
pub fn kind(&self) -> &ShapeErrorKind {
self.inner.get_context()
}
}

impl fmt::Display for ShapeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ShapeError/{:?}: {}", self.kind(), self.description())
impl From<ShapeErrorKind> for ShapeError {
fn from(kind: ShapeErrorKind) -> ShapeError {
ShapeError {
inner: Context::new(kind),
}
}
}

impl fmt::Debug for ShapeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ShapeError/{:?}: {}", self.kind(), self.description())
impl From<Context<ShapeErrorKind>> for ShapeError {
fn from(inner: Context<ShapeErrorKind>) -> ShapeError {
ShapeError { inner }
}
}

pub fn incompatible_shapes<D, E>(_a: &D, _b: &E) -> ShapeError
where
D: Dimension,
E: Dimension,
{
from_kind(ErrorKind::IncompatibleShape)
impl PartialEq for ShapeError {
#[inline(always)]
fn eq(&self, rhs: &Self) -> bool {
self.kind() == rhs.kind()
}
}
Loading