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