Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions Src/ConfigurationReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace SharpConfig
{
Expand All @@ -25,6 +26,7 @@ private static void Parse(StringReader reader, Configuration config)
{
var currentSection = new Section(Section.DefaultSectionName);
var preCommentBuilder = new StringBuilder();
HashSet<char> validCommentChars = new HashSet<char>(Configuration.ValidCommentChars); // Initialize once for each reader to optimize performance

int lineNumber = 0;

Expand All @@ -44,7 +46,7 @@ private static void Parse(StringReader reader, Configuration config)
continue;
}

var comment = ParseComment(line, out int commentIndex);
var comment = ParseComment(line, validCommentChars, out int commentIndex);

if (commentIndex == 0)
{
Expand Down Expand Up @@ -108,7 +110,7 @@ private static void Parse(StringReader reader, Configuration config)
}
}

private static string ParseComment(string line, out int commentCharIndex)
private static string ParseComment(string line, HashSet<char> validCommentChars, out int commentCharIndex)
{
// A comment starts with a valid comment character that:
// 1. is not within a quote (eg. "this is # not a comment"), and
Expand All @@ -122,11 +124,13 @@ private static string ParseComment(string line, out int commentCharIndex)

int index = 0;
int quoteCount = 0;
while (line.Length > index) // traverse line from left to right
int length = line.Length;
while (index < length) // traverse line from left to right
{
bool isValidCommentChar = Array.IndexOf(Configuration.ValidCommentChars, line[index]) > -1;
bool isQuotationMark = line[index] == '\"';
bool isCharWithinQuotes = quoteCount % 2 == 1;
char currentChar = line[index];
bool isValidCommentChar = validCommentChars.Contains(currentChar);
bool isQuotationMark = currentChar == '\"';
bool isCharWithinQuotes = (quoteCount & 1) == 1; // bitwise AND is slightly faster
bool isCharEscaped = index > 0 && line[index - 1] == '\\';

if (isValidCommentChar && !isCharWithinQuotes && !isCharEscaped)
Expand Down