Search code examples
multidimensional-arrayrustrow-major-ordercolumn-major-order

Is Rust multi-dimensional array row major and tightly packed?


I'm writing a 3D math library for my project, I want to know is the Rust column major or row major? For example I have a 2 dimensional array as matrix and I want to serve it to a C library (like OpenGL or Vulkan), for those library this is important to have a tightly packed column major array.


Solution

  • Well, let's find out:

    let arr: [[i8; 2]; 2] = [[1, 2], [8, 9]];
    
    println!(
        "{:?} {:?} {:?} {:?}", 
        &arr[0][0] as *const _,
        &arr[0][1] as *const _,
        &arr[1][0] as *const _,
        &arr[1][1] as *const _,
    );
    

    Prints 0x7fff5584ae74 0x7fff5584ae75 0x7fff5584ae76 0x7fff5584ae77 for example. So: yes these arrays with length known to compile time are tightly packed and (considering the common definition of the terms) row major.

    Note: the test above doesn't say that this always works! You can read more about this topic here.

    But: usually you use heap allocated arrays since you can't know the length beforehand. For that purpose it's idiomatic to use Vec. But there are no special rules for this type, so Vec<Vec<T>> is not tightly packed! For that reason Vec<Vec<T>> is not idiomatic anymore -- you should use a simple Vec<T> and do the calculation of the index yourself.

    Of course, writing the indexing calculation multiple times is not a good solution either. Instead, you should define some wrapper type which does the indexing for you. But as Sebastian Redl already mentioned: you are not the only one having this problem and there exist types exactly for this purpose already.