summary refs log tree commit diff
path: root/crypto/src/util/io/LimitedInputStream.cs
blob: 2f19ef996f8d091c6bbb2c9de2f5191fa97e81bd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.IO;

namespace Org.BouncyCastle.Utilities.IO
{
    internal sealed 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;
        }
    }
}