Skip to content

Commit

Permalink
Commit of a new class that got left behind...
Browse files Browse the repository at this point in the history
  • Loading branch information
cridus committed Jul 12, 2022
1 parent 072cdf8 commit a5ddd2d
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions SteamP2PInfo/ReverseTextReader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace SteamP2PInfo
{
public class ReverseTextReader
{
private const int LineFeedLf = 10;
private const int LineFeedCr = 13;
private readonly Stream _stream;
private readonly Encoding _encoding;

public bool EndOfStream => _stream.Position == 0;

public ReverseTextReader(Stream stream, Encoding encoding)
{
_stream = stream;
_encoding = encoding;
_stream.Position = _stream.Length;
}

public string ReadLine()
{
if (_stream.Position == 0) return null;

var line = new List<byte>();
var endOfLine = false;
while (!endOfLine)
{
var b = _stream.ReadByteFromBehind();

if (b == -1 || b == LineFeedLf)
{
endOfLine = true;
}
line.Add(Convert.ToByte(b));
}

line.Reverse();
return _encoding.GetString(line.ToArray());
}
}

public static class StreamExtensions
{
public static int ReadByteFromBehind(this Stream stream)
{
if (stream.Position == 0) return -1;

stream.Position = stream.Position - 1;
var value = stream.ReadByte();
stream.Position = stream.Position - 1;
return value;
}
}
}

0 comments on commit a5ddd2d

Please sign in to comment.