chat_message.hpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // chat_message.hpp
  3. // ~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 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. #ifndef CHAT_MESSAGE_HPP
  11. #define CHAT_MESSAGE_HPP
  12. #include <cstdio>
  13. #include <cstdlib>
  14. #include <cstring>
  15. class chat_message
  16. {
  17. public:
  18. enum { header_length = 4 };
  19. enum { max_body_length = 512 };
  20. chat_message()
  21. : body_length_(0)
  22. {
  23. }
  24. const char* data() const
  25. {
  26. return data_;
  27. }
  28. char* data()
  29. {
  30. return data_;
  31. }
  32. std::size_t length() const
  33. {
  34. return header_length + body_length_;
  35. }
  36. const char* body() const
  37. {
  38. return data_ + header_length;
  39. }
  40. char* body()
  41. {
  42. return data_ + header_length;
  43. }
  44. std::size_t body_length() const
  45. {
  46. return body_length_;
  47. }
  48. void body_length(std::size_t new_length)
  49. {
  50. body_length_ = new_length;
  51. if (body_length_ > max_body_length)
  52. body_length_ = max_body_length;
  53. }
  54. bool decode_header()
  55. {
  56. char header[header_length + 1] = "";
  57. std::strncat(header, data_, header_length);
  58. body_length_ = std::atoi(header);
  59. if (body_length_ > max_body_length)
  60. {
  61. body_length_ = 0;
  62. return false;
  63. }
  64. return true;
  65. }
  66. void encode_header()
  67. {
  68. char header[header_length + 1] = "";
  69. std::sprintf(header, "%4d", static_cast<int>(body_length_));
  70. std::memcpy(data_, header, header_length);
  71. }
  72. private:
  73. char data_[header_length + max_body_length];
  74. std::size_t body_length_;
  75. };
  76. #endif // CHAT_MESSAGE_HPP