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

Add fallible Indices constructor #5

Merged
merged 4 commits into from
May 25, 2022
Merged
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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Changelog

## [Unreleased]

### Added

* Add fallible function `Indices::try_from_bisector` to create a valid `Indices` instance

### Documentation

* Improved documentation of `Indices::from_bisector`, by better explaining how it may cause problems when calling `bisect`
or `try_bisect`.
* Suggest usage of `Indices::try_from_bisector` over `Indices::from_bisector`

[Unreleased]: https://github.com/foresterre/bisector/compare/v0.3.0...HEAD

14 changes: 14 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use std::fmt::{Debug, Display, Formatter};

#[derive(Debug, Eq, PartialEq)]
pub struct EmptySliceError;

impl Display for EmptySliceError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"Expected a non-empty slice, but the given slice was empty (len = 0)"
))
}
}

impl std::error::Error for EmptySliceError {}
51 changes: 49 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,17 @@
#[cfg(test)]
mod tests;

pub(crate) mod error;

use std::fmt::Debug;

/// Error returned by [`Indices::try_from_bisector`], when the slice given to [`Bisector::new`]
/// is empty.
///
/// [`Indices::try_from_bisector`]: crate::Indices::try_from_bisector
/// [`Bisector::new`]: crate::Bisector::new
pub use error::EmptySliceError;

/// Stateless implementation of the bisection method.
#[derive(Debug)]
pub struct Bisector<'v, T> {
Expand Down Expand Up @@ -188,18 +197,56 @@ impl Indices {
/// The returned indices will be the complete range of the slice, i.e. from index `0` to
/// index `|slice| - 1` (length of slice minus 1, i.e. the last index of the slice).
///
/// **Panics**
/// NB: The slice given to [`Bisector`] **must not be empty**.
///
/// Consider using the fallible function [`Indices::try_from_bisector`] when possible.
///
/// ### Undefined behaviour
///
/// Panics if the slice is empty, i.e. the length of the slice is `0`.
/// If the slice given to [`Bisector`] is empty, the resulting behaviour may not be as expected.
/// In addition, semantically different behaviour may occur when compiling with `rustc`
/// debug or release mode.
///
/// **Debug mode**
///
/// In rustc debug mode, if the slice is empty, i.e. the length of the slice is `0`, this function
/// will panic, by virtue of debug mode out of bounds checking.
///
/// **Release mode**
///
/// In rustc release mode, if the slice is empty, i.e. the length of the slice is `0`, the value
/// set to the `right` index will underflow, resulting in undefined behaviour.
///
/// [`Bisector`]: crate::Bisector
/// [`Indices::try_from_bisector`]: crate::Indices::try_from_bisector
pub fn from_bisector<T>(bisector: &Bisector<T>) -> Self {
Self {
left: 0,
right: bisector.view.len() - 1,
}
}

/// Re-use the slice of the [`Bisector`] to determine the starting indices.
///
/// The returned indices will be the complete range of the slice, i.e. from index `0` to
/// index `|slice| - 1` (length of slice minus 1, i.e. the last index of the slice).
///
/// The slice given to [`Bisector`] must not be empty. If it is, an [`EmptySliceError`]
/// `Err` result will be returned..
///
/// [`Bisector`]: crate::Bisector
/// [`EmptySliceError`]: crate::EmptySliceError
pub fn try_from_bisector<T>(bisector: &Bisector<T>) -> Result<Self, EmptySliceError> {
if !bisector.view.is_empty() {
Ok(Self {
left: 0,
right: bisector.view.len() - 1,
})
} else {
Err(EmptySliceError)
}
}

/// Computes the mid-point between the left and right indices.
/// Uses integer division, so use with care.
#[inline]
Expand Down
29 changes: 29 additions & 0 deletions src/tests/indices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,35 @@ fn create_indices_with_new() {
assert_eq!(indices.right, 1);
}

#[yare::parameterized(
one_to_ten = { input_1_to_10, (0, 9) },
one = { input_1, (0, 0) },
)]
fn create_starting_indices_try_from_bisector(
input: fn() -> Vec<u32>,
indices_expected: (usize, usize),
) {
let values = input();
let bisector = Bisector::new(&values);

let indices = Indices::try_from_bisector(&bisector).unwrap();

let (left_expected, right_expected) = indices_expected;

assert_eq!(indices.left, left_expected);
assert_eq!(indices.right, right_expected);
}

#[test]
fn creating_starting_indices_try_from_bisector_with_empty_slice_should_error() {
let values = input_empty();
let bisector = Bisector::new(&values);

let result = Indices::try_from_bisector(&bisector);

assert_eq!(result.unwrap_err(), EmptySliceError);
}

#[yare::parameterized(
zeros = { 0, 0, 0 },
zero_one = { 0, 1, 0 },
Expand Down