string_pool.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "string_pool.h"
  2. namespace NMonitoring {
  3. ////////////////////////////////////////////////////////////////////////////////
  4. // TStringPoolBuilder
  5. ////////////////////////////////////////////////////////////////////////////////
  6. const TStringPoolBuilder::TValue* TStringPoolBuilder::PutIfAbsent(TStringBuf str) {
  7. Y_ENSURE(!IsBuilt_, "Cannot add more values after string has been built");
  8. auto [it, isInserted] = StrMap_.try_emplace(str, Max<ui32>(), 0);
  9. if (isInserted) {
  10. BytesSize_ += str.size();
  11. it->second.Index = StrVector_.size();
  12. StrVector_.emplace_back(it->first, &it->second);
  13. }
  14. TValue* value = &it->second;
  15. ++value->Frequency;
  16. return value;
  17. }
  18. const TStringPoolBuilder::TValue* TStringPoolBuilder::GetByIndex(ui32 index) const {
  19. return StrVector_.at(index).second;
  20. }
  21. TStringPoolBuilder& TStringPoolBuilder::Build() {
  22. if (RequiresSorting_) {
  23. // sort in reversed order
  24. std::sort(StrVector_.begin(), StrVector_.end(), [](auto& a, auto& b) {
  25. return a.second->Frequency > b.second->Frequency;
  26. });
  27. ui32 i = 0;
  28. for (auto& value : StrVector_) {
  29. value.second->Index = i++;
  30. }
  31. }
  32. IsBuilt_ = true;
  33. return *this;
  34. }
  35. ////////////////////////////////////////////////////////////////////////////////
  36. // TStringPool
  37. ////////////////////////////////////////////////////////////////////////////////
  38. void TStringPool::InitIndex(const char* data, ui32 size) {
  39. const char* begin = data;
  40. const char* end = begin + size;
  41. for (const char* p = begin; p != end; ++p) {
  42. if (*p == '\0') {
  43. Index_.push_back(TStringBuf(begin, p));
  44. begin = p + 1;
  45. }
  46. }
  47. }
  48. }