2

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?

  • 3
    You can't make a `Vec` that is non-contiguous. But `is_standard_layout` can return false just by calling `reversed_axes`, so you could use that to test. – PitaJ Sep 26 '22 at 16:51

1 Answers1

2

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.

kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • I think that for a 1 dimensional array (like I am using) this should work the same as @PitaJ's solution above (using `reversed_axes` instead of `invert_axis`). – stackoverflowing321 Sep 27 '22 at 17:26