NameHelpers.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Google.ProtocolBuffers {
  5. /// <summary>
  6. /// Helpers for converting names to pascal case etc.
  7. /// </summary>
  8. internal class NameHelpers {
  9. internal static string UnderscoresToPascalCase(string input) {
  10. return UnderscoresToPascalOrCamelCase(input, true);
  11. }
  12. internal static string UnderscoresToCamelCase(string input) {
  13. return UnderscoresToPascalOrCamelCase(input, false);
  14. }
  15. /// <summary>
  16. /// Converts a string to Pascal or Camel case. The first letter is capitalized or
  17. /// lower-cased depending on <paramref name="pascal"/> is true.
  18. /// After the first letter, any punctuation is removed but triggers capitalization
  19. /// of the next letter. Digits are preserved but trigger capitalization of the next
  20. /// letter.
  21. /// All capitalisation is done in the invariant culture.
  22. /// </summary>
  23. private static string UnderscoresToPascalOrCamelCase(string input, bool pascal) {
  24. StringBuilder result = new StringBuilder();
  25. bool capitaliseNext = pascal;
  26. for (int i = 0; i < input.Length; i++) {
  27. char c = input[i];
  28. if ('a' <= c && c <= 'z') {
  29. if (capitaliseNext) {
  30. result.Append(char.ToUpperInvariant(c));
  31. } else {
  32. result.Append(c);
  33. }
  34. capitaliseNext = false;
  35. } else if ('A' <= c && c <= 'Z') {
  36. if (i == 0 && !pascal) {
  37. // Force first letter to lower-case unless explicitly told to
  38. // capitalize it.
  39. result.Append(char.ToLowerInvariant(c));
  40. } else {
  41. // Capital letters after the first are left as-is.
  42. result.Append(c);
  43. }
  44. capitaliseNext = false;
  45. } else if ('0' <= c && c <= '9') {
  46. result.Append(c);
  47. capitaliseNext = true;
  48. } else {
  49. capitaliseNext = true;
  50. }
  51. }
  52. return result.ToString();
  53. }
  54. internal static string StripProto(string text) {
  55. if (!StripSuffix(ref text, ".protodevel")) {
  56. StripSuffix(ref text, ".proto");
  57. }
  58. return text;
  59. }
  60. /// <summary>
  61. /// Attempts to strip a suffix from a string, returning whether
  62. /// or not the suffix was actually present.
  63. /// </summary>
  64. internal static bool StripSuffix(ref string text, string suffix) {
  65. if (text.EndsWith(suffix)) {
  66. text = text.Substring(0, text.Length - suffix.Length);
  67. return true;
  68. }
  69. return false;
  70. }
  71. }
  72. }