util.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "util.h"
  2. #include <util/string/ascii.h>
  3. #include <functional>
  4. namespace {
  5. void ToSnakeCaseImpl(TString* const name, std::function<bool(const char)> requiresUnderscore) {
  6. bool requiresChanges = false;
  7. size_t size = name->size();
  8. for (size_t i = 0; i < name->size(); i++) {
  9. if (IsAsciiUpper(name->at(i))) {
  10. requiresChanges = true;
  11. if (i > 0 && requiresUnderscore(name->at(i - 1))) {
  12. size++;
  13. }
  14. }
  15. }
  16. if (!requiresChanges) {
  17. return;
  18. }
  19. if (size != name->size()) {
  20. TString result;
  21. result.reserve(size);
  22. for (size_t i = 0; i < name->size(); i++) {
  23. const char c = name->at(i);
  24. if (IsAsciiUpper(c)) {
  25. if (i > 0 && requiresUnderscore(name->at(i - 1))) {
  26. result += '_';
  27. }
  28. result += AsciiToLower(c);
  29. } else {
  30. result += c;
  31. }
  32. }
  33. *name = std::move(result);
  34. } else {
  35. name->to_lower();
  36. }
  37. }
  38. }
  39. namespace NProtobufJson {
  40. void ToSnakeCase(TString* const name) {
  41. ToSnakeCaseImpl(name, [](const char prev) { return prev != '_'; });
  42. }
  43. void ToSnakeCaseDense(TString* const name) {
  44. ToSnakeCaseImpl(name, [](const char prev) { return prev != '_' && !IsAsciiUpper(prev); });
  45. }
  46. bool EqualsIgnoringCaseAndUnderscores(TStringBuf s1, TStringBuf s2) {
  47. size_t i1 = 0, i2 = 0;
  48. while (i1 < s1.size() && i2 < s2.size()) {
  49. if (s1[i1] == '_') {
  50. ++i1;
  51. } else if (s2[i2] == '_') {
  52. ++i2;
  53. } else if (AsciiToUpper(s1[i1]) != AsciiToUpper(s2[i2])) {
  54. return false;
  55. } else {
  56. ++i1, ++i2;
  57. }
  58. }
  59. while (i1 < s1.size() && s1[i1] == '_') {
  60. ++i1;
  61. }
  62. while (i2 < s2.size() && s2[i2] == '_') {
  63. ++i2;
  64. }
  65. return (i1 == s1.size() && i2 == s2.size());
  66. }
  67. }