Add static asserts to ensure that reflection API arrays are kept in sync (#5934)

* Add static asserts to ensure that reflection API arrays are kept in sync

* Move changes from generated file into source fbs file

* Rename enum value and regenerate reflection_generated.h

* Add comments to each entries of type sizes array
This commit is contained in:
Laurentiu Cristofor
2020-06-02 09:50:56 -07:00
committed by GitHub
parent 988164f6e1
commit d026e6f071
3 changed files with 37 additions and 8 deletions

View File

@@ -46,7 +46,30 @@ inline bool IsLong(reflection::BaseType t) {
// Size of a basic type, don't use with structs.
inline size_t GetTypeSize(reflection::BaseType base_type) {
// This needs to correspond to the BaseType enum.
static size_t sizes[] = { 0, 1, 1, 1, 1, 2, 2, 4, 4, 8, 8, 4, 8, 4, 4, 4, 4 };
static size_t sizes[] = {
0, // None
1, // UType
1, // Bool
1, // Byte
1, // UByte
2, // Short
2, // UShort
4, // Int
4, // UInt
8, // Long
8, // ULong
4, // Float
8, // Double
4, // String
4, // Vector
4, // Obj
4, // Union
0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds errors.
0 // MaxBaseType. This must be kept the last entry in this array.
};
static_assert(sizeof(sizes) / sizeof(size_t) == reflection::MaxBaseType + 1,
"Size of sizes[] array does not match the count of BaseType enum values.");
return sizes[base_type];
}

View File

@@ -53,10 +53,11 @@ enum BaseType {
Vector = 14,
Obj = 15,
Union = 16,
Array = 17
Array = 17,
MaxBaseType = 18
};
inline const BaseType (&EnumValuesBaseType())[18] {
inline const BaseType (&EnumValuesBaseType())[19] {
static const BaseType values[] = {
None,
UType,
@@ -75,13 +76,14 @@ inline const BaseType (&EnumValuesBaseType())[18] {
Vector,
Obj,
Union,
Array
Array,
MaxBaseType
};
return values;
}
inline const char * const *EnumNamesBaseType() {
static const char * const names[19] = {
static const char * const names[20] = {
"None",
"UType",
"Bool",
@@ -100,13 +102,14 @@ inline const char * const *EnumNamesBaseType() {
"Obj",
"Union",
"Array",
"MaxBaseType",
nullptr
};
return names;
}
inline const char *EnumNameBaseType(BaseType e) {
if (flatbuffers::IsOutRange(e, None, Array)) return "";
if (flatbuffers::IsOutRange(e, None, MaxBaseType)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesBaseType()[index];
}

View File

@@ -24,12 +24,15 @@ enum BaseType : byte {
Vector,
Obj, // Used for tables & structs.
Union,
Array
Array,
// Add any new type above this value.
MaxBaseType
}
table Type {
base_type:BaseType;
element:BaseType = None; // Only if base_type == Vector
element:BaseType = None; // Only if base_type == Vector
// or base_type == Array.
index:int = -1; // If base_type == Object, index into "objects" below.
// If base_type == Union, UnionType, or integral derived