rustrust-ndarray

Rust create non-contiguous vector for testing


I am using the ndarray::ArrayBase type, and for one of my unit tests I need to check whether or not a vector is contiguous in memory. I am using the .is_standard_layout() method to check this, so I just need a way to create vector for testing that is non-contiguous in memory. The contiguous vector is easily created with vec![1.0, 2.0, 3.0]. Does anyone know the best way to make a vector that is non-contiguous?


Solution

  • One quick way is to reverse it by using .invert_axis():

    use ndarray::{rcarr1, Axis};
    
    let mut arr = rcarr1(&[1.0, 2.0, 3.0]);
    dbg!(arr.is_standard_layout());
    
    arr.invert_axis(Axis(0));
    dbg!(arr.is_standard_layout());
    
    [src/main.rs:4] arr.is_standard_layout() = true
    [src/main.rs:7] arr.is_standard_layout() = false
    

    Technically it is still "contiguous"; the elements are still all right next to their neighbors. But its not "standard layout" since their locations in memory aren't in an increasing order.