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