You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

75 rivejä
2.1 KiB

  1. #pragma once
  2. #include <vector>
  3. #include <streambuf>
  4. namespace cppcore
  5. {
  6. template<typename T_data, typename T_char>
  7. struct basic_vector_streambuf
  8. : public std::basic_streambuf<T_char>
  9. {
  10. private:
  11. static constexpr size_t min_grow = 32; // 32 Byte
  12. static constexpr size_t max_grow = 1024 * 1024; // 1 MByte
  13. public:
  14. using base_type = std::basic_streambuf<T_char>;
  15. using int_type = typename base_type::int_type;
  16. using char_type = typename base_type::char_type;
  17. using traits_type = typename base_type::traits_type;
  18. using data_type = T_data;
  19. using vector_type = std::vector<data_type>;
  20. static_assert(
  21. sizeof(data_type) >= sizeof(char_type),
  22. "Data type of the vector needs to be equal the char type!");
  23. private:
  24. size_t _grow; //!< Number of bytes to grow on overflow (0 to grow dynamically)
  25. vector_type _buffer; //!< Buffer to store data
  26. public:
  27. /**
  28. * @brief Constructor.
  29. *
  30. * @param[in] p_grow Number of bytes to grow on overflow (0 to grow dynamically)
  31. */
  32. inline basic_vector_streambuf(size_t p_grow = 0);
  33. /**
  34. * @brief Get the data that was written to the vector. The data remains in the streambuf.
  35. */
  36. inline vector_type get() const;
  37. /**
  38. * @brief Set the vector to read data from.
  39. */
  40. template<typename T_vector>
  41. inline void set(T_vector&& v);
  42. /**
  43. * @brief Get the data that was written to the vector. The data is completely extracted from the steambuf.
  44. */
  45. inline vector_type extract();
  46. protected:
  47. /**
  48. * @brief Buffer underflow. Try to get new data to read.
  49. */
  50. int_type underflow() override;
  51. /**
  52. * @brief Buffer overflow. Try to allocate more memory to write to.
  53. */
  54. int_type overflow(int_type ch) override;
  55. };
  56. using vector_streambuf = basic_vector_streambuf<uint8_t, char>;
  57. }
  58. #include "vector_streambuf.inl"