Can I specify a single type for all elements of an enum?

Qn: Can I specify the type(say u64) for all elements of an enum?

I am currently trying to write a ELF parsing lib in Rust. The following are a bunch of macros in the C header file elf.h.

#define ET_NONE         0               /* No file type */
#define ET_REL          1               /* Relocatable file */
#define ET_EXEC         2               /* Executable file */
#define ET_DYN          3               /* Shared object file */
#define ET_CORE         4               /* Core file */
#define ET_NUM          5               /* Number of defined types */
#define ET_LOOS         0xfe00          /* OS-specific range start */
#define ET_HIOS         0xfeff          /* OS-specific range end */
#define ET_LOPROC       0xff00          /* Processor-specific range start */
#define ET_HIPROC       0xffff          /* Processor-specific range end */

It would be helpful if I can write the above as an enum with each element to be of type u64. It will helpful while parsing an object file.

enum ElfObjectFileType // This needs to be of type u64.
{
ET_NONE,
.
.
.
}

Because I am unable to specify the type, I am doing the following right now.

const ET_NONE: u64  =   0;
const ET_REL: u64   =   1;
const ET_EXEC: u64  =   2;
const ET_DYN: u64   =   3;
const ET_CORE: u64  =   4;
const ET_NUM: u64   =   5;
const ET_LOOS: u64  =   0xfe00;
const ET_HIOS: u64  =   0xfeff;
const ET_LOPROC: u64=   0xff00;
const ET_HIPROC: u64=   0xffff; 

This works, but creating an enum groups all the relevant constants together.

Again the qn: Can I specify a single type for all elements of an enum? Or any other alternative would also be fine.

Thank you!

Well, you can use #[repr(u64)] to make sure the values are represented as u64 in memory. But this won't help you convert from or to u64 more conveniently in parser code. To be honest I think a list of constants is a clear way to write your intent here.
(especially as ELF is extensible—so you likely don't want things to fail while converting when there is no matching enumeration value).

What I sometimes do to have some type safety in cases like this where there is no exhaustive enumeration is to use a newtype that wraps the integer type and put the constants in it with impl (e.g. like here).

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.