diff --git a/Src/Configuration.cs b/Src/Configuration.cs index 4c0960f..27caf4f 100644 --- a/Src/Configuration.cs +++ b/Src/Configuration.cs @@ -35,7 +35,7 @@ static Configuration() // but without modifying the real invariant culture instance. s_cultureInfo = (CultureInfo)CultureInfo.InvariantCulture.Clone(); - ValidCommentChars = new[] { '#', ';' }; + ValidCommentChars = new HashSet { '#', ';' }; s_preferredCommentChar = '#'; s_arrayElementSeparator = ','; @@ -585,7 +585,7 @@ public static CultureInfo CultureInfo /// Gets the array that contains all valid comment delimiting characters. /// The current value is { '#', ';' }. /// - public static char[] ValidCommentChars { get; private set; } + public static HashSet ValidCommentChars { get; private set; } /// /// Gets or sets the preferred comment char when saving configurations. @@ -597,7 +597,7 @@ public static char PreferredCommentChar { get => s_preferredCommentChar; set { - if (!Array.Exists(ValidCommentChars, c => c == value)) + if (!ValidCommentChars.Contains(value)) { throw new ArgumentException("The specified char '" + value + "' is not allowed as a comment char."); } diff --git a/Src/ConfigurationReader.cs b/Src/ConfigurationReader.cs index 0d34c7b..d6c430b 100644 --- a/Src/ConfigurationReader.cs +++ b/Src/ConfigurationReader.cs @@ -124,11 +124,13 @@ private static string ParseComment(string line, out int commentCharIndex) var index = 0; var quoteCount = 0; - while (line.Length > index) // traverse line from left to right + var length = line.Length; + while (index < length) // traverse line from left to right { - var isValidCommentChar = Array.IndexOf(Configuration.ValidCommentChars, line[index]) > -1; - var isQuotationMark = line[index] == '\"'; - var isCharWithinQuotes = quoteCount % 2 == 1; + var currentChar = line[index]; + var isValidCommentChar = Configuration.ValidCommentChars.Contains(currentChar); + var isQuotationMark = currentChar == '\"'; + var isCharWithinQuotes = (quoteCount & 1) == 1; // bitwise AND is slightly faster var isCharEscaped = index > 0 && line[index - 1] == '\\'; if (isValidCommentChar && !isCharWithinQuotes && !isCharEscaped) diff --git a/Src/Setting.cs b/Src/Setting.cs index fdfa459..307b857 100644 --- a/Src/Setting.cs +++ b/Src/Setting.cs @@ -2,6 +2,7 @@ // https://sharpconfig.org using System; +using System.Linq; using System.Text; namespace SharpConfig @@ -612,8 +613,10 @@ private static string GetValueForOutput(string rawValue) return rawValue; } + bool isAnyCommentCharInRawValue() => rawValue.Any(c => Configuration.ValidCommentChars.Contains(c)); + if (rawValue.IndexOf(" ", StringComparison.Ordinal) >= 0 || - (rawValue.IndexOfAny(Configuration.ValidCommentChars) >= 0 && !Configuration.IgnoreInlineComments)) + (isAnyCommentCharInRawValue() && !Configuration.IgnoreInlineComments)) { rawValue = "\"" + rawValue + "\""; }