CppWAMP
C++11 client library for the WAMP protocol
rawsockheader.hpp
1 /*------------------------------------------------------------------------------
2  Copyright Butterfly Energy Systems 2014-2015.
3  Distributed under the Boost Software License, Version 1.0.
4  http://www.boost.org/LICENSE_1_0.txt
5 ------------------------------------------------------------------------------*/
6 
7 #ifndef CPPWAMP_INTERNAL_RAWSOCKHEADER_HPP
8 #define CPPWAMP_INTERNAL_RAWSOCKHEADER_HPP
9 
10 #include <cstdint>
11 #include "endian.hpp"
12 
13 namespace wamp
14 {
15 
16 namespace internal
17 {
18 
19 //------------------------------------------------------------------------------
20 enum class RawsockMsgType
21 {
22  wamp,
23  ping,
24  pong
25 };
26 
27 //------------------------------------------------------------------------------
28 class RawsockHeader
29 {
30 public:
31  static RawsockHeader fromBigEndian(uint32_t big)
32  {return RawsockHeader(endian::bigToNative32(big));}
33 
34  RawsockHeader() : hdr_(0) {}
35 
36  explicit RawsockHeader(uint32_t hostOrder) : hdr_(hostOrder) {}
37 
38  bool msgTypeIsValid() const
39  {
40  auto type = msgType();
41  return type == RawsockMsgType::wamp ||
42  type == RawsockMsgType::ping ||
43  type == RawsockMsgType::pong;
44  }
45 
46  RawsockMsgType msgType() const
47  {
48  return get<RawsockMsgType>(msgTypeMask_, msgTypePos_);
49  }
50 
51  size_t length() const {return get<size_t>(lengthMask_);}
52 
53  uint32_t toBigEndian() const {return endian::nativeToBig32(hdr_);}
54 
55  uint32_t toHostOrder() const {return hdr_;}
56 
57  RawsockHeader& setMsgType(RawsockMsgType msgType)
58  {return put(msgType, msgTypePos_);}
59 
60  RawsockHeader& setLength(size_t length)
61  {return put(length, lengthPos_);}
62 
63 private:
64  static constexpr uint32_t msgTypeMask_ = 0xff000000;
65  static constexpr uint32_t lengthMask_ = 0x00ffffff;
66  static constexpr int msgTypePos_ = 24;
67  static constexpr int lengthPos_ = 0;
68 
69  template <typename T = uint32_t>
70  T get(uint32_t mask, int pos = 0) const
71  {return static_cast<T>((hdr_ & mask) >> pos);}
72 
73  template <typename T>
74  RawsockHeader& put(T value, int pos = 0)
75  {hdr_ |= (static_cast<uint32_t>(value) << pos); return *this;}
76 
77  uint32_t hdr_;
78 };
79 
80 } // namespace internal
81 
82 } // namespace wamp
83 
84 #endif // CPPWAMP_INTERNAL_RAWSOCKHEADER_HPP
wamp
Definition: anyhandler.hpp:36