labels.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "labels.h"
  2. #include <util/stream/output.h>
  3. #include <util/string/split.h>
  4. static void OutputLabels(IOutputStream& out, const NMonitoring::ILabels& labels) {
  5. size_t i = 0;
  6. out << '{';
  7. for (const auto& label: labels) {
  8. if (i++ > 0) {
  9. out << TStringBuf(", ");
  10. }
  11. out << label;
  12. }
  13. out << '}';
  14. }
  15. template <>
  16. void Out<NMonitoring::ILabelsPtr>(IOutputStream& out, const NMonitoring::ILabelsPtr& labels) {
  17. OutputLabels(out, *labels);
  18. }
  19. template <>
  20. void Out<NMonitoring::ILabels>(IOutputStream& out, const NMonitoring::ILabels& labels) {
  21. OutputLabels(out, labels);
  22. }
  23. template <>
  24. void Out<NMonitoring::ILabel>(IOutputStream& out, const NMonitoring::ILabel& labels) {
  25. out << labels.Name() << "=" << labels.Value();
  26. }
  27. Y_MONLIB_DEFINE_LABELS_OUT(NMonitoring::TLabels);
  28. Y_MONLIB_DEFINE_LABEL_OUT(NMonitoring::TLabel);
  29. namespace NMonitoring {
  30. bool TryLoadLabelsFromString(TStringBuf sb, ILabels& labels) {
  31. if (sb.Empty()) {
  32. return false;
  33. }
  34. if (!sb.StartsWith('{') || !sb.EndsWith('}')) {
  35. return false;
  36. }
  37. sb.Skip(1);
  38. sb.Chop(1);
  39. if (sb.Empty()) {
  40. return true;
  41. }
  42. bool ok = true;
  43. TVector<std::pair<TStringBuf, TStringBuf>> rawLabels;
  44. StringSplitter(sb).SplitBySet(" ,").SkipEmpty().Consume([&] (TStringBuf label) {
  45. TStringBuf key, value;
  46. ok &= label.TrySplit('=', key, value);
  47. if (!ok) {
  48. return;
  49. }
  50. rawLabels.emplace_back(key, value);
  51. });
  52. if (!ok) {
  53. return false;
  54. }
  55. for (auto&& [k, v] : rawLabels) {
  56. labels.Add(k, v);
  57. }
  58. return true;
  59. }
  60. bool TryLoadLabelsFromString(IInputStream& is, ILabels& labels) {
  61. TString str = is.ReadAll();
  62. return TryLoadLabelsFromString(str, labels);
  63. }
  64. } // namespace NMonitoring