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