tempbuf.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #pragma once
  2. #include <util/system/defaults.h>
  3. #include <util/generic/ptr.h>
  4. /*
  5. * This is really fast buffer for temporary data.
  6. * For small sizes it works almost fast as pure alloca()
  7. * (by using perthreaded list of free blocks),
  8. * for big sizes it works as fast as malloc()/operator new()/...
  9. */
  10. class TTempBuf {
  11. public:
  12. /*
  13. * we do not want many friends for this class :)
  14. */
  15. class TImpl;
  16. TTempBuf();
  17. TTempBuf(size_t len);
  18. TTempBuf(const TTempBuf& b) noexcept;
  19. TTempBuf(TTempBuf&& b) noexcept;
  20. ~TTempBuf();
  21. TTempBuf& operator=(const TTempBuf& b) noexcept;
  22. TTempBuf& operator=(TTempBuf&& b) noexcept;
  23. Y_PURE_FUNCTION char* Data() noexcept;
  24. Y_PURE_FUNCTION const char* Data() const noexcept;
  25. Y_PURE_FUNCTION char* Current() noexcept;
  26. Y_PURE_FUNCTION const char* Current() const noexcept;
  27. Y_PURE_FUNCTION size_t Size() const noexcept;
  28. Y_PURE_FUNCTION size_t Filled() const noexcept;
  29. Y_PURE_FUNCTION size_t Left() const noexcept;
  30. void Reset() noexcept;
  31. void SetPos(size_t off);
  32. char* Proceed(size_t off);
  33. void Append(const void* data, size_t len);
  34. Y_PURE_FUNCTION bool IsNull() const noexcept;
  35. private:
  36. TIntrusivePtr<TImpl> Impl_;
  37. };
  38. template <typename T>
  39. class TTempArray: private TTempBuf {
  40. private:
  41. static T* TypedPointer(char* pointer) noexcept {
  42. return reinterpret_cast<T*>(pointer);
  43. }
  44. static const T* TypedPointer(const char* pointer) noexcept {
  45. return reinterpret_cast<const T*>(pointer);
  46. }
  47. static constexpr size_t RawSize(const size_t size) noexcept {
  48. return size * sizeof(T);
  49. }
  50. static constexpr size_t TypedSize(const size_t size) noexcept {
  51. return size / sizeof(T);
  52. }
  53. public:
  54. TTempArray() = default;
  55. TTempArray(size_t len)
  56. : TTempBuf(RawSize(len))
  57. {
  58. }
  59. T* Data() noexcept {
  60. return TypedPointer(TTempBuf::Data());
  61. }
  62. const T* Data() const noexcept {
  63. return TypedPointer(TTempBuf::Data());
  64. }
  65. T* Current() noexcept {
  66. return TypedPointer(TTempBuf::Current());
  67. }
  68. const T* Current() const noexcept {
  69. return TypedPointer(TTempBuf::Current());
  70. }
  71. size_t Size() const noexcept {
  72. return TypedSize(TTempBuf::Size());
  73. }
  74. size_t Filled() const noexcept {
  75. return TypedSize(TTempBuf::Filled());
  76. }
  77. T* Proceed(size_t off) {
  78. return (T*)TTempBuf::Proceed(RawSize(off));
  79. }
  80. };