string_builder.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #pragma once
  2. #include <util/generic/string.h>
  3. namespace NYT {
  4. ////////////////////////////////////////////////////////////////////////////////
  5. //! A simple helper for constructing strings by a sequence of appends.
  6. class TStringBuilderBase
  7. {
  8. public:
  9. virtual ~TStringBuilderBase() = default;
  10. char* Preallocate(size_t size);
  11. void Reserve(size_t size);
  12. size_t GetLength() const;
  13. TStringBuf GetBuffer() const;
  14. void Advance(size_t size);
  15. void AppendChar(char ch);
  16. void AppendChar(char ch, int n);
  17. void AppendString(TStringBuf str);
  18. void AppendString(const char* str);
  19. template <size_t Length, class... TArgs>
  20. void AppendFormat(const char (&format)[Length], TArgs&&... args);
  21. template <class... TArgs>
  22. void AppendFormat(TStringBuf format, TArgs&&... args);
  23. void Reset();
  24. protected:
  25. char* Begin_ = nullptr;
  26. char* Current_ = nullptr;
  27. char* End_ = nullptr;
  28. virtual void DoReset() = 0;
  29. virtual void DoReserve(size_t newLength) = 0;
  30. static constexpr size_t MinBufferLength = 128;
  31. };
  32. ////////////////////////////////////////////////////////////////////////////////
  33. class TStringBuilder
  34. : public TStringBuilderBase
  35. {
  36. public:
  37. TString Flush();
  38. protected:
  39. TString Buffer_;
  40. void DoReset() override;
  41. void DoReserve(size_t size) override;
  42. };
  43. ////////////////////////////////////////////////////////////////////////////////
  44. //! Appends a certain delimiter starting from the second call.
  45. class TDelimitedStringBuilderWrapper
  46. : private TNonCopyable
  47. {
  48. public:
  49. TDelimitedStringBuilderWrapper(
  50. TStringBuilderBase* builder,
  51. TStringBuf delimiter = TStringBuf(", "));
  52. TStringBuilderBase* operator->();
  53. TStringBuilderBase* operator&();
  54. private:
  55. TStringBuilderBase* const Builder_;
  56. const TStringBuf Delimiter_;
  57. bool FirstCall_ = true;
  58. };
  59. ////////////////////////////////////////////////////////////////////////////////
  60. } // namespace NYT
  61. #define STRING_BUILDER_INL_H_
  62. #include "string_builder-inl.h"
  63. #undef STRING_BUILDER_INL_H_