string_pool.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #pragma once
  2. #include <util/generic/hash.h>
  3. #include <util/generic/vector.h>
  4. namespace NMonitoring {
  5. ////////////////////////////////////////////////////////////////////////////////
  6. // TStringPoolBuilder
  7. ////////////////////////////////////////////////////////////////////////////////
  8. class TStringPoolBuilder {
  9. public:
  10. struct TValue: TNonCopyable {
  11. TValue(ui32 idx, ui32 freq)
  12. : Index{idx}
  13. , Frequency{freq}
  14. {
  15. }
  16. ui32 Index;
  17. ui32 Frequency;
  18. };
  19. public:
  20. const TValue* PutIfAbsent(TStringBuf str);
  21. const TValue* GetByIndex(ui32 index) const;
  22. /// Determines whether pool must be sorted by value frequencies
  23. TStringPoolBuilder& SetSorted(bool sorted) {
  24. RequiresSorting_ = sorted;
  25. return *this;
  26. }
  27. TStringPoolBuilder& Build();
  28. TStringBuf Get(ui32 index) const {
  29. Y_ENSURE(IsBuilt_, "Pool must be sorted first");
  30. return StrVector_.at(index).first;
  31. }
  32. TStringBuf Get(const TValue* value) const {
  33. return StrVector_.at(value->Index).first;
  34. }
  35. template <typename TConsumer>
  36. void ForEach(TConsumer&& c) {
  37. Y_ENSURE(IsBuilt_, "Pool must be sorted first");
  38. for (const auto& value : StrVector_) {
  39. c(value.first, value.second->Index, value.second->Frequency);
  40. }
  41. }
  42. size_t BytesSize() const noexcept {
  43. return BytesSize_;
  44. }
  45. size_t Count() const noexcept {
  46. return StrMap_.size();
  47. }
  48. private:
  49. THashMap<TString, TValue> StrMap_;
  50. TVector<std::pair<TStringBuf, TValue*>> StrVector_;
  51. bool RequiresSorting_ = false;
  52. bool IsBuilt_ = false;
  53. size_t BytesSize_ = 0;
  54. };
  55. ////////////////////////////////////////////////////////////////////////////////
  56. // TStringPool
  57. ////////////////////////////////////////////////////////////////////////////////
  58. class TStringPool {
  59. public:
  60. TStringPool(const char* data, ui32 size) {
  61. InitIndex(data, size);
  62. }
  63. TStringBuf Get(ui32 i) const {
  64. return Index_.at(i);
  65. }
  66. size_t Size() const {
  67. return Index_.size();
  68. }
  69. private:
  70. void InitIndex(const char* data, ui32 size);
  71. private:
  72. TVector<TStringBuf> Index_;
  73. };
  74. }