Skip to content

Commit

Permalink
Improve speed of lexer by implementing binary search for getting line…
Browse files Browse the repository at this point in the history
… numbers
  • Loading branch information
marcin-golebiowski committed Dec 3, 2019
1 parent 0ecee1e commit a959f29
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions src/SpiceSharpParser/Lexers/LexerLineNumberProvider.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;

namespace SpiceSharpParser.Lexers
Expand All @@ -17,15 +18,33 @@ public LexerLineNumberProvider(string text)

public int GetLineForIndex(int index)
{
foreach (var t in _ranges)
// binary search over line ranges
int start = 0;
int end = _ranges.Count - 1;

while (start <= end)
{
if (t.From <= index && index <= t.To)
int middle = (end + start) / 2;

if (_ranges[middle].From <= index && index <= _ranges[middle].To)
{
return _ranges[middle].LineNumber;
}
else if (_ranges[middle].From > index)
{
end = middle - 1;
}
else if (_ranges[middle].To < index)
{
start = middle + 1;
}
else
{
return t.LineNumber;
return -1;
}
}

return _ranges.Last().LineNumber;
return -1;
}

private void Init()
Expand Down

0 comments on commit a959f29

Please sign in to comment.