Browse Source

type and offset size in value are a constant

Kajetan Johannes Hammerle 1 year ago
parent
commit
86a45aa6c2
2 changed files with 13 additions and 5 deletions
  1. 9 5
      DataType.c
  2. 4 0
      DataType.h

+ 9 - 5
DataType.c

@@ -26,8 +26,11 @@ const char* vtGetName(ValueType vt) {
     return "invalid";
 }
 
+#define VALUE_TYPE_MASK ((1u << VALUE_TYPE_BIT_SIZE) - 1u)
+#define VALUE_MAX_OFFSET ((1u << (32 - VALUE_TYPE_BIT_SIZE)) - 1u)
+
 ValueType vGetType(Value v) {
-    uint32 type = v.typeAndOffset & 0xF;
+    uint32 type = v.typeAndOffset & VALUE_TYPE_MASK;
     if(type >= VT_LAST) {
         return VT_INVALID;
     }
@@ -38,19 +41,20 @@ bool vSetType(Value* v, ValueType vt) {
     if(v == NULL || vt < 0 || vt >= VT_LAST) {
         return true;
     }
-    v->typeAndOffset = (v->typeAndOffset & 0xFFFFFFF0) | vt;
+    v->typeAndOffset = (v->typeAndOffset & ~VALUE_TYPE_MASK) | vt;
     return false;
 }
 
 uint32 vGetOffset(Value v) {
-    return v.typeAndOffset >> 4;
+    return v.typeAndOffset >> VALUE_TYPE_BIT_SIZE;
 }
 
 bool vSetOffset(Value* v, uint32 offset) {
-    if(v == NULL || (offset & 0xF0000000) != 0) {
+    if(v == NULL || offset > VALUE_MAX_OFFSET) {
         return true;
     }
-    v->typeAndOffset = (v->typeAndOffset & 0x0000000F) | (offset << 4);
+    v->typeAndOffset =
+        (v->typeAndOffset & VALUE_TYPE_MASK) | (offset << VALUE_TYPE_BIT_SIZE);
     return false;
 }
 

+ 4 - 0
DataType.h

@@ -5,6 +5,7 @@
 extern "C" {
 #endif
 
+#include <assert.h>
 #include <stdbool.h>
 
 #include "Check.h"
@@ -20,6 +21,9 @@ typedef enum {
     VT_LAST
 } ValueType;
 
+#define VALUE_TYPE_BIT_SIZE 4
+static_assert(VT_LAST < (1 << VALUE_TYPE_BIT_SIZE));
+
 typedef struct {
     uint32 typeAndOffset;
     union {