buffer.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #pragma once
  2. #include <util/system/types.h>
  3. #include <util/system/yassert.h>
  4. #include <cstddef>
  5. namespace NYsonPull {
  6. //! \brief A non-owning buffer model.
  7. //!
  8. //! Represents a \p pos pointer moving between \p begin and \p end.
  9. template <typename T>
  10. class buffer {
  11. T* begin_ = nullptr;
  12. T* pos_ = nullptr;
  13. T* end_ = nullptr;
  14. public:
  15. T* begin() const noexcept {
  16. return begin_;
  17. }
  18. T* pos() const noexcept {
  19. return pos_;
  20. }
  21. T* end() const noexcept {
  22. return end_;
  23. }
  24. //! \brief Amount of data after current position.
  25. size_t available() const noexcept {
  26. return end_ - pos_;
  27. }
  28. //! \brief Amount of data before current position.
  29. size_t used() const noexcept {
  30. return pos_ - begin_;
  31. }
  32. //! \brief Move current position \p nbytes forward.
  33. void advance(size_t nbytes) noexcept {
  34. Y_ASSERT(pos_ + nbytes <= end_);
  35. pos_ += nbytes;
  36. }
  37. //! \brief Reset buffer pointers.
  38. void reset(T* new_begin, T* new_end, T* new_pos) {
  39. begin_ = new_begin;
  40. pos_ = new_pos;
  41. end_ = new_end;
  42. }
  43. //! \brief Reset buffer to beginning
  44. void reset(T* new_begin, T* new_end) {
  45. reset(new_begin, new_end, new_begin);
  46. }
  47. };
  48. class output_buffer: public buffer<ui8> {
  49. public:
  50. //! \brief An output buffer is empty when there is no data written to it.
  51. bool is_empty() const noexcept {
  52. return pos() == begin();
  53. }
  54. //! \brief An output buffer is full when there is no space to write more data to it.
  55. bool is_full() const noexcept {
  56. return pos() == end();
  57. }
  58. };
  59. class input_buffer: public buffer<const ui8> {
  60. public:
  61. //! An input stream is empty when there is no data to read in it.
  62. bool is_empty() const noexcept {
  63. return pos() == end();
  64. }
  65. };
  66. }