EquipDev
EquipDev

Reputation: 5931

How to get number of elements in enumerated type

With an enumerated type, like the below, is there a nice way to get the number of elements in the enumerated type enum_t:

type enum_t is (ALFA, BRAVO, CHARLIE);  -- Number of elements is 3

-- Don't work: length is not valid attribute for enum_t
constant ENUM_LENGTH : natural := enum_t'length;  -- illegal!

Based on answer from David Koontz it can be done as:

constant ENUM_LENGTH : natural := enum_t'pos(enum_t'right) + 1;

Upvotes: 8

Views: 3498

Answers (1)

user1155120
user1155120

Reputation:

First find it's POSitional value, then you can get VHDL to tell you what it is:

entity enum_length is
end entity;

architecture foo of enum_length is
    type enum_t is (ALFA, BRAVO, CHARLIE);
    constant enum_left:     natural := enum_t'POS(ALFA);
    constant enum_right:    natural := enum_t'POS(CHARLIE);
begin
    assert FALSE 
         Report "CHARLIE POS = " & natural'IMAGE(enum_right);
end architecture;

ghdl -r enum_length
enum_length.vhdl:9:5:@0ms:(assertion error): CHARLIE POS = 2

See IEEE Std 1076-2008 5.2.2.1 (Enumeration types) General, para 6:

Each enumeration literal yields a different enumeration value. The predefined order relations between enumeration values follow the order of corresponding position numbers. The position number of the value of the first listed enumeration literal is zero; the position number for each additional enumeration literal is one more than that of its predecessor in the list.

So the Leftmost enumeration value's position is 0. The rightmost enumeration value's position is one less than the number of elements. You can also find the rightmost 'VAL and find it's position:

entity enum_length is
end entity;

architecture foo of enum_length is
    type enum_t is (ALFA, BRAVO, CHARLIE);
    constant enum_left:     natural := enum_t'POS(ALFA);
    constant enum_right:    natural := enum_t'POS(CHARLIE);
    constant enum_t_elems:  natural:= enum_t'POS(enum_t'RIGHT) + 1;
begin
--    assert FALSE 
--        Report "CHARLIE POS = " & natural'IMAGE(enum_right);

    assert FALSE 
        Report "enum_t number of elements = " & natural'IMAGE(enum_t_elems);
end architecture;

ghdl -r enum_length
enum_length.vhdl:13:5:@0ms:(assertion error): enum_t number of elements = 3

Upvotes: 7

Related Questions