Speclib  0.1.2
The library for writing better CUDA libraries
Enum Validation

A general mechanism for checking if an enum value is in range. More...

Macros

#define SPARSE_ENUM_VALIDATOR(ENUM, ...)
 Generate a sp::validateEnumValue() specialisation for sparse enum type ENUM. More...
 
#define DENSE_ENUM_VALIDATOR(ENUM, FIRST, LAST)
 Generate a sp::validateEnumValue() specialisation for the dense enum, ENUM More...
 

Functions

template<typename EnumType >
void sp::validateEnumValue (std::underlying_type_t< EnumType >)
 Throw sp::EnumValueOutOfRange if an enum value is out of range. More...
 

Detailed Description

A general mechanism for checking if an enum value is in range.

Mostly useful for API input validation.

Macro Definition Documentation

◆ DENSE_ENUM_VALIDATOR

#define DENSE_ENUM_VALIDATOR (   ENUM,
  FIRST,
  LAST 
)
Value:
template<> \
inline void validateEnumValue<ENUM>(std::underlying_type_t<ENUM> v) { \
static_assert(sizeof(v) <= sizeof(int), "Enum validation needs to get smarter... :D"); \
if (v < FIRST || v > LAST) { \
throw sp::EnumValueOutOfRange(#ENUM, (int) v); \
} \
}
Thrown by validateEnumValue() when the runtime value provided is not valid for the target enum type.
Definition: SpecLibExceptions.hpp:73

Generate a sp::validateEnumValue() specialisation for the dense enum, ENUM

◆ SPARSE_ENUM_VALIDATOR

#define SPARSE_ENUM_VALIDATOR (   ENUM,
  ... 
)
Value:
template<> \
inline void validateEnumValue<ENUM>(std::underlying_type_t<ENUM> v) { \
static_assert(sizeof(v) <= sizeof(int), "Enum validation needs to get smarter... :D"); \
switch (v) { \
MAP_DENSE(ENUM_SWITCH_CASE, __VA_ARGS__) \
} \
\
throw sp::EnumValueOutOfRange(#ENUM, (int) v); \
}

Generate a sp::validateEnumValue() specialisation for sparse enum type ENUM.

This occupies more binary size and is slower than sp::DENSE_ENUM_VALIDATOR, but is necessary for enums that have gaps between their values.

These specialisations (along with the other validation routines) are made inline because they are very short, and we don't want a huge pile of call overhead at the entry to every API function. We want it to compile to a couple of comparison instructions for each argument, not a huge song and dance with 20-ish calls.

Function Documentation

◆ validateEnumValue()

template<typename EnumType >
void sp::validateEnumValue ( std::underlying_type_t< EnumType >  )

Throw sp::EnumValueOutOfRange if an enum value is out of range.

This function is useful for validating enum values being passed in from public APIs. To use it:

  • Use either SPARSE_ENUM_VALIDATOR or DENSE_ENUM_VALIDATOR to generate a validator for your enum type
  • Call this function as validateEnumValue<YourEnumType>(userProvidedInputValue);.
Template Parameters
EnumTypeThe enum type to validate against
Exceptions
<tt>sp::EnumValueOutOfRange</tt>if the value is not one declared in EnumType.