Jump to content

Check if string is 'inside' an enum

Recommended Posts

Is there an easy (concise, maybe one-liner) way to check if a string is 'inside' an enum?


typedef enum {alpha, beta, gamma, delta, epsilon} my_enum;
string my_string;
my_string = <something>; 

//I know this is not possible, but I try to do something like this
if (my_string inside {my_enum.names})  // where names would imply all of the enumeration option strings


I try to avoid walking thru all of the enumerated values, which is what I currently do (and which works fine).

Link to comment
Share on other sites

have a look at uvm_enum_wrapper in uvm12+. you could simply do the following (untested)


class myenumwrapper#(type T) extends uvm_enum_wrapper#(T);

static function bit is_inside(string x); return map.exists(x); endfunction


// and later




Link to comment
Share on other sites

Make it easy. Do a type cast to string. See below the code:

module top;

typedef enum {alpha, beta, gamma, delta, epsilon} my_enum;
string   my_string;
my_enum  state;

initial begin
  state = beta;
  my_string = string'(state.name);
  $display("string = %s", my_string);


Link to comment
Share on other sites

@uwes, thank you.  For better or worse, the project that I work on for this does not use UVM.  (Yes, I realize that this is a UVM forum and that my question is just a vanilla SV one.)   I'll keep this response you sent in mind for the future and look forward to trying it.  That looks like a clear and terse solution - which is what I look for.  (Hopefully my next project uses UVM.)

@chr_sue, Thanks.  But what I try to do is the reverse.  i.e. to see if the value of my_string (which is of type string) is one of the my_enum states.   So, using the cast style you show, I'd need to cast each state of my_enum to string, and then compare it.  As it is, I can just do a direct compare to see if there is a match, without any cast.   Thank you, though.  You got me thinking about this differently.

For now, I just walk thru my_enum and check each state for a match with my_string, to see if my_string has a legal value.

(To provide some more details, I am checking that a command-line input plusarg string is of a legal value for the test.  The legal values are stored as an enum.  Storing them as an enum allows them to be used elsewhere; as opposed to just having an array of legal string values.)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...