chat_message.h 1.6 KB

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