CanonSharp/CanonSharp.Benchmark/Canon.Core/StringSourceReader.cs
jackfiled 89ce313b77 feat: CanonSharp Benchmark. (#4)
Reviewed-on: https://git.bupt-hpc.cn/jackfiled/CanonSharp/pulls/4
Co-authored-by: jackfiled <xcrenchangjun@outlook.com>
Co-committed-by: jackfiled <xcrenchangjun@outlook.com>
2024-08-19 14:37:34 +08:00

83 lines
1.5 KiB
C#

using System.Diagnostics.CodeAnalysis;
using CanonSharp.Benchmark.Canon.Core.Abstractions;
namespace CanonSharp.Benchmark.Canon.Core;
public sealed class StringSourceReader(string source) : ISourceReader
{
private int _pos = -1;
private uint _lastPos;
public uint Line { get; private set; } = 1;
public uint Pos { get; private set; }
public string FileName => "string";
public char Current
{
get
{
if (_pos == -1)
{
throw new InvalidOperationException("Reader at before the start.");
}
return source[_pos];
}
}
public bool Retract()
{
if (_pos <= 0)
{
return false;
}
_pos -= 1;
if (Current == '\n')
{
Line -= 1;
Pos = _lastPos;
}
else
{
Pos -= 1;
}
return true;
}
public bool MoveNext()
{
if (_pos >= source.Length - 1)
{
return false;
}
if (_pos != -1 && Current == '\n')
{
Line += 1;
_lastPos = Pos;
Pos = 0;
}
_pos += 1;
Pos += 1;
return true;
}
public bool TryPeekChar([NotNullWhen(true)] out char? c)
{
if (_pos >= source.Length - 1)
{
c = null;
return false;
}
c = source[_pos + 1];
return true;
}
}