aspclassic-core/AspClassic.Scripting/Utils/ConsoleInputStream.cs
Jelle Luteijn 484dbfc9d9 progress
2022-05-15 11:19:49 +02:00

107 lines
1.9 KiB
C#

using System;
using System.IO;
namespace AspClassic.Scripting.Utils;
public sealed class ConsoleInputStream : Stream
{
private const int MinimalBufferSize = 4096;
public static readonly ConsoleInputStream Instance = new ConsoleInputStream();
private readonly Stream _input;
private readonly object _lock = new object();
private readonly byte[] _buffer = new byte[4096];
private int _bufferPos;
private int _bufferSize;
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length
{
get
{
throw new NotSupportedException();
}
}
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
private ConsoleInputStream()
{
_input = Console.OpenStandardInput();
}
public override int Read(byte[] buffer, int offset, int count)
{
lock (_lock)
{
int num;
if (_bufferSize > 0)
{
num = Math.Min(count, _bufferSize);
Buffer.BlockCopy(_buffer, _bufferPos, buffer, offset, num);
_bufferPos += num;
_bufferSize -= num;
offset += num;
count -= num;
}
else
{
num = 0;
}
if (count > 0)
{
if (count < 4096)
{
int num2 = _input.Read(_buffer, 0, 4096);
int num3 = Math.Min(num2, count);
Buffer.BlockCopy(_buffer, 0, buffer, offset, num3);
_bufferSize = num2 - num3;
_bufferPos = num3;
return num + num3;
}
return num + _input.Read(buffer, offset, count);
}
return num;
}
}
public override void Flush()
{
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}