#slice #move #chunk #index

no-std moveslice

A one-function crate to move chunks in a slice around

6 stable releases

2.0.1 Aug 3, 2019
1.1.0 Aug 3, 2019
1.0.3 Aug 2, 2019

#763 in Rust patterns

Download history 7/week @ 2021-09-27 15/week @ 2021-10-04 34/week @ 2021-10-11 83/week @ 2021-10-18 51/week @ 2021-10-25 63/week @ 2021-11-01 143/week @ 2021-11-08 196/week @ 2021-11-15 93/week @ 2021-11-22 118/week @ 2021-11-29 75/week @ 2021-12-06 126/week @ 2021-12-13 5/week @ 2021-12-20 11/week @ 2021-12-27 20/week @ 2022-01-03 38/week @ 2022-01-10

79 downloads per month
Used in 3 crates

MPL-2.0 license

11KB
77 lines

moveslice

moveslice moveslice

This crate contains functionality to move a slice within an array around. It only uses safe functions, and acts efficiently by using the split_at_mut and rotate_left/rotate_right functions.

This crate also has a focus on being no_std, to allow this functionality in all cases where it is required.

The main feature this crate provides is implementing moveslice functions for any and all slices/arrays. In effect, it implements it on any type that also implements the AsMut<[T]> trait. This includes slices and vectors.

Examples:

use moveslice::{Moveslice, Error};

let mut arr = [1,2,3,4,5,6,7,8,9];

// The following moves the slice 3..6 to index 1.
// In effect, it moves [4,5,6] over to where [2] is.
arr.moveslice(3..6, 1);
assert_eq!(arr, [1,4,5,6,2,3,7,8,9]);

// The following moves the slice 3..6 to index 6.
// In effect, it moves [6,2,3] over to where [7] is.
arr.moveslice(3..6, 6);
assert_eq!(arr, [1,4,5,7,8,9,6,2,3]);

// The following attempts to move the slice beyond boundaries.
// The index given is 7, which exists in the array, but the
// last element of the chunk will not fit (7 + 3 = 10 > 9).
// Therefore, the following should fail.
arr.moveslice(3..6, 7); // will panic

// Panicking on failure however can prove to be not ideal.
// If instead of panicking, you prefer a `Result`, use
// `try_moveslice`.
let res = arr.try_moveslice(3..6, 7);
assert!(res.is_err());

// Moveslice also comes with its own `Error` enum, with diagnostic
// information to help debugging. The line before would have triggered
// an OutOfBoundsMove error. The following line would trigger the
// InvalidBounds error.
let res = arr.try_moveslice(9..10, 7);
assert!(if let Err(Error::InvalidBounds{..}) = res {true} else {false});

// You could pass the destination as the same value as chunk.0.
// However this would mean nothing is moved.
// This doesn't panic, but it's a no-op.
arr.moveslice(0..3, 0);

License: MPL-2.0

No runtime deps

E]