chat_message.hpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. 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. size_t body_length() const
  45. {
  46. return body_length_;
  47. }
  48. void body_length(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. using namespace std; // For strncat and atoi.
  57. char header[header_length + 1] = "";
  58. strncat(header, data_, header_length);
  59. body_length_ = atoi(header);
  60. if (body_length_ > max_body_length)
  61. {
  62. body_length_ = 0;
  63. return false;
  64. }
  65. return true;
  66. }
  67. void encode_header()
  68. {
  69. using namespace std; // For sprintf and memcpy.
  70. char header[header_length + 1] = "";
  71. sprintf(header, "%4d", static_cast<int>(body_length_));
  72. memcpy(data_, header, header_length);
  73. }
  74. private:
  75. char data_[header_length + max_body_length];
  76. size_t body_length_;
  77. };
  78. #endif // CHAT_MESSAGE_HPP