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