hvar.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #ifndef HV_VAR_H_
  2. #define HV_VAR_H_
  3. #include <stdint.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. class HVar {
  7. public:
  8. enum Type {
  9. UNKNOWN,
  10. BOOLEAN,
  11. INTEGER,
  12. FLOAT,
  13. STRING,
  14. POINTER
  15. } type;
  16. union Data {
  17. bool b;
  18. int64_t i;
  19. double f;
  20. char* str;
  21. void* ptr;
  22. } data;
  23. HVar() {memset(&data, 0, sizeof(data)); type = UNKNOWN;}
  24. HVar(bool b) {data.b = b; type = BOOLEAN;}
  25. HVar(int64_t i) {data.i = i; type = INTEGER;}
  26. HVar(double f) {data.f = f; type = FLOAT;}
  27. HVar(char* str) {
  28. data.str = (char*)malloc(strlen(str)+1);
  29. strcpy(data.str, str);
  30. type = STRING;
  31. }
  32. HVar(void* ptr) {data.ptr = ptr; type = POINTER;}
  33. ~HVar() {
  34. if (type == STRING && data.str) {
  35. free(data.str);
  36. data.str = NULL;
  37. }
  38. }
  39. bool isNull() {return type == UNKNOWN;}
  40. bool isValid() {return type != UNKNOWN;}
  41. bool toBool() {return data.b;}
  42. int64_t toInt() {return data.i;}
  43. double toFloat() {return data.f;}
  44. char* toString() {return data.str;}
  45. void* toPointer() {return data.ptr;}
  46. };
  47. #endif // HV_VAR_H_