buffer.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #pragma once
  2. #include <string>
  3. #include <vector>
  4. #include "base/define.h"
  5. namespace ylib
  6. {
  7. class mem_pool
  8. {
  9. public:
  10. mem_pool(size_t initial_length = 1024);
  11. ~mem_pool();
  12. void append(const uchar* data,size_t length);
  13. void clear();
  14. size_t length() const;
  15. uchar* data() const;
  16. void resize(size_t length);
  17. void set(const uchar* data,size_t length);
  18. bool empty() const;
  19. private:
  20. void renew(size_t length);
  21. public:
  22. // 内存数据指针
  23. uchar* m_data = nullptr;
  24. // 内存长度
  25. size_t m_length = 0;
  26. // 使用长度
  27. size_t m_use_length = 0;
  28. };
  29. /**
  30. * @brief BUFF字节流
  31. */
  32. class buffer
  33. {
  34. public:
  35. buffer(size_t initial_length = 1024);
  36. buffer(char data, size_t len);
  37. buffer(const char* data,size_t len);
  38. buffer(const ylib::buffer& data);
  39. buffer(const std::string& data);
  40. buffer(std::initializer_list<uchar> char_list);
  41. ~buffer();
  42. void set(const char* data, size_t length);
  43. void set(const ylib::buffer& data);
  44. void append(const std::string& data);
  45. void append(const char* data, size_t length);
  46. void append(const ylib::buffer& data);
  47. void append(std::initializer_list<uchar> char_list);
  48. template<typename T>
  49. void append(const T& value) {
  50. append((const char*)&value, sizeof(T));
  51. }
  52. void clear();
  53. void resize(size_t length);
  54. size_t find(const char* data, size_t len, size_t start_pos = 0) const;
  55. size_t find(const ylib::buffer& data, size_t start_pos = 0) const;
  56. std::vector<size_t> find_list(const ylib::buffer& value, size_t start = 0) const;
  57. std::vector<ylib::buffer> split(const ylib::buffer& value, size_t start = 0) const;
  58. std::string to_string() const;
  59. bool empty() const;
  60. ylib::buffer left(size_t len) const;
  61. ylib::buffer right(size_t len) const;
  62. ylib::buffer sub(size_t start,size_t len) const;
  63. ylib::buffer sub(size_t start) const;
  64. //ylib::buffer sub(size_t start,size_t len);
  65. operator std::string() const;
  66. ylib::buffer operator+(const ylib::buffer& other) const;
  67. ylib::buffer& operator=(const std::string& data);
  68. ylib::buffer& operator=(const ylib::buffer& data);
  69. unsigned char& operator[](size_t index) const;
  70. const char* data() const;
  71. const size_t length() const;
  72. const size_t size() const { return length(); };
  73. ylib::buffer trim_end(char value);
  74. ylib::buffer trim_begin(char value);
  75. ylib::buffer trim(char value);
  76. std::string to_hex();
  77. size_t& cursor(){ return m_cursor; }
  78. private:
  79. ylib::mem_pool m_data;
  80. size_t m_cursor = 0;
  81. };
  82. }