| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- //
- // chat_message.hpp
- // ~~~~~~~~~~~~~~~~
- //
- // Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
- //
- // Distributed under the Boost Software License, Version 1.0. (See accompanying
- // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
- //
- #ifndef EXPERIMENTAL_CHAT_MESSAGE_H
- #define EXPERIMENTAL_CHAT_MESSAGE_H
- #include <cstdio>
- #include <cstdlib>
- #include <cstring>
- class chat_message
- {
- public:
- enum
- {
- header_length = 4
- };
- enum
- {
- max_body_length = 512
- };
- chat_message() :
- body_length_(0)
- {
- }
- const char* data() const
- {
- return data_;
- }
- char* data()
- {
- return data_;
- }
- size_t length() const
- {
- return header_length + body_length_;
- }
- const char* body() const
- {
- return data_ + header_length;
- }
- char* body()
- {
- return data_ + header_length;
- }
- size_t body_length() const
- {
- return body_length_;
- }
- void body_length(size_t length)
- {
- body_length_ = length;
- if (body_length_ > max_body_length)
- body_length_ = max_body_length;
- }
- bool decode_header()
- {
- using namespace std;
- // For strncat and atoi.
- char header[header_length + 1] = "";
- strncat(header, data_, header_length);
- body_length_ = atoi(header);
- if (body_length_ > max_body_length)
- {
- body_length_ = 0;
- return false;
- }
- return true;
- }
- void encode_header()
- {
- using namespace std;
- // For sprintf and memcpy.
- char header[header_length + 1] = "";
- sprintf(header, "%4d", body_length_);
- memcpy(data_, header, header_length);
- }
- private:
- char data_[header_length + max_body_length];
- size_t body_length_;
- };
- #endif // EXPERIMENTAL_CHAT_MESSAGE_H
|