arraysadaunchecked-conversion

ada: unchecked Conversions and multi-level arrays


I am working on a program that needs to write a gigantic, multilayer array to several smaller buffers. I am looking to do this by using unchecked_conversion to flatten the multilayer array into a single layer array, then slice up the array. To recover it from memory, I want to append the parts back into order and Unchecked_Conversion them back to tohe original state.

The original implementation looks something like this:

-- array of up to 500 (most likely 100 - 200 though)
type Bottom_Level is array(1 .. 500) of Integer;

-- colors type
type Colors is (red, blue, green, purple);
for Colors use (red => 1, blue => 2, green => 3, purple => 4);

-- Middle Level Array
type Middle_Level is array(Colors) of Bottom_Level;

-- shapes type
type Shapes is (square, triangle, circle);
for Shapes use (square => 1, triangle => 2, circle => 3);

-- Top Level Array
type Top_Level is array(Shapes) of Middle_Level;

I would like to flatten it into an array like:

type Monolithic_Array is Array (1 .. 6000) of Integer;

Would Unchecked_Conversion do something of this sort, or would it mangle the original array so that it is unrecoverable? Thanks!


Solution

  • Yeah, since these are statically sized arrays, Unchecked_Conversion would work.

    (But it's a rather unusual way to go about this. Had we some idea of what you're actually trying to do, a more apt data structure could perhaps be suggested.)

    Another approach is aliasing (warning, not compiled):

    TL     : Top_Level;
    
    Buffer : Monolithic_Array;
    for Buffer'Address use TL'Address;
    

    So long as you populate your receiving buffer in the same sequence as you transmit the source buffer segments, it should reassemble just fine.