Crate array_rotation

source ·
Expand description

Rotate arrays and elements.

§Examples

use std::mem::MaybeUninit;

use array_rotation::array_rotate_2;

fn uninit_array<T, const N: usize>() -> [MaybeUninit<T>; N] {
    unsafe { MaybeUninit::<[MaybeUninit<T>; N]>::uninit().assume_init() }
}

let mut left = uninit_array::<String, 10>();
left[0].write("A".to_owned());
left[1].write("B".to_owned());
left[2].write("C".to_owned());
left[3].write("D".to_owned());
let mut right = uninit_array::<String, 10>();
right[0].write("E".to_owned());

let leftlen_old = 4;
let rightlen_old = 1;
let leftlen_new = 2;
let rightlen_new = unsafe {
    array_rotate_2(&mut left, &mut right, leftlen_old, rightlen_old, leftlen_new)
};

assert_eq!(rightlen_new, 3);
unsafe {
    let left = &*(&left[..leftlen_new] as *const [_] as *const [String]);
    assert_eq!(left, ["A", "B"]);
    let right = &*(&right[..rightlen_new] as *const [_] as *const [String]);
    assert_eq!(right, ["C", "D", "E"]);
}

unsafe {
    array_rotate_2(&mut left, &mut right, leftlen_new, rightlen_new, 0);
    for e in &mut right[..leftlen_new + rightlen_new] {
        e.assume_init_drop();
    }
}
use std::mem::MaybeUninit;

use array_rotation::array_rotate_3;

fn uninit_array<T, const N: usize>() -> [MaybeUninit<T>; N] {
    unsafe { MaybeUninit::<[MaybeUninit<T>; N]>::uninit().assume_init() }
}

let mut left = uninit_array::<String, 10>();
left[0].write("A".to_owned());
left[1].write("B".to_owned());
left[2].write("C".to_owned());
left[3].write("D".to_owned());
let mut mid = MaybeUninit::new("E".to_owned());
let mut right = uninit_array::<String, 10>();
right[0].write("F".to_owned());

let leftlen_old = 4;
let rightlen_old = 1;
let leftlen_new = 2;
let rightlen_new = unsafe {
    array_rotate_3(&mut left, &mut mid, &mut right, leftlen_old, rightlen_old, leftlen_new)
};

assert_eq!(rightlen_new, 3);
unsafe {
    let left = &*(&left[..leftlen_new] as *const [_] as *const [String]);
    assert_eq!(left, ["A", "B"]);
    assert_eq!(mid.assume_init_ref(), "C");
    let right = &*(&right[..rightlen_new] as *const [_] as *const [String]);
    assert_eq!(right, ["D", "E", "F"]);
}

unsafe {
    array_rotate_3(&mut left, &mut mid, &mut right, leftlen_new, rightlen_new, 0);
    mid.assume_init_drop();
    for e in &mut right[..leftlen_new + rightlen_new] {
        e.assume_init_drop();
    }
}

Functions§