Helpers.cs 2.8 KB

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