aboutsummaryrefslogtreecommitdiff
path: root/csharp/src/ProtocolBuffers/LimitedInputStream.cs
blob: cfbf47de3bb9ee7e24ed181db3c93b491d9b6b6e (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.IO;

namespace Google.Protobuf
{
    /// <summary>
    /// Stream implementation which proxies another stream, only allowing a certain amount
    /// of data to be read. Note that this is only used to read delimited streams, so it
    /// doesn't attempt to implement everything.
    /// </summary>
    internal sealed class LimitedInputStream : Stream
    {
        private readonly Stream proxied;
        private int bytesLeft;

        internal LimitedInputStream(Stream proxied, int size)
        {
            this.proxied = proxied;
            bytesLeft = size;
        }

        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return false; }
        }

        public override void Flush()
        {
        }

        public override long Length
        {
            get { throw new NotSupportedException(); }
        }

        public override long Position
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            if (bytesLeft > 0)
            {
                int bytesRead = proxied.Read(buffer, offset, Math.Min(bytesLeft, count));
                bytesLeft -= bytesRead;
                return bytesRead;
            }
            return 0;
        }

        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();
        }
    }
}