Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix potential out of range issue if IsBetween was provided an imprope… #349

Merged
merged 1 commit into from
Dec 9, 2021
Merged
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
14 changes: 9 additions & 5 deletions DevSkim-DotNet/Microsoft.DevSkim/TextContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ private int BoundaryByLine(int line, int offset)
}

/// <summary>
/// Checks if the index in the string lies between preffix and suffix
/// Checks if the index in the string lies between prefix and suffix
/// </summary>
/// <param name="text"> Text </param>
/// <param name="index"> Index to check </param>
Expand All @@ -229,13 +229,17 @@ private int BoundaryByLine(int line, int offset)
/// <returns> True if the index is between prefix and suffix </returns>
private static bool IsBetween(string text, int index, string prefix, string suffix, string inline = "")
{
string preText = string.Concat(text.Substring(0, index));
if (index < 0 || index >= text.Length)
{
return false;
}
string preText = string.Concat(text[..index]);
int lastPrefix = preText.LastIndexOf(prefix, StringComparison.InvariantCulture);
if (lastPrefix >= 0)
{
int lastInline = preText.Substring(0, lastPrefix).LastIndexOf(inline, StringComparison.InvariantCulture);
int lastInline = preText[..lastPrefix].LastIndexOf(inline, StringComparison.InvariantCulture);
// For example in C#, If this /* is actually commented out by a //
if (!(lastInline >= 0 && lastInline < lastPrefix && !preText.Substring(lastInline, lastPrefix - lastInline).Contains(Environment.NewLine)))
if (!(lastInline >= 0 && lastInline < lastPrefix && !preText[lastInline..lastPrefix].Contains(Environment.NewLine)))
{
var commentedText = text.Substring(lastPrefix);
int nextSuffix = commentedText.IndexOf(suffix, StringComparison.Ordinal);
Expand All @@ -251,7 +255,7 @@ private static bool IsBetween(string text, int index, string prefix, string suff
int lastInline = preText.LastIndexOf(inline, StringComparison.InvariantCulture);
if (lastInline >= 0)
{
var commentedText = text.Substring(lastInline);
var commentedText = text[lastInline..];
int endOfLine = commentedText.IndexOf("\n", StringComparison.Ordinal);
if (endOfLine < 0)
{
Expand Down