Search code examples
recordadasubtype

In Ada, how could I make subtype of records?


if I have a record type like this:

  type ABC is record
       A : Integer;
       B : Integer;
  end record;

How could I create a subtype of ABC with two Integer types whose range are specified?


Solution

  • While not answering your question per se (as NWS says, you can't do that), if instead of A and B being integers, they were to be arrays, you can do the following:

    package Record_Subtypes is
    
       type Int_Data is array (Integer range <>) of Integer;
    
       type ABC (X_Min, X_Max, Y_Min, Y_Max : Integer) is record
          A : Int_Data (X_Min .. X_Max);
          B : Int_Data (Y_Min .. Y_Max);
       end record;
    
       subtype ABC_4_4 is ABC(X_Min => 1, X_Max => 4,
                              Y_Min => 1, Y_Max => 4);
    
       subtype ABC_1_7_3_12 is ABC (X_Min => 1, X_Max => 7,
                                    Y_Min => 3, Y_Max => 12);
    end Record_Subtypes;
    

    The A and B record fields then utilize the index subtype as provided by the record discriminants.

    This is a nice trick I've used from time to time, useful when reading in variable length strings from an interface (such as a socket) where the number of bytes to read is supplied via fixed-sized header; or in the case of a variant record with an enumeration discriminant, I can subtype the record to a specific variant.