Skip to content

Commit db5cb7f

Browse files
committed
make GetTypeSize constexpr
1 parent 39625f4 commit db5cb7f

1 file changed

Lines changed: 32 additions & 31 deletions

File tree

include/flatbuffers/reflection.h

Lines changed: 32 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -43,37 +43,38 @@ constexpr bool IsLong(reflection::BaseType t) {
4343
return t == reflection::Long || t == reflection::ULong;
4444
}
4545

46+
// This needs to correspond to the BaseType enum.
47+
constexpr size_t kBaseTypeSize[] = {
48+
0, // None
49+
1, // UType
50+
1, // Bool
51+
1, // Byte
52+
1, // UByte
53+
2, // Short
54+
2, // UShort
55+
4, // Int
56+
4, // UInt
57+
8, // Long
58+
8, // ULong
59+
4, // Float
60+
8, // Double
61+
4, // String
62+
4, // Vector
63+
4, // Obj
64+
4, // Union
65+
0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds
66+
// errors.
67+
8, // Vector64
68+
69+
0 // MaxBaseType. This must be kept the last entry in this array.
70+
};
71+
static_assert(sizeof(kBaseTypeSize) / sizeof(size_t) == reflection::MaxBaseType + 1,
72+
"Size of sizes[] array does not match the count of BaseType "
73+
"enum values.");
74+
4675
// Size of a basic type, don't use with structs.
47-
inline size_t GetTypeSize(reflection::BaseType base_type) {
48-
// This needs to correspond to the BaseType enum.
49-
static size_t sizes[] = {
50-
0, // None
51-
1, // UType
52-
1, // Bool
53-
1, // Byte
54-
1, // UByte
55-
2, // Short
56-
2, // UShort
57-
4, // Int
58-
4, // UInt
59-
8, // Long
60-
8, // ULong
61-
4, // Float
62-
8, // Double
63-
4, // String
64-
4, // Vector
65-
4, // Obj
66-
4, // Union
67-
0, // Array. Only used in structs. 0 was chosen to prevent out-of-bounds
68-
// errors.
69-
8, // Vector64
70-
71-
0 // MaxBaseType. This must be kept the last entry in this array.
72-
};
73-
static_assert(sizeof(sizes) / sizeof(size_t) == reflection::MaxBaseType + 1,
74-
"Size of sizes[] array does not match the count of BaseType "
75-
"enum values.");
76-
return sizes[base_type];
76+
constexpr size_t GetTypeSize(reflection::BaseType base_type) {
77+
return kBaseTypeSize[base_type];
7778
}
7879

7980
// Same as above, but now correctly returns the size of a struct if
@@ -420,7 +421,7 @@ pointer_inside_vector<T, U> piv(T* ptr, std::vector<U>& vec) {
420421
return pointer_inside_vector<T, U>(ptr, vec);
421422
}
422423

423-
inline const char* UnionTypeFieldSuffix() { return "_type"; }
424+
constexpr const char* UnionTypeFieldSuffix() { return "_type"; }
424425

425426
// Helper to figure out the actual table type a union refers to.
426427
inline const reflection::Object& GetUnionType(

0 commit comments

Comments
 (0)