/TGame/TCommon/Message/MsgBuffer.h

http://awoe.googlecode.com/ · C Header · 103 lines · 78 code · 23 blank · 2 comment · 3 complexity · 7dadc65c003285f8376d75e782977a1e MD5 · raw file

  1. #ifndef ___MSG_BUFFER___
  2. #define ___MSG_BUFFER___
  3. #include "Entry/LibExportCom.h"
  4. #pragma warning(push)
  5. #pragma warning(disable:4275)
  6. #pragma warning(disable:4251)
  7. #define MSG_BUFF_SIZE 1024
  8. class TCOM_API MsgBuffer : public std::streambuf
  9. {
  10. public:
  11. typedef boost::asio::const_buffers_1 const_buffers_type;
  12. typedef boost::asio::mutable_buffers_1 mutable_buffers_type;
  13. MsgBuffer()
  14. {
  15. setg(buffer_, buffer_, buffer_ + MSG_BUFF_SIZE);
  16. setp(buffer_, buffer_ + MSG_BUFF_SIZE);
  17. }
  18. std::size_t size() const
  19. {
  20. return pptr() - gptr();
  21. }
  22. std::size_t max_size() const
  23. {
  24. return MSG_BUFF_SIZE;
  25. }
  26. mutable_buffers_type prepare(std::size_t n = MSG_BUFF_SIZE)
  27. {
  28. return boost::asio::buffer(boost::asio::mutable_buffer(pptr(), MSG_BUFF_SIZE));
  29. }
  30. const_buffers_type data() const
  31. {
  32. return boost::asio::buffer(boost::asio::const_buffer(gptr(), (pptr() - gptr()) ));
  33. }
  34. void commit(std::size_t n)
  35. {
  36. if (pptr() + n > epptr())
  37. n = epptr() - pptr();
  38. pbump(static_cast<int>(n));
  39. setg(eback(), gptr(), pptr());
  40. }
  41. void consume(std::size_t n)
  42. {
  43. if (gptr() + n > pptr())
  44. n = pptr() - gptr();
  45. gbump(static_cast<int>(n));
  46. }
  47. void update_buffer_length4()
  48. {
  49. short val = size();
  50. memcpy(gptr()+4, (char*)&val, 2);
  51. }
  52. protected:
  53. enum { buffer_delta = 128 };
  54. int_type underflow()
  55. {
  56. if (gptr() < pptr())
  57. {
  58. setg(&buffer_[0], gptr(), pptr());
  59. return traits_type::to_int_type(*gptr());
  60. }
  61. else
  62. {
  63. return traits_type::eof();
  64. }
  65. }
  66. int_type overflow(int_type c)
  67. {
  68. // detail in boost buffer
  69. return traits_type::not_eof(c);
  70. }
  71. void reserve(std::size_t n)
  72. {
  73. // detail in boost buffer
  74. }
  75. private:
  76. char buffer_[MSG_BUFF_SIZE];
  77. };
  78. typedef boost::object_pool<MsgBuffer> MsgBufferFactory;
  79. #pragma warning(pop)
  80. #endif