]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp11/chat/chat_message.hpp
add subtree-ish sources for 12.0.3
[ceph.git] / ceph / src / boost / libs / asio / example / cpp11 / chat / chat_message.hpp
1 //
2 // chat_message.hpp
3 // ~~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com)
6 //
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9 //
10
11 #ifndef CHAT_MESSAGE_HPP
12 #define CHAT_MESSAGE_HPP
13
14 #include <cstdio>
15 #include <cstdlib>
16 #include <cstring>
17
18 class chat_message
19 {
20 public:
21 enum { header_length = 4 };
22 enum { max_body_length = 512 };
23
24 chat_message()
25 : body_length_(0)
26 {
27 }
28
29 const char* data() const
30 {
31 return data_;
32 }
33
34 char* data()
35 {
36 return data_;
37 }
38
39 std::size_t length() const
40 {
41 return header_length + body_length_;
42 }
43
44 const char* body() const
45 {
46 return data_ + header_length;
47 }
48
49 char* body()
50 {
51 return data_ + header_length;
52 }
53
54 std::size_t body_length() const
55 {
56 return body_length_;
57 }
58
59 void body_length(std::size_t new_length)
60 {
61 body_length_ = new_length;
62 if (body_length_ > max_body_length)
63 body_length_ = max_body_length;
64 }
65
66 bool decode_header()
67 {
68 char header[header_length + 1] = "";
69 std::strncat(header, data_, header_length);
70 body_length_ = std::atoi(header);
71 if (body_length_ > max_body_length)
72 {
73 body_length_ = 0;
74 return false;
75 }
76 return true;
77 }
78
79 void encode_header()
80 {
81 char header[header_length + 1] = "";
82 std::sprintf(header, "%4d", static_cast<int>(body_length_));
83 std::memcpy(data_, header, header_length);
84 }
85
86 private:
87 char data_[header_length + max_body_length];
88 std::size_t body_length_;
89 };
90
91 #endif // CHAT_MESSAGE_HPP