diff options
author | Peter Dettman <peter.dettman@bouncycastle.org> | 2022-09-03 00:36:40 +0700 |
---|---|---|
committer | Peter Dettman <peter.dettman@bouncycastle.org> | 2022-09-03 00:36:40 +0700 |
commit | aa5f3f0929c50fc942325f18ed7ae48129d4c992 (patch) | |
tree | 0382f7336cb55c4a01bd38782d7694d1cb094921 /crypto/src/util/io/LimitedInputStream.cs | |
parent | Clean up tests (diff) | |
download | BouncyCastle.NET-ed25519-aa5f3f0929c50fc942325f18ed7ae48129d4c992.tar.xz |
Stream modernization
Diffstat (limited to 'crypto/src/util/io/LimitedInputStream.cs')
-rw-r--r-- | crypto/src/util/io/LimitedInputStream.cs | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/crypto/src/util/io/LimitedInputStream.cs b/crypto/src/util/io/LimitedInputStream.cs new file mode 100644 index 000000000..d6616eff5 --- /dev/null +++ b/crypto/src/util/io/LimitedInputStream.cs @@ -0,0 +1,56 @@ +using Org.BouncyCastle.Utilities.Zlib; +using System; +using System.IO; + +namespace Org.BouncyCastle.Utilities.IO +{ + internal class LimitedInputStream + : BaseInputStream + { + private readonly Stream m_stream; + private long m_limit; + + internal LimitedInputStream(Stream stream, long limit) + { + this.m_stream = stream; + this.m_limit = limit; + } + + internal long CurrentLimit => m_limit; + + public override int Read(byte[] buffer, int offset, int count) + { + int numRead = m_stream.Read(buffer, offset, count); + if (numRead > 0) + { + if ((m_limit -= numRead) < 0) + throw new StreamOverflowException("Data Overflow"); + } + return numRead; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + public override int Read(Span<byte> buffer) + { + int numRead = m_stream.Read(buffer); + if (numRead > 0) + { + if ((m_limit -= numRead) < 0) + throw new StreamOverflowException("Data Overflow"); + } + return numRead; + } +#endif + + public override int ReadByte() + { + int b = m_stream.ReadByte(); + if (b >= 0) + { + if (--m_limit < 0) + throw new StreamOverflowException("Data Overflow"); + } + return b; + } + } +} |