msg_vector.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #pragma once
  2. #include <vector>
  3. class MessageVector {
  4. public:
  5. struct header_t {
  6. size_t len_{};
  7. };
  8. size_t get_buff_size() const
  9. {
  10. return buffer_.size();
  11. }
  12. size_t get_buff_capacity() const
  13. {
  14. return buffer_.capacity();
  15. }
  16. void clear() {
  17. buffer_.clear();
  18. }
  19. void shrink(size_t size) {
  20. buffer_.reserve(size);
  21. }
  22. template<typename T, typename... Types>
  23. static size_t get_len(T value, Types... args)
  24. {
  25. if constexpr (std::is_convertible_v<T, std::size_t>) {
  26. return value ;
  27. }
  28. return 0;
  29. }
  30. template<typename... Types>
  31. bool put(Types&&... args){
  32. size_t total_len = (... + get_len(std::forward<Types>(args))) ;
  33. size_t buff_used = buffer_.size();
  34. buffer_.resize(buff_used + total_len + sizeof(header_t));
  35. header_t* p = (header_t*)(buffer_.data() + buff_used);
  36. p->len_ = total_len;
  37. char* pbuff = (char*)p + sizeof(header_t);
  38. auto func = [&pbuff](auto func, void* pdata, size_t len, auto&&... args) {
  39. memcpy(pbuff, pdata, len);
  40. pbuff += len;
  41. if constexpr (sizeof ... (args) > 0) {
  42. func(func, args...);
  43. }
  44. };
  45. func(func, std::forward<Types>(args)...);
  46. return true;
  47. }
  48. bool peek(size_t& it, const void*& pdata, size_t& len) const
  49. {
  50. size_t pos = it + sizeof(header_t);
  51. if(pos > buffer_.size()) {
  52. return false;
  53. }
  54. header_t* p = (header_t*)(buffer_.data() + it);
  55. if(pos + p->len_ > buffer_.size())
  56. {
  57. return false;
  58. }
  59. it = pos + p->len_;
  60. pdata = buffer_.data() + pos;
  61. len = p->len_;
  62. return true;
  63. }
  64. private:
  65. std::vector<char> buffer_;
  66. };