Every once and awhile, I want to convert a string to an enumeration in SystemVerilog. Casting from strings to enums is not supported in SystemVerilog, but luckily, it is possible to implement a function to do the appropriate conversion using built in methods designed for iterating over the enum values:
///////////
// enum.sv
///////////
class cmd;
// My enumerated type
typedef enum {UNKNOWN, ADD, SUB, MULT} cmd_e;
// Store the string -> enumerated type mappings.
static cmd_e enum_map[string];
// Configure the mapping from string to enum the first
// time this data structure is created.
virtual function void config_enum_map();
cmd_e e;
string str;
e = e.first();
str = e.name();
enum_map[str] = e;
// Note - we’ve already processed the first element above. This loop
// starts at the *second* element.
for (int i = 1; i < e.num(); i++) begin
e = e.next();
str = e.name();
enum_map[str] = e;
end
foreach (enum_map[m]) begin
$display(”enum_map[%5s] = %5s (%1d)”, m, enum_map[m].name(), enum_map[m]);
end
endfunction: config_enum_map
function cmd_e get_enum(string s);
get_enum = enum_map[s];
endfunction
function new();
if (enum_map.num() == 0) begin
config_enum_map();
end
endfunction: new
endclass: cmd
program test;
initial begin
cmd c = new;
cmd::cmd_e ce;
string s = “ADD”;
ce = c.get_enum(s);
$display(”Enum = %s (%1d) for string %s”, ce.name, ce, s);
end
endprogram
In VCS, run the above code using ‘vcsi -sverilog -ntb_opts dtm -R enum.sv’ to see the following output:
Compiler version VCSi Y-2006.06-SP1; Runtime version VCSi Y-2006.06-SP1; Oct 21 14:43 2007
enum_map[ADD] = ADD (1)
enum_map[MULT] = MULT (3)
enum_map[SUB] = SUB (2)
enum_map[UNKNOWN] = UNKNOWN (0)
Enum = ADD (1) for string ADD
V C S S i m u l a t i o n R e p o r t
1 comment:
Virtual memory is something that I seemingly will never have enough of. It feels like megabytes and gigabytes have become a permanent part of my every day existence. Ever since I bought a Micro SD Card for my Nintendo DS flash card, I've been constantly vigilant for high memory at low prices. I feel like I'm going insane.
(Posted from Nintendo DS running [url=http://kwstar88.zoomshare.com/2.shtml]R4i DSi[/url] Net10)
Post a Comment