common_types.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #ifndef __COMMON_TYPES_H
  2. #define __COMMON_TYPES_H
  3. #include <functional>
  4. #include <string>
  5. #include <unordered_map>
  6. struct tag_mem_t {
  7. std::unordered_map<unsigned int, std::string> memory;
  8. unsigned int convert(const std::string& v) {
  9. if (v.empty())
  10. return 0;
  11. unsigned int vh = std::hash<std::string>()(v);
  12. if (vh == 0) {
  13. throw std::runtime_error("Hash failed for string value: " + v);
  14. }
  15. auto tmp = memory.find(vh);
  16. if (tmp != memory.end() && tmp->second != v) {
  17. throw std::runtime_error("Double hash for string value: " + v);
  18. }
  19. memory[vh] = v;
  20. return vh;
  21. }
  22. };
  23. struct tag_t {
  24. unsigned int v;
  25. tag_t() : v(0) {}
  26. tag_t(unsigned int _v) : v(_v) {
  27. if (v == 0) {
  28. throw std::runtime_error("Cannot initialize tag to zero");
  29. }
  30. }
  31. template <typename T>
  32. tag_t(const T& _v, tag_mem_t& tm) : v(tm.convert(_v)) {}
  33. bool operator==(const tag_t& other) const {
  34. return v == other.v;
  35. }
  36. bool operator!=(const tag_t& other) const {
  37. return v != other.v;
  38. }
  39. bool operator<(const tag_t& other) const {
  40. return v < other.v;
  41. }
  42. bool null() const {
  43. return (v == 0);
  44. }
  45. };
  46. struct mean_deviation_t {
  47. double mean;
  48. double deviation;
  49. mean_deviation_t(double m = 0.0, double d = 0.0) : mean(m), deviation(d) {}
  50. };
  51. namespace std {
  52. template <>
  53. struct hash<tag_t> {
  54. size_t operator()(tag_t t) const {
  55. return t.v;
  56. }
  57. };
  58. }
  59. #endif