hmbdc
simplify-high-performance-messaging-programming
TypedString.hpp
1 #include "hmbdc/Copyright.hpp"
2 #pragma once
3 #include "hmbdc/Exception.hpp"
4 #include "hmbdc/Compile.hpp"
5 // #include "hmbdc/pattern/Typed.h"
6 
7 #include <string>
8 #include <stdexcept>
9 #include <functional>
10 #include <algorithm>
11 #include <stdio.h>
12 #include <string.h>
13 
14 namespace hmbdc { namespace text {
15 struct TypedStringHash;
16 template <char const NAME[], uint16_t SIZE>
18 {
19 private:
21  char v_[SIZE];
22  friend struct std::hash<TypedString<NAME, SIZE>>;
23 
24 public:
25  using rawType = char[SIZE];
26  enum{capacity = SIZE,};
27 
28  TypedString(){v_[0] = 0;}
29  explicit TypedString(char const* s, size_t len = SIZE) {
30 #ifndef __clang__
31 #pragma GCC diagnostic push
32 #pragma GCC diagnostic ignored "-Wformat-truncation"
33 #endif
34  snprintf(v_, std::min((size_t)SIZE, len + 1), "%s", s);
35  }
36  explicit TypedString(std::string const& s) {
37  snprintf(v_, SIZE, "%s", s.c_str());
38  }
39 #ifndef __clang__
40 #pragma GCC diagnostic pop
41 #endif
42  static constexpr char const* typeName() { return NAME; }
43  char const* c_str() const { return v_; }
44  bool operator == (ThisT const& other) const {
45  return strncmp(v_, other.v_, SIZE) == 0;
46  }
47  bool operator != (ThisT const& other) const {
48  return strncmp(v_, other.v_, SIZE) != 0;
49  }
50  bool operator < (ThisT const& other) const {
51  return strncmp(v_, other.v_, SIZE) < 0;
52  }
53  friend
54  std::ostream& operator << (std::ostream& os, ThisT const& s) {
55  os << s.v_;
56  return os;
57  }
58  friend
59  std::istream& operator >> (std::istream& is, ThisT& s) {
60  std::string tmp;
61  is >> tmp;
62  s = TypedString(tmp);
63  return is;
64  }
65 
66  void clear() { v_[0] = 0; }
67  size_t size() const {
68  char const* b = v_;
69  return std::find(b, b + SIZE, '\x00') - b;
70  }
71 
72  size_t copyTo(char* to) const {
73  char const* b = v_;
74  char * p = to;
75  for (; p != to + capacity && *b;) {
76  *(p++) = *(b++);
77  }
78  return p - to;
79  }
80 };
81 
82 }}
83 
84 namespace std {
85  template <char const NAME[], uint16_t SIZE>
86  struct hash<hmbdc::text::TypedString<NAME, SIZE>> {
87  size_t operator()(const hmbdc::text::TypedString<NAME, SIZE>& x) const {
88  uint32_t hash, i;
89  for(hash = i = 0; i < SIZE && x.v_[i]; ++i)
90  {
91  hash += x.v_[i];
92  hash += (hash << 10);
93  hash ^= (hash >> 6);
94  }
95  hash += (hash << 3);
96  hash ^= (hash >> 11);
97  hash += (hash << 15);
98  return hash;
99  }
100  };
101 };
Definition: TypedString.hpp:84
Definition: TypedString.hpp:17
Definition: Base.hpp:12